org.apache.ddlutils.platform
Class SqlBuilder

java.lang.Object
  extended by org.apache.ddlutils.platform.SqlBuilder
Direct Known Subclasses:
AxionBuilder, CloudscapeBuilder, Db2Builder, FirebirdBuilder, HsqlDbBuilder, InterbaseBuilder, MckoiBuilder, MSSqlBuilder, MySqlBuilder, Oracle8Builder, PostgreSqlBuilder, SapDbBuilder, SybaseBuilder

public abstract class SqlBuilder
extends Object

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 $

Field Summary
protected  org.apache.commons.logging.Log _log
          The Log to which logging calls will be made.
protected static String SIZE_PLACEHOLDER
          The placeholder for the size value in the native type spec.
 
Constructor Summary
SqlBuilder(Platform platform)
          Creates a new sql builder.
 
Method Summary
protected  void addEscapedCharSequence(String charSequence, String escapedVersion)
          Adds a char sequence that needs escaping, and its escaped version.
 void alterDatabase(Database currentModel, Database desiredModel, CreationParameters params)
          Generates the DDL to modify an existing database so the schema matches the specified database schema by using drops, modifications and additions.
protected  void applyForSelectedChanges(Collection changes, Class[] changeTypes, org.apache.commons.collections.Closure closure)
          Calls the given closure for all changes that are of one of the given types, and then removes them from the changes collection.
protected  boolean areEqual(String string1, String string2, boolean caseMatters)
          Compares the two strings.
protected  boolean columnsDiffer(Column currentColumn, Column desiredColumn)
          Compares the current column in the database with the desired one.
 void createExternalForeignKeys(Database database)
          Creates the external foreignkey creation statements for all tables in the database.
 void createExternalForeignKeys(Database database, Table table)
          Creates external foreignkey creation statements if necessary.
 void createTable(Database database, Table table)
          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).
 void createTable(Database database, Table table, Map parameters)
          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).
 void createTables(Database database)
          Outputs the DDL required to drop and (re)create all tables in the database model.
 void createTables(Database database, boolean dropTables)
          Outputs the DDL required to drop (if requested) and (re)create all tables in the database model.
 void createTables(Database database, CreationParameters params, boolean dropTables)
          Outputs the DDL required to drop (if requested) and (re)create all tables in the database model.
protected  void createTemporaryTable(Database database, Table table, Map parameters)
          Outputs the DDL to create the given temporary table.
protected  String createUniqueIdentifier()
          Creates a reasonably unique identifier only consisting of hexadecimal characters and underscores.
 void dropExternalForeignKeys(Table table)
          Creates external foreignkey drop statements.
 void dropTable(Database database, Table table)
          Outputs the DDL required to drop the given table.
 void dropTable(Table table)
          Outputs the DDL to drop the table.
 void dropTables(Database database)
          Outputs the DDL required to drop the database.
protected  void dropTemporaryTable(Database database, Table table)
          Outputs the DDL to drop the given temporary table.
protected  String escapeStringValue(String value)
          Escapes the necessary characters in given string value.
protected  ForeignKey findCorrespondingForeignKey(Table table, ForeignKey fk)
          Searches in the given table for a corresponding foreign key.
protected  String getBareNativeType(Column column)
          Returns the bare database-native type for the given column without any size specifies.
protected  String getColumnName(Column column)
          Returns the column name.
 String getConstraintName(String prefix, Table table, String secondPart, String suffix)
          Returns the constraint name.
 DefaultValueHelper getDefaultValueHelper()
          Returns the default value helper.
 String getDeleteSql(Table table, Map pkValues, boolean genPlaceholders)
          Creates the SQL for deleting an object from the specified table.
protected  String getDelimitedIdentifier(String identifier)
          Returns the delimited version of the identifier (if configured).
 String getForeignKeyName(Table table, ForeignKey fk)
          Returns the name to be used for the given foreign key.
 String getIndent()
          Returns the string used to indent the SQL.
 String getIndexName(Index index)
          Returns the index name.
 String getInsertSql(Table table, Map columnValues, boolean genPlaceholders)
          Creates the SQL for inserting an object into the specified table.
 int getMaxColumnNameLength()
          Returns the maximum number of characters that a column name can have.
 int getMaxConstraintNameLength()
          Returns the maximum number of characters that a constraint name can have.
 int getMaxForeignKeyNameLength()
          Returns the maximum number of characters that a foreign key name can have.
 int getMaxTableNameLength()
          Returns the maximum number of characters that a table name can have.
protected  String getNativeDefaultValue(Column column)
          Returns the native default value for the column.
protected  String getNativeType(Column column)
          Returns the database-native type for the given column.
 Platform getPlatform()
          Returns the platform object.
 PlatformInfo getPlatformInfo()
          Returns the platform info object.
protected  Table getRealTargetTableFor(Database targetModel, Table sourceTable, Table targetTable)
          Creates the target table object that differs from the given target table only in the indices.
 String getSelectLastIdentityValues(Table table)
          Generates the SQL for querying the id that was created in the last insertion operation.
protected  String getSqlType(Column column)
          Returns the full SQL type specification (including size and precision/scale) for the given column.
 String getTableName(Table table)
          Returns the table name.
protected  Table getTemporaryTableFor(Database targetModel, Table targetTable)
          Creates a temporary table object that corresponds to the given table.
 String getUpdateSql(Table table, Map columnValues, boolean genPlaceholders)
          Creates the SQL for updating an object in the specified table.
protected  String getValueAsString(Column column, Object value)
          Generates the string representation of the given value.
protected  DateFormat getValueDateFormat()
          Returns the format object for formatting dates in the specified locale.
 String getValueLocale()
          Returns the locale that is used for number and date formatting (when printing default values and in generates insert/update/delete statements).
protected  NumberFormat getValueNumberFormat()
          Returns the format object for formatting numbers in the specified locale.
protected  DateFormat getValueTimeFormat()
          Returns the format object for formatting times in the specified locale.
 Writer getWriter()
          Returns the writer that the DDL is printed to.
protected  boolean isValidDefaultValue(String defaultSpec, int typeCode)
          Determines whether the given default spec is a non-empty spec that shall be used in a DEFAULT expression.
protected  void print(String text)
          Prints some text.
protected  void printComment(String text)
          Prints an SQL comment to the current stream.
protected  void printDefaultValue(Object defaultValue, int typeCode)
          Prints the default value of the column.
protected  void printEndOfStatement()
          Prints the end of statement text, which is typically a semi colon followed by a carriage return.
protected  void printIdentifier(String identifier)
          Prints the given identifier.
protected  void printIndent()
          Prints the characters used to indent SQL.
protected  void println()
          Prints a newline.
protected  void println(String text)
          Prints some text followed by a newline.
protected  void printlnIdentifier(String identifier)
          Prints the given identifier followed by a newline.
protected  void printStartOfEmbeddedStatement()
          Prints the start of an embedded statement.
protected  void processChange(Database currentModel, Database desiredModel, AddPrimaryKeyChange change)
          Processes the addition of a primary key to a table.
protected  void processChange(Database currentModel, Database desiredModel, CreationParameters params, AddForeignKeyChange change)
          Processes the change representing the addition of a foreign key.
protected  void processChange(Database currentModel, Database desiredModel, CreationParameters params, AddIndexChange change)
          Processes the change representing the addition of an index.
protected  void processChange(Database currentModel, Database desiredModel, CreationParameters params, AddTableChange change)
          Processes the change representing the addition of a table.
protected  void processChange(Database currentModel, Database desiredModel, CreationParameters params, ModelChange change)
          This is a fall-through callback which generates a warning because a specific change type wasn't handled.
protected  void processChange(Database currentModel, Database desiredModel, CreationParameters params, RemoveForeignKeyChange change)
          Processes the change representing the removal of a foreign key.
protected  void processChange(Database currentModel, Database desiredModel, CreationParameters params, RemoveIndexChange change)
          Processes the change representing the removal of an index.
protected  void processChange(Database currentModel, Database desiredModel, CreationParameters params, RemoveTableChange change)
          Processes the change representing the removal of a table.
protected  void processChanges(Database currentModel, Database desiredModel, List changes, CreationParameters params)
          Processes the changes.
protected  void processTableStructureChanges(Database currentModel, Database desiredModel, CreationParameters params, Collection changes)
          Processes the changes to the structure of tables.
protected  void processTableStructureChanges(Database currentModel, Database desiredModel, String tableName, Map parameters, List changes)
          Processes the changes to the structure of a single table.
protected  void processTableStructureChanges(Database currentModel, Database desiredModel, Table sourceTable, Table targetTable, Map parameters, List changes)
          Allows database-specific implementations to handle changes in a database specific manner.
 void setIndent(String indent)
          Sets the string used to indent the SQL.
protected  void setValueDateFormat(DateFormat format)
          Sets the format object for formatting dates in the specified locale.
 void setValueLocale(String localeStr)
          Sets the locale that is used for number and date formatting (when printing default values and in generates insert/update/delete statements).
protected  void setValueNumberFormat(NumberFormat format)
          Returns a new date format object for formatting numbers in the specified locale.
protected  void setValueTimeFormat(DateFormat format)
          Sets the date format object for formatting times in the specified locale.
 void setWriter(Writer writer)
          Sets the writer for printing the DDL to.
 String shortenName(String name, int desiredLength)
          Generates a version of the name that has at most the specified length.
protected  boolean shouldGeneratePrimaryKeys(Column[] primaryKeyColumns)
          Determines whether we should generate a primary key constraint for the given primary key columns.
protected  void writeCastExpression(Column sourceColumn, Column targetColumn)
          Writes a cast expression that converts the value of the source column to the data type of the target column.
protected  void writeColumn(Table table, Column column)
          Outputs the DDL for the specified column.
protected  void writeColumnAutoIncrementStmt(Table table, Column column)
          Prints that the column is an auto increment column.
protected  void writeColumnDefaultValue(Table table, Column column)
          Prints the default value of the column.
protected  void writeColumnDefaultValueStmt(Table table, Column column)
          Prints the default value stmt part for the column.
protected  void writeColumnNotNullableStmt()
          Prints that a column is not nullable.
protected  void writeColumnNullableStmt()
          Prints that a column is nullable.
protected  void writeColumns(Table table)
          Writes the columns of the given table.
protected  void writeCopyDataStatement(Table sourceTable, Table targetTable)
          Writes a statement that copies the data from the source to the target table.
protected  void writeEmbeddedForeignKeysStmt(Database database, Table table)
          Writes the foreign key constraints inside a create table () clause.
protected  void writeEmbeddedIndexCreateStmt(Table table, Index index)
          Writes the given embedded index of the table.
protected  void writeEmbeddedIndicesStmt(Table table)
          Writes the indexes embedded within the create table statement.
protected  void writeEmbeddedPrimaryKeysStmt(Table table)
          Writes the primary key constraints of the table inside its definition.
protected  void writeExternalForeignKeyCreateStmt(Database database, Table table, ForeignKey key)
          Writes a single foreign key constraint using a alter table statement.
protected  void writeExternalForeignKeyDropStmt(Table table, ForeignKey foreignKey)
          Generates the statement to drop a foreignkey constraint from the database using an alter table statement.
protected  void writeExternalIndexCreateStmt(Table table, Index index)
          Writes the given index of the table.
 void writeExternalIndexDropStmt(Table table, Index index)
          Generates the statement to drop a non-embedded index from the database.
protected  void writeExternalIndicesCreateStmt(Table table)
          Writes the indexes of the given table.
protected  void writeExternalPrimaryKeysCreateStmt(Table table, Column[] primaryKeyColumns)
          Writes the primary key constraints of the table as alter table statements.
protected  void writeForeignReferences(ForeignKey key)
          Writes a list of foreign references for the given foreign key.
protected  void writeLocalReferences(ForeignKey key)
          Writes a list of local references for the given foreign key.
protected  void writePrimaryKeyStmt(Table table, Column[] primaryKeyColumns)
          Writes a primary key statement for the given columns.
protected  void writeTableAlterStmt(Table table)
          Generates the first part of the ALTER TABLE statement including the table name.
protected  void writeTableComment(Table table)
          Outputs a comment for the table.
protected  void writeTableCreationStmt(Database database, Table table, Map parameters)
          Writes the table creation statement without the statement end.
protected  void writeTableCreationStmtEnding(Table table, Map parameters)
          Writes the end of the table creation statement.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

SIZE_PLACEHOLDER

protected static final String SIZE_PLACEHOLDER
The placeholder for the size value in the native type spec.

See Also:
Constant Field Values

_log

protected final org.apache.commons.logging.Log _log
The Log to which logging calls will be made.

Constructor Detail

SqlBuilder

public SqlBuilder(Platform platform)
Creates a new sql builder.

Parameters:
platform - The plaftform this builder belongs to
Method Detail

getPlatform

public Platform getPlatform()
Returns the platform object.

Returns:
The platform

getPlatformInfo

public PlatformInfo getPlatformInfo()
Returns the platform info object.

Returns:
The info object

getWriter

public Writer getWriter()
Returns the writer that the DDL is printed to.

Returns:
The writer

setWriter

public void setWriter(Writer writer)
Sets the writer for printing the DDL to.

Parameters:
writer - The writer

getDefaultValueHelper

public DefaultValueHelper getDefaultValueHelper()
Returns the default value helper.

Returns:
The default value helper

getIndent

public String getIndent()
Returns the string used to indent the SQL.

Returns:
The indentation string

setIndent

public void setIndent(String indent)
Sets the string used to indent the SQL.

Parameters:
indent - The indentation string

getValueLocale

public String getValueLocale()
Returns the locale that is used for number and date formatting (when printing default values and in generates insert/update/delete statements).

Returns:
The locale or null if default formatting is used

setValueLocale

public void setValueLocale(String localeStr)
Sets the locale that is used for number and date formatting (when printing default values and in generates insert/update/delete statements).

Parameters:
localeStr - The new locale or null if default formatting should be used; Format is "language[_country[_variant]]"

getValueDateFormat

protected DateFormat getValueDateFormat()
Returns the format object for formatting dates in the specified locale.

Returns:
The date format object or null if no locale is set

setValueDateFormat

protected void setValueDateFormat(DateFormat format)
Sets the format object for formatting dates in the specified locale.

Parameters:
format - The date format object

getValueTimeFormat

protected DateFormat getValueTimeFormat()
Returns the format object for formatting times in the specified locale.

Returns:
The time format object or null if no locale is set

setValueTimeFormat

protected void setValueTimeFormat(DateFormat format)
Sets the date format object for formatting times in the specified locale.

Parameters:
format - The time format object

getValueNumberFormat

protected NumberFormat getValueNumberFormat()
Returns the format object for formatting numbers in the specified locale.

Returns:
The number format object or null if no locale is set

setValueNumberFormat

protected void setValueNumberFormat(NumberFormat format)
Returns a new date format object for formatting numbers in the specified locale. Platforms can override this if necessary.

Parameters:
format - The number format object

addEscapedCharSequence

protected void addEscapedCharSequence(String charSequence,
                                      String escapedVersion)
Adds a char sequence that needs escaping, and its escaped version.

Parameters:
charSequence - The char sequence
escapedVersion - The escaped version

getMaxTableNameLength

public int getMaxTableNameLength()
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.

Returns:
The number of characters, or -1 if not limited

getMaxColumnNameLength

public int getMaxColumnNameLength()
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.

Returns:
The number of characters, or -1 if not limited

getMaxConstraintNameLength

public int getMaxConstraintNameLength()
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.

Returns:
The number of characters, or -1 if not limited

getMaxForeignKeyNameLength

public int getMaxForeignKeyNameLength()
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.

Returns:
The number of characters, or -1 if not limited

createTables

public void createTables(Database database)
                  throws IOException
Outputs the DDL required to drop and (re)create all tables in the database model.

Parameters:
database - The database model
Throws:
IOException

createTables

public void createTables(Database database,
                         boolean dropTables)
                  throws IOException
Outputs the DDL required to drop (if requested) and (re)create all tables in the database model.

Parameters:
database - The database
dropTables - Whether to drop tables before creating them
Throws:
IOException

createTables

public void createTables(Database database,
                         CreationParameters params,
                         boolean dropTables)
                  throws IOException
Outputs the DDL required to drop (if requested) and (re)create all tables in the database model.

Parameters:
database - The database
params - The parameters used in the creation
dropTables - Whether to drop tables before creating them
Throws:
IOException

alterDatabase

public void alterDatabase(Database currentModel,
                          Database desiredModel,
                          CreationParameters params)
                   throws IOException
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.

Parameters:
currentModel - The current database schema
desiredModel - The desired database schema
params - The parameters used in the creation of new tables. Note that for existing tables, the parameters won't be applied
Throws:
IOException

applyForSelectedChanges

protected void applyForSelectedChanges(Collection changes,
                                       Class[] changeTypes,
                                       org.apache.commons.collections.Closure closure)
Calls the given closure for all changes that are of one of the given types, and then removes them from the changes collection.

Parameters:
changes - The changes
changeTypes - The types to search for
closure - The closure to invoke

processChanges

protected void processChanges(Database currentModel,
                              Database desiredModel,
                              List changes,
                              CreationParameters params)
                       throws IOException
Processes the changes. The default argument performs several passes:
  1. RemoveForeignKeyChange and RemoveIndexChange come first to allow for e.g. subsequent primary key changes or column removal.
  2. RemoveTableChange comes after the removal of foreign keys and indices.
  3. These are all handled together:
    RemovePrimaryKeyChange
    AddPrimaryKeyChange
    PrimaryKeyChange
    RemoveColumnChange
    AddColumnChange
    ColumnAutoIncrementChange
    ColumnDefaultValueChange
    ColumnRequiredChange
    ColumnDataTypeChange
    ColumnSizeChange
    The reason for this is that the default algorithm rebuilds the table for these changes and thus their order is irrelevant.
  4. AddTableChange
    needs to come after the table removal (so that tables of the same name are removed) and before the addition of foreign keys etc.
  5. AddForeignKeyChange and AddIndexChange come last after table/column/primary key additions or changes.

Parameters:
currentModel - The current database schema
desiredModel - The desired database schema
changes - The changes
params - The parameters used in the creation of new tables. Note that for existing tables, the parameters won't be applied
Throws:
IOException

processChange

protected void processChange(Database currentModel,
                             Database desiredModel,
                             CreationParameters params,
                             ModelChange change)
                      throws IOException
This is a fall-through callback which generates a warning because a specific change type wasn't handled.

Parameters:
currentModel - The current database schema
desiredModel - The desired database schema
params - The parameters used in the creation of new tables. Note that for existing tables, the parameters won't be applied
change - The change object
Throws:
IOException

processChange

protected void processChange(Database currentModel,
                             Database desiredModel,
                             CreationParameters params,
                             RemoveForeignKeyChange change)
                      throws IOException
Processes the change representing the removal of a foreign key.

Parameters:
currentModel - The current database schema
desiredModel - The desired database schema
params - The parameters used in the creation of new tables. Note that for existing tables, the parameters won't be applied
change - The change object
Throws:
IOException

processChange

protected void processChange(Database currentModel,
                             Database desiredModel,
                             CreationParameters params,
                             RemoveIndexChange change)
                      throws IOException
Processes the change representing the removal of an index.

Parameters:
currentModel - The current database schema
desiredModel - The desired database schema
params - The parameters used in the creation of new tables. Note that for existing tables, the parameters won't be applied
change - The change object
Throws:
IOException

processChange

protected void processChange(Database currentModel,
                             Database desiredModel,
                             CreationParameters params,
                             RemoveTableChange change)
                      throws IOException
Processes the change representing the removal of a table.

Parameters:
currentModel - The current database schema
desiredModel - The desired database schema
params - The parameters used in the creation of new tables. Note that for existing tables, the parameters won't be applied
change - The change object
Throws:
IOException

processChange

protected void processChange(Database currentModel,
                             Database desiredModel,
                             CreationParameters params,
                             AddTableChange change)
                      throws IOException
Processes the change representing the addition of a table.

Parameters:
currentModel - The current database schema
desiredModel - The desired database schema
params - The parameters used in the creation of new tables. Note that for existing tables, the parameters won't be applied
change - The change object
Throws:
IOException

processChange

protected void processChange(Database currentModel,
                             Database desiredModel,
                             CreationParameters params,
                             AddForeignKeyChange change)
                      throws IOException
Processes the change representing the addition of a foreign key.

Parameters:
currentModel - The current database schema
desiredModel - The desired database schema
params - The parameters used in the creation of new tables. Note that for existing tables, the parameters won't be applied
change - The change object
Throws:
IOException

processChange

protected void processChange(Database currentModel,
                             Database desiredModel,
                             CreationParameters params,
                             AddIndexChange change)
                      throws IOException
Processes the change representing the addition of an index.

Parameters:
currentModel - The current database schema
desiredModel - The desired database schema
params - The parameters used in the creation of new tables. Note that for existing tables, the parameters won't be applied
change - The change object
Throws:
IOException

processTableStructureChanges

protected void processTableStructureChanges(Database currentModel,
                                            Database desiredModel,
                                            CreationParameters params,
                                            Collection changes)
                                     throws IOException
Processes the changes to the structure of tables.

Parameters:
currentModel - The current database schema
desiredModel - The desired database schema
params - The parameters used in the creation of new tables. Note that for existing tables, the parameters won't be applied
changes - The change objects
Throws:
IOException

processTableStructureChanges

protected void processTableStructureChanges(Database currentModel,
                                            Database desiredModel,
                                            String tableName,
                                            Map parameters,
                                            List changes)
                                     throws IOException
Processes the changes to the structure of a single table. Database-specific implementations might redefine this method, but it is usually sufficient to redefine the processTableStructureChanges(Database, Database, Table, Table, Map, List) method instead.

Parameters:
currentModel - The current database schema
desiredModel - The desired database schema
tableName - The name of the changed table
parameters - The creation parameters for the desired table
changes - The change objects for this table
Throws:
IOException

processTableStructureChanges

protected void processTableStructureChanges(Database currentModel,
                                            Database desiredModel,
                                            Table sourceTable,
                                            Table targetTable,
                                            Map parameters,
                                            List changes)
                                     throws IOException
Allows database-specific implementations to handle changes in a database specific manner. Any handled change should be applied to the given current model (which is a copy of the real original model) and be removed from the list of changes.
In the default implementation, all AddPrimaryKeyChange changes are applied via an ALTER TABLE ADD CONSTRAINT statement.

Parameters:
currentModel - The current database schema
desiredModel - The desired database schema
sourceTable - The original table
targetTable - The desired table
parameters - The creation parameters for the table
changes - The change objects for the target table
Throws:
IOException

getTemporaryTableFor

protected Table getTemporaryTableFor(Database targetModel,
                                     Table targetTable)
                              throws IOException
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.

Parameters:
targetModel - The target database
targetTable - The target table
Returns:
The temporary table
Throws:
IOException

createTemporaryTable

protected void createTemporaryTable(Database database,
                                    Table table,
                                    Map parameters)
                             throws IOException
Outputs the DDL to create the given temporary table. Per default this is simply a call to createTable(Database, Table, Map).

Parameters:
database - The database model
table - The table
parameters - Additional platform-specific parameters for the table creation
Throws:
IOException

dropTemporaryTable

protected void dropTemporaryTable(Database database,
                                  Table table)
                           throws IOException
Outputs the DDL to drop the given temporary table. Per default this is simply a call to dropTable(Table).

Parameters:
database - The database model
table - The table
Throws:
IOException

getRealTargetTableFor

protected Table getRealTargetTableFor(Database targetModel,
                                      Table sourceTable,
                                      Table targetTable)
                               throws IOException
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.

Parameters:
targetModel - The target database
sourceTable - The source table
targetTable - The target table
Returns:
The table
Throws:
IOException

writeCopyDataStatement

protected void writeCopyDataStatement(Table sourceTable,
                                      Table targetTable)
                               throws IOException
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 writeCastExpression(Column, Column) method.

Parameters:
sourceTable - The source table
targetTable - The target table
Throws:
IOException

writeCastExpression

protected void writeCastExpression(Column sourceColumn,
                                   Column targetColumn)
                            throws IOException
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.

Parameters:
sourceColumn - The source column
targetColumn - The target column
Throws:
IOException

processChange

protected void processChange(Database currentModel,
                             Database desiredModel,
                             AddPrimaryKeyChange change)
                      throws IOException
Processes the addition of a primary key to a table.

Parameters:
currentModel - The current database schema
desiredModel - The desired database schema
change - The change object
Throws:
IOException

findCorrespondingForeignKey

protected ForeignKey findCorrespondingForeignKey(Table table,
                                                 ForeignKey fk)
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.

Parameters:
table - The table to search in
fk - The original foreign key
Returns:
The corresponding foreign key if found

areEqual

protected boolean areEqual(String string1,
                           String string2,
                           boolean caseMatters)
Compares the two strings.

Parameters:
string1 - The first string
string2 - The second string
caseMatters - Whether case matters in the comparison
Returns:
true if the string are equal

createTable

public void createTable(Database database,
                        Table table)
                 throws IOException
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).

Parameters:
database - The database model
table - The table
Throws:
IOException

createTable

public void createTable(Database database,
                        Table table,
                        Map parameters)
                 throws IOException
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).

Parameters:
database - The database model
table - The table
parameters - Additional platform-specific parameters for the table creation
Throws:
IOException

createExternalForeignKeys

public void createExternalForeignKeys(Database database)
                               throws IOException
Creates the external foreignkey creation statements for all tables in the database.

Parameters:
database - The database
Throws:
IOException

createExternalForeignKeys

public void createExternalForeignKeys(Database database,
                                      Table table)
                               throws IOException
Creates external foreignkey creation statements if necessary.

Parameters:
database - The database model
table - The table
Throws:
IOException

dropTables

public void dropTables(Database database)
                throws IOException
Outputs the DDL required to drop the database.

Parameters:
database - The database
Throws:
IOException

dropTable

public void dropTable(Database database,
                      Table table)
               throws IOException
Outputs the DDL required to drop the given table. This method also drops foreign keys to the table.

Parameters:
database - The database
table - The table
Throws:
IOException

dropTable

public void dropTable(Table table)
               throws IOException
Outputs the DDL to drop the table. Note that this method does not drop foreign keys to this table. Use dropTable(Database, Table) if you want that.

Parameters:
table - The table to drop
Throws:
IOException

dropExternalForeignKeys

public void dropExternalForeignKeys(Table table)
                             throws IOException
Creates external foreignkey drop statements.

Parameters:
table - The table
Throws:
IOException

getInsertSql

public String getInsertSql(Table table,
                           Map columnValues,
                           boolean genPlaceholders)
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.

Parameters:
table - The table
columnValues - The columns values indexed by the column names
genPlaceholders - Whether to generate value placeholders for a prepared statement
Returns:
The insertion sql

getUpdateSql

public String getUpdateSql(Table table,
                           Map columnValues,
                           boolean genPlaceholders)
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.

Parameters:
table - The table
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
genPlaceholders - Whether to generate value placeholders for a prepared statement (both for the pk values and the object values)
Returns:
The update sql

getDeleteSql

public String getDeleteSql(Table table,
                           Map pkValues,
                           boolean genPlaceholders)
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.

Parameters:
table - The table
pkValues - The primary key values indexed by the column names, can be empty
genPlaceholders - Whether to generate value placeholders for a prepared statement
Returns:
The delete sql

getValueAsString

protected String getValueAsString(Column column,
                                  Object value)
Generates the string representation of the given value.

Parameters:
column - The column
value - The value
Returns:
The string representation

getSelectLastIdentityValues

public String getSelectLastIdentityValues(Table table)
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.

Parameters:
table - The table
Returns:
The sql, or null if the database does not support this

shortenName

public String shortenName(String name,
                          int desiredLength)
Generates a version of the name that has at most the specified length.

Parameters:
name - The original name
desiredLength - The desired maximum length
Returns:
The shortened version

getTableName

public String getTableName(Table table)
Returns the table name. This method takes care of length limitations imposed by some databases.

Parameters:
table - The table
Returns:
The table name

writeTableComment

protected void writeTableComment(Table table)
                          throws IOException
Outputs a comment for the table.

Parameters:
table - The table
Throws:
IOException

writeTableAlterStmt

protected void writeTableAlterStmt(Table table)
                            throws IOException
Generates the first part of the ALTER TABLE statement including the table name.

Parameters:
table - The table being altered
Throws:
IOException

writeTableCreationStmt

protected void writeTableCreationStmt(Database database,
                                      Table table,
                                      Map parameters)
                               throws IOException
Writes the table creation statement without the statement end.

Parameters:
database - The model
table - The table
parameters - Additional platform-specific parameters for the table creation
Throws:
IOException

writeTableCreationStmtEnding

protected void writeTableCreationStmtEnding(Table table,
                                            Map parameters)
                                     throws IOException
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.

Parameters:
table - The table
parameters - Additional platform-specific parameters for the table creation
Throws:
IOException

writeColumns

protected void writeColumns(Table table)
                     throws IOException
Writes the columns of the given table.

Parameters:
table - The table
Throws:
IOException

getColumnName

protected String getColumnName(Column column)
                        throws IOException
Returns the column name. This method takes care of length limitations imposed by some databases.

Parameters:
column - The column
Returns:
The column name
Throws:
IOException

writeColumn

protected void writeColumn(Table table,
                           Column column)
                    throws IOException
Outputs the DDL for the specified column.

Parameters:
table - The table containing the column
column - The column
Throws:
IOException

getSqlType

protected String getSqlType(Column column)
Returns the full SQL type specification (including size and precision/scale) for the given column.

Parameters:
column - The column
Returns:
The full SQL type string including the size

getNativeType

protected String getNativeType(Column column)
Returns the database-native type for the given column.

Parameters:
column - The column
Returns:
The native type

getBareNativeType

protected String getBareNativeType(Column column)
Returns the bare database-native type for the given column without any size specifies.

Parameters:
column - The column
Returns:
The native type

getNativeDefaultValue

protected String getNativeDefaultValue(Column column)
Returns the native default value for the column.

Parameters:
column - The column
Returns:
The native default value

escapeStringValue

protected String escapeStringValue(String value)
Escapes the necessary characters in given string value.

Parameters:
value - The value
Returns:
The corresponding string with the special characters properly escaped

isValidDefaultValue

protected boolean isValidDefaultValue(String defaultSpec,
                                      int typeCode)
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.

Parameters:
defaultSpec - The default value spec
typeCode - The JDBC type code
Returns:
true if the default value spec is valid

writeColumnDefaultValueStmt

protected void writeColumnDefaultValueStmt(Table table,
                                           Column column)
                                    throws IOException
Prints the default value stmt part for the column.

Parameters:
table - The table
column - The column
Throws:
IOException

writeColumnDefaultValue

protected void writeColumnDefaultValue(Table table,
                                       Column column)
                                throws IOException
Prints the default value of the column.

Parameters:
table - The table
column - The column
Throws:
IOException

printDefaultValue

protected void printDefaultValue(Object defaultValue,
                                 int typeCode)
                          throws IOException
Prints the default value of the column.

Parameters:
defaultValue - The default value
typeCode - The type code to write the default value for
Throws:
IOException

writeColumnAutoIncrementStmt

protected void writeColumnAutoIncrementStmt(Table table,
                                            Column column)
                                     throws IOException
Prints that the column is an auto increment column.

Parameters:
table - The table
column - The column
Throws:
IOException

writeColumnNullableStmt

protected void writeColumnNullableStmt()
                                throws IOException
Prints that a column is nullable.

Throws:
IOException

writeColumnNotNullableStmt

protected void writeColumnNotNullableStmt()
                                   throws IOException
Prints that a column is not nullable.

Throws:
IOException

columnsDiffer

protected boolean columnsDiffer(Column currentColumn,
                                Column desiredColumn)
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.

Parameters:
currentColumn - The current column as it is in the database
desiredColumn - The desired column
Returns:
true if the column specifications differ

getForeignKeyName

public String getForeignKeyName(Table table,
                                ForeignKey fk)
Returns the name to be used for the given foreign key. If the foreign key has no specified name, this method determines a unique name for it. The name will also be shortened to honor the maximum identifier length imposed by the platform.

Parameters:
table - The table for whith the foreign key is defined
fk - The foreign key
Returns:
The name

getConstraintName

public String getConstraintName(String prefix,
                                Table table,
                                String secondPart,
                                String suffix)
Returns the constraint name. This method takes care of length limitations imposed by some databases.

Parameters:
prefix - The constraint prefix, can be null
table - The table that the constraint belongs to
secondPart - The second name part, e.g. the name of the constraint column
suffix - The constraint suffix, e.g. a counter (can be null)
Returns:
The constraint name

writeEmbeddedPrimaryKeysStmt

protected void writeEmbeddedPrimaryKeysStmt(Table table)
                                     throws IOException
Writes the primary key constraints of the table inside its definition.

Parameters:
table - The table
Throws:
IOException

writeExternalPrimaryKeysCreateStmt

protected void writeExternalPrimaryKeysCreateStmt(Table table,
                                                  Column[] primaryKeyColumns)
                                           throws IOException
Writes the primary key constraints of the table as alter table statements.

Parameters:
table - The table
primaryKeyColumns - The primary key columns
Throws:
IOException

shouldGeneratePrimaryKeys

protected boolean shouldGeneratePrimaryKeys(Column[] primaryKeyColumns)
Determines whether we should generate a primary key constraint for the given primary key columns.

Parameters:
primaryKeyColumns - The pk columns
Returns:
true if a pk statement should be generated for the columns

