⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 platformimplbase.java

📁 OBPM是一个开源
💻 JAVA
📖 第 1 页 / 共 5 页
字号:
package org.apache.ddlutils.platform;

/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.Statement;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.DynaBean;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Predicate;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ddlutils.DatabaseOperationException;
import org.apache.ddlutils.DdlUtilsException;
import org.apache.ddlutils.Platform;
import org.apache.ddlutils.PlatformInfo;
import org.apache.ddlutils.dynabean.SqlDynaClass;
import org.apache.ddlutils.dynabean.SqlDynaProperty;
import org.apache.ddlutils.model.Column;
import org.apache.ddlutils.model.Database;
import org.apache.ddlutils.model.Table;
import org.apache.ddlutils.model.TypeMap;
import org.apache.ddlutils.util.Jdbc3Utils;
import org.apache.ddlutils.util.JdbcSupport;
import org.apache.ddlutils.util.SqlTokenizer;

/**
 * Base class for platform implementations.
 * 
 * @version $Revision: 231110 $
 */
public abstract class PlatformImplBase extends JdbcSupport implements Platform {
	/** The default name for models read from the database, if no name as given. */
	protected static final String MODEL_DEFAULT_NAME = "default";

	/** The log for this platform. */
	private final Log _log = LogFactory.getLog(getClass());

	/** The platform info. */
	private PlatformInfo _info = new PlatformInfo();

	/** The sql builder for this platform. */
	private SqlBuilder _builder;

	/** The model reader for this platform. */
	private JdbcModelReader _modelReader;

	/** Whether script mode is on. */
	private boolean _scriptModeOn;

	/** Whether SQL comments are generated or not. */
	private boolean _sqlCommentsOn = true;

	/** Whether delimited identifiers are used or not. */
	private boolean _delimitedIdentifierModeOn;

	/** Whether identity override is enabled. */
	private boolean _identityOverrideOn;

	/** Whether read foreign keys shall be sorted alphabetically. */
	private boolean _foreignKeysSorted;

	/**
	 * {@inheritDoc}
	 */
	public SqlBuilder getSqlBuilder() {
		return _builder;
	}

	/**
	 * Sets the sql builder for this platform.
	 * 
	 * @param builder
	 *            The sql builder
	 */
	protected void setSqlBuilder(SqlBuilder builder) {
		_builder = builder;
	}

	/**
	 * {@inheritDoc}
	 */
	public JdbcModelReader getModelReader() {
		if (_modelReader == null) {
			_modelReader = new JdbcModelReader(this);
		}
		return _modelReader;
	}

	/**
	 * Sets the model reader for this platform.
	 * 
	 * @param modelReader
	 *            The model reader
	 */
	protected void setModelReader(JdbcModelReader modelReader) {
		_modelReader = modelReader;
	}

	/**
	 * {@inheritDoc}
	 */
	public PlatformInfo getPlatformInfo() {
		return _info;
	}

	/**
	 * {@inheritDoc}
	 */
	public boolean isScriptModeOn() {
		return _scriptModeOn;
	}

	/**
	 * {@inheritDoc}
	 */
	public void setScriptModeOn(boolean scriptModeOn) {
		_scriptModeOn = scriptModeOn;
	}

	/**
	 * {@inheritDoc}
	 */
	public boolean isSqlCommentsOn() {
		return _sqlCommentsOn;
	}

	/**
	 * {@inheritDoc}
	 */
	public void setSqlCommentsOn(boolean sqlCommentsOn) {
		if (!getPlatformInfo().isSqlCommentsSupported() && sqlCommentsOn) {
			throw new DdlUtilsException("Platform " + getName()
					+ " does not support SQL comments");
		}
		_sqlCommentsOn = sqlCommentsOn;
	}

	/**
	 * {@inheritDoc}
	 */
	public boolean isDelimitedIdentifierModeOn() {
		return _delimitedIdentifierModeOn;
	}

	/**
	 * {@inheritDoc}
	 */
	public void setDelimitedIdentifierModeOn(boolean delimitedIdentifierModeOn) {
		if (!getPlatformInfo().isDelimitedIdentifiersSupported()
				&& delimitedIdentifierModeOn) {
			throw new DdlUtilsException("Platform " + getName()
					+ " does not support delimited identifier");
		}
		_delimitedIdentifierModeOn = delimitedIdentifierModeOn;
	}

	/**
	 * {@inheritDoc}
	 */
	public boolean isIdentityOverrideOn() {
		return _identityOverrideOn;
	}

	/**
	 * {@inheritDoc}
	 */
	public void setIdentityOverrideOn(boolean identityOverrideOn) {
		_identityOverrideOn = identityOverrideOn;
	}

	/**
	 * {@inheritDoc}
	 */
	public boolean isForeignKeysSorted() {
		return _foreignKeysSorted;
	}

	/**
	 * {@inheritDoc}
	 */
	public void setForeignKeysSorted(boolean foreignKeysSorted) {
		_foreignKeysSorted = foreignKeysSorted;
	}

	/**
	 * Returns the log for this platform.
	 * 
	 * @return The log
	 */
	protected Log getLog() {
		return _log;
	}

