From ff289445e91966b3c337f0cdd94cb2d4a627e6fb Mon Sep 17 00:00:00 2001
From: chenson42
null
if the database is not
+ * supported
+ */
+ public static synchronized IDatabasePlatform createNewPlatformInstance(String databaseName)
+ throws DdlUtilsException {
+ Class extends IDatabasePlatform> platformClass = getPlatforms().get(
+ databaseName.toLowerCase());
+
+ try {
+ return platformClass != null ? (IDatabasePlatform) platformClass.newInstance() : null;
+ } catch (Exception ex) {
+ throw new DdlUtilsException("Could not create platform for database " + databaseName,
+ ex);
+ }
+ }
+
+ /*
+ * Creates a new platform for the specified database. This is a shortcut
+ * method that uses {@link PlatformUtils#determineDatabaseType(DataSource)}
+ * to determine the parameter for {@link
+ * #createNewPlatformInstance(String)}. Note that this method sets the data
+ * source at the returned platform instance (method {@link
+ * Platform#setDataSource(DataSource)}).
+ *
+ * @param dataSource The data source for the database
+ *
+ * @return The platform or null
if the database is not
+ * supported
+ */
+ public static synchronized IDatabasePlatform createNewPlatformInstance(DataSource dataSource)
+ throws DdlUtilsException {
+ // connects to the database and uses actual metadata info to get db name
+ // and version to determine platform
+ String nameVersion = determineDatabaseNameVersion(dataSource);
+ return createNewPlatformInstance(nameVersion);
+ }
+
+ public static String determineDatabaseNameVersion(DataSource dataSource)
+ throws DatabaseOperationException {
+ Connection connection = null;
+
+ try {
+ connection = dataSource.getConnection();
+ DatabaseMetaData metaData = connection.getMetaData();
+ String productName = metaData.getDatabaseProductName();
+ int majorVersion = metaData.getDatabaseMajorVersion();
+ /*
+ * if the productName is PostgreSQL, it could be either PostgreSQL
+ * or Greenplum
+ */
+ /* query the metadata to determine which one it is */
+ if (productName.equalsIgnoreCase(PostgreSqlPlatform.DATABASENAME)) {
+ if (isGreenplumDatabase(connection)) {
+ productName = GreenplumPlatform.DATABASE;
+ majorVersion = getGreenplumVersion(connection);
+ }
+ }
+ String productString = productName;
+ if (majorVersion > 0) {
+ productString += majorVersion;
+ }
+
+ return productString;
+ } catch (SQLException ex) {
+ throw new DatabaseOperationException("Error while reading the database metadata: "
+ + ex.getMessage(), ex);
+ } finally {
+ if (connection != null) {
+ try {
+ connection.close();
+ } catch (SQLException ex) {
+ // we ignore this one
+ }
+ }
+ }
+ }
+
+ private static boolean isGreenplumDatabase(Connection connection) {
+ Statement stmt = null;
+ ResultSet rs = null;
+ String productName = null;
+ boolean isGreenplum = false;
+ try {
+ stmt = connection.createStatement();
+ rs = stmt.executeQuery(GreenplumPlatform.SQL_GET_GREENPLUM_NAME);
+ while (rs.next()) {
+ productName = rs.getString(1);
+ }
+ if (productName != null && productName.equalsIgnoreCase(GreenplumPlatform.DATABASE)) {
+ isGreenplum = true;
+ }
+ } catch (SQLException ex) {
+ // ignore the exception, if it is caught, then this is most likely
+ // not
+ // a greenplum database
+ } finally {
+ try {
+ if (rs != null) {
+ rs.close();
+ }
+ if (stmt != null) {
+ stmt.close();
+ }
+ } catch (SQLException ex) {
+ }
+ }
+ return isGreenplum;
+ }
+
+ private static int getGreenplumVersion(Connection connection) {
+ Statement stmt = null;
+ ResultSet rs = null;
+ String versionName = null;
+ int productVersion = 0;
+ try {
+ stmt = connection.createStatement();
+ rs = stmt.executeQuery(GreenplumPlatform.SQL_GET_GREENPLUM_VERSION);
+ while (rs.next()) {
+ versionName = rs.getString(1);
+ }
+ // take up to the first "." for version number
+ if (versionName.indexOf('.') != -1) {
+ versionName = versionName.substring(0, versionName.indexOf('.'));
+ }
+ try {
+ productVersion = Integer.parseInt(versionName);
+ } catch (NumberFormatException ex) {
+ // if we can't convert this to a version number, leave it 0
+ }
+ } catch (SQLException ex) {
+ // ignore the exception, if it is caught, then this is most likely
+ // not
+ // a greenplum database
+ } finally {
+ try {
+ rs.close();
+ stmt.close();
+ } catch (SQLException ex) {
+ }
+ }
+ return productVersion;
+ }
+
+ /*
+ * Registers a new platform.
+ *
+ * @param platformName The platform name
+ *
+ * @param platformClass The platform class which must implement the {@link
+ * Platform} interface
+ */
+ public static synchronized void registerPlatform(String platformName,
+ Class extends IDatabasePlatform> platformClass) {
+ addPlatform(getPlatforms(), platformName, platformClass);
+ }
+
+ /*
+ * Registers the known platforms.
+ */
+ private static void registerPlatforms() {
+ for (String name : H2Platform.DATABASENAMES) {
+ addPlatform(platforms, name, H2Platform.class);
+ }
+ addPlatform(platforms, SqLitePlatform.DATABASENAME, SqLitePlatform.class);
+ addPlatform(platforms, InformixPlatform.DATABASENAME, InformixPlatform.class);
+ addPlatform(platforms, DerbyPlatform.DATABASENAME, DerbyPlatform.class);
+ addPlatform(platforms, FirebirdPlatform.DATABASENAME, FirebirdPlatform.class);
+ addPlatform(platforms, GreenplumPlatform.DATABASENAME, GreenplumPlatform.class);
+ addPlatform(platforms, HsqlDbPlatform.DATABASENAME, HsqlDbPlatform.class);
+ addPlatform(platforms, HsqlDb2Platform.DATABASENAME, HsqlDb2Platform.class);
+ addPlatform(platforms, InterbasePlatform.DATABASENAME, InterbasePlatform.class);
+ addPlatform(platforms, MSSqlPlatform.DATABASENAME, MSSqlPlatform.class);
+ addPlatform(platforms, MySqlPlatform.DATABASENAME, MySqlPlatform.class);
+ addPlatform(platforms, OraclePlatform.DATABASENAME, OraclePlatform.class);
+ addPlatform(platforms, PostgreSqlPlatform.DATABASENAME, PostgreSqlPlatform.class);
+ addPlatform(platforms, SybasePlatform.DATABASENAME, SybasePlatform.class);
+ }
+
+ private static synchronized void addPlatform(
+ Maptrue
if script mode is on
+ */
+ public boolean isScriptModeOn();
+
+ /*
+ * Specifies whether script mode is on. This means that the generated SQL is
+ * not intended to be sent directly to the database but rather to be saved
+ * in a SQL script file.
+ *
+ * @param scriptModeOn true
if script mode is on
+ */
+ public void setScriptModeOn(boolean scriptModeOn);
+
+ /*
+ * Determines whether delimited identifiers are used or normal SQL92
+ * identifiers (which may only contain alphanumerical characters and the
+ * underscore, must start with a letter and cannot be a reserved keyword).
+ * Per default, delimited identifiers are not used
+ *
+ * @return true
if delimited identifiers are used
+ */
+ public boolean isDelimitedIdentifierModeOn();
+
+ /*
+ * Specifies whether delimited identifiers are used or normal SQL92
+ * identifiers.
+ *
+ * @param delimitedIdentifierModeOn true
if delimited
+ * identifiers shall be used
+ */
+ public void setDelimitedIdentifierModeOn(boolean delimitedIdentifierModeOn);
+
+ /*
+ * Determines whether SQL comments are generated.
+ *
+ * @return true
if SQL comments shall be generated
+ */
+ public boolean isSqlCommentsOn();
+
+ /*
+ * Specifies whether SQL comments shall be generated.
+ *
+ * @param sqlCommentsOn true
if SQL comments shall be generated
+ */
+ public void setSqlCommentsOn(boolean sqlCommentsOn);
+
+ /*
+ * Determines whether SQL insert statements can specify values for identity
+ * columns. This setting is only relevant if the database supports it
+ * ({@link PlatformInfo#isIdentityOverrideAllowed()}). If this is off, then
+ * the insert
methods will ignore values for identity columns.
+ *
+ * @return true
if identity override is enabled (the default)
+ */
+ public boolean isIdentityOverrideOn();
+
+ /*
+ * Specifies whether SQL insert statements can specify values for identity
+ * columns. This setting is only relevant if the database supports it
+ * ({@link PlatformInfo#isIdentityOverrideAllowed()}). If this is off, then
+ * the insert
methods will ignore values for identity columns.
+ *
+ * @param identityOverrideOn true
if identity override is
+ * enabled (the default)
+ */
+ public void setIdentityOverrideOn(boolean identityOverrideOn);
+
+ /*
+ * Determines whether foreign keys of a table read from a live database are
+ * alphabetically sorted.
+ *
+ * @return true
if read foreign keys are sorted
+ */
+ public boolean isForeignKeysSorted();
+
+ /*
+ * Specifies whether foreign keys read from a live database, shall be
+ * alphabetically sorted.
+ *
+ * @param foreignKeysSorted true
if read foreign keys shall be
+ * sorted
+ */
+ public void setForeignKeysSorted(boolean foreignKeysSorted);
+
+ /*
+ * Reads the database model from the live database to which the given
+ * connection is pointing.
+ *
+ * @param connection The connection to the database
+ *
+ * @param name The name of the resulting database; null
when
+ * the default name (the catalog) is desired which might be
+ * null
itself though
+ *
+ * @param catalog The catalog to access in the database; use
+ * null
for the default value
+ *
+ * @param schema The schema to access in the database; use null
+ * for the default value
+ *
+ * @param tableTypes The table types to process; use null
or an
+ * empty list for the default ones
+ *
+ * @return The database model
+ *
+ * @throws DatabaseOperationException If an error occurred during reading
+ * the model
+ */
+ public Database readDatabase(Connection connection, String name, String catalog,
+ String schema, String[] tableTypes) throws DatabaseOperationException;
+
+ public Table readTableFromDatabase(Connection connection, String catalogName,
+ String schemaName, String tablename) throws SQLException;
+
+ public void createDatabase(DataSource dataSource, Database targetDatabase,
+ boolean dropTablesFirst, boolean continueOnError);
+
+}
diff --git a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/alteration/AddColumnChange.java b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/alter/AddColumnChange.java
similarity index 90%
rename from symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/alteration/AddColumnChange.java
rename to symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/alter/AddColumnChange.java
index 6881378790..116a113fc0 100644
--- a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/alteration/AddColumnChange.java
+++ b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/alter/AddColumnChange.java
@@ -1,4 +1,4 @@
-package org.jumpmind.symmetric.db.ddl.alteration;
+package org.jumpmind.symmetric.db.alter;
/*
* Licensed to the Apache Software Foundation (ASF) under one
@@ -19,10 +19,10 @@
* under the License.
*/
-import org.jumpmind.symmetric.db.ddl.DdlUtilsException;
-import org.jumpmind.symmetric.db.ddl.model.Column;
-import org.jumpmind.symmetric.db.ddl.model.Database;
-import org.jumpmind.symmetric.db.ddl.model.Table;
+import org.jumpmind.symmetric.db.DdlUtilsException;
+import org.jumpmind.symmetric.db.model.Column;
+import org.jumpmind.symmetric.db.model.Database;
+import org.jumpmind.symmetric.db.model.Table;
/**
* Represents the addition of a column to a table.
diff --git a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/alteration/AddForeignKeyChange.java b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/alter/AddForeignKeyChange.java
similarity index 86%
rename from symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/alteration/AddForeignKeyChange.java
rename to symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/alter/AddForeignKeyChange.java
index eddbb8a7f2..8c21cfca8c 100644
--- a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/alteration/AddForeignKeyChange.java
+++ b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/alter/AddForeignKeyChange.java
@@ -1,4 +1,4 @@
-package org.jumpmind.symmetric.db.ddl.alteration;
+package org.jumpmind.symmetric.db.alter;
/*
* Licensed to the Apache Software Foundation (ASF) under one
@@ -19,10 +19,10 @@
* under the License.
*/
-import org.jumpmind.symmetric.db.ddl.DdlUtilsException;
-import org.jumpmind.symmetric.db.ddl.model.Database;
-import org.jumpmind.symmetric.db.ddl.model.ForeignKey;
-import org.jumpmind.symmetric.db.ddl.model.Table;
+import org.jumpmind.symmetric.db.DdlUtilsException;
+import org.jumpmind.symmetric.db.model.Database;
+import org.jumpmind.symmetric.db.model.ForeignKey;
+import org.jumpmind.symmetric.db.model.Table;
/**
* Represents the addition of a foreign key to a table. Note that for
diff --git a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/alteration/AddIndexChange.java b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/alter/AddIndexChange.java
similarity index 84%
rename from symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/alteration/AddIndexChange.java
rename to symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/alter/AddIndexChange.java
index 0ea1c881e8..83caafc96e 100644
--- a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/alteration/AddIndexChange.java
+++ b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/alter/AddIndexChange.java
@@ -1,4 +1,4 @@
-package org.jumpmind.symmetric.db.ddl.alteration;
+package org.jumpmind.symmetric.db.alter;
/*
* Licensed to the Apache Software Foundation (ASF) under one
@@ -19,10 +19,10 @@
* under the License.
*/
-import org.jumpmind.symmetric.db.ddl.DdlUtilsException;
-import org.jumpmind.symmetric.db.ddl.model.Database;
-import org.jumpmind.symmetric.db.ddl.model.Index;
-import org.jumpmind.symmetric.db.ddl.model.Table;
+import org.jumpmind.symmetric.db.DdlUtilsException;
+import org.jumpmind.symmetric.db.model.Database;
+import org.jumpmind.symmetric.db.model.Index;
+import org.jumpmind.symmetric.db.model.Table;
/**
* Represents the addition of an index to a table.
diff --git a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/alteration/AddPrimaryKeyChange.java b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/alter/AddPrimaryKeyChange.java
similarity index 88%
rename from symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/alteration/AddPrimaryKeyChange.java
rename to symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/alter/AddPrimaryKeyChange.java
index f87a0aca35..6520e30eeb 100644
--- a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/alteration/AddPrimaryKeyChange.java
+++ b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/alter/AddPrimaryKeyChange.java
@@ -1,4 +1,4 @@
-package org.jumpmind.symmetric.db.ddl.alteration;
+package org.jumpmind.symmetric.db.alter;
/*
* Licensed to the Apache Software Foundation (ASF) under one
@@ -19,9 +19,9 @@
* under the License.
*/
-import org.jumpmind.symmetric.db.ddl.model.Column;
-import org.jumpmind.symmetric.db.ddl.model.Database;
-import org.jumpmind.symmetric.db.ddl.model.Table;
+import org.jumpmind.symmetric.db.model.Column;
+import org.jumpmind.symmetric.db.model.Database;
+import org.jumpmind.symmetric.db.model.Table;
/**
* Represents the addition of a primary key to a table which does not have one.
diff --git a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/alteration/AddTableChange.java b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/alter/AddTableChange.java
similarity index 83%
rename from symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/alteration/AddTableChange.java
rename to symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/alter/AddTableChange.java
index a7db92aca6..b340f2d46b 100644
--- a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/alteration/AddTableChange.java
+++ b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/alter/AddTableChange.java
@@ -1,4 +1,4 @@
-package org.jumpmind.symmetric.db.ddl.alteration;
+package org.jumpmind.symmetric.db.alter;
/*
* Licensed to the Apache Software Foundation (ASF) under one
@@ -19,17 +19,15 @@
* under the License.
*/
-import org.jumpmind.symmetric.db.ddl.DdlUtilsException;
-import org.jumpmind.symmetric.db.ddl.model.Database;
-import org.jumpmind.symmetric.db.ddl.model.Table;
+import org.jumpmind.symmetric.db.DdlUtilsException;
+import org.jumpmind.symmetric.db.model.Database;
+import org.jumpmind.symmetric.db.model.Table;
/**
* Represents the addition of a table to a model. Note that this change does not include foreign keys
* originating from the new table.
- *
- * @version $Revision: $
*/
-public class AddTableChange implements ModelChange
+public class AddTableChange implements IModelChange
{
/** The new table. */
private Table _newTable;
diff --git a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/alteration/ColumnAutoIncrementChange.java b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/alter/ColumnAutoIncrementChange.java
similarity index 87%
rename from symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/alteration/ColumnAutoIncrementChange.java
rename to symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/alter/ColumnAutoIncrementChange.java
index bf7af822a6..b42b30eb47 100644
--- a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/alteration/ColumnAutoIncrementChange.java
+++ b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/alter/ColumnAutoIncrementChange.java
@@ -1,4 +1,4 @@
-package org.jumpmind.symmetric.db.ddl.alteration;
+package org.jumpmind.symmetric.db.alter;
/*
* Licensed to the Apache Software Foundation (ASF) under one
@@ -19,9 +19,9 @@
* under the License.
*/
-import org.jumpmind.symmetric.db.ddl.model.Column;
-import org.jumpmind.symmetric.db.ddl.model.Database;
-import org.jumpmind.symmetric.db.ddl.model.Table;
+import org.jumpmind.symmetric.db.model.Column;
+import org.jumpmind.symmetric.db.model.Database;
+import org.jumpmind.symmetric.db.model.Table;
/**
* Represents the change of the auto-increment constraint of a column. Since it is a boolean value,
diff --git a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/alteration/ColumnChange.java b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/alter/ColumnChange.java
similarity index 88%
rename from symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/alteration/ColumnChange.java
rename to symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/alter/ColumnChange.java
index 84aad73610..2767eaad83 100644
--- a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/alteration/ColumnChange.java
+++ b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/alter/ColumnChange.java
@@ -1,4 +1,4 @@
-package org.jumpmind.symmetric.db.ddl.alteration;
+package org.jumpmind.symmetric.db.alter;
/*
* Licensed to the Apache Software Foundation (ASF) under one
@@ -19,7 +19,7 @@
* under the License.
*/
-import org.jumpmind.symmetric.db.ddl.model.Column;
+import org.jumpmind.symmetric.db.model.Column;
/**
* Represents a change to a column of a table.
diff --git a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/alteration/ColumnDataTypeChange.java b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/alter/ColumnDataTypeChange.java
similarity index 88%
rename from symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/alteration/ColumnDataTypeChange.java
rename to symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/alter/ColumnDataTypeChange.java
index 3c86937929..2f25801f34 100644
--- a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/alteration/ColumnDataTypeChange.java
+++ b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/alter/ColumnDataTypeChange.java
@@ -1,4 +1,4 @@
-package org.jumpmind.symmetric.db.ddl.alteration;
+package org.jumpmind.symmetric.db.alter;
/*
* Licensed to the Apache Software Foundation (ASF) under one
@@ -19,9 +19,9 @@
* under the License.
*/
-import org.jumpmind.symmetric.db.ddl.model.Column;
-import org.jumpmind.symmetric.db.ddl.model.Database;
-import org.jumpmind.symmetric.db.ddl.model.Table;
+import org.jumpmind.symmetric.db.model.Column;
+import org.jumpmind.symmetric.db.model.Database;
+import org.jumpmind.symmetric.db.model.Table;
/**
* Represents the change of the data type of a column.
diff --git a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/alteration/ColumnDefaultValueChange.java b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/alter/ColumnDefaultValueChange.java
similarity index 88%
rename from symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/alteration/ColumnDefaultValueChange.java
rename to symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/alter/ColumnDefaultValueChange.java
index 7c640c4c78..772509df28 100644
--- a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/alteration/ColumnDefaultValueChange.java
+++ b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/alter/ColumnDefaultValueChange.java
@@ -1,4 +1,4 @@
-package org.jumpmind.symmetric.db.ddl.alteration;
+package org.jumpmind.symmetric.db.alter;
/*
* Licensed to the Apache Software Foundation (ASF) under one
@@ -19,9 +19,9 @@
* under the License.
*/
-import org.jumpmind.symmetric.db.ddl.model.Column;
-import org.jumpmind.symmetric.db.ddl.model.Database;
-import org.jumpmind.symmetric.db.ddl.model.Table;
+import org.jumpmind.symmetric.db.model.Column;
+import org.jumpmind.symmetric.db.model.Database;
+import org.jumpmind.symmetric.db.model.Table;
/**
* Represents the change of the default value of a column.
diff --git a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/alteration/ColumnRequiredChange.java b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/alter/ColumnRequiredChange.java
similarity index 87%
rename from symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/alteration/ColumnRequiredChange.java
rename to symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/alter/ColumnRequiredChange.java
index 09d8fe699e..b360c310cd 100644
--- a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/alteration/ColumnRequiredChange.java
+++ b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/alter/ColumnRequiredChange.java
@@ -1,4 +1,4 @@
-package org.jumpmind.symmetric.db.ddl.alteration;
+package org.jumpmind.symmetric.db.alter;
/*
* Licensed to the Apache Software Foundation (ASF) under one
@@ -19,9 +19,9 @@
* under the License.
*/
-import org.jumpmind.symmetric.db.ddl.model.Column;
-import org.jumpmind.symmetric.db.ddl.model.Database;
-import org.jumpmind.symmetric.db.ddl.model.Table;
+import org.jumpmind.symmetric.db.model.Column;
+import org.jumpmind.symmetric.db.model.Database;
+import org.jumpmind.symmetric.db.model.Table;
/**
* Represents the change of the required constraint of a column. Since it is a boolean value,
diff --git a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/alteration/ColumnSizeChange.java b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/alter/ColumnSizeChange.java
similarity index 88%
rename from symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/alteration/ColumnSizeChange.java
rename to symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/alter/ColumnSizeChange.java
index 041d2d7a2c..0e9bdefc9c 100644
--- a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/alteration/ColumnSizeChange.java
+++ b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/alter/ColumnSizeChange.java
@@ -1,4 +1,4 @@
-package org.jumpmind.symmetric.db.ddl.alteration;
+package org.jumpmind.symmetric.db.alter;
/*
* Licensed to the Apache Software Foundation (ASF) under one
@@ -19,9 +19,9 @@
* under the License.
*/
-import org.jumpmind.symmetric.db.ddl.model.Column;
-import org.jumpmind.symmetric.db.ddl.model.Database;
-import org.jumpmind.symmetric.db.ddl.model.Table;
+import org.jumpmind.symmetric.db.model.Column;
+import org.jumpmind.symmetric.db.model.Database;
+import org.jumpmind.symmetric.db.model.Table;
/**
* Represents the change of the size or scale of a column.
diff --git a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/alteration/ModelChange.java b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/alter/IModelChange.java
similarity index 84%
rename from symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/alteration/ModelChange.java
rename to symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/alter/IModelChange.java
index 11c5f3b3bf..c329bab048 100644
--- a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/alteration/ModelChange.java
+++ b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/alter/IModelChange.java
@@ -1,4 +1,4 @@
-package org.jumpmind.symmetric.db.ddl.alteration;
+package org.jumpmind.symmetric.db.alter;
/*
* Licensed to the Apache Software Foundation (ASF) under one
@@ -19,14 +19,12 @@
* under the License.
*/
-import org.jumpmind.symmetric.db.ddl.model.Database;
+import org.jumpmind.symmetric.db.model.Database;
/**
* Marker interface for changes to a database model element.
- *
- * @version $Revision: $
*/
-public interface ModelChange
+public interface IModelChange
{
/**
* Applies this change to the given database.
diff --git a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/alteration/ModelComparator.java b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/alter/ModelComparator.java
similarity index 52%
rename from symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/alteration/ModelComparator.java
rename to symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/alter/ModelComparator.java
index cbddf49cdb..125a14387f 100644
--- a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/alteration/ModelComparator.java
+++ b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/alter/ModelComparator.java
@@ -1,4 +1,4 @@
-package org.jumpmind.symmetric.db.ddl.alteration;
+package org.jumpmind.symmetric.db.alter;
/*
* Licensed to the Apache Software Foundation (ASF) under one
@@ -26,99 +26,96 @@
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import org.jumpmind.symmetric.db.ddl.PlatformInfo;
-import org.jumpmind.symmetric.db.ddl.model.Column;
-import org.jumpmind.symmetric.db.ddl.model.Database;
-import org.jumpmind.symmetric.db.ddl.model.ForeignKey;
-import org.jumpmind.symmetric.db.ddl.model.Index;
-import org.jumpmind.symmetric.db.ddl.model.Table;
+import org.jumpmind.symmetric.db.DatabasePlatformInfo;
+import org.jumpmind.symmetric.db.model.Column;
+import org.jumpmind.symmetric.db.model.Database;
+import org.jumpmind.symmetric.db.model.ForeignKey;
+import org.jumpmind.symmetric.db.model.Index;
+import org.jumpmind.symmetric.db.model.Table;
/**
* Compares two database models and creates change objects that express how to
- * adapt the first model so that it becomes the second one. Neither of the models
- * are changed in the process, however, it is also assumed that the models do not
- * change in between.
+ * adapt the first model so that it becomes the second one. Neither of the
+ * models are changed in the process, however, it is also assumed that the
+ * models do not change in between.
*
- * TODO: Add support and tests for the change of the column order
+ * TODO: Add support and tests for the change of the column order
*/
-public class ModelComparator
-{
+public class ModelComparator {
/** The log for this comparator. */
private final Log _log = LogFactory.getLog(ModelComparator.class);
/** The platform information. */
- private PlatformInfo _platformInfo;
+ private DatabasePlatformInfo _platformInfo;
/** Whether comparison is case sensitive. */
private boolean _caseSensitive;
/**
* Creates a new model comparator object.
*
- * @param platformInfo The platform info
- * @param caseSensitive Whether comparison is case sensitive
+ * @param platformInfo
+ * The platform info
+ * @param caseSensitive
+ * Whether comparison is case sensitive
*/
- public ModelComparator(PlatformInfo platformInfo, boolean caseSensitive)
- {
- _platformInfo = platformInfo;
+ public ModelComparator(DatabasePlatformInfo platformInfo, boolean caseSensitive) {
+ _platformInfo = platformInfo;
_caseSensitive = caseSensitive;
}
/**
- * Compares the two models and returns the changes necessary to create the second
- * model from the first one.
- *
- * @param sourceModel The source model
- * @param targetModel The target model
+ * Compares the two models and returns the changes necessary to create the
+ * second model from the first one.
+ *
+ * @param sourceModel
+ * The source model
+ * @param targetModel
+ * The target model
* @return The changes
*/
- public List compare(Database sourceModel, Database targetModel)
- {
- ArrayList changes = new ArrayList();
+ public Listtrue
if script mode is on
- */
- public boolean isScriptModeOn();
-
- /*
- * Specifies whether script mode is on. This means that the generated SQL is not
- * intended to be sent directly to the database but rather to be saved in a SQL
- * script file.
- *
- * @param scriptModeOn true
if script mode is on
- */
- public void setScriptModeOn(boolean scriptModeOn);
-
- /*
- * Determines whether delimited identifiers are used or normal SQL92 identifiers
- * (which may only contain alphanumerical characters and the underscore, must start
- * with a letter and cannot be a reserved keyword).
- * Per default, delimited identifiers are not used
- *
- * @return true
if delimited identifiers are used
- */
- public boolean isDelimitedIdentifierModeOn();
-
- /*
- * Specifies whether delimited identifiers are used or normal SQL92 identifiers.
- *
- * @param delimitedIdentifierModeOn true
if delimited identifiers shall be used
- */
- public void setDelimitedIdentifierModeOn(boolean delimitedIdentifierModeOn);
-
- /*
- * Determines whether SQL comments are generated.
- *
- * @return true
if SQL comments shall be generated
- */
- public boolean isSqlCommentsOn();
-
- /*
- * Specifies whether SQL comments shall be generated.
- *
- * @param sqlCommentsOn true
if SQL comments shall be generated
- */
- public void setSqlCommentsOn(boolean sqlCommentsOn);
-
- /*
- * Determines whether SQL insert statements can specify values for identity columns.
- * This setting is only relevant if the database supports it
- * ({@link PlatformInfo#isIdentityOverrideAllowed()}). If this is off, then the
- * insert
methods will ignore values for identity columns.
- *
- * @return true
if identity override is enabled (the default)
- */
- public boolean isIdentityOverrideOn();
-
- /*
- * Specifies whether SQL insert statements can specify values for identity columns.
- * This setting is only relevant if the database supports it
- * ({@link PlatformInfo#isIdentityOverrideAllowed()}). If this is off, then the
- * insert
methods will ignore values for identity columns.
- *
- * @param identityOverrideOn true
if identity override is enabled (the default)
- */
- public void setIdentityOverrideOn(boolean identityOverrideOn);
-
- /*
- * Determines whether foreign keys of a table read from a live database
- * are alphabetically sorted.
- *
- * @return true
if read foreign keys are sorted
- */
- public boolean isForeignKeysSorted();
-
- /*
- * Specifies whether foreign keys read from a live database, shall be
- * alphabetically sorted.
- *
- * @param foreignKeysSorted true
if read foreign keys shall be sorted
- */
- public void setForeignKeysSorted(boolean foreignKeysSorted);
-
- /*
- * Returns a (new) JDBC connection from the data source.
- *
- * @return The connection
- */
- public Connection borrowConnection() throws DatabaseOperationException;
-
- /*
- * Closes the given JDBC connection (returns it back to the pool if the datasource is poolable).
- *
- * @param connection The connection
- */
- public void returnConnection(Connection connection);
-
- /*
- * Performs a shutdown at the database. This is necessary for some embedded databases which otherwise
- * would be locked and thus would refuse other connections. Note that this does not change the database
- * structure or data in it in any way.
- */
- public void shutdownDatabase() throws DatabaseOperationException;
-
- /*
- * Performs a shutdown at the database. This is necessary for some embedded databases which otherwise
- * would be locked and thus would refuse other connections. Note that this does not change the database
- * structure or data in it in any way.
- *
- * @param connection The connection to the database
- */
- public void shutdownDatabase(Connection connection) throws DatabaseOperationException;
-
- /*
- * Creates the database specified by the given parameters. Please note that this method does not
- * use a data source set via {@link #setDataSource(DataSource)} because it is not possible to
- * retrieve the connection information from it without establishing a connection.null
for the platform-specific default value
- * @param schema The schema in the existing database to read (can be a pattern);
- * use null
for the platform-specific default value
- * @param tableTypes The table types to read from the existing database;
- * use null
or an empty array for the platform-specific default value
- * @param desiredDb The desired database schema
- * @param continueOnError Whether to continue with the next sql statement when an error occurred
- */
- public void alterTables(String catalog, String schema, String[] tableTypes, Database desiredDb, boolean continueOnError) throws DatabaseOperationException;
-
- /*
- * Returns the SQL for altering the database schema so that it match the given model.
- *
- * @param catalog The catalog in the existing database to read (can be a pattern);
- * use null
for the platform-specific default value
- * @param schema The schema in the existing database to read (can be a pattern);
- * use null
for the platform-specific default value
- * @param tableTypes The table types to read from the existing database;
- * use null
or an empty array for the platform-specific default value
- * @param desiredDb The desired database schema
- * @return The SQL statements
- */
- public String getAlterTablesSql(String catalog, String schema, String[] tableTypes, Database desiredDb) throws DatabaseOperationException;
-
- /*
- * Alters the database schema so that it match the given model.
- *
- * @param catalog The catalog in the existing database to read (can be a pattern);
- * use null
for the platform-specific default value
- * @param schema The schema in the existing database to read (can be a pattern);
- * use null
for the platform-specific default value
- * @param tableTypes The table types to read from the existing database;
- * use null
or an empty array for the platform-specific default value
- * @param desiredDb The desired database schema
- * @param params The parameters used in the creation
- * @param continueOnError Whether to continue with the next sql statement when an error occurred
- */
- public void alterTables(String catalog, String schema, String[] tableTypes, Database desiredDb, CreationParameters params, boolean continueOnError) throws DatabaseOperationException;
-
- /*
- * Returns the SQL for altering the database schema so that it match the given model.
- *
- * @param catalog The catalog in the existing database to read (can be a pattern);
- * use null
for the platform-specific default value
- * @param schema The schema in the existing database to read (can be a pattern);
- * use null
for the platform-specific default value
- * @param tableTypes The table types to read from the existing database;
- * use null
or an empty array for the platform-specific default value
- * @param desiredDb The desired database schema
- * @param params The parameters used in the creation
- * @return The SQL statements
- */
- public String getAlterTablesSql(String catalog, String schema, String[] tableTypes, Database desiredDb, CreationParameters params) throws DatabaseOperationException;
-
- /*
- * Alters the database schema so that it match the given model.
- *
- * @param connection A connection to the existing database that shall be modified
- * @param desiredDb The desired database schema
- * @param continueOnError Whether to continue with the next sql statement when an error occurred
- */
- public void alterTables(Connection connection, Database desiredDb, boolean continueOnError) throws DatabaseOperationException;
-
- /*
- * Returns the SQL for altering the database schema so that it match the given model.
- *
- * @param connection A connection to the existing database that shall be modified
- * @param desiredDb The desired database schema
- * @return The SQL statements
- */
- public String getAlterTablesSql(Connection connection, Database desiredDb) throws DatabaseOperationException;
-
- /*
- * Alters the database schema so that it match the given model.
- *
- * @param connection A connection to the existing database that shall be modified
- * @param desiredDb The desired database schema
- * @param params The parameters used in the creation
- * @param continueOnError Whether to continue with the next sql statement when an error occurred
- */
- public void alterTables(Connection connection, Database desiredDb, CreationParameters params, boolean continueOnError) throws DatabaseOperationException;
-
- /*
- * Returns the SQL for altering the database schema so that it match the given model.
- *
- * @param connection A connection to the existing database that shall be modified
- * @param desiredDb The desired database schema
- * @param params The parameters used in the creation
- * @return The SQL statements
- */
- public String getAlterTablesSql(Connection connection, Database desiredDb, CreationParameters params) throws DatabaseOperationException;
-
- /*
- * Alters the database schema so that it match the given model.
- *
- * @param connection A connection to the existing database that shall be modified
- * @param catalog The catalog in the existing database to read (can be a pattern);
- * use null
for the platform-specific default value
- * @param schema The schema in the existing database to read (can be a pattern);
- * use null
for the platform-specific default value
- * @param tableTypes The table types to read from the existing database;
- * use null
or an empty array for the platform-specific default value
- * @param desiredDb The desired database schema
- * @param continueOnError Whether to continue with the next sql statement when an error occurred
- */
- public void alterTables(Connection connection, String catalog, String schema, String[] tableTypes, Database desiredDb, boolean continueOnError) throws DatabaseOperationException;
-
- /*
- * Returns the SQL for altering the database schema so that it match the given model.
- *
- * @param connection A connection to the existing database that shall be modified
- * @param catalog The catalog in the existing database to read (can be a pattern);
- * use null
for the platform-specific default value
- * @param schema The schema in the existing database to read (can be a pattern);
- * use null
for the platform-specific default value
- * @param tableTypes The table types to read from the existing database;
- * use null
or an empty array for the platform-specific default value
- * @param desiredDb The desired database schema
- * @return The SQL statements
- */
- public String getAlterTablesSql(Connection connection, String catalog, String schema, String[] tableTypes, Database desiredDb) throws DatabaseOperationException;
-
- /*
- * Alters the database schema so that it match the given model.
- *
- * @param connection A connection to the existing database that shall be modified
- * @param catalog The catalog in the existing database to read (can be a pattern);
- * use null
for the platform-specific default value
- * @param schema The schema in the existing database to read (can be a pattern);
- * use null
for the platform-specific default value
- * @param tableTypes The table types to read from the existing database;
- * use null
or an empty array for the platform-specific default value
- * @param desiredDb The desired database schema
- * @param params The parameters used in the creation
- * @param continueOnError Whether to continue with the next sql statement when an error occurred
- */
- public void alterTables(Connection connection, String catalog, String schema, String[] tableTypes, Database desiredDb, CreationParameters params, boolean continueOnError) throws DatabaseOperationException;
-
- /*
- * Returns the SQL for altering the database schema so that it match the given model.
- *
- * @param connection A connection to the existing database that shall be modified
- * @param catalog The catalog in the existing database to read (can be a pattern);
- * use null
for the platform-specific default value
- * @param schema The schema in the existing database to read (can be a pattern);
- * use null
for the platform-specific default value
- * @param tableTypes The table types to read from the existing database;
- * use null
or an empty array for the platform-specific default value
- * @param desiredDb The desired database schema
- * @param params The parameters used in the creation
- * @return The SQL statements
- */
- public String getAlterTablesSql(Connection connection, String catalog, String schema, String[] tableTypes, Database desiredDb, CreationParameters params) throws DatabaseOperationException;
-
- /*
- * Drops the specified table and all foreign keys pointing to it.
- *
- * @param model The database model
- * @param table The table to drop
- * @param continueOnError Whether to continue executing the sql commands when an error occurred
- */
- public void dropTable(Database model, Table table, boolean continueOnError) throws DatabaseOperationException;
-
- /*
- * Returns the SQL for dropping the given table and all foreign keys pointing to it.
- *
- * @param model The database model
- * @param table The table to drop
- * @param continueOnError Whether to continue executing the sql commands when an error occurred
- * @return The SQL statements
- */
- public String getDropTableSql(Database model, Table table, boolean continueOnError);
-
- /*
- * Drops the specified table and all foreign keys pointing to it.
- *
- * @param connection The connection to the database
- * @param model The database model
- * @param table The table to drop
- * @param continueOnError Whether to continue executing the sql commands when an error occurred
- */
- public void dropTable(Connection connection, Database model, Table table, boolean continueOnError) throws DatabaseOperationException;
-
- /*
- * Drops the tables defined in the given database.
- *
- * @param model The database model
- * @param continueOnError Whether to continue executing the sql commands when an error occurred
- */
- public void dropTables(Database model, boolean continueOnError) throws DatabaseOperationException;
-
- /*
- * Returns the SQL for dropping the tables defined in the given database.
- *
- * @param model The database model
- * @param continueOnError Whether to continue executing the sql commands when an error occurred
- * @return The SQL statements
- */
- public String getDropTablesSql(Database model, boolean continueOnError);
-
- /*
- * Drops the tables defined in the given database.
- *
- * @param connection The connection to the database
- * @param model The database model
- * @param continueOnError Whether to continue executing the sql commands when an error occurred
- */
- public void dropTables(Connection connection, Database model, boolean continueOnError) throws DatabaseOperationException;
-
- /*
- * Reads the database model from the live database as specified by the data source set for
- * this platform.
- *
- * @param name The name of the resulting database; null
when the default name (the catalog)
- * is desired which might be null
itself though
- * @return The database model
- * @throws DatabaseOperationException If an error occurred during reading the model
- */
- public Database readModelFromDatabase(String name) throws DatabaseOperationException;
-
- /*
- * Reads the database model from the live database as specified by the data source set for
- * this platform.
- *
- * @param name The name of the resulting database; null
when the default name (the catalog)
- * is desired which might be null
itself though
- * @param catalog The catalog to access in the database; use null
for the default value
- * @param schema The schema to access in the database; use null
for the default value
- * @param tableTypes The table types to process; use null
or an empty list for the default ones
- * @return The database model
- * @throws DatabaseOperationException If an error occurred during reading the model
- */
- public Database readModelFromDatabase(String name, String catalog, String schema, String[] tableTypes) throws DatabaseOperationException;
-
- /*
- * Reads the database model from the live database to which the given connection is pointing.
- *
- * @param connection The connection to the database
- * @param name The name of the resulting database; null
when the default name (the catalog)
- * is desired which might be null
itself though
- * @return The database model
- * @throws DatabaseOperationException If an error occurred during reading the model
- */
- public Database readModelFromDatabase(Connection connection, String name) throws DatabaseOperationException;
-
- /*
- * Reads the database model from the live database to which the given connection is pointing.
- *
- * @param connection The connection to the database
- * @param name The name of the resulting database; null
when the default name (the catalog)
- * is desired which might be null
itself though
- * @param catalog The catalog to access in the database; use null
for the default value
- * @param schema The schema to access in the database; use null
for the default value
- * @param tableTypes The table types to process; use null
or an empty list for the default ones
- * @return The database model
- * @throws DatabaseOperationException If an error occurred during reading the model
- */
- public Database readModelFromDatabase(Connection connection, String name, String catalog, String schema, String[] tableTypes) throws DatabaseOperationException;
-
-
- public Table readTableFromDatabase(Connection connection, String catalogName, String schemaName, String tablename) throws SQLException;
-
-}
diff --git a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/PlatformFactory.java b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/PlatformFactory.java
deleted file mode 100644
index f3cfede4c1..0000000000
--- a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/PlatformFactory.java
+++ /dev/null
@@ -1,231 +0,0 @@
-package org.jumpmind.symmetric.db.ddl;
-
-/*
- * 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.util.HashMap;
-import java.util.Map;
-
-import javax.sql.DataSource;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.jumpmind.symmetric.db.ddl.platform.cloudscape.CloudscapePlatform;
-import org.jumpmind.symmetric.db.ddl.platform.db2.Db2v8Platform;
-import org.jumpmind.symmetric.db.ddl.platform.derby.DerbyPlatform;
-import org.jumpmind.symmetric.db.ddl.platform.firebird.FirebirdPlatform;
-import org.jumpmind.symmetric.db.ddl.platform.greenplum.GreenplumPlatform;
-import org.jumpmind.symmetric.db.ddl.platform.h2.H2Platform;
-import org.jumpmind.symmetric.db.ddl.platform.hsqldb.HsqlDbPlatform;
-import org.jumpmind.symmetric.db.ddl.platform.hsqldb2.HsqlDb2Platform;
-import org.jumpmind.symmetric.db.ddl.platform.informix.InformixPlatform;
-import org.jumpmind.symmetric.db.ddl.platform.interbase.InterbasePlatform;
-import org.jumpmind.symmetric.db.ddl.platform.mssql.MSSqlPlatform;
-import org.jumpmind.symmetric.db.ddl.platform.mysql.MySql50Platform;
-import org.jumpmind.symmetric.db.ddl.platform.mysql.MySqlPlatform;
-import org.jumpmind.symmetric.db.ddl.platform.oracle.Oracle10Platform;
-import org.jumpmind.symmetric.db.ddl.platform.oracle.Oracle8Platform;
-import org.jumpmind.symmetric.db.ddl.platform.oracle.Oracle9Platform;
-import org.jumpmind.symmetric.db.ddl.platform.postgresql.PostgreSqlPlatform;
-import org.jumpmind.symmetric.db.ddl.platform.sqlite.SqLitePlatform;
-import org.jumpmind.symmetric.db.ddl.platform.sybase.SybaseASE15Platform;
-import org.jumpmind.symmetric.db.ddl.platform.sybase.SybasePlatform;
-
-/*
- * A factory of {@link org.jumpmind.symmetric.ddl.Platform} instances based on a case
- * insensitive database name. Note that this is a convenience class as the platforms
- * can also simply be created via their constructors.
- *
- * @version $Revision: 209952 $
- */
-public class PlatformFactory
-{
- /* The log for this platform. */
- private static final Log _log = LogFactory.getLog(PlatformFactory.class);
-
- /* The database name -> platform map. */
- private static Mapnull
if the database is not supported
- */
- public static synchronized Platform createNewPlatformInstance(String databaseName) throws DdlUtilsException
- {
- Class extends Platform> platformClass = getPlatforms().get(databaseName.toLowerCase());
-
- try
- {
- return platformClass != null ? (Platform)platformClass.newInstance() : null;
- }
- catch (Exception ex)
- {
- throw new DdlUtilsException("Could not create platform for database "+databaseName, ex);
- }
- }
-
- /*
- * Creates a new platform for the specified database. This is a shortcut method that uses
- * {@link PlatformUtils#determineDatabaseType(String, String)} to determine the parameter
- * for {@link #createNewPlatformInstance(String)}. Note that no database connection is
- * established when using this method.
- *
- * @param jdbcDriver The jdbc driver
- * @param jdbcConnectionUrl The connection url
- * @return The platform or null
if the database is not supported
- */
- public static synchronized Platform createNewPlatformInstance(String jdbcDriver, String jdbcConnectionUrl) throws DdlUtilsException
- {
- return createNewPlatformInstance(PlatformUtils.determineDatabaseType(jdbcDriver, jdbcConnectionUrl));
- }
-
- /*
- * Creates a new platform for the specified database. This is a shortcut method that uses
- * {@link PlatformUtils#determineDatabaseType(DataSource)} to determine the parameter
- * for {@link #createNewPlatformInstance(String)}. Note that this method sets the data source
- * at the returned platform instance (method {@link Platform#setDataSource(DataSource)}).
- *
- * @param dataSource The data source for the database
- * @return The platform or null
if the database is not supported
- */
- public static synchronized Platform createNewPlatformInstance(DataSource dataSource) throws DdlUtilsException
- {
- //connects to the database and uses actual metadata info to get db name and version
- //to determine platform
- String nameVersion = PlatformUtils.determineDatabaseNameVersion(dataSource);
- Platform platform = createNewPlatformInstance(nameVersion);
- if (platform == null) {
- //uses the driver info to try and infer a platform
- String dbType = PlatformUtils.determineDatabaseType(dataSource);
- _log.debug("The name/version pair returned for the database, "
- + nameVersion
- + ", was not mapped to a known database platform. Defaulting to using just the database type of "
- + dbType);
- platform = createNewPlatformInstance(dbType);
- }
- platform.setDataSource(dataSource);
- return platform;
- }
-
- /*
- * Returns a list of all supported platforms.
- *
- * @return The names of the currently registered platforms
- */
- public static synchronized String[] getSupportedPlatforms()
- {
- return (String[])getPlatforms().keySet().toArray(new String[0]);
- }
-
- /*
- * Determines whether the indicated platform is supported.
- *
- * @param platformName The name of the platform
- * @return true
if the platform is supported
- */
- public static boolean isPlatformSupported(String platformName)
- {
- return getPlatforms().containsKey(platformName.toLowerCase());
- }
-
- /*
- * Registers a new platform.
- *
- * @param platformName The platform name
- * @param platformClass The platform class which must implement the {@link Platform} interface
- */
- public static synchronized void registerPlatform(String platformName, Class extends Platform> platformClass)
- {
- addPlatform(getPlatforms(), platformName, platformClass);
- }
-
- /*
- * Registers the known platforms.
- */
- private static void registerPlatforms()
- {
- for (String name : H2Platform.DATABASENAMES) {
- addPlatform(_platforms, name,
- H2Platform.class);
- }
- addPlatform(_platforms, SqLitePlatform.DATABASENAME, SqLitePlatform.class);
- addPlatform(_platforms, InformixPlatform.DATABASENAME, InformixPlatform.class);
- addPlatform(_platforms, CloudscapePlatform.DATABASENAME, CloudscapePlatform.class);
- addPlatform(_platforms, Db2v8Platform.DATABASENAMES, Db2v8Platform.class);
- addPlatform(_platforms, DerbyPlatform.DATABASENAME, DerbyPlatform.class);
- addPlatform(_platforms, FirebirdPlatform.DATABASENAME, FirebirdPlatform.class);
- addPlatform(_platforms, GreenplumPlatform.DATABASENAME, GreenplumPlatform.class);
- addPlatform(_platforms, HsqlDbPlatform.DATABASENAME, HsqlDbPlatform.class);
- addPlatform(_platforms, HsqlDb2Platform.DATABASENAME, HsqlDb2Platform.class);
- addPlatform(_platforms, InterbasePlatform.DATABASENAME, InterbasePlatform.class);
- addPlatform(_platforms, MSSqlPlatform.DATABASENAME, MSSqlPlatform.class);
- addPlatform(_platforms, MySqlPlatform.DATABASENAME, MySqlPlatform.class);
- addPlatform(_platforms, MySql50Platform.DATABASENAME, MySql50Platform.class);
- addPlatform(_platforms, Oracle8Platform.DATABASENAME, Oracle8Platform.class);
- addPlatform(_platforms, Oracle9Platform.DATABASENAME, Oracle9Platform.class);
- addPlatform(_platforms, Oracle10Platform.DATABASENAME10, Oracle10Platform.class);
- addPlatform(_platforms, Oracle10Platform.DATABASENAME11, Oracle10Platform.class);
- addPlatform(_platforms, PostgreSqlPlatform.DATABASENAME, PostgreSqlPlatform.class);
- addPlatform(_platforms, SybasePlatform.DATABASENAME, SybasePlatform.class);
- addPlatform(_platforms, SybaseASE15Platform.DATABASENAME, SybaseASE15Platform.class);
- }
-
- /*
- * Registers a new platform.
- *
- * @param platformMap The map to add the platform info to
- * @param platformName The platform name
- * @param platformClass The platform class which must implement the {@link Platform} interface
- */
- private static synchronized void addPlatform(Mapnull
if the database type couldn't be determined
- */
- public static String determineDatabaseType(DataSource dataSource) throws DatabaseOperationException
- {
- Connection connection = null;
-
- try
- {
- connection = dataSource.getConnection();
- DatabaseMetaData metaData = connection.getMetaData();
- return determineDatabaseType(metaData.getDriverName(), metaData.getURL());
- }
- catch (SQLException ex)
- {
- throw new DatabaseOperationException("Error while reading the database metadata: " + ex.getMessage(), ex);
- }
- finally
- {
- if (connection != null)
- {
- try
- {
- connection.close();
- }
- catch (SQLException ex)
- {
- // we ignore this one
- }
- }
- }
- }
-
- public static String getDatabaseProductVersion(DataSource dataSource) {
- Connection connection = null;
-
- try {
- connection = dataSource.getConnection();
- DatabaseMetaData metaData = connection.getMetaData();
- return metaData.getDatabaseProductVersion();
- } catch (SQLException ex) {
- throw new DatabaseOperationException("Error while reading the database metadata: "
- + ex.getMessage(), ex);
- } finally {
- if (connection != null) {
- try {
- connection.close();
- } catch (SQLException ex) {
- // we ignore this one
- }
- }
- }
- }
-
- public static int getDatabaseMajorVersion(DataSource dataSource) {
- Connection connection = null;
- try {
- connection = dataSource.getConnection();
- DatabaseMetaData metaData = connection.getMetaData();
- return metaData.getDatabaseMajorVersion();
- } catch (SQLException ex) {
- throw new DatabaseOperationException("Error while reading the database metadata: "
- + ex.getMessage(), ex);
- } finally {
- if (connection != null) {
- try {
- connection.close();
- } catch (SQLException ex) {
- // we ignore this one
- }
- }
- }
- }
-
- public static int getDatabaseMinorVersion(DataSource dataSource) {
- Connection connection = null;
- try {
- connection = dataSource.getConnection();
- DatabaseMetaData metaData = connection.getMetaData();
- return metaData.getDatabaseMinorVersion();
- } catch (SQLException ex) {
- throw new DatabaseOperationException("Error while reading the database metadata: "
- + ex.getMessage(), ex);
- } finally {
- if (connection != null) {
- try {
- connection.close();
- } catch (SQLException ex) {
- // we ignore this one
- }
- }
- }
- }
-
- public static String determineDatabaseNameVersion(DataSource dataSource) throws DatabaseOperationException {
- Connection connection = null;
-
- try {
- connection = dataSource.getConnection();
- DatabaseMetaData metaData = connection.getMetaData();
- String productName = metaData.getDatabaseProductName();
- int majorVersion = metaData.getDatabaseMajorVersion();
- /* if the productName is PostgreSQL, it could be either PostgreSQL or Greenplum */
- /* query the metadata to determine which one it is */
- if (productName.equalsIgnoreCase(PostgreSqlPlatform.DATABASENAME)) {
- if (isGreenplumDatabase(connection)) {
- productName = GreenplumPlatform.DATABASE;
- majorVersion = getGreenplumVersion(connection);
- }
- }
- String productString = productName;
- if (majorVersion > 0) {
- productString += majorVersion;
- }
-
- return productString;
- } catch (SQLException ex) {
- throw new DatabaseOperationException("Error while reading the database metadata: "
- + ex.getMessage(), ex);
- } finally {
- if (connection != null) {
- try {
- connection.close();
- } catch (SQLException ex) {
- // we ignore this one
- }
- }
- }
- }
-
- private static boolean isGreenplumDatabase(Connection connection) {
- Statement stmt = null;
- ResultSet rs = null;
- String productName = null;
- boolean isGreenplum = false;
- try {
- stmt = connection.createStatement();
- rs = stmt.executeQuery(GreenplumPlatform.SQL_GET_GREENPLUM_NAME);
- while (rs.next()) {
- productName = rs.getString(1);
- }
- if (productName != null && productName.equalsIgnoreCase(GreenplumPlatform.DATABASE)) {
- isGreenplum = true;
- }
- }catch (SQLException ex) {
- // ignore the exception, if it is caught, then this is most likely not
- // a greenplum database
- } finally {
- try {
- if (rs != null) {
- rs.close();
- }
- if (stmt != null) {
- stmt.close();
- }
- }
- catch (SQLException ex) {
- }
- }
- return isGreenplum;
- }
-
- private static int getGreenplumVersion(Connection connection) {
- Statement stmt = null;
- ResultSet rs = null;
- String versionName = null;
- int productVersion = 0;
- try {
- stmt = connection.createStatement();
- rs = stmt.executeQuery(GreenplumPlatform.SQL_GET_GREENPLUM_VERSION);
- while (rs.next()) {
- versionName = rs.getString(1);
- }
- //take up to the first "." for version number
- if (versionName.indexOf('.') != -1) {
- versionName = versionName.substring(0,versionName.indexOf('.'));
- }
- try {
- productVersion = Integer.parseInt(versionName);
- }
- catch (NumberFormatException ex) {
- // if we can't convert this to a version number, leave it 0
- }
- }
- catch (SQLException ex) {
- // ignore the exception, if it is caught, then this is most likely not
- // a greenplum database
- }
- finally {
- try {
- rs.close();
- stmt.close();
- }
- catch (SQLException ex) {
- }
- }
- return productVersion;
- }
-
- /*
- * Tries to determine the database type for the given jdbc driver and connection url.
- *
- * @param driverName The fully qualified name of the JDBC driver
- * @param jdbcConnectionUrl The connection url
- * @return The database type or null
if the database type couldn't be determined
- */
- public static String determineDatabaseType(String driverName, String jdbcConnectionUrl)
- {
- if (jdbcDriverToPlatform.containsKey(driverName))
- {
- return (String)jdbcDriverToPlatform.get(driverName);
- }
- if (jdbcConnectionUrl == null)
- {
- return null;
- }
- for (Iteratornull
then the parameter is for all tables
- * @param paramName The name of the parameter
- * @param paramValue The value of the parameter
- */
- public void addParameter(Table table, String paramName, String paramValue)
- {
- Map params = (Map)_parametersPerTable.get(table);
-
- if (params == null)
- {
- // we're using a list orderered map to retain the order
- params = new ListOrderedMap();
- _parametersPerTable.put(table, params);
- }
- params.put(paramName, paramValue);
- }
-}
diff --git a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/platform/PlatformImplBase.java b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/platform/PlatformImplBase.java
deleted file mode 100644
index 94e8e3243a..0000000000
--- a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/platform/PlatformImplBase.java
+++ /dev/null
@@ -1,1247 +0,0 @@
-package org.jumpmind.symmetric.db.ddl.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.StringWriter;
-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.Map;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.jumpmind.symmetric.db.ddl.DatabaseOperationException;
-import org.jumpmind.symmetric.db.ddl.DdlUtilsException;
-import org.jumpmind.symmetric.db.ddl.Platform;
-import org.jumpmind.symmetric.db.ddl.PlatformInfo;
-import org.jumpmind.symmetric.db.ddl.model.Column;
-import org.jumpmind.symmetric.db.ddl.model.Database;
-import org.jumpmind.symmetric.db.ddl.model.Table;
-import org.jumpmind.symmetric.db.ddl.model.TypeMap;
-import org.jumpmind.symmetric.db.ddl.util.Jdbc3Utils;
-import org.jumpmind.symmetric.db.ddl.util.JdbcSupport;
-import org.jumpmind.symmetric.db.ddl.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 = false;
- /* 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("Executing 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);
- }
- }
-
- /*
- * {@inheritDoc}
- */
- public void createTables(Connection connection, Database model, CreationParameters params, boolean dropTablesFirst, boolean continueOnError) throws DatabaseOperationException
- {
- String sql = getCreateTablesSql(model, params, dropTablesFirst, continueOnError);
-
- evaluateBatch(connection, sql, continueOnError);
- }
-
- /*
- * {@inheritDoc}
- */
- public String getCreateTablesSql(Database model, CreationParameters params, boolean dropTablesFirst, boolean continueOnError)
- {
- String sql = null;
-
- try
- {
- StringWriter buffer = new StringWriter();
-
- getSqlBuilder().setWriter(buffer);
- getSqlBuilder().createTables(model, params, dropTablesFirst);
- sql = buffer.toString();
- }
- catch (IOException e)
- {
- // won't happen because we're using a string writer
- }
- return sql;
- }
-
- /*
- * {@inheritDoc}
- */
- public void alterTables(Database desiredDb, boolean continueOnError) throws DatabaseOperationException
- {
- Connection connection = borrowConnection();
-
- try
- {
- alterTables(connection, desiredDb, continueOnError);
- }
- finally
- {
- returnConnection(connection);
- }
- }
-
- /*
- * {@inheritDoc}
- */
- public String getAlterTablesSql(Database desiredDb) throws DatabaseOperationException
- {
- Connection connection = borrowConnection();
-
- try
- {
- return getAlterTablesSql(connection, desiredDb);
- }
- finally
- {
- returnConnection(connection);
- }
- }
-
- /*
- * {@inheritDoc}
- */
- public void alterTables(Database desiredDb, CreationParameters params, boolean continueOnError) throws DatabaseOperationException
- {
- Connection connection = borrowConnection();
-
- try
- {
- alterTables(connection, desiredDb, params, continueOnError);
- }
- finally
- {
- returnConnection(connection);
- }
- }
-
- /*
- * {@inheritDoc}
- */
- public String getAlterTablesSql(Database desiredDb, CreationParameters params) throws DatabaseOperationException
- {
- Connection connection = borrowConnection();
-
- try
- {
- return getAlterTablesSql(connection, desiredDb, params);
- }
- finally
- {
- returnConnection(connection);
- }
- }
-
- /*
- * {@inheritDoc}
- */
- public void alterTables(Connection connection, Database desiredModel, boolean continueOnError) throws DatabaseOperationException
- {
- String sql = getAlterTablesSql(connection, desiredModel);
-
- evaluateBatch(connection, sql, continueOnError);
- }
-
- /*
- * {@inheritDoc}
- */
- public String getAlterTablesSql(Connection connection, Database desiredModel) throws DatabaseOperationException
- {
- String sql = null;
- Database currentModel = readModelFromDatabase(connection, desiredModel.getName());
-
- try
- {
- StringWriter buffer = new StringWriter();
-
- getSqlBuilder().setWriter(buffer);
- getSqlBuilder().alterDatabase(currentModel, desiredModel, null);
- sql = buffer.toString();
- }
- catch (IOException ex)
- {
- // won't happen because we're using a string writer
- }
- return sql;
- }
-
- /*
- * {@inheritDoc}
- */
- public void alterTables(Connection connection, Database desiredModel, CreationParameters params, boolean continueOnError) throws DatabaseOperationException
- {
- String sql = getAlterTablesSql(connection, desiredModel, params);
-
- evaluateBatch(connection, sql, continueOnError);
- }
-
- /*
- * {@inheritDoc}
- */
- public String getAlterTablesSql(Connection connection, Database desiredModel, CreationParameters params) throws DatabaseOperationException
- {
- String sql = null;
- Database currentModel = readModelFromDatabase(connection, desiredModel.getName());
-
- try
- {
- StringWriter buffer = new StringWriter();
-
- getSqlBuilder().setWriter(buffer);
- getSqlBuilder().alterDatabase(currentModel, desiredModel, params);
- sql = buffer.toString();
- }
- catch (IOException ex)
- {
- // won't happen because we're using a string writer
- }
- return sql;
- }
-
- /*
- * {@inheritDoc}
- */
- public void alterTables(String catalog, String schema, String[] tableTypes, Database desiredModel, boolean continueOnError) throws DatabaseOperationException
- {
- Connection connection = borrowConnection();
-
- try
- {
- alterTables(connection, catalog, schema, tableTypes, desiredModel, continueOnError);
- }
- finally
- {
- returnConnection(connection);
- }
- }
-
- /*
- * {@inheritDoc}
- */
- public String getAlterTablesSql(String catalog, String schema, String[] tableTypes, Database desiredModel) throws DatabaseOperationException
- {
- Connection connection = borrowConnection();
-
- try
- {
- return getAlterTablesSql(connection, catalog, schema, tableTypes, desiredModel);
- }
- finally
- {
- returnConnection(connection);
- }
- }
-
- /*
- * {@inheritDoc}
- */
- public void alterTables(String catalog, String schema, String[] tableTypes, Database desiredModel, CreationParameters params, boolean continueOnError) throws DatabaseOperationException
- {
- Connection connection = borrowConnection();
-
- try
- {
- alterTables(connection, catalog, schema, tableTypes, desiredModel, params, continueOnError);
- }
- finally
- {
- returnConnection(connection);
- }
- }
-
- /*
- * {@inheritDoc}
- */
- public String getAlterTablesSql(String catalog, String schema, String[] tableTypes, Database desiredModel, CreationParameters params) throws DatabaseOperationException
- {
- Connection connection = borrowConnection();
-
- try
- {
- return getAlterTablesSql(connection, catalog, schema, tableTypes, desiredModel, params);
- }
- finally
- {
- returnConnection(connection);
- }
- }
-
- /*
- * {@inheritDoc}
- */
- public void alterTables(Connection connection, String catalog, String schema, String[] tableTypes, Database desiredModel, boolean continueOnError) throws DatabaseOperationException
- {
- String sql = getAlterTablesSql(connection, catalog, schema, tableTypes, desiredModel);
-
- evaluateBatch(connection, sql, continueOnError);
- }
-
- /*
- * {@inheritDoc}
- */
- public String getAlterTablesSql(Connection connection, String catalog, String schema, String[] tableTypes, Database desiredModel) throws DatabaseOperationException
- {
- String sql = null;
- Database currentModel = readModelFromDatabase(connection, desiredModel.getName(), catalog, schema, tableTypes);
-
- try
- {
- StringWriter buffer = new StringWriter();
-
- getSqlBuilder().setWriter(buffer);
- getSqlBuilder().alterDatabase(currentModel, desiredModel, null);
- sql = buffer.toString();
- }
- catch (IOException ex)
- {
- // won't happen because we're using a string writer
- }
- return sql;
- }
-
- /*
- * {@inheritDoc}
- */
- public void alterTables(Connection connection, String catalog, String schema, String[] tableTypes, Database desiredModel, CreationParameters params, boolean continueOnError) throws DatabaseOperationException
- {
- String sql = getAlterTablesSql(connection, catalog, schema, tableTypes, desiredModel, params);
-
- evaluateBatch(connection, sql, continueOnError);
- }
-
- /*
- * {@inheritDoc}
- */
- public String getAlterTablesSql(Connection connection, String catalog, String schema, String[] tableTypes, Database desiredModel, CreationParameters params) throws DatabaseOperationException
- {
- String sql = null;
- Database currentModel = readModelFromDatabase(connection, desiredModel.getName(), catalog, schema, tableTypes);
-
- try
- {
- StringWriter buffer = new StringWriter();
-
- getSqlBuilder().setWriter(buffer);
- getSqlBuilder().alterDatabase(currentModel, desiredModel, params);
- sql = buffer.toString();
- }
- catch (IOException ex)
- {
- // won't happen because we're using a string writer
- }
- return sql;
- }
-
- /*
- * {@inheritDoc}
- */
- public void dropTable(Connection connection, Database model, Table table, boolean continueOnError) throws DatabaseOperationException
- {
- String sql = getDropTableSql(model, table, continueOnError);
-
- evaluateBatch(connection, sql, continueOnError);
- }
-
- /*
- * {@inheritDoc}
- */
- public void dropTable(Database model, Table table, boolean continueOnError) throws DatabaseOperationException
- {
- Connection connection = borrowConnection();
-
- try
- {
- dropTable(connection, model, table, continueOnError);
- }
- finally
- {
- returnConnection(connection);
- }
- }
-
- /*
- * {@inheritDoc}
- */
- public String getDropTableSql(Database model, Table table, boolean continueOnError)
- {
- String sql = null;
-
- try
- {
- StringWriter buffer = new StringWriter();
-
- getSqlBuilder().setWriter(buffer);
- getSqlBuilder().dropTable(model, table);
- sql = buffer.toString();
- }
- catch (IOException e)
- {
- // won't happen because we're using a string writer
- }
- return sql;
- }
-
- /*
- * {@inheritDoc}
- */
- public void dropTables(Database model, boolean continueOnError) throws DatabaseOperationException
- {
- Connection connection = borrowConnection();
-
- try
- {
- dropTables(connection, model, continueOnError);
- }
- finally
- {
- returnConnection(connection);
- }
- }
-
- /*
- * {@inheritDoc}
- */
- public void dropTables(Connection connection, Database model, boolean continueOnError) throws DatabaseOperationException
- {
- String sql = getDropTablesSql(model, continueOnError);
-
- evaluateBatch(connection, sql, continueOnError);
- }
-
- /*
- * {@inheritDoc}
- */
- public String getDropTablesSql(Database model, boolean continueOnError)
- {
- String sql = null;
-
- try
- {
- StringWriter buffer = new StringWriter();
-
- getSqlBuilder().setWriter(buffer);
- getSqlBuilder().dropTables(model);
- sql = buffer.toString();
- }
- catch (IOException e)
- {
- // won't happen because we're using a string writer
- }
- return sql;
- }
-
- /*
- * {@inheritDoc}
- */
- public Database readModelFromDatabase(String name) throws DatabaseOperationException
- {
- Connection connection = borrowConnection();
-
- try
- {
- return readModelFromDatabase(connection, name);
- }
- finally
- {
- returnConnection(connection);
- }
- }
-
- /*
- * {@inheritDoc}
- */
- public Database readModelFromDatabase(Connection connection, String name) throws DatabaseOperationException
- {
- try
- {
- Database model = getModelReader().getDatabase(connection, name);
-
- postprocessModelFromDatabase(model);
- return model;
- }
- catch (SQLException ex)
- {
- throw new DatabaseOperationException(ex);
- }
- }
-
- /*
- * {@inheritDoc}
- */
- public Database readModelFromDatabase(String name, String catalog, String schema, String[] tableTypes) throws DatabaseOperationException
- {
- Connection connection = borrowConnection();
-
- try
- {
- return readModelFromDatabase(connection, name, catalog, schema, tableTypes);
- }
- finally
- {
- returnConnection(connection);
- }
- }
-
- /*
- * {@inheritDoc}
- */
- public Database readModelFromDatabase(Connection connection, String name, String catalog, String schema, String[] tableTypes) throws DatabaseOperationException
- {
- try
- {
- JdbcModelReader reader = getModelReader();
- Database model = reader.getDatabase(connection, name, catalog, schema, tableTypes);
-
- postprocessModelFromDatabase(model);
- if ((model.getName() == null) || (model.getName().length() == 0))
- {
- model.setName(MODEL_DEFAULT_NAME);
- }
- return model;
- }
- catch (SQLException ex)
- {
- throw new DatabaseOperationException(ex);
- }
- }
-
- public Table readTableFromDatabase(Connection connection, String catalogName,
- String schemaName, String tablename) throws SQLException {
- return postprocessTableFromDatabase(_modelReader.readTable(connection, catalogName, schemaName, tablename));
- }
-
- /*
- * Allows the platform to postprocess the model just read from the database.
- *
- * @param model The model
- */
- protected void postprocessModelFromDatabase(Database model)
- {
- // Default values for CHAR/VARCHAR/LONGVARCHAR columns have quotation marks
- // around them which we'll remove now
- for (int tableIdx = 0; tableIdx < model.getTableCount(); tableIdx++)
- {
- postprocessTableFromDatabase(model.getTable(tableIdx));
- }
- }
-
- protected Table postprocessTableFromDatabase(Table table) {
- if (table != null) {
- for (int columnIdx = 0; columnIdx < table.getColumnCount(); columnIdx++) {
- Column column = table.getColumn(columnIdx);
-
- if (TypeMap.isTextType(column.getTypeCode())
- || TypeMap.isDateTimeType(column.getTypeCode())) {
- String defaultValue = column.getDefaultValue();
-
- if ((defaultValue != null) && (defaultValue.length() >= 2)
- && defaultValue.startsWith("'") && defaultValue.endsWith("'")) {
- defaultValue = defaultValue.substring(1, defaultValue.length() - 1);
- column.setDefaultValue(defaultValue);
- }
- }
- }
- }
- return table;
- }
-
- /*
- * This is the core method to set the parameter of a prepared statement to a given value.
- * The primary purpose of this method is to call the appropriate method on the statement,
- * and to give database-specific implementations the ability to change this behavior.
- *
- * @param statement The statement
- * @param sqlIndex The parameter index
- * @param typeCode The JDBC type code
- * @param value The value
- * @throws SQLException If an error occurred while setting the parameter value
- */
- protected void setStatementParameterValue(PreparedStatement statement, int sqlIndex, int typeCode, Object value) throws SQLException
- {
- if (value == null)
- {
- statement.setNull(sqlIndex, typeCode);
- }
- else if (value instanceof String)
- {
- statement.setString(sqlIndex, (String)value);
- }
- else if (value instanceof byte[])
- {
- statement.setBytes(sqlIndex, (byte[])value);
- }
- else if (value instanceof Boolean)
- {
- statement.setBoolean(sqlIndex, ((Boolean)value).booleanValue());
- }
- else if (value instanceof Byte)
- {
- statement.setByte(sqlIndex, ((Byte)value).byteValue());
- }
- else if (value instanceof Short)
- {
- statement.setShort(sqlIndex, ((Short)value).shortValue());
- }
- else if (value instanceof Integer)
- {
- statement.setInt(sqlIndex, ((Integer)value).intValue());
- }
- else if (value instanceof Long)
- {
- statement.setLong(sqlIndex, ((Long)value).longValue());
- }
- else if (value instanceof BigDecimal)
- {
- // setObject assumes a scale of 0, so we rather use the typed setter
- statement.setBigDecimal(sqlIndex, (BigDecimal)value);
- }
- else if (value instanceof Float)
- {
- statement.setFloat(sqlIndex, ((Float)value).floatValue());
- }
- else if (value instanceof Double)
- {
- statement.setDouble(sqlIndex, ((Double)value).doubleValue());
- }
- else
- {
- statement.setObject(sqlIndex, value, typeCode);
- }
- }
-
- /*
- * Helper method esp. for the {@link ModelBasedResultSetIterator} class that retrieves
- * the value for a column from the given result set. If a table was specified,
- * and it contains the column, then the jdbc type defined for the column is used for extracting
- * the value, otherwise the object directly retrieved from the result set is returned.null
in which case the
- * columnIdx
will be used instead
- * @param columnIdx The index of the column's value in the result set; is only used if
- * columnName
is null
- * @param jdbcType The jdbc type to extract
- * @return The value
- * @throws SQLException If an error occurred while accessing the result set
- */
- protected Object extractColumnValue(ResultSet resultSet, String columnName, int columnIdx, int jdbcType) throws SQLException
- {
- boolean useIdx = (columnName == null);
- Object value;
-
- switch (jdbcType)
- {
- case Types.CHAR:
- case Types.VARCHAR:
- case Types.LONGVARCHAR:
- value = useIdx ? resultSet.getString(columnIdx) : resultSet.getString(columnName);
- break;
- case Types.NUMERIC:
- case Types.DECIMAL:
- value = useIdx ? resultSet.getBigDecimal(columnIdx) : resultSet.getBigDecimal(columnName);
- break;
- case Types.BIT:
- value = new Boolean(useIdx ? resultSet.getBoolean(columnIdx) : resultSet.getBoolean(columnName));
- break;
- case Types.TINYINT:
- case Types.SMALLINT:
- case Types.INTEGER:
- value = new Integer(useIdx ? resultSet.getInt(columnIdx) : resultSet.getInt(columnName));
- break;
- case Types.BIGINT:
- value = new Long(useIdx ? resultSet.getLong(columnIdx) : resultSet.getLong(columnName));
- break;
- case Types.REAL:
- value = new Float(useIdx ? resultSet.getFloat(columnIdx) : resultSet.getFloat(columnName));
- break;
- case Types.FLOAT:
- case Types.DOUBLE:
- value = new Double(useIdx ? resultSet.getDouble(columnIdx) : resultSet.getDouble(columnName));
- break;
- case Types.BINARY:
- case Types.VARBINARY:
- case Types.LONGVARBINARY:
- value = useIdx ? resultSet.getBytes(columnIdx) : resultSet.getBytes(columnName);
- break;
- case Types.DATE:
- value = useIdx ? resultSet.getDate(columnIdx) : resultSet.getDate(columnName);
- break;
- case Types.TIME:
- value = useIdx ? resultSet.getTime(columnIdx) : resultSet.getTime(columnName);
- break;
- case Types.TIMESTAMP:
- value = useIdx ? resultSet.getTimestamp(columnIdx) : resultSet.getTimestamp(columnName);
- break;
- case Types.CLOB:
- Clob clob = useIdx ? resultSet.getClob(columnIdx) : resultSet.getClob(columnName);
-
- if (clob == null)
- {
- value = null;
- }
- else
- {
- long length = clob.length();
-
- if (length > Integer.MAX_VALUE)
- {
- value = clob;
- }
- else if (length == 0)
- {
- // the javadoc is not clear about whether Clob.getSubString
- // can be used with a substring length of 0
- // thus we do the safe thing and handle it ourselves
- value = "";
- }
- else
- {
- value = clob.getSubString(1l, (int)length);
- }
- }
- break;
- case Types.BLOB:
- Blob blob = useIdx ? resultSet.getBlob(columnIdx) : resultSet.getBlob(columnName);
-
- if (blob == null)
- {
- value = null;
- }
- else
- {
- long length = blob.length();
-
- if (length > Integer.MAX_VALUE)
- {
- value = blob;
- }
- else if (length == 0)
- {
- // the javadoc is not clear about whether Blob.getBytes
- // can be used with for 0 bytes to be copied
- // thus we do the safe thing and handle it ourselves
- value = new byte[0];
- }
- else
- {
- value = blob.getBytes(1l, (int)length);
- }
- }
- break;
- case Types.ARRAY:
- value = useIdx ? resultSet.getArray(columnIdx) : resultSet.getArray(columnName);
- break;
- case Types.REF:
- value = useIdx ? resultSet.getRef(columnIdx) : resultSet.getRef(columnName);
- break;
- default:
- // special handling for Java 1.4/JDBC 3 types
- if (Jdbc3Utils.supportsJava14JdbcTypes() &&
- (jdbcType == Jdbc3Utils.determineBooleanTypeCode()))
- {
- value = new Boolean(useIdx ? resultSet.getBoolean(columnIdx) : resultSet.getBoolean(columnName));
- }
- else
- {
- value = useIdx ? resultSet.getObject(columnIdx) : resultSet.getObject(columnName);
- }
- break;
- }
- return resultSet.wasNull() ? null : value;
- }
-
-}
diff --git a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/platform/SqlBuilder.java b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/platform/SqlBuilder.java
deleted file mode 100644
index eb2469b052..0000000000
--- a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/platform/SqlBuilder.java
+++ /dev/null
@@ -1,2783 +0,0 @@
-package org.jumpmind.symmetric.db.ddl.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.Writer;
-import java.rmi.server.UID;
-import java.sql.Types;
-import java.text.DateFormat;
-import java.text.NumberFormat;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Locale;
-import java.util.Map;
-import java.util.Set;
-
-import org.apache.commons.collections.Closure;
-import org.apache.commons.collections.CollectionUtils;
-import org.apache.commons.collections.Predicate;
-import org.apache.commons.collections.map.ListOrderedMap;
-import org.apache.commons.lang.StringUtils;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.jumpmind.symmetric.db.ddl.DdlUtilsException;
-import org.jumpmind.symmetric.db.ddl.Platform;
-import org.jumpmind.symmetric.db.ddl.PlatformInfo;
-import org.jumpmind.symmetric.db.ddl.alteration.AddColumnChange;
-import org.jumpmind.symmetric.db.ddl.alteration.AddForeignKeyChange;
-import org.jumpmind.symmetric.db.ddl.alteration.AddIndexChange;
-import org.jumpmind.symmetric.db.ddl.alteration.AddPrimaryKeyChange;
-import org.jumpmind.symmetric.db.ddl.alteration.AddTableChange;
-import org.jumpmind.symmetric.db.ddl.alteration.ColumnAutoIncrementChange;
-import org.jumpmind.symmetric.db.ddl.alteration.ColumnDataTypeChange;
-import org.jumpmind.symmetric.db.ddl.alteration.ColumnDefaultValueChange;
-import org.jumpmind.symmetric.db.ddl.alteration.ColumnRequiredChange;
-import org.jumpmind.symmetric.db.ddl.alteration.ColumnSizeChange;
-import org.jumpmind.symmetric.db.ddl.alteration.ModelChange;
-import org.jumpmind.symmetric.db.ddl.alteration.ModelComparator;
-import org.jumpmind.symmetric.db.ddl.alteration.PrimaryKeyChange;
-import org.jumpmind.symmetric.db.ddl.alteration.RemoveColumnChange;
-import org.jumpmind.symmetric.db.ddl.alteration.RemoveForeignKeyChange;
-import org.jumpmind.symmetric.db.ddl.alteration.RemoveIndexChange;
-import org.jumpmind.symmetric.db.ddl.alteration.RemovePrimaryKeyChange;
-import org.jumpmind.symmetric.db.ddl.alteration.RemoveTableChange;
-import org.jumpmind.symmetric.db.ddl.alteration.TableChange;
-import org.jumpmind.symmetric.db.ddl.model.Column;
-import org.jumpmind.symmetric.db.ddl.model.Database;
-import org.jumpmind.symmetric.db.ddl.model.ForeignKey;
-import org.jumpmind.symmetric.db.ddl.model.Index;
-import org.jumpmind.symmetric.db.ddl.model.IndexColumn;
-import org.jumpmind.symmetric.db.ddl.model.ModelException;
-import org.jumpmind.symmetric.db.ddl.model.Reference;
-import org.jumpmind.symmetric.db.ddl.model.Table;
-import org.jumpmind.symmetric.db.ddl.model.TypeMap;
-import org.jumpmind.symmetric.db.ddl.util.CallbackClosure;
-import org.jumpmind.symmetric.db.ddl.util.MultiInstanceofPredicate;
-
-/**
- * This class is a collection of Strategy methods for creating the DDL required to create and drop
- * databases and tables.
- *
- * It is hoped that just a single implementation of this class, for each database should make creating DDL
- * for each physical database fairly straightforward.
- *
- * An implementation of this class can always delegate down to some templating technology such as Velocity if
- * it requires. Though often that can be quite complex when attempting to reuse code across many databases.
- * Hopefully only a small amount code needs to be changed on a per database basis.
- *
- * @version $Revision: 518498 $
- */
-public abstract class SqlBuilder
-{
- /** The line separator for in between sql commands. */
- private static final String LINE_SEPARATOR = System.getProperty("line.separator", "\n");
- /** The placeholder for the size value in the native type spec. */
- protected static final String SIZE_PLACEHOLDER = "{0}";
-
- /** The Log to which logging calls will be made. */
- protected final Log _log = LogFactory.getLog(SqlBuilder.class);
-
- /** The platform that this builder belongs to. */
- private Platform _platform;
- /** The current Writer used to output the SQL to. */
- private Writer _writer;
- /** The indentation used to indent commands. */
- private String _indent = " ";
- /** An optional locale specification for number and date formatting. */
- private String _valueLocale;
- /** The date formatter. */
- private DateFormat _valueDateFormat;
- /** The date time formatter. */
- private DateFormat _valueTimeFormat;
- /** The number formatter. */
- private NumberFormat _valueNumberFormat;
- /** Helper object for dealing with default values. */
- private DefaultValueHelper _defaultValueHelper = new DefaultValueHelper();
- /** The character sequences that need escaping. */
- private Map _charSequencesToEscape = new ListOrderedMap();
-
- //
- // Configuration
- //
-
- /**
- * Creates a new sql builder.
- *
- * @param platform The plaftform this builder belongs to
- */
- public SqlBuilder(Platform platform)
- {
- _platform = platform;
- }
-
- /**
- * Returns the platform object.
- *
- * @return The platform
- */
- public Platform getPlatform()
- {
- return _platform;
- }
-
- /**
- * Returns the platform info object.
- *
- * @return The info object
- */
- public PlatformInfo getPlatformInfo()
- {
- return _platform.getPlatformInfo();
- }
-
- /**
- * Returns the writer that the DDL is printed to.
- *
- * @return The writer
- */
- public Writer getWriter()
- {
- return _writer;
- }
-
- /**
- * Sets the writer for printing the DDL to.
- *
- * @param writer The writer
- */
- public void setWriter(Writer writer)
- {
- _writer = writer;
- }
-
- /**
- * Returns the default value helper.
- *
- * @return The default value helper
- */
- public DefaultValueHelper getDefaultValueHelper()
- {
- return _defaultValueHelper;
- }
-
- /**
- * Returns the string used to indent the SQL.
- *
- * @return The indentation string
- */
- public String getIndent()
- {
- return _indent;
- }
-
- /**
- * Sets the string used to indent the SQL.
- *
- * @param indent The indentation string
- */
- public void setIndent(String indent)
- {
- _indent = indent;
- }
-
- /**
- * Returns the locale that is used for number and date formatting
- * (when printing default values and in generates insert/update/delete
- * statements).
- *
- * @return The locale or null
if default formatting is used
- */
- public String getValueLocale()
- {
- return _valueLocale;
- }
-
- /**
- * Sets the locale that is used for number and date formatting
- * (when printing default values and in generates insert/update/delete
- * statements).
- *
- * @param localeStr The new locale or null
if default formatting
- * should be used; Format is "language[_country[_variant]]"
- */
- public void setValueLocale(String localeStr)
- {
- if (localeStr != null)
- {
- int sepPos = localeStr.indexOf('_');
- String language = null;
- String country = null;
- String variant = null;
-
- if (sepPos > 0)
- {
- language = localeStr.substring(0, sepPos);
- country = localeStr.substring(sepPos + 1);
- sepPos = country.indexOf('_');
- if (sepPos > 0)
- {
- variant = country.substring(sepPos + 1);
- country = country.substring(0, sepPos);
- }
- }
- else
- {
- language = localeStr;
- }
- if (language != null)
- {
- Locale locale = null;
-
- if (variant != null)
- {
- locale = new Locale(language, country, variant);
- }
- else if (country != null)
- {
- locale = new Locale(language, country);
- }
- else
- {
- locale = new Locale(language);
- }
-
- _valueLocale = localeStr;
- setValueDateFormat(DateFormat.getDateInstance(DateFormat.SHORT, locale));
- setValueTimeFormat(DateFormat.getTimeInstance(DateFormat.SHORT, locale));
- setValueNumberFormat(NumberFormat.getNumberInstance(locale));
- return;
- }
- }
- _valueLocale = null;
- setValueDateFormat(null);
- setValueTimeFormat(null);
- setValueNumberFormat(null);
- }
-
- /**
- * Returns the format object for formatting dates in the specified locale.
- *
- * @return The date format object or null if no locale is set
- */
- protected DateFormat getValueDateFormat()
- {
- return _valueDateFormat;
- }
-
- /**
- * Sets the format object for formatting dates in the specified locale.
- *
- * @param format The date format object
- */
- protected void setValueDateFormat(DateFormat format)
- {
- _valueDateFormat = format;
- }
-
- /**
- * Returns the format object for formatting times in the specified locale.
- *
- * @return The time format object or null if no locale is set
- */
- protected DateFormat getValueTimeFormat()
- {
- return _valueTimeFormat;
- }
-
- /**
- * Sets the date format object for formatting times in the specified locale.
- *
- * @param format The time format object
- */
- protected void setValueTimeFormat(DateFormat format)
- {
- _valueTimeFormat = format;
- }
-
- /**
- * Returns the format object for formatting numbers in the specified locale.
- *
- * @return The number format object or null if no locale is set
- */
- protected NumberFormat getValueNumberFormat()
- {
- return _valueNumberFormat;
- }
-
- /**
- * Returns a new date format object for formatting numbers in the specified locale.
- * Platforms can override this if necessary.
- *
- * @param format The number format object
- */
- protected void setValueNumberFormat(NumberFormat format)
- {
- _valueNumberFormat = format;
- }
-
- /**
- * Adds a char sequence that needs escaping, and its escaped version.
- *
- * @param charSequence The char sequence
- * @param escapedVersion The escaped version
- */
- protected void addEscapedCharSequence(String charSequence, String escapedVersion)
- {
- _charSequencesToEscape.put(charSequence, escapedVersion);
- }
-
- /**
- * Returns the maximum number of characters that a table name can have.
- * This method is intended to give platform specific builder implementations
- * more control over the maximum length.
- *
- * @return The number of characters, or -1 if not limited
- */
- public int getMaxTableNameLength()
- {
- return getPlatformInfo().getMaxTableNameLength();
- }
-
- /**
- * Returns the maximum number of characters that a column name can have.
- * This method is intended to give platform specific builder implementations
- * more control over the maximum length.
- *
- * @return The number of characters, or -1 if not limited
- */
- public int getMaxColumnNameLength()
- {
- return getPlatformInfo().getMaxColumnNameLength();
- }
-
- /**
- * Returns the maximum number of characters that a constraint name can have.
- * This method is intended to give platform specific builder implementations
- * more control over the maximum length.
- *
- * @return The number of characters, or -1 if not limited
- */
- public int getMaxConstraintNameLength()
- {
- return getPlatformInfo().getMaxConstraintNameLength();
- }
-
- /**
- * Returns the maximum number of characters that a foreign key name can have.
- * This method is intended to give platform specific builder implementations
- * more control over the maximum length.
- *
- * @return The number of characters, or -1 if not limited
- */
- public int getMaxForeignKeyNameLength()
- {
- return getPlatformInfo().getMaxForeignKeyNameLength();
- }
-
- //
- // public interface
- //
-
- /**
- * Outputs the DDL required to drop and (re)create all tables in the database model.
- *
- * @param database The database model
- */
- public void createTables(Database database) throws IOException
- {
- createTables(database, null, true);
- }
-
- /**
- * Outputs the DDL required to drop (if requested) and (re)create all tables in the database model.
- *
- * @param database The database
- * @param dropTables Whether to drop tables before creating them
- */
- public void createTables(Database database, boolean dropTables) throws IOException
- {
- createTables(database, null, dropTables);
- }
-
- /**
- * Outputs the DDL required to drop (if requested) and (re)create all tables in the database model.
- *
- * @param database The database
- * @param params The parameters used in the creation
- * @param dropTables Whether to drop tables before creating them
- */
- public void createTables(Database database, CreationParameters params, boolean dropTables) throws IOException
- {
- if (dropTables)
- {
- dropTables(database);
- }
-
- for (int idx = 0; idx < database.getTableCount(); idx++)
- {
- Table table = database.getTable(idx);
-
- writeTableComment(table);
- createTable(database,
- table,
- params == null ? null : params.getParametersFor(table));
- }
-
- // we're writing the external foreignkeys last to ensure that all referenced tables are already defined
- createExternalForeignKeys(database);
- }
-
- /**
- * Generates the DDL to modify an existing database so the schema matches
- * the specified database schema by using drops, modifications and additions.
- * Database-specific implementations can change aspect of this algorithm by
- * redefining the individual methods that compromise it.
- *
- * @param currentModel The current database schema
- * @param desiredModel The desired database schema
- * @param params The parameters used in the creation of new tables. Note that for existing
- * tables, the parameters won't be applied
- */
- public void alterDatabase(Database currentModel, Database desiredModel, CreationParameters params) throws IOException
- {
- ModelComparator comparator = new ModelComparator(getPlatformInfo(),
- getPlatform().isDelimitedIdentifierModeOn());
- List changes = comparator.compare(currentModel, desiredModel);
-
- processChanges(currentModel, desiredModel, changes, params);
- }
-
- public boolean isAlterDatabase(Database currentModel, Database desiredModel, CreationParameters params) throws IOException
- {
- ModelComparator comparator = new ModelComparator(getPlatformInfo(),
- getPlatform().isDelimitedIdentifierModeOn());
- List changes = comparator.compare(currentModel, desiredModel);
-
- return changes.size() > 0;
- }
-
- /**
- * Calls the given closure for all changes that are of one of the given types, and
- * then removes them from the changes collection.
- *
- * @param changes The changes
- * @param changeTypes The types to search for
- * @param closure The closure to invoke
- */
- protected void applyForSelectedChanges(Collection changes, Class[] changeTypes, final Closure closure)
- {
- final Predicate predicate = new MultiInstanceofPredicate(changeTypes);
-
- // basically we filter the changes for all objects where the above predicate
- // returns true, and for these filtered objects we invoke the given closure
- CollectionUtils.filter(changes,
- new Predicate()
- {
- public boolean evaluate(Object obj)
- {
- if (predicate.evaluate(obj))
- {
- closure.execute(obj);
- return false;
- }
- else
- {
- return true;
- }
- }
- });
- }
-
- /**
- * Processes the changes. The default argument performs several passes:
- * ALTER TABLE ADD CONSTRAINT
statement.
- *
- * @param currentModel The current database schema
- * @param desiredModel The desired database schema
- * @param sourceTable The original table
- * @param targetTable The desired table
- * @param parameters The creation parameters for the table
- * @param changes The change objects for the target table
- */
- protected void processTableStructureChanges(Database currentModel,
- Database desiredModel,
- Table sourceTable,
- Table targetTable,
- Map parameters,
- List changes) throws IOException
- {
- if (changes.size() == 1)
- {
- TableChange change = (TableChange)changes.get(0);
-
- if (change instanceof AddPrimaryKeyChange)
- {
- processChange(currentModel, desiredModel, (AddPrimaryKeyChange)change);
- changes.clear();
- }
- }
- }
-
- /**
- * Creates a temporary table object that corresponds to the given table.
- * Database-specific implementations may redefine this method if e.g. the
- * database directly supports temporary tables. The default implementation
- * simply appends an underscore to the table name and uses that as the
- * table name.
- *
- * @param targetModel The target database
- * @param targetTable The target table
- * @return The temporary table
- */
- protected Table getTemporaryTableFor(Database targetModel, Table targetTable) throws IOException
- {
- return getTemporaryTableFor(targetModel, targetTable, "_");
- }
-
- public Table getBackupTableFor(Database model, Table sourceTable) throws IOException
- {
- return getTemporaryTableFor(model, sourceTable, "x");
- }
-
- public Table createBackupTableFor(Database model, Table sourceTable) throws IOException
- {
- Table backupTable = getBackupTableFor(model, sourceTable);
- writeTableCreationStmt(model, backupTable, null);
- printEndOfStatement();
- writeCopyDataStatement(sourceTable, backupTable);
- return backupTable;
- }
-
- public void restoreTableFromBackup(Table backupTable, Table targetTable, ListOrderedMap columnMap) throws IOException
- {
- print("DELETE FROM ");
- printIdentifier(getTableName(targetTable));
- printEndOfStatement();
- writeCopyDataStatement(backupTable, targetTable, columnMap);
- }
-
- protected Table getTemporaryTableFor(Database targetModel, Table targetTable, String suffix) throws IOException
- {
- Table table = new Table();
-
- table.setCatalog(targetTable.getCatalog());
- table.setSchema(targetTable.getSchema());
- table.setName(targetTable.getName() + suffix);
- table.setType(targetTable.getType());
- for (int idx = 0; idx < targetTable.getColumnCount(); idx++)
- {
- try
- {
- table.addColumn((Column)targetTable.getColumn(idx).clone());
- }
- catch (CloneNotSupportedException ex)
- {
- throw new DdlUtilsException(ex);
- }
- }
-
- return table;
- }
-
- /**
- * Outputs the DDL to create the given temporary table. Per default this is simply
- * a call to {@link #createTable(Database, Table, Map)}.
- *
- * @param database The database model
- * @param table The table
- * @param parameters Additional platform-specific parameters for the table creation
- */
- protected void createTemporaryTable(Database database, Table table, Map parameters) throws IOException
- {
- createTable(database, table, parameters);
- }
-
- /**
- * Outputs the DDL to drop the given temporary table. Per default this is simply
- * a call to {@link #dropTable(Table)}.
- *
- * @param database The database model
- * @param table The table
- */
- protected void dropTemporaryTable(Database database, Table table) throws IOException
- {
- dropTable(table);
- }
-
- /**
- * Creates the target table object that differs from the given target table only in the
- * indices. More specifically, only those indices are used that have not changed.
- *
- * @param targetModel The target database
- * @param sourceTable The source table
- * @param targetTable The target table
- * @return The table
- */
- protected Table getRealTargetTableFor(Database targetModel, Table sourceTable, Table targetTable) throws IOException
- {
- Table table = new Table();
-
- table.setCatalog(targetTable.getCatalog());
- table.setSchema(targetTable.getSchema());
- table.setName(targetTable.getName());
- table.setType(targetTable.getType());
- for (int idx = 0; idx < targetTable.getColumnCount(); idx++)
- {
- try
- {
- table.addColumn((Column)targetTable.getColumn(idx).clone());
- }
- catch (CloneNotSupportedException ex)
- {
- throw new DdlUtilsException(ex);
- }
- }
-
- boolean caseSensitive = getPlatform().isDelimitedIdentifierModeOn();
-
- for (int idx = 0; idx < targetTable.getIndexCount(); idx++)
- {
- Index targetIndex = targetTable.getIndex(idx);
- Index sourceIndex = sourceTable.findIndex(targetIndex.getName(), caseSensitive);
-
- if (sourceIndex != null)
- {
- if ((caseSensitive && sourceIndex.equals(targetIndex)) ||
- (!caseSensitive && sourceIndex.equalsIgnoreCase(targetIndex)))
- {
- table.addIndex(targetIndex);
- }
- }
- }
-
- return table;
- }
-
- /**
- * Writes a statement that copies the data from the source to the target table. Note
- * that this copies only those columns that are in both tables.
- * Database-specific implementations might redefine this method though they usually
- * it suffices to redefine the {@link #writeCastExpression(Column, Column)} method.
- *
- * @param sourceTable The source table
- * @param targetTable The target table
- */
- public void writeCopyDataStatement(Table sourceTable, Table targetTable) throws IOException
- {
- ListOrderedMap columnMap = getCopyDataColumnMapping(sourceTable, targetTable);
- writeCopyDataStatement(sourceTable, targetTable, columnMap);
- }
-
- public void writeCopyDataStatement(Table sourceTable, Table targetTable, ListOrderedMap columnMap) throws IOException
- {
- print("INSERT INTO ");
- printIdentifier(getTableName(targetTable));
- print(" (");
- for (Iterator columnIt = columnMap.values().iterator(); columnIt.hasNext();)
- {
- printIdentifier(getColumnName((Column)columnIt.next()));
- if (columnIt.hasNext())
- {
- print(",");
- }
- }
- print(") SELECT ");
- for (Iterator columnsIt = columnMap.entrySet().iterator(); columnsIt.hasNext();)
- {
- Map.Entry entry = (Map.Entry)columnsIt.next();
-
- writeCastExpression((Column)entry.getKey(),
- (Column)entry.getValue());
- if (columnsIt.hasNext())
- {
- print(",");
- }
- }
- print(" FROM ");
- printIdentifier(getTableName(sourceTable));
- printEndOfStatement();
- }
-
- public ListOrderedMap getCopyDataColumnMapping(Table sourceTable, Table targetTable)
- {
- ListOrderedMap columns = new ListOrderedMap();
-
- for (int idx = 0; idx < sourceTable.getColumnCount(); idx++)
- {
- Column sourceColumn = sourceTable.getColumn(idx);
- Column targetColumn = targetTable.findColumn(sourceColumn.getName(),
- getPlatform().isDelimitedIdentifierModeOn());
-
-
- if (targetColumn != null)
- {
- columns.put(sourceColumn, targetColumn);
- }
- }
- return columns;
- }
-
- public ListOrderedMap getCopyDataColumnOrderedMapping(Table sourceTable, Table targetTable)
- {
- ListOrderedMap columns = new ListOrderedMap();
-
- for (int idx = 0; idx < sourceTable.getColumnCount(); idx++)
- {
- columns.put(sourceTable.getColumn(idx), targetTable.getColumn(idx));
- }
- return columns;
- }
-
- /**
- * Writes a cast expression that converts the value of the source column to the data type
- * of the target column. Per default, simply the name of the source column is written
- * thereby assuming that any casts happen implicitly.
- *
- * @param sourceColumn The source column
- * @param targetColumn The target column
- */
- protected void writeCastExpression(Column sourceColumn, Column targetColumn) throws IOException
- {
- printIdentifier(getColumnName(sourceColumn));
- }
-
- /**
- * Processes the addition of a primary key to a table.
- *
- * @param currentModel The current database schema
- * @param desiredModel The desired database schema
- * @param change The change object
- */
- protected void processChange(Database currentModel,
- Database desiredModel,
- AddPrimaryKeyChange change) throws IOException
- {
- writeExternalPrimaryKeysCreateStmt(change.getChangedTable(), change.getPrimaryKeyColumns());
- change.apply(currentModel, getPlatform().isDelimitedIdentifierModeOn());
- }
-
- /**
- * Searches in the given table for a corresponding foreign key. If the given key
- * has no name, then a foreign key to the same table with the same columns in the
- * same order is searched. If the given key has a name, then the a corresponding
- * key also needs to have the same name, or no name at all, but not a different one.
- *
- * @param table The table to search in
- * @param fk The original foreign key
- * @return The corresponding foreign key if found
- */
- protected ForeignKey findCorrespondingForeignKey(Table table, ForeignKey fk)
- {
- boolean caseMatters = getPlatform().isDelimitedIdentifierModeOn();
- boolean checkFkName = (fk.getName() != null) && (fk.getName().length() > 0);
- Reference[] refs = fk.getReferences();
- ArrayList curRefs = new ArrayList();
-
- for (int fkIdx = 0; fkIdx < table.getForeignKeyCount(); fkIdx++)
- {
- ForeignKey curFk = table.getForeignKey(fkIdx);
- boolean checkCurFkName = checkFkName &&
- (curFk.getName() != null) && (curFk.getName().length() > 0);
-
- if ((!checkCurFkName || areEqual(fk.getName(), curFk.getName(), caseMatters)) &&
- areEqual(fk.getForeignTableName(), curFk.getForeignTableName(), caseMatters))
- {
- curRefs.clear();
- CollectionUtils.addAll(curRefs, curFk.getReferences());
-
- // the order is not fixed, so we have to take this long way
- if (curRefs.size() == refs.length)
- {
- for (int refIdx = 0; refIdx < refs.length; refIdx++)
- {
- boolean found = false;
-
- for (int curRefIdx = 0; !found && (curRefIdx < curRefs.size()); curRefIdx++)
- {
- Reference curRef = (Reference)curRefs.get(curRefIdx);
-
- if ((caseMatters && refs[refIdx].equals(curRef)) ||
- (!caseMatters && refs[refIdx].equalsIgnoreCase(curRef)))
- {
- curRefs.remove(curRefIdx);
- found = true;
- }
- }
- }
- if (curRefs.isEmpty())
- {
- return curFk;
- }
- }
- }
- }
- return null;
- }
-
- /**
- * Compares the two strings.
- *
- * @param string1 The first string
- * @param string2 The second string
- * @param caseMatters Whether case matters in the comparison
- * @return true
if the string are equal
- */
- protected boolean areEqual(String string1, String string2, boolean caseMatters)
- {
- return (caseMatters && string1.equals(string2)) ||
- (!caseMatters && string1.equalsIgnoreCase(string2));
- }
-
- /**
- * Outputs the DDL to create the table along with any non-external constraints as well
- * as with external primary keys and indices (but not foreign keys).
- *
- * @param database The database model
- * @param table The table
- */
- public void createTable(Database database, Table table) throws IOException
- {
- createTable(database, table, null);
- }
-
- /**
- * Outputs the DDL to create the table along with any non-external constraints as well
- * as with external primary keys and indices (but not foreign keys).
- *
- * @param database The database model
- * @param table The table
- * @param parameters Additional platform-specific parameters for the table creation
- */
- public void createTable(Database database, Table table, Map parameters) throws IOException
- {
- writeTableCreationStmt(database, table, parameters);
- writeTableCreationStmtEnding(table, parameters);
-
- if (!getPlatformInfo().isPrimaryKeyEmbedded())
- {
- writeExternalPrimaryKeysCreateStmt(table, table.getPrimaryKeyColumns());
- }
- if (!getPlatformInfo().isIndicesEmbedded())
- {
- writeExternalIndicesCreateStmt(table);
- }
- }
-
- /**
- * Creates the external foreignkey creation statements for all tables in the database.
- *
- * @param database The database
- */
- public void createExternalForeignKeys(Database database) throws IOException
- {
- for (int idx = 0; idx < database.getTableCount(); idx++)
- {
- createExternalForeignKeys(database, database.getTable(idx));
- }
- }
-
- /**
- * Creates external foreignkey creation statements if necessary.
- *
- * @param database The database model
- * @param table The table
- */
- public void createExternalForeignKeys(Database database, Table table) throws IOException
- {
- if (!getPlatformInfo().isForeignKeysEmbedded())
- {
- for (int idx = 0; idx < table.getForeignKeyCount(); idx++)
- {
- writeExternalForeignKeyCreateStmt(database, table, table.getForeignKey(idx));
- }
- }
- }
-
- /**
- * Outputs the DDL required to drop the database.
- *
- * @param database The database
- */
- public void dropTables(Database database) throws IOException
- {
- // we're dropping the external foreignkeys first
- for (int idx = database.getTableCount() - 1; idx >= 0; idx--)
- {
- Table table = database.getTable(idx);
-
- if ((table.getName() != null) &&
- (table.getName().length() > 0))
- {
- dropExternalForeignKeys(table);
- }
- }
-
- // Next we drop the tables in reverse order to avoid referencial problems
- // TODO: It might be more useful to either (or both)
- // * determine an order in which the tables can be dropped safely (via the foreignkeys)
- // * alter the tables first to drop the internal foreignkeys
- for (int idx = database.getTableCount() - 1; idx >= 0; idx--)
- {
- Table table = database.getTable(idx);
-
- if ((table.getName() != null) &&
- (table.getName().length() > 0))
- {
- writeTableComment(table);
- dropTable(table);
- }
- }
- }
-
- /**
- * Outputs the DDL required to drop the given table. This method also
- * drops foreign keys to the table.
- *
- * @param database The database
- * @param table The table
- */
- public void dropTable(Database database, Table table) throws IOException
- {
- // we're dropping the foreignkeys to the table first
- for (int idx = database.getTableCount() - 1; idx >= 0; idx--)
- {
- Table otherTable = database.getTable(idx);
- ForeignKey[] fks = otherTable.getForeignKeys();
-
- for (int fkIdx = 0; (fks != null) && (fkIdx < fks.length); fkIdx++)
- {
- if (fks[fkIdx].getForeignTable().equals(table))
- {
- writeExternalForeignKeyDropStmt(otherTable, fks[fkIdx]);
- }
- }
- }
- // and the foreign keys from the table
- dropExternalForeignKeys(table);
-
- writeTableComment(table);
- dropTable(table);
- }
-
- /**
- * Outputs the DDL to drop the table. Note that this method does not drop
- * foreign keys to this table. Use {@link #dropTable(Database, Table)}
- * if you want that.
- *
- * @param table The table to drop
- */
- public void dropTable(Table table) throws IOException
- {
- print("DROP TABLE ");
- printIdentifier(getTableName(table));
- printEndOfStatement();
- }
-
- /**
- * Creates external foreignkey drop statements.
- *
- * @param table The table
- */
- public void dropExternalForeignKeys(Table table) throws IOException
- {
- if (!getPlatformInfo().isForeignKeysEmbedded())
- {
- for (int idx = 0; idx < table.getForeignKeyCount(); idx++)
- {
- writeExternalForeignKeyDropStmt(table, table.getForeignKey(idx));
- }
- }
- }
-
- /**
- * Creates the SQL for inserting an object into the specified table.
- * If values are given then a concrete insert statement is created, otherwise an
- * insert statement usable in a prepared statement is build.
- *
- * @param table The table
- * @param columnValues The columns values indexed by the column names
- * @param genPlaceholders Whether to generate value placeholders for a
- * prepared statement
- * @return The insertion sql
- */
- public String getInsertSql(Table table, Map columnValues, boolean genPlaceholders)
- {
- StringBuffer buffer = new StringBuffer("INSERT INTO ");
- boolean addComma = false;
-
- buffer.append(getDelimitedIdentifier(getTableName(table)));
- buffer.append(" (");
-
- for (int idx = 0; idx < table.getColumnCount(); idx++)
- {
- Column column = table.getColumn(idx);
-
- if (columnValues.containsKey(column.getName()))
- {
- if (addComma)
- {
- buffer.append(", ");
- }
- buffer.append(getDelimitedIdentifier(column.getName()));
- addComma = true;
- }
- }
- buffer.append(") VALUES (");
- if (genPlaceholders)
- {
- addComma = false;
- for (int idx = 0; idx < columnValues.size(); idx++)
- {
- if (addComma)
- {
- buffer.append(", ");
- }
- buffer.append("?");
- addComma = true;
- }
- }
- else
- {
- addComma = false;
- for (int idx = 0; idx < table.getColumnCount(); idx++)
- {
- Column column = table.getColumn(idx);
-
- if (columnValues.containsKey(column.getName()))
- {
- if (addComma)
- {
- buffer.append(", ");
- }
- buffer.append(getValueAsString(column, columnValues.get(column.getName())));
- addComma = true;
- }
- }
- }
- buffer.append(")");
- return buffer.toString();
- }
-
- /**
- * Creates the SQL for updating an object in the specified table.
- * If values are given then a concrete update statement is created, otherwise an
- * update statement usable in a prepared statement is build.
- *
- * @param table The table
- * @param columnValues Contains the values for the columns to update, and should also
- * contain the primary key values to identify the object to update
- * in case genPlaceholders
is false
- * @param genPlaceholders Whether to generate value placeholders for a
- * prepared statement (both for the pk values and the object values)
- * @return The update sql
- */
- public String getUpdateSql(Table table, Map columnValues, boolean genPlaceholders)
- {
- StringBuffer buffer = new StringBuffer("UPDATE ");
- boolean addSep = false;
-
- buffer.append(getDelimitedIdentifier(getTableName(table)));
- buffer.append(" SET ");
-
- for (int idx = 0; idx < table.getColumnCount(); idx++)
- {
- Column column = table.getColumn(idx);
-
- if (!column.isPrimaryKey() && columnValues.containsKey(column.getName()))
- {
- if (addSep)
- {
- buffer.append(", ");
- }
- buffer.append(getDelimitedIdentifier(column.getName()));
- buffer.append(" = ");
- if (genPlaceholders)
- {
- buffer.append("?");
- }
- else
- {
- buffer.append(getValueAsString(column, columnValues.get(column.getName())));
- }
- addSep = true;
- }
- }
- buffer.append(" WHERE ");
- addSep = false;
- for (int idx = 0; idx < table.getColumnCount(); idx++)
- {
- Column column = table.getColumn(idx);
-
- if (column.isPrimaryKey() && columnValues.containsKey(column.getName()))
- {
- if (addSep)
- {
- buffer.append(" AND ");
- }
- buffer.append(getDelimitedIdentifier(column.getName()));
- buffer.append(" = ");
- if (genPlaceholders)
- {
- buffer.append("?");
- }
- else
- {
- buffer.append(getValueAsString(column, columnValues.get(column.getName())));
- }
- addSep = true;
- }
- }
- return buffer.toString();
- }
-
- /**
- * Creates the SQL for deleting an object from the specified table.
- * If values are given then a concrete delete statement is created, otherwise an
- * delete statement usable in a prepared statement is build.
- *
- * @param table The table
- * @param pkValues The primary key values indexed by the column names, can be empty
- * @param genPlaceholders Whether to generate value placeholders for a
- * prepared statement
- * @return The delete sql
- */
- public String getDeleteSql(Table table, Map pkValues, boolean genPlaceholders)
- {
- StringBuffer buffer = new StringBuffer("DELETE FROM ");
- boolean addSep = false;
-
- buffer.append(getDelimitedIdentifier(getTableName(table)));
- if ((pkValues != null) && !pkValues.isEmpty())
- {
- buffer.append(" WHERE ");
- for (Iterator it = pkValues.entrySet().iterator(); it.hasNext();)
- {
- Map.Entry entry = (Map.Entry)it.next();
- Column column = table.findColumn((String)entry.getKey());
-
- if (addSep)
- {
- buffer.append(" AND ");
- }
- buffer.append(getDelimitedIdentifier(entry.getKey().toString()));
- buffer.append(" = ");
- if (genPlaceholders)
- {
- buffer.append("?");
- }
- else
- {
- buffer.append(column == null ? entry.getValue() : getValueAsString(column, entry.getValue()));
- }
- addSep = true;
- }
- }
- return buffer.toString();
- }
-
- /**
- * Generates the string representation of the given value.
- *
- * @param column The column
- * @param value The value
- * @return The string representation
- */
- protected String getValueAsString(Column column, Object value)
- {
- if (value == null)
- {
- return "NULL";
- }
-
- StringBuffer result = new StringBuffer();
-
- // TODO: Handle binary types (BINARY, VARBINARY, LONGVARBINARY, BLOB)
- switch (column.getTypeCode())
- {
- case Types.DATE:
- result.append(getPlatformInfo().getValueQuoteToken());
- if (!(value instanceof String) && (getValueDateFormat() != null))
- {
- // TODO: Can the format method handle java.sql.Date properly ?
- result.append(getValueDateFormat().format(value));
- }
- else
- {
- result.append(value.toString());
- }
- result.append(getPlatformInfo().getValueQuoteToken());
- break;
- case Types.TIME:
- result.append(getPlatformInfo().getValueQuoteToken());
- if (!(value instanceof String) && (getValueTimeFormat() != null))
- {
- // TODO: Can the format method handle java.sql.Date properly ?
- result.append(getValueTimeFormat().format(value));
- }
- else
- {
- result.append(value.toString());
- }
- result.append(getPlatformInfo().getValueQuoteToken());
- break;
- case Types.TIMESTAMP:
- result.append(getPlatformInfo().getValueQuoteToken());
- // TODO: SimpleDateFormat does not support nano seconds so we would
- // need a custom date formatter for timestamps
- result.append(value.toString());
- result.append(getPlatformInfo().getValueQuoteToken());
- break;
- case Types.REAL:
- case Types.NUMERIC:
- case Types.FLOAT:
- case Types.DOUBLE:
- case Types.DECIMAL:
- result.append(getPlatformInfo().getValueQuoteToken());
- if (!(value instanceof String) && (getValueNumberFormat() != null))
- {
- result.append(getValueNumberFormat().format(value));
- }
- else
- {
- result.append(value.toString());
- }
- result.append(getPlatformInfo().getValueQuoteToken());
- break;
- default:
- result.append(getPlatformInfo().getValueQuoteToken());
- result.append(escapeStringValue(value.toString()));
- result.append(getPlatformInfo().getValueQuoteToken());
- break;
- }
- return result.toString();
- }
-
- /**
- * Generates the SQL for querying the id that was created in the last insertion
- * operation. This is obviously only useful for pk fields that are auto-incrementing.
- * A database that does not support this, will return null
.
- *
- * @param table The table
- * @return The sql, or null
if the database does not support this
- */
- public String getSelectLastIdentityValues(Table table)
- {
- // No default possible as the databases are quite different in this respect
- return null;
- }
-
- /**
- * Generates the SQL to execute that sets the current sequence number.
- *
- * @param table
- * @param id
- * @return
- */
- public String fixLastIdentityValues(Table table)
- {
- return null;
- }
-
- public void writeFixLastIdentityValues(Table table) throws IOException
- {
- String sql = fixLastIdentityValues(table);
- if (sql != null) {
- print(sql);
- printEndOfStatement();
- }
- }
-
- //
- // implementation methods that may be overridden by specific database builders
- //
-
- /**
- * Generates a version of the name that has at most the specified
- * length.
- *
- * @param name The original name
- * @param desiredLength The desired maximum length
- * @return The shortened version
- */
- public String shortenName(String name, int desiredLength)
- {
- // TODO: Find an algorithm that generates unique names
- int originalLength = name.length();
-
- if ((desiredLength <= 0) || (originalLength <= desiredLength))
- {
- return name;
- }
-
- int delta = originalLength - desiredLength;
- int startCut = desiredLength / 2;
-
- StringBuffer result = new StringBuffer();
-
- result.append(name.substring(0, startCut));
- if (((startCut == 0) || (name.charAt(startCut - 1) != '_')) &&
- ((startCut + delta + 1 == originalLength) || (name.charAt(startCut + delta + 1) != '_')))
- {
- // just to make sure that there isn't already a '_' right before or right
- // after the cutting place (which would look odd with an aditional one)
- result.append("_");
- }
- result.append(name.substring(startCut + delta + 1, originalLength));
- return result.toString();
- }
-
- /**
- * Returns the table name. This method takes care of length limitations imposed by some databases.
- *
- * @param table The table
- * @return The table name
- */
- public String getTableName(Table table)
- {
- return shortenName(table.getName(), getMaxTableNameLength());
- }
-
- /**
- * Outputs a comment for the table.
- *
- * @param table The table
- */
- protected void writeTableComment(Table table) throws IOException
- {
- printComment("-----------------------------------------------------------------------");
- printComment(getTableName(table));
- printComment("-----------------------------------------------------------------------");
- println();
- }
-
- /**
- * Generates the first part of the ALTER TABLE statement including the
- * table name.
- *
- * @param table The table being altered
- */
- protected void writeTableAlterStmt(Table table) throws IOException
- {
- print("ALTER TABLE ");
- printlnIdentifier(getTableName(table));
- printIndent();
- }
-
- /**
- * Writes the table creation statement without the statement end.
- *
- * @param database The model
- * @param table The table
- * @param parameters Additional platform-specific parameters for the table creation
- */
- protected void writeTableCreationStmt(Database database, Table table, Map parameters) throws IOException
- {
- print("CREATE TABLE ");
- printlnIdentifier(getTableName(table));
- println("(");
-
- writeColumns(table);
-
- if (getPlatformInfo().isPrimaryKeyEmbedded())
- {
- writeEmbeddedPrimaryKeysStmt(table);
- }
- if (getPlatformInfo().isForeignKeysEmbedded())
- {
- writeEmbeddedForeignKeysStmt(database, table);
- }
- if (getPlatformInfo().isIndicesEmbedded())
- {
- writeEmbeddedIndicesStmt(table);
- }
- println();
- print(")");
- }
-
- /**
- * Writes the end of the table creation statement. Per default,
- * only the end of the statement is written, but this can be changed
- * in subclasses.
- *
- * @param table The table
- * @param parameters Additional platform-specific parameters for the table creation
- */
- protected void writeTableCreationStmtEnding(Table table, Map parameters) throws IOException
- {
- printEndOfStatement();
- }
-
- /**
- * Writes the columns of the given table.
- *
- * @param table The table
- */
- protected void writeColumns(Table table) throws IOException
- {
- for (int idx = 0; idx < table.getColumnCount(); idx++)
- {
- printIndent();
- writeColumn(table, table.getColumn(idx));
- if (idx < table.getColumnCount() - 1)
- {
- println(",");
- }
- }
- }
-
- /**
- * Returns the column name. This method takes care of length limitations imposed by some databases.
- *
- * @param column The column
- * @return The column name
- */
- protected String getColumnName(Column column) throws IOException
- {
- return shortenName(column.getName(), getMaxColumnNameLength());
- }
-
- /**
- * Outputs the DDL for the specified column.
- *
- * @param table The table containing the column
- * @param column The column
- */
- protected void writeColumn(Table table, Column column) throws IOException
- {
- //see comments in columnsDiffer about null/"" defaults
- printIdentifier(getColumnName(column));
- print(" ");
- print(getSqlType(column));
- writeColumnDefaultValueStmt(table, column);
- if (column.isRequired())
- {
- print(" ");
- writeColumnNotNullableStmt();
- }
- else if (getPlatformInfo().isNullAsDefaultValueRequired() &&
- getPlatformInfo().hasNullDefault(column.getTypeCode()))
- {
- print(" ");
- writeColumnNullableStmt();
- }
- if (column.isAutoIncrement() && !getPlatformInfo().isDefaultValueUsedForIdentitySpec())
- {
- if (!getPlatformInfo().isNonPKIdentityColumnsSupported() && !column.isPrimaryKey())
- {
- throw new ModelException("Column "+column.getName()+" in table "+table.getName()+" is auto-incrementing but not a primary key column, which is not supported by the platform");
- }
- print(" ");
- writeColumnAutoIncrementStmt(table, column);
- }
- }
-
- /**
- * Returns the full SQL type specification (including size and precision/scale) for the
- * given column.
- *
- * @param column The column
- * @return The full SQL type string including the size
- */
- protected String getSqlType(Column column)
- {
- String nativeType = getNativeType(column);
- int sizePos = nativeType.indexOf(SIZE_PLACEHOLDER);
- StringBuffer sqlType = new StringBuffer();
-
- sqlType.append(sizePos >= 0 ? nativeType.substring(0, sizePos) : nativeType);
-
- Object sizeSpec = column.getSize();
-
- if (sizeSpec == null)
- {
- sizeSpec = getPlatformInfo().getDefaultSize(column.getTypeCode());
- }
- if (sizeSpec != null)
- {
- if (getPlatformInfo().hasSize(column.getTypeCode()))
- {
- sqlType.append("(");
- sqlType.append(sizeSpec.toString());
- sqlType.append(")");
- }
- else if (getPlatformInfo().hasPrecisionAndScale(column.getTypeCode()))
- {
- sqlType.append("(");
- sqlType.append(column.getSizeAsInt());
- sqlType.append(",");
- sqlType.append(column.getScale());
- sqlType.append(")");
- }
- }
- sqlType.append(sizePos >= 0 ? nativeType.substring(sizePos + SIZE_PLACEHOLDER.length()) : "");
-
- return sqlType.toString();
- }
-
- /**
- * Returns the database-native type for the given column.
- *
- * @param column The column
- * @return The native type
- */
- protected String getNativeType(Column column)
- {
- String nativeType = (String)getPlatformInfo().getNativeType(column.getTypeCode());
-
- return nativeType == null ? column.getType() : nativeType;
- }
-
- /**
- * Returns the bare database-native type for the given column without any size specifies.
- *
- * @param column The column
- * @return The native type
- */
- protected String getBareNativeType(Column column)
- {
- String nativeType = getNativeType(column);
- int sizePos = nativeType.indexOf(SIZE_PLACEHOLDER);
-
- return sizePos >= 0 ? nativeType.substring(0, sizePos) : nativeType;
- }
-
- /**
- * Returns the native default value for the column.
- *
- * @param column The column
- * @return The native default value
- */
- protected String getNativeDefaultValue(Column column)
- {
- return column.getDefaultValue();
- }
-
- /**
- * Escapes the necessary characters in given string value.
- *
- * @param value The value
- * @return The corresponding string with the special characters properly escaped
- */
- protected String escapeStringValue(String value)
- {
- String result = value;
-
- for (Iterator it = _charSequencesToEscape.entrySet().iterator(); it.hasNext();)
- {
- Map.Entry entry = (Map.Entry)it.next();
-
- result = StringUtils.replace(result, (String)entry.getKey(), (String)entry.getValue());
- }
- return result;
- }
-
- /**
- * Determines whether the given default spec is a non-empty spec that shall be used in a DEFAULT
- * expression. E.g. if the spec is an empty string and the type is a numeric type, then it is
- * no valid default value whereas if it is a string type, then it is valid.
- *
- * @param defaultSpec The default value spec
- * @param typeCode The JDBC type code
- * @return true
if the default value spec is valid
- */
- protected boolean isValidDefaultValue(String defaultSpec, int typeCode)
- {
- return (defaultSpec != null) &&
- ((defaultSpec.length() > 0) ||
- (!TypeMap.isNumericType(typeCode) && !TypeMap.isDateTimeType(typeCode)));
- }
-
- /**
- * Prints the default value stmt part for the column.
- *
- * @param table The table
- * @param column The column
- */
- protected void writeColumnDefaultValueStmt(Table table, Column column) throws IOException
- {
- Object parsedDefault = column.getParsedDefaultValue();
-
- if (parsedDefault != null)
- {
- if (!getPlatformInfo().isDefaultValuesForLongTypesSupported() &&
- ((column.getTypeCode() == Types.LONGVARBINARY) || (column.getTypeCode() == Types.LONGVARCHAR)))
- {
- throw new ModelException("The platform does not support default values for LONGVARCHAR or LONGVARBINARY columns");
- }
- // we write empty default value strings only if the type is not a numeric or date/time type
- if (isValidDefaultValue(column.getDefaultValue(), column.getTypeCode()))
- {
- print(" DEFAULT ");
- writeColumnDefaultValue(table, column);
- }
- }
- else if (getPlatformInfo().isDefaultValueUsedForIdentitySpec() && column.isAutoIncrement())
- {
- print(" DEFAULT ");
- writeColumnDefaultValue(table, column);
- }
- }
-
- /**
- * Prints the default value of the column.
- *
- * @param table The table
- * @param column The column
- */
- protected void writeColumnDefaultValue(Table table, Column column) throws IOException
- {
- printDefaultValue(getNativeDefaultValue(column), column.getTypeCode());
- }
-
- /**
- * Prints the default value of the column.
- *
- * @param defaultValue The default value
- * @param typeCode The type code to write the default value for
- */
- protected void printDefaultValue(Object defaultValue, int typeCode) throws IOException
- {
- if (defaultValue != null)
- {
- boolean shouldUseQuotes = !TypeMap.isNumericType(typeCode);
-
- if (shouldUseQuotes)
- {
- // characters are only escaped when within a string literal
- print(getPlatformInfo().getValueQuoteToken());
- print(escapeStringValue(defaultValue.toString()));
- print(getPlatformInfo().getValueQuoteToken());
- }
- else
- {
- print(defaultValue.toString());
- }
- }
- }
-
- /**
- * Prints that the column is an auto increment column.
- *
- * @param table The table
- * @param column The column
- */
- protected void writeColumnAutoIncrementStmt(Table table, Column column) throws IOException
- {
- print("IDENTITY");
- }
-
- /**
- * Prints that a column is nullable.
- */
- protected void writeColumnNullableStmt() throws IOException
- {
- print("NULL");
- }
-
- /**
- * Prints that a column is not nullable.
- */
- protected void writeColumnNotNullableStmt() throws IOException
- {
- print("NOT NULL");
- }
-
- /**
- * Compares the current column in the database with the desired one.
- * Type, nullability, size, scale, default value, and precision radix are
- * the attributes checked. Currently default values are compared, and
- * null and empty string are considered equal.
- *
- * @param currentColumn The current column as it is in the database
- * @param desiredColumn The desired column
- * @return true
if the column specifications differ
- */
- protected boolean columnsDiffer(Column currentColumn, Column desiredColumn)
- {
- //The createColumn method leaves off the default clause if column.getDefaultValue()
- //is null. mySQL interprets this as a default of "" or 0, and thus the columns
- //are always different according to this method. alterDatabase will generate
- //an alter statement for the column, but it will be the exact same definition
- //as before. In order to avoid this situation I am ignoring the comparison
- //if the desired default is null. In order to "un-default" a column you'll
- //have to have a default="" or default="0" in the schema xml.
- //If this is bad for other databases, it is recommended that the createColumn
- //method use a "DEFAULT NULL" statement if that is what is needed.
- //A good way to get this would be to require a defaultValue="null
- * @param table The table that the constraint belongs to
- * @param secondPart The second name part, e.g. the name of the constraint column
- * @param suffix The constraint suffix, e.g. a counter (can be null
)
- * @return The constraint name
- */
- public String getConstraintName(String prefix, Table table, String secondPart, String suffix)
- {
- StringBuffer result = new StringBuffer();
-
- if (prefix != null)
- {
- result.append(prefix);
- result.append("_");
- }
- result.append(table.getName());
- result.append("_");
- result.append(secondPart);
- if (suffix != null)
- {
- result.append("_");
- result.append(suffix);
- }
- return shortenName(result.toString(), getMaxConstraintNameLength());
- }
-
- /**
- * Writes the primary key constraints of the table inside its definition.
- *
- * @param table The table
- */
- protected void writeEmbeddedPrimaryKeysStmt(Table table) throws IOException
- {
- Column[] primaryKeyColumns = table.getPrimaryKeyColumns();
-
- if ((primaryKeyColumns.length > 0) && shouldGeneratePrimaryKeys(primaryKeyColumns))
- {
- printStartOfEmbeddedStatement();
- writePrimaryKeyStmt(table, primaryKeyColumns);
- }
- }
-
- /**
- * Writes the primary key constraints of the table as alter table statements.
- *
- * @param table The table
- * @param primaryKeyColumns The primary key columns
- */
- protected void writeExternalPrimaryKeysCreateStmt(Table table, Column[] primaryKeyColumns) throws IOException
- {
- if ((primaryKeyColumns.length > 0) && shouldGeneratePrimaryKeys(primaryKeyColumns))
- {
- print("ALTER TABLE ");
- printlnIdentifier(getTableName(table));
- printIndent();
- print("ADD CONSTRAINT ");
- printIdentifier(getConstraintName(null, table, "PK", null));
- print(" ");
- writePrimaryKeyStmt(table, primaryKeyColumns);
- printEndOfStatement();
- }
- }
-
- /**
- * Determines whether we should generate a primary key constraint for the given
- * primary key columns.
- *
- * @param primaryKeyColumns The pk columns
- * @return true
if a pk statement should be generated for the columns
- */
- protected boolean shouldGeneratePrimaryKeys(Column[] primaryKeyColumns)
- {
- return true;
- }
-
- /**
- * Writes a primary key statement for the given columns.
- *
- * @param table The table
- * @param primaryKeyColumns The primary columns
- */
- protected void writePrimaryKeyStmt(Table table, Column[] primaryKeyColumns) throws IOException
- {
- print("PRIMARY KEY (");
- for (int idx = 0; idx < primaryKeyColumns.length; idx++)
- {
- printIdentifier(getColumnName(primaryKeyColumns[idx]));
- if (idx < primaryKeyColumns.length - 1)
- {
- print(", ");
- }
- }
- print(")");
- }
-
- /**
- * Returns the index name. This method takes care of length limitations imposed by some databases.
- *
- * @param index The index
- * @return The index name
- */
- public String getIndexName(Index index)
- {
- return shortenName(index.getName(), getMaxConstraintNameLength());
- }
-
- /**
- * Writes the indexes of the given table.
- *
- * @param table The table
- */
- protected void writeExternalIndicesCreateStmt(Table table) throws IOException
- {
- for (int idx = 0; idx < table.getIndexCount(); idx++)
- {
- Index index = table.getIndex(idx);
-
- if (!index.isUnique() && !getPlatformInfo().isIndicesSupported())
- {
- throw new ModelException("Platform does not support non-unique indices");
- }
- writeExternalIndexCreateStmt(table, index);
- }
- }
-
- /**
- * Writes the indexes embedded within the create table statement.
- *
- * @param table The table
- */
- protected void writeEmbeddedIndicesStmt(Table table) throws IOException
- {
- if (getPlatformInfo().isIndicesSupported())
- {
- for (int idx = 0; idx < table.getIndexCount(); idx++)
- {
- printStartOfEmbeddedStatement();
- writeEmbeddedIndexCreateStmt(table, table.getIndex(idx));
- }
- }
- }
-
- /**
- * Writes the given index of the table.
- *
- * @param table The table
- * @param index The index
- */
- protected void writeExternalIndexCreateStmt(Table table, Index index) throws IOException
- {
- if (getPlatformInfo().isIndicesSupported())
- {
- if (index.getName() == null)
- {
- _log.warn("Cannot write unnamed index " + index);
- }
- else
- {
- print("CREATE");
- if (index.isUnique())
- {
- print(" UNIQUE");
- }
- print(" INDEX ");
- printIdentifier(getIndexName(index));
- print(" ON ");
- printIdentifier(getTableName(table));
- print(" (");
-
- for (int idx = 0; idx < index.getColumnCount(); idx++)
- {
- IndexColumn idxColumn = index.getColumn(idx);
- Column col = table.findColumn(idxColumn.getName());
-
- if (col == null)
- {
- // would get null pointer on next line anyway, so throw exception
- throw new ModelException("Invalid column '" + idxColumn.getName() + "' on index " + index.getName() + " for table " + table.getName());
- }
- if (idx > 0)
- {
- print(", ");
- }
- printIdentifier(getColumnName(col));
- }
-
- print(")");
- printEndOfStatement();
- }
- }
- }
-
- /**
- * Writes the given embedded index of the table.
- *
- * @param table The table
- * @param index The index
- */
- protected void writeEmbeddedIndexCreateStmt(Table table, Index index) throws IOException
- {
- if ((index.getName() != null) && (index.getName().length() > 0))
- {
- print(" CONSTRAINT ");
- printIdentifier(getIndexName(index));
- }
- if (index.isUnique())
- {
- print(" UNIQUE");
- }
- else
- {
- print(" INDEX ");
- }
- print(" (");
-
- for (int idx = 0; idx < index.getColumnCount(); idx++)
- {
- IndexColumn idxColumn = index.getColumn(idx);
- Column col = table.findColumn(idxColumn.getName());
-
- if (col == null)
- {
- // would get null pointer on next line anyway, so throw exception
- throw new ModelException("Invalid column '" + idxColumn.getName() + "' on index " + index.getName() + " for table " + table.getName());
- }
- if (idx > 0)
- {
- print(", ");
- }
- printIdentifier(getColumnName(col));
- }
-
- print(")");
- }
-
- /**
- * Generates the statement to drop a non-embedded index from the database.
- *
- * @param table The table the index is on
- * @param index The index to drop
- */
- public void writeExternalIndexDropStmt(Table table, Index index) throws IOException
- {
- if (getPlatformInfo().isAlterTableForDropUsed())
- {
- writeTableAlterStmt(table);
- }
- print("DROP INDEX ");
- printIdentifier(getIndexName(index));
- if (!getPlatformInfo().isAlterTableForDropUsed())
- {
- print(" ON ");
- printIdentifier(getTableName(table));
- }
- printEndOfStatement();
- }
-
-
- /**
- * Writes the foreign key constraints inside a create table () clause.
- *
- * @param database The database model
- * @param table The table
- */
- protected void writeEmbeddedForeignKeysStmt(Database database, Table table) throws IOException
- {
- for (int idx = 0; idx < table.getForeignKeyCount(); idx++)
- {
- ForeignKey key = table.getForeignKey(idx);
-
- if (key.getForeignTableName() == null)
- {
- _log.warn("Foreign key table is null for key " + key);
- }
- else
- {
- printStartOfEmbeddedStatement();
- if (getPlatformInfo().isEmbeddedForeignKeysNamed())
- {
- print("CONSTRAINT ");
- printIdentifier(getForeignKeyName(table, key));
- print(" ");
- }
- print("FOREIGN KEY (");
- writeLocalReferences(key);
- print(") REFERENCES ");
- printIdentifier(getTableName(database.findTable(key.getForeignTableName())));
- print(" (");
- writeForeignReferences(key);
- print(")");
- }
- }
- }
-
- /**
- * Writes a single foreign key constraint using a alter table statement.
- *
- * @param database The database model
- * @param table The table
- * @param key The foreign key
- */
- protected void writeExternalForeignKeyCreateStmt(Database database, Table table, ForeignKey key) throws IOException
- {
- if (key.getForeignTableName() == null)
- {
- _log.warn("Foreign key table is null for key " + key);
- }
- else
- {
- writeTableAlterStmt(table);
-
- print("ADD CONSTRAINT ");
- printIdentifier(getForeignKeyName(table, key));
- print(" FOREIGN KEY (");
- writeLocalReferences(key);
- print(") REFERENCES ");
- printIdentifier(getTableName(database.findTable(key.getForeignTableName())));
- print(" (");
- writeForeignReferences(key);
- print(")");
- printEndOfStatement();
- }
- }
-
- /**
- * Writes a list of local references for the given foreign key.
- *
- * @param key The foreign key
- */
- protected void writeLocalReferences(ForeignKey key) throws IOException
- {
- for (int idx = 0; idx < key.getReferenceCount(); idx++)
- {
- if (idx > 0)
- {
- print(", ");
- }
- printIdentifier(key.getReference(idx).getLocalColumnName());
- }
- }
-
- /**
- * Writes a list of foreign references for the given foreign key.
- *
- * @param key The foreign key
- */
- protected void writeForeignReferences(ForeignKey key) throws IOException
- {
- for (int idx = 0; idx < key.getReferenceCount(); idx++)
- {
- if (idx > 0)
- {
- print(", ");
- }
- printIdentifier(key.getReference(idx).getForeignColumnName());
- }
- }
-
- /**
- * Generates the statement to drop a foreignkey constraint from the database using an
- * alter table statement.
- *
- * @param table The table
- * @param foreignKey The foreign key
- */
- protected void writeExternalForeignKeyDropStmt(Table table, ForeignKey foreignKey) throws IOException
- {
- writeTableAlterStmt(table);
- print("DROP CONSTRAINT ");
- printIdentifier(getForeignKeyName(table, foreignKey));
- printEndOfStatement();
- }
-
- //
- // Helper methods
- //
-
- /**
- * Prints an SQL comment to the current stream.
- *
- * @param text The comment text
- */
- protected void printComment(String text) throws IOException
- {
- if (getPlatform().isSqlCommentsOn())
- {
- print(getPlatformInfo().getCommentPrefix());
- // Some databases insist on a space after the prefix
- print(" ");
- print(text);
- print(" ");
- print(getPlatformInfo().getCommentSuffix());
- println();
- }
- }
-
- /**
- * Prints the start of an embedded statement.
- */
- protected void printStartOfEmbeddedStatement() throws IOException
- {
- println(",");
- printIndent();
- }
-
- /**
- * Prints the end of statement text, which is typically a semi colon followed by
- * a carriage return.
- */
- protected void printEndOfStatement() throws IOException
- {
- // TODO: It might make sense to use a special writer which stores the individual
- // statements separately (the end of a statement is identified by this method)
- println(getPlatformInfo().getSqlCommandDelimiter());
- println();
- }
-
- /**
- * Prints a newline.
- */
- protected void println() throws IOException
- {
- print(LINE_SEPARATOR);
- }
-
- /**
- * Prints some text.
- *
- * @param text The text to print
- */
- protected void print(String text) throws IOException
- {
- _writer.write(text);
- }
-
- /**
- * Returns the delimited version of the identifier (if configured).
- *
- * @param identifier The identifier
- * @return The delimited version of the identifier unless the platform is configured
- * to use undelimited identifiers; in that case, the identifier is returned unchanged
- */
- protected String getDelimitedIdentifier(String identifier)
- {
- if (getPlatform().isDelimitedIdentifierModeOn())
- {
- return getPlatformInfo().getDelimiterToken() + identifier + getPlatformInfo().getDelimiterToken();
- }
- else
- {
- return identifier;
- }
- }
-
- /**
- * Prints the given identifier. For most databases, this will
- * be a delimited identifier.
- *
- * @param identifier The identifier
- */
- protected void printIdentifier(String identifier) throws IOException
- {
- print(getDelimitedIdentifier(identifier));
- }
-
- /**
- * Prints the given identifier followed by a newline. For most databases, this will
- * be a delimited identifier.
- *
- * @param identifier The identifier
- */
- protected void printlnIdentifier(String identifier) throws IOException
- {
- println(getDelimitedIdentifier(identifier));
- }
-
- /**
- * Prints some text followed by a newline.
- *
- * @param text The text to print
- */
- protected void println(String text) throws IOException
- {
- print(text);
- println();
- }
-
- /**
- * Prints the characters used to indent SQL.
- */
- protected void printIndent() throws IOException
- {
- print(getIndent());
- }
-
- /**
- * Creates a reasonably unique identifier only consisting of hexadecimal characters and underscores.
- * It looks like d578271282b42fce__2955b56e_107df3fbc96__8000
and is 48 characters long.
- *
- * @return The identifier
- */
- protected String createUniqueIdentifier()
- {
- return new UID().toString().replace(':', '_').replace('-', '_');
- }
-}
diff --git a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/platform/cloudscape/CloudscapeBuilder.java b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/platform/cloudscape/CloudscapeBuilder.java
deleted file mode 100644
index 35dca7f8d3..0000000000
--- a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/platform/cloudscape/CloudscapeBuilder.java
+++ /dev/null
@@ -1,62 +0,0 @@
-package org.jumpmind.symmetric.db.ddl.platform.cloudscape;
-
-/*
- * 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 org.jumpmind.symmetric.db.ddl.Platform;
-import org.jumpmind.symmetric.db.ddl.model.Column;
-import org.jumpmind.symmetric.db.ddl.model.Table;
-import org.jumpmind.symmetric.db.ddl.platform.SqlBuilder;
-
-/**
- * The SQL Builder for Cloudscape.
- *
- * @version $Revision: 463757 $
- */
-public class CloudscapeBuilder extends SqlBuilder
-{
- /**
- * Creates a new builder instance.
- *
- * @param platform The plaftform this builder belongs to
- */
- public CloudscapeBuilder(Platform platform)
- {
- super(platform);
- addEscapedCharSequence("'", "''");
- }
-
- /**
- * {@inheritDoc}
- */
- protected void writeColumnAutoIncrementStmt(Table table, Column column) throws IOException
- {
- print("GENERATED ALWAYS AS IDENTITY");
- }
-
- /**
- * {@inheritDoc}
- */
- public String getSelectLastIdentityValues(Table table)
- {
- return "VALUES IDENTITY_VAL_LOCAL()";
- }
-}
diff --git a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/platform/cloudscape/CloudscapePlatform.java b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/platform/cloudscape/CloudscapePlatform.java
deleted file mode 100644
index 666390ca57..0000000000
--- a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/platform/cloudscape/CloudscapePlatform.java
+++ /dev/null
@@ -1,84 +0,0 @@
-package org.jumpmind.symmetric.db.ddl.platform.cloudscape;
-
-/*
- * 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.sql.Types;
-
-import org.jumpmind.symmetric.db.ddl.PlatformInfo;
-import org.jumpmind.symmetric.db.ddl.platform.PlatformImplBase;
-
-/**
- * The Cloudscape platform implementation.
- *
- * @version $Revision: 231306 $
- */
-public class CloudscapePlatform extends PlatformImplBase
-{
- /** Database name of this platform. */
- public static final String DATABASENAME = "Cloudscape";
- /** A subprotocol used by the DB2 network driver. */
- public static final String JDBC_SUBPROTOCOL_1 = "db2j:net";
- /** A subprotocol used by the DB2 network driver. */
- public static final String JDBC_SUBPROTOCOL_2 = "cloudscape:net";
-
- /**
- * Creates a new platform instance.
- */
- public CloudscapePlatform()
- {
- PlatformInfo info = getPlatformInfo();
-
- info.setMaxIdentifierLength(128);
- info.setSystemForeignKeyIndicesAlwaysNonUnique(true);
- // BINARY and VARBINARY will also be handled by CloudscapeBuilder.getSqlType
- info.addNativeTypeMapping(Types.ARRAY, "BLOB", Types.BLOB);
- info.addNativeTypeMapping(Types.BINARY, "CHAR {0} FOR BIT DATA");
- info.addNativeTypeMapping(Types.BIT, "SMALLINT", Types.SMALLINT);
- info.addNativeTypeMapping(Types.DISTINCT, "BLOB", Types.BLOB);
- info.addNativeTypeMapping(Types.DOUBLE, "DOUBLE PRECISION");
- info.addNativeTypeMapping(Types.FLOAT, "DOUBLE PRECISION", Types.DOUBLE);
- info.addNativeTypeMapping(Types.JAVA_OBJECT, "BLOB", Types.BLOB);
- info.addNativeTypeMapping(Types.LONGVARBINARY, "LONG VARCHAR FOR BIT DATA");
- info.addNativeTypeMapping(Types.LONGVARCHAR, "LONG VARCHAR");
- info.addNativeTypeMapping(Types.NULL, "LONG VARCHAR FOR BIT DATA", Types.LONGVARBINARY);
- info.addNativeTypeMapping(Types.OTHER, "BLOB", Types.BLOB);
- info.addNativeTypeMapping(Types.REF, "LONG VARCHAR FOR BIT DATA", Types.LONGVARBINARY);
- info.addNativeTypeMapping(Types.STRUCT, "BLOB", Types.BLOB);
- info.addNativeTypeMapping(Types.TINYINT, "SMALLINT", Types.SMALLINT);
- info.addNativeTypeMapping(Types.VARBINARY, "VARCHAR {0} FOR BIT DATA");
- info.addNativeTypeMapping("BOOLEAN", "SMALLINT", "SMALLINT");
- info.addNativeTypeMapping("DATALINK", "LONG VARCHAR FOR BIT DATA", "LONGVARBINARY");
-
- info.setDefaultSize(Types.BINARY, 254);
- info.setDefaultSize(Types.CHAR, 254);
- info.setDefaultSize(Types.VARBINARY, 254);
- info.setDefaultSize(Types.VARCHAR, 254);
-
- setSqlBuilder(new CloudscapeBuilder(this));
- }
-
- /**
- * {@inheritDoc}
- */
- public String getName()
- {
- return DATABASENAME;
- }
-}
diff --git a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/platform/cloudscape/package.html b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/platform/cloudscape/package.html
deleted file mode 100644
index 1eb7833509..0000000000
--- a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/platform/cloudscape/package.html
+++ /dev/null
@@ -1,30 +0,0 @@
-
-
-
-
-
-
-
- - This package contains the platform implementation for the - Cloudscape database. -
- - diff --git a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/platform/db2/Db2Builder.java b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/platform/db2/Db2Builder.java deleted file mode 100644 index dbe5c4d018..0000000000 --- a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/platform/db2/Db2Builder.java +++ /dev/null @@ -1,273 +0,0 @@ -package org.jumpmind.symmetric.db.ddl.platform.db2; - -/* - * 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.sql.Types; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import org.jumpmind.symmetric.db.ddl.Platform; -import org.jumpmind.symmetric.db.ddl.alteration.AddColumnChange; -import org.jumpmind.symmetric.db.ddl.alteration.AddPrimaryKeyChange; -import org.jumpmind.symmetric.db.ddl.alteration.PrimaryKeyChange; -import org.jumpmind.symmetric.db.ddl.alteration.RemoveColumnChange; -import org.jumpmind.symmetric.db.ddl.alteration.RemovePrimaryKeyChange; -import org.jumpmind.symmetric.db.ddl.alteration.TableChange; -import org.jumpmind.symmetric.db.ddl.model.Column; -import org.jumpmind.symmetric.db.ddl.model.Database; -import org.jumpmind.symmetric.db.ddl.model.Index; -import org.jumpmind.symmetric.db.ddl.model.Table; -import org.jumpmind.symmetric.db.ddl.model.TypeMap; -import org.jumpmind.symmetric.db.ddl.platform.SqlBuilder; -import org.jumpmind.symmetric.db.ddl.util.Jdbc3Utils; - -/* - * The SQL Builder for DB2. - * - * @version $Revision: 504811 $ - */ -public class Db2Builder extends SqlBuilder -{ - /* - * Creates a new builder instance. - * - * @param platform The plaftform this builder belongs to - */ - public Db2Builder(Platform platform) - { - super(platform); - addEscapedCharSequence("'", "''"); - } - - /* - * {@inheritDoc} - */ - protected String getNativeDefaultValue(Column column) - { - if ((column.getTypeCode() == Types.BIT) || - (Jdbc3Utils.supportsJava14JdbcTypes() && (column.getTypeCode() == Jdbc3Utils.determineBooleanTypeCode()))) - { - return getDefaultValueHelper().convert(column.getDefaultValue(), column.getTypeCode(), Types.SMALLINT).toString(); - } - else - { - return super.getNativeDefaultValue(column); - } - } - - /* - * {@inheritDoc} - */ - protected void writeColumnAutoIncrementStmt(Table table, Column column) throws IOException - { - print("GENERATED BY DEFAULT AS IDENTITY"); - } - - /* - * {@inheritDoc} - */ - public String getSelectLastIdentityValues(Table table) - { - return "VALUES IDENTITY_VAL_LOCAL()"; - } - - /* - * {@inheritDoc} - */ - public void writeExternalIndexDropStmt(Table table, Index index) throws IOException - { - // Index names in DB2 are unique to a schema and hence Derby does not - // use the ONtrue
if identity override mode is needed
- */
- private boolean useIdentityOverrideFor(Table table)
- {
- return isIdentityOverrideOn() &&
- getPlatformInfo().isIdentityOverrideAllowed() &&
- (table.getAutoIncrementColumns().length > 0);
- }
-
- /*
- * {@inheritDoc}
- */
- protected void beforeInsert(Connection connection, Table table) throws SQLException
- {
- if (useIdentityOverrideFor(table))
- {
- MSSqlBuilder builder = (MSSqlBuilder)getSqlBuilder();
-
- connection.createStatement().execute(builder.getEnableIdentityOverrideSql(table));
- }
- }
-
- /*
- * {@inheritDoc}
- */
- protected void afterInsert(Connection connection, Table table) throws SQLException
- {
- if (useIdentityOverrideFor(table))
- {
- MSSqlBuilder builder = (MSSqlBuilder)getSqlBuilder();
-
- connection.createStatement().execute(builder.getDisableIdentityOverrideSql(table));
- }
- }
-
- /*
- * {@inheritDoc}
- */
- protected void beforeUpdate(Connection connection, Table table) throws SQLException
- {
- beforeInsert(connection, table);
- }
-
- /*
- * {@inheritDoc}
- */
- protected void afterUpdate(Connection connection, Table table) throws SQLException
- {
- afterInsert(connection, table);
- }
-}
diff --git a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/platform/mysql/MySql50ModelReader.java b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/platform/mysql/MySql50ModelReader.java
deleted file mode 100644
index 9f875e9114..0000000000
--- a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/platform/mysql/MySql50ModelReader.java
+++ /dev/null
@@ -1,56 +0,0 @@
-package org.jumpmind.symmetric.db.ddl.platform.mysql;
-
-/*
- * 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.sql.SQLException;
-import java.util.Map;
-
-import org.jumpmind.symmetric.db.ddl.Platform;
-import org.jumpmind.symmetric.db.ddl.model.Column;
-import org.jumpmind.symmetric.db.ddl.platform.DatabaseMetaDataWrapper;
-
-/*
- * Reads a database model from a MySql 5 database.
- */
-public class MySql50ModelReader extends MySqlModelReader
-{
- /*
- * Creates a new model reader for MySql 5 databases.
- *
- * @param platform The platform that this model reader belongs to
- */
- public MySql50ModelReader(Platform platform)
- {
- super(platform);
- }
-
- @Override
- protected Column readColumn(DatabaseMetaDataWrapper metaData, Map values) throws SQLException
- {
- Column column = super.readColumn(metaData, values);
-
- // make sure the defaultvalue is null when an empty is returned.
- if ("".equals(column.getDefaultValue()))
- {
- column.setDefaultValue(null);
- }
- return column;
- }
-}
diff --git a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/platform/mysql/MySql50Platform.java b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/platform/mysql/MySql50Platform.java
deleted file mode 100644
index 29692578e3..0000000000
--- a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/platform/mysql/MySql50Platform.java
+++ /dev/null
@@ -1,57 +0,0 @@
-package org.jumpmind.symmetric.db.ddl.platform.mysql;
-
-/*
- * 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 org.jumpmind.symmetric.db.ddl.PlatformInfo;
-
-/*
- * The platform implementation for MySQL 5 and above.
- *
- * @version $Revision: 231306 $
- */
-public class MySql50Platform extends MySqlPlatform
-{
- /* Database name of this platform. */
- public static final String DATABASENAME = "MySQL5";
-
- /*
- * Creates a new platform instance.
- */
- public MySql50Platform()
- {
- super();
-
- PlatformInfo info = getPlatformInfo();
-
- // MySql 5.0 returns an empty string for default values for pk columns
- // which is different from the MySql 4 behaviour
- info.setSyntheticDefaultValueForRequiredReturned(false);
-
- setModelReader(new MySql50ModelReader(this));
- }
-
- /*
- * {@inheritDoc}
- */
- public String getName()
- {
- return DATABASENAME;
- }
-}
diff --git a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/platform/mysql/MySqlBuilder.java b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/platform/mysql/MySqlBuilder.java
deleted file mode 100644
index 2d6ff93d7f..0000000000
--- a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/platform/mysql/MySqlBuilder.java
+++ /dev/null
@@ -1,351 +0,0 @@
-package org.jumpmind.symmetric.db.ddl.platform.mysql;
-
-/*
- * 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.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import org.apache.commons.collections.set.ListOrderedSet;
-import org.jumpmind.symmetric.db.ddl.Platform;
-import org.jumpmind.symmetric.db.ddl.alteration.AddColumnChange;
-import org.jumpmind.symmetric.db.ddl.alteration.AddPrimaryKeyChange;
-import org.jumpmind.symmetric.db.ddl.alteration.ColumnChange;
-import org.jumpmind.symmetric.db.ddl.alteration.PrimaryKeyChange;
-import org.jumpmind.symmetric.db.ddl.alteration.RemoveColumnChange;
-import org.jumpmind.symmetric.db.ddl.alteration.RemovePrimaryKeyChange;
-import org.jumpmind.symmetric.db.ddl.alteration.TableChange;
-import org.jumpmind.symmetric.db.ddl.model.Column;
-import org.jumpmind.symmetric.db.ddl.model.Database;
-import org.jumpmind.symmetric.db.ddl.model.ForeignKey;
-import org.jumpmind.symmetric.db.ddl.model.Table;
-import org.jumpmind.symmetric.db.ddl.platform.SqlBuilder;
-
-/*
- * The SQL Builder for MySQL.
- *
- * @version $Revision: 518498 $
- */
-public class MySqlBuilder extends SqlBuilder
-{
- /*
- * Creates a new builder instance.
- *
- * @param platform The plaftform this builder belongs to
- */
- public MySqlBuilder(Platform platform)
- {
- super(platform);
- // we need to handle the backslash first otherwise the other
- // already escaped sequences would be affected
- addEscapedCharSequence("\\", "\\\\");
- addEscapedCharSequence("\0", "\\0");
- addEscapedCharSequence("'", "\\'");
- addEscapedCharSequence("\"", "\\\"");
- addEscapedCharSequence("\b", "\\b");
- addEscapedCharSequence("\n", "\\n");
- addEscapedCharSequence("\r", "\\r");
- addEscapedCharSequence("\t", "\\t");
- addEscapedCharSequence("\u001A", "\\Z");
- addEscapedCharSequence("%", "\\%");
- addEscapedCharSequence("_", "\\_");
- }
-
- /*
- * {@inheritDoc}
- */
- public void dropTable(Table table) throws IOException
- {
- print("DROP TABLE IF EXISTS ");
- printIdentifier(getTableName(table));
- printEndOfStatement();
- }
-
- /*
- * {@inheritDoc}
- */
- protected void writeColumnAutoIncrementStmt(Table table, Column column) throws IOException
- {
- print("AUTO_INCREMENT");
- }
-
- /*
- * {@inheritDoc}
- */
- protected boolean shouldGeneratePrimaryKeys(Column[] primaryKeyColumns)
- {
- // mySQL requires primary key indication for autoincrement key columns
- // I'm not sure why the default skips the pk statement if all are identity
- return true;
- }
-
- /*
- * {@inheritDoc}
- * Normally mysql will return the LAST_INSERT_ID as the column name for the inserted id.
- * Since ddlutils expects the real column name of the field that is autoincrementing, the
- * column has an alias of that column name.
- */
- public String getSelectLastIdentityValues(Table table)
- {
- String autoIncrementKeyName = "";
- if (table.getAutoIncrementColumns().length > 0)
- {
- autoIncrementKeyName = table.getAutoIncrementColumns()[0].getName();
- }
- return "SELECT LAST_INSERT_ID() " + autoIncrementKeyName;
- }
-
- /*
- * {@inheritDoc}
- */
- protected void writeTableCreationStmtEnding(Table table, Map parameters) throws IOException
- {
- if (parameters != null)
- {
- print(" ");
- // MySql supports additional table creation options which are appended
- // at the end of the CREATE TABLE statement
- for (Iterator it = parameters.entrySet().iterator(); it.hasNext();)
- {
- Map.Entry entry = (Map.Entry)it.next();
-
- print(entry.getKey().toString());
- if (entry.getValue() != null)
- {
- print("=");
- print(entry.getValue().toString());
- }
- if (it.hasNext())
- {
- print(" ");
- }
- }
- }
- super.writeTableCreationStmtEnding(table, parameters);
- }
-
- /*
- * {@inheritDoc}
- */
- protected void writeExternalForeignKeyDropStmt(Table table, ForeignKey foreignKey) throws IOException
- {
- writeTableAlterStmt(table);
- print("DROP FOREIGN KEY ");
- printIdentifier(getForeignKeyName(table, foreignKey));
- printEndOfStatement();
-
- if (foreignKey.isAutoIndexPresent())
- {
- writeTableAlterStmt(table);
- print("DROP INDEX ");
- printIdentifier(getForeignKeyName(table, foreignKey));
- printEndOfStatement();
- }
- }
-
- /*
- * {@inheritDoc}
- */
- protected void processTableStructureChanges(Database currentModel,
- Database desiredModel,
- Table sourceTable,
- Table targetTable,
- Map parameters,
- List changes) throws IOException
- {
- // in order to utilize the ALTER TABLE ADD COLUMN AFTER statement
- // we have to apply the add column changes in the correct order
- // thus we first gather all add column changes and then execute them
- ArrayList addColumnChanges = new ArrayList();
-
- for (Iterator changeIt = changes.iterator(); changeIt.hasNext();)
- {
- TableChange change = (TableChange)changeIt.next();
-
- if (change instanceof AddColumnChange)
- {
- addColumnChanges.add((AddColumnChange)change);
- changeIt.remove();
- }
- }
- for (Iterator changeIt = addColumnChanges.iterator(); changeIt.hasNext();)
- {
- AddColumnChange addColumnChange = (AddColumnChange)changeIt.next();
-
- processChange(currentModel, desiredModel, addColumnChange);
- changeIt.remove();
- }
-
- ListOrderedSet changedColumns = new ListOrderedSet();
-
- // we don't have to care about the order because the comparator will have ensured
- // that a add primary key change comes after all necessary columns are present
- for (Iterator changeIt = changes.iterator(); changeIt.hasNext();)
- {
- TableChange change = (TableChange)changeIt.next();
-
- if (change instanceof RemoveColumnChange)
- {
- processChange(currentModel, desiredModel, (RemoveColumnChange)change);
- changeIt.remove();
- }
- else if (change instanceof AddPrimaryKeyChange)
- {
- processChange(currentModel, desiredModel, (AddPrimaryKeyChange)change);
- changeIt.remove();
- }
- else if (change instanceof PrimaryKeyChange)
- {
- processChange(currentModel, desiredModel, (PrimaryKeyChange)change);
- changeIt.remove();
- }
- else if (change instanceof RemovePrimaryKeyChange)
- {
- processChange(currentModel, desiredModel, (RemovePrimaryKeyChange)change);
- changeIt.remove();
- }
- else if (change instanceof ColumnChange)
- {
- // we gather all changed columns because we can use the ALTER TABLE MODIFY COLUMN
- // statement for them
- changedColumns.add(((ColumnChange)change).getChangedColumn());
- changeIt.remove();
- }
- }
- for (Iterator columnIt = changedColumns.iterator(); columnIt.hasNext();)
- {
- Column sourceColumn = (Column)columnIt.next();
- Column targetColumn = targetTable.findColumn(sourceColumn.getName(), getPlatform().isDelimitedIdentifierModeOn());
-
- processColumnChange(sourceTable, targetTable, sourceColumn, targetColumn);
- }
- }
-
- /*
- * Processes the addition of a column to a table.
- *
- * @param currentModel The current database schema
- * @param desiredModel The desired database schema
- * @param change The change object
- */
- protected void processChange(Database currentModel,
- Database desiredModel,
- AddColumnChange change) throws IOException
- {
- print("ALTER TABLE ");
- printlnIdentifier(getTableName(change.getChangedTable()));
- printIndent();
- print("ADD COLUMN ");
- writeColumn(change.getChangedTable(), change.getNewColumn());
- if (change.getPreviousColumn() != null)
- {
- print(" AFTER ");
- printIdentifier(getColumnName(change.getPreviousColumn()));
- }
- else
- {
- print(" FIRST");
- }
- printEndOfStatement();
- change.apply(currentModel, getPlatform().isDelimitedIdentifierModeOn());
- }
-
- /*
- * Processes the removal of a column from a table.
- *
- * @param currentModel The current database schema
- * @param desiredModel The desired database schema
- * @param change The change object
- */
- protected void processChange(Database currentModel,
- Database desiredModel,
- RemoveColumnChange change) throws IOException
- {
- print("ALTER TABLE ");
- printlnIdentifier(getTableName(change.getChangedTable()));
- printIndent();
- print("DROP COLUMN ");
- printIdentifier(getColumnName(change.getColumn()));
- printEndOfStatement();
- change.apply(currentModel, getPlatform().isDelimitedIdentifierModeOn());
- }
-
- /*
- * Processes the removal of a primary key from a table.
- *
- * @param currentModel The current database schema
- * @param desiredModel The desired database schema
- * @param change The change object
- */
- protected void processChange(Database currentModel,
- Database desiredModel,
- RemovePrimaryKeyChange change) throws IOException
- {
- print("ALTER TABLE ");
- printlnIdentifier(getTableName(change.getChangedTable()));
- printIndent();
- print("DROP PRIMARY KEY");
- printEndOfStatement();
- change.apply(currentModel, getPlatform().isDelimitedIdentifierModeOn());
- }
-
- /*
- * Processes the change of the primary key of a table.
- *
- * @param currentModel The current database schema
- * @param desiredModel The desired database schema
- * @param change The change object
- */
- protected void processChange(Database currentModel,
- Database desiredModel,
- PrimaryKeyChange change) throws IOException
- {
- print("ALTER TABLE ");
- printlnIdentifier(getTableName(change.getChangedTable()));
- printIndent();
- print("DROP PRIMARY KEY");
- printEndOfStatement();
- writeExternalPrimaryKeysCreateStmt(change.getChangedTable(), change.getNewPrimaryKeyColumns());
- change.apply(currentModel, getPlatform().isDelimitedIdentifierModeOn());
- }
-
- /*
- * Processes a change to a column.
- *
- * @param sourceTable The current table
- * @param targetTable The desired table
- * @param sourceColumn The current column
- * @param targetColumn The desired column
- */
- protected void processColumnChange(Table sourceTable,
- Table targetTable,
- Column sourceColumn,
- Column targetColumn) throws IOException
- {
- print("ALTER TABLE ");
- printlnIdentifier(getTableName(sourceTable));
- printIndent();
- print("MODIFY COLUMN ");
- writeColumn(targetTable, targetColumn);
- printEndOfStatement();
- }
-}
diff --git a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/platform/mysql/MySqlPlatform.java b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/platform/mysql/MySqlPlatform.java
deleted file mode 100644
index f516c69b7f..0000000000
--- a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/platform/mysql/MySqlPlatform.java
+++ /dev/null
@@ -1,102 +0,0 @@
-package org.jumpmind.symmetric.db.ddl.platform.mysql;
-
-/*
- * 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.sql.Types;
-
-import org.jumpmind.symmetric.db.ddl.PlatformInfo;
-import org.jumpmind.symmetric.db.ddl.platform.PlatformImplBase;
-
-/*
- * The platform implementation for MySQL.
- *
- * @version $Revision: 231306 $
- */
-public class MySqlPlatform extends PlatformImplBase
-{
- /* Database name of this platform. */
- public static final String DATABASENAME = "MySQL";
- /* The standard MySQL jdbc driver. */
- public static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
- /* The old MySQL jdbc driver. */
- public static final String JDBC_DRIVER_OLD = "org.gjt.mm.mysql.Driver";
- /* The subprotocol used by the standard MySQL driver. */
- public static final String JDBC_SUBPROTOCOL = "mysql";
-
- /*
- * Creates a new platform instance.
- */
- public MySqlPlatform()
- {
- PlatformInfo info = getPlatformInfo();
-
- info.setMaxIdentifierLength(64);
- info.setNullAsDefaultValueRequired(true);
- info.setDefaultValuesForLongTypesSupported(false);
- // see http://dev.mysql.com/doc/refman/4.1/en/example-auto-increment.html
- info.setNonPKIdentityColumnsSupported(false);
- // MySql returns synthetic default values for pk columns
- info.setSyntheticDefaultValueForRequiredReturned(true);
- info.setCommentPrefix("#");
- // Double quotes are only allowed for delimiting identifiers if the server SQL mode includes ANSI_QUOTES
- info.setDelimiterToken("`");
-
- info.addNativeTypeMapping(Types.ARRAY, "LONGBLOB", Types.LONGVARBINARY);
- info.addNativeTypeMapping(Types.BIT, "TINYINT(1)");
- info.addNativeTypeMapping(Types.BLOB, "LONGBLOB", Types.LONGVARBINARY);
- info.addNativeTypeMapping(Types.CLOB, "LONGTEXT", Types.LONGVARCHAR);
- info.addNativeTypeMapping(Types.DISTINCT, "LONGBLOB", Types.LONGVARBINARY);
- info.addNativeTypeMapping(Types.FLOAT, "DOUBLE", Types.DOUBLE);
- info.addNativeTypeMapping(Types.JAVA_OBJECT, "LONGBLOB", Types.LONGVARBINARY);
- info.addNativeTypeMapping(Types.LONGVARBINARY, "MEDIUMBLOB");
- info.addNativeTypeMapping(Types.LONGVARCHAR, "MEDIUMTEXT");
- info.addNativeTypeMapping(Types.NULL, "MEDIUMBLOB", Types.LONGVARBINARY);
- info.addNativeTypeMapping(Types.NUMERIC, "DECIMAL", Types.DECIMAL);
- info.addNativeTypeMapping(Types.OTHER, "LONGBLOB", Types.LONGVARBINARY);
- info.addNativeTypeMapping(Types.REAL, "FLOAT");
- info.addNativeTypeMapping(Types.REF, "MEDIUMBLOB", Types.LONGVARBINARY);
- info.addNativeTypeMapping(Types.STRUCT, "LONGBLOB", Types.LONGVARBINARY);
- // Since TIMESTAMP is not a stable datatype yet, and does not support a higher precision
- // than DATETIME (year to seconds) as of MySQL 5, we map the JDBC type here to DATETIME
- // TODO: Make this configurable
- info.addNativeTypeMapping(Types.TIMESTAMP, "DATETIME");
- // In MySql, TINYINT has only a range of -128 to 127
- info.addNativeTypeMapping(Types.TINYINT, "SMALLINT", Types.SMALLINT);
- info.addNativeTypeMapping("BOOLEAN", "TINYINT(1)", "BIT");
- info.addNativeTypeMapping("DATALINK", "MEDIUMBLOB", "LONGVARBINARY");
-
- info.setDefaultSize(Types.CHAR, 254);
- info.setDefaultSize(Types.VARCHAR, 254);
- info.setDefaultSize(Types.BINARY, 254);
- info.setDefaultSize(Types.VARBINARY, 254);
-
- setDelimitedIdentifierModeOn(true);
- setSqlBuilder(new MySqlBuilder(this));
- setModelReader(new MySqlModelReader(this));
- }
-
- /*
- * {@inheritDoc}
- */
- public String getName()
- {
- return DATABASENAME;
- }
-}
diff --git a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/platform/oracle/Oracle10Builder.java b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/platform/oracle/Oracle10Builder.java
deleted file mode 100644
index 9ab5712311..0000000000
--- a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/platform/oracle/Oracle10Builder.java
+++ /dev/null
@@ -1,65 +0,0 @@
-package org.jumpmind.symmetric.db.ddl.platform.oracle;
-
-/*
- * 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 org.jumpmind.symmetric.db.ddl.Platform;
-import org.jumpmind.symmetric.db.ddl.model.Column;
-import org.jumpmind.symmetric.db.ddl.model.Table;
-
-/*
- * The SQL builder for Oracle 10.
- *
- * @version $Revision: $
- */
-public class Oracle10Builder extends Oracle8Builder
-{
- /*
- * Creates a new builder instance.
- *
- * @param platform The plaftform this builder belongs to
- */
- public Oracle10Builder(Platform platform)
- {
- super(platform);
- }
-
- /*
- * {@inheritDoc}
- */
- public void dropTable(Table table) throws IOException
- {
- // The only difference to the Oracle 8/9 variant is the purge which prevents the
- // table from being moved to the recycle bin (which is new in Oracle 10)
- Column[] columns = table.getAutoIncrementColumns();
-
- for (int idx = 0; idx < columns.length; idx++)
- {
- dropAutoIncrementTrigger(table, columns[idx]);
- dropAutoIncrementSequence(table, columns[idx]);
- }
-
- print("DROP TABLE ");
- printIdentifier(getTableName(table));
- print(" CASCADE CONSTRAINTS PURGE");
- printEndOfStatement();
- }
-}
diff --git a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/platform/oracle/Oracle10Platform.java b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/platform/oracle/Oracle10Platform.java
deleted file mode 100644
index b46cd856de..0000000000
--- a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/platform/oracle/Oracle10Platform.java
+++ /dev/null
@@ -1,48 +0,0 @@
-package org.jumpmind.symmetric.db.ddl.platform.oracle;
-
-
-/*
- * 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.
- */
-
-/*
- * The platform for Oracle 10.
- */
-public class Oracle10Platform extends Oracle9Platform
-{
- /* Database name of this platform. */
- public static final String DATABASENAME10 = "Oracle10";
- public static final String DATABASENAME11 = "Oracle11";
-
- /*
- * Creates a new platform instance.
- */
- public Oracle10Platform()
- {
- super();
- setSqlBuilder(new Oracle10Builder(this));
- }
-
- /*
- * {@inheritDoc}
- */
- public String getName()
- {
- return DATABASENAME;
- }
-}
diff --git a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/platform/oracle/Oracle8Builder.java b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/platform/oracle/Oracle8Builder.java
deleted file mode 100644
index c56eaa64fe..0000000000
--- a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/platform/oracle/Oracle8Builder.java
+++ /dev/null
@@ -1,524 +0,0 @@
-package org.jumpmind.symmetric.db.ddl.platform.oracle;
-
-/*
- * 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.sql.Types;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-
-import org.apache.oro.text.regex.MalformedPatternException;
-import org.apache.oro.text.regex.Pattern;
-import org.apache.oro.text.regex.PatternCompiler;
-import org.apache.oro.text.regex.Perl5Compiler;
-import org.apache.oro.text.regex.Perl5Matcher;
-import org.jumpmind.symmetric.db.ddl.DdlUtilsException;
-import org.jumpmind.symmetric.db.ddl.Platform;
-import org.jumpmind.symmetric.db.ddl.alteration.AddColumnChange;
-import org.jumpmind.symmetric.db.ddl.alteration.AddPrimaryKeyChange;
-import org.jumpmind.symmetric.db.ddl.alteration.PrimaryKeyChange;
-import org.jumpmind.symmetric.db.ddl.alteration.RemoveColumnChange;
-import org.jumpmind.symmetric.db.ddl.alteration.RemovePrimaryKeyChange;
-import org.jumpmind.symmetric.db.ddl.alteration.TableChange;
-import org.jumpmind.symmetric.db.ddl.model.Column;
-import org.jumpmind.symmetric.db.ddl.model.Database;
-import org.jumpmind.symmetric.db.ddl.model.Index;
-import org.jumpmind.symmetric.db.ddl.model.Table;
-import org.jumpmind.symmetric.db.ddl.model.TypeMap;
-import org.jumpmind.symmetric.db.ddl.platform.SqlBuilder;
-import org.jumpmind.symmetric.db.ddl.util.Jdbc3Utils;
-
-/*
- * The SQL Builder for Oracle.
- *
- * @version $Revision: 517050 $
- */
-public class Oracle8Builder extends SqlBuilder
-{
- /* The regular expression pattern for ISO dates, i.e. 'YYYY-MM-DD'. */
- private Pattern _isoDatePattern;
- /* The regular expression pattern for ISO times, i.e. 'HH:MI:SS'. */
- private Pattern _isoTimePattern;
- /* The regular expression pattern for ISO timestamps, i.e. 'YYYY-MM-DD HH:MI:SS.fffffffff'. */
- private Pattern _isoTimestampPattern;
-
- /*
- * Creates a new builder instance.
- *
- * @param platform The plaftform this builder belongs to
- */
- public Oracle8Builder(Platform platform)
- {
- super(platform);
- addEscapedCharSequence("'", "''");
-
- PatternCompiler compiler = new Perl5Compiler();
-
- try
- {
- _isoDatePattern = compiler.compile("\\d{4}\\-\\d{2}\\-\\d{2}");
- _isoTimePattern = compiler.compile("\\d{2}:\\d{2}:\\d{2}");
- _isoTimestampPattern = compiler.compile("\\d{4}\\-\\d{2}\\-\\d{2} \\d{2}:\\d{2}:\\d{2}[\\.\\d{1,8}]?");
- }
- catch (MalformedPatternException ex)
- {
- throw new DdlUtilsException(ex);
- }
- }
-
- /*
- * {@inheritDoc}
- */
- public void createTable(Database database, Table table, Map parameters) throws IOException
- {
- // lets create any sequences
- Column[] columns = table.getAutoIncrementColumns();
-
- for (int idx = 0; idx < columns.length; idx++)
- {
- createAutoIncrementSequence(table, columns[idx]);
- }
-
- super.createTable(database, table, parameters);
-
- for (int idx = 0; idx < columns.length; idx++)
- {
- createAutoIncrementTrigger(table, columns[idx]);
- }
- }
-
- /*
- * {@inheritDoc}
- */
- public void dropTable(Table table) throws IOException
- {
- Column[] columns = table.getAutoIncrementColumns();
-
- for (int idx = 0; idx < columns.length; idx++)
- {
- dropAutoIncrementTrigger(table, columns[idx]);
- dropAutoIncrementSequence(table, columns[idx]);
- }
-
- print("DROP TABLE ");
- printIdentifier(getTableName(table));
- print(" CASCADE CONSTRAINTS");
- printEndOfStatement();
- }
-
- /*
- * Creates the sequence necessary for the auto-increment of the given column.
- *
- * @param table The table
- * @param column The column
- */
- protected void createAutoIncrementSequence(Table table,
- Column column) throws IOException
- {
- print("CREATE SEQUENCE ");
- printIdentifier(getConstraintName("seq", table, column.getName(), null));
- printEndOfStatement();
- }
-
- /*
- * Creates the trigger necessary for the auto-increment of the given column.
- *
- * @param table The table
- * @param column The column
- */
- protected void createAutoIncrementTrigger(Table table,
- Column column) throws IOException
- {
- String columnName = getColumnName(column);
- String triggerName = getConstraintName("trg", table, column.getName(), null);
-
- if (getPlatform().isScriptModeOn())
- {
- // For the script, we output a more nicely formatted version
- print("CREATE OR REPLACE TRIGGER ");
- printlnIdentifier(triggerName);
- print("BEFORE INSERT ON ");
- printlnIdentifier(getTableName(table));
- print("FOR EACH ROW WHEN (new.");
- printIdentifier(columnName);
- println(" IS NULL)");
- println("BEGIN");
- print(" SELECT ");
- printIdentifier(getConstraintName("seq", table, column.getName(), null));
- print(".nextval INTO :new.");
- printIdentifier(columnName);
- print(" FROM dual");
- println(getPlatformInfo().getSqlCommandDelimiter());
- print("END");
- println(getPlatformInfo().getSqlCommandDelimiter());
- println("/");
- println();
- }
- else
- {
- // note that the BEGIN ... SELECT ... END; is all in one line and does
- // not contain a semicolon except for the END-one
- // this way, the tokenizer will not split the statement before the END
- print("CREATE OR REPLACE TRIGGER ");
- printIdentifier(triggerName);
- print(" BEFORE INSERT ON ");
- printIdentifier(getTableName(table));
- print(" FOR EACH ROW WHEN (new.");
- printIdentifier(columnName);
- println(" IS NULL)");
- print("BEGIN SELECT ");
- printIdentifier(getConstraintName("seq", table, column.getName(), null));
- print(".nextval INTO :new.");
- printIdentifier(columnName);
- print(" FROM dual");
- print(getPlatformInfo().getSqlCommandDelimiter());
- print(" END");
- // It is important that there is a semicolon at the end of the statement (or more
- // precisely, at the end of the PL/SQL block), and thus we put two semicolons here
- // because the tokenizer will remove the one at the end
- print(getPlatformInfo().getSqlCommandDelimiter());
- printEndOfStatement();
- }
- }
-
- /*
- * Drops the sequence used for the auto-increment of the given column.
- *
- * @param table The table
- * @param column The column
- */
- protected void dropAutoIncrementSequence(Table table,
- Column column) throws IOException
- {
- print("DROP SEQUENCE ");
- printIdentifier(getConstraintName("seq", table, column.getName(), null));
- printEndOfStatement();
- }
-
- /*
- * Drops the trigger used for the auto-increment of the given column.
- *
- * @param table The table
- * @param column The column
- */
- protected void dropAutoIncrementTrigger(Table table,
- Column column) throws IOException
- {
- print("DROP TRIGGER ");
- printIdentifier(getConstraintName("trg", table, column.getName(), null));
- printEndOfStatement();
- }
-
- /*
- * {@inheritDoc}
- */
- protected void createTemporaryTable(Database database, Table table, Map parameters) throws IOException
- {
- createTable(database, table, parameters);
- }
-
- /*
- * {@inheritDoc}
- */
- protected void dropTemporaryTable(Database database, Table table) throws IOException
- {
- dropTable(table);
- }
-
- /*
- * {@inheritDoc}
- */
- public void dropExternalForeignKeys(Table table) throws IOException
- {
- // no need to as we drop the table with CASCASE CONSTRAINTS
- }
-
- /*
- * {@inheritDoc}
- */
- public void writeExternalIndexDropStmt(Table table, Index index) throws IOException
- {
- // Index names in Oracle are unique to a schema and hence Oracle does not
- // use the ON true
if the column is an identity column
- */
- protected boolean isAutoIncrement(Connection connection, Table table, Column column) throws SQLException
- {
- // TODO: For now, we only check whether there is a sequence & trigger as generated by DdlUtils
- // But once sequence/trigger support is in place, it might be possible to 'parse' the
- // trigger body (via SELECT trigger_name, trigger_body FROM user_triggers) in order to
- // determine whether it fits our auto-increment definition
- PreparedStatement prepStmt = null;
- String triggerName = getPlatform().getSqlBuilder().getConstraintName("trg", table, column.getName(), null);
- String seqName = getPlatform().getSqlBuilder().getConstraintName("seq", table, column.getName(), null);
-
- if (!getPlatform().isDelimitedIdentifierModeOn())
- {
- triggerName = triggerName.toUpperCase();
- seqName = seqName.toUpperCase();
- }
- try
- {
- prepStmt = connection.prepareStatement("SELECT * FROM user_triggers WHERE trigger_name = ?");
- prepStmt.setString(1, triggerName);
-
- ResultSet resultSet = prepStmt.executeQuery();
-
- if (!resultSet.next())
- {
- return false;
- }
- // we have a trigger, so lets check the sequence
- prepStmt.close();
-
- prepStmt = connection.prepareStatement("SELECT * FROM user_sequences WHERE sequence_name = ?");
- prepStmt.setString(1, seqName);
-
- resultSet = prepStmt.executeQuery();
- return resultSet.next();
- }
- finally
- {
- if (prepStmt != null)
- {
- prepStmt.close();
- }
- }
- }
-
- @Override
- protected Collection readIndices(Connection connection, DatabaseMetaDataWrapper metaData, String tableName) throws SQLException
- {
- // Oracle bug 4999817 causes a table analyze to execute in response to a call to
- // DatabaseMetaData#getIndexInfo.
- // The bug is fixed in driver version 10.2.0.4. The bug is present in at least
- // driver versions 10.2.0.1.0, 10.1.0.2.0, and 9.2.0.5.
- // To avoid this bug, we will access user_indexes view.
- // This also allows us to filter system-generated indices which are identified by either
- // having GENERATED='Y' in the query result, or by their index names being equal to the
- // name of the primary key of the table
-
- StringBuffer query = new StringBuffer();
-
- query.append("SELECT a.INDEX_NAME, a.INDEX_TYPE, a.UNIQUENESS, b.COLUMN_NAME, b.COLUMN_POSITION FROM USER_INDEXES a, USER_IND_COLUMNS b WHERE ");
- query.append("a.TABLE_NAME=? AND a.GENERATED=? AND a.TABLE_TYPE=? AND a.TABLE_NAME=b.TABLE_NAME AND a.INDEX_NAME=b.INDEX_NAME AND ");
- query.append("a.INDEX_NAME NOT IN (SELECT DISTINCT c.CONSTRAINT_NAME FROM USER_CONSTRAINTS c WHERE c.CONSTRAINT_TYPE=? AND c.TABLE_NAME=a.TABLE_NAME");
- if (metaData.getSchemaPattern() != null)
- {
- query.append(" AND c.OWNER LIKE ?) AND a.TABLE_OWNER LIKE ?");
- }
- else
- {
- query.append(")");
- }
-
- Map indices = new ListOrderedMap();
- PreparedStatement stmt = null;
-
- try
- {
- stmt = connection.prepareStatement(query.toString());
- stmt.setString(1, getPlatform().isDelimitedIdentifierModeOn() ? tableName : tableName.toUpperCase());
- stmt.setString(2, "N");
- stmt.setString(3, "TABLE");
- stmt.setString(4, "P");
- if (metaData.getSchemaPattern() != null)
- {
- stmt.setString(5, metaData.getSchemaPattern().toUpperCase());
- stmt.setString(6, metaData.getSchemaPattern().toUpperCase());
- }
-
- ResultSet rs = stmt.executeQuery();
- Map values = new HashMap();
-
- while (rs.next())
- {
- String name =rs.getString(1);
- String type = rs.getString(2);
- // Only read in normal oracle indexes
- if (type.startsWith("NORMAL"))
- {
- values.put("INDEX_TYPE", new Short(DatabaseMetaData.tableIndexOther));
- values.put("INDEX_NAME", name);
- values.put("NON_UNIQUE", "UNIQUE".equalsIgnoreCase(rs.getString(3)) ? Boolean.FALSE : Boolean.TRUE);
- values.put("COLUMN_NAME", rs.getString(4));
- values.put("ORDINAL_POSITION", new Short(rs.getShort(5)));
-
- readIndex(metaData, values, indices);
- } else {
- _log.warn("Skipping index " + name + " of type " + type);
- }
- }
- }
- finally
- {
- if (stmt != null)
- {
- stmt.close();
- }
- }
- return indices.values();
- }
-}
diff --git a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/platform/postgresql/PostgreSqlPlatform.java b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/platform/postgresql/PostgreSqlPlatform.java
deleted file mode 100644
index ac4c133db3..0000000000
--- a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/platform/postgresql/PostgreSqlPlatform.java
+++ /dev/null
@@ -1,213 +0,0 @@
-package org.jumpmind.symmetric.db.ddl.platform.postgresql;
-
-/*
- * 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.sql.Connection;
-import java.sql.DriverManager;
-import java.sql.SQLException;
-import java.sql.Statement;
-import java.sql.Types;
-import java.util.Iterator;
-import java.util.Map;
-
-import org.jumpmind.symmetric.db.ddl.DatabaseOperationException;
-import org.jumpmind.symmetric.db.ddl.PlatformInfo;
-import org.jumpmind.symmetric.db.ddl.platform.PlatformImplBase;
-
-/*
- * The platform implementation for PostgresSql.
- *
- * @version $Revision: 231306 $
- */
-public class PostgreSqlPlatform extends PlatformImplBase
-{
- /* Database name of this platform. */
- public static final String DATABASENAME = "PostgreSql";
- /* The standard PostgreSQL jdbc driver. */
- public static final String JDBC_DRIVER = "org.postgresql.Driver";
- /* The subprotocol used by the standard PostgreSQL driver. */
- public static final String JDBC_SUBPROTOCOL = "postgresql";
-
- /*
- * Creates a new platform instance.
- */
- public PostgreSqlPlatform()
- {
- PlatformInfo info = getPlatformInfo();
-
- // this is the default length though it might be changed when building PostgreSQL
- // in file src/include/postgres_ext.h
- info.setMaxIdentifierLength(31);
-
- info.addNativeTypeMapping(Types.ARRAY, "BYTEA", Types.LONGVARBINARY);
- info.addNativeTypeMapping(Types.BINARY, "BYTEA", Types.LONGVARBINARY);
- info.addNativeTypeMapping(Types.BIT, "BOOLEAN");
- info.addNativeTypeMapping(Types.BLOB, "BYTEA", Types.LONGVARBINARY);
- info.addNativeTypeMapping(Types.CLOB, "TEXT", Types.LONGVARCHAR);
- info.addNativeTypeMapping(Types.DECIMAL, "NUMERIC", Types.NUMERIC);
- info.addNativeTypeMapping(Types.DISTINCT, "BYTEA", Types.LONGVARBINARY);
- info.addNativeTypeMapping(Types.DOUBLE, "DOUBLE PRECISION");
- info.addNativeTypeMapping(Types.FLOAT, "DOUBLE PRECISION", Types.DOUBLE);
- info.addNativeTypeMapping(Types.JAVA_OBJECT, "BYTEA", Types.LONGVARBINARY);
- info.addNativeTypeMapping(Types.LONGVARBINARY, "BYTEA");
- info.addNativeTypeMapping(Types.LONGVARCHAR, "TEXT", Types.LONGVARCHAR);
- info.addNativeTypeMapping(Types.NULL, "BYTEA", Types.LONGVARBINARY);
- info.addNativeTypeMapping(Types.OTHER, "BYTEA", Types.LONGVARBINARY);
- info.addNativeTypeMapping(Types.REF, "BYTEA", Types.LONGVARBINARY);
- info.addNativeTypeMapping(Types.STRUCT, "BYTEA", Types.LONGVARBINARY);
- info.addNativeTypeMapping(Types.TINYINT, "SMALLINT", Types.SMALLINT);
- info.addNativeTypeMapping(Types.VARBINARY, "BYTEA", Types.LONGVARBINARY);
- info.addNativeTypeMapping("BOOLEAN", "BOOLEAN", "BIT");
- info.addNativeTypeMapping("DATALINK", "BYTEA", "LONGVARBINARY");
-
- info.setDefaultSize(Types.CHAR, 254);
- info.setDefaultSize(Types.VARCHAR, 254);
-
- // no support for specifying the size for these types (because they are mapped
- // to BYTEA which back-maps to BLOB)
- info.setHasSize(Types.BINARY, false);
- info.setHasSize(Types.VARBINARY, false);
-
- setDelimitedIdentifierModeOn(true);
-
- setSqlBuilder(new PostgreSqlBuilder(this));
- setModelReader(new PostgreSqlModelReader(this));
- }
-
- /*
- * {@inheritDoc}
- */
- public String getName()
- {
- return DATABASENAME;
- }
-
- /*
- * Creates or drops the database referenced by the given connection url.
- *
- * @param jdbcDriverClassName The jdbc driver class name
- * @param connectionUrl The url to connect to the database if it were already created
- * @param username The username for creating the database
- * @param password The password for creating the database
- * @param parameters Additional parameters for the operation
- * @param createDb Whether to create or drop the database
- */
- private void createOrDropDatabase(String jdbcDriverClassName, String connectionUrl, String username, String password, Map parameters, boolean createDb) throws DatabaseOperationException, UnsupportedOperationException
- {
- if (JDBC_DRIVER.equals(jdbcDriverClassName))
- {
- int slashPos = connectionUrl.lastIndexOf('/');
-
- if (slashPos < 0)
- {
- throw new DatabaseOperationException("Cannot parse the given connection url "+connectionUrl);
- }
-
- int paramPos = connectionUrl.lastIndexOf('?');
- String baseDb = connectionUrl.substring(0, slashPos + 1) + "template1";
- String dbName = (paramPos > slashPos ? connectionUrl.substring(slashPos + 1, paramPos) : connectionUrl.substring(slashPos + 1));
- Connection connection = null;
- Statement stmt = null;
- StringBuffer sql = new StringBuffer();
-
- sql.append(createDb ? "CREATE" : "DROP");
- sql.append(" DATABASE ");
- sql.append(dbName);
- if ((parameters != null) && !parameters.isEmpty())
- {
- for (Iterator it = parameters.entrySet().iterator(); it.hasNext();)
- {
- Map.Entry entry = (Map.Entry)it.next();
-
- sql.append(" ");
- sql.append(entry.getKey().toString());
- if (entry.getValue() != null)
- {
- sql.append(" ");
- sql.append(entry.getValue().toString());
- }
- }
- }
- if (getLog().isDebugEnabled())
- {
- getLog().debug("About to create database via "+baseDb+" using this SQL: "+sql.toString());
- }
- try
- {
- Class.forName(jdbcDriverClassName);
-
- connection = DriverManager.getConnection(baseDb, username, password);
- stmt = connection.createStatement();
- stmt.execute(sql.toString());
- logWarnings(connection);
- }
- catch (Exception ex)
- {
- throw new DatabaseOperationException("Error while trying to " + (createDb ? "create" : "drop") + " a database: "+ex.getLocalizedMessage(), ex);
- }
- finally
- {
- if (stmt != null)
- {
- try
- {
- stmt.close();
- }
- catch (SQLException ex)
- {}
- }
- if (connection != null)
- {
- try
- {
- connection.close();
- }
- catch (SQLException ex)
- {}
- }
- }
- }
- else
- {
- throw new UnsupportedOperationException("Unable to " + (createDb ? "create" : "drop") + " a PostgreSQL database via the driver "+jdbcDriverClassName);
- }
- }
-
- /*
- * {@inheritDoc}
- */
- public void createDatabase(String jdbcDriverClassName, String connectionUrl, String username, String password, Map parameters) throws DatabaseOperationException, UnsupportedOperationException
- {
- // With PostgreSQL, you create a database by executing "CREATE DATABASE" in an existing database (usually
- // the template1 database because it usually exists)
- createOrDropDatabase(jdbcDriverClassName, connectionUrl, username, password, parameters, true);
- }
-
- /*
- * {@inheritDoc}
- */
- public void dropDatabase(String jdbcDriverClassName, String connectionUrl, String username, String password) throws DatabaseOperationException, UnsupportedOperationException
- {
- // With PostgreSQL, you create a database by executing "DROP DATABASE" in an existing database (usually
- // the template1 database because it usually exists)
- createOrDropDatabase(jdbcDriverClassName, connectionUrl, username, password, null, false);
- }
-
-}
diff --git a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/platform/sybase/SybaseASE15Platform.java b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/platform/sybase/SybaseASE15Platform.java
deleted file mode 100644
index 94aa205d16..0000000000
--- a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/platform/sybase/SybaseASE15Platform.java
+++ /dev/null
@@ -1,47 +0,0 @@
-package org.jumpmind.symmetric.db.ddl.platform.sybase;
-
-/*
- * 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.
- */
-
-/*
- * The platform implementation for Sybase ASE 15 and above.
- *
- * @version $Revision: $
- */
-public class SybaseASE15Platform extends SybasePlatform
-{
- /* Database name of this platform. */
- public static final String DATABASENAME = "SybaseASE15";
-
- /*
- * Creates a new platform instance.
- */
- public SybaseASE15Platform()
- {
- super();
- }
-
- /*
- * {@inheritDoc}
- */
- public String getName()
- {
- return DATABASENAME;
- }
-}
diff --git a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/platform/sybase/SybasePlatform.java b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/platform/sybase/SybasePlatform.java
deleted file mode 100644
index 992de34826..0000000000
--- a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/platform/sybase/SybasePlatform.java
+++ /dev/null
@@ -1,296 +0,0 @@
-package org.jumpmind.symmetric.db.ddl.platform.sybase;
-
-/*
- * 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.ByteArrayInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.sql.Connection;
-import java.sql.PreparedStatement;
-import java.sql.ResultSet;
-import java.sql.SQLException;
-import java.sql.Statement;
-import java.sql.Types;
-
-import org.jumpmind.symmetric.db.ddl.DatabaseOperationException;
-import org.jumpmind.symmetric.db.ddl.PlatformInfo;
-import org.jumpmind.symmetric.db.ddl.model.Table;
-import org.jumpmind.symmetric.db.ddl.model.TypeMap;
-import org.jumpmind.symmetric.db.ddl.platform.PlatformImplBase;
-
-/*
- * The platform implementation for Sybase.
- *
- * @version $Revision: 231306 $
- */
-public class SybasePlatform extends PlatformImplBase
-{
- /* Database name of this platform. */
- public static final String DATABASENAME = "Sybase";
- /* The standard Sybase jdbc driver. */
- public static final String JDBC_DRIVER = "com.sybase.jdbc2.jdbc.SybDriver";
- /* The old Sybase jdbc driver. */
- public static final String JDBC_DRIVER_OLD = "com.sybase.jdbc.SybDriver";
- /* The subprotocol used by the standard Sybase driver. */
- public static final String JDBC_SUBPROTOCOL = "sybase:Tds";
-
- /* The maximum size that text and binary columns can have. */
- public static final long MAX_TEXT_SIZE = 2147483647;
-
- /*
- * Creates a new platform instance.
- */
- public SybasePlatform()
- {
- PlatformInfo info = getPlatformInfo();
-
- info.setMaxIdentifierLength(128);
- info.setNullAsDefaultValueRequired(true);
- info.setCommentPrefix("/*");
- info.setCommentSuffix("*/");
- info.setDelimiterToken("\"");
- setDelimitedIdentifierModeOn(true);
-
- info.addNativeTypeMapping(Types.ARRAY, "IMAGE");
- // BIGINT is mapped back in the model reader
- info.addNativeTypeMapping(Types.BIGINT, "DECIMAL(19,0)");
- // we're not using the native BIT type because it is rather limited (cannot be NULL, cannot be indexed)
- info.addNativeTypeMapping(Types.BIT, "SMALLINT", Types.SMALLINT);
- info.addNativeTypeMapping(Types.BLOB, "IMAGE", Types.LONGVARBINARY);
- info.addNativeTypeMapping(Types.CLOB, "TEXT", Types.LONGVARCHAR);
- info.addNativeTypeMapping(Types.DATE, "DATETIME", Types.TIMESTAMP);
- info.addNativeTypeMapping(Types.DISTINCT, "IMAGE", Types.LONGVARBINARY);
- info.addNativeTypeMapping(Types.DOUBLE, "DOUBLE PRECISION");
- info.addNativeTypeMapping(Types.FLOAT, "DOUBLE PRECISION", Types.DOUBLE);
- info.addNativeTypeMapping(Types.INTEGER, "INT");
- info.addNativeTypeMapping(Types.JAVA_OBJECT, "IMAGE", Types.LONGVARBINARY);
- info.addNativeTypeMapping(Types.LONGVARBINARY, "IMAGE");
- info.addNativeTypeMapping(Types.LONGVARCHAR, "TEXT");
- info.addNativeTypeMapping(Types.NULL, "IMAGE", Types.LONGVARBINARY);
- info.addNativeTypeMapping(Types.OTHER, "IMAGE", Types.LONGVARBINARY);
- info.addNativeTypeMapping(Types.REF, "IMAGE", Types.LONGVARBINARY);
- info.addNativeTypeMapping(Types.STRUCT, "IMAGE", Types.LONGVARBINARY);
- info.addNativeTypeMapping(Types.TIME, "DATETIME", Types.TIMESTAMP);
- info.addNativeTypeMapping(Types.TIMESTAMP, "DATETIME", Types.TIMESTAMP);
- info.addNativeTypeMapping(Types.TINYINT, "SMALLINT", Types.SMALLINT);
- info.addNativeTypeMapping("BOOLEAN", "SMALLINT", "SMALLINT");
- info.addNativeTypeMapping("DATALINK", "IMAGE", "LONGVARBINARY");
-
- info.setDefaultSize(Types.BINARY, 254);
- info.setDefaultSize(Types.VARBINARY, 254);
- info.setDefaultSize(Types.CHAR, 254);
- info.setDefaultSize(Types.VARCHAR, 254);
-
- setSqlBuilder(new SybaseBuilder(this));
- setModelReader(new SybaseModelReader(this));
- }
-
- /*
- * {@inheritDoc}
- */
- public String getName()
- {
- return DATABASENAME;
- }
-
- /*
- * Sets the text size which is the maximum amount of bytes that Sybase returns in a SELECT statement
- * for binary/text columns (e.g. blob, longvarchar etc.).
- *
- * @param size The size to set
- */
- private void setTextSize(long size)
- {
- Connection connection = borrowConnection();
- Statement stmt = null;
-
- try
- {
- stmt = connection.createStatement();
-
- stmt.execute("SET textsize "+size);
- }
- catch (SQLException ex)
- {
- throw new DatabaseOperationException(ex);
- }
- finally
- {
- closeStatement(stmt);
- returnConnection(connection);
- }
- }
-
- /*
- * {@inheritDoc}
- */
- protected Object extractColumnValue(ResultSet resultSet, String columnName, int columnIdx, int jdbcType) throws DatabaseOperationException, SQLException
- {
- boolean useIdx = (columnName == null);
-
- if ((jdbcType == Types.LONGVARBINARY) || (jdbcType == Types.BLOB))
- {
- InputStream stream = useIdx ? resultSet.getBinaryStream(columnIdx) : resultSet.getBinaryStream(columnName);
-
- if (stream == null)
- {
- return null;
- }
- else
- {
- byte[] buf = new byte[65536];
- byte[] result = new byte[0];
- int len;
-
- try
- {
- do
- {
- len = stream.read(buf);
- if (len > 0)
- {
- byte[] newResult = new byte[result.length + len];
-
- System.arraycopy(result, 0, newResult, 0, result.length);
- System.arraycopy(buf, 0, newResult, result.length, len);
- result = newResult;
- }
- }
- while (len > 0);
- stream.close();
- return result;
- }
- catch (IOException ex)
- {
- throw new DatabaseOperationException("Error while extracting the value of column " + columnName + " of type " +
- TypeMap.getJdbcTypeName(jdbcType) + " from a result set", ex);
- }
- }
- }
- else
- {
- return super.extractColumnValue(resultSet, columnName, columnIdx, jdbcType);
- }
- }
-
- /*
- * {@inheritDoc}
- */
- protected void setStatementParameterValue(PreparedStatement statement, int sqlIndex, int typeCode, Object value) throws SQLException
- {
- if ((typeCode == Types.BLOB) || (typeCode == Types.LONGVARBINARY))
- {
- // jConnect doesn't like the BLOB type, but works without problems with LONGVARBINARY
- // even when using the Blob class
- if (value instanceof byte[])
- {
- byte[] data = (byte[])value;
-
- statement.setBinaryStream(sqlIndex, new ByteArrayInputStream(data), data.length);
- }
- else
- {
- // Sybase doesn't like the BLOB type, but works without problems with LONGVARBINARY
- // even when using the Blob class
- super.setStatementParameterValue(statement, sqlIndex, Types.LONGVARBINARY, value);
- }
- }
- else if (typeCode == Types.CLOB)
- {
- // Same for CLOB and LONGVARCHAR
- super.setStatementParameterValue(statement, sqlIndex, Types.LONGVARCHAR, value);
- }
- else
- {
- super.setStatementParameterValue(statement, sqlIndex, typeCode, value);
- }
- }
-
- /*
- * Determines whether we need to use identity override mode for the given table.
- *
- * @param table The table
- * @return true
if identity override mode is needed
- */
- private boolean useIdentityOverrideFor(Table table)
- {
- return isIdentityOverrideOn() &&
- getPlatformInfo().isIdentityOverrideAllowed() &&
- (table.getAutoIncrementColumns().length > 0);
- }
-
- /*
- * {@inheritDoc}
- */
- protected void beforeInsert(Connection connection, Table table) throws SQLException
- {
- if (useIdentityOverrideFor(table))
- {
- SybaseBuilder builder = (SybaseBuilder)getSqlBuilder();
- String quotationOn = builder.getQuotationOnStatement();
- String identityInsertOn = builder.getEnableIdentityOverrideSql(table);
- Statement stmt = connection.createStatement();
-
- if (quotationOn.length() > 0)
- {
- stmt.execute(quotationOn);
- }
- stmt.execute(identityInsertOn);
- stmt.close();
- }
- }
-
- /*
- * {@inheritDoc}
- */
- protected void afterInsert(Connection connection, Table table) throws SQLException
- {
- if (useIdentityOverrideFor(table))
- {
- SybaseBuilder builder = (SybaseBuilder)getSqlBuilder();
- String quotationOn = builder.getQuotationOnStatement();
- String identityInsertOff = builder.getDisableIdentityOverrideSql(table);
- Statement stmt = connection.createStatement();
-
- if (quotationOn.length() > 0)
- {
- stmt.execute(quotationOn);
- }
- stmt.execute(identityInsertOff);
- stmt.close();
- }
- }
-
- /*
- * {@inheritDoc}
- */
- protected void beforeUpdate(Connection connection, Table table) throws SQLException
- {
- beforeInsert(connection, table);
- }
-
- /*
- * {@inheritDoc}
- */
- protected void afterUpdate(Connection connection, Table table) throws SQLException
- {
- afterInsert(connection, table);
- }
-}
diff --git a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/util/JdbcSupport.java b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/util/JdbcSupport.java
deleted file mode 100644
index 75b9b751e5..0000000000
--- a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/util/JdbcSupport.java
+++ /dev/null
@@ -1,220 +0,0 @@
-package org.jumpmind.symmetric.db.ddl.util;
-
-/*
- * 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.sql.Connection;
-import java.sql.SQLException;
-import java.sql.Statement;
-import java.util.HashSet;
-import java.util.Iterator;
-
-import javax.sql.DataSource;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.jumpmind.symmetric.db.ddl.DatabaseOperationException;
-
-/**
- * JdbcSupport is an abstract base class for objects which need to
- * perform JDBC operations. It contains a number of useful methods
- * for implementation inheritence..
- *
- * @version $Revision: 463757 $
- */
-public abstract class JdbcSupport
-{
- /** The Log to which logging calls will be made. */
- private final Log _log = LogFactory.getLog(JdbcSupport.class);
- /** The data source. */
- private DataSource _dataSource;
- /** The username for accessing the database. */
- private String _username;
- /** The password for accessing the database. */
- private String _password;
- /** The names of the currently borrowed connections (for debugging). */
- private HashSet _openConnectionNames = new HashSet();
-
- // Properties
- //-------------------------------------------------------------------------
-
- /**
- * Returns the data source used for communicating with the database.
- *
- * @return The data source
- */
- public DataSource getDataSource()
- {
- return _dataSource;
- }
-
- /**
- * Sets the DataSource used for communicating with the database.
- *
- * @param dataSource The data source
- */
- public void setDataSource(DataSource dataSource)
- {
- _dataSource = dataSource;
- }
-
-
- /**
- * Returns the username used to access the database.
- *
- * @return The username
- */
- public String getUsername()
- {
- return _username;
- }
-
- /**
- * Sets the username to be used to access the database.
- *
- * @param username The username
- */
- public void setUsername(String username)
- {
- _username = username;
- }
-
- /**
- * Returns the password used to access the database.
- *
- * @return The password
- */
- public String getPassword()
- {
- return _password;
- }
-
- /**
- * Sets the password to be used to access the database.
- *
- * @param password The password
- */
- public void setPassword(String password)
- {
- _password = password;
- }
-
- // Implementation methods
- //-------------------------------------------------------------------------
-
- /**
- * Returns a (new) JDBC connection from the data source.
- *
- * @return The connection
- */
- public Connection borrowConnection() throws DatabaseOperationException
- {
- try
- {
- Connection connection = null;
-
- if (_username == null)
- {
- connection = getDataSource().getConnection();
- }
- else
- {
- connection = getDataSource().getConnection(_username, _password);
- }
- if (_log.isDebugEnabled())
- {
- String connName = connection.toString();
-
- _log.debug("Borrowed connection "+connName+" from data source");
- _openConnectionNames.add(connName);
- }
- return connection;
- }
- catch (SQLException ex)
- {
- throw new DatabaseOperationException("Could not get a connection from the datasource", ex);
- }
- }
-
- /**
- * Closes the given JDBC connection (returns it back to the pool if the datasource is poolable).
- *
- * @param connection The connection
- */
- public void returnConnection(Connection connection)
- {
- try
- {
- if ((connection != null) && !connection.isClosed())
- {
- if (_log.isDebugEnabled())
- {
- String connName = connection.toString();
-
- _openConnectionNames.remove(connName);
-
- StringBuffer logMsg = new StringBuffer();
-
- logMsg.append("Returning connection ");
- logMsg.append(connName);
- logMsg.append(" to data source.\nRemaining connections:");
- if (_openConnectionNames.isEmpty())
- {
- logMsg.append(" None");
- }
- else
- {
- for (Iterator it = _openConnectionNames.iterator(); it.hasNext();)
- {
- logMsg.append("\n ");
- logMsg.append(it.next().toString());
- }
- }
- _log.debug(logMsg.toString());
- }
- connection.close();
- }
- }
- catch (Exception e)
- {
- _log.warn("Caught exception while returning connection to pool", e);
- }
- }
-
- /**
- * Closes the given statement (which also closes all result sets for this statement) and the
- * connection it belongs to.
- *
- * @param statement The statement
- */
- public void closeStatement(Statement statement)
- {
- if (statement != null)
- {
- try
- {
- statement.close();
- }
- catch (Exception e)
- {
- _log.debug("Ignoring exception that occurred while closing statement", e);
- }
- }
- }
-}
diff --git a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/util/SqlTokenizer.java b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/util/SqlTokenizer.java
deleted file mode 100644
index d6dd6541e4..0000000000
--- a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/util/SqlTokenizer.java
+++ /dev/null
@@ -1,109 +0,0 @@
-package org.jumpmind.symmetric.db.ddl.util;
-
-/*
- * 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.
- */
-
-/**
- * A statement tokenizer for SQL strings that splits only at delimiters that
- * are at the end of a line or the end of the SQL (row mode).
- *
- * TODO: Add awareness of strings, so that semicolons within strings are not parsed
- *
- * @version $Revision: $
- */
-public class SqlTokenizer
-{
- /** The SQL to tokenize. */
- private String _sql;
- /** The index of the last character in the string. */
- private int _lastCharIdx;
- /** The last delimiter position in the string. */
- private int _lastDelimiterPos = -1;
- /** The next delimiter position in the string. */
- private int _nextDelimiterPos = -1;
- /** Whether there are no more tokens. */
- private boolean _finished;
-
- /**
- * Creates a new sql tokenizer.
- *
- * @param sql The sql text
- */
- public SqlTokenizer(String sql)
- {
- _sql = sql;
- _lastCharIdx = sql.length() - 1;
- }
-
- /**
- * Determines whether there are more statements.
- *
- * @return true
if there are more statements
- */
- public boolean hasMoreStatements()
- {
- if (_finished)
- {
- return false;
- }
- else
- {
- if (_nextDelimiterPos <= _lastDelimiterPos)
- {
- _nextDelimiterPos = _sql.indexOf(';', _lastDelimiterPos + 1);
- while ((_nextDelimiterPos >= 0) && (_nextDelimiterPos < _lastCharIdx))
- {
- char nextChar = _sql.charAt(_nextDelimiterPos + 1);
-
- if ((nextChar == '\r') || (nextChar == '\n'))
- {
- break;
- }
- _nextDelimiterPos = _sql.indexOf(';', _nextDelimiterPos + 1);
- }
- }
- return (_nextDelimiterPos >= 0) || (_lastDelimiterPos < _lastCharIdx);
- }
- }
-
- /**
- * Returns the next statement.
- *
- * @return The statement
- */
- public String getNextStatement()
- {
- String result = null;
-
- if (hasMoreStatements())
- {
- if (_nextDelimiterPos >= 0)
- {
- result = _sql.substring(_lastDelimiterPos + 1, _nextDelimiterPos);
- _lastDelimiterPos = _nextDelimiterPos;
- }
- else
- {
- result = _sql.substring(_lastDelimiterPos + 1);
- _finished = true;
- }
- }
- return result;
- }
-}
diff --git a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/io/DatabaseIO.java b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/io/DatabaseIO.java
similarity index 98%
rename from symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/io/DatabaseIO.java
rename to symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/io/DatabaseIO.java
index c0d7874d35..cb2b529e25 100644
--- a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/io/DatabaseIO.java
+++ b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/io/DatabaseIO.java
@@ -1,4 +1,4 @@
-package org.jumpmind.symmetric.db.ddl.io;
+package org.jumpmind.symmetric.db.io;
/*
* Licensed to the Apache Software Foundation (ASF) under one
@@ -32,8 +32,8 @@
import org.apache.commons.betwixt.io.BeanReader;
import org.apache.commons.betwixt.io.BeanWriter;
import org.apache.commons.betwixt.strategy.HyphenatedNameMapper;
-import org.jumpmind.symmetric.db.ddl.DdlUtilsException;
-import org.jumpmind.symmetric.db.ddl.model.Database;
+import org.jumpmind.symmetric.db.DdlUtilsException;
+import org.jumpmind.symmetric.db.model.Database;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
diff --git a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/io/DigesterRules.java b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/io/DigesterRules.java
similarity index 94%
rename from symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/io/DigesterRules.java
rename to symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/io/DigesterRules.java
index 29c1b6d931..58b44602b5 100644
--- a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/io/DigesterRules.java
+++ b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/io/DigesterRules.java
@@ -1,4 +1,4 @@
-package org.jumpmind.symmetric.db.ddl.io;
+package org.jumpmind.symmetric.db.io;
/*
* Licensed to the Apache Software Foundation (ASF) under one
diff --git a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/io/LocalEntityResolver.java b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/io/LocalEntityResolver.java
similarity index 98%
rename from symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/io/LocalEntityResolver.java
rename to symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/io/LocalEntityResolver.java
index 4df69b9971..fd59e983a1 100644
--- a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/io/LocalEntityResolver.java
+++ b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/io/LocalEntityResolver.java
@@ -1,4 +1,4 @@
-package org.jumpmind.symmetric.db.ddl.io;
+package org.jumpmind.symmetric.db.io;
/*
* Licensed to the Apache Software Foundation (ASF) under one
diff --git a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/io/package.html b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/io/package.html
similarity index 100%
rename from symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/io/package.html
rename to symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/io/package.html
diff --git a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/model/Column.java b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/model/Column.java
similarity index 99%
rename from symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/model/Column.java
rename to symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/model/Column.java
index 200cecd456..28ffb27f31 100644
--- a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/model/Column.java
+++ b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/model/Column.java
@@ -1,4 +1,4 @@
-package org.jumpmind.symmetric.db.ddl.model;
+package org.jumpmind.symmetric.db.model;
/*
* Licensed to the Apache Software Foundation (ASF) under one
@@ -29,7 +29,7 @@
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
-import org.jumpmind.symmetric.db.ddl.util.Jdbc3Utils;
+import org.jumpmind.symmetric.db.util.Jdbc3Utils;
/**
* Represents a column in the database model.
diff --git a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/model/Database.java b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/model/Database.java
similarity index 99%
rename from symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/model/Database.java
rename to symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/model/Database.java
index 1207ca4ed9..05e2537cb3 100644
--- a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/model/Database.java
+++ b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/model/Database.java
@@ -1,4 +1,4 @@
-package org.jumpmind.symmetric.db.ddl.model;
+package org.jumpmind.symmetric.db.model;
/*
* Licensed to the Apache Software Foundation (ASF) under one
diff --git a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/model/ForeignKey.java b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/model/ForeignKey.java
similarity index 99%
rename from symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/model/ForeignKey.java
rename to symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/model/ForeignKey.java
index 9d4e52f4da..909ac8dcd7 100644
--- a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/model/ForeignKey.java
+++ b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/model/ForeignKey.java
@@ -1,4 +1,4 @@
-package org.jumpmind.symmetric.db.ddl.model;
+package org.jumpmind.symmetric.db.model;
/*
* Licensed to the Apache Software Foundation (ASF) under one
diff --git a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/model/Index.java b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/model/Index.java
similarity index 98%
rename from symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/model/Index.java
rename to symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/model/Index.java
index 8b8670ff06..129b984822 100644
--- a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/model/Index.java
+++ b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/model/Index.java
@@ -1,4 +1,4 @@
-package org.jumpmind.symmetric.db.ddl.model;
+package org.jumpmind.symmetric.db.model;
/*
* Licensed to the Apache Software Foundation (ASF) under one
diff --git a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/model/IndexColumn.java b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/model/IndexColumn.java
similarity index 99%
rename from symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/model/IndexColumn.java
rename to symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/model/IndexColumn.java
index 7a8084b0b3..5ec55f6e94 100644
--- a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/model/IndexColumn.java
+++ b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/model/IndexColumn.java
@@ -1,4 +1,4 @@
-package org.jumpmind.symmetric.db.ddl.model;
+package org.jumpmind.symmetric.db.model;
/*
* Licensed to the Apache Software Foundation (ASF) under one
diff --git a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/model/IndexImpBase.java b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/model/IndexImpBase.java
similarity index 94%
rename from symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/model/IndexImpBase.java
rename to symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/model/IndexImpBase.java
index 3e92b76d77..c470f9bc95 100644
--- a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/model/IndexImpBase.java
+++ b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/model/IndexImpBase.java
@@ -1,4 +1,4 @@
-package org.jumpmind.symmetric.db.ddl.model;
+package org.jumpmind.symmetric.db.model;
/*
* Licensed to the Apache Software Foundation (ASF) under one
diff --git a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/model/JdbcTypeCategoryEnum.java b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/model/JdbcTypeCategoryEnum.java
similarity index 96%
rename from symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/model/JdbcTypeCategoryEnum.java
rename to symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/model/JdbcTypeCategoryEnum.java
index d4437ad958..b9dfe1e96a 100644
--- a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/model/JdbcTypeCategoryEnum.java
+++ b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/model/JdbcTypeCategoryEnum.java
@@ -1,4 +1,4 @@
-package org.jumpmind.symmetric.db.ddl.model;
+package org.jumpmind.symmetric.db.model;
/*
* Licensed to the Apache Software Foundation (ASF) under one
diff --git a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/model/ModelException.java b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/model/ModelException.java
similarity index 91%
rename from symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/model/ModelException.java
rename to symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/model/ModelException.java
index 90ace5deb5..ed6c1f458b 100644
--- a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/model/ModelException.java
+++ b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/model/ModelException.java
@@ -1,4 +1,4 @@
-package org.jumpmind.symmetric.db.ddl.model;
+package org.jumpmind.symmetric.db.model;
/*
* Licensed to the Apache Software Foundation (ASF) under one
@@ -19,7 +19,7 @@
* under the License.
*/
-import org.jumpmind.symmetric.db.ddl.DdlUtilsException;
+import org.jumpmind.symmetric.db.DdlUtilsException;
/**
* Indicates a model error.
diff --git a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/model/NonUniqueIndex.java b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/model/NonUniqueIndex.java
similarity index 95%
rename from symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/model/NonUniqueIndex.java
rename to symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/model/NonUniqueIndex.java
index af41696f79..74bc86b8c8 100644
--- a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/model/NonUniqueIndex.java
+++ b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/model/NonUniqueIndex.java
@@ -1,4 +1,4 @@
-package org.jumpmind.symmetric.db.ddl.model;
+package org.jumpmind.symmetric.db.model;
/*
* Licensed to the Apache Software Foundation (ASF) under one
diff --git a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/model/Reference.java b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/model/Reference.java
similarity index 99%
rename from symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/model/Reference.java
rename to symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/model/Reference.java
index 370aabf79a..9a44c7f578 100644
--- a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/model/Reference.java
+++ b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/model/Reference.java
@@ -1,4 +1,4 @@
-package org.jumpmind.symmetric.db.ddl.model;
+package org.jumpmind.symmetric.db.model;
/*
* Licensed to the Apache Software Foundation (ASF) under one
diff --git a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/model/Table.java b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/model/Table.java
similarity index 99%
rename from symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/model/Table.java
rename to symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/model/Table.java
index 8a5d099dfa..f5d9265629 100644
--- a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/model/Table.java
+++ b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/model/Table.java
@@ -1,4 +1,4 @@
-package org.jumpmind.symmetric.db.ddl.model;
+package org.jumpmind.symmetric.db.model;
/*
* Licensed to the Apache Software Foundation (ASF) under one
diff --git a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/model/TypeMap.java b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/model/TypeMap.java
similarity index 99%
rename from symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/model/TypeMap.java
rename to symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/model/TypeMap.java
index 03b831bc33..143498322d 100644
--- a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/model/TypeMap.java
+++ b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/model/TypeMap.java
@@ -1,4 +1,4 @@
-package org.jumpmind.symmetric.db.ddl.model;
+package org.jumpmind.symmetric.db.model;
/*
* Licensed to the Apache Software Foundation (ASF) under one
@@ -24,7 +24,7 @@
import java.util.HashSet;
import java.util.Set;
-import org.jumpmind.symmetric.db.ddl.util.Jdbc3Utils;
+import org.jumpmind.symmetric.db.util.Jdbc3Utils;
/**
* A class that maps SQL type names to their JDBC type ID found in
diff --git a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/model/UniqueIndex.java b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/model/UniqueIndex.java
similarity index 98%
rename from symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/model/UniqueIndex.java
rename to symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/model/UniqueIndex.java
index dea6a1077f..21947e9bd5 100644
--- a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/model/UniqueIndex.java
+++ b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/model/UniqueIndex.java
@@ -1,4 +1,4 @@
-package org.jumpmind.symmetric.db.ddl.model;
+package org.jumpmind.symmetric.db.model;
/*
* Licensed to the Apache Software Foundation (ASF) under one
diff --git a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/model/package.html b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/model/package.html
similarity index 100%
rename from symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/model/package.html
rename to symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/model/package.html
diff --git a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/package.html b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/package.html
similarity index 89%
rename from symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/package.html
rename to symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/package.html
index 02f4dd6666..29b1df3584 100644
--- a/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/ddl/package.html
+++ b/symmetric/symmetric-db/src/main/java/org/jumpmind/symmetric/db/package.html
@@ -23,9 +23,9 @@
- This package mainly contains the database platform abstraction, {@link org.apache.ddlutils.Platform} + This package mainly contains the database platform abstraction, {@link org.jumpmind.symmetric.db.IDatabasePlatform} and the factory to create instances for individual platforms, - {@link org.apache.ddlutils.PlatformFactory}. + {@link org.jumpmind.symmetric.db.DatabasePlatformFactory}.