writePrimaryKeyStmt

protected void writePrimaryKeyStmt(Table table,
                                   Column[] primaryKeyColumns)
                            throws IOException
Writes a primary key statement for the given columns.

Parameters:
table - The table
primaryKeyColumns - The primary columns
Throws:
IOException

getIndexName

public String getIndexName(Index index)
Returns the index name. This method takes care of length limitations imposed by some databases.

Parameters:
index - The index
Returns:
The index name

writeExternalIndicesCreateStmt

protected void writeExternalIndicesCreateStmt(Table table)
                                       throws IOException
Writes the indexes of the given table.

Parameters:
table - The table
Throws:
IOException

writeEmbeddedIndicesStmt

protected void writeEmbeddedIndicesStmt(Table table)
                                 throws IOException
Writes the indexes embedded within the create table statement.

Parameters:
table - The table
Throws:
IOException

writeExternalIndexCreateStmt

protected void writeExternalIndexCreateStmt(Table table,
                                            Index index)
                                     throws IOException
Writes the given index of the table.

Parameters:
table - The table
index - The index
Throws:
IOException

writeEmbeddedIndexCreateStmt

protected void writeEmbeddedIndexCreateStmt(Table table,
                                            Index index)
                                     throws IOException
Writes the given embedded index of the table.

Parameters:
table - The table
index - The index
Throws:
IOException

writeExternalIndexDropStmt

public void writeExternalIndexDropStmt(Table table,
                                       Index index)
                                throws IOException
Generates the statement to drop a non-embedded index from the database.

Parameters:
table - The table the index is on
index - The index to drop
Throws:
IOException

writeEmbeddedForeignKeysStmt

protected void writeEmbeddedForeignKeysStmt(Database database,
                                            Table table)
                                     throws IOException
Writes the foreign key constraints inside a create table () clause.

Parameters:
database - The database model
table - The table
Throws:
IOException

writeExternalForeignKeyCreateStmt

protected void writeExternalForeignKeyCreateStmt(Database database,
                                                 Table table,
                                                 ForeignKey key)
                                          throws IOException
Writes a single foreign key constraint using a alter table statement.

Parameters:
database - The database model
table - The table
key - The foreign key
Throws:
IOException

writeLocalReferences

protected void writeLocalReferences(ForeignKey key)
                             throws IOException
Writes a list of local references for the given foreign key.

Parameters:
key - The foreign key
Throws:
IOException

writeForeignReferences

protected void writeForeignReferences(ForeignKey key)
                               throws IOException
Writes a list of foreign references for the given foreign key.

Parameters:
key - The foreign key
Throws:
IOException

writeExternalForeignKeyDropStmt

protected void writeExternalForeignKeyDropStmt(Table table,
                                               ForeignKey foreignKey)
                                        throws IOException
Generates the statement to drop a foreignkey constraint from the database using an alter table statement.

Parameters:
table - The table
foreignKey - The foreign key
Throws:
IOException

printComment

protected void printComment(String text)
                     throws IOException
Prints an SQL comment to the current stream.

Parameters:
text - The comment text
Throws:
IOException

printStartOfEmbeddedStatement

protected void printStartOfEmbeddedStatement()
                                      throws IOException
Prints the start of an embedded statement.

Throws:
IOException

printEndOfStatement

protected void printEndOfStatement()
                            throws IOException
Prints the end of statement text, which is typically a semi colon followed by a carriage return.

Throws:
IOException

println

protected void println()
                throws IOException
Prints a newline.

Throws:
IOException

print

protected void print(String text)
              throws IOException
Prints some text.

Parameters:
text - The text to print
Throws:
IOException

getDelimitedIdentifier

protected String getDelimitedIdentifier(String identifier)
Returns the delimited version of the identifier (if configured).

Parameters:
identifier - The identifier
Returns:
The delimited version of the identifier unless the platform is configured to use undelimited identifiers; in that case, the identifier is returned unchanged

printIdentifier

protected void printIdentifier(String identifier)
                        throws IOException
Prints the given identifier. For most databases, this will be a delimited identifier.

Parameters:
identifier - The identifier
Throws:
IOException

printlnIdentifier

protected void printlnIdentifier(String identifier)
                          throws IOException
Prints the given identifier followed by a newline. For most databases, this will be a delimited identifier.

Parameters:
identifier - The identifier
Throws:
IOException

println

protected void println(String text)
                throws IOException
Prints some text followed by a newline.

Parameters:
text - The text to print
Throws:
IOException

printIndent

protected void printIndent()
                    throws IOException
Prints the characters used to indent SQL.

Throws:
IOException

createUniqueIdentifier

protected String createUniqueIdentifier()
Creates a reasonably unique identifier only consisting of hexadecimal characters and underscores. It looks like d578271282b42fce__2955b56e_107df3fbc96__8000 and is 48 characters long.

Returns:
The identifier


Copyright © 2005-2007 Apache Software Foundation. All Rights Reserved.