	/**
	 * Logs any warnings associated to the given connection. Note that the
	 * connection needs to be open for this.
	 * 
	 * @param connection
	 *            The open connection
	 */
	protected void logWarnings(Connection connection) throws SQLException {
		SQLWarning warning = connection.getWarnings();

		while (warning != null) {
			getLog().warn(warning.getLocalizedMessage(), warning.getCause());
			warning = warning.getNextWarning();
		}
	}

	/**
	 * {@inheritDoc}
	 */
	public int evaluateBatch(String sql, boolean continueOnError)
			throws DatabaseOperationException {
		Connection connection = borrowConnection();

		try {
			return evaluateBatch(connection, sql, continueOnError);
		} finally {
			returnConnection(connection);
		}
	}

	/**
	 * {@inheritDoc}
	 */
	public int evaluateBatch(Connection connection, String sql,
			boolean continueOnError) throws DatabaseOperationException {
		Statement statement = null;
		int errors = 0;
		int commandCount = 0;

		// we tokenize the SQL along the delimiters, and we also make sure that
		// only delimiters
		// at the end of a line or the end of the string are used (row mode)
		try {
			statement = connection.createStatement();

			SqlTokenizer tokenizer = new SqlTokenizer(sql);

			while (tokenizer.hasMoreStatements()) {
				String command = tokenizer.getNextStatement();

				// ignore whitespace
				command = command.trim();
				if (command.length() == 0) {
					continue;
				}

				commandCount++;

				if (_log.isDebugEnabled()) {
					_log.debug("About to execute SQL " + command);
				}
				try {
					int results = statement.executeUpdate(command);

					if (_log.isDebugEnabled()) {
						_log.debug("After execution, " + results
								+ " row(s) have been changed");
					}
				} catch (SQLException ex) {
					if (continueOnError) {
						// Since the user deciced to ignore this error, we log
						// the error
						// on level warn, and the exception itself on level
						// debug
						_log.warn("SQL Command " + command + " failed with: "
								+ ex.getMessage());
						if (_log.isDebugEnabled()) {
							_log.debug(ex);
						}
						errors++;
					} else {
						throw new DatabaseOperationException(
								"Error while executing SQL " + command, ex);
					}
				}

				// lets display any warnings
				SQLWarning warning = connection.getWarnings();

				while (warning != null) {
					_log.warn(warning.toString());
					warning = warning.getNextWarning();
				}
				connection.clearWarnings();
			}
			_log.info("Executed " + commandCount + " SQL command(s) with "
					+ errors + " error(s)");
		} catch (SQLException ex) {
			throw new DatabaseOperationException("Error while executing SQL",
					ex);
		} finally {
			closeStatement(statement);
		}

		return errors;
	}

	/**
	 * {@inheritDoc}
	 */
	public void shutdownDatabase() throws DatabaseOperationException {
		Connection connection = borrowConnection();

		try {
			shutdownDatabase(connection);
		} finally {
			returnConnection(connection);
		}
	}

	/**
	 * {@inheritDoc}
	 */
	public void shutdownDatabase(Connection connection)
			throws DatabaseOperationException {
		// Per default do nothing as most databases don't need this
	}

	/**
	 * {@inheritDoc}
	 */
	public void createDatabase(String jdbcDriverClassName,
			String connectionUrl, String username, String password,
			Map parameters) throws DatabaseOperationException,
			UnsupportedOperationException {
		throw new UnsupportedOperationException(
				"Database creation is not supported for the database platform "
						+ getName());
	}

	/**
	 * {@inheritDoc}
	 */
	public void dropDatabase(String jdbcDriverClassName, String connectionUrl,
			String username, String password)
			throws DatabaseOperationException, UnsupportedOperationException {
		throw new UnsupportedOperationException(
				"Database deletion is not supported for the database platform "
						+ getName());
	}

	/**
	 * {@inheritDoc}
	 */
	public void createTables(Database model, boolean dropTablesFirst,
			boolean continueOnError) throws DatabaseOperationException {
		Connection connection = borrowConnection();

		try {
			createTables(connection, model, dropTablesFirst, continueOnError);
		} finally {
			returnConnection(connection);
		}
	}

	/**
	 * {@inheritDoc}
	 */
	public void createTables(Connection connection, Database model,
			boolean dropTablesFirst, boolean continueOnError)
			throws DatabaseOperationException {
		String sql = getCreateTablesSql(model, dropTablesFirst, continueOnError);

		evaluateBatch(connection, sql, continueOnError);
	}

	/**
	 * {@inheritDoc}
	 */
	public String getCreateTablesSql(Database model, boolean dropTablesFirst,
			boolean continueOnError) {
		String sql = null;

		try {
			StringWriter buffer = new StringWriter();

			getSqlBuilder().setWriter(buffer);
			getSqlBuilder().createTables(model, dropTablesFirst);
			sql = buffer.toString();
		} catch (IOException e) {
			// won't happen because we're using a string writer
		}
		return sql;
	}

	/**
	 * {@inheritDoc}
	 */
	public void createTables(Database model, CreationParameters params,
			boolean dropTablesFirst, boolean continueOnError)
			throws DatabaseOperationException {
		Connection connection = borrowConnection();

		try {
			createTables(connection, model, params, dropTablesFirst,
					continueOnError);
		} finally {
			returnConnection(connection);

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -