target
stringlengths 20
113k
| src_fm
stringlengths 11
86.3k
| src_fm_fc
stringlengths 21
86.4k
| src_fm_fc_co
stringlengths 30
86.4k
| src_fm_fc_ms
stringlengths 42
86.8k
| src_fm_fc_ms_ff
stringlengths 43
86.8k
|
---|---|---|---|---|---|
@Test public void testAutoIncrementStartWithPostgresDatabase() throws Exception { for (Database database : TestContext.getInstance().getAllDatabases()) { if (database instanceof PostgresDatabase) { CreateTableStatement statement = new CreateTableStatement(SCHEMA_NAME, TABLE_NAME); statement.addColumn( COLUMN_NAME1, TypeConverterFactory.getInstance().findTypeConverter(database).getDataType("BIGINT", true), new AutoIncrementConstraint(COLUMN_NAME1, BigInteger.ZERO, null) ); Sql[] generatedSql = this.generatorUnderTest.generateSql(statement, database, null); assertEquals("CREATE TABLE SCHEMA_NAME.TABLE_NAME (COLUMN1_NAME bigserial)", generatedSql[0].toSql()); } } } | public Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { StringBuffer buffer = new StringBuffer(); buffer.append("CREATE TABLE ").append(database.escapeTableName(statement.getSchemaName(), statement.getTableName())).append(" "); buffer.append("("); boolean isSinglePrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() == 1; boolean isPrimaryKeyAutoIncrement = false; Iterator<String> columnIterator = statement.getColumns().iterator(); while (columnIterator.hasNext()) { String column = columnIterator.next(); buffer.append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), column)); buffer.append(" ").append(statement.getColumnTypes().get(column)); AutoIncrementConstraint autoIncrementConstraint = null; for (AutoIncrementConstraint currentAutoIncrementConstraint : statement.getAutoIncrementConstraints()) { if (column.equals(currentAutoIncrementConstraint.getColumnName())) { autoIncrementConstraint = currentAutoIncrementConstraint; break; } } boolean isAutoIncrementColumn = autoIncrementConstraint != null; boolean isPrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().contains(column); isPrimaryKeyAutoIncrement = isPrimaryKeyAutoIncrement || isPrimaryKeyColumn && isAutoIncrementColumn; if ((database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyColumn && isAutoIncrementColumn) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } buffer.append(" PRIMARY KEY AUTOINCREMENT"); } if (statement.getDefaultValue(column) != null) { Object defaultValue = statement.getDefaultValue(column); if (database instanceof MSSQLDatabase) { buffer.append(" CONSTRAINT ").append(((MSSQLDatabase) database).generateDefaultConstraintName(statement.getTableName(), column)); } buffer.append(" DEFAULT "); buffer.append(statement.getColumnTypes().get(column).convertObjectToString(defaultValue, database)); } if (isAutoIncrementColumn && ! (database instanceof SQLiteDatabase)) { if (database.supportsAutoIncrement()) { String autoIncrementClause = database.getAutoIncrementClause(autoIncrementConstraint.getStartWith(), autoIncrementConstraint.getIncrementBy()); if (!"".equals(autoIncrementClause)) { buffer.append(" ").append(autoIncrementClause); } } else { LogFactory.getLogger().warning(database.getTypeName()+" does not support autoincrement columns as request for "+(database.escapeTableName(statement.getSchemaName(), statement.getTableName()))); } } if (statement.getNotNullColumns().contains(column)) { buffer.append(" NOT NULL"); } else { if (database instanceof SybaseDatabase || database instanceof SybaseASADatabase || database instanceof MySQLDatabase) { if (database instanceof MySQLDatabase && statement.getColumnTypes().get(column).getDataTypeName().equalsIgnoreCase("timestamp")) { } else { buffer.append(" NULL"); } } } if (database instanceof InformixDatabase && isSinglePrimaryKeyColumn) { buffer.append(" PRIMARY KEY"); } if (columnIterator.hasNext()) { buffer.append(", "); } } buffer.append(","); if (!( (database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyAutoIncrement) && !((database instanceof InformixDatabase) && isSinglePrimaryKeyColumn )) { if (statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() > 0) { if (!(database instanceof InformixDatabase)) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } } buffer.append(" PRIMARY KEY ("); buffer.append(database.escapeColumnNameList(StringUtils.join(statement.getPrimaryKeyConstraint().getColumns(), ", "))); buffer.append(")"); if (database instanceof OracleDatabase && statement.getPrimaryKeyConstraint().getTablespace() != null) { buffer.append(" USING INDEX TABLESPACE "); buffer.append(statement.getPrimaryKeyConstraint().getTablespace()); } buffer.append(","); } } for (ForeignKeyConstraint fkConstraint : statement.getForeignKeyConstraints()) { if (!(database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } String referencesString = fkConstraint.getReferences(); if (!referencesString.contains(".") && database.getDefaultSchemaName() != null) { referencesString = database.getDefaultSchemaName()+"."+referencesString; } buffer.append(" FOREIGN KEY (") .append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), fkConstraint.getColumn())) .append(") REFERENCES ") .append(referencesString); if (fkConstraint.isDeleteCascade()) { buffer.append(" ON DELETE CASCADE"); } if ((database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } if (fkConstraint.isInitiallyDeferred()) { buffer.append(" INITIALLY DEFERRED"); } if (fkConstraint.isDeferrable()) { buffer.append(" DEFERRABLE"); } buffer.append(","); } for (UniqueConstraint uniqueConstraint : statement.getUniqueConstraints()) { if (uniqueConstraint.getConstraintName() != null && !constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(" UNIQUE ("); buffer.append(database.escapeColumnNameList(StringUtils.join(uniqueConstraint.getColumns(), ", "))); buffer.append(")"); if (uniqueConstraint.getConstraintName() != null && constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(","); } String sql = buffer.toString().replaceFirst(",\\s*$", "") + ")"; if (statement.getTablespace() != null && database.supportsTablespaces()) { if (database instanceof MSSQLDatabase || database instanceof SybaseASADatabase) { sql += " ON " + statement.getTablespace(); } else if (database instanceof DB2Database || database instanceof InformixDatabase) { sql += " IN " + statement.getTablespace(); } else { sql += " TABLESPACE " + statement.getTablespace(); } } return new Sql[] { new UnparsedSql(sql) }; } | CreateTableGenerator extends AbstractSqlGenerator<CreateTableStatement> { public Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { StringBuffer buffer = new StringBuffer(); buffer.append("CREATE TABLE ").append(database.escapeTableName(statement.getSchemaName(), statement.getTableName())).append(" "); buffer.append("("); boolean isSinglePrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() == 1; boolean isPrimaryKeyAutoIncrement = false; Iterator<String> columnIterator = statement.getColumns().iterator(); while (columnIterator.hasNext()) { String column = columnIterator.next(); buffer.append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), column)); buffer.append(" ").append(statement.getColumnTypes().get(column)); AutoIncrementConstraint autoIncrementConstraint = null; for (AutoIncrementConstraint currentAutoIncrementConstraint : statement.getAutoIncrementConstraints()) { if (column.equals(currentAutoIncrementConstraint.getColumnName())) { autoIncrementConstraint = currentAutoIncrementConstraint; break; } } boolean isAutoIncrementColumn = autoIncrementConstraint != null; boolean isPrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().contains(column); isPrimaryKeyAutoIncrement = isPrimaryKeyAutoIncrement || isPrimaryKeyColumn && isAutoIncrementColumn; if ((database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyColumn && isAutoIncrementColumn) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } buffer.append(" PRIMARY KEY AUTOINCREMENT"); } if (statement.getDefaultValue(column) != null) { Object defaultValue = statement.getDefaultValue(column); if (database instanceof MSSQLDatabase) { buffer.append(" CONSTRAINT ").append(((MSSQLDatabase) database).generateDefaultConstraintName(statement.getTableName(), column)); } buffer.append(" DEFAULT "); buffer.append(statement.getColumnTypes().get(column).convertObjectToString(defaultValue, database)); } if (isAutoIncrementColumn && ! (database instanceof SQLiteDatabase)) { if (database.supportsAutoIncrement()) { String autoIncrementClause = database.getAutoIncrementClause(autoIncrementConstraint.getStartWith(), autoIncrementConstraint.getIncrementBy()); if (!"".equals(autoIncrementClause)) { buffer.append(" ").append(autoIncrementClause); } } else { LogFactory.getLogger().warning(database.getTypeName()+" does not support autoincrement columns as request for "+(database.escapeTableName(statement.getSchemaName(), statement.getTableName()))); } } if (statement.getNotNullColumns().contains(column)) { buffer.append(" NOT NULL"); } else { if (database instanceof SybaseDatabase || database instanceof SybaseASADatabase || database instanceof MySQLDatabase) { if (database instanceof MySQLDatabase && statement.getColumnTypes().get(column).getDataTypeName().equalsIgnoreCase("timestamp")) { } else { buffer.append(" NULL"); } } } if (database instanceof InformixDatabase && isSinglePrimaryKeyColumn) { buffer.append(" PRIMARY KEY"); } if (columnIterator.hasNext()) { buffer.append(", "); } } buffer.append(","); if (!( (database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyAutoIncrement) && !((database instanceof InformixDatabase) && isSinglePrimaryKeyColumn )) { if (statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() > 0) { if (!(database instanceof InformixDatabase)) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } } buffer.append(" PRIMARY KEY ("); buffer.append(database.escapeColumnNameList(StringUtils.join(statement.getPrimaryKeyConstraint().getColumns(), ", "))); buffer.append(")"); if (database instanceof OracleDatabase && statement.getPrimaryKeyConstraint().getTablespace() != null) { buffer.append(" USING INDEX TABLESPACE "); buffer.append(statement.getPrimaryKeyConstraint().getTablespace()); } buffer.append(","); } } for (ForeignKeyConstraint fkConstraint : statement.getForeignKeyConstraints()) { if (!(database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } String referencesString = fkConstraint.getReferences(); if (!referencesString.contains(".") && database.getDefaultSchemaName() != null) { referencesString = database.getDefaultSchemaName()+"."+referencesString; } buffer.append(" FOREIGN KEY (") .append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), fkConstraint.getColumn())) .append(") REFERENCES ") .append(referencesString); if (fkConstraint.isDeleteCascade()) { buffer.append(" ON DELETE CASCADE"); } if ((database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } if (fkConstraint.isInitiallyDeferred()) { buffer.append(" INITIALLY DEFERRED"); } if (fkConstraint.isDeferrable()) { buffer.append(" DEFERRABLE"); } buffer.append(","); } for (UniqueConstraint uniqueConstraint : statement.getUniqueConstraints()) { if (uniqueConstraint.getConstraintName() != null && !constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(" UNIQUE ("); buffer.append(database.escapeColumnNameList(StringUtils.join(uniqueConstraint.getColumns(), ", "))); buffer.append(")"); if (uniqueConstraint.getConstraintName() != null && constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(","); } String sql = buffer.toString().replaceFirst(",\\s*$", "") + ")"; if (statement.getTablespace() != null && database.supportsTablespaces()) { if (database instanceof MSSQLDatabase || database instanceof SybaseASADatabase) { sql += " ON " + statement.getTablespace(); } else if (database instanceof DB2Database || database instanceof InformixDatabase) { sql += " IN " + statement.getTablespace(); } else { sql += " TABLESPACE " + statement.getTablespace(); } } return new Sql[] { new UnparsedSql(sql) }; } } | CreateTableGenerator extends AbstractSqlGenerator<CreateTableStatement> { public Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { StringBuffer buffer = new StringBuffer(); buffer.append("CREATE TABLE ").append(database.escapeTableName(statement.getSchemaName(), statement.getTableName())).append(" "); buffer.append("("); boolean isSinglePrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() == 1; boolean isPrimaryKeyAutoIncrement = false; Iterator<String> columnIterator = statement.getColumns().iterator(); while (columnIterator.hasNext()) { String column = columnIterator.next(); buffer.append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), column)); buffer.append(" ").append(statement.getColumnTypes().get(column)); AutoIncrementConstraint autoIncrementConstraint = null; for (AutoIncrementConstraint currentAutoIncrementConstraint : statement.getAutoIncrementConstraints()) { if (column.equals(currentAutoIncrementConstraint.getColumnName())) { autoIncrementConstraint = currentAutoIncrementConstraint; break; } } boolean isAutoIncrementColumn = autoIncrementConstraint != null; boolean isPrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().contains(column); isPrimaryKeyAutoIncrement = isPrimaryKeyAutoIncrement || isPrimaryKeyColumn && isAutoIncrementColumn; if ((database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyColumn && isAutoIncrementColumn) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } buffer.append(" PRIMARY KEY AUTOINCREMENT"); } if (statement.getDefaultValue(column) != null) { Object defaultValue = statement.getDefaultValue(column); if (database instanceof MSSQLDatabase) { buffer.append(" CONSTRAINT ").append(((MSSQLDatabase) database).generateDefaultConstraintName(statement.getTableName(), column)); } buffer.append(" DEFAULT "); buffer.append(statement.getColumnTypes().get(column).convertObjectToString(defaultValue, database)); } if (isAutoIncrementColumn && ! (database instanceof SQLiteDatabase)) { if (database.supportsAutoIncrement()) { String autoIncrementClause = database.getAutoIncrementClause(autoIncrementConstraint.getStartWith(), autoIncrementConstraint.getIncrementBy()); if (!"".equals(autoIncrementClause)) { buffer.append(" ").append(autoIncrementClause); } } else { LogFactory.getLogger().warning(database.getTypeName()+" does not support autoincrement columns as request for "+(database.escapeTableName(statement.getSchemaName(), statement.getTableName()))); } } if (statement.getNotNullColumns().contains(column)) { buffer.append(" NOT NULL"); } else { if (database instanceof SybaseDatabase || database instanceof SybaseASADatabase || database instanceof MySQLDatabase) { if (database instanceof MySQLDatabase && statement.getColumnTypes().get(column).getDataTypeName().equalsIgnoreCase("timestamp")) { } else { buffer.append(" NULL"); } } } if (database instanceof InformixDatabase && isSinglePrimaryKeyColumn) { buffer.append(" PRIMARY KEY"); } if (columnIterator.hasNext()) { buffer.append(", "); } } buffer.append(","); if (!( (database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyAutoIncrement) && !((database instanceof InformixDatabase) && isSinglePrimaryKeyColumn )) { if (statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() > 0) { if (!(database instanceof InformixDatabase)) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } } buffer.append(" PRIMARY KEY ("); buffer.append(database.escapeColumnNameList(StringUtils.join(statement.getPrimaryKeyConstraint().getColumns(), ", "))); buffer.append(")"); if (database instanceof OracleDatabase && statement.getPrimaryKeyConstraint().getTablespace() != null) { buffer.append(" USING INDEX TABLESPACE "); buffer.append(statement.getPrimaryKeyConstraint().getTablespace()); } buffer.append(","); } } for (ForeignKeyConstraint fkConstraint : statement.getForeignKeyConstraints()) { if (!(database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } String referencesString = fkConstraint.getReferences(); if (!referencesString.contains(".") && database.getDefaultSchemaName() != null) { referencesString = database.getDefaultSchemaName()+"."+referencesString; } buffer.append(" FOREIGN KEY (") .append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), fkConstraint.getColumn())) .append(") REFERENCES ") .append(referencesString); if (fkConstraint.isDeleteCascade()) { buffer.append(" ON DELETE CASCADE"); } if ((database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } if (fkConstraint.isInitiallyDeferred()) { buffer.append(" INITIALLY DEFERRED"); } if (fkConstraint.isDeferrable()) { buffer.append(" DEFERRABLE"); } buffer.append(","); } for (UniqueConstraint uniqueConstraint : statement.getUniqueConstraints()) { if (uniqueConstraint.getConstraintName() != null && !constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(" UNIQUE ("); buffer.append(database.escapeColumnNameList(StringUtils.join(uniqueConstraint.getColumns(), ", "))); buffer.append(")"); if (uniqueConstraint.getConstraintName() != null && constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(","); } String sql = buffer.toString().replaceFirst(",\\s*$", "") + ")"; if (statement.getTablespace() != null && database.supportsTablespaces()) { if (database instanceof MSSQLDatabase || database instanceof SybaseASADatabase) { sql += " ON " + statement.getTablespace(); } else if (database instanceof DB2Database || database instanceof InformixDatabase) { sql += " IN " + statement.getTablespace(); } else { sql += " TABLESPACE " + statement.getTablespace(); } } return new Sql[] { new UnparsedSql(sql) }; } } | CreateTableGenerator extends AbstractSqlGenerator<CreateTableStatement> { public Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { StringBuffer buffer = new StringBuffer(); buffer.append("CREATE TABLE ").append(database.escapeTableName(statement.getSchemaName(), statement.getTableName())).append(" "); buffer.append("("); boolean isSinglePrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() == 1; boolean isPrimaryKeyAutoIncrement = false; Iterator<String> columnIterator = statement.getColumns().iterator(); while (columnIterator.hasNext()) { String column = columnIterator.next(); buffer.append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), column)); buffer.append(" ").append(statement.getColumnTypes().get(column)); AutoIncrementConstraint autoIncrementConstraint = null; for (AutoIncrementConstraint currentAutoIncrementConstraint : statement.getAutoIncrementConstraints()) { if (column.equals(currentAutoIncrementConstraint.getColumnName())) { autoIncrementConstraint = currentAutoIncrementConstraint; break; } } boolean isAutoIncrementColumn = autoIncrementConstraint != null; boolean isPrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().contains(column); isPrimaryKeyAutoIncrement = isPrimaryKeyAutoIncrement || isPrimaryKeyColumn && isAutoIncrementColumn; if ((database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyColumn && isAutoIncrementColumn) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } buffer.append(" PRIMARY KEY AUTOINCREMENT"); } if (statement.getDefaultValue(column) != null) { Object defaultValue = statement.getDefaultValue(column); if (database instanceof MSSQLDatabase) { buffer.append(" CONSTRAINT ").append(((MSSQLDatabase) database).generateDefaultConstraintName(statement.getTableName(), column)); } buffer.append(" DEFAULT "); buffer.append(statement.getColumnTypes().get(column).convertObjectToString(defaultValue, database)); } if (isAutoIncrementColumn && ! (database instanceof SQLiteDatabase)) { if (database.supportsAutoIncrement()) { String autoIncrementClause = database.getAutoIncrementClause(autoIncrementConstraint.getStartWith(), autoIncrementConstraint.getIncrementBy()); if (!"".equals(autoIncrementClause)) { buffer.append(" ").append(autoIncrementClause); } } else { LogFactory.getLogger().warning(database.getTypeName()+" does not support autoincrement columns as request for "+(database.escapeTableName(statement.getSchemaName(), statement.getTableName()))); } } if (statement.getNotNullColumns().contains(column)) { buffer.append(" NOT NULL"); } else { if (database instanceof SybaseDatabase || database instanceof SybaseASADatabase || database instanceof MySQLDatabase) { if (database instanceof MySQLDatabase && statement.getColumnTypes().get(column).getDataTypeName().equalsIgnoreCase("timestamp")) { } else { buffer.append(" NULL"); } } } if (database instanceof InformixDatabase && isSinglePrimaryKeyColumn) { buffer.append(" PRIMARY KEY"); } if (columnIterator.hasNext()) { buffer.append(", "); } } buffer.append(","); if (!( (database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyAutoIncrement) && !((database instanceof InformixDatabase) && isSinglePrimaryKeyColumn )) { if (statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() > 0) { if (!(database instanceof InformixDatabase)) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } } buffer.append(" PRIMARY KEY ("); buffer.append(database.escapeColumnNameList(StringUtils.join(statement.getPrimaryKeyConstraint().getColumns(), ", "))); buffer.append(")"); if (database instanceof OracleDatabase && statement.getPrimaryKeyConstraint().getTablespace() != null) { buffer.append(" USING INDEX TABLESPACE "); buffer.append(statement.getPrimaryKeyConstraint().getTablespace()); } buffer.append(","); } } for (ForeignKeyConstraint fkConstraint : statement.getForeignKeyConstraints()) { if (!(database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } String referencesString = fkConstraint.getReferences(); if (!referencesString.contains(".") && database.getDefaultSchemaName() != null) { referencesString = database.getDefaultSchemaName()+"."+referencesString; } buffer.append(" FOREIGN KEY (") .append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), fkConstraint.getColumn())) .append(") REFERENCES ") .append(referencesString); if (fkConstraint.isDeleteCascade()) { buffer.append(" ON DELETE CASCADE"); } if ((database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } if (fkConstraint.isInitiallyDeferred()) { buffer.append(" INITIALLY DEFERRED"); } if (fkConstraint.isDeferrable()) { buffer.append(" DEFERRABLE"); } buffer.append(","); } for (UniqueConstraint uniqueConstraint : statement.getUniqueConstraints()) { if (uniqueConstraint.getConstraintName() != null && !constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(" UNIQUE ("); buffer.append(database.escapeColumnNameList(StringUtils.join(uniqueConstraint.getColumns(), ", "))); buffer.append(")"); if (uniqueConstraint.getConstraintName() != null && constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(","); } String sql = buffer.toString().replaceFirst(",\\s*$", "") + ")"; if (statement.getTablespace() != null && database.supportsTablespaces()) { if (database instanceof MSSQLDatabase || database instanceof SybaseASADatabase) { sql += " ON " + statement.getTablespace(); } else if (database instanceof DB2Database || database instanceof InformixDatabase) { sql += " IN " + statement.getTablespace(); } else { sql += " TABLESPACE " + statement.getTablespace(); } } return new Sql[] { new UnparsedSql(sql) }; } ValidationErrors validate(CreateTableStatement createTableStatement, Database database, SqlGeneratorChain sqlGeneratorChain); Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain); } | CreateTableGenerator extends AbstractSqlGenerator<CreateTableStatement> { public Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { StringBuffer buffer = new StringBuffer(); buffer.append("CREATE TABLE ").append(database.escapeTableName(statement.getSchemaName(), statement.getTableName())).append(" "); buffer.append("("); boolean isSinglePrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() == 1; boolean isPrimaryKeyAutoIncrement = false; Iterator<String> columnIterator = statement.getColumns().iterator(); while (columnIterator.hasNext()) { String column = columnIterator.next(); buffer.append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), column)); buffer.append(" ").append(statement.getColumnTypes().get(column)); AutoIncrementConstraint autoIncrementConstraint = null; for (AutoIncrementConstraint currentAutoIncrementConstraint : statement.getAutoIncrementConstraints()) { if (column.equals(currentAutoIncrementConstraint.getColumnName())) { autoIncrementConstraint = currentAutoIncrementConstraint; break; } } boolean isAutoIncrementColumn = autoIncrementConstraint != null; boolean isPrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().contains(column); isPrimaryKeyAutoIncrement = isPrimaryKeyAutoIncrement || isPrimaryKeyColumn && isAutoIncrementColumn; if ((database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyColumn && isAutoIncrementColumn) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } buffer.append(" PRIMARY KEY AUTOINCREMENT"); } if (statement.getDefaultValue(column) != null) { Object defaultValue = statement.getDefaultValue(column); if (database instanceof MSSQLDatabase) { buffer.append(" CONSTRAINT ").append(((MSSQLDatabase) database).generateDefaultConstraintName(statement.getTableName(), column)); } buffer.append(" DEFAULT "); buffer.append(statement.getColumnTypes().get(column).convertObjectToString(defaultValue, database)); } if (isAutoIncrementColumn && ! (database instanceof SQLiteDatabase)) { if (database.supportsAutoIncrement()) { String autoIncrementClause = database.getAutoIncrementClause(autoIncrementConstraint.getStartWith(), autoIncrementConstraint.getIncrementBy()); if (!"".equals(autoIncrementClause)) { buffer.append(" ").append(autoIncrementClause); } } else { LogFactory.getLogger().warning(database.getTypeName()+" does not support autoincrement columns as request for "+(database.escapeTableName(statement.getSchemaName(), statement.getTableName()))); } } if (statement.getNotNullColumns().contains(column)) { buffer.append(" NOT NULL"); } else { if (database instanceof SybaseDatabase || database instanceof SybaseASADatabase || database instanceof MySQLDatabase) { if (database instanceof MySQLDatabase && statement.getColumnTypes().get(column).getDataTypeName().equalsIgnoreCase("timestamp")) { } else { buffer.append(" NULL"); } } } if (database instanceof InformixDatabase && isSinglePrimaryKeyColumn) { buffer.append(" PRIMARY KEY"); } if (columnIterator.hasNext()) { buffer.append(", "); } } buffer.append(","); if (!( (database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyAutoIncrement) && !((database instanceof InformixDatabase) && isSinglePrimaryKeyColumn )) { if (statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() > 0) { if (!(database instanceof InformixDatabase)) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } } buffer.append(" PRIMARY KEY ("); buffer.append(database.escapeColumnNameList(StringUtils.join(statement.getPrimaryKeyConstraint().getColumns(), ", "))); buffer.append(")"); if (database instanceof OracleDatabase && statement.getPrimaryKeyConstraint().getTablespace() != null) { buffer.append(" USING INDEX TABLESPACE "); buffer.append(statement.getPrimaryKeyConstraint().getTablespace()); } buffer.append(","); } } for (ForeignKeyConstraint fkConstraint : statement.getForeignKeyConstraints()) { if (!(database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } String referencesString = fkConstraint.getReferences(); if (!referencesString.contains(".") && database.getDefaultSchemaName() != null) { referencesString = database.getDefaultSchemaName()+"."+referencesString; } buffer.append(" FOREIGN KEY (") .append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), fkConstraint.getColumn())) .append(") REFERENCES ") .append(referencesString); if (fkConstraint.isDeleteCascade()) { buffer.append(" ON DELETE CASCADE"); } if ((database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } if (fkConstraint.isInitiallyDeferred()) { buffer.append(" INITIALLY DEFERRED"); } if (fkConstraint.isDeferrable()) { buffer.append(" DEFERRABLE"); } buffer.append(","); } for (UniqueConstraint uniqueConstraint : statement.getUniqueConstraints()) { if (uniqueConstraint.getConstraintName() != null && !constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(" UNIQUE ("); buffer.append(database.escapeColumnNameList(StringUtils.join(uniqueConstraint.getColumns(), ", "))); buffer.append(")"); if (uniqueConstraint.getConstraintName() != null && constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(","); } String sql = buffer.toString().replaceFirst(",\\s*$", "") + ")"; if (statement.getTablespace() != null && database.supportsTablespaces()) { if (database instanceof MSSQLDatabase || database instanceof SybaseASADatabase) { sql += " ON " + statement.getTablespace(); } else if (database instanceof DB2Database || database instanceof InformixDatabase) { sql += " IN " + statement.getTablespace(); } else { sql += " TABLESPACE " + statement.getTablespace(); } } return new Sql[] { new UnparsedSql(sql) }; } ValidationErrors validate(CreateTableStatement createTableStatement, Database database, SqlGeneratorChain sqlGeneratorChain); Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain); } |
@Test public void testAutoIncrementStartWithIncrementByPostgresDatabase() throws Exception { for (Database database : TestContext.getInstance().getAllDatabases()) { if (database instanceof PostgresDatabase) { CreateTableStatement statement = new CreateTableStatement(SCHEMA_NAME, TABLE_NAME); statement.addColumn( COLUMN_NAME1, TypeConverterFactory.getInstance().findTypeConverter(database).getDataType("BIGINT", true), new AutoIncrementConstraint(COLUMN_NAME1, BigInteger.ZERO, BigInteger.TEN) ); Sql[] generatedSql = this.generatorUnderTest.generateSql(statement, database, null); assertEquals("CREATE TABLE SCHEMA_NAME.TABLE_NAME (COLUMN1_NAME bigserial)", generatedSql[0].toSql()); } } } | public Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { StringBuffer buffer = new StringBuffer(); buffer.append("CREATE TABLE ").append(database.escapeTableName(statement.getSchemaName(), statement.getTableName())).append(" "); buffer.append("("); boolean isSinglePrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() == 1; boolean isPrimaryKeyAutoIncrement = false; Iterator<String> columnIterator = statement.getColumns().iterator(); while (columnIterator.hasNext()) { String column = columnIterator.next(); buffer.append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), column)); buffer.append(" ").append(statement.getColumnTypes().get(column)); AutoIncrementConstraint autoIncrementConstraint = null; for (AutoIncrementConstraint currentAutoIncrementConstraint : statement.getAutoIncrementConstraints()) { if (column.equals(currentAutoIncrementConstraint.getColumnName())) { autoIncrementConstraint = currentAutoIncrementConstraint; break; } } boolean isAutoIncrementColumn = autoIncrementConstraint != null; boolean isPrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().contains(column); isPrimaryKeyAutoIncrement = isPrimaryKeyAutoIncrement || isPrimaryKeyColumn && isAutoIncrementColumn; if ((database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyColumn && isAutoIncrementColumn) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } buffer.append(" PRIMARY KEY AUTOINCREMENT"); } if (statement.getDefaultValue(column) != null) { Object defaultValue = statement.getDefaultValue(column); if (database instanceof MSSQLDatabase) { buffer.append(" CONSTRAINT ").append(((MSSQLDatabase) database).generateDefaultConstraintName(statement.getTableName(), column)); } buffer.append(" DEFAULT "); buffer.append(statement.getColumnTypes().get(column).convertObjectToString(defaultValue, database)); } if (isAutoIncrementColumn && ! (database instanceof SQLiteDatabase)) { if (database.supportsAutoIncrement()) { String autoIncrementClause = database.getAutoIncrementClause(autoIncrementConstraint.getStartWith(), autoIncrementConstraint.getIncrementBy()); if (!"".equals(autoIncrementClause)) { buffer.append(" ").append(autoIncrementClause); } } else { LogFactory.getLogger().warning(database.getTypeName()+" does not support autoincrement columns as request for "+(database.escapeTableName(statement.getSchemaName(), statement.getTableName()))); } } if (statement.getNotNullColumns().contains(column)) { buffer.append(" NOT NULL"); } else { if (database instanceof SybaseDatabase || database instanceof SybaseASADatabase || database instanceof MySQLDatabase) { if (database instanceof MySQLDatabase && statement.getColumnTypes().get(column).getDataTypeName().equalsIgnoreCase("timestamp")) { } else { buffer.append(" NULL"); } } } if (database instanceof InformixDatabase && isSinglePrimaryKeyColumn) { buffer.append(" PRIMARY KEY"); } if (columnIterator.hasNext()) { buffer.append(", "); } } buffer.append(","); if (!( (database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyAutoIncrement) && !((database instanceof InformixDatabase) && isSinglePrimaryKeyColumn )) { if (statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() > 0) { if (!(database instanceof InformixDatabase)) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } } buffer.append(" PRIMARY KEY ("); buffer.append(database.escapeColumnNameList(StringUtils.join(statement.getPrimaryKeyConstraint().getColumns(), ", "))); buffer.append(")"); if (database instanceof OracleDatabase && statement.getPrimaryKeyConstraint().getTablespace() != null) { buffer.append(" USING INDEX TABLESPACE "); buffer.append(statement.getPrimaryKeyConstraint().getTablespace()); } buffer.append(","); } } for (ForeignKeyConstraint fkConstraint : statement.getForeignKeyConstraints()) { if (!(database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } String referencesString = fkConstraint.getReferences(); if (!referencesString.contains(".") && database.getDefaultSchemaName() != null) { referencesString = database.getDefaultSchemaName()+"."+referencesString; } buffer.append(" FOREIGN KEY (") .append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), fkConstraint.getColumn())) .append(") REFERENCES ") .append(referencesString); if (fkConstraint.isDeleteCascade()) { buffer.append(" ON DELETE CASCADE"); } if ((database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } if (fkConstraint.isInitiallyDeferred()) { buffer.append(" INITIALLY DEFERRED"); } if (fkConstraint.isDeferrable()) { buffer.append(" DEFERRABLE"); } buffer.append(","); } for (UniqueConstraint uniqueConstraint : statement.getUniqueConstraints()) { if (uniqueConstraint.getConstraintName() != null && !constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(" UNIQUE ("); buffer.append(database.escapeColumnNameList(StringUtils.join(uniqueConstraint.getColumns(), ", "))); buffer.append(")"); if (uniqueConstraint.getConstraintName() != null && constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(","); } String sql = buffer.toString().replaceFirst(",\\s*$", "") + ")"; if (statement.getTablespace() != null && database.supportsTablespaces()) { if (database instanceof MSSQLDatabase || database instanceof SybaseASADatabase) { sql += " ON " + statement.getTablespace(); } else if (database instanceof DB2Database || database instanceof InformixDatabase) { sql += " IN " + statement.getTablespace(); } else { sql += " TABLESPACE " + statement.getTablespace(); } } return new Sql[] { new UnparsedSql(sql) }; } | CreateTableGenerator extends AbstractSqlGenerator<CreateTableStatement> { public Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { StringBuffer buffer = new StringBuffer(); buffer.append("CREATE TABLE ").append(database.escapeTableName(statement.getSchemaName(), statement.getTableName())).append(" "); buffer.append("("); boolean isSinglePrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() == 1; boolean isPrimaryKeyAutoIncrement = false; Iterator<String> columnIterator = statement.getColumns().iterator(); while (columnIterator.hasNext()) { String column = columnIterator.next(); buffer.append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), column)); buffer.append(" ").append(statement.getColumnTypes().get(column)); AutoIncrementConstraint autoIncrementConstraint = null; for (AutoIncrementConstraint currentAutoIncrementConstraint : statement.getAutoIncrementConstraints()) { if (column.equals(currentAutoIncrementConstraint.getColumnName())) { autoIncrementConstraint = currentAutoIncrementConstraint; break; } } boolean isAutoIncrementColumn = autoIncrementConstraint != null; boolean isPrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().contains(column); isPrimaryKeyAutoIncrement = isPrimaryKeyAutoIncrement || isPrimaryKeyColumn && isAutoIncrementColumn; if ((database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyColumn && isAutoIncrementColumn) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } buffer.append(" PRIMARY KEY AUTOINCREMENT"); } if (statement.getDefaultValue(column) != null) { Object defaultValue = statement.getDefaultValue(column); if (database instanceof MSSQLDatabase) { buffer.append(" CONSTRAINT ").append(((MSSQLDatabase) database).generateDefaultConstraintName(statement.getTableName(), column)); } buffer.append(" DEFAULT "); buffer.append(statement.getColumnTypes().get(column).convertObjectToString(defaultValue, database)); } if (isAutoIncrementColumn && ! (database instanceof SQLiteDatabase)) { if (database.supportsAutoIncrement()) { String autoIncrementClause = database.getAutoIncrementClause(autoIncrementConstraint.getStartWith(), autoIncrementConstraint.getIncrementBy()); if (!"".equals(autoIncrementClause)) { buffer.append(" ").append(autoIncrementClause); } } else { LogFactory.getLogger().warning(database.getTypeName()+" does not support autoincrement columns as request for "+(database.escapeTableName(statement.getSchemaName(), statement.getTableName()))); } } if (statement.getNotNullColumns().contains(column)) { buffer.append(" NOT NULL"); } else { if (database instanceof SybaseDatabase || database instanceof SybaseASADatabase || database instanceof MySQLDatabase) { if (database instanceof MySQLDatabase && statement.getColumnTypes().get(column).getDataTypeName().equalsIgnoreCase("timestamp")) { } else { buffer.append(" NULL"); } } } if (database instanceof InformixDatabase && isSinglePrimaryKeyColumn) { buffer.append(" PRIMARY KEY"); } if (columnIterator.hasNext()) { buffer.append(", "); } } buffer.append(","); if (!( (database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyAutoIncrement) && !((database instanceof InformixDatabase) && isSinglePrimaryKeyColumn )) { if (statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() > 0) { if (!(database instanceof InformixDatabase)) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } } buffer.append(" PRIMARY KEY ("); buffer.append(database.escapeColumnNameList(StringUtils.join(statement.getPrimaryKeyConstraint().getColumns(), ", "))); buffer.append(")"); if (database instanceof OracleDatabase && statement.getPrimaryKeyConstraint().getTablespace() != null) { buffer.append(" USING INDEX TABLESPACE "); buffer.append(statement.getPrimaryKeyConstraint().getTablespace()); } buffer.append(","); } } for (ForeignKeyConstraint fkConstraint : statement.getForeignKeyConstraints()) { if (!(database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } String referencesString = fkConstraint.getReferences(); if (!referencesString.contains(".") && database.getDefaultSchemaName() != null) { referencesString = database.getDefaultSchemaName()+"."+referencesString; } buffer.append(" FOREIGN KEY (") .append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), fkConstraint.getColumn())) .append(") REFERENCES ") .append(referencesString); if (fkConstraint.isDeleteCascade()) { buffer.append(" ON DELETE CASCADE"); } if ((database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } if (fkConstraint.isInitiallyDeferred()) { buffer.append(" INITIALLY DEFERRED"); } if (fkConstraint.isDeferrable()) { buffer.append(" DEFERRABLE"); } buffer.append(","); } for (UniqueConstraint uniqueConstraint : statement.getUniqueConstraints()) { if (uniqueConstraint.getConstraintName() != null && !constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(" UNIQUE ("); buffer.append(database.escapeColumnNameList(StringUtils.join(uniqueConstraint.getColumns(), ", "))); buffer.append(")"); if (uniqueConstraint.getConstraintName() != null && constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(","); } String sql = buffer.toString().replaceFirst(",\\s*$", "") + ")"; if (statement.getTablespace() != null && database.supportsTablespaces()) { if (database instanceof MSSQLDatabase || database instanceof SybaseASADatabase) { sql += " ON " + statement.getTablespace(); } else if (database instanceof DB2Database || database instanceof InformixDatabase) { sql += " IN " + statement.getTablespace(); } else { sql += " TABLESPACE " + statement.getTablespace(); } } return new Sql[] { new UnparsedSql(sql) }; } } | CreateTableGenerator extends AbstractSqlGenerator<CreateTableStatement> { public Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { StringBuffer buffer = new StringBuffer(); buffer.append("CREATE TABLE ").append(database.escapeTableName(statement.getSchemaName(), statement.getTableName())).append(" "); buffer.append("("); boolean isSinglePrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() == 1; boolean isPrimaryKeyAutoIncrement = false; Iterator<String> columnIterator = statement.getColumns().iterator(); while (columnIterator.hasNext()) { String column = columnIterator.next(); buffer.append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), column)); buffer.append(" ").append(statement.getColumnTypes().get(column)); AutoIncrementConstraint autoIncrementConstraint = null; for (AutoIncrementConstraint currentAutoIncrementConstraint : statement.getAutoIncrementConstraints()) { if (column.equals(currentAutoIncrementConstraint.getColumnName())) { autoIncrementConstraint = currentAutoIncrementConstraint; break; } } boolean isAutoIncrementColumn = autoIncrementConstraint != null; boolean isPrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().contains(column); isPrimaryKeyAutoIncrement = isPrimaryKeyAutoIncrement || isPrimaryKeyColumn && isAutoIncrementColumn; if ((database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyColumn && isAutoIncrementColumn) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } buffer.append(" PRIMARY KEY AUTOINCREMENT"); } if (statement.getDefaultValue(column) != null) { Object defaultValue = statement.getDefaultValue(column); if (database instanceof MSSQLDatabase) { buffer.append(" CONSTRAINT ").append(((MSSQLDatabase) database).generateDefaultConstraintName(statement.getTableName(), column)); } buffer.append(" DEFAULT "); buffer.append(statement.getColumnTypes().get(column).convertObjectToString(defaultValue, database)); } if (isAutoIncrementColumn && ! (database instanceof SQLiteDatabase)) { if (database.supportsAutoIncrement()) { String autoIncrementClause = database.getAutoIncrementClause(autoIncrementConstraint.getStartWith(), autoIncrementConstraint.getIncrementBy()); if (!"".equals(autoIncrementClause)) { buffer.append(" ").append(autoIncrementClause); } } else { LogFactory.getLogger().warning(database.getTypeName()+" does not support autoincrement columns as request for "+(database.escapeTableName(statement.getSchemaName(), statement.getTableName()))); } } if (statement.getNotNullColumns().contains(column)) { buffer.append(" NOT NULL"); } else { if (database instanceof SybaseDatabase || database instanceof SybaseASADatabase || database instanceof MySQLDatabase) { if (database instanceof MySQLDatabase && statement.getColumnTypes().get(column).getDataTypeName().equalsIgnoreCase("timestamp")) { } else { buffer.append(" NULL"); } } } if (database instanceof InformixDatabase && isSinglePrimaryKeyColumn) { buffer.append(" PRIMARY KEY"); } if (columnIterator.hasNext()) { buffer.append(", "); } } buffer.append(","); if (!( (database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyAutoIncrement) && !((database instanceof InformixDatabase) && isSinglePrimaryKeyColumn )) { if (statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() > 0) { if (!(database instanceof InformixDatabase)) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } } buffer.append(" PRIMARY KEY ("); buffer.append(database.escapeColumnNameList(StringUtils.join(statement.getPrimaryKeyConstraint().getColumns(), ", "))); buffer.append(")"); if (database instanceof OracleDatabase && statement.getPrimaryKeyConstraint().getTablespace() != null) { buffer.append(" USING INDEX TABLESPACE "); buffer.append(statement.getPrimaryKeyConstraint().getTablespace()); } buffer.append(","); } } for (ForeignKeyConstraint fkConstraint : statement.getForeignKeyConstraints()) { if (!(database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } String referencesString = fkConstraint.getReferences(); if (!referencesString.contains(".") && database.getDefaultSchemaName() != null) { referencesString = database.getDefaultSchemaName()+"."+referencesString; } buffer.append(" FOREIGN KEY (") .append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), fkConstraint.getColumn())) .append(") REFERENCES ") .append(referencesString); if (fkConstraint.isDeleteCascade()) { buffer.append(" ON DELETE CASCADE"); } if ((database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } if (fkConstraint.isInitiallyDeferred()) { buffer.append(" INITIALLY DEFERRED"); } if (fkConstraint.isDeferrable()) { buffer.append(" DEFERRABLE"); } buffer.append(","); } for (UniqueConstraint uniqueConstraint : statement.getUniqueConstraints()) { if (uniqueConstraint.getConstraintName() != null && !constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(" UNIQUE ("); buffer.append(database.escapeColumnNameList(StringUtils.join(uniqueConstraint.getColumns(), ", "))); buffer.append(")"); if (uniqueConstraint.getConstraintName() != null && constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(","); } String sql = buffer.toString().replaceFirst(",\\s*$", "") + ")"; if (statement.getTablespace() != null && database.supportsTablespaces()) { if (database instanceof MSSQLDatabase || database instanceof SybaseASADatabase) { sql += " ON " + statement.getTablespace(); } else if (database instanceof DB2Database || database instanceof InformixDatabase) { sql += " IN " + statement.getTablespace(); } else { sql += " TABLESPACE " + statement.getTablespace(); } } return new Sql[] { new UnparsedSql(sql) }; } } | CreateTableGenerator extends AbstractSqlGenerator<CreateTableStatement> { public Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { StringBuffer buffer = new StringBuffer(); buffer.append("CREATE TABLE ").append(database.escapeTableName(statement.getSchemaName(), statement.getTableName())).append(" "); buffer.append("("); boolean isSinglePrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() == 1; boolean isPrimaryKeyAutoIncrement = false; Iterator<String> columnIterator = statement.getColumns().iterator(); while (columnIterator.hasNext()) { String column = columnIterator.next(); buffer.append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), column)); buffer.append(" ").append(statement.getColumnTypes().get(column)); AutoIncrementConstraint autoIncrementConstraint = null; for (AutoIncrementConstraint currentAutoIncrementConstraint : statement.getAutoIncrementConstraints()) { if (column.equals(currentAutoIncrementConstraint.getColumnName())) { autoIncrementConstraint = currentAutoIncrementConstraint; break; } } boolean isAutoIncrementColumn = autoIncrementConstraint != null; boolean isPrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().contains(column); isPrimaryKeyAutoIncrement = isPrimaryKeyAutoIncrement || isPrimaryKeyColumn && isAutoIncrementColumn; if ((database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyColumn && isAutoIncrementColumn) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } buffer.append(" PRIMARY KEY AUTOINCREMENT"); } if (statement.getDefaultValue(column) != null) { Object defaultValue = statement.getDefaultValue(column); if (database instanceof MSSQLDatabase) { buffer.append(" CONSTRAINT ").append(((MSSQLDatabase) database).generateDefaultConstraintName(statement.getTableName(), column)); } buffer.append(" DEFAULT "); buffer.append(statement.getColumnTypes().get(column).convertObjectToString(defaultValue, database)); } if (isAutoIncrementColumn && ! (database instanceof SQLiteDatabase)) { if (database.supportsAutoIncrement()) { String autoIncrementClause = database.getAutoIncrementClause(autoIncrementConstraint.getStartWith(), autoIncrementConstraint.getIncrementBy()); if (!"".equals(autoIncrementClause)) { buffer.append(" ").append(autoIncrementClause); } } else { LogFactory.getLogger().warning(database.getTypeName()+" does not support autoincrement columns as request for "+(database.escapeTableName(statement.getSchemaName(), statement.getTableName()))); } } if (statement.getNotNullColumns().contains(column)) { buffer.append(" NOT NULL"); } else { if (database instanceof SybaseDatabase || database instanceof SybaseASADatabase || database instanceof MySQLDatabase) { if (database instanceof MySQLDatabase && statement.getColumnTypes().get(column).getDataTypeName().equalsIgnoreCase("timestamp")) { } else { buffer.append(" NULL"); } } } if (database instanceof InformixDatabase && isSinglePrimaryKeyColumn) { buffer.append(" PRIMARY KEY"); } if (columnIterator.hasNext()) { buffer.append(", "); } } buffer.append(","); if (!( (database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyAutoIncrement) && !((database instanceof InformixDatabase) && isSinglePrimaryKeyColumn )) { if (statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() > 0) { if (!(database instanceof InformixDatabase)) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } } buffer.append(" PRIMARY KEY ("); buffer.append(database.escapeColumnNameList(StringUtils.join(statement.getPrimaryKeyConstraint().getColumns(), ", "))); buffer.append(")"); if (database instanceof OracleDatabase && statement.getPrimaryKeyConstraint().getTablespace() != null) { buffer.append(" USING INDEX TABLESPACE "); buffer.append(statement.getPrimaryKeyConstraint().getTablespace()); } buffer.append(","); } } for (ForeignKeyConstraint fkConstraint : statement.getForeignKeyConstraints()) { if (!(database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } String referencesString = fkConstraint.getReferences(); if (!referencesString.contains(".") && database.getDefaultSchemaName() != null) { referencesString = database.getDefaultSchemaName()+"."+referencesString; } buffer.append(" FOREIGN KEY (") .append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), fkConstraint.getColumn())) .append(") REFERENCES ") .append(referencesString); if (fkConstraint.isDeleteCascade()) { buffer.append(" ON DELETE CASCADE"); } if ((database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } if (fkConstraint.isInitiallyDeferred()) { buffer.append(" INITIALLY DEFERRED"); } if (fkConstraint.isDeferrable()) { buffer.append(" DEFERRABLE"); } buffer.append(","); } for (UniqueConstraint uniqueConstraint : statement.getUniqueConstraints()) { if (uniqueConstraint.getConstraintName() != null && !constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(" UNIQUE ("); buffer.append(database.escapeColumnNameList(StringUtils.join(uniqueConstraint.getColumns(), ", "))); buffer.append(")"); if (uniqueConstraint.getConstraintName() != null && constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(","); } String sql = buffer.toString().replaceFirst(",\\s*$", "") + ")"; if (statement.getTablespace() != null && database.supportsTablespaces()) { if (database instanceof MSSQLDatabase || database instanceof SybaseASADatabase) { sql += " ON " + statement.getTablespace(); } else if (database instanceof DB2Database || database instanceof InformixDatabase) { sql += " IN " + statement.getTablespace(); } else { sql += " TABLESPACE " + statement.getTablespace(); } } return new Sql[] { new UnparsedSql(sql) }; } ValidationErrors validate(CreateTableStatement createTableStatement, Database database, SqlGeneratorChain sqlGeneratorChain); Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain); } | CreateTableGenerator extends AbstractSqlGenerator<CreateTableStatement> { public Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { StringBuffer buffer = new StringBuffer(); buffer.append("CREATE TABLE ").append(database.escapeTableName(statement.getSchemaName(), statement.getTableName())).append(" "); buffer.append("("); boolean isSinglePrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() == 1; boolean isPrimaryKeyAutoIncrement = false; Iterator<String> columnIterator = statement.getColumns().iterator(); while (columnIterator.hasNext()) { String column = columnIterator.next(); buffer.append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), column)); buffer.append(" ").append(statement.getColumnTypes().get(column)); AutoIncrementConstraint autoIncrementConstraint = null; for (AutoIncrementConstraint currentAutoIncrementConstraint : statement.getAutoIncrementConstraints()) { if (column.equals(currentAutoIncrementConstraint.getColumnName())) { autoIncrementConstraint = currentAutoIncrementConstraint; break; } } boolean isAutoIncrementColumn = autoIncrementConstraint != null; boolean isPrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().contains(column); isPrimaryKeyAutoIncrement = isPrimaryKeyAutoIncrement || isPrimaryKeyColumn && isAutoIncrementColumn; if ((database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyColumn && isAutoIncrementColumn) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } buffer.append(" PRIMARY KEY AUTOINCREMENT"); } if (statement.getDefaultValue(column) != null) { Object defaultValue = statement.getDefaultValue(column); if (database instanceof MSSQLDatabase) { buffer.append(" CONSTRAINT ").append(((MSSQLDatabase) database).generateDefaultConstraintName(statement.getTableName(), column)); } buffer.append(" DEFAULT "); buffer.append(statement.getColumnTypes().get(column).convertObjectToString(defaultValue, database)); } if (isAutoIncrementColumn && ! (database instanceof SQLiteDatabase)) { if (database.supportsAutoIncrement()) { String autoIncrementClause = database.getAutoIncrementClause(autoIncrementConstraint.getStartWith(), autoIncrementConstraint.getIncrementBy()); if (!"".equals(autoIncrementClause)) { buffer.append(" ").append(autoIncrementClause); } } else { LogFactory.getLogger().warning(database.getTypeName()+" does not support autoincrement columns as request for "+(database.escapeTableName(statement.getSchemaName(), statement.getTableName()))); } } if (statement.getNotNullColumns().contains(column)) { buffer.append(" NOT NULL"); } else { if (database instanceof SybaseDatabase || database instanceof SybaseASADatabase || database instanceof MySQLDatabase) { if (database instanceof MySQLDatabase && statement.getColumnTypes().get(column).getDataTypeName().equalsIgnoreCase("timestamp")) { } else { buffer.append(" NULL"); } } } if (database instanceof InformixDatabase && isSinglePrimaryKeyColumn) { buffer.append(" PRIMARY KEY"); } if (columnIterator.hasNext()) { buffer.append(", "); } } buffer.append(","); if (!( (database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyAutoIncrement) && !((database instanceof InformixDatabase) && isSinglePrimaryKeyColumn )) { if (statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() > 0) { if (!(database instanceof InformixDatabase)) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } } buffer.append(" PRIMARY KEY ("); buffer.append(database.escapeColumnNameList(StringUtils.join(statement.getPrimaryKeyConstraint().getColumns(), ", "))); buffer.append(")"); if (database instanceof OracleDatabase && statement.getPrimaryKeyConstraint().getTablespace() != null) { buffer.append(" USING INDEX TABLESPACE "); buffer.append(statement.getPrimaryKeyConstraint().getTablespace()); } buffer.append(","); } } for (ForeignKeyConstraint fkConstraint : statement.getForeignKeyConstraints()) { if (!(database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } String referencesString = fkConstraint.getReferences(); if (!referencesString.contains(".") && database.getDefaultSchemaName() != null) { referencesString = database.getDefaultSchemaName()+"."+referencesString; } buffer.append(" FOREIGN KEY (") .append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), fkConstraint.getColumn())) .append(") REFERENCES ") .append(referencesString); if (fkConstraint.isDeleteCascade()) { buffer.append(" ON DELETE CASCADE"); } if ((database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } if (fkConstraint.isInitiallyDeferred()) { buffer.append(" INITIALLY DEFERRED"); } if (fkConstraint.isDeferrable()) { buffer.append(" DEFERRABLE"); } buffer.append(","); } for (UniqueConstraint uniqueConstraint : statement.getUniqueConstraints()) { if (uniqueConstraint.getConstraintName() != null && !constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(" UNIQUE ("); buffer.append(database.escapeColumnNameList(StringUtils.join(uniqueConstraint.getColumns(), ", "))); buffer.append(")"); if (uniqueConstraint.getConstraintName() != null && constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(","); } String sql = buffer.toString().replaceFirst(",\\s*$", "") + ")"; if (statement.getTablespace() != null && database.supportsTablespaces()) { if (database instanceof MSSQLDatabase || database instanceof SybaseASADatabase) { sql += " ON " + statement.getTablespace(); } else if (database instanceof DB2Database || database instanceof InformixDatabase) { sql += " IN " + statement.getTablespace(); } else { sql += " TABLESPACE " + statement.getTablespace(); } } return new Sql[] { new UnparsedSql(sql) }; } ValidationErrors validate(CreateTableStatement createTableStatement, Database database, SqlGeneratorChain sqlGeneratorChain); Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain); } |
@Test public void splitWithGo() { String testString = "SELECT *\n" + " FROM sys.objects\n" + " WHERE object_id = OBJECT_ID(N'[test].[currval]')\n" + " AND type in (N'FN', N'IF', N'TF', N'FS', N'FT')\n" + " )\n" + " DROP FUNCTION [test].[currval]\n" + "go\n" + " IF EXISTS\n" + " (\n" + " SELECT *\n" + " FROM sys.objects\n" + " WHERE object_id = OBJECT_ID(N'[test].[nextval]')\n" + " AND type in (N'P', N'PC')\n" + " )\n" + " DROP PROCEDURE [test].[nextval]:"; String[] strings = StringUtils.splitSQL(testString, null); assertEquals(2, strings.length); } | public static String[] splitSQL(String multiLineSQL, String endDelimiter) { if (endDelimiter == null) { endDelimiter = ";\\s*\n|;$|\n[gG][oO]\\s*\n|\n[Gg][oO]\\s*$"; } else { if (endDelimiter.equalsIgnoreCase("go")) { endDelimiter = "\n[gG][oO]\\s*\n|\n[Gg][oO]\\s*$"; } } String[] initialSplit = multiLineSQL.split(endDelimiter); List<String> strings = new ArrayList<String>(); for (String anInitialSplit : initialSplit) { String singleLineSQL = anInitialSplit.trim(); if (singleLineSQL.length() > 0) { strings.add(singleLineSQL); } } return strings.toArray(new String[strings.size()]); } | StringUtils { public static String[] splitSQL(String multiLineSQL, String endDelimiter) { if (endDelimiter == null) { endDelimiter = ";\\s*\n|;$|\n[gG][oO]\\s*\n|\n[Gg][oO]\\s*$"; } else { if (endDelimiter.equalsIgnoreCase("go")) { endDelimiter = "\n[gG][oO]\\s*\n|\n[Gg][oO]\\s*$"; } } String[] initialSplit = multiLineSQL.split(endDelimiter); List<String> strings = new ArrayList<String>(); for (String anInitialSplit : initialSplit) { String singleLineSQL = anInitialSplit.trim(); if (singleLineSQL.length() > 0) { strings.add(singleLineSQL); } } return strings.toArray(new String[strings.size()]); } } | StringUtils { public static String[] splitSQL(String multiLineSQL, String endDelimiter) { if (endDelimiter == null) { endDelimiter = ";\\s*\n|;$|\n[gG][oO]\\s*\n|\n[Gg][oO]\\s*$"; } else { if (endDelimiter.equalsIgnoreCase("go")) { endDelimiter = "\n[gG][oO]\\s*\n|\n[Gg][oO]\\s*$"; } } String[] initialSplit = multiLineSQL.split(endDelimiter); List<String> strings = new ArrayList<String>(); for (String anInitialSplit : initialSplit) { String singleLineSQL = anInitialSplit.trim(); if (singleLineSQL.length() > 0) { strings.add(singleLineSQL); } } return strings.toArray(new String[strings.size()]); } } | StringUtils { public static String[] splitSQL(String multiLineSQL, String endDelimiter) { if (endDelimiter == null) { endDelimiter = ";\\s*\n|;$|\n[gG][oO]\\s*\n|\n[Gg][oO]\\s*$"; } else { if (endDelimiter.equalsIgnoreCase("go")) { endDelimiter = "\n[gG][oO]\\s*\n|\n[Gg][oO]\\s*$"; } } String[] initialSplit = multiLineSQL.split(endDelimiter); List<String> strings = new ArrayList<String>(); for (String anInitialSplit : initialSplit) { String singleLineSQL = anInitialSplit.trim(); if (singleLineSQL.length() > 0) { strings.add(singleLineSQL); } } return strings.toArray(new String[strings.size()]); } static String trimToEmpty(String string); static String trimToNull(String string); static String[] processMutliLineSQL(String multiLineSQL,boolean stripComments, boolean splitStatements, String endDelimiter); static String[] splitSQL(String multiLineSQL, String endDelimiter); static String stripComments(String multiLineSQL); static String join(String[] array, String delimiter); static String join(Collection<String> collection, String delimiter); static List<String> splitAndTrim(String s, String regex); static String repeat(String string, int times); static String join(Integer[] array, String delimiter); static String join(int[] array, String delimiter); } | StringUtils { public static String[] splitSQL(String multiLineSQL, String endDelimiter) { if (endDelimiter == null) { endDelimiter = ";\\s*\n|;$|\n[gG][oO]\\s*\n|\n[Gg][oO]\\s*$"; } else { if (endDelimiter.equalsIgnoreCase("go")) { endDelimiter = "\n[gG][oO]\\s*\n|\n[Gg][oO]\\s*$"; } } String[] initialSplit = multiLineSQL.split(endDelimiter); List<String> strings = new ArrayList<String>(); for (String anInitialSplit : initialSplit) { String singleLineSQL = anInitialSplit.trim(); if (singleLineSQL.length() > 0) { strings.add(singleLineSQL); } } return strings.toArray(new String[strings.size()]); } static String trimToEmpty(String string); static String trimToNull(String string); static String[] processMutliLineSQL(String multiLineSQL,boolean stripComments, boolean splitStatements, String endDelimiter); static String[] splitSQL(String multiLineSQL, String endDelimiter); static String stripComments(String multiLineSQL); static String join(String[] array, String delimiter); static String join(Collection<String> collection, String delimiter); static List<String> splitAndTrim(String s, String regex); static String repeat(String string, int times); static String join(Integer[] array, String delimiter); static String join(int[] array, String delimiter); } |
@Test public void testAutoIncrementSQLiteDatabase() throws Exception { for (Database database : TestContext.getInstance().getAllDatabases()) { if (database instanceof SQLiteDatabase) { CreateTableStatement statement = new CreateTableStatement(SCHEMA_NAME, TABLE_NAME); statement.addColumn( COLUMN_NAME1, TypeConverterFactory.getInstance().findTypeConverter(database).getDataType("BIGINT", true), new AutoIncrementConstraint(COLUMN_NAME1) ); Sql[] generatedSql = this.generatorUnderTest.generateSql(statement, database, null); assertEquals("CREATE TABLE SCHEMA_NAME.TABLE_NAME (COLUMN1_NAME BIGINT AUTOINCREMENT)", generatedSql[0].toSql()); } } } | public Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { StringBuffer buffer = new StringBuffer(); buffer.append("CREATE TABLE ").append(database.escapeTableName(statement.getSchemaName(), statement.getTableName())).append(" "); buffer.append("("); boolean isSinglePrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() == 1; boolean isPrimaryKeyAutoIncrement = false; Iterator<String> columnIterator = statement.getColumns().iterator(); while (columnIterator.hasNext()) { String column = columnIterator.next(); buffer.append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), column)); buffer.append(" ").append(statement.getColumnTypes().get(column)); AutoIncrementConstraint autoIncrementConstraint = null; for (AutoIncrementConstraint currentAutoIncrementConstraint : statement.getAutoIncrementConstraints()) { if (column.equals(currentAutoIncrementConstraint.getColumnName())) { autoIncrementConstraint = currentAutoIncrementConstraint; break; } } boolean isAutoIncrementColumn = autoIncrementConstraint != null; boolean isPrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().contains(column); isPrimaryKeyAutoIncrement = isPrimaryKeyAutoIncrement || isPrimaryKeyColumn && isAutoIncrementColumn; if ((database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyColumn && isAutoIncrementColumn) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } buffer.append(" PRIMARY KEY AUTOINCREMENT"); } if (statement.getDefaultValue(column) != null) { Object defaultValue = statement.getDefaultValue(column); if (database instanceof MSSQLDatabase) { buffer.append(" CONSTRAINT ").append(((MSSQLDatabase) database).generateDefaultConstraintName(statement.getTableName(), column)); } buffer.append(" DEFAULT "); buffer.append(statement.getColumnTypes().get(column).convertObjectToString(defaultValue, database)); } if (isAutoIncrementColumn && ! (database instanceof SQLiteDatabase)) { if (database.supportsAutoIncrement()) { String autoIncrementClause = database.getAutoIncrementClause(autoIncrementConstraint.getStartWith(), autoIncrementConstraint.getIncrementBy()); if (!"".equals(autoIncrementClause)) { buffer.append(" ").append(autoIncrementClause); } } else { LogFactory.getLogger().warning(database.getTypeName()+" does not support autoincrement columns as request for "+(database.escapeTableName(statement.getSchemaName(), statement.getTableName()))); } } if (statement.getNotNullColumns().contains(column)) { buffer.append(" NOT NULL"); } else { if (database instanceof SybaseDatabase || database instanceof SybaseASADatabase || database instanceof MySQLDatabase) { if (database instanceof MySQLDatabase && statement.getColumnTypes().get(column).getDataTypeName().equalsIgnoreCase("timestamp")) { } else { buffer.append(" NULL"); } } } if (database instanceof InformixDatabase && isSinglePrimaryKeyColumn) { buffer.append(" PRIMARY KEY"); } if (columnIterator.hasNext()) { buffer.append(", "); } } buffer.append(","); if (!( (database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyAutoIncrement) && !((database instanceof InformixDatabase) && isSinglePrimaryKeyColumn )) { if (statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() > 0) { if (!(database instanceof InformixDatabase)) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } } buffer.append(" PRIMARY KEY ("); buffer.append(database.escapeColumnNameList(StringUtils.join(statement.getPrimaryKeyConstraint().getColumns(), ", "))); buffer.append(")"); if (database instanceof OracleDatabase && statement.getPrimaryKeyConstraint().getTablespace() != null) { buffer.append(" USING INDEX TABLESPACE "); buffer.append(statement.getPrimaryKeyConstraint().getTablespace()); } buffer.append(","); } } for (ForeignKeyConstraint fkConstraint : statement.getForeignKeyConstraints()) { if (!(database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } String referencesString = fkConstraint.getReferences(); if (!referencesString.contains(".") && database.getDefaultSchemaName() != null) { referencesString = database.getDefaultSchemaName()+"."+referencesString; } buffer.append(" FOREIGN KEY (") .append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), fkConstraint.getColumn())) .append(") REFERENCES ") .append(referencesString); if (fkConstraint.isDeleteCascade()) { buffer.append(" ON DELETE CASCADE"); } if ((database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } if (fkConstraint.isInitiallyDeferred()) { buffer.append(" INITIALLY DEFERRED"); } if (fkConstraint.isDeferrable()) { buffer.append(" DEFERRABLE"); } buffer.append(","); } for (UniqueConstraint uniqueConstraint : statement.getUniqueConstraints()) { if (uniqueConstraint.getConstraintName() != null && !constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(" UNIQUE ("); buffer.append(database.escapeColumnNameList(StringUtils.join(uniqueConstraint.getColumns(), ", "))); buffer.append(")"); if (uniqueConstraint.getConstraintName() != null && constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(","); } String sql = buffer.toString().replaceFirst(",\\s*$", "") + ")"; if (statement.getTablespace() != null && database.supportsTablespaces()) { if (database instanceof MSSQLDatabase || database instanceof SybaseASADatabase) { sql += " ON " + statement.getTablespace(); } else if (database instanceof DB2Database || database instanceof InformixDatabase) { sql += " IN " + statement.getTablespace(); } else { sql += " TABLESPACE " + statement.getTablespace(); } } return new Sql[] { new UnparsedSql(sql) }; } | CreateTableGenerator extends AbstractSqlGenerator<CreateTableStatement> { public Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { StringBuffer buffer = new StringBuffer(); buffer.append("CREATE TABLE ").append(database.escapeTableName(statement.getSchemaName(), statement.getTableName())).append(" "); buffer.append("("); boolean isSinglePrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() == 1; boolean isPrimaryKeyAutoIncrement = false; Iterator<String> columnIterator = statement.getColumns().iterator(); while (columnIterator.hasNext()) { String column = columnIterator.next(); buffer.append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), column)); buffer.append(" ").append(statement.getColumnTypes().get(column)); AutoIncrementConstraint autoIncrementConstraint = null; for (AutoIncrementConstraint currentAutoIncrementConstraint : statement.getAutoIncrementConstraints()) { if (column.equals(currentAutoIncrementConstraint.getColumnName())) { autoIncrementConstraint = currentAutoIncrementConstraint; break; } } boolean isAutoIncrementColumn = autoIncrementConstraint != null; boolean isPrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().contains(column); isPrimaryKeyAutoIncrement = isPrimaryKeyAutoIncrement || isPrimaryKeyColumn && isAutoIncrementColumn; if ((database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyColumn && isAutoIncrementColumn) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } buffer.append(" PRIMARY KEY AUTOINCREMENT"); } if (statement.getDefaultValue(column) != null) { Object defaultValue = statement.getDefaultValue(column); if (database instanceof MSSQLDatabase) { buffer.append(" CONSTRAINT ").append(((MSSQLDatabase) database).generateDefaultConstraintName(statement.getTableName(), column)); } buffer.append(" DEFAULT "); buffer.append(statement.getColumnTypes().get(column).convertObjectToString(defaultValue, database)); } if (isAutoIncrementColumn && ! (database instanceof SQLiteDatabase)) { if (database.supportsAutoIncrement()) { String autoIncrementClause = database.getAutoIncrementClause(autoIncrementConstraint.getStartWith(), autoIncrementConstraint.getIncrementBy()); if (!"".equals(autoIncrementClause)) { buffer.append(" ").append(autoIncrementClause); } } else { LogFactory.getLogger().warning(database.getTypeName()+" does not support autoincrement columns as request for "+(database.escapeTableName(statement.getSchemaName(), statement.getTableName()))); } } if (statement.getNotNullColumns().contains(column)) { buffer.append(" NOT NULL"); } else { if (database instanceof SybaseDatabase || database instanceof SybaseASADatabase || database instanceof MySQLDatabase) { if (database instanceof MySQLDatabase && statement.getColumnTypes().get(column).getDataTypeName().equalsIgnoreCase("timestamp")) { } else { buffer.append(" NULL"); } } } if (database instanceof InformixDatabase && isSinglePrimaryKeyColumn) { buffer.append(" PRIMARY KEY"); } if (columnIterator.hasNext()) { buffer.append(", "); } } buffer.append(","); if (!( (database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyAutoIncrement) && !((database instanceof InformixDatabase) && isSinglePrimaryKeyColumn )) { if (statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() > 0) { if (!(database instanceof InformixDatabase)) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } } buffer.append(" PRIMARY KEY ("); buffer.append(database.escapeColumnNameList(StringUtils.join(statement.getPrimaryKeyConstraint().getColumns(), ", "))); buffer.append(")"); if (database instanceof OracleDatabase && statement.getPrimaryKeyConstraint().getTablespace() != null) { buffer.append(" USING INDEX TABLESPACE "); buffer.append(statement.getPrimaryKeyConstraint().getTablespace()); } buffer.append(","); } } for (ForeignKeyConstraint fkConstraint : statement.getForeignKeyConstraints()) { if (!(database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } String referencesString = fkConstraint.getReferences(); if (!referencesString.contains(".") && database.getDefaultSchemaName() != null) { referencesString = database.getDefaultSchemaName()+"."+referencesString; } buffer.append(" FOREIGN KEY (") .append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), fkConstraint.getColumn())) .append(") REFERENCES ") .append(referencesString); if (fkConstraint.isDeleteCascade()) { buffer.append(" ON DELETE CASCADE"); } if ((database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } if (fkConstraint.isInitiallyDeferred()) { buffer.append(" INITIALLY DEFERRED"); } if (fkConstraint.isDeferrable()) { buffer.append(" DEFERRABLE"); } buffer.append(","); } for (UniqueConstraint uniqueConstraint : statement.getUniqueConstraints()) { if (uniqueConstraint.getConstraintName() != null && !constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(" UNIQUE ("); buffer.append(database.escapeColumnNameList(StringUtils.join(uniqueConstraint.getColumns(), ", "))); buffer.append(")"); if (uniqueConstraint.getConstraintName() != null && constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(","); } String sql = buffer.toString().replaceFirst(",\\s*$", "") + ")"; if (statement.getTablespace() != null && database.supportsTablespaces()) { if (database instanceof MSSQLDatabase || database instanceof SybaseASADatabase) { sql += " ON " + statement.getTablespace(); } else if (database instanceof DB2Database || database instanceof InformixDatabase) { sql += " IN " + statement.getTablespace(); } else { sql += " TABLESPACE " + statement.getTablespace(); } } return new Sql[] { new UnparsedSql(sql) }; } } | CreateTableGenerator extends AbstractSqlGenerator<CreateTableStatement> { public Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { StringBuffer buffer = new StringBuffer(); buffer.append("CREATE TABLE ").append(database.escapeTableName(statement.getSchemaName(), statement.getTableName())).append(" "); buffer.append("("); boolean isSinglePrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() == 1; boolean isPrimaryKeyAutoIncrement = false; Iterator<String> columnIterator = statement.getColumns().iterator(); while (columnIterator.hasNext()) { String column = columnIterator.next(); buffer.append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), column)); buffer.append(" ").append(statement.getColumnTypes().get(column)); AutoIncrementConstraint autoIncrementConstraint = null; for (AutoIncrementConstraint currentAutoIncrementConstraint : statement.getAutoIncrementConstraints()) { if (column.equals(currentAutoIncrementConstraint.getColumnName())) { autoIncrementConstraint = currentAutoIncrementConstraint; break; } } boolean isAutoIncrementColumn = autoIncrementConstraint != null; boolean isPrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().contains(column); isPrimaryKeyAutoIncrement = isPrimaryKeyAutoIncrement || isPrimaryKeyColumn && isAutoIncrementColumn; if ((database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyColumn && isAutoIncrementColumn) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } buffer.append(" PRIMARY KEY AUTOINCREMENT"); } if (statement.getDefaultValue(column) != null) { Object defaultValue = statement.getDefaultValue(column); if (database instanceof MSSQLDatabase) { buffer.append(" CONSTRAINT ").append(((MSSQLDatabase) database).generateDefaultConstraintName(statement.getTableName(), column)); } buffer.append(" DEFAULT "); buffer.append(statement.getColumnTypes().get(column).convertObjectToString(defaultValue, database)); } if (isAutoIncrementColumn && ! (database instanceof SQLiteDatabase)) { if (database.supportsAutoIncrement()) { String autoIncrementClause = database.getAutoIncrementClause(autoIncrementConstraint.getStartWith(), autoIncrementConstraint.getIncrementBy()); if (!"".equals(autoIncrementClause)) { buffer.append(" ").append(autoIncrementClause); } } else { LogFactory.getLogger().warning(database.getTypeName()+" does not support autoincrement columns as request for "+(database.escapeTableName(statement.getSchemaName(), statement.getTableName()))); } } if (statement.getNotNullColumns().contains(column)) { buffer.append(" NOT NULL"); } else { if (database instanceof SybaseDatabase || database instanceof SybaseASADatabase || database instanceof MySQLDatabase) { if (database instanceof MySQLDatabase && statement.getColumnTypes().get(column).getDataTypeName().equalsIgnoreCase("timestamp")) { } else { buffer.append(" NULL"); } } } if (database instanceof InformixDatabase && isSinglePrimaryKeyColumn) { buffer.append(" PRIMARY KEY"); } if (columnIterator.hasNext()) { buffer.append(", "); } } buffer.append(","); if (!( (database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyAutoIncrement) && !((database instanceof InformixDatabase) && isSinglePrimaryKeyColumn )) { if (statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() > 0) { if (!(database instanceof InformixDatabase)) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } } buffer.append(" PRIMARY KEY ("); buffer.append(database.escapeColumnNameList(StringUtils.join(statement.getPrimaryKeyConstraint().getColumns(), ", "))); buffer.append(")"); if (database instanceof OracleDatabase && statement.getPrimaryKeyConstraint().getTablespace() != null) { buffer.append(" USING INDEX TABLESPACE "); buffer.append(statement.getPrimaryKeyConstraint().getTablespace()); } buffer.append(","); } } for (ForeignKeyConstraint fkConstraint : statement.getForeignKeyConstraints()) { if (!(database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } String referencesString = fkConstraint.getReferences(); if (!referencesString.contains(".") && database.getDefaultSchemaName() != null) { referencesString = database.getDefaultSchemaName()+"."+referencesString; } buffer.append(" FOREIGN KEY (") .append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), fkConstraint.getColumn())) .append(") REFERENCES ") .append(referencesString); if (fkConstraint.isDeleteCascade()) { buffer.append(" ON DELETE CASCADE"); } if ((database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } if (fkConstraint.isInitiallyDeferred()) { buffer.append(" INITIALLY DEFERRED"); } if (fkConstraint.isDeferrable()) { buffer.append(" DEFERRABLE"); } buffer.append(","); } for (UniqueConstraint uniqueConstraint : statement.getUniqueConstraints()) { if (uniqueConstraint.getConstraintName() != null && !constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(" UNIQUE ("); buffer.append(database.escapeColumnNameList(StringUtils.join(uniqueConstraint.getColumns(), ", "))); buffer.append(")"); if (uniqueConstraint.getConstraintName() != null && constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(","); } String sql = buffer.toString().replaceFirst(",\\s*$", "") + ")"; if (statement.getTablespace() != null && database.supportsTablespaces()) { if (database instanceof MSSQLDatabase || database instanceof SybaseASADatabase) { sql += " ON " + statement.getTablespace(); } else if (database instanceof DB2Database || database instanceof InformixDatabase) { sql += " IN " + statement.getTablespace(); } else { sql += " TABLESPACE " + statement.getTablespace(); } } return new Sql[] { new UnparsedSql(sql) }; } } | CreateTableGenerator extends AbstractSqlGenerator<CreateTableStatement> { public Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { StringBuffer buffer = new StringBuffer(); buffer.append("CREATE TABLE ").append(database.escapeTableName(statement.getSchemaName(), statement.getTableName())).append(" "); buffer.append("("); boolean isSinglePrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() == 1; boolean isPrimaryKeyAutoIncrement = false; Iterator<String> columnIterator = statement.getColumns().iterator(); while (columnIterator.hasNext()) { String column = columnIterator.next(); buffer.append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), column)); buffer.append(" ").append(statement.getColumnTypes().get(column)); AutoIncrementConstraint autoIncrementConstraint = null; for (AutoIncrementConstraint currentAutoIncrementConstraint : statement.getAutoIncrementConstraints()) { if (column.equals(currentAutoIncrementConstraint.getColumnName())) { autoIncrementConstraint = currentAutoIncrementConstraint; break; } } boolean isAutoIncrementColumn = autoIncrementConstraint != null; boolean isPrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().contains(column); isPrimaryKeyAutoIncrement = isPrimaryKeyAutoIncrement || isPrimaryKeyColumn && isAutoIncrementColumn; if ((database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyColumn && isAutoIncrementColumn) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } buffer.append(" PRIMARY KEY AUTOINCREMENT"); } if (statement.getDefaultValue(column) != null) { Object defaultValue = statement.getDefaultValue(column); if (database instanceof MSSQLDatabase) { buffer.append(" CONSTRAINT ").append(((MSSQLDatabase) database).generateDefaultConstraintName(statement.getTableName(), column)); } buffer.append(" DEFAULT "); buffer.append(statement.getColumnTypes().get(column).convertObjectToString(defaultValue, database)); } if (isAutoIncrementColumn && ! (database instanceof SQLiteDatabase)) { if (database.supportsAutoIncrement()) { String autoIncrementClause = database.getAutoIncrementClause(autoIncrementConstraint.getStartWith(), autoIncrementConstraint.getIncrementBy()); if (!"".equals(autoIncrementClause)) { buffer.append(" ").append(autoIncrementClause); } } else { LogFactory.getLogger().warning(database.getTypeName()+" does not support autoincrement columns as request for "+(database.escapeTableName(statement.getSchemaName(), statement.getTableName()))); } } if (statement.getNotNullColumns().contains(column)) { buffer.append(" NOT NULL"); } else { if (database instanceof SybaseDatabase || database instanceof SybaseASADatabase || database instanceof MySQLDatabase) { if (database instanceof MySQLDatabase && statement.getColumnTypes().get(column).getDataTypeName().equalsIgnoreCase("timestamp")) { } else { buffer.append(" NULL"); } } } if (database instanceof InformixDatabase && isSinglePrimaryKeyColumn) { buffer.append(" PRIMARY KEY"); } if (columnIterator.hasNext()) { buffer.append(", "); } } buffer.append(","); if (!( (database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyAutoIncrement) && !((database instanceof InformixDatabase) && isSinglePrimaryKeyColumn )) { if (statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() > 0) { if (!(database instanceof InformixDatabase)) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } } buffer.append(" PRIMARY KEY ("); buffer.append(database.escapeColumnNameList(StringUtils.join(statement.getPrimaryKeyConstraint().getColumns(), ", "))); buffer.append(")"); if (database instanceof OracleDatabase && statement.getPrimaryKeyConstraint().getTablespace() != null) { buffer.append(" USING INDEX TABLESPACE "); buffer.append(statement.getPrimaryKeyConstraint().getTablespace()); } buffer.append(","); } } for (ForeignKeyConstraint fkConstraint : statement.getForeignKeyConstraints()) { if (!(database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } String referencesString = fkConstraint.getReferences(); if (!referencesString.contains(".") && database.getDefaultSchemaName() != null) { referencesString = database.getDefaultSchemaName()+"."+referencesString; } buffer.append(" FOREIGN KEY (") .append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), fkConstraint.getColumn())) .append(") REFERENCES ") .append(referencesString); if (fkConstraint.isDeleteCascade()) { buffer.append(" ON DELETE CASCADE"); } if ((database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } if (fkConstraint.isInitiallyDeferred()) { buffer.append(" INITIALLY DEFERRED"); } if (fkConstraint.isDeferrable()) { buffer.append(" DEFERRABLE"); } buffer.append(","); } for (UniqueConstraint uniqueConstraint : statement.getUniqueConstraints()) { if (uniqueConstraint.getConstraintName() != null && !constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(" UNIQUE ("); buffer.append(database.escapeColumnNameList(StringUtils.join(uniqueConstraint.getColumns(), ", "))); buffer.append(")"); if (uniqueConstraint.getConstraintName() != null && constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(","); } String sql = buffer.toString().replaceFirst(",\\s*$", "") + ")"; if (statement.getTablespace() != null && database.supportsTablespaces()) { if (database instanceof MSSQLDatabase || database instanceof SybaseASADatabase) { sql += " ON " + statement.getTablespace(); } else if (database instanceof DB2Database || database instanceof InformixDatabase) { sql += " IN " + statement.getTablespace(); } else { sql += " TABLESPACE " + statement.getTablespace(); } } return new Sql[] { new UnparsedSql(sql) }; } ValidationErrors validate(CreateTableStatement createTableStatement, Database database, SqlGeneratorChain sqlGeneratorChain); Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain); } | CreateTableGenerator extends AbstractSqlGenerator<CreateTableStatement> { public Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { StringBuffer buffer = new StringBuffer(); buffer.append("CREATE TABLE ").append(database.escapeTableName(statement.getSchemaName(), statement.getTableName())).append(" "); buffer.append("("); boolean isSinglePrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() == 1; boolean isPrimaryKeyAutoIncrement = false; Iterator<String> columnIterator = statement.getColumns().iterator(); while (columnIterator.hasNext()) { String column = columnIterator.next(); buffer.append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), column)); buffer.append(" ").append(statement.getColumnTypes().get(column)); AutoIncrementConstraint autoIncrementConstraint = null; for (AutoIncrementConstraint currentAutoIncrementConstraint : statement.getAutoIncrementConstraints()) { if (column.equals(currentAutoIncrementConstraint.getColumnName())) { autoIncrementConstraint = currentAutoIncrementConstraint; break; } } boolean isAutoIncrementColumn = autoIncrementConstraint != null; boolean isPrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().contains(column); isPrimaryKeyAutoIncrement = isPrimaryKeyAutoIncrement || isPrimaryKeyColumn && isAutoIncrementColumn; if ((database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyColumn && isAutoIncrementColumn) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } buffer.append(" PRIMARY KEY AUTOINCREMENT"); } if (statement.getDefaultValue(column) != null) { Object defaultValue = statement.getDefaultValue(column); if (database instanceof MSSQLDatabase) { buffer.append(" CONSTRAINT ").append(((MSSQLDatabase) database).generateDefaultConstraintName(statement.getTableName(), column)); } buffer.append(" DEFAULT "); buffer.append(statement.getColumnTypes().get(column).convertObjectToString(defaultValue, database)); } if (isAutoIncrementColumn && ! (database instanceof SQLiteDatabase)) { if (database.supportsAutoIncrement()) { String autoIncrementClause = database.getAutoIncrementClause(autoIncrementConstraint.getStartWith(), autoIncrementConstraint.getIncrementBy()); if (!"".equals(autoIncrementClause)) { buffer.append(" ").append(autoIncrementClause); } } else { LogFactory.getLogger().warning(database.getTypeName()+" does not support autoincrement columns as request for "+(database.escapeTableName(statement.getSchemaName(), statement.getTableName()))); } } if (statement.getNotNullColumns().contains(column)) { buffer.append(" NOT NULL"); } else { if (database instanceof SybaseDatabase || database instanceof SybaseASADatabase || database instanceof MySQLDatabase) { if (database instanceof MySQLDatabase && statement.getColumnTypes().get(column).getDataTypeName().equalsIgnoreCase("timestamp")) { } else { buffer.append(" NULL"); } } } if (database instanceof InformixDatabase && isSinglePrimaryKeyColumn) { buffer.append(" PRIMARY KEY"); } if (columnIterator.hasNext()) { buffer.append(", "); } } buffer.append(","); if (!( (database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyAutoIncrement) && !((database instanceof InformixDatabase) && isSinglePrimaryKeyColumn )) { if (statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() > 0) { if (!(database instanceof InformixDatabase)) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } } buffer.append(" PRIMARY KEY ("); buffer.append(database.escapeColumnNameList(StringUtils.join(statement.getPrimaryKeyConstraint().getColumns(), ", "))); buffer.append(")"); if (database instanceof OracleDatabase && statement.getPrimaryKeyConstraint().getTablespace() != null) { buffer.append(" USING INDEX TABLESPACE "); buffer.append(statement.getPrimaryKeyConstraint().getTablespace()); } buffer.append(","); } } for (ForeignKeyConstraint fkConstraint : statement.getForeignKeyConstraints()) { if (!(database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } String referencesString = fkConstraint.getReferences(); if (!referencesString.contains(".") && database.getDefaultSchemaName() != null) { referencesString = database.getDefaultSchemaName()+"."+referencesString; } buffer.append(" FOREIGN KEY (") .append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), fkConstraint.getColumn())) .append(") REFERENCES ") .append(referencesString); if (fkConstraint.isDeleteCascade()) { buffer.append(" ON DELETE CASCADE"); } if ((database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } if (fkConstraint.isInitiallyDeferred()) { buffer.append(" INITIALLY DEFERRED"); } if (fkConstraint.isDeferrable()) { buffer.append(" DEFERRABLE"); } buffer.append(","); } for (UniqueConstraint uniqueConstraint : statement.getUniqueConstraints()) { if (uniqueConstraint.getConstraintName() != null && !constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(" UNIQUE ("); buffer.append(database.escapeColumnNameList(StringUtils.join(uniqueConstraint.getColumns(), ", "))); buffer.append(")"); if (uniqueConstraint.getConstraintName() != null && constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(","); } String sql = buffer.toString().replaceFirst(",\\s*$", "") + ")"; if (statement.getTablespace() != null && database.supportsTablespaces()) { if (database instanceof MSSQLDatabase || database instanceof SybaseASADatabase) { sql += " ON " + statement.getTablespace(); } else if (database instanceof DB2Database || database instanceof InformixDatabase) { sql += " IN " + statement.getTablespace(); } else { sql += " TABLESPACE " + statement.getTablespace(); } } return new Sql[] { new UnparsedSql(sql) }; } ValidationErrors validate(CreateTableStatement createTableStatement, Database database, SqlGeneratorChain sqlGeneratorChain); Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain); } |
@Test public void testAutoIncrementStartWithSQLiteDatabase() throws Exception { for (Database database : TestContext.getInstance().getAllDatabases()) { if (database instanceof SQLiteDatabase) { CreateTableStatement statement = new CreateTableStatement(SCHEMA_NAME, TABLE_NAME); statement.addColumn( COLUMN_NAME1, TypeConverterFactory.getInstance().findTypeConverter(database).getDataType("BIGINT", true), new AutoIncrementConstraint(COLUMN_NAME1, BigInteger.valueOf(2), null) ); Sql[] generatedSql = this.generatorUnderTest.generateSql(statement, database, null); assertEquals("CREATE TABLE SCHEMA_NAME.TABLE_NAME (COLUMN1_NAME BIGINT AUTOINCREMENT)", generatedSql[0].toSql()); } } } | public Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { StringBuffer buffer = new StringBuffer(); buffer.append("CREATE TABLE ").append(database.escapeTableName(statement.getSchemaName(), statement.getTableName())).append(" "); buffer.append("("); boolean isSinglePrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() == 1; boolean isPrimaryKeyAutoIncrement = false; Iterator<String> columnIterator = statement.getColumns().iterator(); while (columnIterator.hasNext()) { String column = columnIterator.next(); buffer.append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), column)); buffer.append(" ").append(statement.getColumnTypes().get(column)); AutoIncrementConstraint autoIncrementConstraint = null; for (AutoIncrementConstraint currentAutoIncrementConstraint : statement.getAutoIncrementConstraints()) { if (column.equals(currentAutoIncrementConstraint.getColumnName())) { autoIncrementConstraint = currentAutoIncrementConstraint; break; } } boolean isAutoIncrementColumn = autoIncrementConstraint != null; boolean isPrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().contains(column); isPrimaryKeyAutoIncrement = isPrimaryKeyAutoIncrement || isPrimaryKeyColumn && isAutoIncrementColumn; if ((database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyColumn && isAutoIncrementColumn) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } buffer.append(" PRIMARY KEY AUTOINCREMENT"); } if (statement.getDefaultValue(column) != null) { Object defaultValue = statement.getDefaultValue(column); if (database instanceof MSSQLDatabase) { buffer.append(" CONSTRAINT ").append(((MSSQLDatabase) database).generateDefaultConstraintName(statement.getTableName(), column)); } buffer.append(" DEFAULT "); buffer.append(statement.getColumnTypes().get(column).convertObjectToString(defaultValue, database)); } if (isAutoIncrementColumn && ! (database instanceof SQLiteDatabase)) { if (database.supportsAutoIncrement()) { String autoIncrementClause = database.getAutoIncrementClause(autoIncrementConstraint.getStartWith(), autoIncrementConstraint.getIncrementBy()); if (!"".equals(autoIncrementClause)) { buffer.append(" ").append(autoIncrementClause); } } else { LogFactory.getLogger().warning(database.getTypeName()+" does not support autoincrement columns as request for "+(database.escapeTableName(statement.getSchemaName(), statement.getTableName()))); } } if (statement.getNotNullColumns().contains(column)) { buffer.append(" NOT NULL"); } else { if (database instanceof SybaseDatabase || database instanceof SybaseASADatabase || database instanceof MySQLDatabase) { if (database instanceof MySQLDatabase && statement.getColumnTypes().get(column).getDataTypeName().equalsIgnoreCase("timestamp")) { } else { buffer.append(" NULL"); } } } if (database instanceof InformixDatabase && isSinglePrimaryKeyColumn) { buffer.append(" PRIMARY KEY"); } if (columnIterator.hasNext()) { buffer.append(", "); } } buffer.append(","); if (!( (database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyAutoIncrement) && !((database instanceof InformixDatabase) && isSinglePrimaryKeyColumn )) { if (statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() > 0) { if (!(database instanceof InformixDatabase)) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } } buffer.append(" PRIMARY KEY ("); buffer.append(database.escapeColumnNameList(StringUtils.join(statement.getPrimaryKeyConstraint().getColumns(), ", "))); buffer.append(")"); if (database instanceof OracleDatabase && statement.getPrimaryKeyConstraint().getTablespace() != null) { buffer.append(" USING INDEX TABLESPACE "); buffer.append(statement.getPrimaryKeyConstraint().getTablespace()); } buffer.append(","); } } for (ForeignKeyConstraint fkConstraint : statement.getForeignKeyConstraints()) { if (!(database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } String referencesString = fkConstraint.getReferences(); if (!referencesString.contains(".") && database.getDefaultSchemaName() != null) { referencesString = database.getDefaultSchemaName()+"."+referencesString; } buffer.append(" FOREIGN KEY (") .append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), fkConstraint.getColumn())) .append(") REFERENCES ") .append(referencesString); if (fkConstraint.isDeleteCascade()) { buffer.append(" ON DELETE CASCADE"); } if ((database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } if (fkConstraint.isInitiallyDeferred()) { buffer.append(" INITIALLY DEFERRED"); } if (fkConstraint.isDeferrable()) { buffer.append(" DEFERRABLE"); } buffer.append(","); } for (UniqueConstraint uniqueConstraint : statement.getUniqueConstraints()) { if (uniqueConstraint.getConstraintName() != null && !constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(" UNIQUE ("); buffer.append(database.escapeColumnNameList(StringUtils.join(uniqueConstraint.getColumns(), ", "))); buffer.append(")"); if (uniqueConstraint.getConstraintName() != null && constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(","); } String sql = buffer.toString().replaceFirst(",\\s*$", "") + ")"; if (statement.getTablespace() != null && database.supportsTablespaces()) { if (database instanceof MSSQLDatabase || database instanceof SybaseASADatabase) { sql += " ON " + statement.getTablespace(); } else if (database instanceof DB2Database || database instanceof InformixDatabase) { sql += " IN " + statement.getTablespace(); } else { sql += " TABLESPACE " + statement.getTablespace(); } } return new Sql[] { new UnparsedSql(sql) }; } | CreateTableGenerator extends AbstractSqlGenerator<CreateTableStatement> { public Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { StringBuffer buffer = new StringBuffer(); buffer.append("CREATE TABLE ").append(database.escapeTableName(statement.getSchemaName(), statement.getTableName())).append(" "); buffer.append("("); boolean isSinglePrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() == 1; boolean isPrimaryKeyAutoIncrement = false; Iterator<String> columnIterator = statement.getColumns().iterator(); while (columnIterator.hasNext()) { String column = columnIterator.next(); buffer.append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), column)); buffer.append(" ").append(statement.getColumnTypes().get(column)); AutoIncrementConstraint autoIncrementConstraint = null; for (AutoIncrementConstraint currentAutoIncrementConstraint : statement.getAutoIncrementConstraints()) { if (column.equals(currentAutoIncrementConstraint.getColumnName())) { autoIncrementConstraint = currentAutoIncrementConstraint; break; } } boolean isAutoIncrementColumn = autoIncrementConstraint != null; boolean isPrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().contains(column); isPrimaryKeyAutoIncrement = isPrimaryKeyAutoIncrement || isPrimaryKeyColumn && isAutoIncrementColumn; if ((database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyColumn && isAutoIncrementColumn) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } buffer.append(" PRIMARY KEY AUTOINCREMENT"); } if (statement.getDefaultValue(column) != null) { Object defaultValue = statement.getDefaultValue(column); if (database instanceof MSSQLDatabase) { buffer.append(" CONSTRAINT ").append(((MSSQLDatabase) database).generateDefaultConstraintName(statement.getTableName(), column)); } buffer.append(" DEFAULT "); buffer.append(statement.getColumnTypes().get(column).convertObjectToString(defaultValue, database)); } if (isAutoIncrementColumn && ! (database instanceof SQLiteDatabase)) { if (database.supportsAutoIncrement()) { String autoIncrementClause = database.getAutoIncrementClause(autoIncrementConstraint.getStartWith(), autoIncrementConstraint.getIncrementBy()); if (!"".equals(autoIncrementClause)) { buffer.append(" ").append(autoIncrementClause); } } else { LogFactory.getLogger().warning(database.getTypeName()+" does not support autoincrement columns as request for "+(database.escapeTableName(statement.getSchemaName(), statement.getTableName()))); } } if (statement.getNotNullColumns().contains(column)) { buffer.append(" NOT NULL"); } else { if (database instanceof SybaseDatabase || database instanceof SybaseASADatabase || database instanceof MySQLDatabase) { if (database instanceof MySQLDatabase && statement.getColumnTypes().get(column).getDataTypeName().equalsIgnoreCase("timestamp")) { } else { buffer.append(" NULL"); } } } if (database instanceof InformixDatabase && isSinglePrimaryKeyColumn) { buffer.append(" PRIMARY KEY"); } if (columnIterator.hasNext()) { buffer.append(", "); } } buffer.append(","); if (!( (database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyAutoIncrement) && !((database instanceof InformixDatabase) && isSinglePrimaryKeyColumn )) { if (statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() > 0) { if (!(database instanceof InformixDatabase)) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } } buffer.append(" PRIMARY KEY ("); buffer.append(database.escapeColumnNameList(StringUtils.join(statement.getPrimaryKeyConstraint().getColumns(), ", "))); buffer.append(")"); if (database instanceof OracleDatabase && statement.getPrimaryKeyConstraint().getTablespace() != null) { buffer.append(" USING INDEX TABLESPACE "); buffer.append(statement.getPrimaryKeyConstraint().getTablespace()); } buffer.append(","); } } for (ForeignKeyConstraint fkConstraint : statement.getForeignKeyConstraints()) { if (!(database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } String referencesString = fkConstraint.getReferences(); if (!referencesString.contains(".") && database.getDefaultSchemaName() != null) { referencesString = database.getDefaultSchemaName()+"."+referencesString; } buffer.append(" FOREIGN KEY (") .append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), fkConstraint.getColumn())) .append(") REFERENCES ") .append(referencesString); if (fkConstraint.isDeleteCascade()) { buffer.append(" ON DELETE CASCADE"); } if ((database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } if (fkConstraint.isInitiallyDeferred()) { buffer.append(" INITIALLY DEFERRED"); } if (fkConstraint.isDeferrable()) { buffer.append(" DEFERRABLE"); } buffer.append(","); } for (UniqueConstraint uniqueConstraint : statement.getUniqueConstraints()) { if (uniqueConstraint.getConstraintName() != null && !constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(" UNIQUE ("); buffer.append(database.escapeColumnNameList(StringUtils.join(uniqueConstraint.getColumns(), ", "))); buffer.append(")"); if (uniqueConstraint.getConstraintName() != null && constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(","); } String sql = buffer.toString().replaceFirst(",\\s*$", "") + ")"; if (statement.getTablespace() != null && database.supportsTablespaces()) { if (database instanceof MSSQLDatabase || database instanceof SybaseASADatabase) { sql += " ON " + statement.getTablespace(); } else if (database instanceof DB2Database || database instanceof InformixDatabase) { sql += " IN " + statement.getTablespace(); } else { sql += " TABLESPACE " + statement.getTablespace(); } } return new Sql[] { new UnparsedSql(sql) }; } } | CreateTableGenerator extends AbstractSqlGenerator<CreateTableStatement> { public Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { StringBuffer buffer = new StringBuffer(); buffer.append("CREATE TABLE ").append(database.escapeTableName(statement.getSchemaName(), statement.getTableName())).append(" "); buffer.append("("); boolean isSinglePrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() == 1; boolean isPrimaryKeyAutoIncrement = false; Iterator<String> columnIterator = statement.getColumns().iterator(); while (columnIterator.hasNext()) { String column = columnIterator.next(); buffer.append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), column)); buffer.append(" ").append(statement.getColumnTypes().get(column)); AutoIncrementConstraint autoIncrementConstraint = null; for (AutoIncrementConstraint currentAutoIncrementConstraint : statement.getAutoIncrementConstraints()) { if (column.equals(currentAutoIncrementConstraint.getColumnName())) { autoIncrementConstraint = currentAutoIncrementConstraint; break; } } boolean isAutoIncrementColumn = autoIncrementConstraint != null; boolean isPrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().contains(column); isPrimaryKeyAutoIncrement = isPrimaryKeyAutoIncrement || isPrimaryKeyColumn && isAutoIncrementColumn; if ((database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyColumn && isAutoIncrementColumn) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } buffer.append(" PRIMARY KEY AUTOINCREMENT"); } if (statement.getDefaultValue(column) != null) { Object defaultValue = statement.getDefaultValue(column); if (database instanceof MSSQLDatabase) { buffer.append(" CONSTRAINT ").append(((MSSQLDatabase) database).generateDefaultConstraintName(statement.getTableName(), column)); } buffer.append(" DEFAULT "); buffer.append(statement.getColumnTypes().get(column).convertObjectToString(defaultValue, database)); } if (isAutoIncrementColumn && ! (database instanceof SQLiteDatabase)) { if (database.supportsAutoIncrement()) { String autoIncrementClause = database.getAutoIncrementClause(autoIncrementConstraint.getStartWith(), autoIncrementConstraint.getIncrementBy()); if (!"".equals(autoIncrementClause)) { buffer.append(" ").append(autoIncrementClause); } } else { LogFactory.getLogger().warning(database.getTypeName()+" does not support autoincrement columns as request for "+(database.escapeTableName(statement.getSchemaName(), statement.getTableName()))); } } if (statement.getNotNullColumns().contains(column)) { buffer.append(" NOT NULL"); } else { if (database instanceof SybaseDatabase || database instanceof SybaseASADatabase || database instanceof MySQLDatabase) { if (database instanceof MySQLDatabase && statement.getColumnTypes().get(column).getDataTypeName().equalsIgnoreCase("timestamp")) { } else { buffer.append(" NULL"); } } } if (database instanceof InformixDatabase && isSinglePrimaryKeyColumn) { buffer.append(" PRIMARY KEY"); } if (columnIterator.hasNext()) { buffer.append(", "); } } buffer.append(","); if (!( (database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyAutoIncrement) && !((database instanceof InformixDatabase) && isSinglePrimaryKeyColumn )) { if (statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() > 0) { if (!(database instanceof InformixDatabase)) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } } buffer.append(" PRIMARY KEY ("); buffer.append(database.escapeColumnNameList(StringUtils.join(statement.getPrimaryKeyConstraint().getColumns(), ", "))); buffer.append(")"); if (database instanceof OracleDatabase && statement.getPrimaryKeyConstraint().getTablespace() != null) { buffer.append(" USING INDEX TABLESPACE "); buffer.append(statement.getPrimaryKeyConstraint().getTablespace()); } buffer.append(","); } } for (ForeignKeyConstraint fkConstraint : statement.getForeignKeyConstraints()) { if (!(database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } String referencesString = fkConstraint.getReferences(); if (!referencesString.contains(".") && database.getDefaultSchemaName() != null) { referencesString = database.getDefaultSchemaName()+"."+referencesString; } buffer.append(" FOREIGN KEY (") .append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), fkConstraint.getColumn())) .append(") REFERENCES ") .append(referencesString); if (fkConstraint.isDeleteCascade()) { buffer.append(" ON DELETE CASCADE"); } if ((database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } if (fkConstraint.isInitiallyDeferred()) { buffer.append(" INITIALLY DEFERRED"); } if (fkConstraint.isDeferrable()) { buffer.append(" DEFERRABLE"); } buffer.append(","); } for (UniqueConstraint uniqueConstraint : statement.getUniqueConstraints()) { if (uniqueConstraint.getConstraintName() != null && !constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(" UNIQUE ("); buffer.append(database.escapeColumnNameList(StringUtils.join(uniqueConstraint.getColumns(), ", "))); buffer.append(")"); if (uniqueConstraint.getConstraintName() != null && constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(","); } String sql = buffer.toString().replaceFirst(",\\s*$", "") + ")"; if (statement.getTablespace() != null && database.supportsTablespaces()) { if (database instanceof MSSQLDatabase || database instanceof SybaseASADatabase) { sql += " ON " + statement.getTablespace(); } else if (database instanceof DB2Database || database instanceof InformixDatabase) { sql += " IN " + statement.getTablespace(); } else { sql += " TABLESPACE " + statement.getTablespace(); } } return new Sql[] { new UnparsedSql(sql) }; } } | CreateTableGenerator extends AbstractSqlGenerator<CreateTableStatement> { public Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { StringBuffer buffer = new StringBuffer(); buffer.append("CREATE TABLE ").append(database.escapeTableName(statement.getSchemaName(), statement.getTableName())).append(" "); buffer.append("("); boolean isSinglePrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() == 1; boolean isPrimaryKeyAutoIncrement = false; Iterator<String> columnIterator = statement.getColumns().iterator(); while (columnIterator.hasNext()) { String column = columnIterator.next(); buffer.append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), column)); buffer.append(" ").append(statement.getColumnTypes().get(column)); AutoIncrementConstraint autoIncrementConstraint = null; for (AutoIncrementConstraint currentAutoIncrementConstraint : statement.getAutoIncrementConstraints()) { if (column.equals(currentAutoIncrementConstraint.getColumnName())) { autoIncrementConstraint = currentAutoIncrementConstraint; break; } } boolean isAutoIncrementColumn = autoIncrementConstraint != null; boolean isPrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().contains(column); isPrimaryKeyAutoIncrement = isPrimaryKeyAutoIncrement || isPrimaryKeyColumn && isAutoIncrementColumn; if ((database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyColumn && isAutoIncrementColumn) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } buffer.append(" PRIMARY KEY AUTOINCREMENT"); } if (statement.getDefaultValue(column) != null) { Object defaultValue = statement.getDefaultValue(column); if (database instanceof MSSQLDatabase) { buffer.append(" CONSTRAINT ").append(((MSSQLDatabase) database).generateDefaultConstraintName(statement.getTableName(), column)); } buffer.append(" DEFAULT "); buffer.append(statement.getColumnTypes().get(column).convertObjectToString(defaultValue, database)); } if (isAutoIncrementColumn && ! (database instanceof SQLiteDatabase)) { if (database.supportsAutoIncrement()) { String autoIncrementClause = database.getAutoIncrementClause(autoIncrementConstraint.getStartWith(), autoIncrementConstraint.getIncrementBy()); if (!"".equals(autoIncrementClause)) { buffer.append(" ").append(autoIncrementClause); } } else { LogFactory.getLogger().warning(database.getTypeName()+" does not support autoincrement columns as request for "+(database.escapeTableName(statement.getSchemaName(), statement.getTableName()))); } } if (statement.getNotNullColumns().contains(column)) { buffer.append(" NOT NULL"); } else { if (database instanceof SybaseDatabase || database instanceof SybaseASADatabase || database instanceof MySQLDatabase) { if (database instanceof MySQLDatabase && statement.getColumnTypes().get(column).getDataTypeName().equalsIgnoreCase("timestamp")) { } else { buffer.append(" NULL"); } } } if (database instanceof InformixDatabase && isSinglePrimaryKeyColumn) { buffer.append(" PRIMARY KEY"); } if (columnIterator.hasNext()) { buffer.append(", "); } } buffer.append(","); if (!( (database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyAutoIncrement) && !((database instanceof InformixDatabase) && isSinglePrimaryKeyColumn )) { if (statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() > 0) { if (!(database instanceof InformixDatabase)) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } } buffer.append(" PRIMARY KEY ("); buffer.append(database.escapeColumnNameList(StringUtils.join(statement.getPrimaryKeyConstraint().getColumns(), ", "))); buffer.append(")"); if (database instanceof OracleDatabase && statement.getPrimaryKeyConstraint().getTablespace() != null) { buffer.append(" USING INDEX TABLESPACE "); buffer.append(statement.getPrimaryKeyConstraint().getTablespace()); } buffer.append(","); } } for (ForeignKeyConstraint fkConstraint : statement.getForeignKeyConstraints()) { if (!(database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } String referencesString = fkConstraint.getReferences(); if (!referencesString.contains(".") && database.getDefaultSchemaName() != null) { referencesString = database.getDefaultSchemaName()+"."+referencesString; } buffer.append(" FOREIGN KEY (") .append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), fkConstraint.getColumn())) .append(") REFERENCES ") .append(referencesString); if (fkConstraint.isDeleteCascade()) { buffer.append(" ON DELETE CASCADE"); } if ((database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } if (fkConstraint.isInitiallyDeferred()) { buffer.append(" INITIALLY DEFERRED"); } if (fkConstraint.isDeferrable()) { buffer.append(" DEFERRABLE"); } buffer.append(","); } for (UniqueConstraint uniqueConstraint : statement.getUniqueConstraints()) { if (uniqueConstraint.getConstraintName() != null && !constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(" UNIQUE ("); buffer.append(database.escapeColumnNameList(StringUtils.join(uniqueConstraint.getColumns(), ", "))); buffer.append(")"); if (uniqueConstraint.getConstraintName() != null && constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(","); } String sql = buffer.toString().replaceFirst(",\\s*$", "") + ")"; if (statement.getTablespace() != null && database.supportsTablespaces()) { if (database instanceof MSSQLDatabase || database instanceof SybaseASADatabase) { sql += " ON " + statement.getTablespace(); } else if (database instanceof DB2Database || database instanceof InformixDatabase) { sql += " IN " + statement.getTablespace(); } else { sql += " TABLESPACE " + statement.getTablespace(); } } return new Sql[] { new UnparsedSql(sql) }; } ValidationErrors validate(CreateTableStatement createTableStatement, Database database, SqlGeneratorChain sqlGeneratorChain); Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain); } | CreateTableGenerator extends AbstractSqlGenerator<CreateTableStatement> { public Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { StringBuffer buffer = new StringBuffer(); buffer.append("CREATE TABLE ").append(database.escapeTableName(statement.getSchemaName(), statement.getTableName())).append(" "); buffer.append("("); boolean isSinglePrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() == 1; boolean isPrimaryKeyAutoIncrement = false; Iterator<String> columnIterator = statement.getColumns().iterator(); while (columnIterator.hasNext()) { String column = columnIterator.next(); buffer.append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), column)); buffer.append(" ").append(statement.getColumnTypes().get(column)); AutoIncrementConstraint autoIncrementConstraint = null; for (AutoIncrementConstraint currentAutoIncrementConstraint : statement.getAutoIncrementConstraints()) { if (column.equals(currentAutoIncrementConstraint.getColumnName())) { autoIncrementConstraint = currentAutoIncrementConstraint; break; } } boolean isAutoIncrementColumn = autoIncrementConstraint != null; boolean isPrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().contains(column); isPrimaryKeyAutoIncrement = isPrimaryKeyAutoIncrement || isPrimaryKeyColumn && isAutoIncrementColumn; if ((database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyColumn && isAutoIncrementColumn) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } buffer.append(" PRIMARY KEY AUTOINCREMENT"); } if (statement.getDefaultValue(column) != null) { Object defaultValue = statement.getDefaultValue(column); if (database instanceof MSSQLDatabase) { buffer.append(" CONSTRAINT ").append(((MSSQLDatabase) database).generateDefaultConstraintName(statement.getTableName(), column)); } buffer.append(" DEFAULT "); buffer.append(statement.getColumnTypes().get(column).convertObjectToString(defaultValue, database)); } if (isAutoIncrementColumn && ! (database instanceof SQLiteDatabase)) { if (database.supportsAutoIncrement()) { String autoIncrementClause = database.getAutoIncrementClause(autoIncrementConstraint.getStartWith(), autoIncrementConstraint.getIncrementBy()); if (!"".equals(autoIncrementClause)) { buffer.append(" ").append(autoIncrementClause); } } else { LogFactory.getLogger().warning(database.getTypeName()+" does not support autoincrement columns as request for "+(database.escapeTableName(statement.getSchemaName(), statement.getTableName()))); } } if (statement.getNotNullColumns().contains(column)) { buffer.append(" NOT NULL"); } else { if (database instanceof SybaseDatabase || database instanceof SybaseASADatabase || database instanceof MySQLDatabase) { if (database instanceof MySQLDatabase && statement.getColumnTypes().get(column).getDataTypeName().equalsIgnoreCase("timestamp")) { } else { buffer.append(" NULL"); } } } if (database instanceof InformixDatabase && isSinglePrimaryKeyColumn) { buffer.append(" PRIMARY KEY"); } if (columnIterator.hasNext()) { buffer.append(", "); } } buffer.append(","); if (!( (database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyAutoIncrement) && !((database instanceof InformixDatabase) && isSinglePrimaryKeyColumn )) { if (statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() > 0) { if (!(database instanceof InformixDatabase)) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } } buffer.append(" PRIMARY KEY ("); buffer.append(database.escapeColumnNameList(StringUtils.join(statement.getPrimaryKeyConstraint().getColumns(), ", "))); buffer.append(")"); if (database instanceof OracleDatabase && statement.getPrimaryKeyConstraint().getTablespace() != null) { buffer.append(" USING INDEX TABLESPACE "); buffer.append(statement.getPrimaryKeyConstraint().getTablespace()); } buffer.append(","); } } for (ForeignKeyConstraint fkConstraint : statement.getForeignKeyConstraints()) { if (!(database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } String referencesString = fkConstraint.getReferences(); if (!referencesString.contains(".") && database.getDefaultSchemaName() != null) { referencesString = database.getDefaultSchemaName()+"."+referencesString; } buffer.append(" FOREIGN KEY (") .append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), fkConstraint.getColumn())) .append(") REFERENCES ") .append(referencesString); if (fkConstraint.isDeleteCascade()) { buffer.append(" ON DELETE CASCADE"); } if ((database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } if (fkConstraint.isInitiallyDeferred()) { buffer.append(" INITIALLY DEFERRED"); } if (fkConstraint.isDeferrable()) { buffer.append(" DEFERRABLE"); } buffer.append(","); } for (UniqueConstraint uniqueConstraint : statement.getUniqueConstraints()) { if (uniqueConstraint.getConstraintName() != null && !constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(" UNIQUE ("); buffer.append(database.escapeColumnNameList(StringUtils.join(uniqueConstraint.getColumns(), ", "))); buffer.append(")"); if (uniqueConstraint.getConstraintName() != null && constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(","); } String sql = buffer.toString().replaceFirst(",\\s*$", "") + ")"; if (statement.getTablespace() != null && database.supportsTablespaces()) { if (database instanceof MSSQLDatabase || database instanceof SybaseASADatabase) { sql += " ON " + statement.getTablespace(); } else if (database instanceof DB2Database || database instanceof InformixDatabase) { sql += " IN " + statement.getTablespace(); } else { sql += " TABLESPACE " + statement.getTablespace(); } } return new Sql[] { new UnparsedSql(sql) }; } ValidationErrors validate(CreateTableStatement createTableStatement, Database database, SqlGeneratorChain sqlGeneratorChain); Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain); } |
@Test public void testAutoIncrementStartWithIncrementBySQLiteDatabase() throws Exception { for (Database database : TestContext.getInstance().getAllDatabases()) { if (database instanceof SQLiteDatabase) { CreateTableStatement statement = new CreateTableStatement(SCHEMA_NAME, TABLE_NAME); statement.addColumn( COLUMN_NAME1, TypeConverterFactory.getInstance().findTypeConverter(database).getDataType("BIGINT", true), new AutoIncrementConstraint(COLUMN_NAME1, BigInteger.valueOf(2), BigInteger.TEN) ); Sql[] generatedSql = this.generatorUnderTest.generateSql(statement, database, null); assertEquals("CREATE TABLE SCHEMA_NAME.TABLE_NAME (COLUMN1_NAME BIGINT AUTOINCREMENT)", generatedSql[0].toSql()); } } } | public Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { StringBuffer buffer = new StringBuffer(); buffer.append("CREATE TABLE ").append(database.escapeTableName(statement.getSchemaName(), statement.getTableName())).append(" "); buffer.append("("); boolean isSinglePrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() == 1; boolean isPrimaryKeyAutoIncrement = false; Iterator<String> columnIterator = statement.getColumns().iterator(); while (columnIterator.hasNext()) { String column = columnIterator.next(); buffer.append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), column)); buffer.append(" ").append(statement.getColumnTypes().get(column)); AutoIncrementConstraint autoIncrementConstraint = null; for (AutoIncrementConstraint currentAutoIncrementConstraint : statement.getAutoIncrementConstraints()) { if (column.equals(currentAutoIncrementConstraint.getColumnName())) { autoIncrementConstraint = currentAutoIncrementConstraint; break; } } boolean isAutoIncrementColumn = autoIncrementConstraint != null; boolean isPrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().contains(column); isPrimaryKeyAutoIncrement = isPrimaryKeyAutoIncrement || isPrimaryKeyColumn && isAutoIncrementColumn; if ((database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyColumn && isAutoIncrementColumn) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } buffer.append(" PRIMARY KEY AUTOINCREMENT"); } if (statement.getDefaultValue(column) != null) { Object defaultValue = statement.getDefaultValue(column); if (database instanceof MSSQLDatabase) { buffer.append(" CONSTRAINT ").append(((MSSQLDatabase) database).generateDefaultConstraintName(statement.getTableName(), column)); } buffer.append(" DEFAULT "); buffer.append(statement.getColumnTypes().get(column).convertObjectToString(defaultValue, database)); } if (isAutoIncrementColumn && ! (database instanceof SQLiteDatabase)) { if (database.supportsAutoIncrement()) { String autoIncrementClause = database.getAutoIncrementClause(autoIncrementConstraint.getStartWith(), autoIncrementConstraint.getIncrementBy()); if (!"".equals(autoIncrementClause)) { buffer.append(" ").append(autoIncrementClause); } } else { LogFactory.getLogger().warning(database.getTypeName()+" does not support autoincrement columns as request for "+(database.escapeTableName(statement.getSchemaName(), statement.getTableName()))); } } if (statement.getNotNullColumns().contains(column)) { buffer.append(" NOT NULL"); } else { if (database instanceof SybaseDatabase || database instanceof SybaseASADatabase || database instanceof MySQLDatabase) { if (database instanceof MySQLDatabase && statement.getColumnTypes().get(column).getDataTypeName().equalsIgnoreCase("timestamp")) { } else { buffer.append(" NULL"); } } } if (database instanceof InformixDatabase && isSinglePrimaryKeyColumn) { buffer.append(" PRIMARY KEY"); } if (columnIterator.hasNext()) { buffer.append(", "); } } buffer.append(","); if (!( (database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyAutoIncrement) && !((database instanceof InformixDatabase) && isSinglePrimaryKeyColumn )) { if (statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() > 0) { if (!(database instanceof InformixDatabase)) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } } buffer.append(" PRIMARY KEY ("); buffer.append(database.escapeColumnNameList(StringUtils.join(statement.getPrimaryKeyConstraint().getColumns(), ", "))); buffer.append(")"); if (database instanceof OracleDatabase && statement.getPrimaryKeyConstraint().getTablespace() != null) { buffer.append(" USING INDEX TABLESPACE "); buffer.append(statement.getPrimaryKeyConstraint().getTablespace()); } buffer.append(","); } } for (ForeignKeyConstraint fkConstraint : statement.getForeignKeyConstraints()) { if (!(database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } String referencesString = fkConstraint.getReferences(); if (!referencesString.contains(".") && database.getDefaultSchemaName() != null) { referencesString = database.getDefaultSchemaName()+"."+referencesString; } buffer.append(" FOREIGN KEY (") .append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), fkConstraint.getColumn())) .append(") REFERENCES ") .append(referencesString); if (fkConstraint.isDeleteCascade()) { buffer.append(" ON DELETE CASCADE"); } if ((database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } if (fkConstraint.isInitiallyDeferred()) { buffer.append(" INITIALLY DEFERRED"); } if (fkConstraint.isDeferrable()) { buffer.append(" DEFERRABLE"); } buffer.append(","); } for (UniqueConstraint uniqueConstraint : statement.getUniqueConstraints()) { if (uniqueConstraint.getConstraintName() != null && !constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(" UNIQUE ("); buffer.append(database.escapeColumnNameList(StringUtils.join(uniqueConstraint.getColumns(), ", "))); buffer.append(")"); if (uniqueConstraint.getConstraintName() != null && constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(","); } String sql = buffer.toString().replaceFirst(",\\s*$", "") + ")"; if (statement.getTablespace() != null && database.supportsTablespaces()) { if (database instanceof MSSQLDatabase || database instanceof SybaseASADatabase) { sql += " ON " + statement.getTablespace(); } else if (database instanceof DB2Database || database instanceof InformixDatabase) { sql += " IN " + statement.getTablespace(); } else { sql += " TABLESPACE " + statement.getTablespace(); } } return new Sql[] { new UnparsedSql(sql) }; } | CreateTableGenerator extends AbstractSqlGenerator<CreateTableStatement> { public Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { StringBuffer buffer = new StringBuffer(); buffer.append("CREATE TABLE ").append(database.escapeTableName(statement.getSchemaName(), statement.getTableName())).append(" "); buffer.append("("); boolean isSinglePrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() == 1; boolean isPrimaryKeyAutoIncrement = false; Iterator<String> columnIterator = statement.getColumns().iterator(); while (columnIterator.hasNext()) { String column = columnIterator.next(); buffer.append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), column)); buffer.append(" ").append(statement.getColumnTypes().get(column)); AutoIncrementConstraint autoIncrementConstraint = null; for (AutoIncrementConstraint currentAutoIncrementConstraint : statement.getAutoIncrementConstraints()) { if (column.equals(currentAutoIncrementConstraint.getColumnName())) { autoIncrementConstraint = currentAutoIncrementConstraint; break; } } boolean isAutoIncrementColumn = autoIncrementConstraint != null; boolean isPrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().contains(column); isPrimaryKeyAutoIncrement = isPrimaryKeyAutoIncrement || isPrimaryKeyColumn && isAutoIncrementColumn; if ((database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyColumn && isAutoIncrementColumn) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } buffer.append(" PRIMARY KEY AUTOINCREMENT"); } if (statement.getDefaultValue(column) != null) { Object defaultValue = statement.getDefaultValue(column); if (database instanceof MSSQLDatabase) { buffer.append(" CONSTRAINT ").append(((MSSQLDatabase) database).generateDefaultConstraintName(statement.getTableName(), column)); } buffer.append(" DEFAULT "); buffer.append(statement.getColumnTypes().get(column).convertObjectToString(defaultValue, database)); } if (isAutoIncrementColumn && ! (database instanceof SQLiteDatabase)) { if (database.supportsAutoIncrement()) { String autoIncrementClause = database.getAutoIncrementClause(autoIncrementConstraint.getStartWith(), autoIncrementConstraint.getIncrementBy()); if (!"".equals(autoIncrementClause)) { buffer.append(" ").append(autoIncrementClause); } } else { LogFactory.getLogger().warning(database.getTypeName()+" does not support autoincrement columns as request for "+(database.escapeTableName(statement.getSchemaName(), statement.getTableName()))); } } if (statement.getNotNullColumns().contains(column)) { buffer.append(" NOT NULL"); } else { if (database instanceof SybaseDatabase || database instanceof SybaseASADatabase || database instanceof MySQLDatabase) { if (database instanceof MySQLDatabase && statement.getColumnTypes().get(column).getDataTypeName().equalsIgnoreCase("timestamp")) { } else { buffer.append(" NULL"); } } } if (database instanceof InformixDatabase && isSinglePrimaryKeyColumn) { buffer.append(" PRIMARY KEY"); } if (columnIterator.hasNext()) { buffer.append(", "); } } buffer.append(","); if (!( (database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyAutoIncrement) && !((database instanceof InformixDatabase) && isSinglePrimaryKeyColumn )) { if (statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() > 0) { if (!(database instanceof InformixDatabase)) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } } buffer.append(" PRIMARY KEY ("); buffer.append(database.escapeColumnNameList(StringUtils.join(statement.getPrimaryKeyConstraint().getColumns(), ", "))); buffer.append(")"); if (database instanceof OracleDatabase && statement.getPrimaryKeyConstraint().getTablespace() != null) { buffer.append(" USING INDEX TABLESPACE "); buffer.append(statement.getPrimaryKeyConstraint().getTablespace()); } buffer.append(","); } } for (ForeignKeyConstraint fkConstraint : statement.getForeignKeyConstraints()) { if (!(database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } String referencesString = fkConstraint.getReferences(); if (!referencesString.contains(".") && database.getDefaultSchemaName() != null) { referencesString = database.getDefaultSchemaName()+"."+referencesString; } buffer.append(" FOREIGN KEY (") .append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), fkConstraint.getColumn())) .append(") REFERENCES ") .append(referencesString); if (fkConstraint.isDeleteCascade()) { buffer.append(" ON DELETE CASCADE"); } if ((database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } if (fkConstraint.isInitiallyDeferred()) { buffer.append(" INITIALLY DEFERRED"); } if (fkConstraint.isDeferrable()) { buffer.append(" DEFERRABLE"); } buffer.append(","); } for (UniqueConstraint uniqueConstraint : statement.getUniqueConstraints()) { if (uniqueConstraint.getConstraintName() != null && !constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(" UNIQUE ("); buffer.append(database.escapeColumnNameList(StringUtils.join(uniqueConstraint.getColumns(), ", "))); buffer.append(")"); if (uniqueConstraint.getConstraintName() != null && constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(","); } String sql = buffer.toString().replaceFirst(",\\s*$", "") + ")"; if (statement.getTablespace() != null && database.supportsTablespaces()) { if (database instanceof MSSQLDatabase || database instanceof SybaseASADatabase) { sql += " ON " + statement.getTablespace(); } else if (database instanceof DB2Database || database instanceof InformixDatabase) { sql += " IN " + statement.getTablespace(); } else { sql += " TABLESPACE " + statement.getTablespace(); } } return new Sql[] { new UnparsedSql(sql) }; } } | CreateTableGenerator extends AbstractSqlGenerator<CreateTableStatement> { public Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { StringBuffer buffer = new StringBuffer(); buffer.append("CREATE TABLE ").append(database.escapeTableName(statement.getSchemaName(), statement.getTableName())).append(" "); buffer.append("("); boolean isSinglePrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() == 1; boolean isPrimaryKeyAutoIncrement = false; Iterator<String> columnIterator = statement.getColumns().iterator(); while (columnIterator.hasNext()) { String column = columnIterator.next(); buffer.append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), column)); buffer.append(" ").append(statement.getColumnTypes().get(column)); AutoIncrementConstraint autoIncrementConstraint = null; for (AutoIncrementConstraint currentAutoIncrementConstraint : statement.getAutoIncrementConstraints()) { if (column.equals(currentAutoIncrementConstraint.getColumnName())) { autoIncrementConstraint = currentAutoIncrementConstraint; break; } } boolean isAutoIncrementColumn = autoIncrementConstraint != null; boolean isPrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().contains(column); isPrimaryKeyAutoIncrement = isPrimaryKeyAutoIncrement || isPrimaryKeyColumn && isAutoIncrementColumn; if ((database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyColumn && isAutoIncrementColumn) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } buffer.append(" PRIMARY KEY AUTOINCREMENT"); } if (statement.getDefaultValue(column) != null) { Object defaultValue = statement.getDefaultValue(column); if (database instanceof MSSQLDatabase) { buffer.append(" CONSTRAINT ").append(((MSSQLDatabase) database).generateDefaultConstraintName(statement.getTableName(), column)); } buffer.append(" DEFAULT "); buffer.append(statement.getColumnTypes().get(column).convertObjectToString(defaultValue, database)); } if (isAutoIncrementColumn && ! (database instanceof SQLiteDatabase)) { if (database.supportsAutoIncrement()) { String autoIncrementClause = database.getAutoIncrementClause(autoIncrementConstraint.getStartWith(), autoIncrementConstraint.getIncrementBy()); if (!"".equals(autoIncrementClause)) { buffer.append(" ").append(autoIncrementClause); } } else { LogFactory.getLogger().warning(database.getTypeName()+" does not support autoincrement columns as request for "+(database.escapeTableName(statement.getSchemaName(), statement.getTableName()))); } } if (statement.getNotNullColumns().contains(column)) { buffer.append(" NOT NULL"); } else { if (database instanceof SybaseDatabase || database instanceof SybaseASADatabase || database instanceof MySQLDatabase) { if (database instanceof MySQLDatabase && statement.getColumnTypes().get(column).getDataTypeName().equalsIgnoreCase("timestamp")) { } else { buffer.append(" NULL"); } } } if (database instanceof InformixDatabase && isSinglePrimaryKeyColumn) { buffer.append(" PRIMARY KEY"); } if (columnIterator.hasNext()) { buffer.append(", "); } } buffer.append(","); if (!( (database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyAutoIncrement) && !((database instanceof InformixDatabase) && isSinglePrimaryKeyColumn )) { if (statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() > 0) { if (!(database instanceof InformixDatabase)) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } } buffer.append(" PRIMARY KEY ("); buffer.append(database.escapeColumnNameList(StringUtils.join(statement.getPrimaryKeyConstraint().getColumns(), ", "))); buffer.append(")"); if (database instanceof OracleDatabase && statement.getPrimaryKeyConstraint().getTablespace() != null) { buffer.append(" USING INDEX TABLESPACE "); buffer.append(statement.getPrimaryKeyConstraint().getTablespace()); } buffer.append(","); } } for (ForeignKeyConstraint fkConstraint : statement.getForeignKeyConstraints()) { if (!(database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } String referencesString = fkConstraint.getReferences(); if (!referencesString.contains(".") && database.getDefaultSchemaName() != null) { referencesString = database.getDefaultSchemaName()+"."+referencesString; } buffer.append(" FOREIGN KEY (") .append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), fkConstraint.getColumn())) .append(") REFERENCES ") .append(referencesString); if (fkConstraint.isDeleteCascade()) { buffer.append(" ON DELETE CASCADE"); } if ((database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } if (fkConstraint.isInitiallyDeferred()) { buffer.append(" INITIALLY DEFERRED"); } if (fkConstraint.isDeferrable()) { buffer.append(" DEFERRABLE"); } buffer.append(","); } for (UniqueConstraint uniqueConstraint : statement.getUniqueConstraints()) { if (uniqueConstraint.getConstraintName() != null && !constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(" UNIQUE ("); buffer.append(database.escapeColumnNameList(StringUtils.join(uniqueConstraint.getColumns(), ", "))); buffer.append(")"); if (uniqueConstraint.getConstraintName() != null && constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(","); } String sql = buffer.toString().replaceFirst(",\\s*$", "") + ")"; if (statement.getTablespace() != null && database.supportsTablespaces()) { if (database instanceof MSSQLDatabase || database instanceof SybaseASADatabase) { sql += " ON " + statement.getTablespace(); } else if (database instanceof DB2Database || database instanceof InformixDatabase) { sql += " IN " + statement.getTablespace(); } else { sql += " TABLESPACE " + statement.getTablespace(); } } return new Sql[] { new UnparsedSql(sql) }; } } | CreateTableGenerator extends AbstractSqlGenerator<CreateTableStatement> { public Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { StringBuffer buffer = new StringBuffer(); buffer.append("CREATE TABLE ").append(database.escapeTableName(statement.getSchemaName(), statement.getTableName())).append(" "); buffer.append("("); boolean isSinglePrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() == 1; boolean isPrimaryKeyAutoIncrement = false; Iterator<String> columnIterator = statement.getColumns().iterator(); while (columnIterator.hasNext()) { String column = columnIterator.next(); buffer.append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), column)); buffer.append(" ").append(statement.getColumnTypes().get(column)); AutoIncrementConstraint autoIncrementConstraint = null; for (AutoIncrementConstraint currentAutoIncrementConstraint : statement.getAutoIncrementConstraints()) { if (column.equals(currentAutoIncrementConstraint.getColumnName())) { autoIncrementConstraint = currentAutoIncrementConstraint; break; } } boolean isAutoIncrementColumn = autoIncrementConstraint != null; boolean isPrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().contains(column); isPrimaryKeyAutoIncrement = isPrimaryKeyAutoIncrement || isPrimaryKeyColumn && isAutoIncrementColumn; if ((database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyColumn && isAutoIncrementColumn) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } buffer.append(" PRIMARY KEY AUTOINCREMENT"); } if (statement.getDefaultValue(column) != null) { Object defaultValue = statement.getDefaultValue(column); if (database instanceof MSSQLDatabase) { buffer.append(" CONSTRAINT ").append(((MSSQLDatabase) database).generateDefaultConstraintName(statement.getTableName(), column)); } buffer.append(" DEFAULT "); buffer.append(statement.getColumnTypes().get(column).convertObjectToString(defaultValue, database)); } if (isAutoIncrementColumn && ! (database instanceof SQLiteDatabase)) { if (database.supportsAutoIncrement()) { String autoIncrementClause = database.getAutoIncrementClause(autoIncrementConstraint.getStartWith(), autoIncrementConstraint.getIncrementBy()); if (!"".equals(autoIncrementClause)) { buffer.append(" ").append(autoIncrementClause); } } else { LogFactory.getLogger().warning(database.getTypeName()+" does not support autoincrement columns as request for "+(database.escapeTableName(statement.getSchemaName(), statement.getTableName()))); } } if (statement.getNotNullColumns().contains(column)) { buffer.append(" NOT NULL"); } else { if (database instanceof SybaseDatabase || database instanceof SybaseASADatabase || database instanceof MySQLDatabase) { if (database instanceof MySQLDatabase && statement.getColumnTypes().get(column).getDataTypeName().equalsIgnoreCase("timestamp")) { } else { buffer.append(" NULL"); } } } if (database instanceof InformixDatabase && isSinglePrimaryKeyColumn) { buffer.append(" PRIMARY KEY"); } if (columnIterator.hasNext()) { buffer.append(", "); } } buffer.append(","); if (!( (database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyAutoIncrement) && !((database instanceof InformixDatabase) && isSinglePrimaryKeyColumn )) { if (statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() > 0) { if (!(database instanceof InformixDatabase)) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } } buffer.append(" PRIMARY KEY ("); buffer.append(database.escapeColumnNameList(StringUtils.join(statement.getPrimaryKeyConstraint().getColumns(), ", "))); buffer.append(")"); if (database instanceof OracleDatabase && statement.getPrimaryKeyConstraint().getTablespace() != null) { buffer.append(" USING INDEX TABLESPACE "); buffer.append(statement.getPrimaryKeyConstraint().getTablespace()); } buffer.append(","); } } for (ForeignKeyConstraint fkConstraint : statement.getForeignKeyConstraints()) { if (!(database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } String referencesString = fkConstraint.getReferences(); if (!referencesString.contains(".") && database.getDefaultSchemaName() != null) { referencesString = database.getDefaultSchemaName()+"."+referencesString; } buffer.append(" FOREIGN KEY (") .append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), fkConstraint.getColumn())) .append(") REFERENCES ") .append(referencesString); if (fkConstraint.isDeleteCascade()) { buffer.append(" ON DELETE CASCADE"); } if ((database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } if (fkConstraint.isInitiallyDeferred()) { buffer.append(" INITIALLY DEFERRED"); } if (fkConstraint.isDeferrable()) { buffer.append(" DEFERRABLE"); } buffer.append(","); } for (UniqueConstraint uniqueConstraint : statement.getUniqueConstraints()) { if (uniqueConstraint.getConstraintName() != null && !constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(" UNIQUE ("); buffer.append(database.escapeColumnNameList(StringUtils.join(uniqueConstraint.getColumns(), ", "))); buffer.append(")"); if (uniqueConstraint.getConstraintName() != null && constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(","); } String sql = buffer.toString().replaceFirst(",\\s*$", "") + ")"; if (statement.getTablespace() != null && database.supportsTablespaces()) { if (database instanceof MSSQLDatabase || database instanceof SybaseASADatabase) { sql += " ON " + statement.getTablespace(); } else if (database instanceof DB2Database || database instanceof InformixDatabase) { sql += " IN " + statement.getTablespace(); } else { sql += " TABLESPACE " + statement.getTablespace(); } } return new Sql[] { new UnparsedSql(sql) }; } ValidationErrors validate(CreateTableStatement createTableStatement, Database database, SqlGeneratorChain sqlGeneratorChain); Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain); } | CreateTableGenerator extends AbstractSqlGenerator<CreateTableStatement> { public Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { StringBuffer buffer = new StringBuffer(); buffer.append("CREATE TABLE ").append(database.escapeTableName(statement.getSchemaName(), statement.getTableName())).append(" "); buffer.append("("); boolean isSinglePrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() == 1; boolean isPrimaryKeyAutoIncrement = false; Iterator<String> columnIterator = statement.getColumns().iterator(); while (columnIterator.hasNext()) { String column = columnIterator.next(); buffer.append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), column)); buffer.append(" ").append(statement.getColumnTypes().get(column)); AutoIncrementConstraint autoIncrementConstraint = null; for (AutoIncrementConstraint currentAutoIncrementConstraint : statement.getAutoIncrementConstraints()) { if (column.equals(currentAutoIncrementConstraint.getColumnName())) { autoIncrementConstraint = currentAutoIncrementConstraint; break; } } boolean isAutoIncrementColumn = autoIncrementConstraint != null; boolean isPrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().contains(column); isPrimaryKeyAutoIncrement = isPrimaryKeyAutoIncrement || isPrimaryKeyColumn && isAutoIncrementColumn; if ((database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyColumn && isAutoIncrementColumn) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } buffer.append(" PRIMARY KEY AUTOINCREMENT"); } if (statement.getDefaultValue(column) != null) { Object defaultValue = statement.getDefaultValue(column); if (database instanceof MSSQLDatabase) { buffer.append(" CONSTRAINT ").append(((MSSQLDatabase) database).generateDefaultConstraintName(statement.getTableName(), column)); } buffer.append(" DEFAULT "); buffer.append(statement.getColumnTypes().get(column).convertObjectToString(defaultValue, database)); } if (isAutoIncrementColumn && ! (database instanceof SQLiteDatabase)) { if (database.supportsAutoIncrement()) { String autoIncrementClause = database.getAutoIncrementClause(autoIncrementConstraint.getStartWith(), autoIncrementConstraint.getIncrementBy()); if (!"".equals(autoIncrementClause)) { buffer.append(" ").append(autoIncrementClause); } } else { LogFactory.getLogger().warning(database.getTypeName()+" does not support autoincrement columns as request for "+(database.escapeTableName(statement.getSchemaName(), statement.getTableName()))); } } if (statement.getNotNullColumns().contains(column)) { buffer.append(" NOT NULL"); } else { if (database instanceof SybaseDatabase || database instanceof SybaseASADatabase || database instanceof MySQLDatabase) { if (database instanceof MySQLDatabase && statement.getColumnTypes().get(column).getDataTypeName().equalsIgnoreCase("timestamp")) { } else { buffer.append(" NULL"); } } } if (database instanceof InformixDatabase && isSinglePrimaryKeyColumn) { buffer.append(" PRIMARY KEY"); } if (columnIterator.hasNext()) { buffer.append(", "); } } buffer.append(","); if (!( (database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyAutoIncrement) && !((database instanceof InformixDatabase) && isSinglePrimaryKeyColumn )) { if (statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() > 0) { if (!(database instanceof InformixDatabase)) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } } buffer.append(" PRIMARY KEY ("); buffer.append(database.escapeColumnNameList(StringUtils.join(statement.getPrimaryKeyConstraint().getColumns(), ", "))); buffer.append(")"); if (database instanceof OracleDatabase && statement.getPrimaryKeyConstraint().getTablespace() != null) { buffer.append(" USING INDEX TABLESPACE "); buffer.append(statement.getPrimaryKeyConstraint().getTablespace()); } buffer.append(","); } } for (ForeignKeyConstraint fkConstraint : statement.getForeignKeyConstraints()) { if (!(database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } String referencesString = fkConstraint.getReferences(); if (!referencesString.contains(".") && database.getDefaultSchemaName() != null) { referencesString = database.getDefaultSchemaName()+"."+referencesString; } buffer.append(" FOREIGN KEY (") .append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), fkConstraint.getColumn())) .append(") REFERENCES ") .append(referencesString); if (fkConstraint.isDeleteCascade()) { buffer.append(" ON DELETE CASCADE"); } if ((database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } if (fkConstraint.isInitiallyDeferred()) { buffer.append(" INITIALLY DEFERRED"); } if (fkConstraint.isDeferrable()) { buffer.append(" DEFERRABLE"); } buffer.append(","); } for (UniqueConstraint uniqueConstraint : statement.getUniqueConstraints()) { if (uniqueConstraint.getConstraintName() != null && !constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(" UNIQUE ("); buffer.append(database.escapeColumnNameList(StringUtils.join(uniqueConstraint.getColumns(), ", "))); buffer.append(")"); if (uniqueConstraint.getConstraintName() != null && constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(","); } String sql = buffer.toString().replaceFirst(",\\s*$", "") + ")"; if (statement.getTablespace() != null && database.supportsTablespaces()) { if (database instanceof MSSQLDatabase || database instanceof SybaseASADatabase) { sql += " ON " + statement.getTablespace(); } else if (database instanceof DB2Database || database instanceof InformixDatabase) { sql += " IN " + statement.getTablespace(); } else { sql += " TABLESPACE " + statement.getTablespace(); } } return new Sql[] { new UnparsedSql(sql) }; } ValidationErrors validate(CreateTableStatement createTableStatement, Database database, SqlGeneratorChain sqlGeneratorChain); Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain); } |
@Test public void testAutoIncrementSybaseASADatabase() throws Exception { for (Database database : TestContext.getInstance().getAllDatabases()) { if (database instanceof SybaseASADatabase) { CreateTableStatement statement = new CreateTableStatement(SCHEMA_NAME, TABLE_NAME); statement.addColumn( COLUMN_NAME1, TypeConverterFactory.getInstance().findTypeConverter(database).getDataType("BIGINT", true), new AutoIncrementConstraint(COLUMN_NAME1) ); Sql[] generatedSql = this.generatorUnderTest.generateSql(statement, database, null); assertEquals("CREATE TABLE \"SCHEMA_NAME\".\"TABLE_NAME\" (\"COLUMN1_NAME\" BIGINT DEFAULT AUTOINCREMENT NULL)", generatedSql[0].toSql()); } } } | public Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { StringBuffer buffer = new StringBuffer(); buffer.append("CREATE TABLE ").append(database.escapeTableName(statement.getSchemaName(), statement.getTableName())).append(" "); buffer.append("("); boolean isSinglePrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() == 1; boolean isPrimaryKeyAutoIncrement = false; Iterator<String> columnIterator = statement.getColumns().iterator(); while (columnIterator.hasNext()) { String column = columnIterator.next(); buffer.append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), column)); buffer.append(" ").append(statement.getColumnTypes().get(column)); AutoIncrementConstraint autoIncrementConstraint = null; for (AutoIncrementConstraint currentAutoIncrementConstraint : statement.getAutoIncrementConstraints()) { if (column.equals(currentAutoIncrementConstraint.getColumnName())) { autoIncrementConstraint = currentAutoIncrementConstraint; break; } } boolean isAutoIncrementColumn = autoIncrementConstraint != null; boolean isPrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().contains(column); isPrimaryKeyAutoIncrement = isPrimaryKeyAutoIncrement || isPrimaryKeyColumn && isAutoIncrementColumn; if ((database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyColumn && isAutoIncrementColumn) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } buffer.append(" PRIMARY KEY AUTOINCREMENT"); } if (statement.getDefaultValue(column) != null) { Object defaultValue = statement.getDefaultValue(column); if (database instanceof MSSQLDatabase) { buffer.append(" CONSTRAINT ").append(((MSSQLDatabase) database).generateDefaultConstraintName(statement.getTableName(), column)); } buffer.append(" DEFAULT "); buffer.append(statement.getColumnTypes().get(column).convertObjectToString(defaultValue, database)); } if (isAutoIncrementColumn && ! (database instanceof SQLiteDatabase)) { if (database.supportsAutoIncrement()) { String autoIncrementClause = database.getAutoIncrementClause(autoIncrementConstraint.getStartWith(), autoIncrementConstraint.getIncrementBy()); if (!"".equals(autoIncrementClause)) { buffer.append(" ").append(autoIncrementClause); } } else { LogFactory.getLogger().warning(database.getTypeName()+" does not support autoincrement columns as request for "+(database.escapeTableName(statement.getSchemaName(), statement.getTableName()))); } } if (statement.getNotNullColumns().contains(column)) { buffer.append(" NOT NULL"); } else { if (database instanceof SybaseDatabase || database instanceof SybaseASADatabase || database instanceof MySQLDatabase) { if (database instanceof MySQLDatabase && statement.getColumnTypes().get(column).getDataTypeName().equalsIgnoreCase("timestamp")) { } else { buffer.append(" NULL"); } } } if (database instanceof InformixDatabase && isSinglePrimaryKeyColumn) { buffer.append(" PRIMARY KEY"); } if (columnIterator.hasNext()) { buffer.append(", "); } } buffer.append(","); if (!( (database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyAutoIncrement) && !((database instanceof InformixDatabase) && isSinglePrimaryKeyColumn )) { if (statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() > 0) { if (!(database instanceof InformixDatabase)) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } } buffer.append(" PRIMARY KEY ("); buffer.append(database.escapeColumnNameList(StringUtils.join(statement.getPrimaryKeyConstraint().getColumns(), ", "))); buffer.append(")"); if (database instanceof OracleDatabase && statement.getPrimaryKeyConstraint().getTablespace() != null) { buffer.append(" USING INDEX TABLESPACE "); buffer.append(statement.getPrimaryKeyConstraint().getTablespace()); } buffer.append(","); } } for (ForeignKeyConstraint fkConstraint : statement.getForeignKeyConstraints()) { if (!(database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } String referencesString = fkConstraint.getReferences(); if (!referencesString.contains(".") && database.getDefaultSchemaName() != null) { referencesString = database.getDefaultSchemaName()+"."+referencesString; } buffer.append(" FOREIGN KEY (") .append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), fkConstraint.getColumn())) .append(") REFERENCES ") .append(referencesString); if (fkConstraint.isDeleteCascade()) { buffer.append(" ON DELETE CASCADE"); } if ((database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } if (fkConstraint.isInitiallyDeferred()) { buffer.append(" INITIALLY DEFERRED"); } if (fkConstraint.isDeferrable()) { buffer.append(" DEFERRABLE"); } buffer.append(","); } for (UniqueConstraint uniqueConstraint : statement.getUniqueConstraints()) { if (uniqueConstraint.getConstraintName() != null && !constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(" UNIQUE ("); buffer.append(database.escapeColumnNameList(StringUtils.join(uniqueConstraint.getColumns(), ", "))); buffer.append(")"); if (uniqueConstraint.getConstraintName() != null && constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(","); } String sql = buffer.toString().replaceFirst(",\\s*$", "") + ")"; if (statement.getTablespace() != null && database.supportsTablespaces()) { if (database instanceof MSSQLDatabase || database instanceof SybaseASADatabase) { sql += " ON " + statement.getTablespace(); } else if (database instanceof DB2Database || database instanceof InformixDatabase) { sql += " IN " + statement.getTablespace(); } else { sql += " TABLESPACE " + statement.getTablespace(); } } return new Sql[] { new UnparsedSql(sql) }; } | CreateTableGenerator extends AbstractSqlGenerator<CreateTableStatement> { public Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { StringBuffer buffer = new StringBuffer(); buffer.append("CREATE TABLE ").append(database.escapeTableName(statement.getSchemaName(), statement.getTableName())).append(" "); buffer.append("("); boolean isSinglePrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() == 1; boolean isPrimaryKeyAutoIncrement = false; Iterator<String> columnIterator = statement.getColumns().iterator(); while (columnIterator.hasNext()) { String column = columnIterator.next(); buffer.append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), column)); buffer.append(" ").append(statement.getColumnTypes().get(column)); AutoIncrementConstraint autoIncrementConstraint = null; for (AutoIncrementConstraint currentAutoIncrementConstraint : statement.getAutoIncrementConstraints()) { if (column.equals(currentAutoIncrementConstraint.getColumnName())) { autoIncrementConstraint = currentAutoIncrementConstraint; break; } } boolean isAutoIncrementColumn = autoIncrementConstraint != null; boolean isPrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().contains(column); isPrimaryKeyAutoIncrement = isPrimaryKeyAutoIncrement || isPrimaryKeyColumn && isAutoIncrementColumn; if ((database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyColumn && isAutoIncrementColumn) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } buffer.append(" PRIMARY KEY AUTOINCREMENT"); } if (statement.getDefaultValue(column) != null) { Object defaultValue = statement.getDefaultValue(column); if (database instanceof MSSQLDatabase) { buffer.append(" CONSTRAINT ").append(((MSSQLDatabase) database).generateDefaultConstraintName(statement.getTableName(), column)); } buffer.append(" DEFAULT "); buffer.append(statement.getColumnTypes().get(column).convertObjectToString(defaultValue, database)); } if (isAutoIncrementColumn && ! (database instanceof SQLiteDatabase)) { if (database.supportsAutoIncrement()) { String autoIncrementClause = database.getAutoIncrementClause(autoIncrementConstraint.getStartWith(), autoIncrementConstraint.getIncrementBy()); if (!"".equals(autoIncrementClause)) { buffer.append(" ").append(autoIncrementClause); } } else { LogFactory.getLogger().warning(database.getTypeName()+" does not support autoincrement columns as request for "+(database.escapeTableName(statement.getSchemaName(), statement.getTableName()))); } } if (statement.getNotNullColumns().contains(column)) { buffer.append(" NOT NULL"); } else { if (database instanceof SybaseDatabase || database instanceof SybaseASADatabase || database instanceof MySQLDatabase) { if (database instanceof MySQLDatabase && statement.getColumnTypes().get(column).getDataTypeName().equalsIgnoreCase("timestamp")) { } else { buffer.append(" NULL"); } } } if (database instanceof InformixDatabase && isSinglePrimaryKeyColumn) { buffer.append(" PRIMARY KEY"); } if (columnIterator.hasNext()) { buffer.append(", "); } } buffer.append(","); if (!( (database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyAutoIncrement) && !((database instanceof InformixDatabase) && isSinglePrimaryKeyColumn )) { if (statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() > 0) { if (!(database instanceof InformixDatabase)) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } } buffer.append(" PRIMARY KEY ("); buffer.append(database.escapeColumnNameList(StringUtils.join(statement.getPrimaryKeyConstraint().getColumns(), ", "))); buffer.append(")"); if (database instanceof OracleDatabase && statement.getPrimaryKeyConstraint().getTablespace() != null) { buffer.append(" USING INDEX TABLESPACE "); buffer.append(statement.getPrimaryKeyConstraint().getTablespace()); } buffer.append(","); } } for (ForeignKeyConstraint fkConstraint : statement.getForeignKeyConstraints()) { if (!(database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } String referencesString = fkConstraint.getReferences(); if (!referencesString.contains(".") && database.getDefaultSchemaName() != null) { referencesString = database.getDefaultSchemaName()+"."+referencesString; } buffer.append(" FOREIGN KEY (") .append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), fkConstraint.getColumn())) .append(") REFERENCES ") .append(referencesString); if (fkConstraint.isDeleteCascade()) { buffer.append(" ON DELETE CASCADE"); } if ((database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } if (fkConstraint.isInitiallyDeferred()) { buffer.append(" INITIALLY DEFERRED"); } if (fkConstraint.isDeferrable()) { buffer.append(" DEFERRABLE"); } buffer.append(","); } for (UniqueConstraint uniqueConstraint : statement.getUniqueConstraints()) { if (uniqueConstraint.getConstraintName() != null && !constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(" UNIQUE ("); buffer.append(database.escapeColumnNameList(StringUtils.join(uniqueConstraint.getColumns(), ", "))); buffer.append(")"); if (uniqueConstraint.getConstraintName() != null && constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(","); } String sql = buffer.toString().replaceFirst(",\\s*$", "") + ")"; if (statement.getTablespace() != null && database.supportsTablespaces()) { if (database instanceof MSSQLDatabase || database instanceof SybaseASADatabase) { sql += " ON " + statement.getTablespace(); } else if (database instanceof DB2Database || database instanceof InformixDatabase) { sql += " IN " + statement.getTablespace(); } else { sql += " TABLESPACE " + statement.getTablespace(); } } return new Sql[] { new UnparsedSql(sql) }; } } | CreateTableGenerator extends AbstractSqlGenerator<CreateTableStatement> { public Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { StringBuffer buffer = new StringBuffer(); buffer.append("CREATE TABLE ").append(database.escapeTableName(statement.getSchemaName(), statement.getTableName())).append(" "); buffer.append("("); boolean isSinglePrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() == 1; boolean isPrimaryKeyAutoIncrement = false; Iterator<String> columnIterator = statement.getColumns().iterator(); while (columnIterator.hasNext()) { String column = columnIterator.next(); buffer.append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), column)); buffer.append(" ").append(statement.getColumnTypes().get(column)); AutoIncrementConstraint autoIncrementConstraint = null; for (AutoIncrementConstraint currentAutoIncrementConstraint : statement.getAutoIncrementConstraints()) { if (column.equals(currentAutoIncrementConstraint.getColumnName())) { autoIncrementConstraint = currentAutoIncrementConstraint; break; } } boolean isAutoIncrementColumn = autoIncrementConstraint != null; boolean isPrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().contains(column); isPrimaryKeyAutoIncrement = isPrimaryKeyAutoIncrement || isPrimaryKeyColumn && isAutoIncrementColumn; if ((database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyColumn && isAutoIncrementColumn) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } buffer.append(" PRIMARY KEY AUTOINCREMENT"); } if (statement.getDefaultValue(column) != null) { Object defaultValue = statement.getDefaultValue(column); if (database instanceof MSSQLDatabase) { buffer.append(" CONSTRAINT ").append(((MSSQLDatabase) database).generateDefaultConstraintName(statement.getTableName(), column)); } buffer.append(" DEFAULT "); buffer.append(statement.getColumnTypes().get(column).convertObjectToString(defaultValue, database)); } if (isAutoIncrementColumn && ! (database instanceof SQLiteDatabase)) { if (database.supportsAutoIncrement()) { String autoIncrementClause = database.getAutoIncrementClause(autoIncrementConstraint.getStartWith(), autoIncrementConstraint.getIncrementBy()); if (!"".equals(autoIncrementClause)) { buffer.append(" ").append(autoIncrementClause); } } else { LogFactory.getLogger().warning(database.getTypeName()+" does not support autoincrement columns as request for "+(database.escapeTableName(statement.getSchemaName(), statement.getTableName()))); } } if (statement.getNotNullColumns().contains(column)) { buffer.append(" NOT NULL"); } else { if (database instanceof SybaseDatabase || database instanceof SybaseASADatabase || database instanceof MySQLDatabase) { if (database instanceof MySQLDatabase && statement.getColumnTypes().get(column).getDataTypeName().equalsIgnoreCase("timestamp")) { } else { buffer.append(" NULL"); } } } if (database instanceof InformixDatabase && isSinglePrimaryKeyColumn) { buffer.append(" PRIMARY KEY"); } if (columnIterator.hasNext()) { buffer.append(", "); } } buffer.append(","); if (!( (database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyAutoIncrement) && !((database instanceof InformixDatabase) && isSinglePrimaryKeyColumn )) { if (statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() > 0) { if (!(database instanceof InformixDatabase)) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } } buffer.append(" PRIMARY KEY ("); buffer.append(database.escapeColumnNameList(StringUtils.join(statement.getPrimaryKeyConstraint().getColumns(), ", "))); buffer.append(")"); if (database instanceof OracleDatabase && statement.getPrimaryKeyConstraint().getTablespace() != null) { buffer.append(" USING INDEX TABLESPACE "); buffer.append(statement.getPrimaryKeyConstraint().getTablespace()); } buffer.append(","); } } for (ForeignKeyConstraint fkConstraint : statement.getForeignKeyConstraints()) { if (!(database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } String referencesString = fkConstraint.getReferences(); if (!referencesString.contains(".") && database.getDefaultSchemaName() != null) { referencesString = database.getDefaultSchemaName()+"."+referencesString; } buffer.append(" FOREIGN KEY (") .append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), fkConstraint.getColumn())) .append(") REFERENCES ") .append(referencesString); if (fkConstraint.isDeleteCascade()) { buffer.append(" ON DELETE CASCADE"); } if ((database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } if (fkConstraint.isInitiallyDeferred()) { buffer.append(" INITIALLY DEFERRED"); } if (fkConstraint.isDeferrable()) { buffer.append(" DEFERRABLE"); } buffer.append(","); } for (UniqueConstraint uniqueConstraint : statement.getUniqueConstraints()) { if (uniqueConstraint.getConstraintName() != null && !constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(" UNIQUE ("); buffer.append(database.escapeColumnNameList(StringUtils.join(uniqueConstraint.getColumns(), ", "))); buffer.append(")"); if (uniqueConstraint.getConstraintName() != null && constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(","); } String sql = buffer.toString().replaceFirst(",\\s*$", "") + ")"; if (statement.getTablespace() != null && database.supportsTablespaces()) { if (database instanceof MSSQLDatabase || database instanceof SybaseASADatabase) { sql += " ON " + statement.getTablespace(); } else if (database instanceof DB2Database || database instanceof InformixDatabase) { sql += " IN " + statement.getTablespace(); } else { sql += " TABLESPACE " + statement.getTablespace(); } } return new Sql[] { new UnparsedSql(sql) }; } } | CreateTableGenerator extends AbstractSqlGenerator<CreateTableStatement> { public Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { StringBuffer buffer = new StringBuffer(); buffer.append("CREATE TABLE ").append(database.escapeTableName(statement.getSchemaName(), statement.getTableName())).append(" "); buffer.append("("); boolean isSinglePrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() == 1; boolean isPrimaryKeyAutoIncrement = false; Iterator<String> columnIterator = statement.getColumns().iterator(); while (columnIterator.hasNext()) { String column = columnIterator.next(); buffer.append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), column)); buffer.append(" ").append(statement.getColumnTypes().get(column)); AutoIncrementConstraint autoIncrementConstraint = null; for (AutoIncrementConstraint currentAutoIncrementConstraint : statement.getAutoIncrementConstraints()) { if (column.equals(currentAutoIncrementConstraint.getColumnName())) { autoIncrementConstraint = currentAutoIncrementConstraint; break; } } boolean isAutoIncrementColumn = autoIncrementConstraint != null; boolean isPrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().contains(column); isPrimaryKeyAutoIncrement = isPrimaryKeyAutoIncrement || isPrimaryKeyColumn && isAutoIncrementColumn; if ((database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyColumn && isAutoIncrementColumn) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } buffer.append(" PRIMARY KEY AUTOINCREMENT"); } if (statement.getDefaultValue(column) != null) { Object defaultValue = statement.getDefaultValue(column); if (database instanceof MSSQLDatabase) { buffer.append(" CONSTRAINT ").append(((MSSQLDatabase) database).generateDefaultConstraintName(statement.getTableName(), column)); } buffer.append(" DEFAULT "); buffer.append(statement.getColumnTypes().get(column).convertObjectToString(defaultValue, database)); } if (isAutoIncrementColumn && ! (database instanceof SQLiteDatabase)) { if (database.supportsAutoIncrement()) { String autoIncrementClause = database.getAutoIncrementClause(autoIncrementConstraint.getStartWith(), autoIncrementConstraint.getIncrementBy()); if (!"".equals(autoIncrementClause)) { buffer.append(" ").append(autoIncrementClause); } } else { LogFactory.getLogger().warning(database.getTypeName()+" does not support autoincrement columns as request for "+(database.escapeTableName(statement.getSchemaName(), statement.getTableName()))); } } if (statement.getNotNullColumns().contains(column)) { buffer.append(" NOT NULL"); } else { if (database instanceof SybaseDatabase || database instanceof SybaseASADatabase || database instanceof MySQLDatabase) { if (database instanceof MySQLDatabase && statement.getColumnTypes().get(column).getDataTypeName().equalsIgnoreCase("timestamp")) { } else { buffer.append(" NULL"); } } } if (database instanceof InformixDatabase && isSinglePrimaryKeyColumn) { buffer.append(" PRIMARY KEY"); } if (columnIterator.hasNext()) { buffer.append(", "); } } buffer.append(","); if (!( (database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyAutoIncrement) && !((database instanceof InformixDatabase) && isSinglePrimaryKeyColumn )) { if (statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() > 0) { if (!(database instanceof InformixDatabase)) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } } buffer.append(" PRIMARY KEY ("); buffer.append(database.escapeColumnNameList(StringUtils.join(statement.getPrimaryKeyConstraint().getColumns(), ", "))); buffer.append(")"); if (database instanceof OracleDatabase && statement.getPrimaryKeyConstraint().getTablespace() != null) { buffer.append(" USING INDEX TABLESPACE "); buffer.append(statement.getPrimaryKeyConstraint().getTablespace()); } buffer.append(","); } } for (ForeignKeyConstraint fkConstraint : statement.getForeignKeyConstraints()) { if (!(database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } String referencesString = fkConstraint.getReferences(); if (!referencesString.contains(".") && database.getDefaultSchemaName() != null) { referencesString = database.getDefaultSchemaName()+"."+referencesString; } buffer.append(" FOREIGN KEY (") .append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), fkConstraint.getColumn())) .append(") REFERENCES ") .append(referencesString); if (fkConstraint.isDeleteCascade()) { buffer.append(" ON DELETE CASCADE"); } if ((database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } if (fkConstraint.isInitiallyDeferred()) { buffer.append(" INITIALLY DEFERRED"); } if (fkConstraint.isDeferrable()) { buffer.append(" DEFERRABLE"); } buffer.append(","); } for (UniqueConstraint uniqueConstraint : statement.getUniqueConstraints()) { if (uniqueConstraint.getConstraintName() != null && !constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(" UNIQUE ("); buffer.append(database.escapeColumnNameList(StringUtils.join(uniqueConstraint.getColumns(), ", "))); buffer.append(")"); if (uniqueConstraint.getConstraintName() != null && constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(","); } String sql = buffer.toString().replaceFirst(",\\s*$", "") + ")"; if (statement.getTablespace() != null && database.supportsTablespaces()) { if (database instanceof MSSQLDatabase || database instanceof SybaseASADatabase) { sql += " ON " + statement.getTablespace(); } else if (database instanceof DB2Database || database instanceof InformixDatabase) { sql += " IN " + statement.getTablespace(); } else { sql += " TABLESPACE " + statement.getTablespace(); } } return new Sql[] { new UnparsedSql(sql) }; } ValidationErrors validate(CreateTableStatement createTableStatement, Database database, SqlGeneratorChain sqlGeneratorChain); Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain); } | CreateTableGenerator extends AbstractSqlGenerator<CreateTableStatement> { public Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { StringBuffer buffer = new StringBuffer(); buffer.append("CREATE TABLE ").append(database.escapeTableName(statement.getSchemaName(), statement.getTableName())).append(" "); buffer.append("("); boolean isSinglePrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() == 1; boolean isPrimaryKeyAutoIncrement = false; Iterator<String> columnIterator = statement.getColumns().iterator(); while (columnIterator.hasNext()) { String column = columnIterator.next(); buffer.append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), column)); buffer.append(" ").append(statement.getColumnTypes().get(column)); AutoIncrementConstraint autoIncrementConstraint = null; for (AutoIncrementConstraint currentAutoIncrementConstraint : statement.getAutoIncrementConstraints()) { if (column.equals(currentAutoIncrementConstraint.getColumnName())) { autoIncrementConstraint = currentAutoIncrementConstraint; break; } } boolean isAutoIncrementColumn = autoIncrementConstraint != null; boolean isPrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().contains(column); isPrimaryKeyAutoIncrement = isPrimaryKeyAutoIncrement || isPrimaryKeyColumn && isAutoIncrementColumn; if ((database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyColumn && isAutoIncrementColumn) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } buffer.append(" PRIMARY KEY AUTOINCREMENT"); } if (statement.getDefaultValue(column) != null) { Object defaultValue = statement.getDefaultValue(column); if (database instanceof MSSQLDatabase) { buffer.append(" CONSTRAINT ").append(((MSSQLDatabase) database).generateDefaultConstraintName(statement.getTableName(), column)); } buffer.append(" DEFAULT "); buffer.append(statement.getColumnTypes().get(column).convertObjectToString(defaultValue, database)); } if (isAutoIncrementColumn && ! (database instanceof SQLiteDatabase)) { if (database.supportsAutoIncrement()) { String autoIncrementClause = database.getAutoIncrementClause(autoIncrementConstraint.getStartWith(), autoIncrementConstraint.getIncrementBy()); if (!"".equals(autoIncrementClause)) { buffer.append(" ").append(autoIncrementClause); } } else { LogFactory.getLogger().warning(database.getTypeName()+" does not support autoincrement columns as request for "+(database.escapeTableName(statement.getSchemaName(), statement.getTableName()))); } } if (statement.getNotNullColumns().contains(column)) { buffer.append(" NOT NULL"); } else { if (database instanceof SybaseDatabase || database instanceof SybaseASADatabase || database instanceof MySQLDatabase) { if (database instanceof MySQLDatabase && statement.getColumnTypes().get(column).getDataTypeName().equalsIgnoreCase("timestamp")) { } else { buffer.append(" NULL"); } } } if (database instanceof InformixDatabase && isSinglePrimaryKeyColumn) { buffer.append(" PRIMARY KEY"); } if (columnIterator.hasNext()) { buffer.append(", "); } } buffer.append(","); if (!( (database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyAutoIncrement) && !((database instanceof InformixDatabase) && isSinglePrimaryKeyColumn )) { if (statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() > 0) { if (!(database instanceof InformixDatabase)) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } } buffer.append(" PRIMARY KEY ("); buffer.append(database.escapeColumnNameList(StringUtils.join(statement.getPrimaryKeyConstraint().getColumns(), ", "))); buffer.append(")"); if (database instanceof OracleDatabase && statement.getPrimaryKeyConstraint().getTablespace() != null) { buffer.append(" USING INDEX TABLESPACE "); buffer.append(statement.getPrimaryKeyConstraint().getTablespace()); } buffer.append(","); } } for (ForeignKeyConstraint fkConstraint : statement.getForeignKeyConstraints()) { if (!(database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } String referencesString = fkConstraint.getReferences(); if (!referencesString.contains(".") && database.getDefaultSchemaName() != null) { referencesString = database.getDefaultSchemaName()+"."+referencesString; } buffer.append(" FOREIGN KEY (") .append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), fkConstraint.getColumn())) .append(") REFERENCES ") .append(referencesString); if (fkConstraint.isDeleteCascade()) { buffer.append(" ON DELETE CASCADE"); } if ((database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } if (fkConstraint.isInitiallyDeferred()) { buffer.append(" INITIALLY DEFERRED"); } if (fkConstraint.isDeferrable()) { buffer.append(" DEFERRABLE"); } buffer.append(","); } for (UniqueConstraint uniqueConstraint : statement.getUniqueConstraints()) { if (uniqueConstraint.getConstraintName() != null && !constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(" UNIQUE ("); buffer.append(database.escapeColumnNameList(StringUtils.join(uniqueConstraint.getColumns(), ", "))); buffer.append(")"); if (uniqueConstraint.getConstraintName() != null && constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(","); } String sql = buffer.toString().replaceFirst(",\\s*$", "") + ")"; if (statement.getTablespace() != null && database.supportsTablespaces()) { if (database instanceof MSSQLDatabase || database instanceof SybaseASADatabase) { sql += " ON " + statement.getTablespace(); } else if (database instanceof DB2Database || database instanceof InformixDatabase) { sql += " IN " + statement.getTablespace(); } else { sql += " TABLESPACE " + statement.getTablespace(); } } return new Sql[] { new UnparsedSql(sql) }; } ValidationErrors validate(CreateTableStatement createTableStatement, Database database, SqlGeneratorChain sqlGeneratorChain); Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain); } |
@Test public void testAutoIncrementStartWithSybaseASADatabase() throws Exception { for (Database database : TestContext.getInstance().getAllDatabases()) { if (database instanceof SybaseASADatabase) { CreateTableStatement statement = new CreateTableStatement(SCHEMA_NAME, TABLE_NAME); statement.addColumn( COLUMN_NAME1, TypeConverterFactory.getInstance().findTypeConverter(database).getDataType("BIGINT", true), new AutoIncrementConstraint(COLUMN_NAME1, BigInteger.valueOf(2), null) ); Sql[] generatedSql = this.generatorUnderTest.generateSql(statement, database, null); assertEquals("CREATE TABLE \"SCHEMA_NAME\".\"TABLE_NAME\" (\"COLUMN1_NAME\" BIGINT DEFAULT AUTOINCREMENT NULL)", generatedSql[0].toSql()); } } } | public Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { StringBuffer buffer = new StringBuffer(); buffer.append("CREATE TABLE ").append(database.escapeTableName(statement.getSchemaName(), statement.getTableName())).append(" "); buffer.append("("); boolean isSinglePrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() == 1; boolean isPrimaryKeyAutoIncrement = false; Iterator<String> columnIterator = statement.getColumns().iterator(); while (columnIterator.hasNext()) { String column = columnIterator.next(); buffer.append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), column)); buffer.append(" ").append(statement.getColumnTypes().get(column)); AutoIncrementConstraint autoIncrementConstraint = null; for (AutoIncrementConstraint currentAutoIncrementConstraint : statement.getAutoIncrementConstraints()) { if (column.equals(currentAutoIncrementConstraint.getColumnName())) { autoIncrementConstraint = currentAutoIncrementConstraint; break; } } boolean isAutoIncrementColumn = autoIncrementConstraint != null; boolean isPrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().contains(column); isPrimaryKeyAutoIncrement = isPrimaryKeyAutoIncrement || isPrimaryKeyColumn && isAutoIncrementColumn; if ((database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyColumn && isAutoIncrementColumn) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } buffer.append(" PRIMARY KEY AUTOINCREMENT"); } if (statement.getDefaultValue(column) != null) { Object defaultValue = statement.getDefaultValue(column); if (database instanceof MSSQLDatabase) { buffer.append(" CONSTRAINT ").append(((MSSQLDatabase) database).generateDefaultConstraintName(statement.getTableName(), column)); } buffer.append(" DEFAULT "); buffer.append(statement.getColumnTypes().get(column).convertObjectToString(defaultValue, database)); } if (isAutoIncrementColumn && ! (database instanceof SQLiteDatabase)) { if (database.supportsAutoIncrement()) { String autoIncrementClause = database.getAutoIncrementClause(autoIncrementConstraint.getStartWith(), autoIncrementConstraint.getIncrementBy()); if (!"".equals(autoIncrementClause)) { buffer.append(" ").append(autoIncrementClause); } } else { LogFactory.getLogger().warning(database.getTypeName()+" does not support autoincrement columns as request for "+(database.escapeTableName(statement.getSchemaName(), statement.getTableName()))); } } if (statement.getNotNullColumns().contains(column)) { buffer.append(" NOT NULL"); } else { if (database instanceof SybaseDatabase || database instanceof SybaseASADatabase || database instanceof MySQLDatabase) { if (database instanceof MySQLDatabase && statement.getColumnTypes().get(column).getDataTypeName().equalsIgnoreCase("timestamp")) { } else { buffer.append(" NULL"); } } } if (database instanceof InformixDatabase && isSinglePrimaryKeyColumn) { buffer.append(" PRIMARY KEY"); } if (columnIterator.hasNext()) { buffer.append(", "); } } buffer.append(","); if (!( (database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyAutoIncrement) && !((database instanceof InformixDatabase) && isSinglePrimaryKeyColumn )) { if (statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() > 0) { if (!(database instanceof InformixDatabase)) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } } buffer.append(" PRIMARY KEY ("); buffer.append(database.escapeColumnNameList(StringUtils.join(statement.getPrimaryKeyConstraint().getColumns(), ", "))); buffer.append(")"); if (database instanceof OracleDatabase && statement.getPrimaryKeyConstraint().getTablespace() != null) { buffer.append(" USING INDEX TABLESPACE "); buffer.append(statement.getPrimaryKeyConstraint().getTablespace()); } buffer.append(","); } } for (ForeignKeyConstraint fkConstraint : statement.getForeignKeyConstraints()) { if (!(database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } String referencesString = fkConstraint.getReferences(); if (!referencesString.contains(".") && database.getDefaultSchemaName() != null) { referencesString = database.getDefaultSchemaName()+"."+referencesString; } buffer.append(" FOREIGN KEY (") .append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), fkConstraint.getColumn())) .append(") REFERENCES ") .append(referencesString); if (fkConstraint.isDeleteCascade()) { buffer.append(" ON DELETE CASCADE"); } if ((database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } if (fkConstraint.isInitiallyDeferred()) { buffer.append(" INITIALLY DEFERRED"); } if (fkConstraint.isDeferrable()) { buffer.append(" DEFERRABLE"); } buffer.append(","); } for (UniqueConstraint uniqueConstraint : statement.getUniqueConstraints()) { if (uniqueConstraint.getConstraintName() != null && !constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(" UNIQUE ("); buffer.append(database.escapeColumnNameList(StringUtils.join(uniqueConstraint.getColumns(), ", "))); buffer.append(")"); if (uniqueConstraint.getConstraintName() != null && constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(","); } String sql = buffer.toString().replaceFirst(",\\s*$", "") + ")"; if (statement.getTablespace() != null && database.supportsTablespaces()) { if (database instanceof MSSQLDatabase || database instanceof SybaseASADatabase) { sql += " ON " + statement.getTablespace(); } else if (database instanceof DB2Database || database instanceof InformixDatabase) { sql += " IN " + statement.getTablespace(); } else { sql += " TABLESPACE " + statement.getTablespace(); } } return new Sql[] { new UnparsedSql(sql) }; } | CreateTableGenerator extends AbstractSqlGenerator<CreateTableStatement> { public Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { StringBuffer buffer = new StringBuffer(); buffer.append("CREATE TABLE ").append(database.escapeTableName(statement.getSchemaName(), statement.getTableName())).append(" "); buffer.append("("); boolean isSinglePrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() == 1; boolean isPrimaryKeyAutoIncrement = false; Iterator<String> columnIterator = statement.getColumns().iterator(); while (columnIterator.hasNext()) { String column = columnIterator.next(); buffer.append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), column)); buffer.append(" ").append(statement.getColumnTypes().get(column)); AutoIncrementConstraint autoIncrementConstraint = null; for (AutoIncrementConstraint currentAutoIncrementConstraint : statement.getAutoIncrementConstraints()) { if (column.equals(currentAutoIncrementConstraint.getColumnName())) { autoIncrementConstraint = currentAutoIncrementConstraint; break; } } boolean isAutoIncrementColumn = autoIncrementConstraint != null; boolean isPrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().contains(column); isPrimaryKeyAutoIncrement = isPrimaryKeyAutoIncrement || isPrimaryKeyColumn && isAutoIncrementColumn; if ((database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyColumn && isAutoIncrementColumn) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } buffer.append(" PRIMARY KEY AUTOINCREMENT"); } if (statement.getDefaultValue(column) != null) { Object defaultValue = statement.getDefaultValue(column); if (database instanceof MSSQLDatabase) { buffer.append(" CONSTRAINT ").append(((MSSQLDatabase) database).generateDefaultConstraintName(statement.getTableName(), column)); } buffer.append(" DEFAULT "); buffer.append(statement.getColumnTypes().get(column).convertObjectToString(defaultValue, database)); } if (isAutoIncrementColumn && ! (database instanceof SQLiteDatabase)) { if (database.supportsAutoIncrement()) { String autoIncrementClause = database.getAutoIncrementClause(autoIncrementConstraint.getStartWith(), autoIncrementConstraint.getIncrementBy()); if (!"".equals(autoIncrementClause)) { buffer.append(" ").append(autoIncrementClause); } } else { LogFactory.getLogger().warning(database.getTypeName()+" does not support autoincrement columns as request for "+(database.escapeTableName(statement.getSchemaName(), statement.getTableName()))); } } if (statement.getNotNullColumns().contains(column)) { buffer.append(" NOT NULL"); } else { if (database instanceof SybaseDatabase || database instanceof SybaseASADatabase || database instanceof MySQLDatabase) { if (database instanceof MySQLDatabase && statement.getColumnTypes().get(column).getDataTypeName().equalsIgnoreCase("timestamp")) { } else { buffer.append(" NULL"); } } } if (database instanceof InformixDatabase && isSinglePrimaryKeyColumn) { buffer.append(" PRIMARY KEY"); } if (columnIterator.hasNext()) { buffer.append(", "); } } buffer.append(","); if (!( (database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyAutoIncrement) && !((database instanceof InformixDatabase) && isSinglePrimaryKeyColumn )) { if (statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() > 0) { if (!(database instanceof InformixDatabase)) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } } buffer.append(" PRIMARY KEY ("); buffer.append(database.escapeColumnNameList(StringUtils.join(statement.getPrimaryKeyConstraint().getColumns(), ", "))); buffer.append(")"); if (database instanceof OracleDatabase && statement.getPrimaryKeyConstraint().getTablespace() != null) { buffer.append(" USING INDEX TABLESPACE "); buffer.append(statement.getPrimaryKeyConstraint().getTablespace()); } buffer.append(","); } } for (ForeignKeyConstraint fkConstraint : statement.getForeignKeyConstraints()) { if (!(database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } String referencesString = fkConstraint.getReferences(); if (!referencesString.contains(".") && database.getDefaultSchemaName() != null) { referencesString = database.getDefaultSchemaName()+"."+referencesString; } buffer.append(" FOREIGN KEY (") .append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), fkConstraint.getColumn())) .append(") REFERENCES ") .append(referencesString); if (fkConstraint.isDeleteCascade()) { buffer.append(" ON DELETE CASCADE"); } if ((database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } if (fkConstraint.isInitiallyDeferred()) { buffer.append(" INITIALLY DEFERRED"); } if (fkConstraint.isDeferrable()) { buffer.append(" DEFERRABLE"); } buffer.append(","); } for (UniqueConstraint uniqueConstraint : statement.getUniqueConstraints()) { if (uniqueConstraint.getConstraintName() != null && !constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(" UNIQUE ("); buffer.append(database.escapeColumnNameList(StringUtils.join(uniqueConstraint.getColumns(), ", "))); buffer.append(")"); if (uniqueConstraint.getConstraintName() != null && constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(","); } String sql = buffer.toString().replaceFirst(",\\s*$", "") + ")"; if (statement.getTablespace() != null && database.supportsTablespaces()) { if (database instanceof MSSQLDatabase || database instanceof SybaseASADatabase) { sql += " ON " + statement.getTablespace(); } else if (database instanceof DB2Database || database instanceof InformixDatabase) { sql += " IN " + statement.getTablespace(); } else { sql += " TABLESPACE " + statement.getTablespace(); } } return new Sql[] { new UnparsedSql(sql) }; } } | CreateTableGenerator extends AbstractSqlGenerator<CreateTableStatement> { public Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { StringBuffer buffer = new StringBuffer(); buffer.append("CREATE TABLE ").append(database.escapeTableName(statement.getSchemaName(), statement.getTableName())).append(" "); buffer.append("("); boolean isSinglePrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() == 1; boolean isPrimaryKeyAutoIncrement = false; Iterator<String> columnIterator = statement.getColumns().iterator(); while (columnIterator.hasNext()) { String column = columnIterator.next(); buffer.append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), column)); buffer.append(" ").append(statement.getColumnTypes().get(column)); AutoIncrementConstraint autoIncrementConstraint = null; for (AutoIncrementConstraint currentAutoIncrementConstraint : statement.getAutoIncrementConstraints()) { if (column.equals(currentAutoIncrementConstraint.getColumnName())) { autoIncrementConstraint = currentAutoIncrementConstraint; break; } } boolean isAutoIncrementColumn = autoIncrementConstraint != null; boolean isPrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().contains(column); isPrimaryKeyAutoIncrement = isPrimaryKeyAutoIncrement || isPrimaryKeyColumn && isAutoIncrementColumn; if ((database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyColumn && isAutoIncrementColumn) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } buffer.append(" PRIMARY KEY AUTOINCREMENT"); } if (statement.getDefaultValue(column) != null) { Object defaultValue = statement.getDefaultValue(column); if (database instanceof MSSQLDatabase) { buffer.append(" CONSTRAINT ").append(((MSSQLDatabase) database).generateDefaultConstraintName(statement.getTableName(), column)); } buffer.append(" DEFAULT "); buffer.append(statement.getColumnTypes().get(column).convertObjectToString(defaultValue, database)); } if (isAutoIncrementColumn && ! (database instanceof SQLiteDatabase)) { if (database.supportsAutoIncrement()) { String autoIncrementClause = database.getAutoIncrementClause(autoIncrementConstraint.getStartWith(), autoIncrementConstraint.getIncrementBy()); if (!"".equals(autoIncrementClause)) { buffer.append(" ").append(autoIncrementClause); } } else { LogFactory.getLogger().warning(database.getTypeName()+" does not support autoincrement columns as request for "+(database.escapeTableName(statement.getSchemaName(), statement.getTableName()))); } } if (statement.getNotNullColumns().contains(column)) { buffer.append(" NOT NULL"); } else { if (database instanceof SybaseDatabase || database instanceof SybaseASADatabase || database instanceof MySQLDatabase) { if (database instanceof MySQLDatabase && statement.getColumnTypes().get(column).getDataTypeName().equalsIgnoreCase("timestamp")) { } else { buffer.append(" NULL"); } } } if (database instanceof InformixDatabase && isSinglePrimaryKeyColumn) { buffer.append(" PRIMARY KEY"); } if (columnIterator.hasNext()) { buffer.append(", "); } } buffer.append(","); if (!( (database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyAutoIncrement) && !((database instanceof InformixDatabase) && isSinglePrimaryKeyColumn )) { if (statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() > 0) { if (!(database instanceof InformixDatabase)) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } } buffer.append(" PRIMARY KEY ("); buffer.append(database.escapeColumnNameList(StringUtils.join(statement.getPrimaryKeyConstraint().getColumns(), ", "))); buffer.append(")"); if (database instanceof OracleDatabase && statement.getPrimaryKeyConstraint().getTablespace() != null) { buffer.append(" USING INDEX TABLESPACE "); buffer.append(statement.getPrimaryKeyConstraint().getTablespace()); } buffer.append(","); } } for (ForeignKeyConstraint fkConstraint : statement.getForeignKeyConstraints()) { if (!(database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } String referencesString = fkConstraint.getReferences(); if (!referencesString.contains(".") && database.getDefaultSchemaName() != null) { referencesString = database.getDefaultSchemaName()+"."+referencesString; } buffer.append(" FOREIGN KEY (") .append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), fkConstraint.getColumn())) .append(") REFERENCES ") .append(referencesString); if (fkConstraint.isDeleteCascade()) { buffer.append(" ON DELETE CASCADE"); } if ((database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } if (fkConstraint.isInitiallyDeferred()) { buffer.append(" INITIALLY DEFERRED"); } if (fkConstraint.isDeferrable()) { buffer.append(" DEFERRABLE"); } buffer.append(","); } for (UniqueConstraint uniqueConstraint : statement.getUniqueConstraints()) { if (uniqueConstraint.getConstraintName() != null && !constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(" UNIQUE ("); buffer.append(database.escapeColumnNameList(StringUtils.join(uniqueConstraint.getColumns(), ", "))); buffer.append(")"); if (uniqueConstraint.getConstraintName() != null && constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(","); } String sql = buffer.toString().replaceFirst(",\\s*$", "") + ")"; if (statement.getTablespace() != null && database.supportsTablespaces()) { if (database instanceof MSSQLDatabase || database instanceof SybaseASADatabase) { sql += " ON " + statement.getTablespace(); } else if (database instanceof DB2Database || database instanceof InformixDatabase) { sql += " IN " + statement.getTablespace(); } else { sql += " TABLESPACE " + statement.getTablespace(); } } return new Sql[] { new UnparsedSql(sql) }; } } | CreateTableGenerator extends AbstractSqlGenerator<CreateTableStatement> { public Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { StringBuffer buffer = new StringBuffer(); buffer.append("CREATE TABLE ").append(database.escapeTableName(statement.getSchemaName(), statement.getTableName())).append(" "); buffer.append("("); boolean isSinglePrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() == 1; boolean isPrimaryKeyAutoIncrement = false; Iterator<String> columnIterator = statement.getColumns().iterator(); while (columnIterator.hasNext()) { String column = columnIterator.next(); buffer.append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), column)); buffer.append(" ").append(statement.getColumnTypes().get(column)); AutoIncrementConstraint autoIncrementConstraint = null; for (AutoIncrementConstraint currentAutoIncrementConstraint : statement.getAutoIncrementConstraints()) { if (column.equals(currentAutoIncrementConstraint.getColumnName())) { autoIncrementConstraint = currentAutoIncrementConstraint; break; } } boolean isAutoIncrementColumn = autoIncrementConstraint != null; boolean isPrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().contains(column); isPrimaryKeyAutoIncrement = isPrimaryKeyAutoIncrement || isPrimaryKeyColumn && isAutoIncrementColumn; if ((database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyColumn && isAutoIncrementColumn) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } buffer.append(" PRIMARY KEY AUTOINCREMENT"); } if (statement.getDefaultValue(column) != null) { Object defaultValue = statement.getDefaultValue(column); if (database instanceof MSSQLDatabase) { buffer.append(" CONSTRAINT ").append(((MSSQLDatabase) database).generateDefaultConstraintName(statement.getTableName(), column)); } buffer.append(" DEFAULT "); buffer.append(statement.getColumnTypes().get(column).convertObjectToString(defaultValue, database)); } if (isAutoIncrementColumn && ! (database instanceof SQLiteDatabase)) { if (database.supportsAutoIncrement()) { String autoIncrementClause = database.getAutoIncrementClause(autoIncrementConstraint.getStartWith(), autoIncrementConstraint.getIncrementBy()); if (!"".equals(autoIncrementClause)) { buffer.append(" ").append(autoIncrementClause); } } else { LogFactory.getLogger().warning(database.getTypeName()+" does not support autoincrement columns as request for "+(database.escapeTableName(statement.getSchemaName(), statement.getTableName()))); } } if (statement.getNotNullColumns().contains(column)) { buffer.append(" NOT NULL"); } else { if (database instanceof SybaseDatabase || database instanceof SybaseASADatabase || database instanceof MySQLDatabase) { if (database instanceof MySQLDatabase && statement.getColumnTypes().get(column).getDataTypeName().equalsIgnoreCase("timestamp")) { } else { buffer.append(" NULL"); } } } if (database instanceof InformixDatabase && isSinglePrimaryKeyColumn) { buffer.append(" PRIMARY KEY"); } if (columnIterator.hasNext()) { buffer.append(", "); } } buffer.append(","); if (!( (database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyAutoIncrement) && !((database instanceof InformixDatabase) && isSinglePrimaryKeyColumn )) { if (statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() > 0) { if (!(database instanceof InformixDatabase)) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } } buffer.append(" PRIMARY KEY ("); buffer.append(database.escapeColumnNameList(StringUtils.join(statement.getPrimaryKeyConstraint().getColumns(), ", "))); buffer.append(")"); if (database instanceof OracleDatabase && statement.getPrimaryKeyConstraint().getTablespace() != null) { buffer.append(" USING INDEX TABLESPACE "); buffer.append(statement.getPrimaryKeyConstraint().getTablespace()); } buffer.append(","); } } for (ForeignKeyConstraint fkConstraint : statement.getForeignKeyConstraints()) { if (!(database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } String referencesString = fkConstraint.getReferences(); if (!referencesString.contains(".") && database.getDefaultSchemaName() != null) { referencesString = database.getDefaultSchemaName()+"."+referencesString; } buffer.append(" FOREIGN KEY (") .append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), fkConstraint.getColumn())) .append(") REFERENCES ") .append(referencesString); if (fkConstraint.isDeleteCascade()) { buffer.append(" ON DELETE CASCADE"); } if ((database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } if (fkConstraint.isInitiallyDeferred()) { buffer.append(" INITIALLY DEFERRED"); } if (fkConstraint.isDeferrable()) { buffer.append(" DEFERRABLE"); } buffer.append(","); } for (UniqueConstraint uniqueConstraint : statement.getUniqueConstraints()) { if (uniqueConstraint.getConstraintName() != null && !constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(" UNIQUE ("); buffer.append(database.escapeColumnNameList(StringUtils.join(uniqueConstraint.getColumns(), ", "))); buffer.append(")"); if (uniqueConstraint.getConstraintName() != null && constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(","); } String sql = buffer.toString().replaceFirst(",\\s*$", "") + ")"; if (statement.getTablespace() != null && database.supportsTablespaces()) { if (database instanceof MSSQLDatabase || database instanceof SybaseASADatabase) { sql += " ON " + statement.getTablespace(); } else if (database instanceof DB2Database || database instanceof InformixDatabase) { sql += " IN " + statement.getTablespace(); } else { sql += " TABLESPACE " + statement.getTablespace(); } } return new Sql[] { new UnparsedSql(sql) }; } ValidationErrors validate(CreateTableStatement createTableStatement, Database database, SqlGeneratorChain sqlGeneratorChain); Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain); } | CreateTableGenerator extends AbstractSqlGenerator<CreateTableStatement> { public Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { StringBuffer buffer = new StringBuffer(); buffer.append("CREATE TABLE ").append(database.escapeTableName(statement.getSchemaName(), statement.getTableName())).append(" "); buffer.append("("); boolean isSinglePrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() == 1; boolean isPrimaryKeyAutoIncrement = false; Iterator<String> columnIterator = statement.getColumns().iterator(); while (columnIterator.hasNext()) { String column = columnIterator.next(); buffer.append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), column)); buffer.append(" ").append(statement.getColumnTypes().get(column)); AutoIncrementConstraint autoIncrementConstraint = null; for (AutoIncrementConstraint currentAutoIncrementConstraint : statement.getAutoIncrementConstraints()) { if (column.equals(currentAutoIncrementConstraint.getColumnName())) { autoIncrementConstraint = currentAutoIncrementConstraint; break; } } boolean isAutoIncrementColumn = autoIncrementConstraint != null; boolean isPrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().contains(column); isPrimaryKeyAutoIncrement = isPrimaryKeyAutoIncrement || isPrimaryKeyColumn && isAutoIncrementColumn; if ((database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyColumn && isAutoIncrementColumn) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } buffer.append(" PRIMARY KEY AUTOINCREMENT"); } if (statement.getDefaultValue(column) != null) { Object defaultValue = statement.getDefaultValue(column); if (database instanceof MSSQLDatabase) { buffer.append(" CONSTRAINT ").append(((MSSQLDatabase) database).generateDefaultConstraintName(statement.getTableName(), column)); } buffer.append(" DEFAULT "); buffer.append(statement.getColumnTypes().get(column).convertObjectToString(defaultValue, database)); } if (isAutoIncrementColumn && ! (database instanceof SQLiteDatabase)) { if (database.supportsAutoIncrement()) { String autoIncrementClause = database.getAutoIncrementClause(autoIncrementConstraint.getStartWith(), autoIncrementConstraint.getIncrementBy()); if (!"".equals(autoIncrementClause)) { buffer.append(" ").append(autoIncrementClause); } } else { LogFactory.getLogger().warning(database.getTypeName()+" does not support autoincrement columns as request for "+(database.escapeTableName(statement.getSchemaName(), statement.getTableName()))); } } if (statement.getNotNullColumns().contains(column)) { buffer.append(" NOT NULL"); } else { if (database instanceof SybaseDatabase || database instanceof SybaseASADatabase || database instanceof MySQLDatabase) { if (database instanceof MySQLDatabase && statement.getColumnTypes().get(column).getDataTypeName().equalsIgnoreCase("timestamp")) { } else { buffer.append(" NULL"); } } } if (database instanceof InformixDatabase && isSinglePrimaryKeyColumn) { buffer.append(" PRIMARY KEY"); } if (columnIterator.hasNext()) { buffer.append(", "); } } buffer.append(","); if (!( (database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyAutoIncrement) && !((database instanceof InformixDatabase) && isSinglePrimaryKeyColumn )) { if (statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() > 0) { if (!(database instanceof InformixDatabase)) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } } buffer.append(" PRIMARY KEY ("); buffer.append(database.escapeColumnNameList(StringUtils.join(statement.getPrimaryKeyConstraint().getColumns(), ", "))); buffer.append(")"); if (database instanceof OracleDatabase && statement.getPrimaryKeyConstraint().getTablespace() != null) { buffer.append(" USING INDEX TABLESPACE "); buffer.append(statement.getPrimaryKeyConstraint().getTablespace()); } buffer.append(","); } } for (ForeignKeyConstraint fkConstraint : statement.getForeignKeyConstraints()) { if (!(database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } String referencesString = fkConstraint.getReferences(); if (!referencesString.contains(".") && database.getDefaultSchemaName() != null) { referencesString = database.getDefaultSchemaName()+"."+referencesString; } buffer.append(" FOREIGN KEY (") .append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), fkConstraint.getColumn())) .append(") REFERENCES ") .append(referencesString); if (fkConstraint.isDeleteCascade()) { buffer.append(" ON DELETE CASCADE"); } if ((database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } if (fkConstraint.isInitiallyDeferred()) { buffer.append(" INITIALLY DEFERRED"); } if (fkConstraint.isDeferrable()) { buffer.append(" DEFERRABLE"); } buffer.append(","); } for (UniqueConstraint uniqueConstraint : statement.getUniqueConstraints()) { if (uniqueConstraint.getConstraintName() != null && !constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(" UNIQUE ("); buffer.append(database.escapeColumnNameList(StringUtils.join(uniqueConstraint.getColumns(), ", "))); buffer.append(")"); if (uniqueConstraint.getConstraintName() != null && constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(","); } String sql = buffer.toString().replaceFirst(",\\s*$", "") + ")"; if (statement.getTablespace() != null && database.supportsTablespaces()) { if (database instanceof MSSQLDatabase || database instanceof SybaseASADatabase) { sql += " ON " + statement.getTablespace(); } else if (database instanceof DB2Database || database instanceof InformixDatabase) { sql += " IN " + statement.getTablespace(); } else { sql += " TABLESPACE " + statement.getTablespace(); } } return new Sql[] { new UnparsedSql(sql) }; } ValidationErrors validate(CreateTableStatement createTableStatement, Database database, SqlGeneratorChain sqlGeneratorChain); Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain); } |
@Test public void testAutoIncrementStartWithIncrementBySybaseASADatabase() throws Exception { for (Database database : TestContext.getInstance().getAllDatabases()) { if (database instanceof SybaseASADatabase) { CreateTableStatement statement = new CreateTableStatement(SCHEMA_NAME, TABLE_NAME); statement.addColumn( COLUMN_NAME1, TypeConverterFactory.getInstance().findTypeConverter(database).getDataType("BIGINT", true), new AutoIncrementConstraint(COLUMN_NAME1, BigInteger.valueOf(2), BigInteger.TEN) ); Sql[] generatedSql = this.generatorUnderTest.generateSql(statement, database, null); assertEquals("CREATE TABLE \"SCHEMA_NAME\".\"TABLE_NAME\" (\"COLUMN1_NAME\" BIGINT DEFAULT AUTOINCREMENT NULL)", generatedSql[0].toSql()); } } } | public Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { StringBuffer buffer = new StringBuffer(); buffer.append("CREATE TABLE ").append(database.escapeTableName(statement.getSchemaName(), statement.getTableName())).append(" "); buffer.append("("); boolean isSinglePrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() == 1; boolean isPrimaryKeyAutoIncrement = false; Iterator<String> columnIterator = statement.getColumns().iterator(); while (columnIterator.hasNext()) { String column = columnIterator.next(); buffer.append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), column)); buffer.append(" ").append(statement.getColumnTypes().get(column)); AutoIncrementConstraint autoIncrementConstraint = null; for (AutoIncrementConstraint currentAutoIncrementConstraint : statement.getAutoIncrementConstraints()) { if (column.equals(currentAutoIncrementConstraint.getColumnName())) { autoIncrementConstraint = currentAutoIncrementConstraint; break; } } boolean isAutoIncrementColumn = autoIncrementConstraint != null; boolean isPrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().contains(column); isPrimaryKeyAutoIncrement = isPrimaryKeyAutoIncrement || isPrimaryKeyColumn && isAutoIncrementColumn; if ((database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyColumn && isAutoIncrementColumn) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } buffer.append(" PRIMARY KEY AUTOINCREMENT"); } if (statement.getDefaultValue(column) != null) { Object defaultValue = statement.getDefaultValue(column); if (database instanceof MSSQLDatabase) { buffer.append(" CONSTRAINT ").append(((MSSQLDatabase) database).generateDefaultConstraintName(statement.getTableName(), column)); } buffer.append(" DEFAULT "); buffer.append(statement.getColumnTypes().get(column).convertObjectToString(defaultValue, database)); } if (isAutoIncrementColumn && ! (database instanceof SQLiteDatabase)) { if (database.supportsAutoIncrement()) { String autoIncrementClause = database.getAutoIncrementClause(autoIncrementConstraint.getStartWith(), autoIncrementConstraint.getIncrementBy()); if (!"".equals(autoIncrementClause)) { buffer.append(" ").append(autoIncrementClause); } } else { LogFactory.getLogger().warning(database.getTypeName()+" does not support autoincrement columns as request for "+(database.escapeTableName(statement.getSchemaName(), statement.getTableName()))); } } if (statement.getNotNullColumns().contains(column)) { buffer.append(" NOT NULL"); } else { if (database instanceof SybaseDatabase || database instanceof SybaseASADatabase || database instanceof MySQLDatabase) { if (database instanceof MySQLDatabase && statement.getColumnTypes().get(column).getDataTypeName().equalsIgnoreCase("timestamp")) { } else { buffer.append(" NULL"); } } } if (database instanceof InformixDatabase && isSinglePrimaryKeyColumn) { buffer.append(" PRIMARY KEY"); } if (columnIterator.hasNext()) { buffer.append(", "); } } buffer.append(","); if (!( (database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyAutoIncrement) && !((database instanceof InformixDatabase) && isSinglePrimaryKeyColumn )) { if (statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() > 0) { if (!(database instanceof InformixDatabase)) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } } buffer.append(" PRIMARY KEY ("); buffer.append(database.escapeColumnNameList(StringUtils.join(statement.getPrimaryKeyConstraint().getColumns(), ", "))); buffer.append(")"); if (database instanceof OracleDatabase && statement.getPrimaryKeyConstraint().getTablespace() != null) { buffer.append(" USING INDEX TABLESPACE "); buffer.append(statement.getPrimaryKeyConstraint().getTablespace()); } buffer.append(","); } } for (ForeignKeyConstraint fkConstraint : statement.getForeignKeyConstraints()) { if (!(database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } String referencesString = fkConstraint.getReferences(); if (!referencesString.contains(".") && database.getDefaultSchemaName() != null) { referencesString = database.getDefaultSchemaName()+"."+referencesString; } buffer.append(" FOREIGN KEY (") .append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), fkConstraint.getColumn())) .append(") REFERENCES ") .append(referencesString); if (fkConstraint.isDeleteCascade()) { buffer.append(" ON DELETE CASCADE"); } if ((database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } if (fkConstraint.isInitiallyDeferred()) { buffer.append(" INITIALLY DEFERRED"); } if (fkConstraint.isDeferrable()) { buffer.append(" DEFERRABLE"); } buffer.append(","); } for (UniqueConstraint uniqueConstraint : statement.getUniqueConstraints()) { if (uniqueConstraint.getConstraintName() != null && !constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(" UNIQUE ("); buffer.append(database.escapeColumnNameList(StringUtils.join(uniqueConstraint.getColumns(), ", "))); buffer.append(")"); if (uniqueConstraint.getConstraintName() != null && constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(","); } String sql = buffer.toString().replaceFirst(",\\s*$", "") + ")"; if (statement.getTablespace() != null && database.supportsTablespaces()) { if (database instanceof MSSQLDatabase || database instanceof SybaseASADatabase) { sql += " ON " + statement.getTablespace(); } else if (database instanceof DB2Database || database instanceof InformixDatabase) { sql += " IN " + statement.getTablespace(); } else { sql += " TABLESPACE " + statement.getTablespace(); } } return new Sql[] { new UnparsedSql(sql) }; } | CreateTableGenerator extends AbstractSqlGenerator<CreateTableStatement> { public Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { StringBuffer buffer = new StringBuffer(); buffer.append("CREATE TABLE ").append(database.escapeTableName(statement.getSchemaName(), statement.getTableName())).append(" "); buffer.append("("); boolean isSinglePrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() == 1; boolean isPrimaryKeyAutoIncrement = false; Iterator<String> columnIterator = statement.getColumns().iterator(); while (columnIterator.hasNext()) { String column = columnIterator.next(); buffer.append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), column)); buffer.append(" ").append(statement.getColumnTypes().get(column)); AutoIncrementConstraint autoIncrementConstraint = null; for (AutoIncrementConstraint currentAutoIncrementConstraint : statement.getAutoIncrementConstraints()) { if (column.equals(currentAutoIncrementConstraint.getColumnName())) { autoIncrementConstraint = currentAutoIncrementConstraint; break; } } boolean isAutoIncrementColumn = autoIncrementConstraint != null; boolean isPrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().contains(column); isPrimaryKeyAutoIncrement = isPrimaryKeyAutoIncrement || isPrimaryKeyColumn && isAutoIncrementColumn; if ((database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyColumn && isAutoIncrementColumn) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } buffer.append(" PRIMARY KEY AUTOINCREMENT"); } if (statement.getDefaultValue(column) != null) { Object defaultValue = statement.getDefaultValue(column); if (database instanceof MSSQLDatabase) { buffer.append(" CONSTRAINT ").append(((MSSQLDatabase) database).generateDefaultConstraintName(statement.getTableName(), column)); } buffer.append(" DEFAULT "); buffer.append(statement.getColumnTypes().get(column).convertObjectToString(defaultValue, database)); } if (isAutoIncrementColumn && ! (database instanceof SQLiteDatabase)) { if (database.supportsAutoIncrement()) { String autoIncrementClause = database.getAutoIncrementClause(autoIncrementConstraint.getStartWith(), autoIncrementConstraint.getIncrementBy()); if (!"".equals(autoIncrementClause)) { buffer.append(" ").append(autoIncrementClause); } } else { LogFactory.getLogger().warning(database.getTypeName()+" does not support autoincrement columns as request for "+(database.escapeTableName(statement.getSchemaName(), statement.getTableName()))); } } if (statement.getNotNullColumns().contains(column)) { buffer.append(" NOT NULL"); } else { if (database instanceof SybaseDatabase || database instanceof SybaseASADatabase || database instanceof MySQLDatabase) { if (database instanceof MySQLDatabase && statement.getColumnTypes().get(column).getDataTypeName().equalsIgnoreCase("timestamp")) { } else { buffer.append(" NULL"); } } } if (database instanceof InformixDatabase && isSinglePrimaryKeyColumn) { buffer.append(" PRIMARY KEY"); } if (columnIterator.hasNext()) { buffer.append(", "); } } buffer.append(","); if (!( (database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyAutoIncrement) && !((database instanceof InformixDatabase) && isSinglePrimaryKeyColumn )) { if (statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() > 0) { if (!(database instanceof InformixDatabase)) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } } buffer.append(" PRIMARY KEY ("); buffer.append(database.escapeColumnNameList(StringUtils.join(statement.getPrimaryKeyConstraint().getColumns(), ", "))); buffer.append(")"); if (database instanceof OracleDatabase && statement.getPrimaryKeyConstraint().getTablespace() != null) { buffer.append(" USING INDEX TABLESPACE "); buffer.append(statement.getPrimaryKeyConstraint().getTablespace()); } buffer.append(","); } } for (ForeignKeyConstraint fkConstraint : statement.getForeignKeyConstraints()) { if (!(database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } String referencesString = fkConstraint.getReferences(); if (!referencesString.contains(".") && database.getDefaultSchemaName() != null) { referencesString = database.getDefaultSchemaName()+"."+referencesString; } buffer.append(" FOREIGN KEY (") .append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), fkConstraint.getColumn())) .append(") REFERENCES ") .append(referencesString); if (fkConstraint.isDeleteCascade()) { buffer.append(" ON DELETE CASCADE"); } if ((database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } if (fkConstraint.isInitiallyDeferred()) { buffer.append(" INITIALLY DEFERRED"); } if (fkConstraint.isDeferrable()) { buffer.append(" DEFERRABLE"); } buffer.append(","); } for (UniqueConstraint uniqueConstraint : statement.getUniqueConstraints()) { if (uniqueConstraint.getConstraintName() != null && !constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(" UNIQUE ("); buffer.append(database.escapeColumnNameList(StringUtils.join(uniqueConstraint.getColumns(), ", "))); buffer.append(")"); if (uniqueConstraint.getConstraintName() != null && constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(","); } String sql = buffer.toString().replaceFirst(",\\s*$", "") + ")"; if (statement.getTablespace() != null && database.supportsTablespaces()) { if (database instanceof MSSQLDatabase || database instanceof SybaseASADatabase) { sql += " ON " + statement.getTablespace(); } else if (database instanceof DB2Database || database instanceof InformixDatabase) { sql += " IN " + statement.getTablespace(); } else { sql += " TABLESPACE " + statement.getTablespace(); } } return new Sql[] { new UnparsedSql(sql) }; } } | CreateTableGenerator extends AbstractSqlGenerator<CreateTableStatement> { public Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { StringBuffer buffer = new StringBuffer(); buffer.append("CREATE TABLE ").append(database.escapeTableName(statement.getSchemaName(), statement.getTableName())).append(" "); buffer.append("("); boolean isSinglePrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() == 1; boolean isPrimaryKeyAutoIncrement = false; Iterator<String> columnIterator = statement.getColumns().iterator(); while (columnIterator.hasNext()) { String column = columnIterator.next(); buffer.append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), column)); buffer.append(" ").append(statement.getColumnTypes().get(column)); AutoIncrementConstraint autoIncrementConstraint = null; for (AutoIncrementConstraint currentAutoIncrementConstraint : statement.getAutoIncrementConstraints()) { if (column.equals(currentAutoIncrementConstraint.getColumnName())) { autoIncrementConstraint = currentAutoIncrementConstraint; break; } } boolean isAutoIncrementColumn = autoIncrementConstraint != null; boolean isPrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().contains(column); isPrimaryKeyAutoIncrement = isPrimaryKeyAutoIncrement || isPrimaryKeyColumn && isAutoIncrementColumn; if ((database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyColumn && isAutoIncrementColumn) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } buffer.append(" PRIMARY KEY AUTOINCREMENT"); } if (statement.getDefaultValue(column) != null) { Object defaultValue = statement.getDefaultValue(column); if (database instanceof MSSQLDatabase) { buffer.append(" CONSTRAINT ").append(((MSSQLDatabase) database).generateDefaultConstraintName(statement.getTableName(), column)); } buffer.append(" DEFAULT "); buffer.append(statement.getColumnTypes().get(column).convertObjectToString(defaultValue, database)); } if (isAutoIncrementColumn && ! (database instanceof SQLiteDatabase)) { if (database.supportsAutoIncrement()) { String autoIncrementClause = database.getAutoIncrementClause(autoIncrementConstraint.getStartWith(), autoIncrementConstraint.getIncrementBy()); if (!"".equals(autoIncrementClause)) { buffer.append(" ").append(autoIncrementClause); } } else { LogFactory.getLogger().warning(database.getTypeName()+" does not support autoincrement columns as request for "+(database.escapeTableName(statement.getSchemaName(), statement.getTableName()))); } } if (statement.getNotNullColumns().contains(column)) { buffer.append(" NOT NULL"); } else { if (database instanceof SybaseDatabase || database instanceof SybaseASADatabase || database instanceof MySQLDatabase) { if (database instanceof MySQLDatabase && statement.getColumnTypes().get(column).getDataTypeName().equalsIgnoreCase("timestamp")) { } else { buffer.append(" NULL"); } } } if (database instanceof InformixDatabase && isSinglePrimaryKeyColumn) { buffer.append(" PRIMARY KEY"); } if (columnIterator.hasNext()) { buffer.append(", "); } } buffer.append(","); if (!( (database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyAutoIncrement) && !((database instanceof InformixDatabase) && isSinglePrimaryKeyColumn )) { if (statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() > 0) { if (!(database instanceof InformixDatabase)) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } } buffer.append(" PRIMARY KEY ("); buffer.append(database.escapeColumnNameList(StringUtils.join(statement.getPrimaryKeyConstraint().getColumns(), ", "))); buffer.append(")"); if (database instanceof OracleDatabase && statement.getPrimaryKeyConstraint().getTablespace() != null) { buffer.append(" USING INDEX TABLESPACE "); buffer.append(statement.getPrimaryKeyConstraint().getTablespace()); } buffer.append(","); } } for (ForeignKeyConstraint fkConstraint : statement.getForeignKeyConstraints()) { if (!(database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } String referencesString = fkConstraint.getReferences(); if (!referencesString.contains(".") && database.getDefaultSchemaName() != null) { referencesString = database.getDefaultSchemaName()+"."+referencesString; } buffer.append(" FOREIGN KEY (") .append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), fkConstraint.getColumn())) .append(") REFERENCES ") .append(referencesString); if (fkConstraint.isDeleteCascade()) { buffer.append(" ON DELETE CASCADE"); } if ((database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } if (fkConstraint.isInitiallyDeferred()) { buffer.append(" INITIALLY DEFERRED"); } if (fkConstraint.isDeferrable()) { buffer.append(" DEFERRABLE"); } buffer.append(","); } for (UniqueConstraint uniqueConstraint : statement.getUniqueConstraints()) { if (uniqueConstraint.getConstraintName() != null && !constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(" UNIQUE ("); buffer.append(database.escapeColumnNameList(StringUtils.join(uniqueConstraint.getColumns(), ", "))); buffer.append(")"); if (uniqueConstraint.getConstraintName() != null && constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(","); } String sql = buffer.toString().replaceFirst(",\\s*$", "") + ")"; if (statement.getTablespace() != null && database.supportsTablespaces()) { if (database instanceof MSSQLDatabase || database instanceof SybaseASADatabase) { sql += " ON " + statement.getTablespace(); } else if (database instanceof DB2Database || database instanceof InformixDatabase) { sql += " IN " + statement.getTablespace(); } else { sql += " TABLESPACE " + statement.getTablespace(); } } return new Sql[] { new UnparsedSql(sql) }; } } | CreateTableGenerator extends AbstractSqlGenerator<CreateTableStatement> { public Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { StringBuffer buffer = new StringBuffer(); buffer.append("CREATE TABLE ").append(database.escapeTableName(statement.getSchemaName(), statement.getTableName())).append(" "); buffer.append("("); boolean isSinglePrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() == 1; boolean isPrimaryKeyAutoIncrement = false; Iterator<String> columnIterator = statement.getColumns().iterator(); while (columnIterator.hasNext()) { String column = columnIterator.next(); buffer.append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), column)); buffer.append(" ").append(statement.getColumnTypes().get(column)); AutoIncrementConstraint autoIncrementConstraint = null; for (AutoIncrementConstraint currentAutoIncrementConstraint : statement.getAutoIncrementConstraints()) { if (column.equals(currentAutoIncrementConstraint.getColumnName())) { autoIncrementConstraint = currentAutoIncrementConstraint; break; } } boolean isAutoIncrementColumn = autoIncrementConstraint != null; boolean isPrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().contains(column); isPrimaryKeyAutoIncrement = isPrimaryKeyAutoIncrement || isPrimaryKeyColumn && isAutoIncrementColumn; if ((database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyColumn && isAutoIncrementColumn) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } buffer.append(" PRIMARY KEY AUTOINCREMENT"); } if (statement.getDefaultValue(column) != null) { Object defaultValue = statement.getDefaultValue(column); if (database instanceof MSSQLDatabase) { buffer.append(" CONSTRAINT ").append(((MSSQLDatabase) database).generateDefaultConstraintName(statement.getTableName(), column)); } buffer.append(" DEFAULT "); buffer.append(statement.getColumnTypes().get(column).convertObjectToString(defaultValue, database)); } if (isAutoIncrementColumn && ! (database instanceof SQLiteDatabase)) { if (database.supportsAutoIncrement()) { String autoIncrementClause = database.getAutoIncrementClause(autoIncrementConstraint.getStartWith(), autoIncrementConstraint.getIncrementBy()); if (!"".equals(autoIncrementClause)) { buffer.append(" ").append(autoIncrementClause); } } else { LogFactory.getLogger().warning(database.getTypeName()+" does not support autoincrement columns as request for "+(database.escapeTableName(statement.getSchemaName(), statement.getTableName()))); } } if (statement.getNotNullColumns().contains(column)) { buffer.append(" NOT NULL"); } else { if (database instanceof SybaseDatabase || database instanceof SybaseASADatabase || database instanceof MySQLDatabase) { if (database instanceof MySQLDatabase && statement.getColumnTypes().get(column).getDataTypeName().equalsIgnoreCase("timestamp")) { } else { buffer.append(" NULL"); } } } if (database instanceof InformixDatabase && isSinglePrimaryKeyColumn) { buffer.append(" PRIMARY KEY"); } if (columnIterator.hasNext()) { buffer.append(", "); } } buffer.append(","); if (!( (database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyAutoIncrement) && !((database instanceof InformixDatabase) && isSinglePrimaryKeyColumn )) { if (statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() > 0) { if (!(database instanceof InformixDatabase)) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } } buffer.append(" PRIMARY KEY ("); buffer.append(database.escapeColumnNameList(StringUtils.join(statement.getPrimaryKeyConstraint().getColumns(), ", "))); buffer.append(")"); if (database instanceof OracleDatabase && statement.getPrimaryKeyConstraint().getTablespace() != null) { buffer.append(" USING INDEX TABLESPACE "); buffer.append(statement.getPrimaryKeyConstraint().getTablespace()); } buffer.append(","); } } for (ForeignKeyConstraint fkConstraint : statement.getForeignKeyConstraints()) { if (!(database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } String referencesString = fkConstraint.getReferences(); if (!referencesString.contains(".") && database.getDefaultSchemaName() != null) { referencesString = database.getDefaultSchemaName()+"."+referencesString; } buffer.append(" FOREIGN KEY (") .append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), fkConstraint.getColumn())) .append(") REFERENCES ") .append(referencesString); if (fkConstraint.isDeleteCascade()) { buffer.append(" ON DELETE CASCADE"); } if ((database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } if (fkConstraint.isInitiallyDeferred()) { buffer.append(" INITIALLY DEFERRED"); } if (fkConstraint.isDeferrable()) { buffer.append(" DEFERRABLE"); } buffer.append(","); } for (UniqueConstraint uniqueConstraint : statement.getUniqueConstraints()) { if (uniqueConstraint.getConstraintName() != null && !constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(" UNIQUE ("); buffer.append(database.escapeColumnNameList(StringUtils.join(uniqueConstraint.getColumns(), ", "))); buffer.append(")"); if (uniqueConstraint.getConstraintName() != null && constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(","); } String sql = buffer.toString().replaceFirst(",\\s*$", "") + ")"; if (statement.getTablespace() != null && database.supportsTablespaces()) { if (database instanceof MSSQLDatabase || database instanceof SybaseASADatabase) { sql += " ON " + statement.getTablespace(); } else if (database instanceof DB2Database || database instanceof InformixDatabase) { sql += " IN " + statement.getTablespace(); } else { sql += " TABLESPACE " + statement.getTablespace(); } } return new Sql[] { new UnparsedSql(sql) }; } ValidationErrors validate(CreateTableStatement createTableStatement, Database database, SqlGeneratorChain sqlGeneratorChain); Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain); } | CreateTableGenerator extends AbstractSqlGenerator<CreateTableStatement> { public Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { StringBuffer buffer = new StringBuffer(); buffer.append("CREATE TABLE ").append(database.escapeTableName(statement.getSchemaName(), statement.getTableName())).append(" "); buffer.append("("); boolean isSinglePrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() == 1; boolean isPrimaryKeyAutoIncrement = false; Iterator<String> columnIterator = statement.getColumns().iterator(); while (columnIterator.hasNext()) { String column = columnIterator.next(); buffer.append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), column)); buffer.append(" ").append(statement.getColumnTypes().get(column)); AutoIncrementConstraint autoIncrementConstraint = null; for (AutoIncrementConstraint currentAutoIncrementConstraint : statement.getAutoIncrementConstraints()) { if (column.equals(currentAutoIncrementConstraint.getColumnName())) { autoIncrementConstraint = currentAutoIncrementConstraint; break; } } boolean isAutoIncrementColumn = autoIncrementConstraint != null; boolean isPrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().contains(column); isPrimaryKeyAutoIncrement = isPrimaryKeyAutoIncrement || isPrimaryKeyColumn && isAutoIncrementColumn; if ((database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyColumn && isAutoIncrementColumn) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } buffer.append(" PRIMARY KEY AUTOINCREMENT"); } if (statement.getDefaultValue(column) != null) { Object defaultValue = statement.getDefaultValue(column); if (database instanceof MSSQLDatabase) { buffer.append(" CONSTRAINT ").append(((MSSQLDatabase) database).generateDefaultConstraintName(statement.getTableName(), column)); } buffer.append(" DEFAULT "); buffer.append(statement.getColumnTypes().get(column).convertObjectToString(defaultValue, database)); } if (isAutoIncrementColumn && ! (database instanceof SQLiteDatabase)) { if (database.supportsAutoIncrement()) { String autoIncrementClause = database.getAutoIncrementClause(autoIncrementConstraint.getStartWith(), autoIncrementConstraint.getIncrementBy()); if (!"".equals(autoIncrementClause)) { buffer.append(" ").append(autoIncrementClause); } } else { LogFactory.getLogger().warning(database.getTypeName()+" does not support autoincrement columns as request for "+(database.escapeTableName(statement.getSchemaName(), statement.getTableName()))); } } if (statement.getNotNullColumns().contains(column)) { buffer.append(" NOT NULL"); } else { if (database instanceof SybaseDatabase || database instanceof SybaseASADatabase || database instanceof MySQLDatabase) { if (database instanceof MySQLDatabase && statement.getColumnTypes().get(column).getDataTypeName().equalsIgnoreCase("timestamp")) { } else { buffer.append(" NULL"); } } } if (database instanceof InformixDatabase && isSinglePrimaryKeyColumn) { buffer.append(" PRIMARY KEY"); } if (columnIterator.hasNext()) { buffer.append(", "); } } buffer.append(","); if (!( (database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyAutoIncrement) && !((database instanceof InformixDatabase) && isSinglePrimaryKeyColumn )) { if (statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() > 0) { if (!(database instanceof InformixDatabase)) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } } buffer.append(" PRIMARY KEY ("); buffer.append(database.escapeColumnNameList(StringUtils.join(statement.getPrimaryKeyConstraint().getColumns(), ", "))); buffer.append(")"); if (database instanceof OracleDatabase && statement.getPrimaryKeyConstraint().getTablespace() != null) { buffer.append(" USING INDEX TABLESPACE "); buffer.append(statement.getPrimaryKeyConstraint().getTablespace()); } buffer.append(","); } } for (ForeignKeyConstraint fkConstraint : statement.getForeignKeyConstraints()) { if (!(database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } String referencesString = fkConstraint.getReferences(); if (!referencesString.contains(".") && database.getDefaultSchemaName() != null) { referencesString = database.getDefaultSchemaName()+"."+referencesString; } buffer.append(" FOREIGN KEY (") .append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), fkConstraint.getColumn())) .append(") REFERENCES ") .append(referencesString); if (fkConstraint.isDeleteCascade()) { buffer.append(" ON DELETE CASCADE"); } if ((database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } if (fkConstraint.isInitiallyDeferred()) { buffer.append(" INITIALLY DEFERRED"); } if (fkConstraint.isDeferrable()) { buffer.append(" DEFERRABLE"); } buffer.append(","); } for (UniqueConstraint uniqueConstraint : statement.getUniqueConstraints()) { if (uniqueConstraint.getConstraintName() != null && !constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(" UNIQUE ("); buffer.append(database.escapeColumnNameList(StringUtils.join(uniqueConstraint.getColumns(), ", "))); buffer.append(")"); if (uniqueConstraint.getConstraintName() != null && constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(","); } String sql = buffer.toString().replaceFirst(",\\s*$", "") + ")"; if (statement.getTablespace() != null && database.supportsTablespaces()) { if (database instanceof MSSQLDatabase || database instanceof SybaseASADatabase) { sql += " ON " + statement.getTablespace(); } else if (database instanceof DB2Database || database instanceof InformixDatabase) { sql += " IN " + statement.getTablespace(); } else { sql += " TABLESPACE " + statement.getTablespace(); } } return new Sql[] { new UnparsedSql(sql) }; } ValidationErrors validate(CreateTableStatement createTableStatement, Database database, SqlGeneratorChain sqlGeneratorChain); Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain); } |
@Test public void testAutoIncrementSybaseDatabase() throws Exception { for (Database database : TestContext.getInstance().getAllDatabases()) { if (database instanceof SybaseDatabase) { CreateTableStatement statement = new CreateTableStatement(SCHEMA_NAME, TABLE_NAME); statement.addColumn( COLUMN_NAME1, TypeConverterFactory.getInstance().findTypeConverter(database).getDataType("BIGINT", true), new AutoIncrementConstraint(COLUMN_NAME1) ); Sql[] generatedSql = this.generatorUnderTest.generateSql(statement, database, null); assertEquals("CREATE TABLE [SCHEMA_NAME].[TABLE_NAME] ([COLUMN1_NAME] BIGINT IDENTITY NULL)", generatedSql[0].toSql()); } } } | public Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { StringBuffer buffer = new StringBuffer(); buffer.append("CREATE TABLE ").append(database.escapeTableName(statement.getSchemaName(), statement.getTableName())).append(" "); buffer.append("("); boolean isSinglePrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() == 1; boolean isPrimaryKeyAutoIncrement = false; Iterator<String> columnIterator = statement.getColumns().iterator(); while (columnIterator.hasNext()) { String column = columnIterator.next(); buffer.append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), column)); buffer.append(" ").append(statement.getColumnTypes().get(column)); AutoIncrementConstraint autoIncrementConstraint = null; for (AutoIncrementConstraint currentAutoIncrementConstraint : statement.getAutoIncrementConstraints()) { if (column.equals(currentAutoIncrementConstraint.getColumnName())) { autoIncrementConstraint = currentAutoIncrementConstraint; break; } } boolean isAutoIncrementColumn = autoIncrementConstraint != null; boolean isPrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().contains(column); isPrimaryKeyAutoIncrement = isPrimaryKeyAutoIncrement || isPrimaryKeyColumn && isAutoIncrementColumn; if ((database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyColumn && isAutoIncrementColumn) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } buffer.append(" PRIMARY KEY AUTOINCREMENT"); } if (statement.getDefaultValue(column) != null) { Object defaultValue = statement.getDefaultValue(column); if (database instanceof MSSQLDatabase) { buffer.append(" CONSTRAINT ").append(((MSSQLDatabase) database).generateDefaultConstraintName(statement.getTableName(), column)); } buffer.append(" DEFAULT "); buffer.append(statement.getColumnTypes().get(column).convertObjectToString(defaultValue, database)); } if (isAutoIncrementColumn && ! (database instanceof SQLiteDatabase)) { if (database.supportsAutoIncrement()) { String autoIncrementClause = database.getAutoIncrementClause(autoIncrementConstraint.getStartWith(), autoIncrementConstraint.getIncrementBy()); if (!"".equals(autoIncrementClause)) { buffer.append(" ").append(autoIncrementClause); } } else { LogFactory.getLogger().warning(database.getTypeName()+" does not support autoincrement columns as request for "+(database.escapeTableName(statement.getSchemaName(), statement.getTableName()))); } } if (statement.getNotNullColumns().contains(column)) { buffer.append(" NOT NULL"); } else { if (database instanceof SybaseDatabase || database instanceof SybaseASADatabase || database instanceof MySQLDatabase) { if (database instanceof MySQLDatabase && statement.getColumnTypes().get(column).getDataTypeName().equalsIgnoreCase("timestamp")) { } else { buffer.append(" NULL"); } } } if (database instanceof InformixDatabase && isSinglePrimaryKeyColumn) { buffer.append(" PRIMARY KEY"); } if (columnIterator.hasNext()) { buffer.append(", "); } } buffer.append(","); if (!( (database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyAutoIncrement) && !((database instanceof InformixDatabase) && isSinglePrimaryKeyColumn )) { if (statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() > 0) { if (!(database instanceof InformixDatabase)) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } } buffer.append(" PRIMARY KEY ("); buffer.append(database.escapeColumnNameList(StringUtils.join(statement.getPrimaryKeyConstraint().getColumns(), ", "))); buffer.append(")"); if (database instanceof OracleDatabase && statement.getPrimaryKeyConstraint().getTablespace() != null) { buffer.append(" USING INDEX TABLESPACE "); buffer.append(statement.getPrimaryKeyConstraint().getTablespace()); } buffer.append(","); } } for (ForeignKeyConstraint fkConstraint : statement.getForeignKeyConstraints()) { if (!(database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } String referencesString = fkConstraint.getReferences(); if (!referencesString.contains(".") && database.getDefaultSchemaName() != null) { referencesString = database.getDefaultSchemaName()+"."+referencesString; } buffer.append(" FOREIGN KEY (") .append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), fkConstraint.getColumn())) .append(") REFERENCES ") .append(referencesString); if (fkConstraint.isDeleteCascade()) { buffer.append(" ON DELETE CASCADE"); } if ((database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } if (fkConstraint.isInitiallyDeferred()) { buffer.append(" INITIALLY DEFERRED"); } if (fkConstraint.isDeferrable()) { buffer.append(" DEFERRABLE"); } buffer.append(","); } for (UniqueConstraint uniqueConstraint : statement.getUniqueConstraints()) { if (uniqueConstraint.getConstraintName() != null && !constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(" UNIQUE ("); buffer.append(database.escapeColumnNameList(StringUtils.join(uniqueConstraint.getColumns(), ", "))); buffer.append(")"); if (uniqueConstraint.getConstraintName() != null && constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(","); } String sql = buffer.toString().replaceFirst(",\\s*$", "") + ")"; if (statement.getTablespace() != null && database.supportsTablespaces()) { if (database instanceof MSSQLDatabase || database instanceof SybaseASADatabase) { sql += " ON " + statement.getTablespace(); } else if (database instanceof DB2Database || database instanceof InformixDatabase) { sql += " IN " + statement.getTablespace(); } else { sql += " TABLESPACE " + statement.getTablespace(); } } return new Sql[] { new UnparsedSql(sql) }; } | CreateTableGenerator extends AbstractSqlGenerator<CreateTableStatement> { public Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { StringBuffer buffer = new StringBuffer(); buffer.append("CREATE TABLE ").append(database.escapeTableName(statement.getSchemaName(), statement.getTableName())).append(" "); buffer.append("("); boolean isSinglePrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() == 1; boolean isPrimaryKeyAutoIncrement = false; Iterator<String> columnIterator = statement.getColumns().iterator(); while (columnIterator.hasNext()) { String column = columnIterator.next(); buffer.append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), column)); buffer.append(" ").append(statement.getColumnTypes().get(column)); AutoIncrementConstraint autoIncrementConstraint = null; for (AutoIncrementConstraint currentAutoIncrementConstraint : statement.getAutoIncrementConstraints()) { if (column.equals(currentAutoIncrementConstraint.getColumnName())) { autoIncrementConstraint = currentAutoIncrementConstraint; break; } } boolean isAutoIncrementColumn = autoIncrementConstraint != null; boolean isPrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().contains(column); isPrimaryKeyAutoIncrement = isPrimaryKeyAutoIncrement || isPrimaryKeyColumn && isAutoIncrementColumn; if ((database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyColumn && isAutoIncrementColumn) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } buffer.append(" PRIMARY KEY AUTOINCREMENT"); } if (statement.getDefaultValue(column) != null) { Object defaultValue = statement.getDefaultValue(column); if (database instanceof MSSQLDatabase) { buffer.append(" CONSTRAINT ").append(((MSSQLDatabase) database).generateDefaultConstraintName(statement.getTableName(), column)); } buffer.append(" DEFAULT "); buffer.append(statement.getColumnTypes().get(column).convertObjectToString(defaultValue, database)); } if (isAutoIncrementColumn && ! (database instanceof SQLiteDatabase)) { if (database.supportsAutoIncrement()) { String autoIncrementClause = database.getAutoIncrementClause(autoIncrementConstraint.getStartWith(), autoIncrementConstraint.getIncrementBy()); if (!"".equals(autoIncrementClause)) { buffer.append(" ").append(autoIncrementClause); } } else { LogFactory.getLogger().warning(database.getTypeName()+" does not support autoincrement columns as request for "+(database.escapeTableName(statement.getSchemaName(), statement.getTableName()))); } } if (statement.getNotNullColumns().contains(column)) { buffer.append(" NOT NULL"); } else { if (database instanceof SybaseDatabase || database instanceof SybaseASADatabase || database instanceof MySQLDatabase) { if (database instanceof MySQLDatabase && statement.getColumnTypes().get(column).getDataTypeName().equalsIgnoreCase("timestamp")) { } else { buffer.append(" NULL"); } } } if (database instanceof InformixDatabase && isSinglePrimaryKeyColumn) { buffer.append(" PRIMARY KEY"); } if (columnIterator.hasNext()) { buffer.append(", "); } } buffer.append(","); if (!( (database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyAutoIncrement) && !((database instanceof InformixDatabase) && isSinglePrimaryKeyColumn )) { if (statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() > 0) { if (!(database instanceof InformixDatabase)) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } } buffer.append(" PRIMARY KEY ("); buffer.append(database.escapeColumnNameList(StringUtils.join(statement.getPrimaryKeyConstraint().getColumns(), ", "))); buffer.append(")"); if (database instanceof OracleDatabase && statement.getPrimaryKeyConstraint().getTablespace() != null) { buffer.append(" USING INDEX TABLESPACE "); buffer.append(statement.getPrimaryKeyConstraint().getTablespace()); } buffer.append(","); } } for (ForeignKeyConstraint fkConstraint : statement.getForeignKeyConstraints()) { if (!(database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } String referencesString = fkConstraint.getReferences(); if (!referencesString.contains(".") && database.getDefaultSchemaName() != null) { referencesString = database.getDefaultSchemaName()+"."+referencesString; } buffer.append(" FOREIGN KEY (") .append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), fkConstraint.getColumn())) .append(") REFERENCES ") .append(referencesString); if (fkConstraint.isDeleteCascade()) { buffer.append(" ON DELETE CASCADE"); } if ((database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } if (fkConstraint.isInitiallyDeferred()) { buffer.append(" INITIALLY DEFERRED"); } if (fkConstraint.isDeferrable()) { buffer.append(" DEFERRABLE"); } buffer.append(","); } for (UniqueConstraint uniqueConstraint : statement.getUniqueConstraints()) { if (uniqueConstraint.getConstraintName() != null && !constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(" UNIQUE ("); buffer.append(database.escapeColumnNameList(StringUtils.join(uniqueConstraint.getColumns(), ", "))); buffer.append(")"); if (uniqueConstraint.getConstraintName() != null && constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(","); } String sql = buffer.toString().replaceFirst(",\\s*$", "") + ")"; if (statement.getTablespace() != null && database.supportsTablespaces()) { if (database instanceof MSSQLDatabase || database instanceof SybaseASADatabase) { sql += " ON " + statement.getTablespace(); } else if (database instanceof DB2Database || database instanceof InformixDatabase) { sql += " IN " + statement.getTablespace(); } else { sql += " TABLESPACE " + statement.getTablespace(); } } return new Sql[] { new UnparsedSql(sql) }; } } | CreateTableGenerator extends AbstractSqlGenerator<CreateTableStatement> { public Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { StringBuffer buffer = new StringBuffer(); buffer.append("CREATE TABLE ").append(database.escapeTableName(statement.getSchemaName(), statement.getTableName())).append(" "); buffer.append("("); boolean isSinglePrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() == 1; boolean isPrimaryKeyAutoIncrement = false; Iterator<String> columnIterator = statement.getColumns().iterator(); while (columnIterator.hasNext()) { String column = columnIterator.next(); buffer.append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), column)); buffer.append(" ").append(statement.getColumnTypes().get(column)); AutoIncrementConstraint autoIncrementConstraint = null; for (AutoIncrementConstraint currentAutoIncrementConstraint : statement.getAutoIncrementConstraints()) { if (column.equals(currentAutoIncrementConstraint.getColumnName())) { autoIncrementConstraint = currentAutoIncrementConstraint; break; } } boolean isAutoIncrementColumn = autoIncrementConstraint != null; boolean isPrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().contains(column); isPrimaryKeyAutoIncrement = isPrimaryKeyAutoIncrement || isPrimaryKeyColumn && isAutoIncrementColumn; if ((database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyColumn && isAutoIncrementColumn) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } buffer.append(" PRIMARY KEY AUTOINCREMENT"); } if (statement.getDefaultValue(column) != null) { Object defaultValue = statement.getDefaultValue(column); if (database instanceof MSSQLDatabase) { buffer.append(" CONSTRAINT ").append(((MSSQLDatabase) database).generateDefaultConstraintName(statement.getTableName(), column)); } buffer.append(" DEFAULT "); buffer.append(statement.getColumnTypes().get(column).convertObjectToString(defaultValue, database)); } if (isAutoIncrementColumn && ! (database instanceof SQLiteDatabase)) { if (database.supportsAutoIncrement()) { String autoIncrementClause = database.getAutoIncrementClause(autoIncrementConstraint.getStartWith(), autoIncrementConstraint.getIncrementBy()); if (!"".equals(autoIncrementClause)) { buffer.append(" ").append(autoIncrementClause); } } else { LogFactory.getLogger().warning(database.getTypeName()+" does not support autoincrement columns as request for "+(database.escapeTableName(statement.getSchemaName(), statement.getTableName()))); } } if (statement.getNotNullColumns().contains(column)) { buffer.append(" NOT NULL"); } else { if (database instanceof SybaseDatabase || database instanceof SybaseASADatabase || database instanceof MySQLDatabase) { if (database instanceof MySQLDatabase && statement.getColumnTypes().get(column).getDataTypeName().equalsIgnoreCase("timestamp")) { } else { buffer.append(" NULL"); } } } if (database instanceof InformixDatabase && isSinglePrimaryKeyColumn) { buffer.append(" PRIMARY KEY"); } if (columnIterator.hasNext()) { buffer.append(", "); } } buffer.append(","); if (!( (database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyAutoIncrement) && !((database instanceof InformixDatabase) && isSinglePrimaryKeyColumn )) { if (statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() > 0) { if (!(database instanceof InformixDatabase)) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } } buffer.append(" PRIMARY KEY ("); buffer.append(database.escapeColumnNameList(StringUtils.join(statement.getPrimaryKeyConstraint().getColumns(), ", "))); buffer.append(")"); if (database instanceof OracleDatabase && statement.getPrimaryKeyConstraint().getTablespace() != null) { buffer.append(" USING INDEX TABLESPACE "); buffer.append(statement.getPrimaryKeyConstraint().getTablespace()); } buffer.append(","); } } for (ForeignKeyConstraint fkConstraint : statement.getForeignKeyConstraints()) { if (!(database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } String referencesString = fkConstraint.getReferences(); if (!referencesString.contains(".") && database.getDefaultSchemaName() != null) { referencesString = database.getDefaultSchemaName()+"."+referencesString; } buffer.append(" FOREIGN KEY (") .append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), fkConstraint.getColumn())) .append(") REFERENCES ") .append(referencesString); if (fkConstraint.isDeleteCascade()) { buffer.append(" ON DELETE CASCADE"); } if ((database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } if (fkConstraint.isInitiallyDeferred()) { buffer.append(" INITIALLY DEFERRED"); } if (fkConstraint.isDeferrable()) { buffer.append(" DEFERRABLE"); } buffer.append(","); } for (UniqueConstraint uniqueConstraint : statement.getUniqueConstraints()) { if (uniqueConstraint.getConstraintName() != null && !constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(" UNIQUE ("); buffer.append(database.escapeColumnNameList(StringUtils.join(uniqueConstraint.getColumns(), ", "))); buffer.append(")"); if (uniqueConstraint.getConstraintName() != null && constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(","); } String sql = buffer.toString().replaceFirst(",\\s*$", "") + ")"; if (statement.getTablespace() != null && database.supportsTablespaces()) { if (database instanceof MSSQLDatabase || database instanceof SybaseASADatabase) { sql += " ON " + statement.getTablespace(); } else if (database instanceof DB2Database || database instanceof InformixDatabase) { sql += " IN " + statement.getTablespace(); } else { sql += " TABLESPACE " + statement.getTablespace(); } } return new Sql[] { new UnparsedSql(sql) }; } } | CreateTableGenerator extends AbstractSqlGenerator<CreateTableStatement> { public Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { StringBuffer buffer = new StringBuffer(); buffer.append("CREATE TABLE ").append(database.escapeTableName(statement.getSchemaName(), statement.getTableName())).append(" "); buffer.append("("); boolean isSinglePrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() == 1; boolean isPrimaryKeyAutoIncrement = false; Iterator<String> columnIterator = statement.getColumns().iterator(); while (columnIterator.hasNext()) { String column = columnIterator.next(); buffer.append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), column)); buffer.append(" ").append(statement.getColumnTypes().get(column)); AutoIncrementConstraint autoIncrementConstraint = null; for (AutoIncrementConstraint currentAutoIncrementConstraint : statement.getAutoIncrementConstraints()) { if (column.equals(currentAutoIncrementConstraint.getColumnName())) { autoIncrementConstraint = currentAutoIncrementConstraint; break; } } boolean isAutoIncrementColumn = autoIncrementConstraint != null; boolean isPrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().contains(column); isPrimaryKeyAutoIncrement = isPrimaryKeyAutoIncrement || isPrimaryKeyColumn && isAutoIncrementColumn; if ((database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyColumn && isAutoIncrementColumn) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } buffer.append(" PRIMARY KEY AUTOINCREMENT"); } if (statement.getDefaultValue(column) != null) { Object defaultValue = statement.getDefaultValue(column); if (database instanceof MSSQLDatabase) { buffer.append(" CONSTRAINT ").append(((MSSQLDatabase) database).generateDefaultConstraintName(statement.getTableName(), column)); } buffer.append(" DEFAULT "); buffer.append(statement.getColumnTypes().get(column).convertObjectToString(defaultValue, database)); } if (isAutoIncrementColumn && ! (database instanceof SQLiteDatabase)) { if (database.supportsAutoIncrement()) { String autoIncrementClause = database.getAutoIncrementClause(autoIncrementConstraint.getStartWith(), autoIncrementConstraint.getIncrementBy()); if (!"".equals(autoIncrementClause)) { buffer.append(" ").append(autoIncrementClause); } } else { LogFactory.getLogger().warning(database.getTypeName()+" does not support autoincrement columns as request for "+(database.escapeTableName(statement.getSchemaName(), statement.getTableName()))); } } if (statement.getNotNullColumns().contains(column)) { buffer.append(" NOT NULL"); } else { if (database instanceof SybaseDatabase || database instanceof SybaseASADatabase || database instanceof MySQLDatabase) { if (database instanceof MySQLDatabase && statement.getColumnTypes().get(column).getDataTypeName().equalsIgnoreCase("timestamp")) { } else { buffer.append(" NULL"); } } } if (database instanceof InformixDatabase && isSinglePrimaryKeyColumn) { buffer.append(" PRIMARY KEY"); } if (columnIterator.hasNext()) { buffer.append(", "); } } buffer.append(","); if (!( (database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyAutoIncrement) && !((database instanceof InformixDatabase) && isSinglePrimaryKeyColumn )) { if (statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() > 0) { if (!(database instanceof InformixDatabase)) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } } buffer.append(" PRIMARY KEY ("); buffer.append(database.escapeColumnNameList(StringUtils.join(statement.getPrimaryKeyConstraint().getColumns(), ", "))); buffer.append(")"); if (database instanceof OracleDatabase && statement.getPrimaryKeyConstraint().getTablespace() != null) { buffer.append(" USING INDEX TABLESPACE "); buffer.append(statement.getPrimaryKeyConstraint().getTablespace()); } buffer.append(","); } } for (ForeignKeyConstraint fkConstraint : statement.getForeignKeyConstraints()) { if (!(database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } String referencesString = fkConstraint.getReferences(); if (!referencesString.contains(".") && database.getDefaultSchemaName() != null) { referencesString = database.getDefaultSchemaName()+"."+referencesString; } buffer.append(" FOREIGN KEY (") .append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), fkConstraint.getColumn())) .append(") REFERENCES ") .append(referencesString); if (fkConstraint.isDeleteCascade()) { buffer.append(" ON DELETE CASCADE"); } if ((database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } if (fkConstraint.isInitiallyDeferred()) { buffer.append(" INITIALLY DEFERRED"); } if (fkConstraint.isDeferrable()) { buffer.append(" DEFERRABLE"); } buffer.append(","); } for (UniqueConstraint uniqueConstraint : statement.getUniqueConstraints()) { if (uniqueConstraint.getConstraintName() != null && !constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(" UNIQUE ("); buffer.append(database.escapeColumnNameList(StringUtils.join(uniqueConstraint.getColumns(), ", "))); buffer.append(")"); if (uniqueConstraint.getConstraintName() != null && constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(","); } String sql = buffer.toString().replaceFirst(",\\s*$", "") + ")"; if (statement.getTablespace() != null && database.supportsTablespaces()) { if (database instanceof MSSQLDatabase || database instanceof SybaseASADatabase) { sql += " ON " + statement.getTablespace(); } else if (database instanceof DB2Database || database instanceof InformixDatabase) { sql += " IN " + statement.getTablespace(); } else { sql += " TABLESPACE " + statement.getTablespace(); } } return new Sql[] { new UnparsedSql(sql) }; } ValidationErrors validate(CreateTableStatement createTableStatement, Database database, SqlGeneratorChain sqlGeneratorChain); Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain); } | CreateTableGenerator extends AbstractSqlGenerator<CreateTableStatement> { public Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { StringBuffer buffer = new StringBuffer(); buffer.append("CREATE TABLE ").append(database.escapeTableName(statement.getSchemaName(), statement.getTableName())).append(" "); buffer.append("("); boolean isSinglePrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() == 1; boolean isPrimaryKeyAutoIncrement = false; Iterator<String> columnIterator = statement.getColumns().iterator(); while (columnIterator.hasNext()) { String column = columnIterator.next(); buffer.append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), column)); buffer.append(" ").append(statement.getColumnTypes().get(column)); AutoIncrementConstraint autoIncrementConstraint = null; for (AutoIncrementConstraint currentAutoIncrementConstraint : statement.getAutoIncrementConstraints()) { if (column.equals(currentAutoIncrementConstraint.getColumnName())) { autoIncrementConstraint = currentAutoIncrementConstraint; break; } } boolean isAutoIncrementColumn = autoIncrementConstraint != null; boolean isPrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().contains(column); isPrimaryKeyAutoIncrement = isPrimaryKeyAutoIncrement || isPrimaryKeyColumn && isAutoIncrementColumn; if ((database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyColumn && isAutoIncrementColumn) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } buffer.append(" PRIMARY KEY AUTOINCREMENT"); } if (statement.getDefaultValue(column) != null) { Object defaultValue = statement.getDefaultValue(column); if (database instanceof MSSQLDatabase) { buffer.append(" CONSTRAINT ").append(((MSSQLDatabase) database).generateDefaultConstraintName(statement.getTableName(), column)); } buffer.append(" DEFAULT "); buffer.append(statement.getColumnTypes().get(column).convertObjectToString(defaultValue, database)); } if (isAutoIncrementColumn && ! (database instanceof SQLiteDatabase)) { if (database.supportsAutoIncrement()) { String autoIncrementClause = database.getAutoIncrementClause(autoIncrementConstraint.getStartWith(), autoIncrementConstraint.getIncrementBy()); if (!"".equals(autoIncrementClause)) { buffer.append(" ").append(autoIncrementClause); } } else { LogFactory.getLogger().warning(database.getTypeName()+" does not support autoincrement columns as request for "+(database.escapeTableName(statement.getSchemaName(), statement.getTableName()))); } } if (statement.getNotNullColumns().contains(column)) { buffer.append(" NOT NULL"); } else { if (database instanceof SybaseDatabase || database instanceof SybaseASADatabase || database instanceof MySQLDatabase) { if (database instanceof MySQLDatabase && statement.getColumnTypes().get(column).getDataTypeName().equalsIgnoreCase("timestamp")) { } else { buffer.append(" NULL"); } } } if (database instanceof InformixDatabase && isSinglePrimaryKeyColumn) { buffer.append(" PRIMARY KEY"); } if (columnIterator.hasNext()) { buffer.append(", "); } } buffer.append(","); if (!( (database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyAutoIncrement) && !((database instanceof InformixDatabase) && isSinglePrimaryKeyColumn )) { if (statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() > 0) { if (!(database instanceof InformixDatabase)) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } } buffer.append(" PRIMARY KEY ("); buffer.append(database.escapeColumnNameList(StringUtils.join(statement.getPrimaryKeyConstraint().getColumns(), ", "))); buffer.append(")"); if (database instanceof OracleDatabase && statement.getPrimaryKeyConstraint().getTablespace() != null) { buffer.append(" USING INDEX TABLESPACE "); buffer.append(statement.getPrimaryKeyConstraint().getTablespace()); } buffer.append(","); } } for (ForeignKeyConstraint fkConstraint : statement.getForeignKeyConstraints()) { if (!(database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } String referencesString = fkConstraint.getReferences(); if (!referencesString.contains(".") && database.getDefaultSchemaName() != null) { referencesString = database.getDefaultSchemaName()+"."+referencesString; } buffer.append(" FOREIGN KEY (") .append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), fkConstraint.getColumn())) .append(") REFERENCES ") .append(referencesString); if (fkConstraint.isDeleteCascade()) { buffer.append(" ON DELETE CASCADE"); } if ((database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } if (fkConstraint.isInitiallyDeferred()) { buffer.append(" INITIALLY DEFERRED"); } if (fkConstraint.isDeferrable()) { buffer.append(" DEFERRABLE"); } buffer.append(","); } for (UniqueConstraint uniqueConstraint : statement.getUniqueConstraints()) { if (uniqueConstraint.getConstraintName() != null && !constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(" UNIQUE ("); buffer.append(database.escapeColumnNameList(StringUtils.join(uniqueConstraint.getColumns(), ", "))); buffer.append(")"); if (uniqueConstraint.getConstraintName() != null && constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(","); } String sql = buffer.toString().replaceFirst(",\\s*$", "") + ")"; if (statement.getTablespace() != null && database.supportsTablespaces()) { if (database instanceof MSSQLDatabase || database instanceof SybaseASADatabase) { sql += " ON " + statement.getTablespace(); } else if (database instanceof DB2Database || database instanceof InformixDatabase) { sql += " IN " + statement.getTablespace(); } else { sql += " TABLESPACE " + statement.getTablespace(); } } return new Sql[] { new UnparsedSql(sql) }; } ValidationErrors validate(CreateTableStatement createTableStatement, Database database, SqlGeneratorChain sqlGeneratorChain); Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain); } |
@Test public void testAutoIncrementStartWithSybaseDatabase() throws Exception { for (Database database : TestContext.getInstance().getAllDatabases()) { if (database instanceof SybaseDatabase) { CreateTableStatement statement = new CreateTableStatement(SCHEMA_NAME, TABLE_NAME); statement.addColumn( COLUMN_NAME1, TypeConverterFactory.getInstance().findTypeConverter(database).getDataType("BIGINT", true), new AutoIncrementConstraint(COLUMN_NAME1, BigInteger.valueOf(2), null) ); Sql[] generatedSql = this.generatorUnderTest.generateSql(statement, database, null); assertEquals("CREATE TABLE [SCHEMA_NAME].[TABLE_NAME] ([COLUMN1_NAME] BIGINT IDENTITY NULL)", generatedSql[0].toSql()); } } } | public Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { StringBuffer buffer = new StringBuffer(); buffer.append("CREATE TABLE ").append(database.escapeTableName(statement.getSchemaName(), statement.getTableName())).append(" "); buffer.append("("); boolean isSinglePrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() == 1; boolean isPrimaryKeyAutoIncrement = false; Iterator<String> columnIterator = statement.getColumns().iterator(); while (columnIterator.hasNext()) { String column = columnIterator.next(); buffer.append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), column)); buffer.append(" ").append(statement.getColumnTypes().get(column)); AutoIncrementConstraint autoIncrementConstraint = null; for (AutoIncrementConstraint currentAutoIncrementConstraint : statement.getAutoIncrementConstraints()) { if (column.equals(currentAutoIncrementConstraint.getColumnName())) { autoIncrementConstraint = currentAutoIncrementConstraint; break; } } boolean isAutoIncrementColumn = autoIncrementConstraint != null; boolean isPrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().contains(column); isPrimaryKeyAutoIncrement = isPrimaryKeyAutoIncrement || isPrimaryKeyColumn && isAutoIncrementColumn; if ((database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyColumn && isAutoIncrementColumn) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } buffer.append(" PRIMARY KEY AUTOINCREMENT"); } if (statement.getDefaultValue(column) != null) { Object defaultValue = statement.getDefaultValue(column); if (database instanceof MSSQLDatabase) { buffer.append(" CONSTRAINT ").append(((MSSQLDatabase) database).generateDefaultConstraintName(statement.getTableName(), column)); } buffer.append(" DEFAULT "); buffer.append(statement.getColumnTypes().get(column).convertObjectToString(defaultValue, database)); } if (isAutoIncrementColumn && ! (database instanceof SQLiteDatabase)) { if (database.supportsAutoIncrement()) { String autoIncrementClause = database.getAutoIncrementClause(autoIncrementConstraint.getStartWith(), autoIncrementConstraint.getIncrementBy()); if (!"".equals(autoIncrementClause)) { buffer.append(" ").append(autoIncrementClause); } } else { LogFactory.getLogger().warning(database.getTypeName()+" does not support autoincrement columns as request for "+(database.escapeTableName(statement.getSchemaName(), statement.getTableName()))); } } if (statement.getNotNullColumns().contains(column)) { buffer.append(" NOT NULL"); } else { if (database instanceof SybaseDatabase || database instanceof SybaseASADatabase || database instanceof MySQLDatabase) { if (database instanceof MySQLDatabase && statement.getColumnTypes().get(column).getDataTypeName().equalsIgnoreCase("timestamp")) { } else { buffer.append(" NULL"); } } } if (database instanceof InformixDatabase && isSinglePrimaryKeyColumn) { buffer.append(" PRIMARY KEY"); } if (columnIterator.hasNext()) { buffer.append(", "); } } buffer.append(","); if (!( (database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyAutoIncrement) && !((database instanceof InformixDatabase) && isSinglePrimaryKeyColumn )) { if (statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() > 0) { if (!(database instanceof InformixDatabase)) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } } buffer.append(" PRIMARY KEY ("); buffer.append(database.escapeColumnNameList(StringUtils.join(statement.getPrimaryKeyConstraint().getColumns(), ", "))); buffer.append(")"); if (database instanceof OracleDatabase && statement.getPrimaryKeyConstraint().getTablespace() != null) { buffer.append(" USING INDEX TABLESPACE "); buffer.append(statement.getPrimaryKeyConstraint().getTablespace()); } buffer.append(","); } } for (ForeignKeyConstraint fkConstraint : statement.getForeignKeyConstraints()) { if (!(database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } String referencesString = fkConstraint.getReferences(); if (!referencesString.contains(".") && database.getDefaultSchemaName() != null) { referencesString = database.getDefaultSchemaName()+"."+referencesString; } buffer.append(" FOREIGN KEY (") .append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), fkConstraint.getColumn())) .append(") REFERENCES ") .append(referencesString); if (fkConstraint.isDeleteCascade()) { buffer.append(" ON DELETE CASCADE"); } if ((database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } if (fkConstraint.isInitiallyDeferred()) { buffer.append(" INITIALLY DEFERRED"); } if (fkConstraint.isDeferrable()) { buffer.append(" DEFERRABLE"); } buffer.append(","); } for (UniqueConstraint uniqueConstraint : statement.getUniqueConstraints()) { if (uniqueConstraint.getConstraintName() != null && !constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(" UNIQUE ("); buffer.append(database.escapeColumnNameList(StringUtils.join(uniqueConstraint.getColumns(), ", "))); buffer.append(")"); if (uniqueConstraint.getConstraintName() != null && constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(","); } String sql = buffer.toString().replaceFirst(",\\s*$", "") + ")"; if (statement.getTablespace() != null && database.supportsTablespaces()) { if (database instanceof MSSQLDatabase || database instanceof SybaseASADatabase) { sql += " ON " + statement.getTablespace(); } else if (database instanceof DB2Database || database instanceof InformixDatabase) { sql += " IN " + statement.getTablespace(); } else { sql += " TABLESPACE " + statement.getTablespace(); } } return new Sql[] { new UnparsedSql(sql) }; } | CreateTableGenerator extends AbstractSqlGenerator<CreateTableStatement> { public Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { StringBuffer buffer = new StringBuffer(); buffer.append("CREATE TABLE ").append(database.escapeTableName(statement.getSchemaName(), statement.getTableName())).append(" "); buffer.append("("); boolean isSinglePrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() == 1; boolean isPrimaryKeyAutoIncrement = false; Iterator<String> columnIterator = statement.getColumns().iterator(); while (columnIterator.hasNext()) { String column = columnIterator.next(); buffer.append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), column)); buffer.append(" ").append(statement.getColumnTypes().get(column)); AutoIncrementConstraint autoIncrementConstraint = null; for (AutoIncrementConstraint currentAutoIncrementConstraint : statement.getAutoIncrementConstraints()) { if (column.equals(currentAutoIncrementConstraint.getColumnName())) { autoIncrementConstraint = currentAutoIncrementConstraint; break; } } boolean isAutoIncrementColumn = autoIncrementConstraint != null; boolean isPrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().contains(column); isPrimaryKeyAutoIncrement = isPrimaryKeyAutoIncrement || isPrimaryKeyColumn && isAutoIncrementColumn; if ((database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyColumn && isAutoIncrementColumn) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } buffer.append(" PRIMARY KEY AUTOINCREMENT"); } if (statement.getDefaultValue(column) != null) { Object defaultValue = statement.getDefaultValue(column); if (database instanceof MSSQLDatabase) { buffer.append(" CONSTRAINT ").append(((MSSQLDatabase) database).generateDefaultConstraintName(statement.getTableName(), column)); } buffer.append(" DEFAULT "); buffer.append(statement.getColumnTypes().get(column).convertObjectToString(defaultValue, database)); } if (isAutoIncrementColumn && ! (database instanceof SQLiteDatabase)) { if (database.supportsAutoIncrement()) { String autoIncrementClause = database.getAutoIncrementClause(autoIncrementConstraint.getStartWith(), autoIncrementConstraint.getIncrementBy()); if (!"".equals(autoIncrementClause)) { buffer.append(" ").append(autoIncrementClause); } } else { LogFactory.getLogger().warning(database.getTypeName()+" does not support autoincrement columns as request for "+(database.escapeTableName(statement.getSchemaName(), statement.getTableName()))); } } if (statement.getNotNullColumns().contains(column)) { buffer.append(" NOT NULL"); } else { if (database instanceof SybaseDatabase || database instanceof SybaseASADatabase || database instanceof MySQLDatabase) { if (database instanceof MySQLDatabase && statement.getColumnTypes().get(column).getDataTypeName().equalsIgnoreCase("timestamp")) { } else { buffer.append(" NULL"); } } } if (database instanceof InformixDatabase && isSinglePrimaryKeyColumn) { buffer.append(" PRIMARY KEY"); } if (columnIterator.hasNext()) { buffer.append(", "); } } buffer.append(","); if (!( (database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyAutoIncrement) && !((database instanceof InformixDatabase) && isSinglePrimaryKeyColumn )) { if (statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() > 0) { if (!(database instanceof InformixDatabase)) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } } buffer.append(" PRIMARY KEY ("); buffer.append(database.escapeColumnNameList(StringUtils.join(statement.getPrimaryKeyConstraint().getColumns(), ", "))); buffer.append(")"); if (database instanceof OracleDatabase && statement.getPrimaryKeyConstraint().getTablespace() != null) { buffer.append(" USING INDEX TABLESPACE "); buffer.append(statement.getPrimaryKeyConstraint().getTablespace()); } buffer.append(","); } } for (ForeignKeyConstraint fkConstraint : statement.getForeignKeyConstraints()) { if (!(database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } String referencesString = fkConstraint.getReferences(); if (!referencesString.contains(".") && database.getDefaultSchemaName() != null) { referencesString = database.getDefaultSchemaName()+"."+referencesString; } buffer.append(" FOREIGN KEY (") .append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), fkConstraint.getColumn())) .append(") REFERENCES ") .append(referencesString); if (fkConstraint.isDeleteCascade()) { buffer.append(" ON DELETE CASCADE"); } if ((database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } if (fkConstraint.isInitiallyDeferred()) { buffer.append(" INITIALLY DEFERRED"); } if (fkConstraint.isDeferrable()) { buffer.append(" DEFERRABLE"); } buffer.append(","); } for (UniqueConstraint uniqueConstraint : statement.getUniqueConstraints()) { if (uniqueConstraint.getConstraintName() != null && !constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(" UNIQUE ("); buffer.append(database.escapeColumnNameList(StringUtils.join(uniqueConstraint.getColumns(), ", "))); buffer.append(")"); if (uniqueConstraint.getConstraintName() != null && constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(","); } String sql = buffer.toString().replaceFirst(",\\s*$", "") + ")"; if (statement.getTablespace() != null && database.supportsTablespaces()) { if (database instanceof MSSQLDatabase || database instanceof SybaseASADatabase) { sql += " ON " + statement.getTablespace(); } else if (database instanceof DB2Database || database instanceof InformixDatabase) { sql += " IN " + statement.getTablespace(); } else { sql += " TABLESPACE " + statement.getTablespace(); } } return new Sql[] { new UnparsedSql(sql) }; } } | CreateTableGenerator extends AbstractSqlGenerator<CreateTableStatement> { public Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { StringBuffer buffer = new StringBuffer(); buffer.append("CREATE TABLE ").append(database.escapeTableName(statement.getSchemaName(), statement.getTableName())).append(" "); buffer.append("("); boolean isSinglePrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() == 1; boolean isPrimaryKeyAutoIncrement = false; Iterator<String> columnIterator = statement.getColumns().iterator(); while (columnIterator.hasNext()) { String column = columnIterator.next(); buffer.append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), column)); buffer.append(" ").append(statement.getColumnTypes().get(column)); AutoIncrementConstraint autoIncrementConstraint = null; for (AutoIncrementConstraint currentAutoIncrementConstraint : statement.getAutoIncrementConstraints()) { if (column.equals(currentAutoIncrementConstraint.getColumnName())) { autoIncrementConstraint = currentAutoIncrementConstraint; break; } } boolean isAutoIncrementColumn = autoIncrementConstraint != null; boolean isPrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().contains(column); isPrimaryKeyAutoIncrement = isPrimaryKeyAutoIncrement || isPrimaryKeyColumn && isAutoIncrementColumn; if ((database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyColumn && isAutoIncrementColumn) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } buffer.append(" PRIMARY KEY AUTOINCREMENT"); } if (statement.getDefaultValue(column) != null) { Object defaultValue = statement.getDefaultValue(column); if (database instanceof MSSQLDatabase) { buffer.append(" CONSTRAINT ").append(((MSSQLDatabase) database).generateDefaultConstraintName(statement.getTableName(), column)); } buffer.append(" DEFAULT "); buffer.append(statement.getColumnTypes().get(column).convertObjectToString(defaultValue, database)); } if (isAutoIncrementColumn && ! (database instanceof SQLiteDatabase)) { if (database.supportsAutoIncrement()) { String autoIncrementClause = database.getAutoIncrementClause(autoIncrementConstraint.getStartWith(), autoIncrementConstraint.getIncrementBy()); if (!"".equals(autoIncrementClause)) { buffer.append(" ").append(autoIncrementClause); } } else { LogFactory.getLogger().warning(database.getTypeName()+" does not support autoincrement columns as request for "+(database.escapeTableName(statement.getSchemaName(), statement.getTableName()))); } } if (statement.getNotNullColumns().contains(column)) { buffer.append(" NOT NULL"); } else { if (database instanceof SybaseDatabase || database instanceof SybaseASADatabase || database instanceof MySQLDatabase) { if (database instanceof MySQLDatabase && statement.getColumnTypes().get(column).getDataTypeName().equalsIgnoreCase("timestamp")) { } else { buffer.append(" NULL"); } } } if (database instanceof InformixDatabase && isSinglePrimaryKeyColumn) { buffer.append(" PRIMARY KEY"); } if (columnIterator.hasNext()) { buffer.append(", "); } } buffer.append(","); if (!( (database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyAutoIncrement) && !((database instanceof InformixDatabase) && isSinglePrimaryKeyColumn )) { if (statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() > 0) { if (!(database instanceof InformixDatabase)) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } } buffer.append(" PRIMARY KEY ("); buffer.append(database.escapeColumnNameList(StringUtils.join(statement.getPrimaryKeyConstraint().getColumns(), ", "))); buffer.append(")"); if (database instanceof OracleDatabase && statement.getPrimaryKeyConstraint().getTablespace() != null) { buffer.append(" USING INDEX TABLESPACE "); buffer.append(statement.getPrimaryKeyConstraint().getTablespace()); } buffer.append(","); } } for (ForeignKeyConstraint fkConstraint : statement.getForeignKeyConstraints()) { if (!(database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } String referencesString = fkConstraint.getReferences(); if (!referencesString.contains(".") && database.getDefaultSchemaName() != null) { referencesString = database.getDefaultSchemaName()+"."+referencesString; } buffer.append(" FOREIGN KEY (") .append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), fkConstraint.getColumn())) .append(") REFERENCES ") .append(referencesString); if (fkConstraint.isDeleteCascade()) { buffer.append(" ON DELETE CASCADE"); } if ((database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } if (fkConstraint.isInitiallyDeferred()) { buffer.append(" INITIALLY DEFERRED"); } if (fkConstraint.isDeferrable()) { buffer.append(" DEFERRABLE"); } buffer.append(","); } for (UniqueConstraint uniqueConstraint : statement.getUniqueConstraints()) { if (uniqueConstraint.getConstraintName() != null && !constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(" UNIQUE ("); buffer.append(database.escapeColumnNameList(StringUtils.join(uniqueConstraint.getColumns(), ", "))); buffer.append(")"); if (uniqueConstraint.getConstraintName() != null && constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(","); } String sql = buffer.toString().replaceFirst(",\\s*$", "") + ")"; if (statement.getTablespace() != null && database.supportsTablespaces()) { if (database instanceof MSSQLDatabase || database instanceof SybaseASADatabase) { sql += " ON " + statement.getTablespace(); } else if (database instanceof DB2Database || database instanceof InformixDatabase) { sql += " IN " + statement.getTablespace(); } else { sql += " TABLESPACE " + statement.getTablespace(); } } return new Sql[] { new UnparsedSql(sql) }; } } | CreateTableGenerator extends AbstractSqlGenerator<CreateTableStatement> { public Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { StringBuffer buffer = new StringBuffer(); buffer.append("CREATE TABLE ").append(database.escapeTableName(statement.getSchemaName(), statement.getTableName())).append(" "); buffer.append("("); boolean isSinglePrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() == 1; boolean isPrimaryKeyAutoIncrement = false; Iterator<String> columnIterator = statement.getColumns().iterator(); while (columnIterator.hasNext()) { String column = columnIterator.next(); buffer.append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), column)); buffer.append(" ").append(statement.getColumnTypes().get(column)); AutoIncrementConstraint autoIncrementConstraint = null; for (AutoIncrementConstraint currentAutoIncrementConstraint : statement.getAutoIncrementConstraints()) { if (column.equals(currentAutoIncrementConstraint.getColumnName())) { autoIncrementConstraint = currentAutoIncrementConstraint; break; } } boolean isAutoIncrementColumn = autoIncrementConstraint != null; boolean isPrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().contains(column); isPrimaryKeyAutoIncrement = isPrimaryKeyAutoIncrement || isPrimaryKeyColumn && isAutoIncrementColumn; if ((database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyColumn && isAutoIncrementColumn) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } buffer.append(" PRIMARY KEY AUTOINCREMENT"); } if (statement.getDefaultValue(column) != null) { Object defaultValue = statement.getDefaultValue(column); if (database instanceof MSSQLDatabase) { buffer.append(" CONSTRAINT ").append(((MSSQLDatabase) database).generateDefaultConstraintName(statement.getTableName(), column)); } buffer.append(" DEFAULT "); buffer.append(statement.getColumnTypes().get(column).convertObjectToString(defaultValue, database)); } if (isAutoIncrementColumn && ! (database instanceof SQLiteDatabase)) { if (database.supportsAutoIncrement()) { String autoIncrementClause = database.getAutoIncrementClause(autoIncrementConstraint.getStartWith(), autoIncrementConstraint.getIncrementBy()); if (!"".equals(autoIncrementClause)) { buffer.append(" ").append(autoIncrementClause); } } else { LogFactory.getLogger().warning(database.getTypeName()+" does not support autoincrement columns as request for "+(database.escapeTableName(statement.getSchemaName(), statement.getTableName()))); } } if (statement.getNotNullColumns().contains(column)) { buffer.append(" NOT NULL"); } else { if (database instanceof SybaseDatabase || database instanceof SybaseASADatabase || database instanceof MySQLDatabase) { if (database instanceof MySQLDatabase && statement.getColumnTypes().get(column).getDataTypeName().equalsIgnoreCase("timestamp")) { } else { buffer.append(" NULL"); } } } if (database instanceof InformixDatabase && isSinglePrimaryKeyColumn) { buffer.append(" PRIMARY KEY"); } if (columnIterator.hasNext()) { buffer.append(", "); } } buffer.append(","); if (!( (database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyAutoIncrement) && !((database instanceof InformixDatabase) && isSinglePrimaryKeyColumn )) { if (statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() > 0) { if (!(database instanceof InformixDatabase)) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } } buffer.append(" PRIMARY KEY ("); buffer.append(database.escapeColumnNameList(StringUtils.join(statement.getPrimaryKeyConstraint().getColumns(), ", "))); buffer.append(")"); if (database instanceof OracleDatabase && statement.getPrimaryKeyConstraint().getTablespace() != null) { buffer.append(" USING INDEX TABLESPACE "); buffer.append(statement.getPrimaryKeyConstraint().getTablespace()); } buffer.append(","); } } for (ForeignKeyConstraint fkConstraint : statement.getForeignKeyConstraints()) { if (!(database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } String referencesString = fkConstraint.getReferences(); if (!referencesString.contains(".") && database.getDefaultSchemaName() != null) { referencesString = database.getDefaultSchemaName()+"."+referencesString; } buffer.append(" FOREIGN KEY (") .append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), fkConstraint.getColumn())) .append(") REFERENCES ") .append(referencesString); if (fkConstraint.isDeleteCascade()) { buffer.append(" ON DELETE CASCADE"); } if ((database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } if (fkConstraint.isInitiallyDeferred()) { buffer.append(" INITIALLY DEFERRED"); } if (fkConstraint.isDeferrable()) { buffer.append(" DEFERRABLE"); } buffer.append(","); } for (UniqueConstraint uniqueConstraint : statement.getUniqueConstraints()) { if (uniqueConstraint.getConstraintName() != null && !constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(" UNIQUE ("); buffer.append(database.escapeColumnNameList(StringUtils.join(uniqueConstraint.getColumns(), ", "))); buffer.append(")"); if (uniqueConstraint.getConstraintName() != null && constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(","); } String sql = buffer.toString().replaceFirst(",\\s*$", "") + ")"; if (statement.getTablespace() != null && database.supportsTablespaces()) { if (database instanceof MSSQLDatabase || database instanceof SybaseASADatabase) { sql += " ON " + statement.getTablespace(); } else if (database instanceof DB2Database || database instanceof InformixDatabase) { sql += " IN " + statement.getTablespace(); } else { sql += " TABLESPACE " + statement.getTablespace(); } } return new Sql[] { new UnparsedSql(sql) }; } ValidationErrors validate(CreateTableStatement createTableStatement, Database database, SqlGeneratorChain sqlGeneratorChain); Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain); } | CreateTableGenerator extends AbstractSqlGenerator<CreateTableStatement> { public Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { StringBuffer buffer = new StringBuffer(); buffer.append("CREATE TABLE ").append(database.escapeTableName(statement.getSchemaName(), statement.getTableName())).append(" "); buffer.append("("); boolean isSinglePrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() == 1; boolean isPrimaryKeyAutoIncrement = false; Iterator<String> columnIterator = statement.getColumns().iterator(); while (columnIterator.hasNext()) { String column = columnIterator.next(); buffer.append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), column)); buffer.append(" ").append(statement.getColumnTypes().get(column)); AutoIncrementConstraint autoIncrementConstraint = null; for (AutoIncrementConstraint currentAutoIncrementConstraint : statement.getAutoIncrementConstraints()) { if (column.equals(currentAutoIncrementConstraint.getColumnName())) { autoIncrementConstraint = currentAutoIncrementConstraint; break; } } boolean isAutoIncrementColumn = autoIncrementConstraint != null; boolean isPrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().contains(column); isPrimaryKeyAutoIncrement = isPrimaryKeyAutoIncrement || isPrimaryKeyColumn && isAutoIncrementColumn; if ((database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyColumn && isAutoIncrementColumn) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } buffer.append(" PRIMARY KEY AUTOINCREMENT"); } if (statement.getDefaultValue(column) != null) { Object defaultValue = statement.getDefaultValue(column); if (database instanceof MSSQLDatabase) { buffer.append(" CONSTRAINT ").append(((MSSQLDatabase) database).generateDefaultConstraintName(statement.getTableName(), column)); } buffer.append(" DEFAULT "); buffer.append(statement.getColumnTypes().get(column).convertObjectToString(defaultValue, database)); } if (isAutoIncrementColumn && ! (database instanceof SQLiteDatabase)) { if (database.supportsAutoIncrement()) { String autoIncrementClause = database.getAutoIncrementClause(autoIncrementConstraint.getStartWith(), autoIncrementConstraint.getIncrementBy()); if (!"".equals(autoIncrementClause)) { buffer.append(" ").append(autoIncrementClause); } } else { LogFactory.getLogger().warning(database.getTypeName()+" does not support autoincrement columns as request for "+(database.escapeTableName(statement.getSchemaName(), statement.getTableName()))); } } if (statement.getNotNullColumns().contains(column)) { buffer.append(" NOT NULL"); } else { if (database instanceof SybaseDatabase || database instanceof SybaseASADatabase || database instanceof MySQLDatabase) { if (database instanceof MySQLDatabase && statement.getColumnTypes().get(column).getDataTypeName().equalsIgnoreCase("timestamp")) { } else { buffer.append(" NULL"); } } } if (database instanceof InformixDatabase && isSinglePrimaryKeyColumn) { buffer.append(" PRIMARY KEY"); } if (columnIterator.hasNext()) { buffer.append(", "); } } buffer.append(","); if (!( (database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyAutoIncrement) && !((database instanceof InformixDatabase) && isSinglePrimaryKeyColumn )) { if (statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() > 0) { if (!(database instanceof InformixDatabase)) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } } buffer.append(" PRIMARY KEY ("); buffer.append(database.escapeColumnNameList(StringUtils.join(statement.getPrimaryKeyConstraint().getColumns(), ", "))); buffer.append(")"); if (database instanceof OracleDatabase && statement.getPrimaryKeyConstraint().getTablespace() != null) { buffer.append(" USING INDEX TABLESPACE "); buffer.append(statement.getPrimaryKeyConstraint().getTablespace()); } buffer.append(","); } } for (ForeignKeyConstraint fkConstraint : statement.getForeignKeyConstraints()) { if (!(database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } String referencesString = fkConstraint.getReferences(); if (!referencesString.contains(".") && database.getDefaultSchemaName() != null) { referencesString = database.getDefaultSchemaName()+"."+referencesString; } buffer.append(" FOREIGN KEY (") .append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), fkConstraint.getColumn())) .append(") REFERENCES ") .append(referencesString); if (fkConstraint.isDeleteCascade()) { buffer.append(" ON DELETE CASCADE"); } if ((database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } if (fkConstraint.isInitiallyDeferred()) { buffer.append(" INITIALLY DEFERRED"); } if (fkConstraint.isDeferrable()) { buffer.append(" DEFERRABLE"); } buffer.append(","); } for (UniqueConstraint uniqueConstraint : statement.getUniqueConstraints()) { if (uniqueConstraint.getConstraintName() != null && !constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(" UNIQUE ("); buffer.append(database.escapeColumnNameList(StringUtils.join(uniqueConstraint.getColumns(), ", "))); buffer.append(")"); if (uniqueConstraint.getConstraintName() != null && constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(","); } String sql = buffer.toString().replaceFirst(",\\s*$", "") + ")"; if (statement.getTablespace() != null && database.supportsTablespaces()) { if (database instanceof MSSQLDatabase || database instanceof SybaseASADatabase) { sql += " ON " + statement.getTablespace(); } else if (database instanceof DB2Database || database instanceof InformixDatabase) { sql += " IN " + statement.getTablespace(); } else { sql += " TABLESPACE " + statement.getTablespace(); } } return new Sql[] { new UnparsedSql(sql) }; } ValidationErrors validate(CreateTableStatement createTableStatement, Database database, SqlGeneratorChain sqlGeneratorChain); Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain); } |
@Test public void testAutoIncrementStartWithIncrementBySybaseDatabase() throws Exception { for (Database database : TestContext.getInstance().getAllDatabases()) { if (database instanceof SybaseDatabase) { CreateTableStatement statement = new CreateTableStatement(SCHEMA_NAME, TABLE_NAME); statement.addColumn( COLUMN_NAME1, TypeConverterFactory.getInstance().findTypeConverter(database).getDataType("BIGINT", true), new AutoIncrementConstraint(COLUMN_NAME1, BigInteger.valueOf(2), BigInteger.TEN) ); Sql[] generatedSql = this.generatorUnderTest.generateSql(statement, database, null); assertEquals("CREATE TABLE [SCHEMA_NAME].[TABLE_NAME] ([COLUMN1_NAME] BIGINT IDENTITY NULL)", generatedSql[0].toSql()); } } } | public Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { StringBuffer buffer = new StringBuffer(); buffer.append("CREATE TABLE ").append(database.escapeTableName(statement.getSchemaName(), statement.getTableName())).append(" "); buffer.append("("); boolean isSinglePrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() == 1; boolean isPrimaryKeyAutoIncrement = false; Iterator<String> columnIterator = statement.getColumns().iterator(); while (columnIterator.hasNext()) { String column = columnIterator.next(); buffer.append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), column)); buffer.append(" ").append(statement.getColumnTypes().get(column)); AutoIncrementConstraint autoIncrementConstraint = null; for (AutoIncrementConstraint currentAutoIncrementConstraint : statement.getAutoIncrementConstraints()) { if (column.equals(currentAutoIncrementConstraint.getColumnName())) { autoIncrementConstraint = currentAutoIncrementConstraint; break; } } boolean isAutoIncrementColumn = autoIncrementConstraint != null; boolean isPrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().contains(column); isPrimaryKeyAutoIncrement = isPrimaryKeyAutoIncrement || isPrimaryKeyColumn && isAutoIncrementColumn; if ((database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyColumn && isAutoIncrementColumn) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } buffer.append(" PRIMARY KEY AUTOINCREMENT"); } if (statement.getDefaultValue(column) != null) { Object defaultValue = statement.getDefaultValue(column); if (database instanceof MSSQLDatabase) { buffer.append(" CONSTRAINT ").append(((MSSQLDatabase) database).generateDefaultConstraintName(statement.getTableName(), column)); } buffer.append(" DEFAULT "); buffer.append(statement.getColumnTypes().get(column).convertObjectToString(defaultValue, database)); } if (isAutoIncrementColumn && ! (database instanceof SQLiteDatabase)) { if (database.supportsAutoIncrement()) { String autoIncrementClause = database.getAutoIncrementClause(autoIncrementConstraint.getStartWith(), autoIncrementConstraint.getIncrementBy()); if (!"".equals(autoIncrementClause)) { buffer.append(" ").append(autoIncrementClause); } } else { LogFactory.getLogger().warning(database.getTypeName()+" does not support autoincrement columns as request for "+(database.escapeTableName(statement.getSchemaName(), statement.getTableName()))); } } if (statement.getNotNullColumns().contains(column)) { buffer.append(" NOT NULL"); } else { if (database instanceof SybaseDatabase || database instanceof SybaseASADatabase || database instanceof MySQLDatabase) { if (database instanceof MySQLDatabase && statement.getColumnTypes().get(column).getDataTypeName().equalsIgnoreCase("timestamp")) { } else { buffer.append(" NULL"); } } } if (database instanceof InformixDatabase && isSinglePrimaryKeyColumn) { buffer.append(" PRIMARY KEY"); } if (columnIterator.hasNext()) { buffer.append(", "); } } buffer.append(","); if (!( (database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyAutoIncrement) && !((database instanceof InformixDatabase) && isSinglePrimaryKeyColumn )) { if (statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() > 0) { if (!(database instanceof InformixDatabase)) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } } buffer.append(" PRIMARY KEY ("); buffer.append(database.escapeColumnNameList(StringUtils.join(statement.getPrimaryKeyConstraint().getColumns(), ", "))); buffer.append(")"); if (database instanceof OracleDatabase && statement.getPrimaryKeyConstraint().getTablespace() != null) { buffer.append(" USING INDEX TABLESPACE "); buffer.append(statement.getPrimaryKeyConstraint().getTablespace()); } buffer.append(","); } } for (ForeignKeyConstraint fkConstraint : statement.getForeignKeyConstraints()) { if (!(database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } String referencesString = fkConstraint.getReferences(); if (!referencesString.contains(".") && database.getDefaultSchemaName() != null) { referencesString = database.getDefaultSchemaName()+"."+referencesString; } buffer.append(" FOREIGN KEY (") .append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), fkConstraint.getColumn())) .append(") REFERENCES ") .append(referencesString); if (fkConstraint.isDeleteCascade()) { buffer.append(" ON DELETE CASCADE"); } if ((database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } if (fkConstraint.isInitiallyDeferred()) { buffer.append(" INITIALLY DEFERRED"); } if (fkConstraint.isDeferrable()) { buffer.append(" DEFERRABLE"); } buffer.append(","); } for (UniqueConstraint uniqueConstraint : statement.getUniqueConstraints()) { if (uniqueConstraint.getConstraintName() != null && !constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(" UNIQUE ("); buffer.append(database.escapeColumnNameList(StringUtils.join(uniqueConstraint.getColumns(), ", "))); buffer.append(")"); if (uniqueConstraint.getConstraintName() != null && constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(","); } String sql = buffer.toString().replaceFirst(",\\s*$", "") + ")"; if (statement.getTablespace() != null && database.supportsTablespaces()) { if (database instanceof MSSQLDatabase || database instanceof SybaseASADatabase) { sql += " ON " + statement.getTablespace(); } else if (database instanceof DB2Database || database instanceof InformixDatabase) { sql += " IN " + statement.getTablespace(); } else { sql += " TABLESPACE " + statement.getTablespace(); } } return new Sql[] { new UnparsedSql(sql) }; } | CreateTableGenerator extends AbstractSqlGenerator<CreateTableStatement> { public Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { StringBuffer buffer = new StringBuffer(); buffer.append("CREATE TABLE ").append(database.escapeTableName(statement.getSchemaName(), statement.getTableName())).append(" "); buffer.append("("); boolean isSinglePrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() == 1; boolean isPrimaryKeyAutoIncrement = false; Iterator<String> columnIterator = statement.getColumns().iterator(); while (columnIterator.hasNext()) { String column = columnIterator.next(); buffer.append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), column)); buffer.append(" ").append(statement.getColumnTypes().get(column)); AutoIncrementConstraint autoIncrementConstraint = null; for (AutoIncrementConstraint currentAutoIncrementConstraint : statement.getAutoIncrementConstraints()) { if (column.equals(currentAutoIncrementConstraint.getColumnName())) { autoIncrementConstraint = currentAutoIncrementConstraint; break; } } boolean isAutoIncrementColumn = autoIncrementConstraint != null; boolean isPrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().contains(column); isPrimaryKeyAutoIncrement = isPrimaryKeyAutoIncrement || isPrimaryKeyColumn && isAutoIncrementColumn; if ((database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyColumn && isAutoIncrementColumn) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } buffer.append(" PRIMARY KEY AUTOINCREMENT"); } if (statement.getDefaultValue(column) != null) { Object defaultValue = statement.getDefaultValue(column); if (database instanceof MSSQLDatabase) { buffer.append(" CONSTRAINT ").append(((MSSQLDatabase) database).generateDefaultConstraintName(statement.getTableName(), column)); } buffer.append(" DEFAULT "); buffer.append(statement.getColumnTypes().get(column).convertObjectToString(defaultValue, database)); } if (isAutoIncrementColumn && ! (database instanceof SQLiteDatabase)) { if (database.supportsAutoIncrement()) { String autoIncrementClause = database.getAutoIncrementClause(autoIncrementConstraint.getStartWith(), autoIncrementConstraint.getIncrementBy()); if (!"".equals(autoIncrementClause)) { buffer.append(" ").append(autoIncrementClause); } } else { LogFactory.getLogger().warning(database.getTypeName()+" does not support autoincrement columns as request for "+(database.escapeTableName(statement.getSchemaName(), statement.getTableName()))); } } if (statement.getNotNullColumns().contains(column)) { buffer.append(" NOT NULL"); } else { if (database instanceof SybaseDatabase || database instanceof SybaseASADatabase || database instanceof MySQLDatabase) { if (database instanceof MySQLDatabase && statement.getColumnTypes().get(column).getDataTypeName().equalsIgnoreCase("timestamp")) { } else { buffer.append(" NULL"); } } } if (database instanceof InformixDatabase && isSinglePrimaryKeyColumn) { buffer.append(" PRIMARY KEY"); } if (columnIterator.hasNext()) { buffer.append(", "); } } buffer.append(","); if (!( (database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyAutoIncrement) && !((database instanceof InformixDatabase) && isSinglePrimaryKeyColumn )) { if (statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() > 0) { if (!(database instanceof InformixDatabase)) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } } buffer.append(" PRIMARY KEY ("); buffer.append(database.escapeColumnNameList(StringUtils.join(statement.getPrimaryKeyConstraint().getColumns(), ", "))); buffer.append(")"); if (database instanceof OracleDatabase && statement.getPrimaryKeyConstraint().getTablespace() != null) { buffer.append(" USING INDEX TABLESPACE "); buffer.append(statement.getPrimaryKeyConstraint().getTablespace()); } buffer.append(","); } } for (ForeignKeyConstraint fkConstraint : statement.getForeignKeyConstraints()) { if (!(database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } String referencesString = fkConstraint.getReferences(); if (!referencesString.contains(".") && database.getDefaultSchemaName() != null) { referencesString = database.getDefaultSchemaName()+"."+referencesString; } buffer.append(" FOREIGN KEY (") .append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), fkConstraint.getColumn())) .append(") REFERENCES ") .append(referencesString); if (fkConstraint.isDeleteCascade()) { buffer.append(" ON DELETE CASCADE"); } if ((database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } if (fkConstraint.isInitiallyDeferred()) { buffer.append(" INITIALLY DEFERRED"); } if (fkConstraint.isDeferrable()) { buffer.append(" DEFERRABLE"); } buffer.append(","); } for (UniqueConstraint uniqueConstraint : statement.getUniqueConstraints()) { if (uniqueConstraint.getConstraintName() != null && !constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(" UNIQUE ("); buffer.append(database.escapeColumnNameList(StringUtils.join(uniqueConstraint.getColumns(), ", "))); buffer.append(")"); if (uniqueConstraint.getConstraintName() != null && constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(","); } String sql = buffer.toString().replaceFirst(",\\s*$", "") + ")"; if (statement.getTablespace() != null && database.supportsTablespaces()) { if (database instanceof MSSQLDatabase || database instanceof SybaseASADatabase) { sql += " ON " + statement.getTablespace(); } else if (database instanceof DB2Database || database instanceof InformixDatabase) { sql += " IN " + statement.getTablespace(); } else { sql += " TABLESPACE " + statement.getTablespace(); } } return new Sql[] { new UnparsedSql(sql) }; } } | CreateTableGenerator extends AbstractSqlGenerator<CreateTableStatement> { public Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { StringBuffer buffer = new StringBuffer(); buffer.append("CREATE TABLE ").append(database.escapeTableName(statement.getSchemaName(), statement.getTableName())).append(" "); buffer.append("("); boolean isSinglePrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() == 1; boolean isPrimaryKeyAutoIncrement = false; Iterator<String> columnIterator = statement.getColumns().iterator(); while (columnIterator.hasNext()) { String column = columnIterator.next(); buffer.append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), column)); buffer.append(" ").append(statement.getColumnTypes().get(column)); AutoIncrementConstraint autoIncrementConstraint = null; for (AutoIncrementConstraint currentAutoIncrementConstraint : statement.getAutoIncrementConstraints()) { if (column.equals(currentAutoIncrementConstraint.getColumnName())) { autoIncrementConstraint = currentAutoIncrementConstraint; break; } } boolean isAutoIncrementColumn = autoIncrementConstraint != null; boolean isPrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().contains(column); isPrimaryKeyAutoIncrement = isPrimaryKeyAutoIncrement || isPrimaryKeyColumn && isAutoIncrementColumn; if ((database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyColumn && isAutoIncrementColumn) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } buffer.append(" PRIMARY KEY AUTOINCREMENT"); } if (statement.getDefaultValue(column) != null) { Object defaultValue = statement.getDefaultValue(column); if (database instanceof MSSQLDatabase) { buffer.append(" CONSTRAINT ").append(((MSSQLDatabase) database).generateDefaultConstraintName(statement.getTableName(), column)); } buffer.append(" DEFAULT "); buffer.append(statement.getColumnTypes().get(column).convertObjectToString(defaultValue, database)); } if (isAutoIncrementColumn && ! (database instanceof SQLiteDatabase)) { if (database.supportsAutoIncrement()) { String autoIncrementClause = database.getAutoIncrementClause(autoIncrementConstraint.getStartWith(), autoIncrementConstraint.getIncrementBy()); if (!"".equals(autoIncrementClause)) { buffer.append(" ").append(autoIncrementClause); } } else { LogFactory.getLogger().warning(database.getTypeName()+" does not support autoincrement columns as request for "+(database.escapeTableName(statement.getSchemaName(), statement.getTableName()))); } } if (statement.getNotNullColumns().contains(column)) { buffer.append(" NOT NULL"); } else { if (database instanceof SybaseDatabase || database instanceof SybaseASADatabase || database instanceof MySQLDatabase) { if (database instanceof MySQLDatabase && statement.getColumnTypes().get(column).getDataTypeName().equalsIgnoreCase("timestamp")) { } else { buffer.append(" NULL"); } } } if (database instanceof InformixDatabase && isSinglePrimaryKeyColumn) { buffer.append(" PRIMARY KEY"); } if (columnIterator.hasNext()) { buffer.append(", "); } } buffer.append(","); if (!( (database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyAutoIncrement) && !((database instanceof InformixDatabase) && isSinglePrimaryKeyColumn )) { if (statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() > 0) { if (!(database instanceof InformixDatabase)) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } } buffer.append(" PRIMARY KEY ("); buffer.append(database.escapeColumnNameList(StringUtils.join(statement.getPrimaryKeyConstraint().getColumns(), ", "))); buffer.append(")"); if (database instanceof OracleDatabase && statement.getPrimaryKeyConstraint().getTablespace() != null) { buffer.append(" USING INDEX TABLESPACE "); buffer.append(statement.getPrimaryKeyConstraint().getTablespace()); } buffer.append(","); } } for (ForeignKeyConstraint fkConstraint : statement.getForeignKeyConstraints()) { if (!(database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } String referencesString = fkConstraint.getReferences(); if (!referencesString.contains(".") && database.getDefaultSchemaName() != null) { referencesString = database.getDefaultSchemaName()+"."+referencesString; } buffer.append(" FOREIGN KEY (") .append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), fkConstraint.getColumn())) .append(") REFERENCES ") .append(referencesString); if (fkConstraint.isDeleteCascade()) { buffer.append(" ON DELETE CASCADE"); } if ((database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } if (fkConstraint.isInitiallyDeferred()) { buffer.append(" INITIALLY DEFERRED"); } if (fkConstraint.isDeferrable()) { buffer.append(" DEFERRABLE"); } buffer.append(","); } for (UniqueConstraint uniqueConstraint : statement.getUniqueConstraints()) { if (uniqueConstraint.getConstraintName() != null && !constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(" UNIQUE ("); buffer.append(database.escapeColumnNameList(StringUtils.join(uniqueConstraint.getColumns(), ", "))); buffer.append(")"); if (uniqueConstraint.getConstraintName() != null && constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(","); } String sql = buffer.toString().replaceFirst(",\\s*$", "") + ")"; if (statement.getTablespace() != null && database.supportsTablespaces()) { if (database instanceof MSSQLDatabase || database instanceof SybaseASADatabase) { sql += " ON " + statement.getTablespace(); } else if (database instanceof DB2Database || database instanceof InformixDatabase) { sql += " IN " + statement.getTablespace(); } else { sql += " TABLESPACE " + statement.getTablespace(); } } return new Sql[] { new UnparsedSql(sql) }; } } | CreateTableGenerator extends AbstractSqlGenerator<CreateTableStatement> { public Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { StringBuffer buffer = new StringBuffer(); buffer.append("CREATE TABLE ").append(database.escapeTableName(statement.getSchemaName(), statement.getTableName())).append(" "); buffer.append("("); boolean isSinglePrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() == 1; boolean isPrimaryKeyAutoIncrement = false; Iterator<String> columnIterator = statement.getColumns().iterator(); while (columnIterator.hasNext()) { String column = columnIterator.next(); buffer.append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), column)); buffer.append(" ").append(statement.getColumnTypes().get(column)); AutoIncrementConstraint autoIncrementConstraint = null; for (AutoIncrementConstraint currentAutoIncrementConstraint : statement.getAutoIncrementConstraints()) { if (column.equals(currentAutoIncrementConstraint.getColumnName())) { autoIncrementConstraint = currentAutoIncrementConstraint; break; } } boolean isAutoIncrementColumn = autoIncrementConstraint != null; boolean isPrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().contains(column); isPrimaryKeyAutoIncrement = isPrimaryKeyAutoIncrement || isPrimaryKeyColumn && isAutoIncrementColumn; if ((database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyColumn && isAutoIncrementColumn) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } buffer.append(" PRIMARY KEY AUTOINCREMENT"); } if (statement.getDefaultValue(column) != null) { Object defaultValue = statement.getDefaultValue(column); if (database instanceof MSSQLDatabase) { buffer.append(" CONSTRAINT ").append(((MSSQLDatabase) database).generateDefaultConstraintName(statement.getTableName(), column)); } buffer.append(" DEFAULT "); buffer.append(statement.getColumnTypes().get(column).convertObjectToString(defaultValue, database)); } if (isAutoIncrementColumn && ! (database instanceof SQLiteDatabase)) { if (database.supportsAutoIncrement()) { String autoIncrementClause = database.getAutoIncrementClause(autoIncrementConstraint.getStartWith(), autoIncrementConstraint.getIncrementBy()); if (!"".equals(autoIncrementClause)) { buffer.append(" ").append(autoIncrementClause); } } else { LogFactory.getLogger().warning(database.getTypeName()+" does not support autoincrement columns as request for "+(database.escapeTableName(statement.getSchemaName(), statement.getTableName()))); } } if (statement.getNotNullColumns().contains(column)) { buffer.append(" NOT NULL"); } else { if (database instanceof SybaseDatabase || database instanceof SybaseASADatabase || database instanceof MySQLDatabase) { if (database instanceof MySQLDatabase && statement.getColumnTypes().get(column).getDataTypeName().equalsIgnoreCase("timestamp")) { } else { buffer.append(" NULL"); } } } if (database instanceof InformixDatabase && isSinglePrimaryKeyColumn) { buffer.append(" PRIMARY KEY"); } if (columnIterator.hasNext()) { buffer.append(", "); } } buffer.append(","); if (!( (database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyAutoIncrement) && !((database instanceof InformixDatabase) && isSinglePrimaryKeyColumn )) { if (statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() > 0) { if (!(database instanceof InformixDatabase)) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } } buffer.append(" PRIMARY KEY ("); buffer.append(database.escapeColumnNameList(StringUtils.join(statement.getPrimaryKeyConstraint().getColumns(), ", "))); buffer.append(")"); if (database instanceof OracleDatabase && statement.getPrimaryKeyConstraint().getTablespace() != null) { buffer.append(" USING INDEX TABLESPACE "); buffer.append(statement.getPrimaryKeyConstraint().getTablespace()); } buffer.append(","); } } for (ForeignKeyConstraint fkConstraint : statement.getForeignKeyConstraints()) { if (!(database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } String referencesString = fkConstraint.getReferences(); if (!referencesString.contains(".") && database.getDefaultSchemaName() != null) { referencesString = database.getDefaultSchemaName()+"."+referencesString; } buffer.append(" FOREIGN KEY (") .append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), fkConstraint.getColumn())) .append(") REFERENCES ") .append(referencesString); if (fkConstraint.isDeleteCascade()) { buffer.append(" ON DELETE CASCADE"); } if ((database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } if (fkConstraint.isInitiallyDeferred()) { buffer.append(" INITIALLY DEFERRED"); } if (fkConstraint.isDeferrable()) { buffer.append(" DEFERRABLE"); } buffer.append(","); } for (UniqueConstraint uniqueConstraint : statement.getUniqueConstraints()) { if (uniqueConstraint.getConstraintName() != null && !constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(" UNIQUE ("); buffer.append(database.escapeColumnNameList(StringUtils.join(uniqueConstraint.getColumns(), ", "))); buffer.append(")"); if (uniqueConstraint.getConstraintName() != null && constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(","); } String sql = buffer.toString().replaceFirst(",\\s*$", "") + ")"; if (statement.getTablespace() != null && database.supportsTablespaces()) { if (database instanceof MSSQLDatabase || database instanceof SybaseASADatabase) { sql += " ON " + statement.getTablespace(); } else if (database instanceof DB2Database || database instanceof InformixDatabase) { sql += " IN " + statement.getTablespace(); } else { sql += " TABLESPACE " + statement.getTablespace(); } } return new Sql[] { new UnparsedSql(sql) }; } ValidationErrors validate(CreateTableStatement createTableStatement, Database database, SqlGeneratorChain sqlGeneratorChain); Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain); } | CreateTableGenerator extends AbstractSqlGenerator<CreateTableStatement> { public Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { StringBuffer buffer = new StringBuffer(); buffer.append("CREATE TABLE ").append(database.escapeTableName(statement.getSchemaName(), statement.getTableName())).append(" "); buffer.append("("); boolean isSinglePrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() == 1; boolean isPrimaryKeyAutoIncrement = false; Iterator<String> columnIterator = statement.getColumns().iterator(); while (columnIterator.hasNext()) { String column = columnIterator.next(); buffer.append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), column)); buffer.append(" ").append(statement.getColumnTypes().get(column)); AutoIncrementConstraint autoIncrementConstraint = null; for (AutoIncrementConstraint currentAutoIncrementConstraint : statement.getAutoIncrementConstraints()) { if (column.equals(currentAutoIncrementConstraint.getColumnName())) { autoIncrementConstraint = currentAutoIncrementConstraint; break; } } boolean isAutoIncrementColumn = autoIncrementConstraint != null; boolean isPrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().contains(column); isPrimaryKeyAutoIncrement = isPrimaryKeyAutoIncrement || isPrimaryKeyColumn && isAutoIncrementColumn; if ((database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyColumn && isAutoIncrementColumn) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } buffer.append(" PRIMARY KEY AUTOINCREMENT"); } if (statement.getDefaultValue(column) != null) { Object defaultValue = statement.getDefaultValue(column); if (database instanceof MSSQLDatabase) { buffer.append(" CONSTRAINT ").append(((MSSQLDatabase) database).generateDefaultConstraintName(statement.getTableName(), column)); } buffer.append(" DEFAULT "); buffer.append(statement.getColumnTypes().get(column).convertObjectToString(defaultValue, database)); } if (isAutoIncrementColumn && ! (database instanceof SQLiteDatabase)) { if (database.supportsAutoIncrement()) { String autoIncrementClause = database.getAutoIncrementClause(autoIncrementConstraint.getStartWith(), autoIncrementConstraint.getIncrementBy()); if (!"".equals(autoIncrementClause)) { buffer.append(" ").append(autoIncrementClause); } } else { LogFactory.getLogger().warning(database.getTypeName()+" does not support autoincrement columns as request for "+(database.escapeTableName(statement.getSchemaName(), statement.getTableName()))); } } if (statement.getNotNullColumns().contains(column)) { buffer.append(" NOT NULL"); } else { if (database instanceof SybaseDatabase || database instanceof SybaseASADatabase || database instanceof MySQLDatabase) { if (database instanceof MySQLDatabase && statement.getColumnTypes().get(column).getDataTypeName().equalsIgnoreCase("timestamp")) { } else { buffer.append(" NULL"); } } } if (database instanceof InformixDatabase && isSinglePrimaryKeyColumn) { buffer.append(" PRIMARY KEY"); } if (columnIterator.hasNext()) { buffer.append(", "); } } buffer.append(","); if (!( (database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyAutoIncrement) && !((database instanceof InformixDatabase) && isSinglePrimaryKeyColumn )) { if (statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() > 0) { if (!(database instanceof InformixDatabase)) { String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName()); if (pkName == null) { pkName = database.generatePrimaryKeyName(statement.getTableName()); } if (pkName != null) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(pkName)); } } buffer.append(" PRIMARY KEY ("); buffer.append(database.escapeColumnNameList(StringUtils.join(statement.getPrimaryKeyConstraint().getColumns(), ", "))); buffer.append(")"); if (database instanceof OracleDatabase && statement.getPrimaryKeyConstraint().getTablespace() != null) { buffer.append(" USING INDEX TABLESPACE "); buffer.append(statement.getPrimaryKeyConstraint().getTablespace()); } buffer.append(","); } } for (ForeignKeyConstraint fkConstraint : statement.getForeignKeyConstraints()) { if (!(database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } String referencesString = fkConstraint.getReferences(); if (!referencesString.contains(".") && database.getDefaultSchemaName() != null) { referencesString = database.getDefaultSchemaName()+"."+referencesString; } buffer.append(" FOREIGN KEY (") .append(database.escapeColumnName(statement.getSchemaName(), statement.getTableName(), fkConstraint.getColumn())) .append(") REFERENCES ") .append(referencesString); if (fkConstraint.isDeleteCascade()) { buffer.append(" ON DELETE CASCADE"); } if ((database instanceof InformixDatabase)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName())); } if (fkConstraint.isInitiallyDeferred()) { buffer.append(" INITIALLY DEFERRED"); } if (fkConstraint.isDeferrable()) { buffer.append(" DEFERRABLE"); } buffer.append(","); } for (UniqueConstraint uniqueConstraint : statement.getUniqueConstraints()) { if (uniqueConstraint.getConstraintName() != null && !constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(" UNIQUE ("); buffer.append(database.escapeColumnNameList(StringUtils.join(uniqueConstraint.getColumns(), ", "))); buffer.append(")"); if (uniqueConstraint.getConstraintName() != null && constraintNameAfterUnique(database)) { buffer.append(" CONSTRAINT "); buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName())); } buffer.append(","); } String sql = buffer.toString().replaceFirst(",\\s*$", "") + ")"; if (statement.getTablespace() != null && database.supportsTablespaces()) { if (database instanceof MSSQLDatabase || database instanceof SybaseASADatabase) { sql += " ON " + statement.getTablespace(); } else if (database instanceof DB2Database || database instanceof InformixDatabase) { sql += " IN " + statement.getTablespace(); } else { sql += " TABLESPACE " + statement.getTablespace(); } } return new Sql[] { new UnparsedSql(sql) }; } ValidationErrors validate(CreateTableStatement createTableStatement, Database database, SqlGeneratorChain sqlGeneratorChain); Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain); } |
@Test public void testGenerateSqlForDefaultSchema() { GetViewDefinitionGeneratorSybase generator = new GetViewDefinitionGeneratorSybase(); GetViewDefinitionStatement statement = new GetViewDefinitionStatement(null, "view_name"); Sql[] sql = generator.generateSql(statement, new SybaseDatabase(), null); assertEquals(1, sql.length); assertEquals("select text from syscomments where id = object_id('dbo.view_name') order by colid", sql[0].toSql()); } | @Override public Sql[] generateSql(GetViewDefinitionStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { try { String sql = "select text from syscomments where id = object_id('" + database.convertRequestedSchemaToSchema(statement.getSchemaName()) + "." + statement.getViewName() + "') order by colid"; return new Sql[]{ new UnparsedSql(sql) }; } catch (DatabaseException e) { throw new UnexpectedLiquibaseException(e); } } | GetViewDefinitionGeneratorSybase extends GetViewDefinitionGenerator { @Override public Sql[] generateSql(GetViewDefinitionStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { try { String sql = "select text from syscomments where id = object_id('" + database.convertRequestedSchemaToSchema(statement.getSchemaName()) + "." + statement.getViewName() + "') order by colid"; return new Sql[]{ new UnparsedSql(sql) }; } catch (DatabaseException e) { throw new UnexpectedLiquibaseException(e); } } } | GetViewDefinitionGeneratorSybase extends GetViewDefinitionGenerator { @Override public Sql[] generateSql(GetViewDefinitionStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { try { String sql = "select text from syscomments where id = object_id('" + database.convertRequestedSchemaToSchema(statement.getSchemaName()) + "." + statement.getViewName() + "') order by colid"; return new Sql[]{ new UnparsedSql(sql) }; } catch (DatabaseException e) { throw new UnexpectedLiquibaseException(e); } } } | GetViewDefinitionGeneratorSybase extends GetViewDefinitionGenerator { @Override public Sql[] generateSql(GetViewDefinitionStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { try { String sql = "select text from syscomments where id = object_id('" + database.convertRequestedSchemaToSchema(statement.getSchemaName()) + "." + statement.getViewName() + "') order by colid"; return new Sql[]{ new UnparsedSql(sql) }; } catch (DatabaseException e) { throw new UnexpectedLiquibaseException(e); } } @Override int getPriority(); @Override boolean supports(GetViewDefinitionStatement statement, Database database); @Override Sql[] generateSql(GetViewDefinitionStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain); } | GetViewDefinitionGeneratorSybase extends GetViewDefinitionGenerator { @Override public Sql[] generateSql(GetViewDefinitionStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { try { String sql = "select text from syscomments where id = object_id('" + database.convertRequestedSchemaToSchema(statement.getSchemaName()) + "." + statement.getViewName() + "') order by colid"; return new Sql[]{ new UnparsedSql(sql) }; } catch (DatabaseException e) { throw new UnexpectedLiquibaseException(e); } } @Override int getPriority(); @Override boolean supports(GetViewDefinitionStatement statement, Database database); @Override Sql[] generateSql(GetViewDefinitionStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain); } |
@Test public void splitWithX() { String testString = "insert into datatable (col) values ('a value with a ;') X\n"+ "insert into datatable (col) values ('another value with a ;') X"; String[] strings = StringUtils.splitSQL(testString, "X"); assertEquals(2, strings.length); assertEquals("insert into datatable (col) values ('a value with a ;')", strings[0]); assertEquals("insert into datatable (col) values ('another value with a ;')", strings[1]); } | public static String[] splitSQL(String multiLineSQL, String endDelimiter) { if (endDelimiter == null) { endDelimiter = ";\\s*\n|;$|\n[gG][oO]\\s*\n|\n[Gg][oO]\\s*$"; } else { if (endDelimiter.equalsIgnoreCase("go")) { endDelimiter = "\n[gG][oO]\\s*\n|\n[Gg][oO]\\s*$"; } } String[] initialSplit = multiLineSQL.split(endDelimiter); List<String> strings = new ArrayList<String>(); for (String anInitialSplit : initialSplit) { String singleLineSQL = anInitialSplit.trim(); if (singleLineSQL.length() > 0) { strings.add(singleLineSQL); } } return strings.toArray(new String[strings.size()]); } | StringUtils { public static String[] splitSQL(String multiLineSQL, String endDelimiter) { if (endDelimiter == null) { endDelimiter = ";\\s*\n|;$|\n[gG][oO]\\s*\n|\n[Gg][oO]\\s*$"; } else { if (endDelimiter.equalsIgnoreCase("go")) { endDelimiter = "\n[gG][oO]\\s*\n|\n[Gg][oO]\\s*$"; } } String[] initialSplit = multiLineSQL.split(endDelimiter); List<String> strings = new ArrayList<String>(); for (String anInitialSplit : initialSplit) { String singleLineSQL = anInitialSplit.trim(); if (singleLineSQL.length() > 0) { strings.add(singleLineSQL); } } return strings.toArray(new String[strings.size()]); } } | StringUtils { public static String[] splitSQL(String multiLineSQL, String endDelimiter) { if (endDelimiter == null) { endDelimiter = ";\\s*\n|;$|\n[gG][oO]\\s*\n|\n[Gg][oO]\\s*$"; } else { if (endDelimiter.equalsIgnoreCase("go")) { endDelimiter = "\n[gG][oO]\\s*\n|\n[Gg][oO]\\s*$"; } } String[] initialSplit = multiLineSQL.split(endDelimiter); List<String> strings = new ArrayList<String>(); for (String anInitialSplit : initialSplit) { String singleLineSQL = anInitialSplit.trim(); if (singleLineSQL.length() > 0) { strings.add(singleLineSQL); } } return strings.toArray(new String[strings.size()]); } } | StringUtils { public static String[] splitSQL(String multiLineSQL, String endDelimiter) { if (endDelimiter == null) { endDelimiter = ";\\s*\n|;$|\n[gG][oO]\\s*\n|\n[Gg][oO]\\s*$"; } else { if (endDelimiter.equalsIgnoreCase("go")) { endDelimiter = "\n[gG][oO]\\s*\n|\n[Gg][oO]\\s*$"; } } String[] initialSplit = multiLineSQL.split(endDelimiter); List<String> strings = new ArrayList<String>(); for (String anInitialSplit : initialSplit) { String singleLineSQL = anInitialSplit.trim(); if (singleLineSQL.length() > 0) { strings.add(singleLineSQL); } } return strings.toArray(new String[strings.size()]); } static String trimToEmpty(String string); static String trimToNull(String string); static String[] processMutliLineSQL(String multiLineSQL,boolean stripComments, boolean splitStatements, String endDelimiter); static String[] splitSQL(String multiLineSQL, String endDelimiter); static String stripComments(String multiLineSQL); static String join(String[] array, String delimiter); static String join(Collection<String> collection, String delimiter); static List<String> splitAndTrim(String s, String regex); static String repeat(String string, int times); static String join(Integer[] array, String delimiter); static String join(int[] array, String delimiter); } | StringUtils { public static String[] splitSQL(String multiLineSQL, String endDelimiter) { if (endDelimiter == null) { endDelimiter = ";\\s*\n|;$|\n[gG][oO]\\s*\n|\n[Gg][oO]\\s*$"; } else { if (endDelimiter.equalsIgnoreCase("go")) { endDelimiter = "\n[gG][oO]\\s*\n|\n[Gg][oO]\\s*$"; } } String[] initialSplit = multiLineSQL.split(endDelimiter); List<String> strings = new ArrayList<String>(); for (String anInitialSplit : initialSplit) { String singleLineSQL = anInitialSplit.trim(); if (singleLineSQL.length() > 0) { strings.add(singleLineSQL); } } return strings.toArray(new String[strings.size()]); } static String trimToEmpty(String string); static String trimToNull(String string); static String[] processMutliLineSQL(String multiLineSQL,boolean stripComments, boolean splitStatements, String endDelimiter); static String[] splitSQL(String multiLineSQL, String endDelimiter); static String stripComments(String multiLineSQL); static String join(String[] array, String delimiter); static String join(Collection<String> collection, String delimiter); static List<String> splitAndTrim(String s, String regex); static String repeat(String string, int times); static String join(Integer[] array, String delimiter); static String join(int[] array, String delimiter); } |
@Test public void testGenerateSqlForNamedSchema() { GetViewDefinitionGeneratorSybase generator = new GetViewDefinitionGeneratorSybase(); GetViewDefinitionStatement statement = new GetViewDefinitionStatement("owner", "view_name"); Sql[] sql = generator.generateSql(statement, new SybaseDatabase(), null); assertEquals(1, sql.length); assertEquals("select text from syscomments where id = object_id('owner.view_name') order by colid", sql[0].toSql()); } | @Override public Sql[] generateSql(GetViewDefinitionStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { try { String sql = "select text from syscomments where id = object_id('" + database.convertRequestedSchemaToSchema(statement.getSchemaName()) + "." + statement.getViewName() + "') order by colid"; return new Sql[]{ new UnparsedSql(sql) }; } catch (DatabaseException e) { throw new UnexpectedLiquibaseException(e); } } | GetViewDefinitionGeneratorSybase extends GetViewDefinitionGenerator { @Override public Sql[] generateSql(GetViewDefinitionStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { try { String sql = "select text from syscomments where id = object_id('" + database.convertRequestedSchemaToSchema(statement.getSchemaName()) + "." + statement.getViewName() + "') order by colid"; return new Sql[]{ new UnparsedSql(sql) }; } catch (DatabaseException e) { throw new UnexpectedLiquibaseException(e); } } } | GetViewDefinitionGeneratorSybase extends GetViewDefinitionGenerator { @Override public Sql[] generateSql(GetViewDefinitionStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { try { String sql = "select text from syscomments where id = object_id('" + database.convertRequestedSchemaToSchema(statement.getSchemaName()) + "." + statement.getViewName() + "') order by colid"; return new Sql[]{ new UnparsedSql(sql) }; } catch (DatabaseException e) { throw new UnexpectedLiquibaseException(e); } } } | GetViewDefinitionGeneratorSybase extends GetViewDefinitionGenerator { @Override public Sql[] generateSql(GetViewDefinitionStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { try { String sql = "select text from syscomments where id = object_id('" + database.convertRequestedSchemaToSchema(statement.getSchemaName()) + "." + statement.getViewName() + "') order by colid"; return new Sql[]{ new UnparsedSql(sql) }; } catch (DatabaseException e) { throw new UnexpectedLiquibaseException(e); } } @Override int getPriority(); @Override boolean supports(GetViewDefinitionStatement statement, Database database); @Override Sql[] generateSql(GetViewDefinitionStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain); } | GetViewDefinitionGeneratorSybase extends GetViewDefinitionGenerator { @Override public Sql[] generateSql(GetViewDefinitionStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { try { String sql = "select text from syscomments where id = object_id('" + database.convertRequestedSchemaToSchema(statement.getSchemaName()) + "." + statement.getViewName() + "') order by colid"; return new Sql[]{ new UnparsedSql(sql) }; } catch (DatabaseException e) { throw new UnexpectedLiquibaseException(e); } } @Override int getPriority(); @Override boolean supports(GetViewDefinitionStatement statement, Database database); @Override Sql[] generateSql(GetViewDefinitionStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain); } |
@Test public void getInstance() { assertNotNull(SqlGeneratorFactory.getInstance()); assertTrue(SqlGeneratorFactory.getInstance() == SqlGeneratorFactory.getInstance()); } | public static SqlGeneratorFactory getInstance() { if (instance == null) { instance = new SqlGeneratorFactory(); } return instance; } | SqlGeneratorFactory { public static SqlGeneratorFactory getInstance() { if (instance == null) { instance = new SqlGeneratorFactory(); } return instance; } } | SqlGeneratorFactory { public static SqlGeneratorFactory getInstance() { if (instance == null) { instance = new SqlGeneratorFactory(); } return instance; } private SqlGeneratorFactory(); } | SqlGeneratorFactory { public static SqlGeneratorFactory getInstance() { if (instance == null) { instance = new SqlGeneratorFactory(); } return instance; } private SqlGeneratorFactory(); static SqlGeneratorFactory getInstance(); static void reset(); void register(SqlGenerator generator); void unregister(SqlGenerator generator); void unregister(Class generatorClass); Sql[] generateSql(SqlStatement statement, Database database); boolean requiresCurrentDatabaseMetadata(SqlStatement statement, Database database); boolean supports(SqlStatement statement, Database database); ValidationErrors validate(SqlStatement statement, Database database); Warnings warn(SqlStatement statement, Database database); Set<DatabaseObject> getAffectedDatabaseObjects(SqlStatement statement, Database database); } | SqlGeneratorFactory { public static SqlGeneratorFactory getInstance() { if (instance == null) { instance = new SqlGeneratorFactory(); } return instance; } private SqlGeneratorFactory(); static SqlGeneratorFactory getInstance(); static void reset(); void register(SqlGenerator generator); void unregister(SqlGenerator generator); void unregister(Class generatorClass); Sql[] generateSql(SqlStatement statement, Database database); boolean requiresCurrentDatabaseMetadata(SqlStatement statement, Database database); boolean supports(SqlStatement statement, Database database); ValidationErrors validate(SqlStatement statement, Database database); Warnings warn(SqlStatement statement, Database database); Set<DatabaseObject> getAffectedDatabaseObjects(SqlStatement statement, Database database); } |
@Test public void register() { SqlGeneratorFactory.getInstance().getGenerators().clear(); assertEquals(0, SqlGeneratorFactory.getInstance().getGenerators().size()); SqlGeneratorFactory.getInstance().register(new MockSqlGenerator(1, "A1")); assertEquals(1, SqlGeneratorFactory.getInstance().getGenerators().size()); } | public void register(SqlGenerator generator) { generators.add(generator); } | SqlGeneratorFactory { public void register(SqlGenerator generator) { generators.add(generator); } } | SqlGeneratorFactory { public void register(SqlGenerator generator) { generators.add(generator); } private SqlGeneratorFactory(); } | SqlGeneratorFactory { public void register(SqlGenerator generator) { generators.add(generator); } private SqlGeneratorFactory(); static SqlGeneratorFactory getInstance(); static void reset(); void register(SqlGenerator generator); void unregister(SqlGenerator generator); void unregister(Class generatorClass); Sql[] generateSql(SqlStatement statement, Database database); boolean requiresCurrentDatabaseMetadata(SqlStatement statement, Database database); boolean supports(SqlStatement statement, Database database); ValidationErrors validate(SqlStatement statement, Database database); Warnings warn(SqlStatement statement, Database database); Set<DatabaseObject> getAffectedDatabaseObjects(SqlStatement statement, Database database); } | SqlGeneratorFactory { public void register(SqlGenerator generator) { generators.add(generator); } private SqlGeneratorFactory(); static SqlGeneratorFactory getInstance(); static void reset(); void register(SqlGenerator generator); void unregister(SqlGenerator generator); void unregister(Class generatorClass); Sql[] generateSql(SqlStatement statement, Database database); boolean requiresCurrentDatabaseMetadata(SqlStatement statement, Database database); boolean supports(SqlStatement statement, Database database); ValidationErrors validate(SqlStatement statement, Database database); Warnings warn(SqlStatement statement, Database database); Set<DatabaseObject> getAffectedDatabaseObjects(SqlStatement statement, Database database); } |
@Test public void reset() { SqlGeneratorFactory instance1 = SqlGeneratorFactory.getInstance(); SqlGeneratorFactory.reset(); assertFalse(instance1 == SqlGeneratorFactory.getInstance()); } | public static void reset() { instance = new SqlGeneratorFactory(); } | SqlGeneratorFactory { public static void reset() { instance = new SqlGeneratorFactory(); } } | SqlGeneratorFactory { public static void reset() { instance = new SqlGeneratorFactory(); } private SqlGeneratorFactory(); } | SqlGeneratorFactory { public static void reset() { instance = new SqlGeneratorFactory(); } private SqlGeneratorFactory(); static SqlGeneratorFactory getInstance(); static void reset(); void register(SqlGenerator generator); void unregister(SqlGenerator generator); void unregister(Class generatorClass); Sql[] generateSql(SqlStatement statement, Database database); boolean requiresCurrentDatabaseMetadata(SqlStatement statement, Database database); boolean supports(SqlStatement statement, Database database); ValidationErrors validate(SqlStatement statement, Database database); Warnings warn(SqlStatement statement, Database database); Set<DatabaseObject> getAffectedDatabaseObjects(SqlStatement statement, Database database); } | SqlGeneratorFactory { public static void reset() { instance = new SqlGeneratorFactory(); } private SqlGeneratorFactory(); static SqlGeneratorFactory getInstance(); static void reset(); void register(SqlGenerator generator); void unregister(SqlGenerator generator); void unregister(Class generatorClass); Sql[] generateSql(SqlStatement statement, Database database); boolean requiresCurrentDatabaseMetadata(SqlStatement statement, Database database); boolean supports(SqlStatement statement, Database database); ValidationErrors validate(SqlStatement statement, Database database); Warnings warn(SqlStatement statement, Database database); Set<DatabaseObject> getAffectedDatabaseObjects(SqlStatement statement, Database database); } |
@Test public void getGenerators() { SortedSet<SqlGenerator> allGenerators = SqlGeneratorFactory.getInstance().getGenerators(new AddAutoIncrementStatement(null, "person", "name", "varchar(255)", null, null), new H2Database()); assertNotNull(allGenerators); assertEquals(1, allGenerators.size()); } | protected Collection<SqlGenerator> getGenerators() { return generators; } | SqlGeneratorFactory { protected Collection<SqlGenerator> getGenerators() { return generators; } } | SqlGeneratorFactory { protected Collection<SqlGenerator> getGenerators() { return generators; } private SqlGeneratorFactory(); } | SqlGeneratorFactory { protected Collection<SqlGenerator> getGenerators() { return generators; } private SqlGeneratorFactory(); static SqlGeneratorFactory getInstance(); static void reset(); void register(SqlGenerator generator); void unregister(SqlGenerator generator); void unregister(Class generatorClass); Sql[] generateSql(SqlStatement statement, Database database); boolean requiresCurrentDatabaseMetadata(SqlStatement statement, Database database); boolean supports(SqlStatement statement, Database database); ValidationErrors validate(SqlStatement statement, Database database); Warnings warn(SqlStatement statement, Database database); Set<DatabaseObject> getAffectedDatabaseObjects(SqlStatement statement, Database database); } | SqlGeneratorFactory { protected Collection<SqlGenerator> getGenerators() { return generators; } private SqlGeneratorFactory(); static SqlGeneratorFactory getInstance(); static void reset(); void register(SqlGenerator generator); void unregister(SqlGenerator generator); void unregister(Class generatorClass); Sql[] generateSql(SqlStatement statement, Database database); boolean requiresCurrentDatabaseMetadata(SqlStatement statement, Database database); boolean supports(SqlStatement statement, Database database); ValidationErrors validate(SqlStatement statement, Database database); Warnings warn(SqlStatement statement, Database database); Set<DatabaseObject> getAffectedDatabaseObjects(SqlStatement statement, Database database); } |
@Test public void getInstance() { assertNotNull(PreconditionFactory.getInstance()); assertTrue(PreconditionFactory.getInstance() == PreconditionFactory.getInstance()); } | public static PreconditionFactory getInstance() { if (instance == null) { instance = new PreconditionFactory(); } return instance; } | PreconditionFactory { public static PreconditionFactory getInstance() { if (instance == null) { instance = new PreconditionFactory(); } return instance; } } | PreconditionFactory { public static PreconditionFactory getInstance() { if (instance == null) { instance = new PreconditionFactory(); } return instance; } @SuppressWarnings("unchecked") private PreconditionFactory(); } | PreconditionFactory { public static PreconditionFactory getInstance() { if (instance == null) { instance = new PreconditionFactory(); } return instance; } @SuppressWarnings("unchecked") private PreconditionFactory(); static PreconditionFactory getInstance(); static void reset(); Map<String, Class<? extends Precondition>> getPreconditions(); void register(Class<? extends Precondition> clazz); void unregister(String name); Precondition create(String tagName); } | PreconditionFactory { public static PreconditionFactory getInstance() { if (instance == null) { instance = new PreconditionFactory(); } return instance; } @SuppressWarnings("unchecked") private PreconditionFactory(); static PreconditionFactory getInstance(); static void reset(); Map<String, Class<? extends Precondition>> getPreconditions(); void register(Class<? extends Precondition> clazz); void unregister(String name); Precondition create(String tagName); } |
@Test public void register() { PreconditionFactory.getInstance().getPreconditions().clear(); assertEquals(0, PreconditionFactory.getInstance().getPreconditions().size()); PreconditionFactory.getInstance().register(MockPrecondition.class); assertEquals(1, PreconditionFactory.getInstance().getPreconditions().size()); } | public void register(Class<? extends Precondition> clazz) { try { preconditions.put(clazz.newInstance().getName(), clazz); } catch (Exception e) { throw new UnexpectedLiquibaseException(e); } } | PreconditionFactory { public void register(Class<? extends Precondition> clazz) { try { preconditions.put(clazz.newInstance().getName(), clazz); } catch (Exception e) { throw new UnexpectedLiquibaseException(e); } } } | PreconditionFactory { public void register(Class<? extends Precondition> clazz) { try { preconditions.put(clazz.newInstance().getName(), clazz); } catch (Exception e) { throw new UnexpectedLiquibaseException(e); } } @SuppressWarnings("unchecked") private PreconditionFactory(); } | PreconditionFactory { public void register(Class<? extends Precondition> clazz) { try { preconditions.put(clazz.newInstance().getName(), clazz); } catch (Exception e) { throw new UnexpectedLiquibaseException(e); } } @SuppressWarnings("unchecked") private PreconditionFactory(); static PreconditionFactory getInstance(); static void reset(); Map<String, Class<? extends Precondition>> getPreconditions(); void register(Class<? extends Precondition> clazz); void unregister(String name); Precondition create(String tagName); } | PreconditionFactory { public void register(Class<? extends Precondition> clazz) { try { preconditions.put(clazz.newInstance().getName(), clazz); } catch (Exception e) { throw new UnexpectedLiquibaseException(e); } } @SuppressWarnings("unchecked") private PreconditionFactory(); static PreconditionFactory getInstance(); static void reset(); Map<String, Class<? extends Precondition>> getPreconditions(); void register(Class<? extends Precondition> clazz); void unregister(String name); Precondition create(String tagName); } |
@Test public void reset() { PreconditionFactory instance1 = PreconditionFactory.getInstance(); PreconditionFactory.reset(); assertFalse(instance1 == PreconditionFactory.getInstance()); } | public static void reset() { instance = new PreconditionFactory(); } | PreconditionFactory { public static void reset() { instance = new PreconditionFactory(); } } | PreconditionFactory { public static void reset() { instance = new PreconditionFactory(); } @SuppressWarnings("unchecked") private PreconditionFactory(); } | PreconditionFactory { public static void reset() { instance = new PreconditionFactory(); } @SuppressWarnings("unchecked") private PreconditionFactory(); static PreconditionFactory getInstance(); static void reset(); Map<String, Class<? extends Precondition>> getPreconditions(); void register(Class<? extends Precondition> clazz); void unregister(String name); Precondition create(String tagName); } | PreconditionFactory { public static void reset() { instance = new PreconditionFactory(); } @SuppressWarnings("unchecked") private PreconditionFactory(); static PreconditionFactory getInstance(); static void reset(); Map<String, Class<? extends Precondition>> getPreconditions(); void register(Class<? extends Precondition> clazz); void unregister(String name); Precondition create(String tagName); } |
@Test public void migrateWithAllParameters() throws Exception { String[] args = new String[]{ "--driver=DRIVER", "--username=USERNAME", "--password=PASSWORD", "--url=URL", "--changeLogFile=FILE", "--classpath=CLASSPATH;CLASSPATH2", "--contexts=CONTEXT1,CONTEXT2", "--promptForNonLocalDatabase=true", "update", }; Main cli = new Main(); cli.parseOptions(args); assertEquals("DRIVER", cli.driver); assertEquals("USERNAME", cli.username); assertEquals("PASSWORD", cli.password); assertEquals("URL", cli.url); assertEquals("FILE", cli.changeLogFile); assertEquals("CLASSPATH;CLASSPATH2", cli.classpath); assertEquals("CONTEXT1,CONTEXT2", cli.contexts); assertEquals(Boolean.TRUE, cli.promptForNonLocalDatabase); assertEquals("update", cli.command); } | protected void parseOptions(String[] args) throws CommandLineParsingException { args = fixupArgs(args); boolean seenCommand = false; for (String arg : args) { if (isCommand(arg)) { this.command = arg; if (this.command.equalsIgnoreCase("migrate")) { this.command = "update"; } else if (this.command.equalsIgnoreCase("migrateSQL")) { this.command = "updateSQL"; } seenCommand = true; } else if (seenCommand) { if (arg.startsWith("-D")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0].replaceFirst("^-D", ""); String value = splitArg[1]; changeLogParameters.put(attributeName, value); } else { commandParams.add(arg); } } else if (arg.startsWith("--")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0]; String value = splitArg[1]; try { Field field = getClass().getDeclaredField(attributeName); if (field.getType().equals(Boolean.class)) { field.set(this, Boolean.valueOf(value)); } else { field.set(this, value); } } catch (Exception e) { throw new CommandLineParsingException("Unknown parameter: '" + attributeName + "'"); } } else { throw new CommandLineParsingException("Unexpected value " + arg + ": parameters must start with a '--'"); } } } | Main { protected void parseOptions(String[] args) throws CommandLineParsingException { args = fixupArgs(args); boolean seenCommand = false; for (String arg : args) { if (isCommand(arg)) { this.command = arg; if (this.command.equalsIgnoreCase("migrate")) { this.command = "update"; } else if (this.command.equalsIgnoreCase("migrateSQL")) { this.command = "updateSQL"; } seenCommand = true; } else if (seenCommand) { if (arg.startsWith("-D")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0].replaceFirst("^-D", ""); String value = splitArg[1]; changeLogParameters.put(attributeName, value); } else { commandParams.add(arg); } } else if (arg.startsWith("--")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0]; String value = splitArg[1]; try { Field field = getClass().getDeclaredField(attributeName); if (field.getType().equals(Boolean.class)) { field.set(this, Boolean.valueOf(value)); } else { field.set(this, value); } } catch (Exception e) { throw new CommandLineParsingException("Unknown parameter: '" + attributeName + "'"); } } else { throw new CommandLineParsingException("Unexpected value " + arg + ": parameters must start with a '--'"); } } } } | Main { protected void parseOptions(String[] args) throws CommandLineParsingException { args = fixupArgs(args); boolean seenCommand = false; for (String arg : args) { if (isCommand(arg)) { this.command = arg; if (this.command.equalsIgnoreCase("migrate")) { this.command = "update"; } else if (this.command.equalsIgnoreCase("migrateSQL")) { this.command = "updateSQL"; } seenCommand = true; } else if (seenCommand) { if (arg.startsWith("-D")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0].replaceFirst("^-D", ""); String value = splitArg[1]; changeLogParameters.put(attributeName, value); } else { commandParams.add(arg); } } else if (arg.startsWith("--")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0]; String value = splitArg[1]; try { Field field = getClass().getDeclaredField(attributeName); if (field.getType().equals(Boolean.class)) { field.set(this, Boolean.valueOf(value)); } else { field.set(this, value); } } catch (Exception e) { throw new CommandLineParsingException("Unknown parameter: '" + attributeName + "'"); } } else { throw new CommandLineParsingException("Unexpected value " + arg + ": parameters must start with a '--'"); } } } Main(); } | Main { protected void parseOptions(String[] args) throws CommandLineParsingException { args = fixupArgs(args); boolean seenCommand = false; for (String arg : args) { if (isCommand(arg)) { this.command = arg; if (this.command.equalsIgnoreCase("migrate")) { this.command = "update"; } else if (this.command.equalsIgnoreCase("migrateSQL")) { this.command = "updateSQL"; } seenCommand = true; } else if (seenCommand) { if (arg.startsWith("-D")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0].replaceFirst("^-D", ""); String value = splitArg[1]; changeLogParameters.put(attributeName, value); } else { commandParams.add(arg); } } else if (arg.startsWith("--")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0]; String value = splitArg[1]; try { Field field = getClass().getDeclaredField(attributeName); if (field.getType().equals(Boolean.class)) { field.set(this, Boolean.valueOf(value)); } else { field.set(this, value); } } catch (Exception e) { throw new CommandLineParsingException("Unknown parameter: '" + attributeName + "'"); } } else { throw new CommandLineParsingException("Unexpected value " + arg + ": parameters must start with a '--'"); } } } Main(); static void main(String args[]); boolean isWindows(); } | Main { protected void parseOptions(String[] args) throws CommandLineParsingException { args = fixupArgs(args); boolean seenCommand = false; for (String arg : args) { if (isCommand(arg)) { this.command = arg; if (this.command.equalsIgnoreCase("migrate")) { this.command = "update"; } else if (this.command.equalsIgnoreCase("migrateSQL")) { this.command = "updateSQL"; } seenCommand = true; } else if (seenCommand) { if (arg.startsWith("-D")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0].replaceFirst("^-D", ""); String value = splitArg[1]; changeLogParameters.put(attributeName, value); } else { commandParams.add(arg); } } else if (arg.startsWith("--")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0]; String value = splitArg[1]; try { Field field = getClass().getDeclaredField(attributeName); if (field.getType().equals(Boolean.class)) { field.set(this, Boolean.valueOf(value)); } else { field.set(this, value); } } catch (Exception e) { throw new CommandLineParsingException("Unknown parameter: '" + attributeName + "'"); } } else { throw new CommandLineParsingException("Unexpected value " + arg + ": parameters must start with a '--'"); } } } Main(); static void main(String args[]); boolean isWindows(); } |
@Test public void falseBooleanParameters() throws Exception { String[] args = new String[]{ "--promptForNonLocalDatabase=false", "update", }; Main cli = new Main(); cli.parseOptions(args); assertEquals(Boolean.FALSE, cli.promptForNonLocalDatabase); assertEquals("update", cli.command); } | protected void parseOptions(String[] args) throws CommandLineParsingException { args = fixupArgs(args); boolean seenCommand = false; for (String arg : args) { if (isCommand(arg)) { this.command = arg; if (this.command.equalsIgnoreCase("migrate")) { this.command = "update"; } else if (this.command.equalsIgnoreCase("migrateSQL")) { this.command = "updateSQL"; } seenCommand = true; } else if (seenCommand) { if (arg.startsWith("-D")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0].replaceFirst("^-D", ""); String value = splitArg[1]; changeLogParameters.put(attributeName, value); } else { commandParams.add(arg); } } else if (arg.startsWith("--")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0]; String value = splitArg[1]; try { Field field = getClass().getDeclaredField(attributeName); if (field.getType().equals(Boolean.class)) { field.set(this, Boolean.valueOf(value)); } else { field.set(this, value); } } catch (Exception e) { throw new CommandLineParsingException("Unknown parameter: '" + attributeName + "'"); } } else { throw new CommandLineParsingException("Unexpected value " + arg + ": parameters must start with a '--'"); } } } | Main { protected void parseOptions(String[] args) throws CommandLineParsingException { args = fixupArgs(args); boolean seenCommand = false; for (String arg : args) { if (isCommand(arg)) { this.command = arg; if (this.command.equalsIgnoreCase("migrate")) { this.command = "update"; } else if (this.command.equalsIgnoreCase("migrateSQL")) { this.command = "updateSQL"; } seenCommand = true; } else if (seenCommand) { if (arg.startsWith("-D")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0].replaceFirst("^-D", ""); String value = splitArg[1]; changeLogParameters.put(attributeName, value); } else { commandParams.add(arg); } } else if (arg.startsWith("--")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0]; String value = splitArg[1]; try { Field field = getClass().getDeclaredField(attributeName); if (field.getType().equals(Boolean.class)) { field.set(this, Boolean.valueOf(value)); } else { field.set(this, value); } } catch (Exception e) { throw new CommandLineParsingException("Unknown parameter: '" + attributeName + "'"); } } else { throw new CommandLineParsingException("Unexpected value " + arg + ": parameters must start with a '--'"); } } } } | Main { protected void parseOptions(String[] args) throws CommandLineParsingException { args = fixupArgs(args); boolean seenCommand = false; for (String arg : args) { if (isCommand(arg)) { this.command = arg; if (this.command.equalsIgnoreCase("migrate")) { this.command = "update"; } else if (this.command.equalsIgnoreCase("migrateSQL")) { this.command = "updateSQL"; } seenCommand = true; } else if (seenCommand) { if (arg.startsWith("-D")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0].replaceFirst("^-D", ""); String value = splitArg[1]; changeLogParameters.put(attributeName, value); } else { commandParams.add(arg); } } else if (arg.startsWith("--")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0]; String value = splitArg[1]; try { Field field = getClass().getDeclaredField(attributeName); if (field.getType().equals(Boolean.class)) { field.set(this, Boolean.valueOf(value)); } else { field.set(this, value); } } catch (Exception e) { throw new CommandLineParsingException("Unknown parameter: '" + attributeName + "'"); } } else { throw new CommandLineParsingException("Unexpected value " + arg + ": parameters must start with a '--'"); } } } Main(); } | Main { protected void parseOptions(String[] args) throws CommandLineParsingException { args = fixupArgs(args); boolean seenCommand = false; for (String arg : args) { if (isCommand(arg)) { this.command = arg; if (this.command.equalsIgnoreCase("migrate")) { this.command = "update"; } else if (this.command.equalsIgnoreCase("migrateSQL")) { this.command = "updateSQL"; } seenCommand = true; } else if (seenCommand) { if (arg.startsWith("-D")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0].replaceFirst("^-D", ""); String value = splitArg[1]; changeLogParameters.put(attributeName, value); } else { commandParams.add(arg); } } else if (arg.startsWith("--")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0]; String value = splitArg[1]; try { Field field = getClass().getDeclaredField(attributeName); if (field.getType().equals(Boolean.class)) { field.set(this, Boolean.valueOf(value)); } else { field.set(this, value); } } catch (Exception e) { throw new CommandLineParsingException("Unknown parameter: '" + attributeName + "'"); } } else { throw new CommandLineParsingException("Unexpected value " + arg + ": parameters must start with a '--'"); } } } Main(); static void main(String args[]); boolean isWindows(); } | Main { protected void parseOptions(String[] args) throws CommandLineParsingException { args = fixupArgs(args); boolean seenCommand = false; for (String arg : args) { if (isCommand(arg)) { this.command = arg; if (this.command.equalsIgnoreCase("migrate")) { this.command = "update"; } else if (this.command.equalsIgnoreCase("migrateSQL")) { this.command = "updateSQL"; } seenCommand = true; } else if (seenCommand) { if (arg.startsWith("-D")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0].replaceFirst("^-D", ""); String value = splitArg[1]; changeLogParameters.put(attributeName, value); } else { commandParams.add(arg); } } else if (arg.startsWith("--")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0]; String value = splitArg[1]; try { Field field = getClass().getDeclaredField(attributeName); if (field.getType().equals(Boolean.class)) { field.set(this, Boolean.valueOf(value)); } else { field.set(this, value); } } catch (Exception e) { throw new CommandLineParsingException("Unknown parameter: '" + attributeName + "'"); } } else { throw new CommandLineParsingException("Unexpected value " + arg + ": parameters must start with a '--'"); } } } Main(); static void main(String args[]); boolean isWindows(); } |
@Test public void commentRemoval() { String testString = "--\n" + "-- Create the blog table.\n" + "--\n" + "CREATE TABLE blog\n" + "(\n" + " ID NUMBER(15) NOT NULL\n" + ")"; String[] strings = StringUtils.processMutliLineSQL(testString, true, false, null); assertEquals(1, strings.length); assertTrue(strings[0].startsWith("CREATE TABLE blog")); } | public static String[] processMutliLineSQL(String multiLineSQL,boolean stripComments, boolean splitStatements, String endDelimiter) { String stripped = stripComments ? stripComments(multiLineSQL) : multiLineSQL; if (splitStatements) { return splitSQL(stripped, endDelimiter); } else { return new String[]{stripped}; } } | StringUtils { public static String[] processMutliLineSQL(String multiLineSQL,boolean stripComments, boolean splitStatements, String endDelimiter) { String stripped = stripComments ? stripComments(multiLineSQL) : multiLineSQL; if (splitStatements) { return splitSQL(stripped, endDelimiter); } else { return new String[]{stripped}; } } } | StringUtils { public static String[] processMutliLineSQL(String multiLineSQL,boolean stripComments, boolean splitStatements, String endDelimiter) { String stripped = stripComments ? stripComments(multiLineSQL) : multiLineSQL; if (splitStatements) { return splitSQL(stripped, endDelimiter); } else { return new String[]{stripped}; } } } | StringUtils { public static String[] processMutliLineSQL(String multiLineSQL,boolean stripComments, boolean splitStatements, String endDelimiter) { String stripped = stripComments ? stripComments(multiLineSQL) : multiLineSQL; if (splitStatements) { return splitSQL(stripped, endDelimiter); } else { return new String[]{stripped}; } } static String trimToEmpty(String string); static String trimToNull(String string); static String[] processMutliLineSQL(String multiLineSQL,boolean stripComments, boolean splitStatements, String endDelimiter); static String[] splitSQL(String multiLineSQL, String endDelimiter); static String stripComments(String multiLineSQL); static String join(String[] array, String delimiter); static String join(Collection<String> collection, String delimiter); static List<String> splitAndTrim(String s, String regex); static String repeat(String string, int times); static String join(Integer[] array, String delimiter); static String join(int[] array, String delimiter); } | StringUtils { public static String[] processMutliLineSQL(String multiLineSQL,boolean stripComments, boolean splitStatements, String endDelimiter) { String stripped = stripComments ? stripComments(multiLineSQL) : multiLineSQL; if (splitStatements) { return splitSQL(stripped, endDelimiter); } else { return new String[]{stripped}; } } static String trimToEmpty(String string); static String trimToNull(String string); static String[] processMutliLineSQL(String multiLineSQL,boolean stripComments, boolean splitStatements, String endDelimiter); static String[] splitSQL(String multiLineSQL, String endDelimiter); static String stripComments(String multiLineSQL); static String join(String[] array, String delimiter); static String join(Collection<String> collection, String delimiter); static List<String> splitAndTrim(String s, String regex); static String repeat(String string, int times); static String join(Integer[] array, String delimiter); static String join(int[] array, String delimiter); } |
@Test public void convertMigrateToUpdate() throws Exception { String[] args = new String[]{ "--promptForNonLocalDatabase=false", "migrate", }; Main cli = new Main(); cli.parseOptions(args); assertEquals("update", cli.command); } | protected void parseOptions(String[] args) throws CommandLineParsingException { args = fixupArgs(args); boolean seenCommand = false; for (String arg : args) { if (isCommand(arg)) { this.command = arg; if (this.command.equalsIgnoreCase("migrate")) { this.command = "update"; } else if (this.command.equalsIgnoreCase("migrateSQL")) { this.command = "updateSQL"; } seenCommand = true; } else if (seenCommand) { if (arg.startsWith("-D")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0].replaceFirst("^-D", ""); String value = splitArg[1]; changeLogParameters.put(attributeName, value); } else { commandParams.add(arg); } } else if (arg.startsWith("--")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0]; String value = splitArg[1]; try { Field field = getClass().getDeclaredField(attributeName); if (field.getType().equals(Boolean.class)) { field.set(this, Boolean.valueOf(value)); } else { field.set(this, value); } } catch (Exception e) { throw new CommandLineParsingException("Unknown parameter: '" + attributeName + "'"); } } else { throw new CommandLineParsingException("Unexpected value " + arg + ": parameters must start with a '--'"); } } } | Main { protected void parseOptions(String[] args) throws CommandLineParsingException { args = fixupArgs(args); boolean seenCommand = false; for (String arg : args) { if (isCommand(arg)) { this.command = arg; if (this.command.equalsIgnoreCase("migrate")) { this.command = "update"; } else if (this.command.equalsIgnoreCase("migrateSQL")) { this.command = "updateSQL"; } seenCommand = true; } else if (seenCommand) { if (arg.startsWith("-D")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0].replaceFirst("^-D", ""); String value = splitArg[1]; changeLogParameters.put(attributeName, value); } else { commandParams.add(arg); } } else if (arg.startsWith("--")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0]; String value = splitArg[1]; try { Field field = getClass().getDeclaredField(attributeName); if (field.getType().equals(Boolean.class)) { field.set(this, Boolean.valueOf(value)); } else { field.set(this, value); } } catch (Exception e) { throw new CommandLineParsingException("Unknown parameter: '" + attributeName + "'"); } } else { throw new CommandLineParsingException("Unexpected value " + arg + ": parameters must start with a '--'"); } } } } | Main { protected void parseOptions(String[] args) throws CommandLineParsingException { args = fixupArgs(args); boolean seenCommand = false; for (String arg : args) { if (isCommand(arg)) { this.command = arg; if (this.command.equalsIgnoreCase("migrate")) { this.command = "update"; } else if (this.command.equalsIgnoreCase("migrateSQL")) { this.command = "updateSQL"; } seenCommand = true; } else if (seenCommand) { if (arg.startsWith("-D")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0].replaceFirst("^-D", ""); String value = splitArg[1]; changeLogParameters.put(attributeName, value); } else { commandParams.add(arg); } } else if (arg.startsWith("--")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0]; String value = splitArg[1]; try { Field field = getClass().getDeclaredField(attributeName); if (field.getType().equals(Boolean.class)) { field.set(this, Boolean.valueOf(value)); } else { field.set(this, value); } } catch (Exception e) { throw new CommandLineParsingException("Unknown parameter: '" + attributeName + "'"); } } else { throw new CommandLineParsingException("Unexpected value " + arg + ": parameters must start with a '--'"); } } } Main(); } | Main { protected void parseOptions(String[] args) throws CommandLineParsingException { args = fixupArgs(args); boolean seenCommand = false; for (String arg : args) { if (isCommand(arg)) { this.command = arg; if (this.command.equalsIgnoreCase("migrate")) { this.command = "update"; } else if (this.command.equalsIgnoreCase("migrateSQL")) { this.command = "updateSQL"; } seenCommand = true; } else if (seenCommand) { if (arg.startsWith("-D")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0].replaceFirst("^-D", ""); String value = splitArg[1]; changeLogParameters.put(attributeName, value); } else { commandParams.add(arg); } } else if (arg.startsWith("--")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0]; String value = splitArg[1]; try { Field field = getClass().getDeclaredField(attributeName); if (field.getType().equals(Boolean.class)) { field.set(this, Boolean.valueOf(value)); } else { field.set(this, value); } } catch (Exception e) { throw new CommandLineParsingException("Unknown parameter: '" + attributeName + "'"); } } else { throw new CommandLineParsingException("Unexpected value " + arg + ": parameters must start with a '--'"); } } } Main(); static void main(String args[]); boolean isWindows(); } | Main { protected void parseOptions(String[] args) throws CommandLineParsingException { args = fixupArgs(args); boolean seenCommand = false; for (String arg : args) { if (isCommand(arg)) { this.command = arg; if (this.command.equalsIgnoreCase("migrate")) { this.command = "update"; } else if (this.command.equalsIgnoreCase("migrateSQL")) { this.command = "updateSQL"; } seenCommand = true; } else if (seenCommand) { if (arg.startsWith("-D")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0].replaceFirst("^-D", ""); String value = splitArg[1]; changeLogParameters.put(attributeName, value); } else { commandParams.add(arg); } } else if (arg.startsWith("--")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0]; String value = splitArg[1]; try { Field field = getClass().getDeclaredField(attributeName); if (field.getType().equals(Boolean.class)) { field.set(this, Boolean.valueOf(value)); } else { field.set(this, value); } } catch (Exception e) { throw new CommandLineParsingException("Unknown parameter: '" + attributeName + "'"); } } else { throw new CommandLineParsingException("Unexpected value " + arg + ": parameters must start with a '--'"); } } } Main(); static void main(String args[]); boolean isWindows(); } |
@Test public void trueBooleanParameters() throws Exception { String[] args = new String[]{ "--promptForNonLocalDatabase=true", "update", }; Main cli = new Main(); cli.parseOptions(args); assertEquals(Boolean.TRUE, cli.promptForNonLocalDatabase); assertEquals("update", cli.command); } | protected void parseOptions(String[] args) throws CommandLineParsingException { args = fixupArgs(args); boolean seenCommand = false; for (String arg : args) { if (isCommand(arg)) { this.command = arg; if (this.command.equalsIgnoreCase("migrate")) { this.command = "update"; } else if (this.command.equalsIgnoreCase("migrateSQL")) { this.command = "updateSQL"; } seenCommand = true; } else if (seenCommand) { if (arg.startsWith("-D")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0].replaceFirst("^-D", ""); String value = splitArg[1]; changeLogParameters.put(attributeName, value); } else { commandParams.add(arg); } } else if (arg.startsWith("--")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0]; String value = splitArg[1]; try { Field field = getClass().getDeclaredField(attributeName); if (field.getType().equals(Boolean.class)) { field.set(this, Boolean.valueOf(value)); } else { field.set(this, value); } } catch (Exception e) { throw new CommandLineParsingException("Unknown parameter: '" + attributeName + "'"); } } else { throw new CommandLineParsingException("Unexpected value " + arg + ": parameters must start with a '--'"); } } } | Main { protected void parseOptions(String[] args) throws CommandLineParsingException { args = fixupArgs(args); boolean seenCommand = false; for (String arg : args) { if (isCommand(arg)) { this.command = arg; if (this.command.equalsIgnoreCase("migrate")) { this.command = "update"; } else if (this.command.equalsIgnoreCase("migrateSQL")) { this.command = "updateSQL"; } seenCommand = true; } else if (seenCommand) { if (arg.startsWith("-D")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0].replaceFirst("^-D", ""); String value = splitArg[1]; changeLogParameters.put(attributeName, value); } else { commandParams.add(arg); } } else if (arg.startsWith("--")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0]; String value = splitArg[1]; try { Field field = getClass().getDeclaredField(attributeName); if (field.getType().equals(Boolean.class)) { field.set(this, Boolean.valueOf(value)); } else { field.set(this, value); } } catch (Exception e) { throw new CommandLineParsingException("Unknown parameter: '" + attributeName + "'"); } } else { throw new CommandLineParsingException("Unexpected value " + arg + ": parameters must start with a '--'"); } } } } | Main { protected void parseOptions(String[] args) throws CommandLineParsingException { args = fixupArgs(args); boolean seenCommand = false; for (String arg : args) { if (isCommand(arg)) { this.command = arg; if (this.command.equalsIgnoreCase("migrate")) { this.command = "update"; } else if (this.command.equalsIgnoreCase("migrateSQL")) { this.command = "updateSQL"; } seenCommand = true; } else if (seenCommand) { if (arg.startsWith("-D")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0].replaceFirst("^-D", ""); String value = splitArg[1]; changeLogParameters.put(attributeName, value); } else { commandParams.add(arg); } } else if (arg.startsWith("--")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0]; String value = splitArg[1]; try { Field field = getClass().getDeclaredField(attributeName); if (field.getType().equals(Boolean.class)) { field.set(this, Boolean.valueOf(value)); } else { field.set(this, value); } } catch (Exception e) { throw new CommandLineParsingException("Unknown parameter: '" + attributeName + "'"); } } else { throw new CommandLineParsingException("Unexpected value " + arg + ": parameters must start with a '--'"); } } } Main(); } | Main { protected void parseOptions(String[] args) throws CommandLineParsingException { args = fixupArgs(args); boolean seenCommand = false; for (String arg : args) { if (isCommand(arg)) { this.command = arg; if (this.command.equalsIgnoreCase("migrate")) { this.command = "update"; } else if (this.command.equalsIgnoreCase("migrateSQL")) { this.command = "updateSQL"; } seenCommand = true; } else if (seenCommand) { if (arg.startsWith("-D")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0].replaceFirst("^-D", ""); String value = splitArg[1]; changeLogParameters.put(attributeName, value); } else { commandParams.add(arg); } } else if (arg.startsWith("--")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0]; String value = splitArg[1]; try { Field field = getClass().getDeclaredField(attributeName); if (field.getType().equals(Boolean.class)) { field.set(this, Boolean.valueOf(value)); } else { field.set(this, value); } } catch (Exception e) { throw new CommandLineParsingException("Unknown parameter: '" + attributeName + "'"); } } else { throw new CommandLineParsingException("Unexpected value " + arg + ": parameters must start with a '--'"); } } } Main(); static void main(String args[]); boolean isWindows(); } | Main { protected void parseOptions(String[] args) throws CommandLineParsingException { args = fixupArgs(args); boolean seenCommand = false; for (String arg : args) { if (isCommand(arg)) { this.command = arg; if (this.command.equalsIgnoreCase("migrate")) { this.command = "update"; } else if (this.command.equalsIgnoreCase("migrateSQL")) { this.command = "updateSQL"; } seenCommand = true; } else if (seenCommand) { if (arg.startsWith("-D")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0].replaceFirst("^-D", ""); String value = splitArg[1]; changeLogParameters.put(attributeName, value); } else { commandParams.add(arg); } } else if (arg.startsWith("--")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0]; String value = splitArg[1]; try { Field field = getClass().getDeclaredField(attributeName); if (field.getType().equals(Boolean.class)) { field.set(this, Boolean.valueOf(value)); } else { field.set(this, value); } } catch (Exception e) { throw new CommandLineParsingException("Unknown parameter: '" + attributeName + "'"); } } else { throw new CommandLineParsingException("Unexpected value " + arg + ": parameters must start with a '--'"); } } } Main(); static void main(String args[]); boolean isWindows(); } |
@Test(expected = CommandLineParsingException.class) public void parameterWithoutDash() throws Exception { String[] args = new String[]{ "promptForNonLocalDatabase=true", "update", }; Main cli = new Main(); cli.parseOptions(args); } | protected void parseOptions(String[] args) throws CommandLineParsingException { args = fixupArgs(args); boolean seenCommand = false; for (String arg : args) { if (isCommand(arg)) { this.command = arg; if (this.command.equalsIgnoreCase("migrate")) { this.command = "update"; } else if (this.command.equalsIgnoreCase("migrateSQL")) { this.command = "updateSQL"; } seenCommand = true; } else if (seenCommand) { if (arg.startsWith("-D")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0].replaceFirst("^-D", ""); String value = splitArg[1]; changeLogParameters.put(attributeName, value); } else { commandParams.add(arg); } } else if (arg.startsWith("--")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0]; String value = splitArg[1]; try { Field field = getClass().getDeclaredField(attributeName); if (field.getType().equals(Boolean.class)) { field.set(this, Boolean.valueOf(value)); } else { field.set(this, value); } } catch (Exception e) { throw new CommandLineParsingException("Unknown parameter: '" + attributeName + "'"); } } else { throw new CommandLineParsingException("Unexpected value " + arg + ": parameters must start with a '--'"); } } } | Main { protected void parseOptions(String[] args) throws CommandLineParsingException { args = fixupArgs(args); boolean seenCommand = false; for (String arg : args) { if (isCommand(arg)) { this.command = arg; if (this.command.equalsIgnoreCase("migrate")) { this.command = "update"; } else if (this.command.equalsIgnoreCase("migrateSQL")) { this.command = "updateSQL"; } seenCommand = true; } else if (seenCommand) { if (arg.startsWith("-D")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0].replaceFirst("^-D", ""); String value = splitArg[1]; changeLogParameters.put(attributeName, value); } else { commandParams.add(arg); } } else if (arg.startsWith("--")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0]; String value = splitArg[1]; try { Field field = getClass().getDeclaredField(attributeName); if (field.getType().equals(Boolean.class)) { field.set(this, Boolean.valueOf(value)); } else { field.set(this, value); } } catch (Exception e) { throw new CommandLineParsingException("Unknown parameter: '" + attributeName + "'"); } } else { throw new CommandLineParsingException("Unexpected value " + arg + ": parameters must start with a '--'"); } } } } | Main { protected void parseOptions(String[] args) throws CommandLineParsingException { args = fixupArgs(args); boolean seenCommand = false; for (String arg : args) { if (isCommand(arg)) { this.command = arg; if (this.command.equalsIgnoreCase("migrate")) { this.command = "update"; } else if (this.command.equalsIgnoreCase("migrateSQL")) { this.command = "updateSQL"; } seenCommand = true; } else if (seenCommand) { if (arg.startsWith("-D")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0].replaceFirst("^-D", ""); String value = splitArg[1]; changeLogParameters.put(attributeName, value); } else { commandParams.add(arg); } } else if (arg.startsWith("--")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0]; String value = splitArg[1]; try { Field field = getClass().getDeclaredField(attributeName); if (field.getType().equals(Boolean.class)) { field.set(this, Boolean.valueOf(value)); } else { field.set(this, value); } } catch (Exception e) { throw new CommandLineParsingException("Unknown parameter: '" + attributeName + "'"); } } else { throw new CommandLineParsingException("Unexpected value " + arg + ": parameters must start with a '--'"); } } } Main(); } | Main { protected void parseOptions(String[] args) throws CommandLineParsingException { args = fixupArgs(args); boolean seenCommand = false; for (String arg : args) { if (isCommand(arg)) { this.command = arg; if (this.command.equalsIgnoreCase("migrate")) { this.command = "update"; } else if (this.command.equalsIgnoreCase("migrateSQL")) { this.command = "updateSQL"; } seenCommand = true; } else if (seenCommand) { if (arg.startsWith("-D")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0].replaceFirst("^-D", ""); String value = splitArg[1]; changeLogParameters.put(attributeName, value); } else { commandParams.add(arg); } } else if (arg.startsWith("--")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0]; String value = splitArg[1]; try { Field field = getClass().getDeclaredField(attributeName); if (field.getType().equals(Boolean.class)) { field.set(this, Boolean.valueOf(value)); } else { field.set(this, value); } } catch (Exception e) { throw new CommandLineParsingException("Unknown parameter: '" + attributeName + "'"); } } else { throw new CommandLineParsingException("Unexpected value " + arg + ": parameters must start with a '--'"); } } } Main(); static void main(String args[]); boolean isWindows(); } | Main { protected void parseOptions(String[] args) throws CommandLineParsingException { args = fixupArgs(args); boolean seenCommand = false; for (String arg : args) { if (isCommand(arg)) { this.command = arg; if (this.command.equalsIgnoreCase("migrate")) { this.command = "update"; } else if (this.command.equalsIgnoreCase("migrateSQL")) { this.command = "updateSQL"; } seenCommand = true; } else if (seenCommand) { if (arg.startsWith("-D")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0].replaceFirst("^-D", ""); String value = splitArg[1]; changeLogParameters.put(attributeName, value); } else { commandParams.add(arg); } } else if (arg.startsWith("--")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0]; String value = splitArg[1]; try { Field field = getClass().getDeclaredField(attributeName); if (field.getType().equals(Boolean.class)) { field.set(this, Boolean.valueOf(value)); } else { field.set(this, value); } } catch (Exception e) { throw new CommandLineParsingException("Unknown parameter: '" + attributeName + "'"); } } else { throw new CommandLineParsingException("Unexpected value " + arg + ": parameters must start with a '--'"); } } } Main(); static void main(String args[]); boolean isWindows(); } |
@Test(expected = CommandLineParsingException.class) public void unknownParameter() throws Exception { String[] args = new String[]{ "--promptForNonLocalDatabase=true", "--badParam=here", "migrate", }; Main cli = new Main(); cli.parseOptions(args); } | protected void parseOptions(String[] args) throws CommandLineParsingException { args = fixupArgs(args); boolean seenCommand = false; for (String arg : args) { if (isCommand(arg)) { this.command = arg; if (this.command.equalsIgnoreCase("migrate")) { this.command = "update"; } else if (this.command.equalsIgnoreCase("migrateSQL")) { this.command = "updateSQL"; } seenCommand = true; } else if (seenCommand) { if (arg.startsWith("-D")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0].replaceFirst("^-D", ""); String value = splitArg[1]; changeLogParameters.put(attributeName, value); } else { commandParams.add(arg); } } else if (arg.startsWith("--")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0]; String value = splitArg[1]; try { Field field = getClass().getDeclaredField(attributeName); if (field.getType().equals(Boolean.class)) { field.set(this, Boolean.valueOf(value)); } else { field.set(this, value); } } catch (Exception e) { throw new CommandLineParsingException("Unknown parameter: '" + attributeName + "'"); } } else { throw new CommandLineParsingException("Unexpected value " + arg + ": parameters must start with a '--'"); } } } | Main { protected void parseOptions(String[] args) throws CommandLineParsingException { args = fixupArgs(args); boolean seenCommand = false; for (String arg : args) { if (isCommand(arg)) { this.command = arg; if (this.command.equalsIgnoreCase("migrate")) { this.command = "update"; } else if (this.command.equalsIgnoreCase("migrateSQL")) { this.command = "updateSQL"; } seenCommand = true; } else if (seenCommand) { if (arg.startsWith("-D")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0].replaceFirst("^-D", ""); String value = splitArg[1]; changeLogParameters.put(attributeName, value); } else { commandParams.add(arg); } } else if (arg.startsWith("--")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0]; String value = splitArg[1]; try { Field field = getClass().getDeclaredField(attributeName); if (field.getType().equals(Boolean.class)) { field.set(this, Boolean.valueOf(value)); } else { field.set(this, value); } } catch (Exception e) { throw new CommandLineParsingException("Unknown parameter: '" + attributeName + "'"); } } else { throw new CommandLineParsingException("Unexpected value " + arg + ": parameters must start with a '--'"); } } } } | Main { protected void parseOptions(String[] args) throws CommandLineParsingException { args = fixupArgs(args); boolean seenCommand = false; for (String arg : args) { if (isCommand(arg)) { this.command = arg; if (this.command.equalsIgnoreCase("migrate")) { this.command = "update"; } else if (this.command.equalsIgnoreCase("migrateSQL")) { this.command = "updateSQL"; } seenCommand = true; } else if (seenCommand) { if (arg.startsWith("-D")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0].replaceFirst("^-D", ""); String value = splitArg[1]; changeLogParameters.put(attributeName, value); } else { commandParams.add(arg); } } else if (arg.startsWith("--")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0]; String value = splitArg[1]; try { Field field = getClass().getDeclaredField(attributeName); if (field.getType().equals(Boolean.class)) { field.set(this, Boolean.valueOf(value)); } else { field.set(this, value); } } catch (Exception e) { throw new CommandLineParsingException("Unknown parameter: '" + attributeName + "'"); } } else { throw new CommandLineParsingException("Unexpected value " + arg + ": parameters must start with a '--'"); } } } Main(); } | Main { protected void parseOptions(String[] args) throws CommandLineParsingException { args = fixupArgs(args); boolean seenCommand = false; for (String arg : args) { if (isCommand(arg)) { this.command = arg; if (this.command.equalsIgnoreCase("migrate")) { this.command = "update"; } else if (this.command.equalsIgnoreCase("migrateSQL")) { this.command = "updateSQL"; } seenCommand = true; } else if (seenCommand) { if (arg.startsWith("-D")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0].replaceFirst("^-D", ""); String value = splitArg[1]; changeLogParameters.put(attributeName, value); } else { commandParams.add(arg); } } else if (arg.startsWith("--")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0]; String value = splitArg[1]; try { Field field = getClass().getDeclaredField(attributeName); if (field.getType().equals(Boolean.class)) { field.set(this, Boolean.valueOf(value)); } else { field.set(this, value); } } catch (Exception e) { throw new CommandLineParsingException("Unknown parameter: '" + attributeName + "'"); } } else { throw new CommandLineParsingException("Unexpected value " + arg + ": parameters must start with a '--'"); } } } Main(); static void main(String args[]); boolean isWindows(); } | Main { protected void parseOptions(String[] args) throws CommandLineParsingException { args = fixupArgs(args); boolean seenCommand = false; for (String arg : args) { if (isCommand(arg)) { this.command = arg; if (this.command.equalsIgnoreCase("migrate")) { this.command = "update"; } else if (this.command.equalsIgnoreCase("migrateSQL")) { this.command = "updateSQL"; } seenCommand = true; } else if (seenCommand) { if (arg.startsWith("-D")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0].replaceFirst("^-D", ""); String value = splitArg[1]; changeLogParameters.put(attributeName, value); } else { commandParams.add(arg); } } else if (arg.startsWith("--")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0]; String value = splitArg[1]; try { Field field = getClass().getDeclaredField(attributeName); if (field.getType().equals(Boolean.class)) { field.set(this, Boolean.valueOf(value)); } else { field.set(this, value); } } catch (Exception e) { throw new CommandLineParsingException("Unknown parameter: '" + attributeName + "'"); } } else { throw new CommandLineParsingException("Unexpected value " + arg + ": parameters must start with a '--'"); } } } Main(); static void main(String args[]); boolean isWindows(); } |
@Test(expected = CommandLineParsingException.class) public void configureNonExistantClassloaderLocation() throws Exception { Main cli = new Main(); cli.classpath = "badClasspathLocation"; cli.configureClassLoader(); } | protected void configureClassLoader() throws CommandLineParsingException { final List<URL> urls = new ArrayList<URL>(); if (this.classpath != null) { String[] classpath; if (isWindows()) { classpath = this.classpath.split(";"); } else { classpath = this.classpath.split(":"); } for (String classpathEntry : classpath) { File classPathFile = new File(classpathEntry); if (!classPathFile.exists()) { throw new CommandLineParsingException(classPathFile.getAbsolutePath() + " does not exist"); } try { if (classpathEntry.endsWith(".war")) { addWarFileClasspathEntries(classPathFile, urls); } else if (classpathEntry.endsWith(".ear")) { JarFile earZip = new JarFile(classPathFile); Enumeration<? extends JarEntry> entries = earZip.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); if (entry.getName().toLowerCase().endsWith(".jar")) { File jar = extract(earZip, entry); urls.add(new URL("jar:" + jar.toURL() + "!/")); jar.deleteOnExit(); } else if (entry.getName().toLowerCase().endsWith("war")) { File warFile = extract(earZip, entry); addWarFileClasspathEntries(warFile, urls); } } } else { urls.add(new File(classpathEntry).toURL()); } } catch (Exception e) { throw new CommandLineParsingException(e); } } } if (includeSystemClasspath) { classLoader = AccessController.doPrivileged(new PrivilegedAction<URLClassLoader>() { public URLClassLoader run() { return new URLClassLoader(urls.toArray(new URL[urls.size()]), Thread.currentThread().getContextClassLoader()); } }); } else { classLoader = AccessController.doPrivileged(new PrivilegedAction<URLClassLoader>() { public URLClassLoader run() { return new URLClassLoader(urls.toArray(new URL[urls.size()])); } }); } ServiceLocator.getInstance().setResourceAccessor(new ClassLoaderResourceAccessor(classLoader)); Thread.currentThread().setContextClassLoader(classLoader); } | Main { protected void configureClassLoader() throws CommandLineParsingException { final List<URL> urls = new ArrayList<URL>(); if (this.classpath != null) { String[] classpath; if (isWindows()) { classpath = this.classpath.split(";"); } else { classpath = this.classpath.split(":"); } for (String classpathEntry : classpath) { File classPathFile = new File(classpathEntry); if (!classPathFile.exists()) { throw new CommandLineParsingException(classPathFile.getAbsolutePath() + " does not exist"); } try { if (classpathEntry.endsWith(".war")) { addWarFileClasspathEntries(classPathFile, urls); } else if (classpathEntry.endsWith(".ear")) { JarFile earZip = new JarFile(classPathFile); Enumeration<? extends JarEntry> entries = earZip.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); if (entry.getName().toLowerCase().endsWith(".jar")) { File jar = extract(earZip, entry); urls.add(new URL("jar:" + jar.toURL() + "!/")); jar.deleteOnExit(); } else if (entry.getName().toLowerCase().endsWith("war")) { File warFile = extract(earZip, entry); addWarFileClasspathEntries(warFile, urls); } } } else { urls.add(new File(classpathEntry).toURL()); } } catch (Exception e) { throw new CommandLineParsingException(e); } } } if (includeSystemClasspath) { classLoader = AccessController.doPrivileged(new PrivilegedAction<URLClassLoader>() { public URLClassLoader run() { return new URLClassLoader(urls.toArray(new URL[urls.size()]), Thread.currentThread().getContextClassLoader()); } }); } else { classLoader = AccessController.doPrivileged(new PrivilegedAction<URLClassLoader>() { public URLClassLoader run() { return new URLClassLoader(urls.toArray(new URL[urls.size()])); } }); } ServiceLocator.getInstance().setResourceAccessor(new ClassLoaderResourceAccessor(classLoader)); Thread.currentThread().setContextClassLoader(classLoader); } } | Main { protected void configureClassLoader() throws CommandLineParsingException { final List<URL> urls = new ArrayList<URL>(); if (this.classpath != null) { String[] classpath; if (isWindows()) { classpath = this.classpath.split(";"); } else { classpath = this.classpath.split(":"); } for (String classpathEntry : classpath) { File classPathFile = new File(classpathEntry); if (!classPathFile.exists()) { throw new CommandLineParsingException(classPathFile.getAbsolutePath() + " does not exist"); } try { if (classpathEntry.endsWith(".war")) { addWarFileClasspathEntries(classPathFile, urls); } else if (classpathEntry.endsWith(".ear")) { JarFile earZip = new JarFile(classPathFile); Enumeration<? extends JarEntry> entries = earZip.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); if (entry.getName().toLowerCase().endsWith(".jar")) { File jar = extract(earZip, entry); urls.add(new URL("jar:" + jar.toURL() + "!/")); jar.deleteOnExit(); } else if (entry.getName().toLowerCase().endsWith("war")) { File warFile = extract(earZip, entry); addWarFileClasspathEntries(warFile, urls); } } } else { urls.add(new File(classpathEntry).toURL()); } } catch (Exception e) { throw new CommandLineParsingException(e); } } } if (includeSystemClasspath) { classLoader = AccessController.doPrivileged(new PrivilegedAction<URLClassLoader>() { public URLClassLoader run() { return new URLClassLoader(urls.toArray(new URL[urls.size()]), Thread.currentThread().getContextClassLoader()); } }); } else { classLoader = AccessController.doPrivileged(new PrivilegedAction<URLClassLoader>() { public URLClassLoader run() { return new URLClassLoader(urls.toArray(new URL[urls.size()])); } }); } ServiceLocator.getInstance().setResourceAccessor(new ClassLoaderResourceAccessor(classLoader)); Thread.currentThread().setContextClassLoader(classLoader); } Main(); } | Main { protected void configureClassLoader() throws CommandLineParsingException { final List<URL> urls = new ArrayList<URL>(); if (this.classpath != null) { String[] classpath; if (isWindows()) { classpath = this.classpath.split(";"); } else { classpath = this.classpath.split(":"); } for (String classpathEntry : classpath) { File classPathFile = new File(classpathEntry); if (!classPathFile.exists()) { throw new CommandLineParsingException(classPathFile.getAbsolutePath() + " does not exist"); } try { if (classpathEntry.endsWith(".war")) { addWarFileClasspathEntries(classPathFile, urls); } else if (classpathEntry.endsWith(".ear")) { JarFile earZip = new JarFile(classPathFile); Enumeration<? extends JarEntry> entries = earZip.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); if (entry.getName().toLowerCase().endsWith(".jar")) { File jar = extract(earZip, entry); urls.add(new URL("jar:" + jar.toURL() + "!/")); jar.deleteOnExit(); } else if (entry.getName().toLowerCase().endsWith("war")) { File warFile = extract(earZip, entry); addWarFileClasspathEntries(warFile, urls); } } } else { urls.add(new File(classpathEntry).toURL()); } } catch (Exception e) { throw new CommandLineParsingException(e); } } } if (includeSystemClasspath) { classLoader = AccessController.doPrivileged(new PrivilegedAction<URLClassLoader>() { public URLClassLoader run() { return new URLClassLoader(urls.toArray(new URL[urls.size()]), Thread.currentThread().getContextClassLoader()); } }); } else { classLoader = AccessController.doPrivileged(new PrivilegedAction<URLClassLoader>() { public URLClassLoader run() { return new URLClassLoader(urls.toArray(new URL[urls.size()])); } }); } ServiceLocator.getInstance().setResourceAccessor(new ClassLoaderResourceAccessor(classLoader)); Thread.currentThread().setContextClassLoader(classLoader); } Main(); static void main(String args[]); boolean isWindows(); } | Main { protected void configureClassLoader() throws CommandLineParsingException { final List<URL> urls = new ArrayList<URL>(); if (this.classpath != null) { String[] classpath; if (isWindows()) { classpath = this.classpath.split(";"); } else { classpath = this.classpath.split(":"); } for (String classpathEntry : classpath) { File classPathFile = new File(classpathEntry); if (!classPathFile.exists()) { throw new CommandLineParsingException(classPathFile.getAbsolutePath() + " does not exist"); } try { if (classpathEntry.endsWith(".war")) { addWarFileClasspathEntries(classPathFile, urls); } else if (classpathEntry.endsWith(".ear")) { JarFile earZip = new JarFile(classPathFile); Enumeration<? extends JarEntry> entries = earZip.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); if (entry.getName().toLowerCase().endsWith(".jar")) { File jar = extract(earZip, entry); urls.add(new URL("jar:" + jar.toURL() + "!/")); jar.deleteOnExit(); } else if (entry.getName().toLowerCase().endsWith("war")) { File warFile = extract(earZip, entry); addWarFileClasspathEntries(warFile, urls); } } } else { urls.add(new File(classpathEntry).toURL()); } } catch (Exception e) { throw new CommandLineParsingException(e); } } } if (includeSystemClasspath) { classLoader = AccessController.doPrivileged(new PrivilegedAction<URLClassLoader>() { public URLClassLoader run() { return new URLClassLoader(urls.toArray(new URL[urls.size()]), Thread.currentThread().getContextClassLoader()); } }); } else { classLoader = AccessController.doPrivileged(new PrivilegedAction<URLClassLoader>() { public URLClassLoader run() { return new URLClassLoader(urls.toArray(new URL[urls.size()])); } }); } ServiceLocator.getInstance().setResourceAccessor(new ClassLoaderResourceAccessor(classLoader)); Thread.currentThread().setContextClassLoader(classLoader); } Main(); static void main(String args[]); boolean isWindows(); } |
@Test public void propertiesFileWithNoOtherArgs() throws Exception { Main cli = new Main(); Properties props = new Properties(); props.setProperty("driver", "DRIVER"); props.setProperty("username", "USERNAME"); props.setProperty("password", "PASSWD"); props.setProperty("url", "URL"); props.setProperty("changeLogFile", "FILE"); props.setProperty("classpath", "CLASSPAHT"); props.setProperty("contexts", "CONTEXTS"); props.setProperty("promptForNonLocalDatabase", "TRUE"); ByteArrayOutputStream propFile = new ByteArrayOutputStream(); props.store(propFile, ""); cli.parsePropertiesFile(new ByteArrayInputStream(propFile.toByteArray())); assertEquals("DRIVER", cli.driver); assertEquals("USERNAME", cli.username); assertEquals("PASSWD", cli.password); assertEquals("URL", cli.url); assertEquals("FILE", cli.changeLogFile); assertEquals("CLASSPAHT", cli.classpath); assertEquals("CONTEXTS", cli.contexts); assertEquals(Boolean.TRUE, cli.promptForNonLocalDatabase); } | protected void parsePropertiesFile(InputStream propertiesInputStream) throws IOException, CommandLineParsingException { Properties props = new Properties(); props.load(propertiesInputStream); for (Map.Entry entry : props.entrySet()) { try { if (entry.getKey().equals("promptOnNonLocalDatabase")) { continue; } if (((String) entry.getKey()).startsWith("parameter.")) { changeLogParameters.put(((String) entry.getKey()).replaceFirst("^parameter.", ""), entry.getValue()); } else { Field field = getClass().getDeclaredField((String) entry.getKey()); Object currentValue = field.get(this); if (currentValue == null) { String value = entry.getValue().toString().trim(); if (field.getType().equals(Boolean.class)) { field.set(this, Boolean.valueOf(value)); } else { field.set(this, value); } } } } catch (Exception e) { throw new CommandLineParsingException("Unknown parameter: '" + entry.getKey() + "'"); } } } | Main { protected void parsePropertiesFile(InputStream propertiesInputStream) throws IOException, CommandLineParsingException { Properties props = new Properties(); props.load(propertiesInputStream); for (Map.Entry entry : props.entrySet()) { try { if (entry.getKey().equals("promptOnNonLocalDatabase")) { continue; } if (((String) entry.getKey()).startsWith("parameter.")) { changeLogParameters.put(((String) entry.getKey()).replaceFirst("^parameter.", ""), entry.getValue()); } else { Field field = getClass().getDeclaredField((String) entry.getKey()); Object currentValue = field.get(this); if (currentValue == null) { String value = entry.getValue().toString().trim(); if (field.getType().equals(Boolean.class)) { field.set(this, Boolean.valueOf(value)); } else { field.set(this, value); } } } } catch (Exception e) { throw new CommandLineParsingException("Unknown parameter: '" + entry.getKey() + "'"); } } } } | Main { protected void parsePropertiesFile(InputStream propertiesInputStream) throws IOException, CommandLineParsingException { Properties props = new Properties(); props.load(propertiesInputStream); for (Map.Entry entry : props.entrySet()) { try { if (entry.getKey().equals("promptOnNonLocalDatabase")) { continue; } if (((String) entry.getKey()).startsWith("parameter.")) { changeLogParameters.put(((String) entry.getKey()).replaceFirst("^parameter.", ""), entry.getValue()); } else { Field field = getClass().getDeclaredField((String) entry.getKey()); Object currentValue = field.get(this); if (currentValue == null) { String value = entry.getValue().toString().trim(); if (field.getType().equals(Boolean.class)) { field.set(this, Boolean.valueOf(value)); } else { field.set(this, value); } } } } catch (Exception e) { throw new CommandLineParsingException("Unknown parameter: '" + entry.getKey() + "'"); } } } Main(); } | Main { protected void parsePropertiesFile(InputStream propertiesInputStream) throws IOException, CommandLineParsingException { Properties props = new Properties(); props.load(propertiesInputStream); for (Map.Entry entry : props.entrySet()) { try { if (entry.getKey().equals("promptOnNonLocalDatabase")) { continue; } if (((String) entry.getKey()).startsWith("parameter.")) { changeLogParameters.put(((String) entry.getKey()).replaceFirst("^parameter.", ""), entry.getValue()); } else { Field field = getClass().getDeclaredField((String) entry.getKey()); Object currentValue = field.get(this); if (currentValue == null) { String value = entry.getValue().toString().trim(); if (field.getType().equals(Boolean.class)) { field.set(this, Boolean.valueOf(value)); } else { field.set(this, value); } } } } catch (Exception e) { throw new CommandLineParsingException("Unknown parameter: '" + entry.getKey() + "'"); } } } Main(); static void main(String args[]); boolean isWindows(); } | Main { protected void parsePropertiesFile(InputStream propertiesInputStream) throws IOException, CommandLineParsingException { Properties props = new Properties(); props.load(propertiesInputStream); for (Map.Entry entry : props.entrySet()) { try { if (entry.getKey().equals("promptOnNonLocalDatabase")) { continue; } if (((String) entry.getKey()).startsWith("parameter.")) { changeLogParameters.put(((String) entry.getKey()).replaceFirst("^parameter.", ""), entry.getValue()); } else { Field field = getClass().getDeclaredField((String) entry.getKey()); Object currentValue = field.get(this); if (currentValue == null) { String value = entry.getValue().toString().trim(); if (field.getType().equals(Boolean.class)) { field.set(this, Boolean.valueOf(value)); } else { field.set(this, value); } } } } catch (Exception e) { throw new CommandLineParsingException("Unknown parameter: '" + entry.getKey() + "'"); } } } Main(); static void main(String args[]); boolean isWindows(); } |
@Test public void propertiesFileWithOtherArgs() throws Exception { Main cli = new Main(); cli.username = "PASSED USERNAME"; cli.password = "PASSED PASSWD"; Properties props = new Properties(); props.setProperty("driver", "DRIVER"); props.setProperty("username", "USERNAME"); props.setProperty("password", "PASSWD"); props.setProperty("url", "URL"); props.setProperty("changeLogFile", "FILE"); props.setProperty("classpath", "CLASSPAHT"); props.setProperty("contexts", "CONTEXTS"); props.setProperty("promptForNonLocalDatabase", "TRUE"); ByteArrayOutputStream propFile = new ByteArrayOutputStream(); props.store(propFile, ""); cli.parsePropertiesFile(new ByteArrayInputStream(propFile.toByteArray())); assertEquals("DRIVER", cli.driver); assertEquals("PASSED USERNAME", cli.username); assertEquals("PASSED PASSWD", cli.password); assertEquals("URL", cli.url); assertEquals("FILE", cli.changeLogFile); assertEquals("CLASSPAHT", cli.classpath); assertEquals("CONTEXTS", cli.contexts); assertEquals(Boolean.TRUE, cli.promptForNonLocalDatabase); } | protected void parsePropertiesFile(InputStream propertiesInputStream) throws IOException, CommandLineParsingException { Properties props = new Properties(); props.load(propertiesInputStream); for (Map.Entry entry : props.entrySet()) { try { if (entry.getKey().equals("promptOnNonLocalDatabase")) { continue; } if (((String) entry.getKey()).startsWith("parameter.")) { changeLogParameters.put(((String) entry.getKey()).replaceFirst("^parameter.", ""), entry.getValue()); } else { Field field = getClass().getDeclaredField((String) entry.getKey()); Object currentValue = field.get(this); if (currentValue == null) { String value = entry.getValue().toString().trim(); if (field.getType().equals(Boolean.class)) { field.set(this, Boolean.valueOf(value)); } else { field.set(this, value); } } } } catch (Exception e) { throw new CommandLineParsingException("Unknown parameter: '" + entry.getKey() + "'"); } } } | Main { protected void parsePropertiesFile(InputStream propertiesInputStream) throws IOException, CommandLineParsingException { Properties props = new Properties(); props.load(propertiesInputStream); for (Map.Entry entry : props.entrySet()) { try { if (entry.getKey().equals("promptOnNonLocalDatabase")) { continue; } if (((String) entry.getKey()).startsWith("parameter.")) { changeLogParameters.put(((String) entry.getKey()).replaceFirst("^parameter.", ""), entry.getValue()); } else { Field field = getClass().getDeclaredField((String) entry.getKey()); Object currentValue = field.get(this); if (currentValue == null) { String value = entry.getValue().toString().trim(); if (field.getType().equals(Boolean.class)) { field.set(this, Boolean.valueOf(value)); } else { field.set(this, value); } } } } catch (Exception e) { throw new CommandLineParsingException("Unknown parameter: '" + entry.getKey() + "'"); } } } } | Main { protected void parsePropertiesFile(InputStream propertiesInputStream) throws IOException, CommandLineParsingException { Properties props = new Properties(); props.load(propertiesInputStream); for (Map.Entry entry : props.entrySet()) { try { if (entry.getKey().equals("promptOnNonLocalDatabase")) { continue; } if (((String) entry.getKey()).startsWith("parameter.")) { changeLogParameters.put(((String) entry.getKey()).replaceFirst("^parameter.", ""), entry.getValue()); } else { Field field = getClass().getDeclaredField((String) entry.getKey()); Object currentValue = field.get(this); if (currentValue == null) { String value = entry.getValue().toString().trim(); if (field.getType().equals(Boolean.class)) { field.set(this, Boolean.valueOf(value)); } else { field.set(this, value); } } } } catch (Exception e) { throw new CommandLineParsingException("Unknown parameter: '" + entry.getKey() + "'"); } } } Main(); } | Main { protected void parsePropertiesFile(InputStream propertiesInputStream) throws IOException, CommandLineParsingException { Properties props = new Properties(); props.load(propertiesInputStream); for (Map.Entry entry : props.entrySet()) { try { if (entry.getKey().equals("promptOnNonLocalDatabase")) { continue; } if (((String) entry.getKey()).startsWith("parameter.")) { changeLogParameters.put(((String) entry.getKey()).replaceFirst("^parameter.", ""), entry.getValue()); } else { Field field = getClass().getDeclaredField((String) entry.getKey()); Object currentValue = field.get(this); if (currentValue == null) { String value = entry.getValue().toString().trim(); if (field.getType().equals(Boolean.class)) { field.set(this, Boolean.valueOf(value)); } else { field.set(this, value); } } } } catch (Exception e) { throw new CommandLineParsingException("Unknown parameter: '" + entry.getKey() + "'"); } } } Main(); static void main(String args[]); boolean isWindows(); } | Main { protected void parsePropertiesFile(InputStream propertiesInputStream) throws IOException, CommandLineParsingException { Properties props = new Properties(); props.load(propertiesInputStream); for (Map.Entry entry : props.entrySet()) { try { if (entry.getKey().equals("promptOnNonLocalDatabase")) { continue; } if (((String) entry.getKey()).startsWith("parameter.")) { changeLogParameters.put(((String) entry.getKey()).replaceFirst("^parameter.", ""), entry.getValue()); } else { Field field = getClass().getDeclaredField((String) entry.getKey()); Object currentValue = field.get(this); if (currentValue == null) { String value = entry.getValue().toString().trim(); if (field.getType().equals(Boolean.class)) { field.set(this, Boolean.valueOf(value)); } else { field.set(this, value); } } } } catch (Exception e) { throw new CommandLineParsingException("Unknown parameter: '" + entry.getKey() + "'"); } } } Main(); static void main(String args[]); boolean isWindows(); } |
@Test public void applyDefaults() { Main cli = new Main(); cli.promptForNonLocalDatabase = Boolean.TRUE; cli.applyDefaults(); assertEquals(Boolean.TRUE, cli.promptForNonLocalDatabase); cli.promptForNonLocalDatabase = Boolean.FALSE; cli.applyDefaults(); assertEquals(Boolean.FALSE, cli.promptForNonLocalDatabase); cli.promptForNonLocalDatabase = null; cli.applyDefaults(); assertEquals(Boolean.FALSE, cli.promptForNonLocalDatabase); } | protected void applyDefaults() { if (this.promptForNonLocalDatabase == null) { this.promptForNonLocalDatabase = Boolean.FALSE; } if (this.logLevel == null) { this.logLevel = "info"; } if (this.includeSystemClasspath == null) { this.includeSystemClasspath = Boolean.TRUE; } } | Main { protected void applyDefaults() { if (this.promptForNonLocalDatabase == null) { this.promptForNonLocalDatabase = Boolean.FALSE; } if (this.logLevel == null) { this.logLevel = "info"; } if (this.includeSystemClasspath == null) { this.includeSystemClasspath = Boolean.TRUE; } } } | Main { protected void applyDefaults() { if (this.promptForNonLocalDatabase == null) { this.promptForNonLocalDatabase = Boolean.FALSE; } if (this.logLevel == null) { this.logLevel = "info"; } if (this.includeSystemClasspath == null) { this.includeSystemClasspath = Boolean.TRUE; } } Main(); } | Main { protected void applyDefaults() { if (this.promptForNonLocalDatabase == null) { this.promptForNonLocalDatabase = Boolean.FALSE; } if (this.logLevel == null) { this.logLevel = "info"; } if (this.includeSystemClasspath == null) { this.includeSystemClasspath = Boolean.TRUE; } } Main(); static void main(String args[]); boolean isWindows(); } | Main { protected void applyDefaults() { if (this.promptForNonLocalDatabase == null) { this.promptForNonLocalDatabase = Boolean.FALSE; } if (this.logLevel == null) { this.logLevel = "info"; } if (this.includeSystemClasspath == null) { this.includeSystemClasspath = Boolean.TRUE; } } Main(); static void main(String args[]); boolean isWindows(); } |
@Test(expected = CommandLineParsingException.class) public void propertiesFileWithBadArgs() throws Exception { Main cli = new Main(); Properties props = new Properties(); props.setProperty("driver", "DRIVER"); props.setProperty("username", "USERNAME"); props.setProperty("badArg", "ARG"); ByteArrayOutputStream propFile = new ByteArrayOutputStream(); props.store(propFile, ""); cli.parsePropertiesFile(new ByteArrayInputStream(propFile.toByteArray())); } | protected void parsePropertiesFile(InputStream propertiesInputStream) throws IOException, CommandLineParsingException { Properties props = new Properties(); props.load(propertiesInputStream); for (Map.Entry entry : props.entrySet()) { try { if (entry.getKey().equals("promptOnNonLocalDatabase")) { continue; } if (((String) entry.getKey()).startsWith("parameter.")) { changeLogParameters.put(((String) entry.getKey()).replaceFirst("^parameter.", ""), entry.getValue()); } else { Field field = getClass().getDeclaredField((String) entry.getKey()); Object currentValue = field.get(this); if (currentValue == null) { String value = entry.getValue().toString().trim(); if (field.getType().equals(Boolean.class)) { field.set(this, Boolean.valueOf(value)); } else { field.set(this, value); } } } } catch (Exception e) { throw new CommandLineParsingException("Unknown parameter: '" + entry.getKey() + "'"); } } } | Main { protected void parsePropertiesFile(InputStream propertiesInputStream) throws IOException, CommandLineParsingException { Properties props = new Properties(); props.load(propertiesInputStream); for (Map.Entry entry : props.entrySet()) { try { if (entry.getKey().equals("promptOnNonLocalDatabase")) { continue; } if (((String) entry.getKey()).startsWith("parameter.")) { changeLogParameters.put(((String) entry.getKey()).replaceFirst("^parameter.", ""), entry.getValue()); } else { Field field = getClass().getDeclaredField((String) entry.getKey()); Object currentValue = field.get(this); if (currentValue == null) { String value = entry.getValue().toString().trim(); if (field.getType().equals(Boolean.class)) { field.set(this, Boolean.valueOf(value)); } else { field.set(this, value); } } } } catch (Exception e) { throw new CommandLineParsingException("Unknown parameter: '" + entry.getKey() + "'"); } } } } | Main { protected void parsePropertiesFile(InputStream propertiesInputStream) throws IOException, CommandLineParsingException { Properties props = new Properties(); props.load(propertiesInputStream); for (Map.Entry entry : props.entrySet()) { try { if (entry.getKey().equals("promptOnNonLocalDatabase")) { continue; } if (((String) entry.getKey()).startsWith("parameter.")) { changeLogParameters.put(((String) entry.getKey()).replaceFirst("^parameter.", ""), entry.getValue()); } else { Field field = getClass().getDeclaredField((String) entry.getKey()); Object currentValue = field.get(this); if (currentValue == null) { String value = entry.getValue().toString().trim(); if (field.getType().equals(Boolean.class)) { field.set(this, Boolean.valueOf(value)); } else { field.set(this, value); } } } } catch (Exception e) { throw new CommandLineParsingException("Unknown parameter: '" + entry.getKey() + "'"); } } } Main(); } | Main { protected void parsePropertiesFile(InputStream propertiesInputStream) throws IOException, CommandLineParsingException { Properties props = new Properties(); props.load(propertiesInputStream); for (Map.Entry entry : props.entrySet()) { try { if (entry.getKey().equals("promptOnNonLocalDatabase")) { continue; } if (((String) entry.getKey()).startsWith("parameter.")) { changeLogParameters.put(((String) entry.getKey()).replaceFirst("^parameter.", ""), entry.getValue()); } else { Field field = getClass().getDeclaredField((String) entry.getKey()); Object currentValue = field.get(this); if (currentValue == null) { String value = entry.getValue().toString().trim(); if (field.getType().equals(Boolean.class)) { field.set(this, Boolean.valueOf(value)); } else { field.set(this, value); } } } } catch (Exception e) { throw new CommandLineParsingException("Unknown parameter: '" + entry.getKey() + "'"); } } } Main(); static void main(String args[]); boolean isWindows(); } | Main { protected void parsePropertiesFile(InputStream propertiesInputStream) throws IOException, CommandLineParsingException { Properties props = new Properties(); props.load(propertiesInputStream); for (Map.Entry entry : props.entrySet()) { try { if (entry.getKey().equals("promptOnNonLocalDatabase")) { continue; } if (((String) entry.getKey()).startsWith("parameter.")) { changeLogParameters.put(((String) entry.getKey()).replaceFirst("^parameter.", ""), entry.getValue()); } else { Field field = getClass().getDeclaredField((String) entry.getKey()); Object currentValue = field.get(this); if (currentValue == null) { String value = entry.getValue().toString().trim(); if (field.getType().equals(Boolean.class)) { field.set(this, Boolean.valueOf(value)); } else { field.set(this, value); } } } } catch (Exception e) { throw new CommandLineParsingException("Unknown parameter: '" + entry.getKey() + "'"); } } } Main(); static void main(String args[]); boolean isWindows(); } |
@Test public void checkSetup() { Main cli = new Main(); assertTrue(cli.checkSetup().size() > 0); cli.driver = "driver"; cli.username = "username"; cli.password = "pwd"; cli.url = "url"; cli.changeLogFile = "file"; cli.classpath = "classpath"; assertTrue(cli.checkSetup().size() > 0); cli.command = "BadCommand"; assertTrue(cli.checkSetup().size() > 0); cli.command = "migrate"; assertEquals(0, cli.checkSetup().size()); String[] noArgCommand = { "migrate", "migrateSQL", "update", "updateSQL", "futureRollbackSQL", "updateTestingRollback", "listLocks", "dropAll", "releaseLocks", "validate", "help", "generateChangeLog", "clearCheckSums", "changelogSync", "changelogSyncSQL", "markNextChangeSetRan", "markNextChangeSetRanSQL" }; cli.commandParams.clear(); cli.commandParams.add("--logLevel=debug"); for(int i=0; i<noArgCommand.length; i++) { cli.command = noArgCommand[i]; assertEquals(1, cli.checkSetup().size()); } cli.command = "update"; cli.commandParams.clear(); cli.changeLogParameters.clear(); cli.changeLogParameters.put("engine", "myisam"); assertEquals(0, cli.checkSetup().size()); cli.commandParams.clear(); for(int i=0; i<noArgCommand.length; i++) { cli.command = noArgCommand[i]; assertEquals(0, cli.checkSetup().size()); } String[] singleArgCommand = { "updateCount", "updateCountSQL", "rollback", "rollbackToDate", "rollbackCount", "rollbackSQL", "rollbackToDateSQL", "rollbackCountSQL", "tag", "dbDoc" }; cli.commandParams.add("--logLevel=debug"); for(int i=0; i<singleArgCommand.length; i++) { cli.command = singleArgCommand[i]; assertEquals(1, cli.checkSetup().size()); } cli.commandParams.clear(); cli.commandParams.add("someCommandValue"); for(int i=0; i<singleArgCommand.length; i++) { cli.command = singleArgCommand[i]; assertEquals(0, cli.checkSetup().size()); } cli.command = "status"; cli.commandParams.clear(); assertEquals(0, cli.checkSetup().size()); cli.commandParams.add("--verbose"); assertEquals(0, cli.checkSetup().size()); cli.commandParams.clear(); cli.commandParams.add("--logLevel=debug"); assertEquals(1, cli.checkSetup().size()); String[] multiArgCommand = { "diff", "diffChangeLog" }; cli.commandParams.clear(); for(int i=0; i<multiArgCommand.length; i++) { cli.command = multiArgCommand[i]; assertEquals(0, cli.checkSetup().size()); } String[] cmdParms = { "--referenceUsername=USERNAME", "--referencePassword=PASSWORD", "--referenceUrl=URL", "--referenceDriver=DRIVER"}; for (String param : cmdParms) { cli.commandParams.add(param); } assertEquals(0, cli.checkSetup().size()); cli.commandParams.add("--logLevel=debug"); assertEquals(1, cli.checkSetup().size()); } | protected List<String> checkSetup() { List<String> messages = new ArrayList<String>(); if (command == null) { messages.add("Command not passed"); } else if (!isCommand(command)) { messages.add("Unknown command: " + command); } else { if (url == null) { messages.add("--url is required"); } if (isChangeLogRequired(command) && changeLogFile == null) { messages.add("--changeLogFile is required"); } if (isNoArgCommand(command) && !commandParams.isEmpty()) { messages.add("unexpected command parameters: "+commandParams); } else { validateCommandParameters(messages); } } return messages; } | Main { protected List<String> checkSetup() { List<String> messages = new ArrayList<String>(); if (command == null) { messages.add("Command not passed"); } else if (!isCommand(command)) { messages.add("Unknown command: " + command); } else { if (url == null) { messages.add("--url is required"); } if (isChangeLogRequired(command) && changeLogFile == null) { messages.add("--changeLogFile is required"); } if (isNoArgCommand(command) && !commandParams.isEmpty()) { messages.add("unexpected command parameters: "+commandParams); } else { validateCommandParameters(messages); } } return messages; } } | Main { protected List<String> checkSetup() { List<String> messages = new ArrayList<String>(); if (command == null) { messages.add("Command not passed"); } else if (!isCommand(command)) { messages.add("Unknown command: " + command); } else { if (url == null) { messages.add("--url is required"); } if (isChangeLogRequired(command) && changeLogFile == null) { messages.add("--changeLogFile is required"); } if (isNoArgCommand(command) && !commandParams.isEmpty()) { messages.add("unexpected command parameters: "+commandParams); } else { validateCommandParameters(messages); } } return messages; } Main(); } | Main { protected List<String> checkSetup() { List<String> messages = new ArrayList<String>(); if (command == null) { messages.add("Command not passed"); } else if (!isCommand(command)) { messages.add("Unknown command: " + command); } else { if (url == null) { messages.add("--url is required"); } if (isChangeLogRequired(command) && changeLogFile == null) { messages.add("--changeLogFile is required"); } if (isNoArgCommand(command) && !commandParams.isEmpty()) { messages.add("unexpected command parameters: "+commandParams); } else { validateCommandParameters(messages); } } return messages; } Main(); static void main(String args[]); boolean isWindows(); } | Main { protected List<String> checkSetup() { List<String> messages = new ArrayList<String>(); if (command == null) { messages.add("Command not passed"); } else if (!isCommand(command)) { messages.add("Unknown command: " + command); } else { if (url == null) { messages.add("--url is required"); } if (isChangeLogRequired(command) && changeLogFile == null) { messages.add("--changeLogFile is required"); } if (isNoArgCommand(command) && !commandParams.isEmpty()) { messages.add("unexpected command parameters: "+commandParams); } else { validateCommandParameters(messages); } } return messages; } Main(); static void main(String args[]); boolean isWindows(); } |
@Test public void testGetStreamContents() throws IOException { byte[] contents = "TEST2".getBytes(); ByteArrayInputStream stream = new ByteArrayInputStream(contents); String result = StreamUtil.getStreamContents(stream); assertEquals("TEST2", result); } | public static String getStreamContents(InputStream ins) throws IOException { InputStreamReader reader = new InputStreamReader(ins); return getReaderContents(reader); } | StreamUtil { public static String getStreamContents(InputStream ins) throws IOException { InputStreamReader reader = new InputStreamReader(ins); return getReaderContents(reader); } } | StreamUtil { public static String getStreamContents(InputStream ins) throws IOException { InputStreamReader reader = new InputStreamReader(ins); return getReaderContents(reader); } } | StreamUtil { public static String getStreamContents(InputStream ins) throws IOException { InputStreamReader reader = new InputStreamReader(ins); return getReaderContents(reader); } static String getLineSeparator(); static String getStreamContents(InputStream ins); static String getStreamContents(InputStream ins, String charsetName); static String getReaderContents(Reader reader); static void copy(InputStream inputStream, OutputStream outputStream); } | StreamUtil { public static String getStreamContents(InputStream ins) throws IOException { InputStreamReader reader = new InputStreamReader(ins); return getReaderContents(reader); } static String getLineSeparator(); static String getStreamContents(InputStream ins); static String getStreamContents(InputStream ins, String charsetName); static String getReaderContents(Reader reader); static void copy(InputStream inputStream, OutputStream outputStream); final static String lineSeparator; } |
@Test public void printHelp() throws Exception { ByteArrayOutputStream stream = new ByteArrayOutputStream(); Main cli = new Main(); cli.printHelp(new PrintStream(stream)); BufferedReader reader = new BufferedReader(new StringReader(new String(stream.toByteArray()))); String line; while ((line = reader.readLine()) != null) { if (line.length() > 80) { fail("'" + line + "' is longer than 80 chars"); } } } | protected void printHelp(List<String> errorMessages, PrintStream stream) { stream.println("Errors:"); for (String message : errorMessages) { stream.println(" " + message); } stream.println(); printHelp(stream); } | Main { protected void printHelp(List<String> errorMessages, PrintStream stream) { stream.println("Errors:"); for (String message : errorMessages) { stream.println(" " + message); } stream.println(); printHelp(stream); } } | Main { protected void printHelp(List<String> errorMessages, PrintStream stream) { stream.println("Errors:"); for (String message : errorMessages) { stream.println(" " + message); } stream.println(); printHelp(stream); } Main(); } | Main { protected void printHelp(List<String> errorMessages, PrintStream stream) { stream.println("Errors:"); for (String message : errorMessages) { stream.println(" " + message); } stream.println(); printHelp(stream); } Main(); static void main(String args[]); boolean isWindows(); } | Main { protected void printHelp(List<String> errorMessages, PrintStream stream) { stream.println("Errors:"); for (String message : errorMessages) { stream.println(" " + message); } stream.println(); printHelp(stream); } Main(); static void main(String args[]); boolean isWindows(); } |
@Test public void tag() throws Exception { String[] args = new String[]{ "--driver=DRIVER", "--username=USERNAME", "--password=PASSWORD", "--url=URL", "--changeLogFile=FILE", "--classpath=CLASSPATH;CLASSPATH2", "--contexts=CONTEXT1,CONTEXT2", "tag", "TagHere" }; Main cli = new Main(); cli.parseOptions(args); assertEquals("DRIVER", cli.driver); assertEquals("USERNAME", cli.username); assertEquals("PASSWORD", cli.password); assertEquals("URL", cli.url); assertEquals("FILE", cli.changeLogFile); assertEquals("CLASSPATH;CLASSPATH2", cli.classpath); assertEquals("CONTEXT1,CONTEXT2", cli.contexts); assertEquals("tag", cli.command); assertEquals("TagHere", cli.commandParams.iterator().next()); } | protected void parseOptions(String[] args) throws CommandLineParsingException { args = fixupArgs(args); boolean seenCommand = false; for (String arg : args) { if (isCommand(arg)) { this.command = arg; if (this.command.equalsIgnoreCase("migrate")) { this.command = "update"; } else if (this.command.equalsIgnoreCase("migrateSQL")) { this.command = "updateSQL"; } seenCommand = true; } else if (seenCommand) { if (arg.startsWith("-D")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0].replaceFirst("^-D", ""); String value = splitArg[1]; changeLogParameters.put(attributeName, value); } else { commandParams.add(arg); } } else if (arg.startsWith("--")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0]; String value = splitArg[1]; try { Field field = getClass().getDeclaredField(attributeName); if (field.getType().equals(Boolean.class)) { field.set(this, Boolean.valueOf(value)); } else { field.set(this, value); } } catch (Exception e) { throw new CommandLineParsingException("Unknown parameter: '" + attributeName + "'"); } } else { throw new CommandLineParsingException("Unexpected value " + arg + ": parameters must start with a '--'"); } } } | Main { protected void parseOptions(String[] args) throws CommandLineParsingException { args = fixupArgs(args); boolean seenCommand = false; for (String arg : args) { if (isCommand(arg)) { this.command = arg; if (this.command.equalsIgnoreCase("migrate")) { this.command = "update"; } else if (this.command.equalsIgnoreCase("migrateSQL")) { this.command = "updateSQL"; } seenCommand = true; } else if (seenCommand) { if (arg.startsWith("-D")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0].replaceFirst("^-D", ""); String value = splitArg[1]; changeLogParameters.put(attributeName, value); } else { commandParams.add(arg); } } else if (arg.startsWith("--")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0]; String value = splitArg[1]; try { Field field = getClass().getDeclaredField(attributeName); if (field.getType().equals(Boolean.class)) { field.set(this, Boolean.valueOf(value)); } else { field.set(this, value); } } catch (Exception e) { throw new CommandLineParsingException("Unknown parameter: '" + attributeName + "'"); } } else { throw new CommandLineParsingException("Unexpected value " + arg + ": parameters must start with a '--'"); } } } } | Main { protected void parseOptions(String[] args) throws CommandLineParsingException { args = fixupArgs(args); boolean seenCommand = false; for (String arg : args) { if (isCommand(arg)) { this.command = arg; if (this.command.equalsIgnoreCase("migrate")) { this.command = "update"; } else if (this.command.equalsIgnoreCase("migrateSQL")) { this.command = "updateSQL"; } seenCommand = true; } else if (seenCommand) { if (arg.startsWith("-D")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0].replaceFirst("^-D", ""); String value = splitArg[1]; changeLogParameters.put(attributeName, value); } else { commandParams.add(arg); } } else if (arg.startsWith("--")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0]; String value = splitArg[1]; try { Field field = getClass().getDeclaredField(attributeName); if (field.getType().equals(Boolean.class)) { field.set(this, Boolean.valueOf(value)); } else { field.set(this, value); } } catch (Exception e) { throw new CommandLineParsingException("Unknown parameter: '" + attributeName + "'"); } } else { throw new CommandLineParsingException("Unexpected value " + arg + ": parameters must start with a '--'"); } } } Main(); } | Main { protected void parseOptions(String[] args) throws CommandLineParsingException { args = fixupArgs(args); boolean seenCommand = false; for (String arg : args) { if (isCommand(arg)) { this.command = arg; if (this.command.equalsIgnoreCase("migrate")) { this.command = "update"; } else if (this.command.equalsIgnoreCase("migrateSQL")) { this.command = "updateSQL"; } seenCommand = true; } else if (seenCommand) { if (arg.startsWith("-D")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0].replaceFirst("^-D", ""); String value = splitArg[1]; changeLogParameters.put(attributeName, value); } else { commandParams.add(arg); } } else if (arg.startsWith("--")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0]; String value = splitArg[1]; try { Field field = getClass().getDeclaredField(attributeName); if (field.getType().equals(Boolean.class)) { field.set(this, Boolean.valueOf(value)); } else { field.set(this, value); } } catch (Exception e) { throw new CommandLineParsingException("Unknown parameter: '" + attributeName + "'"); } } else { throw new CommandLineParsingException("Unexpected value " + arg + ": parameters must start with a '--'"); } } } Main(); static void main(String args[]); boolean isWindows(); } | Main { protected void parseOptions(String[] args) throws CommandLineParsingException { args = fixupArgs(args); boolean seenCommand = false; for (String arg : args) { if (isCommand(arg)) { this.command = arg; if (this.command.equalsIgnoreCase("migrate")) { this.command = "update"; } else if (this.command.equalsIgnoreCase("migrateSQL")) { this.command = "updateSQL"; } seenCommand = true; } else if (seenCommand) { if (arg.startsWith("-D")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0].replaceFirst("^-D", ""); String value = splitArg[1]; changeLogParameters.put(attributeName, value); } else { commandParams.add(arg); } } else if (arg.startsWith("--")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0]; String value = splitArg[1]; try { Field field = getClass().getDeclaredField(attributeName); if (field.getType().equals(Boolean.class)) { field.set(this, Boolean.valueOf(value)); } else { field.set(this, value); } } catch (Exception e) { throw new CommandLineParsingException("Unknown parameter: '" + attributeName + "'"); } } else { throw new CommandLineParsingException("Unexpected value " + arg + ": parameters must start with a '--'"); } } } Main(); static void main(String args[]); boolean isWindows(); } |
@Test public void migrateWithEqualsInParams() throws Exception { String url = "dbc:sqlserver: String[] args = new String[]{ "--url=" + url, "migrate", }; Main cli = new Main(); cli.parseOptions(args); assertEquals(url, cli.url); } | protected void parseOptions(String[] args) throws CommandLineParsingException { args = fixupArgs(args); boolean seenCommand = false; for (String arg : args) { if (isCommand(arg)) { this.command = arg; if (this.command.equalsIgnoreCase("migrate")) { this.command = "update"; } else if (this.command.equalsIgnoreCase("migrateSQL")) { this.command = "updateSQL"; } seenCommand = true; } else if (seenCommand) { if (arg.startsWith("-D")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0].replaceFirst("^-D", ""); String value = splitArg[1]; changeLogParameters.put(attributeName, value); } else { commandParams.add(arg); } } else if (arg.startsWith("--")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0]; String value = splitArg[1]; try { Field field = getClass().getDeclaredField(attributeName); if (field.getType().equals(Boolean.class)) { field.set(this, Boolean.valueOf(value)); } else { field.set(this, value); } } catch (Exception e) { throw new CommandLineParsingException("Unknown parameter: '" + attributeName + "'"); } } else { throw new CommandLineParsingException("Unexpected value " + arg + ": parameters must start with a '--'"); } } } | Main { protected void parseOptions(String[] args) throws CommandLineParsingException { args = fixupArgs(args); boolean seenCommand = false; for (String arg : args) { if (isCommand(arg)) { this.command = arg; if (this.command.equalsIgnoreCase("migrate")) { this.command = "update"; } else if (this.command.equalsIgnoreCase("migrateSQL")) { this.command = "updateSQL"; } seenCommand = true; } else if (seenCommand) { if (arg.startsWith("-D")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0].replaceFirst("^-D", ""); String value = splitArg[1]; changeLogParameters.put(attributeName, value); } else { commandParams.add(arg); } } else if (arg.startsWith("--")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0]; String value = splitArg[1]; try { Field field = getClass().getDeclaredField(attributeName); if (field.getType().equals(Boolean.class)) { field.set(this, Boolean.valueOf(value)); } else { field.set(this, value); } } catch (Exception e) { throw new CommandLineParsingException("Unknown parameter: '" + attributeName + "'"); } } else { throw new CommandLineParsingException("Unexpected value " + arg + ": parameters must start with a '--'"); } } } } | Main { protected void parseOptions(String[] args) throws CommandLineParsingException { args = fixupArgs(args); boolean seenCommand = false; for (String arg : args) { if (isCommand(arg)) { this.command = arg; if (this.command.equalsIgnoreCase("migrate")) { this.command = "update"; } else if (this.command.equalsIgnoreCase("migrateSQL")) { this.command = "updateSQL"; } seenCommand = true; } else if (seenCommand) { if (arg.startsWith("-D")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0].replaceFirst("^-D", ""); String value = splitArg[1]; changeLogParameters.put(attributeName, value); } else { commandParams.add(arg); } } else if (arg.startsWith("--")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0]; String value = splitArg[1]; try { Field field = getClass().getDeclaredField(attributeName); if (field.getType().equals(Boolean.class)) { field.set(this, Boolean.valueOf(value)); } else { field.set(this, value); } } catch (Exception e) { throw new CommandLineParsingException("Unknown parameter: '" + attributeName + "'"); } } else { throw new CommandLineParsingException("Unexpected value " + arg + ": parameters must start with a '--'"); } } } Main(); } | Main { protected void parseOptions(String[] args) throws CommandLineParsingException { args = fixupArgs(args); boolean seenCommand = false; for (String arg : args) { if (isCommand(arg)) { this.command = arg; if (this.command.equalsIgnoreCase("migrate")) { this.command = "update"; } else if (this.command.equalsIgnoreCase("migrateSQL")) { this.command = "updateSQL"; } seenCommand = true; } else if (seenCommand) { if (arg.startsWith("-D")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0].replaceFirst("^-D", ""); String value = splitArg[1]; changeLogParameters.put(attributeName, value); } else { commandParams.add(arg); } } else if (arg.startsWith("--")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0]; String value = splitArg[1]; try { Field field = getClass().getDeclaredField(attributeName); if (field.getType().equals(Boolean.class)) { field.set(this, Boolean.valueOf(value)); } else { field.set(this, value); } } catch (Exception e) { throw new CommandLineParsingException("Unknown parameter: '" + attributeName + "'"); } } else { throw new CommandLineParsingException("Unexpected value " + arg + ": parameters must start with a '--'"); } } } Main(); static void main(String args[]); boolean isWindows(); } | Main { protected void parseOptions(String[] args) throws CommandLineParsingException { args = fixupArgs(args); boolean seenCommand = false; for (String arg : args) { if (isCommand(arg)) { this.command = arg; if (this.command.equalsIgnoreCase("migrate")) { this.command = "update"; } else if (this.command.equalsIgnoreCase("migrateSQL")) { this.command = "updateSQL"; } seenCommand = true; } else if (seenCommand) { if (arg.startsWith("-D")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0].replaceFirst("^-D", ""); String value = splitArg[1]; changeLogParameters.put(attributeName, value); } else { commandParams.add(arg); } } else if (arg.startsWith("--")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0]; String value = splitArg[1]; try { Field field = getClass().getDeclaredField(attributeName); if (field.getType().equals(Boolean.class)) { field.set(this, Boolean.valueOf(value)); } else { field.set(this, value); } } catch (Exception e) { throw new CommandLineParsingException("Unknown parameter: '" + attributeName + "'"); } } else { throw new CommandLineParsingException("Unexpected value " + arg + ": parameters must start with a '--'"); } } } Main(); static void main(String args[]); boolean isWindows(); } |
@Test public void fixArgs() { Main liquibase = new Main(); String[] fixedArgs = liquibase.fixupArgs(new String[] {"--defaultsFile","liquibase.properties", "migrate"}); assertEquals("--defaultsFile=liquibase.properties migrate", StringUtils.join(Arrays.asList(fixedArgs), " ")); fixedArgs = liquibase.fixupArgs(new String[] {"--defaultsFile=liquibase.properties", "migrate"}); assertEquals("--defaultsFile=liquibase.properties migrate", StringUtils.join(Arrays.asList(fixedArgs), " ")); fixedArgs = liquibase.fixupArgs(new String[] {"--driver=DRIVER", "--username=USERNAME", "--password=PASSWORD", "--url=URL", "--changeLogFile=FILE", "--classpath=CLASSPATH;CLASSPATH2", "--contexts=CONTEXT1,CONTEXT2", "--promptForNonLocalDatabase=true", "migrate" }); assertEquals("--driver=DRIVER --username=USERNAME --password=PASSWORD --url=URL --changeLogFile=FILE --classpath=CLASSPATH;CLASSPATH2 --contexts=CONTEXT1,CONTEXT2 --promptForNonLocalDatabase=true migrate", StringUtils.join(Arrays.asList(fixedArgs), " ")); } | protected String[] fixupArgs(String[] args) { List<String> fixedArgs = new ArrayList<String>(); for (int i = 0; i < args.length; i++) { String arg = args[i]; if ((arg.startsWith("--") || arg.startsWith("-D")) && !arg.contains("=")) { String nextArg = null; if (i + 1 < args.length) { nextArg = args[i + 1]; } if (nextArg != null && !nextArg.startsWith("--") && !isCommand(nextArg)) { arg = arg + "=" + nextArg; i++; } } fixedArgs.add(arg); } return fixedArgs.toArray(new String[fixedArgs.size()]); } | Main { protected String[] fixupArgs(String[] args) { List<String> fixedArgs = new ArrayList<String>(); for (int i = 0; i < args.length; i++) { String arg = args[i]; if ((arg.startsWith("--") || arg.startsWith("-D")) && !arg.contains("=")) { String nextArg = null; if (i + 1 < args.length) { nextArg = args[i + 1]; } if (nextArg != null && !nextArg.startsWith("--") && !isCommand(nextArg)) { arg = arg + "=" + nextArg; i++; } } fixedArgs.add(arg); } return fixedArgs.toArray(new String[fixedArgs.size()]); } } | Main { protected String[] fixupArgs(String[] args) { List<String> fixedArgs = new ArrayList<String>(); for (int i = 0; i < args.length; i++) { String arg = args[i]; if ((arg.startsWith("--") || arg.startsWith("-D")) && !arg.contains("=")) { String nextArg = null; if (i + 1 < args.length) { nextArg = args[i + 1]; } if (nextArg != null && !nextArg.startsWith("--") && !isCommand(nextArg)) { arg = arg + "=" + nextArg; i++; } } fixedArgs.add(arg); } return fixedArgs.toArray(new String[fixedArgs.size()]); } Main(); } | Main { protected String[] fixupArgs(String[] args) { List<String> fixedArgs = new ArrayList<String>(); for (int i = 0; i < args.length; i++) { String arg = args[i]; if ((arg.startsWith("--") || arg.startsWith("-D")) && !arg.contains("=")) { String nextArg = null; if (i + 1 < args.length) { nextArg = args[i + 1]; } if (nextArg != null && !nextArg.startsWith("--") && !isCommand(nextArg)) { arg = arg + "=" + nextArg; i++; } } fixedArgs.add(arg); } return fixedArgs.toArray(new String[fixedArgs.size()]); } Main(); static void main(String args[]); boolean isWindows(); } | Main { protected String[] fixupArgs(String[] args) { List<String> fixedArgs = new ArrayList<String>(); for (int i = 0; i < args.length; i++) { String arg = args[i]; if ((arg.startsWith("--") || arg.startsWith("-D")) && !arg.contains("=")) { String nextArg = null; if (i + 1 < args.length) { nextArg = args[i + 1]; } if (nextArg != null && !nextArg.startsWith("--") && !isCommand(nextArg)) { arg = arg + "=" + nextArg; i++; } } fixedArgs.add(arg); } return fixedArgs.toArray(new String[fixedArgs.size()]); } Main(); static void main(String args[]); boolean isWindows(); } |
@Test public void testVersionArg() throws IOException, CommandLineParsingException { Main.main(new String[] {"--version"}); } | public static void main(String args[]) throws CommandLineParsingException, IOException { try { String shouldRunProperty = System.getProperty(Liquibase.SHOULD_RUN_SYSTEM_PROPERTY); if (shouldRunProperty != null && !Boolean.valueOf(shouldRunProperty)) { System.err.println("Liquibase did not run because '" + Liquibase.SHOULD_RUN_SYSTEM_PROPERTY + "' system property was set to false"); return; } Main main = new Main(); if (args.length == 1 && "--help".equals(args[0])) { main.printHelp(System.err); return; } else if (args.length == 1 && "--version".equals(args[0])) { System.err.println("Liquibase Version: " + LiquibaseUtil.getBuildVersion() + StreamUtil.getLineSeparator()); return; } try { main.parseOptions(args); } catch (CommandLineParsingException e) { main.printHelp(Arrays.asList(e.getMessage()), System.err); System.exit(-2); } File propertiesFile = new File(main.defaultsFile); File localPropertiesFile = new File(main.defaultsFile.replaceFirst("(\\.[^\\.]+)$", ".local$1")); if (localPropertiesFile.exists()) { main.parsePropertiesFile(new FileInputStream(localPropertiesFile)); } if (propertiesFile.exists()) { main.parsePropertiesFile(new FileInputStream(propertiesFile)); } List<String> setupMessages = main.checkSetup(); if (setupMessages.size() > 0) { main.printHelp(setupMessages, System.err); return; } try { main.applyDefaults(); main.configureClassLoader(); main.doMigration(); } catch (Throwable e) { String message = e.getMessage(); if (e.getCause() != null) { message = e.getCause().getMessage(); } if (message == null) { message = "Unknown Reason"; } if (e.getCause() instanceof ValidationFailedException) { ((ValidationFailedException) e.getCause()).printDescriptiveError(System.err); } else { System.err.println("Liquibase Update Failed: " + message); LogFactory.getLogger().severe(message, e); System.err.println(generateLogLevelWarningMessage()); } System.exit(-1); } if ("update".equals(main.command)) { System.err.println("Liquibase Update Successful"); } else if (main.command.startsWith("rollback") && !main.command.endsWith("SQL")) { System.err.println("Liquibase Rollback Successful"); } else if (!main.command.endsWith("SQL")) { System.err.println("Liquibase '"+main.command+"' Successful"); } } catch (Throwable e) { String message = "Unexpected error running Liquibase: " + e.getMessage(); System.err.println(message); try { LogFactory.getLogger().severe(message, e); } catch (Exception e1) { e.printStackTrace(); } System.exit(-3); } System.exit(0); } | Main { public static void main(String args[]) throws CommandLineParsingException, IOException { try { String shouldRunProperty = System.getProperty(Liquibase.SHOULD_RUN_SYSTEM_PROPERTY); if (shouldRunProperty != null && !Boolean.valueOf(shouldRunProperty)) { System.err.println("Liquibase did not run because '" + Liquibase.SHOULD_RUN_SYSTEM_PROPERTY + "' system property was set to false"); return; } Main main = new Main(); if (args.length == 1 && "--help".equals(args[0])) { main.printHelp(System.err); return; } else if (args.length == 1 && "--version".equals(args[0])) { System.err.println("Liquibase Version: " + LiquibaseUtil.getBuildVersion() + StreamUtil.getLineSeparator()); return; } try { main.parseOptions(args); } catch (CommandLineParsingException e) { main.printHelp(Arrays.asList(e.getMessage()), System.err); System.exit(-2); } File propertiesFile = new File(main.defaultsFile); File localPropertiesFile = new File(main.defaultsFile.replaceFirst("(\\.[^\\.]+)$", ".local$1")); if (localPropertiesFile.exists()) { main.parsePropertiesFile(new FileInputStream(localPropertiesFile)); } if (propertiesFile.exists()) { main.parsePropertiesFile(new FileInputStream(propertiesFile)); } List<String> setupMessages = main.checkSetup(); if (setupMessages.size() > 0) { main.printHelp(setupMessages, System.err); return; } try { main.applyDefaults(); main.configureClassLoader(); main.doMigration(); } catch (Throwable e) { String message = e.getMessage(); if (e.getCause() != null) { message = e.getCause().getMessage(); } if (message == null) { message = "Unknown Reason"; } if (e.getCause() instanceof ValidationFailedException) { ((ValidationFailedException) e.getCause()).printDescriptiveError(System.err); } else { System.err.println("Liquibase Update Failed: " + message); LogFactory.getLogger().severe(message, e); System.err.println(generateLogLevelWarningMessage()); } System.exit(-1); } if ("update".equals(main.command)) { System.err.println("Liquibase Update Successful"); } else if (main.command.startsWith("rollback") && !main.command.endsWith("SQL")) { System.err.println("Liquibase Rollback Successful"); } else if (!main.command.endsWith("SQL")) { System.err.println("Liquibase '"+main.command+"' Successful"); } } catch (Throwable e) { String message = "Unexpected error running Liquibase: " + e.getMessage(); System.err.println(message); try { LogFactory.getLogger().severe(message, e); } catch (Exception e1) { e.printStackTrace(); } System.exit(-3); } System.exit(0); } } | Main { public static void main(String args[]) throws CommandLineParsingException, IOException { try { String shouldRunProperty = System.getProperty(Liquibase.SHOULD_RUN_SYSTEM_PROPERTY); if (shouldRunProperty != null && !Boolean.valueOf(shouldRunProperty)) { System.err.println("Liquibase did not run because '" + Liquibase.SHOULD_RUN_SYSTEM_PROPERTY + "' system property was set to false"); return; } Main main = new Main(); if (args.length == 1 && "--help".equals(args[0])) { main.printHelp(System.err); return; } else if (args.length == 1 && "--version".equals(args[0])) { System.err.println("Liquibase Version: " + LiquibaseUtil.getBuildVersion() + StreamUtil.getLineSeparator()); return; } try { main.parseOptions(args); } catch (CommandLineParsingException e) { main.printHelp(Arrays.asList(e.getMessage()), System.err); System.exit(-2); } File propertiesFile = new File(main.defaultsFile); File localPropertiesFile = new File(main.defaultsFile.replaceFirst("(\\.[^\\.]+)$", ".local$1")); if (localPropertiesFile.exists()) { main.parsePropertiesFile(new FileInputStream(localPropertiesFile)); } if (propertiesFile.exists()) { main.parsePropertiesFile(new FileInputStream(propertiesFile)); } List<String> setupMessages = main.checkSetup(); if (setupMessages.size() > 0) { main.printHelp(setupMessages, System.err); return; } try { main.applyDefaults(); main.configureClassLoader(); main.doMigration(); } catch (Throwable e) { String message = e.getMessage(); if (e.getCause() != null) { message = e.getCause().getMessage(); } if (message == null) { message = "Unknown Reason"; } if (e.getCause() instanceof ValidationFailedException) { ((ValidationFailedException) e.getCause()).printDescriptiveError(System.err); } else { System.err.println("Liquibase Update Failed: " + message); LogFactory.getLogger().severe(message, e); System.err.println(generateLogLevelWarningMessage()); } System.exit(-1); } if ("update".equals(main.command)) { System.err.println("Liquibase Update Successful"); } else if (main.command.startsWith("rollback") && !main.command.endsWith("SQL")) { System.err.println("Liquibase Rollback Successful"); } else if (!main.command.endsWith("SQL")) { System.err.println("Liquibase '"+main.command+"' Successful"); } } catch (Throwable e) { String message = "Unexpected error running Liquibase: " + e.getMessage(); System.err.println(message); try { LogFactory.getLogger().severe(message, e); } catch (Exception e1) { e.printStackTrace(); } System.exit(-3); } System.exit(0); } Main(); } | Main { public static void main(String args[]) throws CommandLineParsingException, IOException { try { String shouldRunProperty = System.getProperty(Liquibase.SHOULD_RUN_SYSTEM_PROPERTY); if (shouldRunProperty != null && !Boolean.valueOf(shouldRunProperty)) { System.err.println("Liquibase did not run because '" + Liquibase.SHOULD_RUN_SYSTEM_PROPERTY + "' system property was set to false"); return; } Main main = new Main(); if (args.length == 1 && "--help".equals(args[0])) { main.printHelp(System.err); return; } else if (args.length == 1 && "--version".equals(args[0])) { System.err.println("Liquibase Version: " + LiquibaseUtil.getBuildVersion() + StreamUtil.getLineSeparator()); return; } try { main.parseOptions(args); } catch (CommandLineParsingException e) { main.printHelp(Arrays.asList(e.getMessage()), System.err); System.exit(-2); } File propertiesFile = new File(main.defaultsFile); File localPropertiesFile = new File(main.defaultsFile.replaceFirst("(\\.[^\\.]+)$", ".local$1")); if (localPropertiesFile.exists()) { main.parsePropertiesFile(new FileInputStream(localPropertiesFile)); } if (propertiesFile.exists()) { main.parsePropertiesFile(new FileInputStream(propertiesFile)); } List<String> setupMessages = main.checkSetup(); if (setupMessages.size() > 0) { main.printHelp(setupMessages, System.err); return; } try { main.applyDefaults(); main.configureClassLoader(); main.doMigration(); } catch (Throwable e) { String message = e.getMessage(); if (e.getCause() != null) { message = e.getCause().getMessage(); } if (message == null) { message = "Unknown Reason"; } if (e.getCause() instanceof ValidationFailedException) { ((ValidationFailedException) e.getCause()).printDescriptiveError(System.err); } else { System.err.println("Liquibase Update Failed: " + message); LogFactory.getLogger().severe(message, e); System.err.println(generateLogLevelWarningMessage()); } System.exit(-1); } if ("update".equals(main.command)) { System.err.println("Liquibase Update Successful"); } else if (main.command.startsWith("rollback") && !main.command.endsWith("SQL")) { System.err.println("Liquibase Rollback Successful"); } else if (!main.command.endsWith("SQL")) { System.err.println("Liquibase '"+main.command+"' Successful"); } } catch (Throwable e) { String message = "Unexpected error running Liquibase: " + e.getMessage(); System.err.println(message); try { LogFactory.getLogger().severe(message, e); } catch (Exception e1) { e.printStackTrace(); } System.exit(-3); } System.exit(0); } Main(); static void main(String args[]); boolean isWindows(); } | Main { public static void main(String args[]) throws CommandLineParsingException, IOException { try { String shouldRunProperty = System.getProperty(Liquibase.SHOULD_RUN_SYSTEM_PROPERTY); if (shouldRunProperty != null && !Boolean.valueOf(shouldRunProperty)) { System.err.println("Liquibase did not run because '" + Liquibase.SHOULD_RUN_SYSTEM_PROPERTY + "' system property was set to false"); return; } Main main = new Main(); if (args.length == 1 && "--help".equals(args[0])) { main.printHelp(System.err); return; } else if (args.length == 1 && "--version".equals(args[0])) { System.err.println("Liquibase Version: " + LiquibaseUtil.getBuildVersion() + StreamUtil.getLineSeparator()); return; } try { main.parseOptions(args); } catch (CommandLineParsingException e) { main.printHelp(Arrays.asList(e.getMessage()), System.err); System.exit(-2); } File propertiesFile = new File(main.defaultsFile); File localPropertiesFile = new File(main.defaultsFile.replaceFirst("(\\.[^\\.]+)$", ".local$1")); if (localPropertiesFile.exists()) { main.parsePropertiesFile(new FileInputStream(localPropertiesFile)); } if (propertiesFile.exists()) { main.parsePropertiesFile(new FileInputStream(propertiesFile)); } List<String> setupMessages = main.checkSetup(); if (setupMessages.size() > 0) { main.printHelp(setupMessages, System.err); return; } try { main.applyDefaults(); main.configureClassLoader(); main.doMigration(); } catch (Throwable e) { String message = e.getMessage(); if (e.getCause() != null) { message = e.getCause().getMessage(); } if (message == null) { message = "Unknown Reason"; } if (e.getCause() instanceof ValidationFailedException) { ((ValidationFailedException) e.getCause()).printDescriptiveError(System.err); } else { System.err.println("Liquibase Update Failed: " + message); LogFactory.getLogger().severe(message, e); System.err.println(generateLogLevelWarningMessage()); } System.exit(-1); } if ("update".equals(main.command)) { System.err.println("Liquibase Update Successful"); } else if (main.command.startsWith("rollback") && !main.command.endsWith("SQL")) { System.err.println("Liquibase Rollback Successful"); } else if (!main.command.endsWith("SQL")) { System.err.println("Liquibase '"+main.command+"' Successful"); } } catch (Throwable e) { String message = "Unexpected error running Liquibase: " + e.getMessage(); System.err.println(message); try { LogFactory.getLogger().severe(message, e); } catch (Exception e1) { e.printStackTrace(); } System.exit(-3); } System.exit(0); } Main(); static void main(String args[]); boolean isWindows(); } |
@Test public void testSplitArgWithValueEndingByEqualSing() throws CommandLineParsingException { final String argName = "password"; final String argValue = "s3-cr3t="; Main tested = new Main(); tested.parseOptions(new String[] { "--" + argName + "=" + argValue }); assertEquals(argValue, tested.password); } | protected void parseOptions(String[] args) throws CommandLineParsingException { args = fixupArgs(args); boolean seenCommand = false; for (String arg : args) { if (isCommand(arg)) { this.command = arg; if (this.command.equalsIgnoreCase("migrate")) { this.command = "update"; } else if (this.command.equalsIgnoreCase("migrateSQL")) { this.command = "updateSQL"; } seenCommand = true; } else if (seenCommand) { if (arg.startsWith("-D")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0].replaceFirst("^-D", ""); String value = splitArg[1]; changeLogParameters.put(attributeName, value); } else { commandParams.add(arg); } } else if (arg.startsWith("--")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0]; String value = splitArg[1]; try { Field field = getClass().getDeclaredField(attributeName); if (field.getType().equals(Boolean.class)) { field.set(this, Boolean.valueOf(value)); } else { field.set(this, value); } } catch (Exception e) { throw new CommandLineParsingException("Unknown parameter: '" + attributeName + "'"); } } else { throw new CommandLineParsingException("Unexpected value " + arg + ": parameters must start with a '--'"); } } } | Main { protected void parseOptions(String[] args) throws CommandLineParsingException { args = fixupArgs(args); boolean seenCommand = false; for (String arg : args) { if (isCommand(arg)) { this.command = arg; if (this.command.equalsIgnoreCase("migrate")) { this.command = "update"; } else if (this.command.equalsIgnoreCase("migrateSQL")) { this.command = "updateSQL"; } seenCommand = true; } else if (seenCommand) { if (arg.startsWith("-D")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0].replaceFirst("^-D", ""); String value = splitArg[1]; changeLogParameters.put(attributeName, value); } else { commandParams.add(arg); } } else if (arg.startsWith("--")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0]; String value = splitArg[1]; try { Field field = getClass().getDeclaredField(attributeName); if (field.getType().equals(Boolean.class)) { field.set(this, Boolean.valueOf(value)); } else { field.set(this, value); } } catch (Exception e) { throw new CommandLineParsingException("Unknown parameter: '" + attributeName + "'"); } } else { throw new CommandLineParsingException("Unexpected value " + arg + ": parameters must start with a '--'"); } } } } | Main { protected void parseOptions(String[] args) throws CommandLineParsingException { args = fixupArgs(args); boolean seenCommand = false; for (String arg : args) { if (isCommand(arg)) { this.command = arg; if (this.command.equalsIgnoreCase("migrate")) { this.command = "update"; } else if (this.command.equalsIgnoreCase("migrateSQL")) { this.command = "updateSQL"; } seenCommand = true; } else if (seenCommand) { if (arg.startsWith("-D")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0].replaceFirst("^-D", ""); String value = splitArg[1]; changeLogParameters.put(attributeName, value); } else { commandParams.add(arg); } } else if (arg.startsWith("--")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0]; String value = splitArg[1]; try { Field field = getClass().getDeclaredField(attributeName); if (field.getType().equals(Boolean.class)) { field.set(this, Boolean.valueOf(value)); } else { field.set(this, value); } } catch (Exception e) { throw new CommandLineParsingException("Unknown parameter: '" + attributeName + "'"); } } else { throw new CommandLineParsingException("Unexpected value " + arg + ": parameters must start with a '--'"); } } } Main(); } | Main { protected void parseOptions(String[] args) throws CommandLineParsingException { args = fixupArgs(args); boolean seenCommand = false; for (String arg : args) { if (isCommand(arg)) { this.command = arg; if (this.command.equalsIgnoreCase("migrate")) { this.command = "update"; } else if (this.command.equalsIgnoreCase("migrateSQL")) { this.command = "updateSQL"; } seenCommand = true; } else if (seenCommand) { if (arg.startsWith("-D")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0].replaceFirst("^-D", ""); String value = splitArg[1]; changeLogParameters.put(attributeName, value); } else { commandParams.add(arg); } } else if (arg.startsWith("--")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0]; String value = splitArg[1]; try { Field field = getClass().getDeclaredField(attributeName); if (field.getType().equals(Boolean.class)) { field.set(this, Boolean.valueOf(value)); } else { field.set(this, value); } } catch (Exception e) { throw new CommandLineParsingException("Unknown parameter: '" + attributeName + "'"); } } else { throw new CommandLineParsingException("Unexpected value " + arg + ": parameters must start with a '--'"); } } } Main(); static void main(String args[]); boolean isWindows(); } | Main { protected void parseOptions(String[] args) throws CommandLineParsingException { args = fixupArgs(args); boolean seenCommand = false; for (String arg : args) { if (isCommand(arg)) { this.command = arg; if (this.command.equalsIgnoreCase("migrate")) { this.command = "update"; } else if (this.command.equalsIgnoreCase("migrateSQL")) { this.command = "updateSQL"; } seenCommand = true; } else if (seenCommand) { if (arg.startsWith("-D")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0].replaceFirst("^-D", ""); String value = splitArg[1]; changeLogParameters.put(attributeName, value); } else { commandParams.add(arg); } } else if (arg.startsWith("--")) { String[] splitArg = splitArg(arg); String attributeName = splitArg[0]; String value = splitArg[1]; try { Field field = getClass().getDeclaredField(attributeName); if (field.getType().equals(Boolean.class)) { field.set(this, Boolean.valueOf(value)); } else { field.set(this, value); } } catch (Exception e) { throw new CommandLineParsingException("Unknown parameter: '" + attributeName + "'"); } } else { throw new CommandLineParsingException("Unexpected value " + arg + ": parameters must start with a '--'"); } } } Main(); static void main(String args[]); boolean isWindows(); } |
@Test public void setValue() throws Exception { ColumnConfig column = new ColumnConfig(); column.setValue(null); assertNull(column.getValue()); column.setValue("abc"); assertEquals("abc", column.getValue()); column.setValue(null); assertEquals("passed null should override the value", null, column.getValue()); column.setValue(""); assertEquals("passed empty strings should override the value", "", column.getValue()); } | public void setValue(String value) { this.value = value; } | ColumnConfig { public void setValue(String value) { this.value = value; } } | ColumnConfig { public void setValue(String value) { this.value = value; } ColumnConfig(Column columnStructure); ColumnConfig(ColumnConfig column); ColumnConfig(); } | ColumnConfig { public void setValue(String value) { this.value = value; } ColumnConfig(Column columnStructure); ColumnConfig(ColumnConfig column); ColumnConfig(); String getName(); ColumnConfig setName(String name); String getType(); ColumnConfig setType(String type); String getValue(); void setValue(String value); Number getValueNumeric(); ColumnConfig setValueNumeric(String valueNumeric); ColumnConfig setValueNumeric(Number valueNumeric); Boolean getValueBoolean(); ColumnConfig setValueBoolean(Boolean valueBoolean); DatabaseFunction getValueComputed(); ColumnConfig setValueComputed(DatabaseFunction valueComputed); Date getValueDate(); ColumnConfig setValueDate(Date valueDate); ColumnConfig setValueDate(String valueDate); Object getValueObject(); String getDefaultValue(); ColumnConfig setDefaultValue(String defaultValue); Number getDefaultValueNumeric(); ColumnConfig setDefaultValueNumeric(Number defaultValueNumeric); ColumnConfig setDefaultValueNumeric(String defaultValueNumeric); Date getDefaultValueDate(); ColumnConfig setDefaultValueDate(String defaultValueDate); ColumnConfig setDefaultValueDate(Date defaultValueDate); Boolean getDefaultValueBoolean(); ColumnConfig setDefaultValueBoolean(Boolean defaultValueBoolean); DatabaseFunction getDefaultValueComputed(); ColumnConfig setDefaultValueComputed(DatabaseFunction defaultValueComputed); Object getDefaultValueObject(); ConstraintsConfig getConstraints(); ColumnConfig setConstraints(ConstraintsConfig constraints); Boolean isAutoIncrement(); ColumnConfig setAutoIncrement(Boolean autoIncrement); BigInteger getStartWith(); ColumnConfig setStartWith(BigInteger startWith); BigInteger getIncrementBy(); ColumnConfig setIncrementBy(BigInteger incrementBy); boolean isPrimaryKey(); boolean isNullable(); boolean hasDefaultValue(); String getRemarks(); ColumnConfig setRemarks(String remarks); } | ColumnConfig { public void setValue(String value) { this.value = value; } ColumnConfig(Column columnStructure); ColumnConfig(ColumnConfig column); ColumnConfig(); String getName(); ColumnConfig setName(String name); String getType(); ColumnConfig setType(String type); String getValue(); void setValue(String value); Number getValueNumeric(); ColumnConfig setValueNumeric(String valueNumeric); ColumnConfig setValueNumeric(Number valueNumeric); Boolean getValueBoolean(); ColumnConfig setValueBoolean(Boolean valueBoolean); DatabaseFunction getValueComputed(); ColumnConfig setValueComputed(DatabaseFunction valueComputed); Date getValueDate(); ColumnConfig setValueDate(Date valueDate); ColumnConfig setValueDate(String valueDate); Object getValueObject(); String getDefaultValue(); ColumnConfig setDefaultValue(String defaultValue); Number getDefaultValueNumeric(); ColumnConfig setDefaultValueNumeric(Number defaultValueNumeric); ColumnConfig setDefaultValueNumeric(String defaultValueNumeric); Date getDefaultValueDate(); ColumnConfig setDefaultValueDate(String defaultValueDate); ColumnConfig setDefaultValueDate(Date defaultValueDate); Boolean getDefaultValueBoolean(); ColumnConfig setDefaultValueBoolean(Boolean defaultValueBoolean); DatabaseFunction getDefaultValueComputed(); ColumnConfig setDefaultValueComputed(DatabaseFunction defaultValueComputed); Object getDefaultValueObject(); ConstraintsConfig getConstraints(); ColumnConfig setConstraints(ConstraintsConfig constraints); Boolean isAutoIncrement(); ColumnConfig setAutoIncrement(Boolean autoIncrement); BigInteger getStartWith(); ColumnConfig setStartWith(BigInteger startWith); BigInteger getIncrementBy(); ColumnConfig setIncrementBy(BigInteger incrementBy); boolean isPrimaryKey(); boolean isNullable(); boolean hasDefaultValue(); String getRemarks(); ColumnConfig setRemarks(String remarks); } |
@Override @Test public void getConfirmationMessage() throws Exception { DropPrimaryKeyChange change = new DropPrimaryKeyChange(); change.setSchemaName("SCHEMA_NAME"); change.setTableName("TABLE_NAME"); change.setConstraintName("PK_NAME"); assertEquals("Primary key dropped from TABLE_NAME", change.getConfirmationMessage()); } | public String getConfirmationMessage() { return "Primary key dropped from "+getTableName(); } | DropPrimaryKeyChange extends AbstractChange { public String getConfirmationMessage() { return "Primary key dropped from "+getTableName(); } } | DropPrimaryKeyChange extends AbstractChange { public String getConfirmationMessage() { return "Primary key dropped from "+getTableName(); } DropPrimaryKeyChange(); } | DropPrimaryKeyChange extends AbstractChange { public String getConfirmationMessage() { return "Primary key dropped from "+getTableName(); } DropPrimaryKeyChange(); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); String getConstraintName(); void setConstraintName(String constraintName); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); } | DropPrimaryKeyChange extends AbstractChange { public String getConfirmationMessage() { return "Primary key dropped from "+getTableName(); } DropPrimaryKeyChange(); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); String getConstraintName(); void setConstraintName(String constraintName); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); } |
@Override @Test public void getConfirmationMessage() throws Exception { DropDefaultValueChange change = new DropDefaultValueChange(); change.setTableName("TABLE_NAME"); change.setColumnName("COL_HERE"); assertEquals("Default value dropped from TABLE_NAME.COL_HERE", change.getConfirmationMessage()); } | public String getConfirmationMessage() { return "Default value dropped from "+getTableName()+"."+getColumnName(); } | DropDefaultValueChange extends AbstractChange { public String getConfirmationMessage() { return "Default value dropped from "+getTableName()+"."+getColumnName(); } } | DropDefaultValueChange extends AbstractChange { public String getConfirmationMessage() { return "Default value dropped from "+getTableName()+"."+getColumnName(); } DropDefaultValueChange(); } | DropDefaultValueChange extends AbstractChange { public String getConfirmationMessage() { return "Default value dropped from "+getTableName()+"."+getColumnName(); } DropDefaultValueChange(); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); String getColumnName(); void setColumnName(String columnName); String getColumnDataType(); void setColumnDataType(String columnDataType); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); } | DropDefaultValueChange extends AbstractChange { public String getConfirmationMessage() { return "Default value dropped from "+getTableName()+"."+getColumnName(); } DropDefaultValueChange(); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); String getColumnName(); void setColumnName(String columnName); String getColumnDataType(); void setColumnDataType(String columnDataType); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); } |
@Test public void addColumn() throws Exception { AddColumnChange change = new AddColumnChange(); assertEquals(0, change.getColumns().size()); change.addColumn(new ColumnConfig().setName("a")); assertEquals(1, change.getColumns().size()); change.addColumn(new ColumnConfig().setName("b")); assertEquals(2, change.getColumns().size()); } | public void addColumn(ColumnConfig column) { columns.add(column); } | AddColumnChange extends AbstractChange implements ChangeWithColumns<ColumnConfig> { public void addColumn(ColumnConfig column) { columns.add(column); } } | AddColumnChange extends AbstractChange implements ChangeWithColumns<ColumnConfig> { public void addColumn(ColumnConfig column) { columns.add(column); } AddColumnChange(); } | AddColumnChange extends AbstractChange implements ChangeWithColumns<ColumnConfig> { public void addColumn(ColumnConfig column) { columns.add(column); } AddColumnChange(); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); List<ColumnConfig> getColumns(); void addColumn(ColumnConfig column); void removeColumn(ColumnConfig column); @Override ValidationErrors validate(Database database); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); } | AddColumnChange extends AbstractChange implements ChangeWithColumns<ColumnConfig> { public void addColumn(ColumnConfig column) { columns.add(column); } AddColumnChange(); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); List<ColumnConfig> getColumns(); void addColumn(ColumnConfig column); void removeColumn(ColumnConfig column); @Override ValidationErrors validate(Database database); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); } |
@Test public void testGetReaderContents() throws IOException { String contents = "TEST"; StringReader reader = new StringReader(contents); String result = StreamUtil.getReaderContents(reader); assertEquals(contents, result); } | public static String getReaderContents(Reader reader) throws IOException { try { StringBuffer result = new StringBuffer(); char[] buffer = new char[2048]; int read; while ((read = reader.read(buffer)) > -1) { result.append(buffer, 0, read); } return result.toString(); } finally { try { reader.close(); } catch (IOException ioe) { } } } | StreamUtil { public static String getReaderContents(Reader reader) throws IOException { try { StringBuffer result = new StringBuffer(); char[] buffer = new char[2048]; int read; while ((read = reader.read(buffer)) > -1) { result.append(buffer, 0, read); } return result.toString(); } finally { try { reader.close(); } catch (IOException ioe) { } } } } | StreamUtil { public static String getReaderContents(Reader reader) throws IOException { try { StringBuffer result = new StringBuffer(); char[] buffer = new char[2048]; int read; while ((read = reader.read(buffer)) > -1) { result.append(buffer, 0, read); } return result.toString(); } finally { try { reader.close(); } catch (IOException ioe) { } } } } | StreamUtil { public static String getReaderContents(Reader reader) throws IOException { try { StringBuffer result = new StringBuffer(); char[] buffer = new char[2048]; int read; while ((read = reader.read(buffer)) > -1) { result.append(buffer, 0, read); } return result.toString(); } finally { try { reader.close(); } catch (IOException ioe) { } } } static String getLineSeparator(); static String getStreamContents(InputStream ins); static String getStreamContents(InputStream ins, String charsetName); static String getReaderContents(Reader reader); static void copy(InputStream inputStream, OutputStream outputStream); } | StreamUtil { public static String getReaderContents(Reader reader) throws IOException { try { StringBuffer result = new StringBuffer(); char[] buffer = new char[2048]; int read; while ((read = reader.read(buffer)) > -1) { result.append(buffer, 0, read); } return result.toString(); } finally { try { reader.close(); } catch (IOException ioe) { } } } static String getLineSeparator(); static String getStreamContents(InputStream ins); static String getStreamContents(InputStream ins, String charsetName); static String getReaderContents(Reader reader); static void copy(InputStream inputStream, OutputStream outputStream); final static String lineSeparator; } |
@Test public void removeColumn() throws Exception { ColumnConfig columnA = new ColumnConfig().setName("a"); ColumnConfig columnB = new ColumnConfig().setName("b"); AddColumnChange change = new AddColumnChange(); assertEquals(0, change.getColumns().size()); change.removeColumn(columnA); assertEquals(0, change.getColumns().size()); change.addColumn(columnA); assertEquals(1, change.getColumns().size()); change.removeColumn(columnB); assertEquals(1, change.getColumns().size()); change.removeColumn(columnA); assertEquals(0, change.getColumns().size()); } | public void removeColumn(ColumnConfig column) { columns.remove(column); } | AddColumnChange extends AbstractChange implements ChangeWithColumns<ColumnConfig> { public void removeColumn(ColumnConfig column) { columns.remove(column); } } | AddColumnChange extends AbstractChange implements ChangeWithColumns<ColumnConfig> { public void removeColumn(ColumnConfig column) { columns.remove(column); } AddColumnChange(); } | AddColumnChange extends AbstractChange implements ChangeWithColumns<ColumnConfig> { public void removeColumn(ColumnConfig column) { columns.remove(column); } AddColumnChange(); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); List<ColumnConfig> getColumns(); void addColumn(ColumnConfig column); void removeColumn(ColumnConfig column); @Override ValidationErrors validate(Database database); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); } | AddColumnChange extends AbstractChange implements ChangeWithColumns<ColumnConfig> { public void removeColumn(ColumnConfig column) { columns.remove(column); } AddColumnChange(); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); List<ColumnConfig> getColumns(); void addColumn(ColumnConfig column); void removeColumn(ColumnConfig column); @Override ValidationErrors validate(Database database); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); } |
@Override @Test public void getConfirmationMessage() throws Exception { AddColumnChange refactoring = new AddColumnChange(); refactoring.setTableName("TAB"); ColumnConfig column = new ColumnConfig(); column.setName("NEWCOL"); column.setType("TYP"); refactoring.addColumn(column); assertEquals("Columns NEWCOL(TYP) added to TAB", refactoring.getConfirmationMessage()); } | public String getConfirmationMessage() { List<String> names = new ArrayList<String>(columns.size()); for (ColumnConfig col : columns) { names.add(col.getName() + "(" + col.getType() + ")"); } return "Columns " + StringUtils.join(names, ",") + " added to " + tableName; } | AddColumnChange extends AbstractChange implements ChangeWithColumns<ColumnConfig> { public String getConfirmationMessage() { List<String> names = new ArrayList<String>(columns.size()); for (ColumnConfig col : columns) { names.add(col.getName() + "(" + col.getType() + ")"); } return "Columns " + StringUtils.join(names, ",") + " added to " + tableName; } } | AddColumnChange extends AbstractChange implements ChangeWithColumns<ColumnConfig> { public String getConfirmationMessage() { List<String> names = new ArrayList<String>(columns.size()); for (ColumnConfig col : columns) { names.add(col.getName() + "(" + col.getType() + ")"); } return "Columns " + StringUtils.join(names, ",") + " added to " + tableName; } AddColumnChange(); } | AddColumnChange extends AbstractChange implements ChangeWithColumns<ColumnConfig> { public String getConfirmationMessage() { List<String> names = new ArrayList<String>(columns.size()); for (ColumnConfig col : columns) { names.add(col.getName() + "(" + col.getType() + ")"); } return "Columns " + StringUtils.join(names, ",") + " added to " + tableName; } AddColumnChange(); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); List<ColumnConfig> getColumns(); void addColumn(ColumnConfig column); void removeColumn(ColumnConfig column); @Override ValidationErrors validate(Database database); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); } | AddColumnChange extends AbstractChange implements ChangeWithColumns<ColumnConfig> { public String getConfirmationMessage() { List<String> names = new ArrayList<String>(columns.size()); for (ColumnConfig col : columns) { names.add(col.getName() + "(" + col.getType() + ")"); } return "Columns " + StringUtils.join(names, ",") + " added to " + tableName; } AddColumnChange(); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); List<ColumnConfig> getColumns(); void addColumn(ColumnConfig column); void removeColumn(ColumnConfig column); @Override ValidationErrors validate(Database database); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); } |
@Override @Test public void getConfirmationMessage() throws Exception { CreateProcedureChange refactoring = new CreateProcedureChange(); assertEquals("Stored procedure created", refactoring.getConfirmationMessage()); } | public String getConfirmationMessage() { return "Stored procedure created"; } | CreateProcedureChange extends AbstractChange { public String getConfirmationMessage() { return "Stored procedure created"; } } | CreateProcedureChange extends AbstractChange { public String getConfirmationMessage() { return "Stored procedure created"; } CreateProcedureChange(); } | CreateProcedureChange extends AbstractChange { public String getConfirmationMessage() { return "Stored procedure created"; } CreateProcedureChange(); String getProcedureBody(); void setProcedureBody(String procedureBody); String getComments(); void setComments(String comments); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); } | CreateProcedureChange extends AbstractChange { public String getConfirmationMessage() { return "Stored procedure created"; } CreateProcedureChange(); String getProcedureBody(); void setProcedureBody(String procedureBody); String getComments(); void setComments(String comments); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); } |
@Override @Test public void getConfirmationMessage() throws Exception { refactoring.setOldTableName("OLD_NAME"); refactoring.setNewTableName("NEW_NAME"); assertEquals("Table OLD_NAME renamed to NEW_NAME", refactoring.getConfirmationMessage()); } | public String getConfirmationMessage() { return "Table " + oldTableName + " renamed to " + newTableName; } | RenameTableChange extends AbstractChange { public String getConfirmationMessage() { return "Table " + oldTableName + " renamed to " + newTableName; } } | RenameTableChange extends AbstractChange { public String getConfirmationMessage() { return "Table " + oldTableName + " renamed to " + newTableName; } RenameTableChange(); } | RenameTableChange extends AbstractChange { public String getConfirmationMessage() { return "Table " + oldTableName + " renamed to " + newTableName; } RenameTableChange(); String getSchemaName(); void setSchemaName(String schemaName); String getOldTableName(); void setOldTableName(String oldTableName); String getNewTableName(); void setNewTableName(String newTableName); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); } | RenameTableChange extends AbstractChange { public String getConfirmationMessage() { return "Table " + oldTableName + " renamed to " + newTableName; } RenameTableChange(); String getSchemaName(); void setSchemaName(String schemaName); String getOldTableName(); void setOldTableName(String oldTableName); String getNewTableName(); void setNewTableName(String newTableName); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); } |
@Override @Test public void getConfirmationMessage() throws Exception { assertEquals("Custom SQL executed", refactoring.getConfirmationMessage()); } | public String getConfirmationMessage() { return "Custom SQL executed"; } | RawSQLChange extends AbstractSQLChange { public String getConfirmationMessage() { return "Custom SQL executed"; } } | RawSQLChange extends AbstractSQLChange { public String getConfirmationMessage() { return "Custom SQL executed"; } RawSQLChange(); RawSQLChange(String sql); } | RawSQLChange extends AbstractSQLChange { public String getConfirmationMessage() { return "Custom SQL executed"; } RawSQLChange(); RawSQLChange(String sql); String getComments(); void setComments(String comments); String getConfirmationMessage(); } | RawSQLChange extends AbstractSQLChange { public String getConfirmationMessage() { return "Custom SQL executed"; } RawSQLChange(); RawSQLChange(String sql); String getComments(); void setComments(String comments); String getConfirmationMessage(); } |
@Override @Test public void getConfirmationMessage() throws Exception { DropIndexChange refactoring = new DropIndexChange(); refactoring.setIndexName("IDX_NAME"); refactoring.setTableName("TABLE_NAME"); assertEquals("Index IDX_NAME dropped from table TABLE_NAME", refactoring.getConfirmationMessage()); } | public String getConfirmationMessage() { return "Index " + getIndexName() + " dropped from table " + getTableName(); } | DropIndexChange extends AbstractChange { public String getConfirmationMessage() { return "Index " + getIndexName() + " dropped from table " + getTableName(); } } | DropIndexChange extends AbstractChange { public String getConfirmationMessage() { return "Index " + getIndexName() + " dropped from table " + getTableName(); } DropIndexChange(); } | DropIndexChange extends AbstractChange { public String getConfirmationMessage() { return "Index " + getIndexName() + " dropped from table " + getTableName(); } DropIndexChange(); String getSchemaName(); void setSchemaName(String schemaName); String getIndexName(); void setIndexName(String indexName); String getTableName(); void setTableName(String tableName); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); String getAssociatedWith(); void setAssociatedWith(String associatedWith); } | DropIndexChange extends AbstractChange { public String getConfirmationMessage() { return "Index " + getIndexName() + " dropped from table " + getTableName(); } DropIndexChange(); String getSchemaName(); void setSchemaName(String schemaName); String getIndexName(); void setIndexName(String indexName); String getTableName(); void setTableName(String tableName); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); String getAssociatedWith(); void setAssociatedWith(String associatedWith); } |
@Override @Test public void getConfirmationMessage() throws Exception { refactoring.setTag("TAG_NAME"); assertEquals("Tag 'TAG_NAME' applied to database", refactoring.getConfirmationMessage()); } | public String getConfirmationMessage() { return "Tag '"+tag+"' applied to database"; } | TagDatabaseChange extends AbstractChange { public String getConfirmationMessage() { return "Tag '"+tag+"' applied to database"; } } | TagDatabaseChange extends AbstractChange { public String getConfirmationMessage() { return "Tag '"+tag+"' applied to database"; } TagDatabaseChange(); } | TagDatabaseChange extends AbstractChange { public String getConfirmationMessage() { return "Tag '"+tag+"' applied to database"; } TagDatabaseChange(); String getTag(); void setTag(String tag); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); } | TagDatabaseChange extends AbstractChange { public String getConfirmationMessage() { return "Tag '"+tag+"' applied to database"; } TagDatabaseChange(); String getTag(); void setTag(String tag); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); } |
@Override @Test public void getConfirmationMessage() throws Exception { AddForeignKeyConstraintChange change = new AddForeignKeyConstraintChange(); change.setConstraintName("FK_NAME"); change.setBaseTableSchemaName("SCHEMA_NAME"); change.setBaseTableName("TABLE_NAME"); change.setBaseColumnNames("COL_NAME"); assertEquals("Foreign key contraint added to TABLE_NAME (COL_NAME)", change.getConfirmationMessage()); } | public String getConfirmationMessage() { return "Foreign key contraint added to " + getBaseTableName() + " (" + getBaseColumnNames() + ")"; } | AddForeignKeyConstraintChange extends AbstractChange { public String getConfirmationMessage() { return "Foreign key contraint added to " + getBaseTableName() + " (" + getBaseColumnNames() + ")"; } } | AddForeignKeyConstraintChange extends AbstractChange { public String getConfirmationMessage() { return "Foreign key contraint added to " + getBaseTableName() + " (" + getBaseColumnNames() + ")"; } AddForeignKeyConstraintChange(); } | AddForeignKeyConstraintChange extends AbstractChange { public String getConfirmationMessage() { return "Foreign key contraint added to " + getBaseTableName() + " (" + getBaseColumnNames() + ")"; } AddForeignKeyConstraintChange(); String getBaseTableSchemaName(); void setBaseTableSchemaName(String baseTableSchemaName); String getBaseTableName(); void setBaseTableName(String baseTableName); String getBaseColumnNames(); void setBaseColumnNames(String baseColumnNames); String getReferencedTableSchemaName(); void setReferencedTableSchemaName(String referencedTableSchemaName); String getReferencedTableName(); void setReferencedTableName(String referencedTableName); String getReferencedColumnNames(); void setReferencedColumnNames(String referencedColumnNames); String getConstraintName(); void setConstraintName(String constraintName); Boolean getDeferrable(); void setDeferrable(Boolean deferrable); Boolean getInitiallyDeferred(); void setInitiallyDeferred(Boolean initiallyDeferred); void setDeleteCascade(Boolean deleteCascade); void setOnUpdate(String rule); String getOnUpdate(); void setOnDelete(String onDelete); String getOnDelete(); Boolean getReferencesUniqueColumn(); void setReferencesUniqueColumn(Boolean referencesUniqueColumn); void setOnDelete(ForeignKeyConstraintType rule); void setOnUpdate(ForeignKeyConstraintType rule); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); } | AddForeignKeyConstraintChange extends AbstractChange { public String getConfirmationMessage() { return "Foreign key contraint added to " + getBaseTableName() + " (" + getBaseColumnNames() + ")"; } AddForeignKeyConstraintChange(); String getBaseTableSchemaName(); void setBaseTableSchemaName(String baseTableSchemaName); String getBaseTableName(); void setBaseTableName(String baseTableName); String getBaseColumnNames(); void setBaseColumnNames(String baseColumnNames); String getReferencedTableSchemaName(); void setReferencedTableSchemaName(String referencedTableSchemaName); String getReferencedTableName(); void setReferencedTableName(String referencedTableName); String getReferencedColumnNames(); void setReferencedColumnNames(String referencedColumnNames); String getConstraintName(); void setConstraintName(String constraintName); Boolean getDeferrable(); void setDeferrable(Boolean deferrable); Boolean getInitiallyDeferred(); void setInitiallyDeferred(Boolean initiallyDeferred); void setDeleteCascade(Boolean deleteCascade); void setOnUpdate(String rule); String getOnUpdate(); void setOnDelete(String onDelete); String getOnDelete(); Boolean getReferencesUniqueColumn(); void setReferencesUniqueColumn(Boolean referencesUniqueColumn); void setOnDelete(ForeignKeyConstraintType rule); void setOnUpdate(ForeignKeyConstraintType rule); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); } |
@Override @Test public void getConfirmationMessage() throws Exception { assertEquals("Column TABLE_NAME.oldColName renamed to newColName", refactoring.getConfirmationMessage()); } | public String getConfirmationMessage() { return "Column "+tableName+"."+ oldColumnName + " renamed to " + newColumnName; } | RenameColumnChange extends AbstractChange { public String getConfirmationMessage() { return "Column "+tableName+"."+ oldColumnName + " renamed to " + newColumnName; } } | RenameColumnChange extends AbstractChange { public String getConfirmationMessage() { return "Column "+tableName+"."+ oldColumnName + " renamed to " + newColumnName; } RenameColumnChange(); } | RenameColumnChange extends AbstractChange { public String getConfirmationMessage() { return "Column "+tableName+"."+ oldColumnName + " renamed to " + newColumnName; } RenameColumnChange(); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); String getOldColumnName(); void setOldColumnName(String oldColumnName); String getNewColumnName(); void setNewColumnName(String newColumnName); String getColumnDataType(); void setColumnDataType(String columnDataType); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); } | RenameColumnChange extends AbstractChange { public String getConfirmationMessage() { return "Column "+tableName+"."+ oldColumnName + " renamed to " + newColumnName; } RenameColumnChange(); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); String getOldColumnName(); void setOldColumnName(String oldColumnName); String getNewColumnName(); void setNewColumnName(String newColumnName); String getColumnDataType(); void setColumnDataType(String columnDataType); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); } |
@Override @Test public void getConfirmationMessage() throws Exception { AlterSequenceChange refactoring = new AlterSequenceChange(); refactoring.setSequenceName("SEQ_NAME"); assertEquals("Sequence SEQ_NAME altered", refactoring.getConfirmationMessage()); } | public String getConfirmationMessage() { return "Sequence " + getSequenceName() + " altered"; } | AlterSequenceChange extends AbstractChange { public String getConfirmationMessage() { return "Sequence " + getSequenceName() + " altered"; } } | AlterSequenceChange extends AbstractChange { public String getConfirmationMessage() { return "Sequence " + getSequenceName() + " altered"; } AlterSequenceChange(); } | AlterSequenceChange extends AbstractChange { public String getConfirmationMessage() { return "Sequence " + getSequenceName() + " altered"; } AlterSequenceChange(); String getSchemaName(); void setSchemaName(String schemaName); String getSequenceName(); void setSequenceName(String sequenceName); BigInteger getIncrementBy(); void setIncrementBy(BigInteger incrementBy); BigInteger getMaxValue(); void setMaxValue(BigInteger maxValue); BigInteger getMinValue(); void setMinValue(BigInteger minValue); Boolean isOrdered(); void setOrdered(Boolean ordered); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); } | AlterSequenceChange extends AbstractChange { public String getConfirmationMessage() { return "Sequence " + getSequenceName() + " altered"; } AlterSequenceChange(); String getSchemaName(); void setSchemaName(String schemaName); String getSequenceName(); void setSequenceName(String sequenceName); BigInteger getIncrementBy(); void setIncrementBy(BigInteger incrementBy); BigInteger getMaxValue(); void setMaxValue(BigInteger maxValue); BigInteger getMinValue(); void setMinValue(BigInteger minValue); Boolean isOrdered(); void setOrdered(Boolean ordered); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); } |
@Test public void testComputeMD5() throws Exception { String hash = MD5Util.computeMD5(TEST_STRING); assertEquals(TEST_STRING_MD5_HASH, hash); String hash2 = MD5Util.computeMD5(TEST_STRING2); assertEquals(TEST_STRING2_MD5_HASH, hash2); String hash3 = MD5Util.computeMD5(TEST_STRING3); assertEquals(TEST_STRING3_MD5_HASH, hash3); } | public static String computeMD5(String input) { if (input == null) { return null; } MessageDigest digest; try { digest = MessageDigest.getInstance("MD5"); digest.update(input.getBytes("UTF-8")); } catch (Exception e) { throw new UnexpectedLiquibaseException(e); } byte[] digestBytes = digest.digest(); String returnString = new String(encodeHex(digestBytes)); LogFactory.getLogger().debug("Computed checksum for "+input+" as "+returnString); return returnString; } | MD5Util { public static String computeMD5(String input) { if (input == null) { return null; } MessageDigest digest; try { digest = MessageDigest.getInstance("MD5"); digest.update(input.getBytes("UTF-8")); } catch (Exception e) { throw new UnexpectedLiquibaseException(e); } byte[] digestBytes = digest.digest(); String returnString = new String(encodeHex(digestBytes)); LogFactory.getLogger().debug("Computed checksum for "+input+" as "+returnString); return returnString; } } | MD5Util { public static String computeMD5(String input) { if (input == null) { return null; } MessageDigest digest; try { digest = MessageDigest.getInstance("MD5"); digest.update(input.getBytes("UTF-8")); } catch (Exception e) { throw new UnexpectedLiquibaseException(e); } byte[] digestBytes = digest.digest(); String returnString = new String(encodeHex(digestBytes)); LogFactory.getLogger().debug("Computed checksum for "+input+" as "+returnString); return returnString; } } | MD5Util { public static String computeMD5(String input) { if (input == null) { return null; } MessageDigest digest; try { digest = MessageDigest.getInstance("MD5"); digest.update(input.getBytes("UTF-8")); } catch (Exception e) { throw new UnexpectedLiquibaseException(e); } byte[] digestBytes = digest.digest(); String returnString = new String(encodeHex(digestBytes)); LogFactory.getLogger().debug("Computed checksum for "+input+" as "+returnString); return returnString; } static String computeMD5(String input); static String computeMD5(InputStream stream); } | MD5Util { public static String computeMD5(String input) { if (input == null) { return null; } MessageDigest digest; try { digest = MessageDigest.getInstance("MD5"); digest.update(input.getBytes("UTF-8")); } catch (Exception e) { throw new UnexpectedLiquibaseException(e); } byte[] digestBytes = digest.digest(); String returnString = new String(encodeHex(digestBytes)); LogFactory.getLogger().debug("Computed checksum for "+input+" as "+returnString); return returnString; } static String computeMD5(String input); static String computeMD5(InputStream stream); } |
@Override @Test public void getConfirmationMessage() throws Exception { DropForeignKeyConstraintChange change = new DropForeignKeyConstraintChange(); change.setBaseTableSchemaName("SCHEMA_NAME"); change.setBaseTableName("TABLE_NAME"); change.setConstraintName("FK_NAME"); assertEquals("Foreign key FK_NAME dropped", change.getConfirmationMessage()); } | public String getConfirmationMessage() { return "Foreign key " + getConstraintName() + " dropped"; } | DropForeignKeyConstraintChange extends AbstractChange { public String getConfirmationMessage() { return "Foreign key " + getConstraintName() + " dropped"; } } | DropForeignKeyConstraintChange extends AbstractChange { public String getConfirmationMessage() { return "Foreign key " + getConstraintName() + " dropped"; } DropForeignKeyConstraintChange(); } | DropForeignKeyConstraintChange extends AbstractChange { public String getConfirmationMessage() { return "Foreign key " + getConstraintName() + " dropped"; } DropForeignKeyConstraintChange(); String getBaseTableSchemaName(); void setBaseTableSchemaName(String baseTableSchemaName); String getBaseTableName(); void setBaseTableName(String baseTableName); String getConstraintName(); void setConstraintName(String constraintName); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); } | DropForeignKeyConstraintChange extends AbstractChange { public String getConfirmationMessage() { return "Foreign key " + getConstraintName() + " dropped"; } DropForeignKeyConstraintChange(); String getBaseTableSchemaName(); void setBaseTableSchemaName(String baseTableSchemaName); String getBaseTableName(); void setBaseTableName(String baseTableName); String getConstraintName(); void setConstraintName(String constraintName); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); } |
@Override @Test public void getConfirmationMessage() throws Exception { assertEquals("Table TAB_NAME dropped", change.getConfirmationMessage()); } | public String getConfirmationMessage() { return "Table " + getTableName() + " dropped"; } | DropTableChange extends AbstractChange { public String getConfirmationMessage() { return "Table " + getTableName() + " dropped"; } } | DropTableChange extends AbstractChange { public String getConfirmationMessage() { return "Table " + getTableName() + " dropped"; } DropTableChange(); } | DropTableChange extends AbstractChange { public String getConfirmationMessage() { return "Table " + getTableName() + " dropped"; } DropTableChange(); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); Boolean isCascadeConstraints(); void setCascadeConstraints(Boolean cascadeConstraints); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); } | DropTableChange extends AbstractChange { public String getConfirmationMessage() { return "Table " + getTableName() + " dropped"; } DropTableChange(); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); Boolean isCascadeConstraints(); void setCascadeConstraints(Boolean cascadeConstraints); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); } |
@Test public void getStatements() throws Exception { MockDatabase database = new MockDatabase(); LoadUpdateDataChange change = new LoadUpdateDataChange(); change.setSchemaName("SCHEMA_NAME"); change.setTableName("TABLE_NAME"); change.setFile("liquibase/change/core/sample.data1.csv"); change.setResourceAccessor(new ClassLoaderResourceAccessor()); SqlStatement[] statements = change.generateStatements(database); assertNotNull(statements); assertEquals(InsertOrUpdateStatement.class,statements[0].getClass()); } | @Override public SqlStatement[] generateStatements(Database database) { return super.generateStatements(database); } | LoadUpdateDataChange extends LoadDataChange { @Override public SqlStatement[] generateStatements(Database database) { return super.generateStatements(database); } } | LoadUpdateDataChange extends LoadDataChange { @Override public SqlStatement[] generateStatements(Database database) { return super.generateStatements(database); } LoadUpdateDataChange(); } | LoadUpdateDataChange extends LoadDataChange { @Override public SqlStatement[] generateStatements(Database database) { return super.generateStatements(database); } LoadUpdateDataChange(); @Override SqlStatement[] generateStatements(Database database); void setPrimaryKey(String primaryKey); String getPrimaryKey(); @Override SqlStatement[] generateRollbackStatements(Database database); } | LoadUpdateDataChange extends LoadDataChange { @Override public SqlStatement[] generateStatements(Database database) { return super.generateStatements(database); } LoadUpdateDataChange(); @Override SqlStatement[] generateStatements(Database database); void setPrimaryKey(String primaryKey); String getPrimaryKey(); @Override SqlStatement[] generateRollbackStatements(Database database); } |
@Test public void generateSql(){ MockDatabase database = new MockDatabase(); LoadUpdateDataChange change = new LoadUpdateDataChange(); change.setSchemaName("SCHEMA_NAME"); change.setTableName("TABLE_NAME"); change.setFile("liquibase/change/core/sample.data1.csv"); change.setResourceAccessor(new ClassLoaderResourceAccessor()); SqlStatement[] statements = change.generateStatements(database); assertNotNull(statements); assertEquals(InsertOrUpdateStatement.class,statements[0].getClass()); } | @Override public SqlStatement[] generateStatements(Database database) { return super.generateStatements(database); } | LoadUpdateDataChange extends LoadDataChange { @Override public SqlStatement[] generateStatements(Database database) { return super.generateStatements(database); } } | LoadUpdateDataChange extends LoadDataChange { @Override public SqlStatement[] generateStatements(Database database) { return super.generateStatements(database); } LoadUpdateDataChange(); } | LoadUpdateDataChange extends LoadDataChange { @Override public SqlStatement[] generateStatements(Database database) { return super.generateStatements(database); } LoadUpdateDataChange(); @Override SqlStatement[] generateStatements(Database database); void setPrimaryKey(String primaryKey); String getPrimaryKey(); @Override SqlStatement[] generateRollbackStatements(Database database); } | LoadUpdateDataChange extends LoadDataChange { @Override public SqlStatement[] generateStatements(Database database) { return super.generateStatements(database); } LoadUpdateDataChange(); @Override SqlStatement[] generateStatements(Database database); void setPrimaryKey(String primaryKey); String getPrimaryKey(); @Override SqlStatement[] generateRollbackStatements(Database database); } |
@Test public void primaryKeyNullThrowsException() { LoadUpdateDataChange change = new LoadUpdateDataChange(); try { change.setPrimaryKey(null); fail("setPrimaryKey did not throw InvalidArgumentException as expected."); } catch(LiquibaseException e) { } } | public void setPrimaryKey(String primaryKey) throws LiquibaseException { if (primaryKey == null) { throw new LiquibaseException("primaryKey cannot be null."); } this.primaryKey = primaryKey; } | LoadUpdateDataChange extends LoadDataChange { public void setPrimaryKey(String primaryKey) throws LiquibaseException { if (primaryKey == null) { throw new LiquibaseException("primaryKey cannot be null."); } this.primaryKey = primaryKey; } } | LoadUpdateDataChange extends LoadDataChange { public void setPrimaryKey(String primaryKey) throws LiquibaseException { if (primaryKey == null) { throw new LiquibaseException("primaryKey cannot be null."); } this.primaryKey = primaryKey; } LoadUpdateDataChange(); } | LoadUpdateDataChange extends LoadDataChange { public void setPrimaryKey(String primaryKey) throws LiquibaseException { if (primaryKey == null) { throw new LiquibaseException("primaryKey cannot be null."); } this.primaryKey = primaryKey; } LoadUpdateDataChange(); @Override SqlStatement[] generateStatements(Database database); void setPrimaryKey(String primaryKey); String getPrimaryKey(); @Override SqlStatement[] generateRollbackStatements(Database database); } | LoadUpdateDataChange extends LoadDataChange { public void setPrimaryKey(String primaryKey) throws LiquibaseException { if (primaryKey == null) { throw new LiquibaseException("primaryKey cannot be null."); } this.primaryKey = primaryKey; } LoadUpdateDataChange(); @Override SqlStatement[] generateStatements(Database database); void setPrimaryKey(String primaryKey); String getPrimaryKey(); @Override SqlStatement[] generateRollbackStatements(Database database); } |
@Test public void getWhereClause() throws LiquibaseException { MockDatabase database = new MockDatabase(); LoadUpdateDataChange change = new LoadUpdateDataChange(); change.setSchemaName("SCHEMA_NAME"); change.setTableName("TABLE_NAME"); change.setFile("liquibase/change/core/sample.data1.csv"); change.setResourceAccessor(new ClassLoaderResourceAccessor()); change.setPrimaryKey("name"); SqlStatement[] statements = change.generateStatements(database); Object[] args ; String result ; args = new Object[] { statements[0], database }; result = (String)invokePrivateMethod(change,"getWhereClause",args); assertEquals("name = 'Bob Johnson'",result.trim()); args = new Object[] { statements[1], database }; result = (String)invokePrivateMethod(change,"getWhereClause",args); assertEquals("name = 'John Doe'",result.trim()); } | private String getWhereClause(InsertOrUpdateStatement insertOrUpdateStatement, Database database) { StringBuffer where = new StringBuffer(); String[] pkColumns = insertOrUpdateStatement.getPrimaryKey().split(","); for(String thisPkColumn:pkColumns) { where.append(database.escapeColumnName(insertOrUpdateStatement.getSchemaName(), insertOrUpdateStatement.getTableName(), thisPkColumn) + " = " ); Object newValue = insertOrUpdateStatement.getColumnValues().get(thisPkColumn); if (newValue == null || newValue.toString().equals("NULL")) { where.append("NULL"); } else if (newValue instanceof String && database.shouldQuoteValue(((String) newValue))) { where.append("'").append(database.escapeStringForDatabase((String) newValue)).append("'"); } else if (newValue instanceof Date) { where.append(database.getDateLiteral(((Date) newValue))); } else if (newValue instanceof Boolean) { if (((Boolean) newValue)) { where.append(TypeConverterFactory.getInstance().findTypeConverter(database).getBooleanType().getTrueBooleanValue()); } else { where.append(TypeConverterFactory.getInstance().findTypeConverter(database).getBooleanType().getFalseBooleanValue()); } } else { where.append(newValue); } where.append(" AND "); } where.delete(where.lastIndexOf(" AND "),where.lastIndexOf(" AND ") + " AND ".length()); return where.toString(); } | LoadUpdateDataChange extends LoadDataChange { private String getWhereClause(InsertOrUpdateStatement insertOrUpdateStatement, Database database) { StringBuffer where = new StringBuffer(); String[] pkColumns = insertOrUpdateStatement.getPrimaryKey().split(","); for(String thisPkColumn:pkColumns) { where.append(database.escapeColumnName(insertOrUpdateStatement.getSchemaName(), insertOrUpdateStatement.getTableName(), thisPkColumn) + " = " ); Object newValue = insertOrUpdateStatement.getColumnValues().get(thisPkColumn); if (newValue == null || newValue.toString().equals("NULL")) { where.append("NULL"); } else if (newValue instanceof String && database.shouldQuoteValue(((String) newValue))) { where.append("'").append(database.escapeStringForDatabase((String) newValue)).append("'"); } else if (newValue instanceof Date) { where.append(database.getDateLiteral(((Date) newValue))); } else if (newValue instanceof Boolean) { if (((Boolean) newValue)) { where.append(TypeConverterFactory.getInstance().findTypeConverter(database).getBooleanType().getTrueBooleanValue()); } else { where.append(TypeConverterFactory.getInstance().findTypeConverter(database).getBooleanType().getFalseBooleanValue()); } } else { where.append(newValue); } where.append(" AND "); } where.delete(where.lastIndexOf(" AND "),where.lastIndexOf(" AND ") + " AND ".length()); return where.toString(); } } | LoadUpdateDataChange extends LoadDataChange { private String getWhereClause(InsertOrUpdateStatement insertOrUpdateStatement, Database database) { StringBuffer where = new StringBuffer(); String[] pkColumns = insertOrUpdateStatement.getPrimaryKey().split(","); for(String thisPkColumn:pkColumns) { where.append(database.escapeColumnName(insertOrUpdateStatement.getSchemaName(), insertOrUpdateStatement.getTableName(), thisPkColumn) + " = " ); Object newValue = insertOrUpdateStatement.getColumnValues().get(thisPkColumn); if (newValue == null || newValue.toString().equals("NULL")) { where.append("NULL"); } else if (newValue instanceof String && database.shouldQuoteValue(((String) newValue))) { where.append("'").append(database.escapeStringForDatabase((String) newValue)).append("'"); } else if (newValue instanceof Date) { where.append(database.getDateLiteral(((Date) newValue))); } else if (newValue instanceof Boolean) { if (((Boolean) newValue)) { where.append(TypeConverterFactory.getInstance().findTypeConverter(database).getBooleanType().getTrueBooleanValue()); } else { where.append(TypeConverterFactory.getInstance().findTypeConverter(database).getBooleanType().getFalseBooleanValue()); } } else { where.append(newValue); } where.append(" AND "); } where.delete(where.lastIndexOf(" AND "),where.lastIndexOf(" AND ") + " AND ".length()); return where.toString(); } LoadUpdateDataChange(); } | LoadUpdateDataChange extends LoadDataChange { private String getWhereClause(InsertOrUpdateStatement insertOrUpdateStatement, Database database) { StringBuffer where = new StringBuffer(); String[] pkColumns = insertOrUpdateStatement.getPrimaryKey().split(","); for(String thisPkColumn:pkColumns) { where.append(database.escapeColumnName(insertOrUpdateStatement.getSchemaName(), insertOrUpdateStatement.getTableName(), thisPkColumn) + " = " ); Object newValue = insertOrUpdateStatement.getColumnValues().get(thisPkColumn); if (newValue == null || newValue.toString().equals("NULL")) { where.append("NULL"); } else if (newValue instanceof String && database.shouldQuoteValue(((String) newValue))) { where.append("'").append(database.escapeStringForDatabase((String) newValue)).append("'"); } else if (newValue instanceof Date) { where.append(database.getDateLiteral(((Date) newValue))); } else if (newValue instanceof Boolean) { if (((Boolean) newValue)) { where.append(TypeConverterFactory.getInstance().findTypeConverter(database).getBooleanType().getTrueBooleanValue()); } else { where.append(TypeConverterFactory.getInstance().findTypeConverter(database).getBooleanType().getFalseBooleanValue()); } } else { where.append(newValue); } where.append(" AND "); } where.delete(where.lastIndexOf(" AND "),where.lastIndexOf(" AND ") + " AND ".length()); return where.toString(); } LoadUpdateDataChange(); @Override SqlStatement[] generateStatements(Database database); void setPrimaryKey(String primaryKey); String getPrimaryKey(); @Override SqlStatement[] generateRollbackStatements(Database database); } | LoadUpdateDataChange extends LoadDataChange { private String getWhereClause(InsertOrUpdateStatement insertOrUpdateStatement, Database database) { StringBuffer where = new StringBuffer(); String[] pkColumns = insertOrUpdateStatement.getPrimaryKey().split(","); for(String thisPkColumn:pkColumns) { where.append(database.escapeColumnName(insertOrUpdateStatement.getSchemaName(), insertOrUpdateStatement.getTableName(), thisPkColumn) + " = " ); Object newValue = insertOrUpdateStatement.getColumnValues().get(thisPkColumn); if (newValue == null || newValue.toString().equals("NULL")) { where.append("NULL"); } else if (newValue instanceof String && database.shouldQuoteValue(((String) newValue))) { where.append("'").append(database.escapeStringForDatabase((String) newValue)).append("'"); } else if (newValue instanceof Date) { where.append(database.getDateLiteral(((Date) newValue))); } else if (newValue instanceof Boolean) { if (((Boolean) newValue)) { where.append(TypeConverterFactory.getInstance().findTypeConverter(database).getBooleanType().getTrueBooleanValue()); } else { where.append(TypeConverterFactory.getInstance().findTypeConverter(database).getBooleanType().getFalseBooleanValue()); } } else { where.append(newValue); } where.append(" AND "); } where.delete(where.lastIndexOf(" AND "),where.lastIndexOf(" AND ") + " AND ".length()); return where.toString(); } LoadUpdateDataChange(); @Override SqlStatement[] generateStatements(Database database); void setPrimaryKey(String primaryKey); String getPrimaryKey(); @Override SqlStatement[] generateRollbackStatements(Database database); } |
@Override @Test public void getConfirmationMessage() throws Exception { AddUniqueConstraintChange change = new AddUniqueConstraintChange(); change.setTableName("TABLE_NAME"); change.setColumnNames("COL_HERE"); assertEquals("Unique constraint added to TABLE_NAME(COL_HERE)", change.getConfirmationMessage()); } | public String getConfirmationMessage() { return "Unique constraint added to "+getTableName()+"("+getColumnNames()+")"; } | AddUniqueConstraintChange extends AbstractChange { public String getConfirmationMessage() { return "Unique constraint added to "+getTableName()+"("+getColumnNames()+")"; } } | AddUniqueConstraintChange extends AbstractChange { public String getConfirmationMessage() { return "Unique constraint added to "+getTableName()+"("+getColumnNames()+")"; } AddUniqueConstraintChange(); } | AddUniqueConstraintChange extends AbstractChange { public String getConfirmationMessage() { return "Unique constraint added to "+getTableName()+"("+getColumnNames()+")"; } AddUniqueConstraintChange(); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); String getColumnNames(); void setColumnNames(String columnNames); String getConstraintName(); void setConstraintName(String constraintName); String getTablespace(); void setTablespace(String tablespace); Boolean getDeferrable(); void setDeferrable(Boolean deferrable); Boolean getInitiallyDeferred(); void setInitiallyDeferred(Boolean initiallyDeferred); Boolean getDisabled(); void setDisabled(Boolean disabled); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); } | AddUniqueConstraintChange extends AbstractChange { public String getConfirmationMessage() { return "Unique constraint added to "+getTableName()+"("+getColumnNames()+")"; } AddUniqueConstraintChange(); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); String getColumnNames(); void setColumnNames(String columnNames); String getConstraintName(); void setConstraintName(String constraintName); String getTablespace(); void setTablespace(String tablespace); Boolean getDeferrable(); void setDeferrable(Boolean deferrable); Boolean getInitiallyDeferred(); void setInitiallyDeferred(Boolean initiallyDeferred); Boolean getDisabled(); void setDisabled(Boolean disabled); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); } |
@Override @Test public void getConfirmationMessage() throws Exception { AddNotNullConstraintChange change = new AddNotNullConstraintChange(); change.setTableName("TABLE_NAME"); change.setColumnName("COL_HERE"); assertEquals("Null constraint has been added to TABLE_NAME.COL_HERE", change.getConfirmationMessage()); } | public String getConfirmationMessage() { return "Null constraint has been added to " + getTableName() + "." + getColumnName(); } | AddNotNullConstraintChange extends AbstractChange { public String getConfirmationMessage() { return "Null constraint has been added to " + getTableName() + "." + getColumnName(); } } | AddNotNullConstraintChange extends AbstractChange { public String getConfirmationMessage() { return "Null constraint has been added to " + getTableName() + "." + getColumnName(); } AddNotNullConstraintChange(); } | AddNotNullConstraintChange extends AbstractChange { public String getConfirmationMessage() { return "Null constraint has been added to " + getTableName() + "." + getColumnName(); } AddNotNullConstraintChange(); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); String getColumnName(); void setColumnName(String columnName); String getDefaultNullValue(); void setDefaultNullValue(String defaultNullValue); String getColumnDataType(); void setColumnDataType(String columnDataType); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); } | AddNotNullConstraintChange extends AbstractChange { public String getConfirmationMessage() { return "Null constraint has been added to " + getTableName() + "." + getColumnName(); } AddNotNullConstraintChange(); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); String getColumnName(); void setColumnName(String columnName); String getDefaultNullValue(); void setDefaultNullValue(String defaultNullValue); String getColumnDataType(); void setColumnDataType(String columnDataType); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); } |
@Override @Test public void getConfirmationMessage() throws Exception { refactoring.setOldViewName("OLD_NAME"); refactoring.setNewViewName("NEW_NAME"); assertEquals("View OLD_NAME renamed to NEW_NAME", refactoring.getConfirmationMessage()); } | public String getConfirmationMessage() { return "View " + oldViewName + " renamed to " + newViewName; } | RenameViewChange extends AbstractChange { public String getConfirmationMessage() { return "View " + oldViewName + " renamed to " + newViewName; } } | RenameViewChange extends AbstractChange { public String getConfirmationMessage() { return "View " + oldViewName + " renamed to " + newViewName; } RenameViewChange(); } | RenameViewChange extends AbstractChange { public String getConfirmationMessage() { return "View " + oldViewName + " renamed to " + newViewName; } RenameViewChange(); String getSchemaName(); void setSchemaName(String schemaName); String getOldViewName(); void setOldViewName(String oldViewName); String getNewViewName(); void setNewViewName(String newViewName); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); } | RenameViewChange extends AbstractChange { public String getConfirmationMessage() { return "View " + oldViewName + " renamed to " + newViewName; } RenameViewChange(); String getSchemaName(); void setSchemaName(String schemaName); String getOldViewName(); void setOldViewName(String oldViewName); String getNewViewName(); void setNewViewName(String newViewName); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); } |
@Override @Test public void getConfirmationMessage() throws Exception { LoadDataChange refactoring = new LoadDataChange(); refactoring.setTableName("TABLE_NAME"); refactoring.setFile("FILE_NAME"); assertEquals("Data loaded from FILE_NAME into TABLE_NAME", refactoring.getConfirmationMessage()); } | public String getConfirmationMessage() { return "Data loaded from "+getFile()+" into "+getTableName(); } | LoadDataChange extends AbstractChange implements ChangeWithColumns<LoadDataColumnConfig> { public String getConfirmationMessage() { return "Data loaded from "+getFile()+" into "+getTableName(); } } | LoadDataChange extends AbstractChange implements ChangeWithColumns<LoadDataColumnConfig> { public String getConfirmationMessage() { return "Data loaded from "+getFile()+" into "+getTableName(); } LoadDataChange(); protected LoadDataChange(String changeName, String changeDescription); } | LoadDataChange extends AbstractChange implements ChangeWithColumns<LoadDataColumnConfig> { public String getConfirmationMessage() { return "Data loaded from "+getFile()+" into "+getTableName(); } LoadDataChange(); protected LoadDataChange(String changeName, String changeDescription); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); String getFile(); void setFile(String file); String getEncoding(); void setEncoding(String encoding); String getSeparator(); void setSeparator(String separator); String getQuotchar(); void setQuotchar(String quotchar); void addColumn(LoadDataColumnConfig column); List<LoadDataColumnConfig> getColumns(); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); @Override CheckSum generateCheckSum(); } | LoadDataChange extends AbstractChange implements ChangeWithColumns<LoadDataColumnConfig> { public String getConfirmationMessage() { return "Data loaded from "+getFile()+" into "+getTableName(); } LoadDataChange(); protected LoadDataChange(String changeName, String changeDescription); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); String getFile(); void setFile(String file); String getEncoding(); void setEncoding(String encoding); String getSeparator(); void setSeparator(String separator); String getQuotchar(); void setQuotchar(String quotchar); void addColumn(LoadDataColumnConfig column); List<LoadDataColumnConfig> getColumns(); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); @Override CheckSum generateCheckSum(); } |
@Test public void testComputeMD5InputStream() { ByteArrayInputStream bais = new ByteArrayInputStream(TEST_STRING.getBytes()); String hexString = MD5Util.computeMD5(bais); assertEquals(TEST_STRING_MD5_HASH, hexString); } | public static String computeMD5(String input) { if (input == null) { return null; } MessageDigest digest; try { digest = MessageDigest.getInstance("MD5"); digest.update(input.getBytes("UTF-8")); } catch (Exception e) { throw new UnexpectedLiquibaseException(e); } byte[] digestBytes = digest.digest(); String returnString = new String(encodeHex(digestBytes)); LogFactory.getLogger().debug("Computed checksum for "+input+" as "+returnString); return returnString; } | MD5Util { public static String computeMD5(String input) { if (input == null) { return null; } MessageDigest digest; try { digest = MessageDigest.getInstance("MD5"); digest.update(input.getBytes("UTF-8")); } catch (Exception e) { throw new UnexpectedLiquibaseException(e); } byte[] digestBytes = digest.digest(); String returnString = new String(encodeHex(digestBytes)); LogFactory.getLogger().debug("Computed checksum for "+input+" as "+returnString); return returnString; } } | MD5Util { public static String computeMD5(String input) { if (input == null) { return null; } MessageDigest digest; try { digest = MessageDigest.getInstance("MD5"); digest.update(input.getBytes("UTF-8")); } catch (Exception e) { throw new UnexpectedLiquibaseException(e); } byte[] digestBytes = digest.digest(); String returnString = new String(encodeHex(digestBytes)); LogFactory.getLogger().debug("Computed checksum for "+input+" as "+returnString); return returnString; } } | MD5Util { public static String computeMD5(String input) { if (input == null) { return null; } MessageDigest digest; try { digest = MessageDigest.getInstance("MD5"); digest.update(input.getBytes("UTF-8")); } catch (Exception e) { throw new UnexpectedLiquibaseException(e); } byte[] digestBytes = digest.digest(); String returnString = new String(encodeHex(digestBytes)); LogFactory.getLogger().debug("Computed checksum for "+input+" as "+returnString); return returnString; } static String computeMD5(String input); static String computeMD5(InputStream stream); } | MD5Util { public static String computeMD5(String input) { if (input == null) { return null; } MessageDigest digest; try { digest = MessageDigest.getInstance("MD5"); digest.update(input.getBytes("UTF-8")); } catch (Exception e) { throw new UnexpectedLiquibaseException(e); } byte[] digestBytes = digest.digest(); String returnString = new String(encodeHex(digestBytes)); LogFactory.getLogger().debug("Computed checksum for "+input+" as "+returnString); return returnString; } static String computeMD5(String input); static String computeMD5(InputStream stream); } |
@Override @Test public void generateCheckSum() throws Exception { LoadDataChange refactoring = new LoadDataChange(); refactoring.setSchemaName("SCHEMA_NAME"); refactoring.setTableName("TABLE_NAME"); refactoring.setFile("liquibase/change/core/sample.data1.csv"); refactoring.setResourceAccessor(new ClassLoaderResourceAccessor()); String md5sum1 = refactoring.generateCheckSum().toString(); refactoring.setFile("liquibase/change/core/sample.data2.csv"); String md5sum2 = refactoring.generateCheckSum().toString(); assertTrue(!md5sum1.equals(md5sum2)); assertEquals(md5sum2, refactoring.generateCheckSum().toString()); } | @Override public CheckSum generateCheckSum() { InputStream stream = null; try { stream = getResourceAccessor().getResourceAsStream(getFile()); if (stream == null) { throw new RuntimeException(getFile() + " could not be found"); } return CheckSum.compute(stream); } catch (IOException e) { throw new RuntimeException(e); } finally { if (stream != null) { try { stream.close(); } catch (IOException e) { ; } } } } | LoadDataChange extends AbstractChange implements ChangeWithColumns<LoadDataColumnConfig> { @Override public CheckSum generateCheckSum() { InputStream stream = null; try { stream = getResourceAccessor().getResourceAsStream(getFile()); if (stream == null) { throw new RuntimeException(getFile() + " could not be found"); } return CheckSum.compute(stream); } catch (IOException e) { throw new RuntimeException(e); } finally { if (stream != null) { try { stream.close(); } catch (IOException e) { ; } } } } } | LoadDataChange extends AbstractChange implements ChangeWithColumns<LoadDataColumnConfig> { @Override public CheckSum generateCheckSum() { InputStream stream = null; try { stream = getResourceAccessor().getResourceAsStream(getFile()); if (stream == null) { throw new RuntimeException(getFile() + " could not be found"); } return CheckSum.compute(stream); } catch (IOException e) { throw new RuntimeException(e); } finally { if (stream != null) { try { stream.close(); } catch (IOException e) { ; } } } } LoadDataChange(); protected LoadDataChange(String changeName, String changeDescription); } | LoadDataChange extends AbstractChange implements ChangeWithColumns<LoadDataColumnConfig> { @Override public CheckSum generateCheckSum() { InputStream stream = null; try { stream = getResourceAccessor().getResourceAsStream(getFile()); if (stream == null) { throw new RuntimeException(getFile() + " could not be found"); } return CheckSum.compute(stream); } catch (IOException e) { throw new RuntimeException(e); } finally { if (stream != null) { try { stream.close(); } catch (IOException e) { ; } } } } LoadDataChange(); protected LoadDataChange(String changeName, String changeDescription); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); String getFile(); void setFile(String file); String getEncoding(); void setEncoding(String encoding); String getSeparator(); void setSeparator(String separator); String getQuotchar(); void setQuotchar(String quotchar); void addColumn(LoadDataColumnConfig column); List<LoadDataColumnConfig> getColumns(); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); @Override CheckSum generateCheckSum(); } | LoadDataChange extends AbstractChange implements ChangeWithColumns<LoadDataColumnConfig> { @Override public CheckSum generateCheckSum() { InputStream stream = null; try { stream = getResourceAccessor().getResourceAsStream(getFile()); if (stream == null) { throw new RuntimeException(getFile() + " could not be found"); } return CheckSum.compute(stream); } catch (IOException e) { throw new RuntimeException(e); } finally { if (stream != null) { try { stream.close(); } catch (IOException e) { ; } } } } LoadDataChange(); protected LoadDataChange(String changeName, String changeDescription); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); String getFile(); void setFile(String file); String getEncoding(); void setEncoding(String encoding); String getSeparator(); void setSeparator(String separator); String getQuotchar(); void setQuotchar(String quotchar); void addColumn(LoadDataColumnConfig column); List<LoadDataColumnConfig> getColumns(); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); @Override CheckSum generateCheckSum(); } |
@Override @Test public void getConfirmationMessage() throws Exception { CreateViewChange change = new CreateViewChange(); change.setViewName("VIEW_NAME"); assertEquals("View VIEW_NAME created", change.getConfirmationMessage()); } | public String getConfirmationMessage() { return "View " + getViewName() + " created"; } | CreateViewChange extends AbstractChange { public String getConfirmationMessage() { return "View " + getViewName() + " created"; } } | CreateViewChange extends AbstractChange { public String getConfirmationMessage() { return "View " + getViewName() + " created"; } CreateViewChange(); } | CreateViewChange extends AbstractChange { public String getConfirmationMessage() { return "View " + getViewName() + " created"; } CreateViewChange(); String getSchemaName(); void setSchemaName(String schemaName); String getViewName(); void setViewName(String viewName); String getSelectQuery(); void setSelectQuery(String selectQuery); Boolean getReplaceIfExists(); void setReplaceIfExists(Boolean replaceIfExists); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); } | CreateViewChange extends AbstractChange { public String getConfirmationMessage() { return "View " + getViewName() + " created"; } CreateViewChange(); String getSchemaName(); void setSchemaName(String schemaName); String getViewName(); void setViewName(String viewName); String getSelectQuery(); void setSelectQuery(String selectQuery); Boolean getReplaceIfExists(); void setReplaceIfExists(Boolean replaceIfExists); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); } |
@Override @Test public void getConfirmationMessage() throws Exception { assertEquals("Unique constraint UQ_CONSTRAINT dropped from TAB_NAME", change.getConfirmationMessage()); } | public String getConfirmationMessage() { return "Unique constraint "+getConstraintName()+" dropped from "+getTableName(); } | DropUniqueConstraintChange extends AbstractChange { public String getConfirmationMessage() { return "Unique constraint "+getConstraintName()+" dropped from "+getTableName(); } } | DropUniqueConstraintChange extends AbstractChange { public String getConfirmationMessage() { return "Unique constraint "+getConstraintName()+" dropped from "+getTableName(); } DropUniqueConstraintChange(); } | DropUniqueConstraintChange extends AbstractChange { public String getConfirmationMessage() { return "Unique constraint "+getConstraintName()+" dropped from "+getTableName(); } DropUniqueConstraintChange(); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); String getConstraintName(); void setConstraintName(String constraintName); String getUniqueColumns(); void setUniqueColumns(String uniqueColumns); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); } | DropUniqueConstraintChange extends AbstractChange { public String getConfirmationMessage() { return "Unique constraint "+getConstraintName()+" dropped from "+getTableName(); } DropUniqueConstraintChange(); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); String getConstraintName(); void setConstraintName(String constraintName); String getUniqueColumns(); void setUniqueColumns(String uniqueColumns); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); } |
@Override @Test public void getConfirmationMessage() throws Exception { change.setTableName("TAB_NAME"); assertEquals("Table TAB_NAME created", change.getConfirmationMessage()); } | public String getConfirmationMessage() { return "Table " + tableName + " created"; } | CreateTableChange extends AbstractChange implements ChangeWithColumns<ColumnConfig> { public String getConfirmationMessage() { return "Table " + tableName + " created"; } } | CreateTableChange extends AbstractChange implements ChangeWithColumns<ColumnConfig> { public String getConfirmationMessage() { return "Table " + tableName + " created"; } CreateTableChange(); } | CreateTableChange extends AbstractChange implements ChangeWithColumns<ColumnConfig> { public String getConfirmationMessage() { return "Table " + tableName + " created"; } CreateTableChange(); SqlStatement[] generateStatements(Database database); List<ColumnConfig> getColumns(); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); String getTablespace(); void setTablespace(String tablespace); void addColumn(ColumnConfig column); String getRemarks(); void setRemarks(String remarks); String getConfirmationMessage(); } | CreateTableChange extends AbstractChange implements ChangeWithColumns<ColumnConfig> { public String getConfirmationMessage() { return "Table " + tableName + " created"; } CreateTableChange(); SqlStatement[] generateStatements(Database database); List<ColumnConfig> getColumns(); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); String getTablespace(); void setTablespace(String tablespace); void addColumn(ColumnConfig column); String getRemarks(); void setRemarks(String remarks); String getConfirmationMessage(); } |
@Override @Test public void generateStatement() throws Exception { SqlStatement[] sqlStatements = refactoring.generateStatements(new MockDatabase()); assertEquals(1, sqlStatements.length); assertTrue(sqlStatements[0] instanceof InsertStatement); assertEquals("123", ((InsertStatement) sqlStatements[0]).getColumnValue("id").toString()); assertEquals("Andrew", ((InsertStatement) sqlStatements[0]).getColumnValue("name").toString()); assertEquals("21", ((InsertStatement) sqlStatements[0]).getColumnValue("age").toString()); assertEquals("1.78", ((InsertStatement) sqlStatements[0]).getColumnValue("height").toString()); } | public SqlStatement[] generateStatements(Database database) { InsertStatement statement = new InsertStatement(getSchemaName() == null?database.getDefaultSchemaName():getSchemaName(), getTableName()); for (ColumnConfig column : columns) { if (database.supportsAutoIncrement() && column.isAutoIncrement() != null && column.isAutoIncrement()) { continue; } statement.addColumnValue(column.getName(), column.getValueObject()); } return new SqlStatement[]{ statement }; } | InsertDataChange extends AbstractChange implements ChangeWithColumns<ColumnConfig> { public SqlStatement[] generateStatements(Database database) { InsertStatement statement = new InsertStatement(getSchemaName() == null?database.getDefaultSchemaName():getSchemaName(), getTableName()); for (ColumnConfig column : columns) { if (database.supportsAutoIncrement() && column.isAutoIncrement() != null && column.isAutoIncrement()) { continue; } statement.addColumnValue(column.getName(), column.getValueObject()); } return new SqlStatement[]{ statement }; } } | InsertDataChange extends AbstractChange implements ChangeWithColumns<ColumnConfig> { public SqlStatement[] generateStatements(Database database) { InsertStatement statement = new InsertStatement(getSchemaName() == null?database.getDefaultSchemaName():getSchemaName(), getTableName()); for (ColumnConfig column : columns) { if (database.supportsAutoIncrement() && column.isAutoIncrement() != null && column.isAutoIncrement()) { continue; } statement.addColumnValue(column.getName(), column.getValueObject()); } return new SqlStatement[]{ statement }; } InsertDataChange(); } | InsertDataChange extends AbstractChange implements ChangeWithColumns<ColumnConfig> { public SqlStatement[] generateStatements(Database database) { InsertStatement statement = new InsertStatement(getSchemaName() == null?database.getDefaultSchemaName():getSchemaName(), getTableName()); for (ColumnConfig column : columns) { if (database.supportsAutoIncrement() && column.isAutoIncrement() != null && column.isAutoIncrement()) { continue; } statement.addColumnValue(column.getName(), column.getValueObject()); } return new SqlStatement[]{ statement }; } InsertDataChange(); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); List<ColumnConfig> getColumns(); void setColumns(List<ColumnConfig> columns); void addColumn(ColumnConfig column); void removeColumn(ColumnConfig column); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); } | InsertDataChange extends AbstractChange implements ChangeWithColumns<ColumnConfig> { public SqlStatement[] generateStatements(Database database) { InsertStatement statement = new InsertStatement(getSchemaName() == null?database.getDefaultSchemaName():getSchemaName(), getTableName()); for (ColumnConfig column : columns) { if (database.supportsAutoIncrement() && column.isAutoIncrement() != null && column.isAutoIncrement()) { continue; } statement.addColumnValue(column.getName(), column.getValueObject()); } return new SqlStatement[]{ statement }; } InsertDataChange(); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); List<ColumnConfig> getColumns(); void setColumns(List<ColumnConfig> columns); void addColumn(ColumnConfig column); void removeColumn(ColumnConfig column); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); } |
@Override @Test public void getConfirmationMessage() throws Exception { assertEquals("New row inserted into TABLE_NAME", refactoring.getConfirmationMessage()); } | public String getConfirmationMessage() { return "New row inserted into " + getTableName(); } | InsertDataChange extends AbstractChange implements ChangeWithColumns<ColumnConfig> { public String getConfirmationMessage() { return "New row inserted into " + getTableName(); } } | InsertDataChange extends AbstractChange implements ChangeWithColumns<ColumnConfig> { public String getConfirmationMessage() { return "New row inserted into " + getTableName(); } InsertDataChange(); } | InsertDataChange extends AbstractChange implements ChangeWithColumns<ColumnConfig> { public String getConfirmationMessage() { return "New row inserted into " + getTableName(); } InsertDataChange(); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); List<ColumnConfig> getColumns(); void setColumns(List<ColumnConfig> columns); void addColumn(ColumnConfig column); void removeColumn(ColumnConfig column); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); } | InsertDataChange extends AbstractChange implements ChangeWithColumns<ColumnConfig> { public String getConfirmationMessage() { return "New row inserted into " + getTableName(); } InsertDataChange(); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); List<ColumnConfig> getColumns(); void setColumns(List<ColumnConfig> columns); void addColumn(ColumnConfig column); void removeColumn(ColumnConfig column); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); } |
@Override @Test public void getConfirmationMessage() throws Exception { DropViewChange change = new DropViewChange(); change.setViewName("VIEW_NAME"); assertEquals("View VIEW_NAME dropped", change.getConfirmationMessage()); } | public String getConfirmationMessage() { return "View "+getViewName()+" dropped"; } | DropViewChange extends AbstractChange { public String getConfirmationMessage() { return "View "+getViewName()+" dropped"; } } | DropViewChange extends AbstractChange { public String getConfirmationMessage() { return "View "+getViewName()+" dropped"; } DropViewChange(); } | DropViewChange extends AbstractChange { public String getConfirmationMessage() { return "View "+getViewName()+" dropped"; } DropViewChange(); String getSchemaName(); void setSchemaName(String schemaName); String getViewName(); void setViewName(String viewName); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); } | DropViewChange extends AbstractChange { public String getConfirmationMessage() { return "View "+getViewName()+" dropped"; } DropViewChange(); String getSchemaName(); void setSchemaName(String schemaName); String getViewName(); void setViewName(String viewName); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); } |
@Override @Test public void getConfirmationMessage() throws Exception { DropColumnChange change = new DropColumnChange(); change.setTableName("TABLE_NAME"); change.setColumnName("COL_HERE"); assertEquals("Column TABLE_NAME.COL_HERE dropped", change.getConfirmationMessage()); } | public String getConfirmationMessage() { return "Column " + getTableName() + "." + getColumnName() + " dropped"; } | DropColumnChange extends AbstractChange { public String getConfirmationMessage() { return "Column " + getTableName() + "." + getColumnName() + " dropped"; } } | DropColumnChange extends AbstractChange { public String getConfirmationMessage() { return "Column " + getTableName() + "." + getColumnName() + " dropped"; } DropColumnChange(); } | DropColumnChange extends AbstractChange { public String getConfirmationMessage() { return "Column " + getTableName() + "." + getColumnName() + " dropped"; } DropColumnChange(); String getColumnName(); void setColumnName(String columnName); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); } | DropColumnChange extends AbstractChange { public String getConfirmationMessage() { return "Column " + getTableName() + "." + getColumnName() + " dropped"; } DropColumnChange(); String getColumnName(); void setColumnName(String columnName); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); } |
@Override @Test public void getConfirmationMessage() throws Exception { DropNotNullConstraintChange change = new DropNotNullConstraintChange(); change.setTableName("TABLE_NAME"); change.setColumnName("COL_HERE"); assertEquals("Null constraint dropped from TABLE_NAME.COL_HERE", change.getConfirmationMessage()); } | public String getConfirmationMessage() { return "Null constraint dropped from " + getTableName() + "." + getColumnName(); } | DropNotNullConstraintChange extends AbstractChange { public String getConfirmationMessage() { return "Null constraint dropped from " + getTableName() + "." + getColumnName(); } } | DropNotNullConstraintChange extends AbstractChange { public String getConfirmationMessage() { return "Null constraint dropped from " + getTableName() + "." + getColumnName(); } DropNotNullConstraintChange(); } | DropNotNullConstraintChange extends AbstractChange { public String getConfirmationMessage() { return "Null constraint dropped from " + getTableName() + "." + getColumnName(); } DropNotNullConstraintChange(); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); String getColumnName(); void setColumnName(String columnName); String getColumnDataType(); void setColumnDataType(String columnDataType); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); } | DropNotNullConstraintChange extends AbstractChange { public String getConfirmationMessage() { return "Null constraint dropped from " + getTableName() + "." + getColumnName(); } DropNotNullConstraintChange(); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); String getColumnName(); void setColumnName(String columnName); String getColumnDataType(); void setColumnDataType(String columnDataType); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); } |
@Override @Test public void getConfirmationMessage() throws Exception { AddDefaultValueChange change = new AddDefaultValueChange(); change.setSchemaName("SCHEMA_NAME"); change.setTableName("TABLE_NAME"); change.setColumnName("COLUMN_NAME"); assertEquals("Default value added to TABLE_NAME.COLUMN_NAME", change.getConfirmationMessage()); } | public String getConfirmationMessage() { return "Default value added to " + getTableName() + "." + getColumnName(); } | AddDefaultValueChange extends AbstractChange { public String getConfirmationMessage() { return "Default value added to " + getTableName() + "." + getColumnName(); } } | AddDefaultValueChange extends AbstractChange { public String getConfirmationMessage() { return "Default value added to " + getTableName() + "." + getColumnName(); } AddDefaultValueChange(); } | AddDefaultValueChange extends AbstractChange { public String getConfirmationMessage() { return "Default value added to " + getTableName() + "." + getColumnName(); } AddDefaultValueChange(); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); String getColumnName(); void setColumnName(String columnName); String getColumnDataType(); void setColumnDataType(String columnDataType); String getDefaultValue(); void setDefaultValue(String defaultValue); String getDefaultValueNumeric(); void setDefaultValueNumeric(String defaultValueNumeric); String getDefaultValueDate(); void setDefaultValueDate(String defaultValueDate); Boolean getDefaultValueBoolean(); void setDefaultValueBoolean(Boolean defaultValueBoolean); DatabaseFunction getDefaultValueComputed(); void setDefaultValueComputed(DatabaseFunction defaultValueComputed); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); } | AddDefaultValueChange extends AbstractChange { public String getConfirmationMessage() { return "Default value added to " + getTableName() + "." + getColumnName(); } AddDefaultValueChange(); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); String getColumnName(); void setColumnName(String columnName); String getColumnDataType(); void setColumnDataType(String columnDataType); String getDefaultValue(); void setDefaultValue(String defaultValue); String getDefaultValueNumeric(); void setDefaultValueNumeric(String defaultValueNumeric); String getDefaultValueDate(); void setDefaultValueDate(String defaultValueDate); Boolean getDefaultValueBoolean(); void setDefaultValueBoolean(Boolean defaultValueBoolean); DatabaseFunction getDefaultValueComputed(); void setDefaultValueComputed(DatabaseFunction defaultValueComputed); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); } |
@Test public void testMatchingInSequentialOrder() { matcher=new RegexMatcher(text,new String[]{"Pulp","Reservoir","Kill"}); assertTrue("All matched",matcher.allMatchedInSequentialOrder()); matcher=new RegexMatcher(text,new String[]{"Pulp","ion"}); assertTrue("All matched",matcher.allMatchedInSequentialOrder()); matcher=new RegexMatcher(text,new String[]{"Pu.p","^Ki.+ll$"}); assertTrue("All matched",matcher.allMatchedInSequentialOrder()); matcher=new RegexMatcher(text,new String[]{"pulP","kiLL"}); assertTrue("Case insensitive",matcher.allMatchedInSequentialOrder()); matcher=new RegexMatcher(text,new String[]{"Reservoir","Pulp","Dogs"}); assertFalse("Not in order",matcher.allMatchedInSequentialOrder()); matcher=new RegexMatcher(text,new String[]{"Memento"}); assertFalse("Not found",matcher.allMatchedInSequentialOrder()); } | public boolean allMatchedInSequentialOrder() { return allMatched; } | RegexMatcher { public boolean allMatchedInSequentialOrder() { return allMatched; } } | RegexMatcher { public boolean allMatchedInSequentialOrder() { return allMatched; } RegexMatcher(String text,String [] regexToMatch); } | RegexMatcher { public boolean allMatchedInSequentialOrder() { return allMatched; } RegexMatcher(String text,String [] regexToMatch); boolean allMatchedInSequentialOrder(); } | RegexMatcher { public boolean allMatchedInSequentialOrder() { return allMatched; } RegexMatcher(String text,String [] regexToMatch); boolean allMatchedInSequentialOrder(); } |
@Override @Test public void getConfirmationMessage() throws Exception { assertEquals("Sequence SEQ_NAME dropped", change.getConfirmationMessage()); } | public String getConfirmationMessage() { return "Sequence " + getSequenceName() + " dropped"; } | DropSequenceChange extends AbstractChange { public String getConfirmationMessage() { return "Sequence " + getSequenceName() + " dropped"; } } | DropSequenceChange extends AbstractChange { public String getConfirmationMessage() { return "Sequence " + getSequenceName() + " dropped"; } DropSequenceChange(); } | DropSequenceChange extends AbstractChange { public String getConfirmationMessage() { return "Sequence " + getSequenceName() + " dropped"; } DropSequenceChange(); String getSchemaName(); void setSchemaName(String schemaName); String getSequenceName(); void setSequenceName(String sequenceName); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); } | DropSequenceChange extends AbstractChange { public String getConfirmationMessage() { return "Sequence " + getSequenceName() + " dropped"; } DropSequenceChange(); String getSchemaName(); void setSchemaName(String schemaName); String getSequenceName(); void setSequenceName(String sequenceName); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); } |
@Test public void multilineComment2() { String original = "--\r\n"+ "-- This is a comment\r\n" + "UPDATE tablename SET column = 1;\r\n" + "GO"; SQLFileChange change = new SQLFileChange(); change.setSql(original); change.setSplitStatements(true); change.setStripComments(true); SqlStatement[] out = change.generateStatements(new MockDatabase()); assertEquals(2, out.length); assertEquals("UPDATE tablename SET column = 1", out[0].toString()); } | @Override public void setSql(String sql) { if (getChangeLogParameters() != null) { sql = getChangeLogParameters().expandExpressions(sql); } super.setSql(sql); } | SQLFileChange extends AbstractSQLChange { @Override public void setSql(String sql) { if (getChangeLogParameters() != null) { sql = getChangeLogParameters().expandExpressions(sql); } super.setSql(sql); } } | SQLFileChange extends AbstractSQLChange { @Override public void setSql(String sql) { if (getChangeLogParameters() != null) { sql = getChangeLogParameters().expandExpressions(sql); } super.setSql(sql); } SQLFileChange(); } | SQLFileChange extends AbstractSQLChange { @Override public void setSql(String sql) { if (getChangeLogParameters() != null) { sql = getChangeLogParameters().expandExpressions(sql); } super.setSql(sql); } SQLFileChange(); String getPath(); void setPath(String fileName); String getEncoding(); void setEncoding(String encoding); Boolean isRelativeToChangelogFile(); void setRelativeToChangelogFile(Boolean relativeToChangelogFile); @Override void init(); @Override ValidationErrors validate(Database database); @Override Warnings warn(Database database); @Override CheckSum generateCheckSum(); String getConfirmationMessage(); @Override void setSql(String sql); } | SQLFileChange extends AbstractSQLChange { @Override public void setSql(String sql) { if (getChangeLogParameters() != null) { sql = getChangeLogParameters().expandExpressions(sql); } super.setSql(sql); } SQLFileChange(); String getPath(); void setPath(String fileName); String getEncoding(); void setEncoding(String encoding); Boolean isRelativeToChangelogFile(); void setRelativeToChangelogFile(Boolean relativeToChangelogFile); @Override void init(); @Override ValidationErrors validate(Database database); @Override Warnings warn(Database database); @Override CheckSum generateCheckSum(); String getConfirmationMessage(); @Override void setSql(String sql); } |
@Override @Test public void getConfirmationMessage() throws Exception { change.setPath(fileName); assertEquals("SQL in file " + fileName + " executed", change.getConfirmationMessage()); } | public String getConfirmationMessage() { return "SQL in file " + path + " executed"; } | SQLFileChange extends AbstractSQLChange { public String getConfirmationMessage() { return "SQL in file " + path + " executed"; } } | SQLFileChange extends AbstractSQLChange { public String getConfirmationMessage() { return "SQL in file " + path + " executed"; } SQLFileChange(); } | SQLFileChange extends AbstractSQLChange { public String getConfirmationMessage() { return "SQL in file " + path + " executed"; } SQLFileChange(); String getPath(); void setPath(String fileName); String getEncoding(); void setEncoding(String encoding); Boolean isRelativeToChangelogFile(); void setRelativeToChangelogFile(Boolean relativeToChangelogFile); @Override void init(); @Override ValidationErrors validate(Database database); @Override Warnings warn(Database database); @Override CheckSum generateCheckSum(); String getConfirmationMessage(); @Override void setSql(String sql); } | SQLFileChange extends AbstractSQLChange { public String getConfirmationMessage() { return "SQL in file " + path + " executed"; } SQLFileChange(); String getPath(); void setPath(String fileName); String getEncoding(); void setEncoding(String encoding); Boolean isRelativeToChangelogFile(); void setRelativeToChangelogFile(Boolean relativeToChangelogFile); @Override void init(); @Override ValidationErrors validate(Database database); @Override Warnings warn(Database database); @Override CheckSum generateCheckSum(); String getConfirmationMessage(); @Override void setSql(String sql); } |
@Test public void testStatementsWithSemicolons() { AbstractSQLChange change2 = new SQLFileChange(); String insertWithSemicolon = "insert into table ( col ) values (' value with; semicolon ');"; change2.setSql(insertWithSemicolon); Database database = new MockDatabase(); SqlStatement[] statements = change2.generateStatements(database); assertEquals("Unexpected amount of statements returned",1, statements.length); String insertWithoutTrailingSemicolon = insertWithSemicolon.substring(0, insertWithSemicolon.length() - 1); assertEquals("unexpected SQL statement returned", insertWithoutTrailingSemicolon, statements[0].toString()); } | @Override public void setSql(String sql) { if (getChangeLogParameters() != null) { sql = getChangeLogParameters().expandExpressions(sql); } super.setSql(sql); } | SQLFileChange extends AbstractSQLChange { @Override public void setSql(String sql) { if (getChangeLogParameters() != null) { sql = getChangeLogParameters().expandExpressions(sql); } super.setSql(sql); } } | SQLFileChange extends AbstractSQLChange { @Override public void setSql(String sql) { if (getChangeLogParameters() != null) { sql = getChangeLogParameters().expandExpressions(sql); } super.setSql(sql); } SQLFileChange(); } | SQLFileChange extends AbstractSQLChange { @Override public void setSql(String sql) { if (getChangeLogParameters() != null) { sql = getChangeLogParameters().expandExpressions(sql); } super.setSql(sql); } SQLFileChange(); String getPath(); void setPath(String fileName); String getEncoding(); void setEncoding(String encoding); Boolean isRelativeToChangelogFile(); void setRelativeToChangelogFile(Boolean relativeToChangelogFile); @Override void init(); @Override ValidationErrors validate(Database database); @Override Warnings warn(Database database); @Override CheckSum generateCheckSum(); String getConfirmationMessage(); @Override void setSql(String sql); } | SQLFileChange extends AbstractSQLChange { @Override public void setSql(String sql) { if (getChangeLogParameters() != null) { sql = getChangeLogParameters().expandExpressions(sql); } super.setSql(sql); } SQLFileChange(); String getPath(); void setPath(String fileName); String getEncoding(); void setEncoding(String encoding); Boolean isRelativeToChangelogFile(); void setRelativeToChangelogFile(Boolean relativeToChangelogFile); @Override void init(); @Override ValidationErrors validate(Database database); @Override Warnings warn(Database database); @Override CheckSum generateCheckSum(); String getConfirmationMessage(); @Override void setSql(String sql); } |
@Test public void replacementOfProperties() throws Exception { SQLFileChange change = new SQLFileChange(); ChangeLogParameters changeLogParameters = new ChangeLogParameters(); changeLogParameters.set("table.prefix", "prfx"); changeLogParameters.set("some.other.prop", "nofx"); change.setChangeLogParameters(changeLogParameters); String fakeSql = "create ${table.prefix}_customer (${some.other.prop} INTEGER NOT NULL, PRIMARY KEY (${some.other.prop}));"; change.setSql(fakeSql); String expected = "create prfx_customer (nofx INTEGER NOT NULL, PRIMARY KEY (nofx));"; assertEquals(expected, change.getSql()); } | @Override public void setSql(String sql) { if (getChangeLogParameters() != null) { sql = getChangeLogParameters().expandExpressions(sql); } super.setSql(sql); } | SQLFileChange extends AbstractSQLChange { @Override public void setSql(String sql) { if (getChangeLogParameters() != null) { sql = getChangeLogParameters().expandExpressions(sql); } super.setSql(sql); } } | SQLFileChange extends AbstractSQLChange { @Override public void setSql(String sql) { if (getChangeLogParameters() != null) { sql = getChangeLogParameters().expandExpressions(sql); } super.setSql(sql); } SQLFileChange(); } | SQLFileChange extends AbstractSQLChange { @Override public void setSql(String sql) { if (getChangeLogParameters() != null) { sql = getChangeLogParameters().expandExpressions(sql); } super.setSql(sql); } SQLFileChange(); String getPath(); void setPath(String fileName); String getEncoding(); void setEncoding(String encoding); Boolean isRelativeToChangelogFile(); void setRelativeToChangelogFile(Boolean relativeToChangelogFile); @Override void init(); @Override ValidationErrors validate(Database database); @Override Warnings warn(Database database); @Override CheckSum generateCheckSum(); String getConfirmationMessage(); @Override void setSql(String sql); } | SQLFileChange extends AbstractSQLChange { @Override public void setSql(String sql) { if (getChangeLogParameters() != null) { sql = getChangeLogParameters().expandExpressions(sql); } super.setSql(sql); } SQLFileChange(); String getPath(); void setPath(String fileName); String getEncoding(); void setEncoding(String encoding); Boolean isRelativeToChangelogFile(); void setRelativeToChangelogFile(Boolean relativeToChangelogFile); @Override void init(); @Override ValidationErrors validate(Database database); @Override Warnings warn(Database database); @Override CheckSum generateCheckSum(); String getConfirmationMessage(); @Override void setSql(String sql); } |
@Override @Test public void getConfirmationMessage() throws Exception { CreateIndexChange refactoring = new CreateIndexChange(); refactoring.setIndexName("IDX_TEST"); assertEquals("Index IDX_TEST created", refactoring.getConfirmationMessage()); } | public String getConfirmationMessage() { return "Index " + getIndexName() + " created"; } | CreateIndexChange extends AbstractChange implements ChangeWithColumns<ColumnConfig> { public String getConfirmationMessage() { return "Index " + getIndexName() + " created"; } } | CreateIndexChange extends AbstractChange implements ChangeWithColumns<ColumnConfig> { public String getConfirmationMessage() { return "Index " + getIndexName() + " created"; } CreateIndexChange(); } | CreateIndexChange extends AbstractChange implements ChangeWithColumns<ColumnConfig> { public String getConfirmationMessage() { return "Index " + getIndexName() + " created"; } CreateIndexChange(); String getIndexName(); void setIndexName(String indexName); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); List<ColumnConfig> getColumns(); void setColumns(List<ColumnConfig> columns); void addColumn(ColumnConfig column); String getTablespace(); void setTablespace(String tablespace); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); void setUnique(Boolean isUnique); Boolean isUnique(); String getAssociatedWith(); void setAssociatedWith(String associatedWith); } | CreateIndexChange extends AbstractChange implements ChangeWithColumns<ColumnConfig> { public String getConfirmationMessage() { return "Index " + getIndexName() + " created"; } CreateIndexChange(); String getIndexName(); void setIndexName(String indexName); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); List<ColumnConfig> getColumns(); void setColumns(List<ColumnConfig> columns); void addColumn(ColumnConfig column); String getTablespace(); void setTablespace(String tablespace); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); void setUnique(Boolean isUnique); Boolean isUnique(); String getAssociatedWith(); void setAssociatedWith(String associatedWith); } |
@Override @Test public void getConfirmationMessage() throws Exception { AddAutoIncrementChange change = new AddAutoIncrementChange(); change.setSchemaName("SCHEMA_NAME"); change.setTableName("TABLE_NAME"); change.setColumnName("COLUMN_NAME"); change.setColumnDataType("DATATYPE(255)"); assertEquals("Auto-increment added to TABLE_NAME.COLUMN_NAME", change.getConfirmationMessage()); } | public String getConfirmationMessage() { return "Auto-increment added to " + getTableName() + "." + getColumnName(); } | AddAutoIncrementChange extends AbstractChange { public String getConfirmationMessage() { return "Auto-increment added to " + getTableName() + "." + getColumnName(); } } | AddAutoIncrementChange extends AbstractChange { public String getConfirmationMessage() { return "Auto-increment added to " + getTableName() + "." + getColumnName(); } AddAutoIncrementChange(); } | AddAutoIncrementChange extends AbstractChange { public String getConfirmationMessage() { return "Auto-increment added to " + getTableName() + "." + getColumnName(); } AddAutoIncrementChange(); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); String getColumnName(); void setColumnName(String columnName); String getColumnDataType(); void setColumnDataType(String columnDataType); BigInteger getStartWith(); void setStartWith(BigInteger startWith); BigInteger getIncrementBy(); void setIncrementBy(BigInteger incrementBy); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); } | AddAutoIncrementChange extends AbstractChange { public String getConfirmationMessage() { return "Auto-increment added to " + getTableName() + "." + getColumnName(); } AddAutoIncrementChange(); String getSchemaName(); void setSchemaName(String schemaName); String getTableName(); void setTableName(String tableName); String getColumnName(); void setColumnName(String columnName); String getColumnDataType(); void setColumnDataType(String columnDataType); BigInteger getStartWith(); void setStartWith(BigInteger startWith); BigInteger getIncrementBy(); void setIncrementBy(BigInteger incrementBy); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); } |
@Override @Test public void getConfirmationMessage() throws Exception { AddPrimaryKeyChange change = new AddPrimaryKeyChange(); change.setTableName("TABLE_NAME"); change.setColumnNames("COL_HERE"); assertEquals("Primary key added to TABLE_NAME (COL_HERE)", change.getConfirmationMessage()); } | public String getConfirmationMessage() { return "Primary key added to " + getTableName() + " (" + getColumnNames() + ")"; } | AddPrimaryKeyChange extends AbstractChange { public String getConfirmationMessage() { return "Primary key added to " + getTableName() + " (" + getColumnNames() + ")"; } } | AddPrimaryKeyChange extends AbstractChange { public String getConfirmationMessage() { return "Primary key added to " + getTableName() + " (" + getColumnNames() + ")"; } AddPrimaryKeyChange(); } | AddPrimaryKeyChange extends AbstractChange { public String getConfirmationMessage() { return "Primary key added to " + getTableName() + " (" + getColumnNames() + ")"; } AddPrimaryKeyChange(); String getTableName(); void setTableName(String tableName); String getSchemaName(); void setSchemaName(String schemaName); String getColumnNames(); void setColumnNames(String columnNames); String getConstraintName(); void setConstraintName(String constraintName); String getTablespace(); void setTablespace(String tablespace); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); } | AddPrimaryKeyChange extends AbstractChange { public String getConfirmationMessage() { return "Primary key added to " + getTableName() + " (" + getColumnNames() + ")"; } AddPrimaryKeyChange(); String getTableName(); void setTableName(String tableName); String getSchemaName(); void setSchemaName(String schemaName); String getColumnNames(); void setColumnNames(String columnNames); String getConstraintName(); void setConstraintName(String constraintName); String getTablespace(); void setTablespace(String tablespace); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); } |
@Override @Test public void getConfirmationMessage() throws Exception { CreateSequenceChange change = new CreateSequenceChange(); change.setSequenceName("SEQ_NAME"); assertEquals("Sequence SEQ_NAME created", change.getConfirmationMessage()); } | public String getConfirmationMessage() { return "Sequence " + getSequenceName() + " created"; } | CreateSequenceChange extends AbstractChange { public String getConfirmationMessage() { return "Sequence " + getSequenceName() + " created"; } } | CreateSequenceChange extends AbstractChange { public String getConfirmationMessage() { return "Sequence " + getSequenceName() + " created"; } CreateSequenceChange(); } | CreateSequenceChange extends AbstractChange { public String getConfirmationMessage() { return "Sequence " + getSequenceName() + " created"; } CreateSequenceChange(); String getSchemaName(); void setSchemaName(String schemaName); String getSequenceName(); void setSequenceName(String sequenceName); BigInteger getStartValue(); void setStartValue(BigInteger startValue); BigInteger getIncrementBy(); void setIncrementBy(BigInteger incrementBy); BigInteger getMaxValue(); void setMaxValue(BigInteger maxValue); BigInteger getMinValue(); void setMinValue(BigInteger minValue); Boolean isOrdered(); void setOrdered(Boolean ordered); Boolean getCycle(); void setCycle(Boolean cycle); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); } | CreateSequenceChange extends AbstractChange { public String getConfirmationMessage() { return "Sequence " + getSequenceName() + " created"; } CreateSequenceChange(); String getSchemaName(); void setSchemaName(String schemaName); String getSequenceName(); void setSequenceName(String sequenceName); BigInteger getStartValue(); void setStartValue(BigInteger startValue); BigInteger getIncrementBy(); void setIncrementBy(BigInteger incrementBy); BigInteger getMaxValue(); void setMaxValue(BigInteger maxValue); BigInteger getMinValue(); void setMinValue(BigInteger minValue); Boolean isOrdered(); void setOrdered(Boolean ordered); Boolean getCycle(); void setCycle(Boolean cycle); SqlStatement[] generateStatements(Database database); String getConfirmationMessage(); } |
@Test public void generateCheckSum() throws Exception { Change change = createClassUnderTest(); if (change == null) { return; } CheckSum checkSum = change.generateCheckSum(); assertNotNull(checkSum); assertEquals(CheckSum.getCurrentVersion(), checkSum.getVersion()); assertTrue(checkSum.toString().startsWith(CheckSum.getCurrentVersion()+":")); Map<String, String> seenCheckSums = new HashMap<String, String>(); for (Field field : change.getClass().getDeclaredFields()) { field.setAccessible(true); if (field.getName().startsWith("$VR") || field.getName().equals("serialVersionUID")) { } else if (field.getName().equals("associatedWith")) { } else if (String.class.isAssignableFrom(field.getType())) { field.set(change, "asdghasdgasdg"); checkThatChecksumIsNew(change, seenCheckSums, field); field.set(change, "gsgasdgasdggasdg sdg a"); checkThatChecksumIsNew(change, seenCheckSums, field); } else if (Boolean.class.isAssignableFrom(field.getType())) { field.set(change, Boolean.TRUE); checkThatChecksumIsNew(change, seenCheckSums, field); field.set(change, Boolean.FALSE); checkThatChecksumIsNew(change, seenCheckSums, field); } else if (Integer.class.isAssignableFrom(field.getType())) { field.set(change, 6532); checkThatChecksumIsNew(change, seenCheckSums, field); field.set(change, -52352); checkThatChecksumIsNew(change, seenCheckSums, field); } else if (DatabaseFunction.class.isAssignableFrom(field.getType())) { field.set(change, new DatabaseFunction("FUNC1")); checkThatChecksumIsNew(change, seenCheckSums, field); field.set(change, new DatabaseFunction("FUNC 2")); checkThatChecksumIsNew(change, seenCheckSums, field); } else if (BigInteger.class.isAssignableFrom(field.getType())) { field.set(change, new BigInteger("6532")); checkThatChecksumIsNew(change, seenCheckSums, field); field.set(change, new BigInteger("-52352")); checkThatChecksumIsNew(change, seenCheckSums, field); } else if (List.class.isAssignableFrom(field.getType())) { ColumnConfig column1 = new ColumnConfig(); ((List) field.get(change)).add(column1); column1.setName("ghsdgasdg"); checkThatChecksumIsNew(change, seenCheckSums, field); column1.setType("gasdgasdg"); checkThatChecksumIsNew(change, seenCheckSums, field); ColumnConfig column2 = new ColumnConfig(); ((List) field.get(change)).add(column2); column2.setName("87682346asgasdg"); checkThatChecksumIsNew(change, seenCheckSums, field); } else if (field.getName().equalsIgnoreCase("changeLogParameters")) { } else { throw new RuntimeException("Unknown field type: "+field.getType()+" for "+field.getName()); } } } | public CheckSum generateCheckSum() { return CheckSum.compute(new StringChangeLogSerializer().serialize(this)); } | AbstractChange implements Change { public CheckSum generateCheckSum() { return CheckSum.compute(new StringChangeLogSerializer().serialize(this)); } } | AbstractChange implements Change { public CheckSum generateCheckSum() { return CheckSum.compute(new StringChangeLogSerializer().serialize(this)); } protected AbstractChange(String changeName, String changeDescription, int priority); } | AbstractChange implements Change { public CheckSum generateCheckSum() { return CheckSum.compute(new StringChangeLogSerializer().serialize(this)); } protected AbstractChange(String changeName, String changeDescription, int priority); ChangeMetaData getChangeMetaData(); ChangeSet getChangeSet(); void setChangeSet(ChangeSet changeSet); boolean requiresUpdatedDatabaseMetadata(Database database); boolean supports(Database database); Warnings warn(Database database); ValidationErrors validate(Database database); SqlStatement[] generateRollbackStatements(Database database); boolean supportsRollback(Database database); CheckSum generateCheckSum(); void setResourceAccessor(ResourceAccessor resourceAccessor); ResourceAccessor getResourceAccessor(); void init(); Set<DatabaseObject> getAffectedDatabaseObjects(Database database); void setChangeLogParameters(ChangeLogParameters changeLogParameters); } | AbstractChange implements Change { public CheckSum generateCheckSum() { return CheckSum.compute(new StringChangeLogSerializer().serialize(this)); } protected AbstractChange(String changeName, String changeDescription, int priority); ChangeMetaData getChangeMetaData(); ChangeSet getChangeSet(); void setChangeSet(ChangeSet changeSet); boolean requiresUpdatedDatabaseMetadata(Database database); boolean supports(Database database); Warnings warn(Database database); ValidationErrors validate(Database database); SqlStatement[] generateRollbackStatements(Database database); boolean supportsRollback(Database database); CheckSum generateCheckSum(); void setResourceAccessor(ResourceAccessor resourceAccessor); ResourceAccessor getResourceAccessor(); void init(); Set<DatabaseObject> getAffectedDatabaseObjects(Database database); void setChangeLogParameters(ChangeLogParameters changeLogParameters); } |
@Test public void escapeTableName_noSchema() { Database database = getDatabase(); assertEquals("tableName", database.escapeTableName(null, "tableName")); } | public String escapeTableName(String schemaName, String tableName) { if (schemaName == null) { schemaName = getDefaultSchemaName(); } if (StringUtils.trimToNull(schemaName) == null || !supportsSchemas()) { return escapeDatabaseObject(tableName); } else { return escapeDatabaseObject(schemaName) + "." + escapeDatabaseObject(tableName); } } | AbstractDatabase implements Database { public String escapeTableName(String schemaName, String tableName) { if (schemaName == null) { schemaName = getDefaultSchemaName(); } if (StringUtils.trimToNull(schemaName) == null || !supportsSchemas()) { return escapeDatabaseObject(tableName); } else { return escapeDatabaseObject(schemaName) + "." + escapeDatabaseObject(tableName); } } } | AbstractDatabase implements Database { public String escapeTableName(String schemaName, String tableName) { if (schemaName == null) { schemaName = getDefaultSchemaName(); } if (StringUtils.trimToNull(schemaName) == null || !supportsSchemas()) { return escapeDatabaseObject(tableName); } else { return escapeDatabaseObject(schemaName) + "." + escapeDatabaseObject(tableName); } } protected AbstractDatabase(); } | AbstractDatabase implements Database { public String escapeTableName(String schemaName, String tableName) { if (schemaName == null) { schemaName = getDefaultSchemaName(); } if (StringUtils.trimToNull(schemaName) == null || !supportsSchemas()) { return escapeDatabaseObject(tableName); } else { return escapeDatabaseObject(schemaName) + "." + escapeDatabaseObject(tableName); } } protected AbstractDatabase(); boolean requiresPassword(); boolean requiresUsername(); DatabaseObject[] getContainingObjects(); DatabaseConnection getConnection(); void setConnection(DatabaseConnection conn); boolean getAutoCommitMode(); boolean supportsDDLInTransaction(); String getDatabaseProductName(); String getDatabaseProductVersion(); int getDatabaseMajorVersion(); int getDatabaseMinorVersion(); String getDefaultCatalogName(); String getDefaultSchemaName(); void setDefaultSchemaName(String schemaName); boolean supportsSequences(); boolean supportsAutoIncrement(); void setCurrentDateTimeFunction(String function); String getDateLiteral(String isoDate); String getDateTimeLiteral(java.sql.Timestamp date); String getDateLiteral(java.sql.Date date); String getTimeLiteral(java.sql.Time date); String getDateLiteral(Date date); Date parseDate(String dateAsString); String getLineComment(); String getAutoIncrementClause(BigInteger startWith, BigInteger incrementBy); String getConcatSql(String... values); String getDatabaseChangeLogTableName(); String getDatabaseChangeLogLockTableName(); void setDatabaseChangeLogTableName(String tableName); void setDatabaseChangeLogLockTableName(String tableName); void checkDatabaseChangeLogTable(boolean updateExistingNullChecksums, DatabaseChangeLog databaseChangeLog, String... contexts); void setCanCacheLiquibaseTableInfo(boolean canCacheLiquibaseTableInfo); boolean hasDatabaseChangeLogTable(); boolean hasDatabaseChangeLogLockTable(); String getLiquibaseSchemaName(); void checkDatabaseChangeLogLockTable(); boolean isReservedWord(String string); void dropDatabaseObjects(String schema); boolean supportsDropTableCascadeConstraints(); boolean isSystemTable(String catalogName, String schemaName, String tableName); boolean isSystemView(String catalogName, String schemaName, String viewName); boolean isLiquibaseTable(String tableName); void tag(String tagString); boolean doesTagExist(String tag); @Override String toString(); boolean shouldQuoteValue(String value); String getViewDefinition(String schemaName, String viewName); String escapeTableName(String schemaName, String tableName); String escapeDatabaseObject(String objectName); String escapeIndexName(String schemaName, String indexName); String escapeSequenceName(String schemaName, String sequenceName); String escapeConstraintName(String constraintName); String escapeColumnName(String schemaName, String tableName, String columnName); String escapeColumnNameList(String columnNames); String convertRequestedSchemaToCatalog(String requestedSchema); String convertRequestedSchemaToSchema(String requestedSchema); boolean supportsSchemas(); String generatePrimaryKeyName(String tableName); String escapeViewName(String schemaName, String viewName); ChangeSet.RunStatus getRunStatus(ChangeSet changeSet); RanChangeSet getRanChangeSet(ChangeSet changeSet); List<RanChangeSet> getRanChangeSetList(); Date getRanDate(ChangeSet changeSet); void markChangeSetExecStatus(ChangeSet changeSet, ChangeSet.ExecType execType); void removeRanStatus(ChangeSet changeSet); String escapeStringForDatabase(String string); void commit(); void rollback(); @Override boolean equals(Object o); @Override int hashCode(); void close(); boolean supportsRestrictForeignKeys(); boolean isAutoCommit(); void setAutoCommit(boolean b); boolean isLocalDatabase(); void executeStatements(Change change, DatabaseChangeLog changeLog, List<SqlVisitor> sqlVisitors); void execute(SqlStatement[] statements, List<SqlVisitor> sqlVisitors); void saveStatements(Change change, List<SqlVisitor> sqlVisitors, Writer writer); void executeRollbackStatements(Change change, List<SqlVisitor> sqlVisitors); void saveRollbackStatement(Change change, List<SqlVisitor> sqlVisitors, Writer writer); int getNextChangeSetSequenceValue(); Table getTable(String schemaName, String tableName); List<DatabaseFunction> getDatabaseFunctions(); void reset(); boolean supportsForeignKeyDisable(); boolean disableForeignKeyChecks(); void enableForeignKeyChecks(); } | AbstractDatabase implements Database { public String escapeTableName(String schemaName, String tableName) { if (schemaName == null) { schemaName = getDefaultSchemaName(); } if (StringUtils.trimToNull(schemaName) == null || !supportsSchemas()) { return escapeDatabaseObject(tableName); } else { return escapeDatabaseObject(schemaName) + "." + escapeDatabaseObject(tableName); } } protected AbstractDatabase(); boolean requiresPassword(); boolean requiresUsername(); DatabaseObject[] getContainingObjects(); DatabaseConnection getConnection(); void setConnection(DatabaseConnection conn); boolean getAutoCommitMode(); boolean supportsDDLInTransaction(); String getDatabaseProductName(); String getDatabaseProductVersion(); int getDatabaseMajorVersion(); int getDatabaseMinorVersion(); String getDefaultCatalogName(); String getDefaultSchemaName(); void setDefaultSchemaName(String schemaName); boolean supportsSequences(); boolean supportsAutoIncrement(); void setCurrentDateTimeFunction(String function); String getDateLiteral(String isoDate); String getDateTimeLiteral(java.sql.Timestamp date); String getDateLiteral(java.sql.Date date); String getTimeLiteral(java.sql.Time date); String getDateLiteral(Date date); Date parseDate(String dateAsString); String getLineComment(); String getAutoIncrementClause(BigInteger startWith, BigInteger incrementBy); String getConcatSql(String... values); String getDatabaseChangeLogTableName(); String getDatabaseChangeLogLockTableName(); void setDatabaseChangeLogTableName(String tableName); void setDatabaseChangeLogLockTableName(String tableName); void checkDatabaseChangeLogTable(boolean updateExistingNullChecksums, DatabaseChangeLog databaseChangeLog, String... contexts); void setCanCacheLiquibaseTableInfo(boolean canCacheLiquibaseTableInfo); boolean hasDatabaseChangeLogTable(); boolean hasDatabaseChangeLogLockTable(); String getLiquibaseSchemaName(); void checkDatabaseChangeLogLockTable(); boolean isReservedWord(String string); void dropDatabaseObjects(String schema); boolean supportsDropTableCascadeConstraints(); boolean isSystemTable(String catalogName, String schemaName, String tableName); boolean isSystemView(String catalogName, String schemaName, String viewName); boolean isLiquibaseTable(String tableName); void tag(String tagString); boolean doesTagExist(String tag); @Override String toString(); boolean shouldQuoteValue(String value); String getViewDefinition(String schemaName, String viewName); String escapeTableName(String schemaName, String tableName); String escapeDatabaseObject(String objectName); String escapeIndexName(String schemaName, String indexName); String escapeSequenceName(String schemaName, String sequenceName); String escapeConstraintName(String constraintName); String escapeColumnName(String schemaName, String tableName, String columnName); String escapeColumnNameList(String columnNames); String convertRequestedSchemaToCatalog(String requestedSchema); String convertRequestedSchemaToSchema(String requestedSchema); boolean supportsSchemas(); String generatePrimaryKeyName(String tableName); String escapeViewName(String schemaName, String viewName); ChangeSet.RunStatus getRunStatus(ChangeSet changeSet); RanChangeSet getRanChangeSet(ChangeSet changeSet); List<RanChangeSet> getRanChangeSetList(); Date getRanDate(ChangeSet changeSet); void markChangeSetExecStatus(ChangeSet changeSet, ChangeSet.ExecType execType); void removeRanStatus(ChangeSet changeSet); String escapeStringForDatabase(String string); void commit(); void rollback(); @Override boolean equals(Object o); @Override int hashCode(); void close(); boolean supportsRestrictForeignKeys(); boolean isAutoCommit(); void setAutoCommit(boolean b); boolean isLocalDatabase(); void executeStatements(Change change, DatabaseChangeLog changeLog, List<SqlVisitor> sqlVisitors); void execute(SqlStatement[] statements, List<SqlVisitor> sqlVisitors); void saveStatements(Change change, List<SqlVisitor> sqlVisitors, Writer writer); void executeRollbackStatements(Change change, List<SqlVisitor> sqlVisitors); void saveRollbackStatement(Change change, List<SqlVisitor> sqlVisitors, Writer writer); int getNextChangeSetSequenceValue(); Table getTable(String schemaName, String tableName); List<DatabaseFunction> getDatabaseFunctions(); void reset(); boolean supportsForeignKeyDisable(); boolean disableForeignKeyChecks(); void enableForeignKeyChecks(); } |
@Test public void isSupported() throws Exception { Change change = createClassUnderTest(); if (change == null) { return; } for (Database database : TestContext.getInstance().getAllDatabases()) { assertEquals("Unexpected availablity on "+database.getTypeName(), !changeIsUnsupported(database), change.supports(database)); } } | public boolean supports(Database database) { for (SqlStatement statement : generateStatements(database)) { if (!SqlGeneratorFactory.getInstance().supports(statement, database)) { return false; } } return true; } | AbstractChange implements Change { public boolean supports(Database database) { for (SqlStatement statement : generateStatements(database)) { if (!SqlGeneratorFactory.getInstance().supports(statement, database)) { return false; } } return true; } } | AbstractChange implements Change { public boolean supports(Database database) { for (SqlStatement statement : generateStatements(database)) { if (!SqlGeneratorFactory.getInstance().supports(statement, database)) { return false; } } return true; } protected AbstractChange(String changeName, String changeDescription, int priority); } | AbstractChange implements Change { public boolean supports(Database database) { for (SqlStatement statement : generateStatements(database)) { if (!SqlGeneratorFactory.getInstance().supports(statement, database)) { return false; } } return true; } protected AbstractChange(String changeName, String changeDescription, int priority); ChangeMetaData getChangeMetaData(); ChangeSet getChangeSet(); void setChangeSet(ChangeSet changeSet); boolean requiresUpdatedDatabaseMetadata(Database database); boolean supports(Database database); Warnings warn(Database database); ValidationErrors validate(Database database); SqlStatement[] generateRollbackStatements(Database database); boolean supportsRollback(Database database); CheckSum generateCheckSum(); void setResourceAccessor(ResourceAccessor resourceAccessor); ResourceAccessor getResourceAccessor(); void init(); Set<DatabaseObject> getAffectedDatabaseObjects(Database database); void setChangeLogParameters(ChangeLogParameters changeLogParameters); } | AbstractChange implements Change { public boolean supports(Database database) { for (SqlStatement statement : generateStatements(database)) { if (!SqlGeneratorFactory.getInstance().supports(statement, database)) { return false; } } return true; } protected AbstractChange(String changeName, String changeDescription, int priority); ChangeMetaData getChangeMetaData(); ChangeSet getChangeSet(); void setChangeSet(ChangeSet changeSet); boolean requiresUpdatedDatabaseMetadata(Database database); boolean supports(Database database); Warnings warn(Database database); ValidationErrors validate(Database database); SqlStatement[] generateRollbackStatements(Database database); boolean supportsRollback(Database database); CheckSum generateCheckSum(); void setResourceAccessor(ResourceAccessor resourceAccessor); ResourceAccessor getResourceAccessor(); void init(); Set<DatabaseObject> getAffectedDatabaseObjects(Database database); void setChangeLogParameters(ChangeLogParameters changeLogParameters); } |
@Test public void validate() throws Exception { Change change = createClassUnderTest(); if (change == null) { return; } for (Database database : TestContext.getInstance().getAllDatabases()) { if (change.supports(database)) { ValidationErrors validationErrors = change.validate(database); assertTrue("no errors found for "+database.getClass().getName(), validationErrors.hasErrors()); } } } | public ValidationErrors validate(Database database) { ValidationErrors changeValidationErrors = new ValidationErrors(); for (SqlStatement statement : generateStatements(database)) { boolean supported = SqlGeneratorFactory.getInstance().supports(statement, database); if (!supported) { if (statement.skipOnUnsupported()) { LogFactory.getLogger().info(getChangeMetaData().getName()+" is not supported on "+database.getTypeName()+" but will continue"); } else { changeValidationErrors.addError(getChangeMetaData().getName()+" is not supported on "+database.getTypeName()); } } else { changeValidationErrors.addAll(SqlGeneratorFactory.getInstance().validate(statement, database)); } } return changeValidationErrors; } | AbstractChange implements Change { public ValidationErrors validate(Database database) { ValidationErrors changeValidationErrors = new ValidationErrors(); for (SqlStatement statement : generateStatements(database)) { boolean supported = SqlGeneratorFactory.getInstance().supports(statement, database); if (!supported) { if (statement.skipOnUnsupported()) { LogFactory.getLogger().info(getChangeMetaData().getName()+" is not supported on "+database.getTypeName()+" but will continue"); } else { changeValidationErrors.addError(getChangeMetaData().getName()+" is not supported on "+database.getTypeName()); } } else { changeValidationErrors.addAll(SqlGeneratorFactory.getInstance().validate(statement, database)); } } return changeValidationErrors; } } | AbstractChange implements Change { public ValidationErrors validate(Database database) { ValidationErrors changeValidationErrors = new ValidationErrors(); for (SqlStatement statement : generateStatements(database)) { boolean supported = SqlGeneratorFactory.getInstance().supports(statement, database); if (!supported) { if (statement.skipOnUnsupported()) { LogFactory.getLogger().info(getChangeMetaData().getName()+" is not supported on "+database.getTypeName()+" but will continue"); } else { changeValidationErrors.addError(getChangeMetaData().getName()+" is not supported on "+database.getTypeName()); } } else { changeValidationErrors.addAll(SqlGeneratorFactory.getInstance().validate(statement, database)); } } return changeValidationErrors; } protected AbstractChange(String changeName, String changeDescription, int priority); } | AbstractChange implements Change { public ValidationErrors validate(Database database) { ValidationErrors changeValidationErrors = new ValidationErrors(); for (SqlStatement statement : generateStatements(database)) { boolean supported = SqlGeneratorFactory.getInstance().supports(statement, database); if (!supported) { if (statement.skipOnUnsupported()) { LogFactory.getLogger().info(getChangeMetaData().getName()+" is not supported on "+database.getTypeName()+" but will continue"); } else { changeValidationErrors.addError(getChangeMetaData().getName()+" is not supported on "+database.getTypeName()); } } else { changeValidationErrors.addAll(SqlGeneratorFactory.getInstance().validate(statement, database)); } } return changeValidationErrors; } protected AbstractChange(String changeName, String changeDescription, int priority); ChangeMetaData getChangeMetaData(); ChangeSet getChangeSet(); void setChangeSet(ChangeSet changeSet); boolean requiresUpdatedDatabaseMetadata(Database database); boolean supports(Database database); Warnings warn(Database database); ValidationErrors validate(Database database); SqlStatement[] generateRollbackStatements(Database database); boolean supportsRollback(Database database); CheckSum generateCheckSum(); void setResourceAccessor(ResourceAccessor resourceAccessor); ResourceAccessor getResourceAccessor(); void init(); Set<DatabaseObject> getAffectedDatabaseObjects(Database database); void setChangeLogParameters(ChangeLogParameters changeLogParameters); } | AbstractChange implements Change { public ValidationErrors validate(Database database) { ValidationErrors changeValidationErrors = new ValidationErrors(); for (SqlStatement statement : generateStatements(database)) { boolean supported = SqlGeneratorFactory.getInstance().supports(statement, database); if (!supported) { if (statement.skipOnUnsupported()) { LogFactory.getLogger().info(getChangeMetaData().getName()+" is not supported on "+database.getTypeName()+" but will continue"); } else { changeValidationErrors.addError(getChangeMetaData().getName()+" is not supported on "+database.getTypeName()); } } else { changeValidationErrors.addAll(SqlGeneratorFactory.getInstance().validate(statement, database)); } } return changeValidationErrors; } protected AbstractChange(String changeName, String changeDescription, int priority); ChangeMetaData getChangeMetaData(); ChangeSet getChangeSet(); void setChangeSet(ChangeSet changeSet); boolean requiresUpdatedDatabaseMetadata(Database database); boolean supports(Database database); Warnings warn(Database database); ValidationErrors validate(Database database); SqlStatement[] generateRollbackStatements(Database database); boolean supportsRollback(Database database); CheckSum generateCheckSum(); void setResourceAccessor(ResourceAccessor resourceAccessor); ResourceAccessor getResourceAccessor(); void init(); Set<DatabaseObject> getAffectedDatabaseObjects(Database database); void setChangeLogParameters(ChangeLogParameters changeLogParameters); } |
@Test public void simpleChangeLog() throws Exception { DatabaseChangeLog changeLog = new XMLChangeLogSAXParser().parse("liquibase/parser/core/xml/simpleChangeLog.xml", new ChangeLogParameters(), new JUnitResourceAccessor()); assertEquals("liquibase/parser/core/xml/simpleChangeLog.xml", changeLog.getLogicalFilePath()); assertEquals("liquibase/parser/core/xml/simpleChangeLog.xml", changeLog.getPhysicalFilePath()); assertEquals(0, changeLog.getPreconditions().getNestedPreconditions().size()); assertEquals(1, changeLog.getChangeSets().size()); ChangeSet changeSet = changeLog.getChangeSets().get(0); assertEquals("nvoxland", changeSet.getAuthor()); assertEquals("1", changeSet.getId()); assertEquals(1, changeSet.getChanges().size()); assertEquals("liquibase/parser/core/xml/simpleChangeLog.xml", changeSet.getFilePath()); assertEquals("Some comments go here", changeSet.getComments()); Change change = changeSet.getChanges().get(0); assertEquals("createTable", change.getChangeMetaData().getName()); assertTrue(change instanceof CreateTableChange); } | public DatabaseChangeLog parse(String physicalChangeLogLocation, ChangeLogParameters changeLogParameters, ResourceAccessor resourceAccessor) throws ChangeLogParseException { InputStream inputStream = null; try { SAXParser parser = saxParserFactory.newSAXParser(); try { parser.setProperty("http: } catch (SAXNotRecognizedException e) { } catch (SAXNotSupportedException e) { } XMLReader xmlReader = parser.getXMLReader(); LiquibaseEntityResolver resolver=new LiquibaseEntityResolver(); resolver.useResoureAccessor(resourceAccessor,FilenameUtils.getFullPath(physicalChangeLogLocation)); xmlReader.setEntityResolver(resolver); xmlReader.setErrorHandler(new ErrorHandler() { public void warning(SAXParseException exception) throws SAXException { LogFactory.getLogger().warning(exception.getMessage()); throw exception; } public void error(SAXParseException exception) throws SAXException { LogFactory.getLogger().severe(exception.getMessage()); throw exception; } public void fatalError(SAXParseException exception) throws SAXException { LogFactory.getLogger().severe(exception.getMessage()); throw exception; } }); inputStream = resourceAccessor.getResourceAsStream(physicalChangeLogLocation); if (inputStream == null) { throw new ChangeLogParseException(physicalChangeLogLocation + " does not exist"); } XMLChangeLogSAXHandler contentHandler = new XMLChangeLogSAXHandler(physicalChangeLogLocation, resourceAccessor, changeLogParameters); xmlReader.setContentHandler(contentHandler); xmlReader.parse(new InputSource(inputStream)); return contentHandler.getDatabaseChangeLog(); } catch (ChangeLogParseException e) { throw e; } catch (IOException e) { throw new ChangeLogParseException("Error Reading Migration File: " + e.getMessage(), e); } catch (SAXParseException e) { throw new ChangeLogParseException("Error parsing line " + e.getLineNumber() + " column " + e.getColumnNumber() + " of " + physicalChangeLogLocation +": " + e.getMessage(), e); } catch (SAXException e) { Throwable parentCause = e.getException(); while (parentCause != null) { if (parentCause instanceof ChangeLogParseException) { throw ((ChangeLogParseException) parentCause); } parentCause = parentCause.getCause(); } String reason = e.getMessage(); String causeReason = null; if (e.getCause() != null) { causeReason = e.getCause().getMessage(); } if (reason == null) { if (causeReason != null) { reason = causeReason; } else { reason = "Unknown Reason"; } } throw new ChangeLogParseException("Invalid Migration File: " + reason, e); } catch (Exception e) { throw new ChangeLogParseException(e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { } } } } | XMLChangeLogSAXParser implements ChangeLogParser { public DatabaseChangeLog parse(String physicalChangeLogLocation, ChangeLogParameters changeLogParameters, ResourceAccessor resourceAccessor) throws ChangeLogParseException { InputStream inputStream = null; try { SAXParser parser = saxParserFactory.newSAXParser(); try { parser.setProperty("http: } catch (SAXNotRecognizedException e) { } catch (SAXNotSupportedException e) { } XMLReader xmlReader = parser.getXMLReader(); LiquibaseEntityResolver resolver=new LiquibaseEntityResolver(); resolver.useResoureAccessor(resourceAccessor,FilenameUtils.getFullPath(physicalChangeLogLocation)); xmlReader.setEntityResolver(resolver); xmlReader.setErrorHandler(new ErrorHandler() { public void warning(SAXParseException exception) throws SAXException { LogFactory.getLogger().warning(exception.getMessage()); throw exception; } public void error(SAXParseException exception) throws SAXException { LogFactory.getLogger().severe(exception.getMessage()); throw exception; } public void fatalError(SAXParseException exception) throws SAXException { LogFactory.getLogger().severe(exception.getMessage()); throw exception; } }); inputStream = resourceAccessor.getResourceAsStream(physicalChangeLogLocation); if (inputStream == null) { throw new ChangeLogParseException(physicalChangeLogLocation + " does not exist"); } XMLChangeLogSAXHandler contentHandler = new XMLChangeLogSAXHandler(physicalChangeLogLocation, resourceAccessor, changeLogParameters); xmlReader.setContentHandler(contentHandler); xmlReader.parse(new InputSource(inputStream)); return contentHandler.getDatabaseChangeLog(); } catch (ChangeLogParseException e) { throw e; } catch (IOException e) { throw new ChangeLogParseException("Error Reading Migration File: " + e.getMessage(), e); } catch (SAXParseException e) { throw new ChangeLogParseException("Error parsing line " + e.getLineNumber() + " column " + e.getColumnNumber() + " of " + physicalChangeLogLocation +": " + e.getMessage(), e); } catch (SAXException e) { Throwable parentCause = e.getException(); while (parentCause != null) { if (parentCause instanceof ChangeLogParseException) { throw ((ChangeLogParseException) parentCause); } parentCause = parentCause.getCause(); } String reason = e.getMessage(); String causeReason = null; if (e.getCause() != null) { causeReason = e.getCause().getMessage(); } if (reason == null) { if (causeReason != null) { reason = causeReason; } else { reason = "Unknown Reason"; } } throw new ChangeLogParseException("Invalid Migration File: " + reason, e); } catch (Exception e) { throw new ChangeLogParseException(e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { } } } } } | XMLChangeLogSAXParser implements ChangeLogParser { public DatabaseChangeLog parse(String physicalChangeLogLocation, ChangeLogParameters changeLogParameters, ResourceAccessor resourceAccessor) throws ChangeLogParseException { InputStream inputStream = null; try { SAXParser parser = saxParserFactory.newSAXParser(); try { parser.setProperty("http: } catch (SAXNotRecognizedException e) { } catch (SAXNotSupportedException e) { } XMLReader xmlReader = parser.getXMLReader(); LiquibaseEntityResolver resolver=new LiquibaseEntityResolver(); resolver.useResoureAccessor(resourceAccessor,FilenameUtils.getFullPath(physicalChangeLogLocation)); xmlReader.setEntityResolver(resolver); xmlReader.setErrorHandler(new ErrorHandler() { public void warning(SAXParseException exception) throws SAXException { LogFactory.getLogger().warning(exception.getMessage()); throw exception; } public void error(SAXParseException exception) throws SAXException { LogFactory.getLogger().severe(exception.getMessage()); throw exception; } public void fatalError(SAXParseException exception) throws SAXException { LogFactory.getLogger().severe(exception.getMessage()); throw exception; } }); inputStream = resourceAccessor.getResourceAsStream(physicalChangeLogLocation); if (inputStream == null) { throw new ChangeLogParseException(physicalChangeLogLocation + " does not exist"); } XMLChangeLogSAXHandler contentHandler = new XMLChangeLogSAXHandler(physicalChangeLogLocation, resourceAccessor, changeLogParameters); xmlReader.setContentHandler(contentHandler); xmlReader.parse(new InputSource(inputStream)); return contentHandler.getDatabaseChangeLog(); } catch (ChangeLogParseException e) { throw e; } catch (IOException e) { throw new ChangeLogParseException("Error Reading Migration File: " + e.getMessage(), e); } catch (SAXParseException e) { throw new ChangeLogParseException("Error parsing line " + e.getLineNumber() + " column " + e.getColumnNumber() + " of " + physicalChangeLogLocation +": " + e.getMessage(), e); } catch (SAXException e) { Throwable parentCause = e.getException(); while (parentCause != null) { if (parentCause instanceof ChangeLogParseException) { throw ((ChangeLogParseException) parentCause); } parentCause = parentCause.getCause(); } String reason = e.getMessage(); String causeReason = null; if (e.getCause() != null) { causeReason = e.getCause().getMessage(); } if (reason == null) { if (causeReason != null) { reason = causeReason; } else { reason = "Unknown Reason"; } } throw new ChangeLogParseException("Invalid Migration File: " + reason, e); } catch (Exception e) { throw new ChangeLogParseException(e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { } } } } XMLChangeLogSAXParser(); } | XMLChangeLogSAXParser implements ChangeLogParser { public DatabaseChangeLog parse(String physicalChangeLogLocation, ChangeLogParameters changeLogParameters, ResourceAccessor resourceAccessor) throws ChangeLogParseException { InputStream inputStream = null; try { SAXParser parser = saxParserFactory.newSAXParser(); try { parser.setProperty("http: } catch (SAXNotRecognizedException e) { } catch (SAXNotSupportedException e) { } XMLReader xmlReader = parser.getXMLReader(); LiquibaseEntityResolver resolver=new LiquibaseEntityResolver(); resolver.useResoureAccessor(resourceAccessor,FilenameUtils.getFullPath(physicalChangeLogLocation)); xmlReader.setEntityResolver(resolver); xmlReader.setErrorHandler(new ErrorHandler() { public void warning(SAXParseException exception) throws SAXException { LogFactory.getLogger().warning(exception.getMessage()); throw exception; } public void error(SAXParseException exception) throws SAXException { LogFactory.getLogger().severe(exception.getMessage()); throw exception; } public void fatalError(SAXParseException exception) throws SAXException { LogFactory.getLogger().severe(exception.getMessage()); throw exception; } }); inputStream = resourceAccessor.getResourceAsStream(physicalChangeLogLocation); if (inputStream == null) { throw new ChangeLogParseException(physicalChangeLogLocation + " does not exist"); } XMLChangeLogSAXHandler contentHandler = new XMLChangeLogSAXHandler(physicalChangeLogLocation, resourceAccessor, changeLogParameters); xmlReader.setContentHandler(contentHandler); xmlReader.parse(new InputSource(inputStream)); return contentHandler.getDatabaseChangeLog(); } catch (ChangeLogParseException e) { throw e; } catch (IOException e) { throw new ChangeLogParseException("Error Reading Migration File: " + e.getMessage(), e); } catch (SAXParseException e) { throw new ChangeLogParseException("Error parsing line " + e.getLineNumber() + " column " + e.getColumnNumber() + " of " + physicalChangeLogLocation +": " + e.getMessage(), e); } catch (SAXException e) { Throwable parentCause = e.getException(); while (parentCause != null) { if (parentCause instanceof ChangeLogParseException) { throw ((ChangeLogParseException) parentCause); } parentCause = parentCause.getCause(); } String reason = e.getMessage(); String causeReason = null; if (e.getCause() != null) { causeReason = e.getCause().getMessage(); } if (reason == null) { if (causeReason != null) { reason = causeReason; } else { reason = "Unknown Reason"; } } throw new ChangeLogParseException("Invalid Migration File: " + reason, e); } catch (Exception e) { throw new ChangeLogParseException(e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { } } } } XMLChangeLogSAXParser(); int getPriority(); static String getSchemaVersion(); static String getDatabaseChangeLogNameSpace(); boolean supports(String changeLogFile, ResourceAccessor resourceAccessor); DatabaseChangeLog parse(String physicalChangeLogLocation, ChangeLogParameters changeLogParameters, ResourceAccessor resourceAccessor); } | XMLChangeLogSAXParser implements ChangeLogParser { public DatabaseChangeLog parse(String physicalChangeLogLocation, ChangeLogParameters changeLogParameters, ResourceAccessor resourceAccessor) throws ChangeLogParseException { InputStream inputStream = null; try { SAXParser parser = saxParserFactory.newSAXParser(); try { parser.setProperty("http: } catch (SAXNotRecognizedException e) { } catch (SAXNotSupportedException e) { } XMLReader xmlReader = parser.getXMLReader(); LiquibaseEntityResolver resolver=new LiquibaseEntityResolver(); resolver.useResoureAccessor(resourceAccessor,FilenameUtils.getFullPath(physicalChangeLogLocation)); xmlReader.setEntityResolver(resolver); xmlReader.setErrorHandler(new ErrorHandler() { public void warning(SAXParseException exception) throws SAXException { LogFactory.getLogger().warning(exception.getMessage()); throw exception; } public void error(SAXParseException exception) throws SAXException { LogFactory.getLogger().severe(exception.getMessage()); throw exception; } public void fatalError(SAXParseException exception) throws SAXException { LogFactory.getLogger().severe(exception.getMessage()); throw exception; } }); inputStream = resourceAccessor.getResourceAsStream(physicalChangeLogLocation); if (inputStream == null) { throw new ChangeLogParseException(physicalChangeLogLocation + " does not exist"); } XMLChangeLogSAXHandler contentHandler = new XMLChangeLogSAXHandler(physicalChangeLogLocation, resourceAccessor, changeLogParameters); xmlReader.setContentHandler(contentHandler); xmlReader.parse(new InputSource(inputStream)); return contentHandler.getDatabaseChangeLog(); } catch (ChangeLogParseException e) { throw e; } catch (IOException e) { throw new ChangeLogParseException("Error Reading Migration File: " + e.getMessage(), e); } catch (SAXParseException e) { throw new ChangeLogParseException("Error parsing line " + e.getLineNumber() + " column " + e.getColumnNumber() + " of " + physicalChangeLogLocation +": " + e.getMessage(), e); } catch (SAXException e) { Throwable parentCause = e.getException(); while (parentCause != null) { if (parentCause instanceof ChangeLogParseException) { throw ((ChangeLogParseException) parentCause); } parentCause = parentCause.getCause(); } String reason = e.getMessage(); String causeReason = null; if (e.getCause() != null) { causeReason = e.getCause().getMessage(); } if (reason == null) { if (causeReason != null) { reason = causeReason; } else { reason = "Unknown Reason"; } } throw new ChangeLogParseException("Invalid Migration File: " + reason, e); } catch (Exception e) { throw new ChangeLogParseException(e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { } } } } XMLChangeLogSAXParser(); int getPriority(); static String getSchemaVersion(); static String getDatabaseChangeLogNameSpace(); boolean supports(String changeLogFile, ResourceAccessor resourceAccessor); DatabaseChangeLog parse(String physicalChangeLogLocation, ChangeLogParameters changeLogParameters, ResourceAccessor resourceAccessor); } |
@Test public void multiChangeSetChangeLog() throws Exception { DatabaseChangeLog changeLog = new XMLChangeLogSAXParser().parse("liquibase/parser/core/xml/multiChangeSetChangeLog.xml", new ChangeLogParameters(), new JUnitResourceAccessor()); assertEquals("liquibase/parser/core/xml/multiChangeSetChangeLog.xml", changeLog.getLogicalFilePath()); assertEquals("liquibase/parser/core/xml/multiChangeSetChangeLog.xml", changeLog.getPhysicalFilePath()); assertEquals(0, changeLog.getPreconditions().getNestedPreconditions().size()); assertEquals(4, changeLog.getChangeSets().size()); ChangeSet changeSet = changeLog.getChangeSets().get(0); assertEquals("nvoxland", changeSet.getAuthor()); assertEquals("1", changeSet.getId()); assertEquals(1, changeSet.getChanges().size()); assertEquals("liquibase/parser/core/xml/multiChangeSetChangeLog.xml", changeSet.getFilePath()); assertNull(changeSet.getComments()); assertFalse(changeSet.shouldAlwaysRun()); assertFalse(changeSet.shouldRunOnChange()); Change change = changeSet.getChanges().get(0); assertEquals("createTable", change.getChangeMetaData().getName()); assertTrue(change instanceof CreateTableChange); changeSet = changeLog.getChangeSets().get(1); assertEquals("nvoxland", changeSet.getAuthor()); assertEquals("2", changeSet.getId()); assertEquals(2, changeSet.getChanges().size()); assertEquals("liquibase/parser/core/xml/multiChangeSetChangeLog.xml", changeSet.getFilePath()); assertEquals("Testing add column", changeSet.getComments()); assertTrue(changeSet.shouldAlwaysRun()); assertTrue(changeSet.shouldRunOnChange()); assertEquals(2, changeSet.getRollBackChanges().length); assertTrue(changeSet.getRollBackChanges()[0] instanceof RawSQLChange); assertTrue(changeSet.getRollBackChanges()[1] instanceof RawSQLChange); change = changeSet.getChanges().get(0); assertEquals("addColumn", change.getChangeMetaData().getName()); assertTrue(change instanceof AddColumnChange); change = changeSet.getChanges().get(1); assertEquals("addColumn", change.getChangeMetaData().getName()); assertTrue(change instanceof AddColumnChange); changeSet = changeLog.getChangeSets().get(2); assertEquals("bob", changeSet.getAuthor()); assertEquals("3", changeSet.getId()); assertEquals(1, changeSet.getChanges().size()); assertEquals("liquibase/parser/core/xml/multiChangeSetChangeLog.xml", changeSet.getFilePath()); assertNull(changeSet.getComments()); assertFalse(changeSet.shouldAlwaysRun()); assertFalse(changeSet.shouldRunOnChange()); change = changeSet.getChanges().get(0); assertEquals("createTable", change.getChangeMetaData().getName()); assertTrue(change instanceof CreateTableChange); changeSet = changeLog.getChangeSets().get(3); assertEquals(1, changeSet.getChanges().size()); change = changeSet.getChanges().get(0); assertTrue(change instanceof CustomChangeWrapper); CustomChangeWrapper wrapper = (CustomChangeWrapper) change; wrapper.generateStatements(null); assertTrue(wrapper.getCustomChange() instanceof ExampleCustomSqlChange); ExampleCustomSqlChange exChg = (ExampleCustomSqlChange) wrapper.getCustomChange(); assertEquals("table", exChg.getTableName()); assertEquals("column", exChg.getColumnName()); } | public DatabaseChangeLog parse(String physicalChangeLogLocation, ChangeLogParameters changeLogParameters, ResourceAccessor resourceAccessor) throws ChangeLogParseException { InputStream inputStream = null; try { SAXParser parser = saxParserFactory.newSAXParser(); try { parser.setProperty("http: } catch (SAXNotRecognizedException e) { } catch (SAXNotSupportedException e) { } XMLReader xmlReader = parser.getXMLReader(); LiquibaseEntityResolver resolver=new LiquibaseEntityResolver(); resolver.useResoureAccessor(resourceAccessor,FilenameUtils.getFullPath(physicalChangeLogLocation)); xmlReader.setEntityResolver(resolver); xmlReader.setErrorHandler(new ErrorHandler() { public void warning(SAXParseException exception) throws SAXException { LogFactory.getLogger().warning(exception.getMessage()); throw exception; } public void error(SAXParseException exception) throws SAXException { LogFactory.getLogger().severe(exception.getMessage()); throw exception; } public void fatalError(SAXParseException exception) throws SAXException { LogFactory.getLogger().severe(exception.getMessage()); throw exception; } }); inputStream = resourceAccessor.getResourceAsStream(physicalChangeLogLocation); if (inputStream == null) { throw new ChangeLogParseException(physicalChangeLogLocation + " does not exist"); } XMLChangeLogSAXHandler contentHandler = new XMLChangeLogSAXHandler(physicalChangeLogLocation, resourceAccessor, changeLogParameters); xmlReader.setContentHandler(contentHandler); xmlReader.parse(new InputSource(inputStream)); return contentHandler.getDatabaseChangeLog(); } catch (ChangeLogParseException e) { throw e; } catch (IOException e) { throw new ChangeLogParseException("Error Reading Migration File: " + e.getMessage(), e); } catch (SAXParseException e) { throw new ChangeLogParseException("Error parsing line " + e.getLineNumber() + " column " + e.getColumnNumber() + " of " + physicalChangeLogLocation +": " + e.getMessage(), e); } catch (SAXException e) { Throwable parentCause = e.getException(); while (parentCause != null) { if (parentCause instanceof ChangeLogParseException) { throw ((ChangeLogParseException) parentCause); } parentCause = parentCause.getCause(); } String reason = e.getMessage(); String causeReason = null; if (e.getCause() != null) { causeReason = e.getCause().getMessage(); } if (reason == null) { if (causeReason != null) { reason = causeReason; } else { reason = "Unknown Reason"; } } throw new ChangeLogParseException("Invalid Migration File: " + reason, e); } catch (Exception e) { throw new ChangeLogParseException(e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { } } } } | XMLChangeLogSAXParser implements ChangeLogParser { public DatabaseChangeLog parse(String physicalChangeLogLocation, ChangeLogParameters changeLogParameters, ResourceAccessor resourceAccessor) throws ChangeLogParseException { InputStream inputStream = null; try { SAXParser parser = saxParserFactory.newSAXParser(); try { parser.setProperty("http: } catch (SAXNotRecognizedException e) { } catch (SAXNotSupportedException e) { } XMLReader xmlReader = parser.getXMLReader(); LiquibaseEntityResolver resolver=new LiquibaseEntityResolver(); resolver.useResoureAccessor(resourceAccessor,FilenameUtils.getFullPath(physicalChangeLogLocation)); xmlReader.setEntityResolver(resolver); xmlReader.setErrorHandler(new ErrorHandler() { public void warning(SAXParseException exception) throws SAXException { LogFactory.getLogger().warning(exception.getMessage()); throw exception; } public void error(SAXParseException exception) throws SAXException { LogFactory.getLogger().severe(exception.getMessage()); throw exception; } public void fatalError(SAXParseException exception) throws SAXException { LogFactory.getLogger().severe(exception.getMessage()); throw exception; } }); inputStream = resourceAccessor.getResourceAsStream(physicalChangeLogLocation); if (inputStream == null) { throw new ChangeLogParseException(physicalChangeLogLocation + " does not exist"); } XMLChangeLogSAXHandler contentHandler = new XMLChangeLogSAXHandler(physicalChangeLogLocation, resourceAccessor, changeLogParameters); xmlReader.setContentHandler(contentHandler); xmlReader.parse(new InputSource(inputStream)); return contentHandler.getDatabaseChangeLog(); } catch (ChangeLogParseException e) { throw e; } catch (IOException e) { throw new ChangeLogParseException("Error Reading Migration File: " + e.getMessage(), e); } catch (SAXParseException e) { throw new ChangeLogParseException("Error parsing line " + e.getLineNumber() + " column " + e.getColumnNumber() + " of " + physicalChangeLogLocation +": " + e.getMessage(), e); } catch (SAXException e) { Throwable parentCause = e.getException(); while (parentCause != null) { if (parentCause instanceof ChangeLogParseException) { throw ((ChangeLogParseException) parentCause); } parentCause = parentCause.getCause(); } String reason = e.getMessage(); String causeReason = null; if (e.getCause() != null) { causeReason = e.getCause().getMessage(); } if (reason == null) { if (causeReason != null) { reason = causeReason; } else { reason = "Unknown Reason"; } } throw new ChangeLogParseException("Invalid Migration File: " + reason, e); } catch (Exception e) { throw new ChangeLogParseException(e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { } } } } } | XMLChangeLogSAXParser implements ChangeLogParser { public DatabaseChangeLog parse(String physicalChangeLogLocation, ChangeLogParameters changeLogParameters, ResourceAccessor resourceAccessor) throws ChangeLogParseException { InputStream inputStream = null; try { SAXParser parser = saxParserFactory.newSAXParser(); try { parser.setProperty("http: } catch (SAXNotRecognizedException e) { } catch (SAXNotSupportedException e) { } XMLReader xmlReader = parser.getXMLReader(); LiquibaseEntityResolver resolver=new LiquibaseEntityResolver(); resolver.useResoureAccessor(resourceAccessor,FilenameUtils.getFullPath(physicalChangeLogLocation)); xmlReader.setEntityResolver(resolver); xmlReader.setErrorHandler(new ErrorHandler() { public void warning(SAXParseException exception) throws SAXException { LogFactory.getLogger().warning(exception.getMessage()); throw exception; } public void error(SAXParseException exception) throws SAXException { LogFactory.getLogger().severe(exception.getMessage()); throw exception; } public void fatalError(SAXParseException exception) throws SAXException { LogFactory.getLogger().severe(exception.getMessage()); throw exception; } }); inputStream = resourceAccessor.getResourceAsStream(physicalChangeLogLocation); if (inputStream == null) { throw new ChangeLogParseException(physicalChangeLogLocation + " does not exist"); } XMLChangeLogSAXHandler contentHandler = new XMLChangeLogSAXHandler(physicalChangeLogLocation, resourceAccessor, changeLogParameters); xmlReader.setContentHandler(contentHandler); xmlReader.parse(new InputSource(inputStream)); return contentHandler.getDatabaseChangeLog(); } catch (ChangeLogParseException e) { throw e; } catch (IOException e) { throw new ChangeLogParseException("Error Reading Migration File: " + e.getMessage(), e); } catch (SAXParseException e) { throw new ChangeLogParseException("Error parsing line " + e.getLineNumber() + " column " + e.getColumnNumber() + " of " + physicalChangeLogLocation +": " + e.getMessage(), e); } catch (SAXException e) { Throwable parentCause = e.getException(); while (parentCause != null) { if (parentCause instanceof ChangeLogParseException) { throw ((ChangeLogParseException) parentCause); } parentCause = parentCause.getCause(); } String reason = e.getMessage(); String causeReason = null; if (e.getCause() != null) { causeReason = e.getCause().getMessage(); } if (reason == null) { if (causeReason != null) { reason = causeReason; } else { reason = "Unknown Reason"; } } throw new ChangeLogParseException("Invalid Migration File: " + reason, e); } catch (Exception e) { throw new ChangeLogParseException(e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { } } } } XMLChangeLogSAXParser(); } | XMLChangeLogSAXParser implements ChangeLogParser { public DatabaseChangeLog parse(String physicalChangeLogLocation, ChangeLogParameters changeLogParameters, ResourceAccessor resourceAccessor) throws ChangeLogParseException { InputStream inputStream = null; try { SAXParser parser = saxParserFactory.newSAXParser(); try { parser.setProperty("http: } catch (SAXNotRecognizedException e) { } catch (SAXNotSupportedException e) { } XMLReader xmlReader = parser.getXMLReader(); LiquibaseEntityResolver resolver=new LiquibaseEntityResolver(); resolver.useResoureAccessor(resourceAccessor,FilenameUtils.getFullPath(physicalChangeLogLocation)); xmlReader.setEntityResolver(resolver); xmlReader.setErrorHandler(new ErrorHandler() { public void warning(SAXParseException exception) throws SAXException { LogFactory.getLogger().warning(exception.getMessage()); throw exception; } public void error(SAXParseException exception) throws SAXException { LogFactory.getLogger().severe(exception.getMessage()); throw exception; } public void fatalError(SAXParseException exception) throws SAXException { LogFactory.getLogger().severe(exception.getMessage()); throw exception; } }); inputStream = resourceAccessor.getResourceAsStream(physicalChangeLogLocation); if (inputStream == null) { throw new ChangeLogParseException(physicalChangeLogLocation + " does not exist"); } XMLChangeLogSAXHandler contentHandler = new XMLChangeLogSAXHandler(physicalChangeLogLocation, resourceAccessor, changeLogParameters); xmlReader.setContentHandler(contentHandler); xmlReader.parse(new InputSource(inputStream)); return contentHandler.getDatabaseChangeLog(); } catch (ChangeLogParseException e) { throw e; } catch (IOException e) { throw new ChangeLogParseException("Error Reading Migration File: " + e.getMessage(), e); } catch (SAXParseException e) { throw new ChangeLogParseException("Error parsing line " + e.getLineNumber() + " column " + e.getColumnNumber() + " of " + physicalChangeLogLocation +": " + e.getMessage(), e); } catch (SAXException e) { Throwable parentCause = e.getException(); while (parentCause != null) { if (parentCause instanceof ChangeLogParseException) { throw ((ChangeLogParseException) parentCause); } parentCause = parentCause.getCause(); } String reason = e.getMessage(); String causeReason = null; if (e.getCause() != null) { causeReason = e.getCause().getMessage(); } if (reason == null) { if (causeReason != null) { reason = causeReason; } else { reason = "Unknown Reason"; } } throw new ChangeLogParseException("Invalid Migration File: " + reason, e); } catch (Exception e) { throw new ChangeLogParseException(e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { } } } } XMLChangeLogSAXParser(); int getPriority(); static String getSchemaVersion(); static String getDatabaseChangeLogNameSpace(); boolean supports(String changeLogFile, ResourceAccessor resourceAccessor); DatabaseChangeLog parse(String physicalChangeLogLocation, ChangeLogParameters changeLogParameters, ResourceAccessor resourceAccessor); } | XMLChangeLogSAXParser implements ChangeLogParser { public DatabaseChangeLog parse(String physicalChangeLogLocation, ChangeLogParameters changeLogParameters, ResourceAccessor resourceAccessor) throws ChangeLogParseException { InputStream inputStream = null; try { SAXParser parser = saxParserFactory.newSAXParser(); try { parser.setProperty("http: } catch (SAXNotRecognizedException e) { } catch (SAXNotSupportedException e) { } XMLReader xmlReader = parser.getXMLReader(); LiquibaseEntityResolver resolver=new LiquibaseEntityResolver(); resolver.useResoureAccessor(resourceAccessor,FilenameUtils.getFullPath(physicalChangeLogLocation)); xmlReader.setEntityResolver(resolver); xmlReader.setErrorHandler(new ErrorHandler() { public void warning(SAXParseException exception) throws SAXException { LogFactory.getLogger().warning(exception.getMessage()); throw exception; } public void error(SAXParseException exception) throws SAXException { LogFactory.getLogger().severe(exception.getMessage()); throw exception; } public void fatalError(SAXParseException exception) throws SAXException { LogFactory.getLogger().severe(exception.getMessage()); throw exception; } }); inputStream = resourceAccessor.getResourceAsStream(physicalChangeLogLocation); if (inputStream == null) { throw new ChangeLogParseException(physicalChangeLogLocation + " does not exist"); } XMLChangeLogSAXHandler contentHandler = new XMLChangeLogSAXHandler(physicalChangeLogLocation, resourceAccessor, changeLogParameters); xmlReader.setContentHandler(contentHandler); xmlReader.parse(new InputSource(inputStream)); return contentHandler.getDatabaseChangeLog(); } catch (ChangeLogParseException e) { throw e; } catch (IOException e) { throw new ChangeLogParseException("Error Reading Migration File: " + e.getMessage(), e); } catch (SAXParseException e) { throw new ChangeLogParseException("Error parsing line " + e.getLineNumber() + " column " + e.getColumnNumber() + " of " + physicalChangeLogLocation +": " + e.getMessage(), e); } catch (SAXException e) { Throwable parentCause = e.getException(); while (parentCause != null) { if (parentCause instanceof ChangeLogParseException) { throw ((ChangeLogParseException) parentCause); } parentCause = parentCause.getCause(); } String reason = e.getMessage(); String causeReason = null; if (e.getCause() != null) { causeReason = e.getCause().getMessage(); } if (reason == null) { if (causeReason != null) { reason = causeReason; } else { reason = "Unknown Reason"; } } throw new ChangeLogParseException("Invalid Migration File: " + reason, e); } catch (Exception e) { throw new ChangeLogParseException(e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { } } } } XMLChangeLogSAXParser(); int getPriority(); static String getSchemaVersion(); static String getDatabaseChangeLogNameSpace(); boolean supports(String changeLogFile, ResourceAccessor resourceAccessor); DatabaseChangeLog parse(String physicalChangeLogLocation, ChangeLogParameters changeLogParameters, ResourceAccessor resourceAccessor); } |
@Test public void logicalPathChangeLog() throws Exception { DatabaseChangeLog changeLog = new XMLChangeLogSAXParser().parse("liquibase/parser/core/xml/logicalPathChangeLog.xml", new ChangeLogParameters(), new JUnitResourceAccessor()); assertEquals("liquibase/parser-logical/xml/logicalPathChangeLog.xml", changeLog.getLogicalFilePath()); assertEquals("liquibase/parser/core/xml/logicalPathChangeLog.xml", changeLog.getPhysicalFilePath()); assertEquals(0, changeLog.getPreconditions().getNestedPreconditions().size()); assertEquals(1, changeLog.getChangeSets().size()); assertEquals("liquibase/parser-logical/xml/logicalPathChangeLog.xml", changeLog.getChangeSets().get(0).getFilePath()); } | public DatabaseChangeLog parse(String physicalChangeLogLocation, ChangeLogParameters changeLogParameters, ResourceAccessor resourceAccessor) throws ChangeLogParseException { InputStream inputStream = null; try { SAXParser parser = saxParserFactory.newSAXParser(); try { parser.setProperty("http: } catch (SAXNotRecognizedException e) { } catch (SAXNotSupportedException e) { } XMLReader xmlReader = parser.getXMLReader(); LiquibaseEntityResolver resolver=new LiquibaseEntityResolver(); resolver.useResoureAccessor(resourceAccessor,FilenameUtils.getFullPath(physicalChangeLogLocation)); xmlReader.setEntityResolver(resolver); xmlReader.setErrorHandler(new ErrorHandler() { public void warning(SAXParseException exception) throws SAXException { LogFactory.getLogger().warning(exception.getMessage()); throw exception; } public void error(SAXParseException exception) throws SAXException { LogFactory.getLogger().severe(exception.getMessage()); throw exception; } public void fatalError(SAXParseException exception) throws SAXException { LogFactory.getLogger().severe(exception.getMessage()); throw exception; } }); inputStream = resourceAccessor.getResourceAsStream(physicalChangeLogLocation); if (inputStream == null) { throw new ChangeLogParseException(physicalChangeLogLocation + " does not exist"); } XMLChangeLogSAXHandler contentHandler = new XMLChangeLogSAXHandler(physicalChangeLogLocation, resourceAccessor, changeLogParameters); xmlReader.setContentHandler(contentHandler); xmlReader.parse(new InputSource(inputStream)); return contentHandler.getDatabaseChangeLog(); } catch (ChangeLogParseException e) { throw e; } catch (IOException e) { throw new ChangeLogParseException("Error Reading Migration File: " + e.getMessage(), e); } catch (SAXParseException e) { throw new ChangeLogParseException("Error parsing line " + e.getLineNumber() + " column " + e.getColumnNumber() + " of " + physicalChangeLogLocation +": " + e.getMessage(), e); } catch (SAXException e) { Throwable parentCause = e.getException(); while (parentCause != null) { if (parentCause instanceof ChangeLogParseException) { throw ((ChangeLogParseException) parentCause); } parentCause = parentCause.getCause(); } String reason = e.getMessage(); String causeReason = null; if (e.getCause() != null) { causeReason = e.getCause().getMessage(); } if (reason == null) { if (causeReason != null) { reason = causeReason; } else { reason = "Unknown Reason"; } } throw new ChangeLogParseException("Invalid Migration File: " + reason, e); } catch (Exception e) { throw new ChangeLogParseException(e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { } } } } | XMLChangeLogSAXParser implements ChangeLogParser { public DatabaseChangeLog parse(String physicalChangeLogLocation, ChangeLogParameters changeLogParameters, ResourceAccessor resourceAccessor) throws ChangeLogParseException { InputStream inputStream = null; try { SAXParser parser = saxParserFactory.newSAXParser(); try { parser.setProperty("http: } catch (SAXNotRecognizedException e) { } catch (SAXNotSupportedException e) { } XMLReader xmlReader = parser.getXMLReader(); LiquibaseEntityResolver resolver=new LiquibaseEntityResolver(); resolver.useResoureAccessor(resourceAccessor,FilenameUtils.getFullPath(physicalChangeLogLocation)); xmlReader.setEntityResolver(resolver); xmlReader.setErrorHandler(new ErrorHandler() { public void warning(SAXParseException exception) throws SAXException { LogFactory.getLogger().warning(exception.getMessage()); throw exception; } public void error(SAXParseException exception) throws SAXException { LogFactory.getLogger().severe(exception.getMessage()); throw exception; } public void fatalError(SAXParseException exception) throws SAXException { LogFactory.getLogger().severe(exception.getMessage()); throw exception; } }); inputStream = resourceAccessor.getResourceAsStream(physicalChangeLogLocation); if (inputStream == null) { throw new ChangeLogParseException(physicalChangeLogLocation + " does not exist"); } XMLChangeLogSAXHandler contentHandler = new XMLChangeLogSAXHandler(physicalChangeLogLocation, resourceAccessor, changeLogParameters); xmlReader.setContentHandler(contentHandler); xmlReader.parse(new InputSource(inputStream)); return contentHandler.getDatabaseChangeLog(); } catch (ChangeLogParseException e) { throw e; } catch (IOException e) { throw new ChangeLogParseException("Error Reading Migration File: " + e.getMessage(), e); } catch (SAXParseException e) { throw new ChangeLogParseException("Error parsing line " + e.getLineNumber() + " column " + e.getColumnNumber() + " of " + physicalChangeLogLocation +": " + e.getMessage(), e); } catch (SAXException e) { Throwable parentCause = e.getException(); while (parentCause != null) { if (parentCause instanceof ChangeLogParseException) { throw ((ChangeLogParseException) parentCause); } parentCause = parentCause.getCause(); } String reason = e.getMessage(); String causeReason = null; if (e.getCause() != null) { causeReason = e.getCause().getMessage(); } if (reason == null) { if (causeReason != null) { reason = causeReason; } else { reason = "Unknown Reason"; } } throw new ChangeLogParseException("Invalid Migration File: " + reason, e); } catch (Exception e) { throw new ChangeLogParseException(e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { } } } } } | XMLChangeLogSAXParser implements ChangeLogParser { public DatabaseChangeLog parse(String physicalChangeLogLocation, ChangeLogParameters changeLogParameters, ResourceAccessor resourceAccessor) throws ChangeLogParseException { InputStream inputStream = null; try { SAXParser parser = saxParserFactory.newSAXParser(); try { parser.setProperty("http: } catch (SAXNotRecognizedException e) { } catch (SAXNotSupportedException e) { } XMLReader xmlReader = parser.getXMLReader(); LiquibaseEntityResolver resolver=new LiquibaseEntityResolver(); resolver.useResoureAccessor(resourceAccessor,FilenameUtils.getFullPath(physicalChangeLogLocation)); xmlReader.setEntityResolver(resolver); xmlReader.setErrorHandler(new ErrorHandler() { public void warning(SAXParseException exception) throws SAXException { LogFactory.getLogger().warning(exception.getMessage()); throw exception; } public void error(SAXParseException exception) throws SAXException { LogFactory.getLogger().severe(exception.getMessage()); throw exception; } public void fatalError(SAXParseException exception) throws SAXException { LogFactory.getLogger().severe(exception.getMessage()); throw exception; } }); inputStream = resourceAccessor.getResourceAsStream(physicalChangeLogLocation); if (inputStream == null) { throw new ChangeLogParseException(physicalChangeLogLocation + " does not exist"); } XMLChangeLogSAXHandler contentHandler = new XMLChangeLogSAXHandler(physicalChangeLogLocation, resourceAccessor, changeLogParameters); xmlReader.setContentHandler(contentHandler); xmlReader.parse(new InputSource(inputStream)); return contentHandler.getDatabaseChangeLog(); } catch (ChangeLogParseException e) { throw e; } catch (IOException e) { throw new ChangeLogParseException("Error Reading Migration File: " + e.getMessage(), e); } catch (SAXParseException e) { throw new ChangeLogParseException("Error parsing line " + e.getLineNumber() + " column " + e.getColumnNumber() + " of " + physicalChangeLogLocation +": " + e.getMessage(), e); } catch (SAXException e) { Throwable parentCause = e.getException(); while (parentCause != null) { if (parentCause instanceof ChangeLogParseException) { throw ((ChangeLogParseException) parentCause); } parentCause = parentCause.getCause(); } String reason = e.getMessage(); String causeReason = null; if (e.getCause() != null) { causeReason = e.getCause().getMessage(); } if (reason == null) { if (causeReason != null) { reason = causeReason; } else { reason = "Unknown Reason"; } } throw new ChangeLogParseException("Invalid Migration File: " + reason, e); } catch (Exception e) { throw new ChangeLogParseException(e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { } } } } XMLChangeLogSAXParser(); } | XMLChangeLogSAXParser implements ChangeLogParser { public DatabaseChangeLog parse(String physicalChangeLogLocation, ChangeLogParameters changeLogParameters, ResourceAccessor resourceAccessor) throws ChangeLogParseException { InputStream inputStream = null; try { SAXParser parser = saxParserFactory.newSAXParser(); try { parser.setProperty("http: } catch (SAXNotRecognizedException e) { } catch (SAXNotSupportedException e) { } XMLReader xmlReader = parser.getXMLReader(); LiquibaseEntityResolver resolver=new LiquibaseEntityResolver(); resolver.useResoureAccessor(resourceAccessor,FilenameUtils.getFullPath(physicalChangeLogLocation)); xmlReader.setEntityResolver(resolver); xmlReader.setErrorHandler(new ErrorHandler() { public void warning(SAXParseException exception) throws SAXException { LogFactory.getLogger().warning(exception.getMessage()); throw exception; } public void error(SAXParseException exception) throws SAXException { LogFactory.getLogger().severe(exception.getMessage()); throw exception; } public void fatalError(SAXParseException exception) throws SAXException { LogFactory.getLogger().severe(exception.getMessage()); throw exception; } }); inputStream = resourceAccessor.getResourceAsStream(physicalChangeLogLocation); if (inputStream == null) { throw new ChangeLogParseException(physicalChangeLogLocation + " does not exist"); } XMLChangeLogSAXHandler contentHandler = new XMLChangeLogSAXHandler(physicalChangeLogLocation, resourceAccessor, changeLogParameters); xmlReader.setContentHandler(contentHandler); xmlReader.parse(new InputSource(inputStream)); return contentHandler.getDatabaseChangeLog(); } catch (ChangeLogParseException e) { throw e; } catch (IOException e) { throw new ChangeLogParseException("Error Reading Migration File: " + e.getMessage(), e); } catch (SAXParseException e) { throw new ChangeLogParseException("Error parsing line " + e.getLineNumber() + " column " + e.getColumnNumber() + " of " + physicalChangeLogLocation +": " + e.getMessage(), e); } catch (SAXException e) { Throwable parentCause = e.getException(); while (parentCause != null) { if (parentCause instanceof ChangeLogParseException) { throw ((ChangeLogParseException) parentCause); } parentCause = parentCause.getCause(); } String reason = e.getMessage(); String causeReason = null; if (e.getCause() != null) { causeReason = e.getCause().getMessage(); } if (reason == null) { if (causeReason != null) { reason = causeReason; } else { reason = "Unknown Reason"; } } throw new ChangeLogParseException("Invalid Migration File: " + reason, e); } catch (Exception e) { throw new ChangeLogParseException(e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { } } } } XMLChangeLogSAXParser(); int getPriority(); static String getSchemaVersion(); static String getDatabaseChangeLogNameSpace(); boolean supports(String changeLogFile, ResourceAccessor resourceAccessor); DatabaseChangeLog parse(String physicalChangeLogLocation, ChangeLogParameters changeLogParameters, ResourceAccessor resourceAccessor); } | XMLChangeLogSAXParser implements ChangeLogParser { public DatabaseChangeLog parse(String physicalChangeLogLocation, ChangeLogParameters changeLogParameters, ResourceAccessor resourceAccessor) throws ChangeLogParseException { InputStream inputStream = null; try { SAXParser parser = saxParserFactory.newSAXParser(); try { parser.setProperty("http: } catch (SAXNotRecognizedException e) { } catch (SAXNotSupportedException e) { } XMLReader xmlReader = parser.getXMLReader(); LiquibaseEntityResolver resolver=new LiquibaseEntityResolver(); resolver.useResoureAccessor(resourceAccessor,FilenameUtils.getFullPath(physicalChangeLogLocation)); xmlReader.setEntityResolver(resolver); xmlReader.setErrorHandler(new ErrorHandler() { public void warning(SAXParseException exception) throws SAXException { LogFactory.getLogger().warning(exception.getMessage()); throw exception; } public void error(SAXParseException exception) throws SAXException { LogFactory.getLogger().severe(exception.getMessage()); throw exception; } public void fatalError(SAXParseException exception) throws SAXException { LogFactory.getLogger().severe(exception.getMessage()); throw exception; } }); inputStream = resourceAccessor.getResourceAsStream(physicalChangeLogLocation); if (inputStream == null) { throw new ChangeLogParseException(physicalChangeLogLocation + " does not exist"); } XMLChangeLogSAXHandler contentHandler = new XMLChangeLogSAXHandler(physicalChangeLogLocation, resourceAccessor, changeLogParameters); xmlReader.setContentHandler(contentHandler); xmlReader.parse(new InputSource(inputStream)); return contentHandler.getDatabaseChangeLog(); } catch (ChangeLogParseException e) { throw e; } catch (IOException e) { throw new ChangeLogParseException("Error Reading Migration File: " + e.getMessage(), e); } catch (SAXParseException e) { throw new ChangeLogParseException("Error parsing line " + e.getLineNumber() + " column " + e.getColumnNumber() + " of " + physicalChangeLogLocation +": " + e.getMessage(), e); } catch (SAXException e) { Throwable parentCause = e.getException(); while (parentCause != null) { if (parentCause instanceof ChangeLogParseException) { throw ((ChangeLogParseException) parentCause); } parentCause = parentCause.getCause(); } String reason = e.getMessage(); String causeReason = null; if (e.getCause() != null) { causeReason = e.getCause().getMessage(); } if (reason == null) { if (causeReason != null) { reason = causeReason; } else { reason = "Unknown Reason"; } } throw new ChangeLogParseException("Invalid Migration File: " + reason, e); } catch (Exception e) { throw new ChangeLogParseException(e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { } } } } XMLChangeLogSAXParser(); int getPriority(); static String getSchemaVersion(); static String getDatabaseChangeLogNameSpace(); boolean supports(String changeLogFile, ResourceAccessor resourceAccessor); DatabaseChangeLog parse(String physicalChangeLogLocation, ChangeLogParameters changeLogParameters, ResourceAccessor resourceAccessor); } |
@Test public void preconditionsChangeLog() throws Exception { DatabaseChangeLog changeLog = new XMLChangeLogSAXParser().parse("liquibase/parser/core/xml/preconditionsChangeLog.xml", new ChangeLogParameters(), new JUnitResourceAccessor()); assertEquals("liquibase/parser/core/xml/preconditionsChangeLog.xml", changeLog.getLogicalFilePath()); assertEquals("liquibase/parser/core/xml/preconditionsChangeLog.xml", changeLog.getPhysicalFilePath()); assertNotNull(changeLog.getPreconditions()); assertEquals(2, changeLog.getPreconditions().getNestedPreconditions().size()); assertEquals("runningAs", changeLog.getPreconditions().getNestedPreconditions().get(0).getName()); assertEquals("or", changeLog.getPreconditions().getNestedPreconditions().get(1).getName()); assertEquals("dbms", ((OrPrecondition) changeLog.getPreconditions().getNestedPreconditions().get(1)).getNestedPreconditions().get(0).getName()); assertEquals("dbms", ((OrPrecondition) changeLog.getPreconditions().getNestedPreconditions().get(1)).getNestedPreconditions().get(1).getName()); assertEquals(1, changeLog.getChangeSets().size()); } | public DatabaseChangeLog parse(String physicalChangeLogLocation, ChangeLogParameters changeLogParameters, ResourceAccessor resourceAccessor) throws ChangeLogParseException { InputStream inputStream = null; try { SAXParser parser = saxParserFactory.newSAXParser(); try { parser.setProperty("http: } catch (SAXNotRecognizedException e) { } catch (SAXNotSupportedException e) { } XMLReader xmlReader = parser.getXMLReader(); LiquibaseEntityResolver resolver=new LiquibaseEntityResolver(); resolver.useResoureAccessor(resourceAccessor,FilenameUtils.getFullPath(physicalChangeLogLocation)); xmlReader.setEntityResolver(resolver); xmlReader.setErrorHandler(new ErrorHandler() { public void warning(SAXParseException exception) throws SAXException { LogFactory.getLogger().warning(exception.getMessage()); throw exception; } public void error(SAXParseException exception) throws SAXException { LogFactory.getLogger().severe(exception.getMessage()); throw exception; } public void fatalError(SAXParseException exception) throws SAXException { LogFactory.getLogger().severe(exception.getMessage()); throw exception; } }); inputStream = resourceAccessor.getResourceAsStream(physicalChangeLogLocation); if (inputStream == null) { throw new ChangeLogParseException(physicalChangeLogLocation + " does not exist"); } XMLChangeLogSAXHandler contentHandler = new XMLChangeLogSAXHandler(physicalChangeLogLocation, resourceAccessor, changeLogParameters); xmlReader.setContentHandler(contentHandler); xmlReader.parse(new InputSource(inputStream)); return contentHandler.getDatabaseChangeLog(); } catch (ChangeLogParseException e) { throw e; } catch (IOException e) { throw new ChangeLogParseException("Error Reading Migration File: " + e.getMessage(), e); } catch (SAXParseException e) { throw new ChangeLogParseException("Error parsing line " + e.getLineNumber() + " column " + e.getColumnNumber() + " of " + physicalChangeLogLocation +": " + e.getMessage(), e); } catch (SAXException e) { Throwable parentCause = e.getException(); while (parentCause != null) { if (parentCause instanceof ChangeLogParseException) { throw ((ChangeLogParseException) parentCause); } parentCause = parentCause.getCause(); } String reason = e.getMessage(); String causeReason = null; if (e.getCause() != null) { causeReason = e.getCause().getMessage(); } if (reason == null) { if (causeReason != null) { reason = causeReason; } else { reason = "Unknown Reason"; } } throw new ChangeLogParseException("Invalid Migration File: " + reason, e); } catch (Exception e) { throw new ChangeLogParseException(e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { } } } } | XMLChangeLogSAXParser implements ChangeLogParser { public DatabaseChangeLog parse(String physicalChangeLogLocation, ChangeLogParameters changeLogParameters, ResourceAccessor resourceAccessor) throws ChangeLogParseException { InputStream inputStream = null; try { SAXParser parser = saxParserFactory.newSAXParser(); try { parser.setProperty("http: } catch (SAXNotRecognizedException e) { } catch (SAXNotSupportedException e) { } XMLReader xmlReader = parser.getXMLReader(); LiquibaseEntityResolver resolver=new LiquibaseEntityResolver(); resolver.useResoureAccessor(resourceAccessor,FilenameUtils.getFullPath(physicalChangeLogLocation)); xmlReader.setEntityResolver(resolver); xmlReader.setErrorHandler(new ErrorHandler() { public void warning(SAXParseException exception) throws SAXException { LogFactory.getLogger().warning(exception.getMessage()); throw exception; } public void error(SAXParseException exception) throws SAXException { LogFactory.getLogger().severe(exception.getMessage()); throw exception; } public void fatalError(SAXParseException exception) throws SAXException { LogFactory.getLogger().severe(exception.getMessage()); throw exception; } }); inputStream = resourceAccessor.getResourceAsStream(physicalChangeLogLocation); if (inputStream == null) { throw new ChangeLogParseException(physicalChangeLogLocation + " does not exist"); } XMLChangeLogSAXHandler contentHandler = new XMLChangeLogSAXHandler(physicalChangeLogLocation, resourceAccessor, changeLogParameters); xmlReader.setContentHandler(contentHandler); xmlReader.parse(new InputSource(inputStream)); return contentHandler.getDatabaseChangeLog(); } catch (ChangeLogParseException e) { throw e; } catch (IOException e) { throw new ChangeLogParseException("Error Reading Migration File: " + e.getMessage(), e); } catch (SAXParseException e) { throw new ChangeLogParseException("Error parsing line " + e.getLineNumber() + " column " + e.getColumnNumber() + " of " + physicalChangeLogLocation +": " + e.getMessage(), e); } catch (SAXException e) { Throwable parentCause = e.getException(); while (parentCause != null) { if (parentCause instanceof ChangeLogParseException) { throw ((ChangeLogParseException) parentCause); } parentCause = parentCause.getCause(); } String reason = e.getMessage(); String causeReason = null; if (e.getCause() != null) { causeReason = e.getCause().getMessage(); } if (reason == null) { if (causeReason != null) { reason = causeReason; } else { reason = "Unknown Reason"; } } throw new ChangeLogParseException("Invalid Migration File: " + reason, e); } catch (Exception e) { throw new ChangeLogParseException(e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { } } } } } | XMLChangeLogSAXParser implements ChangeLogParser { public DatabaseChangeLog parse(String physicalChangeLogLocation, ChangeLogParameters changeLogParameters, ResourceAccessor resourceAccessor) throws ChangeLogParseException { InputStream inputStream = null; try { SAXParser parser = saxParserFactory.newSAXParser(); try { parser.setProperty("http: } catch (SAXNotRecognizedException e) { } catch (SAXNotSupportedException e) { } XMLReader xmlReader = parser.getXMLReader(); LiquibaseEntityResolver resolver=new LiquibaseEntityResolver(); resolver.useResoureAccessor(resourceAccessor,FilenameUtils.getFullPath(physicalChangeLogLocation)); xmlReader.setEntityResolver(resolver); xmlReader.setErrorHandler(new ErrorHandler() { public void warning(SAXParseException exception) throws SAXException { LogFactory.getLogger().warning(exception.getMessage()); throw exception; } public void error(SAXParseException exception) throws SAXException { LogFactory.getLogger().severe(exception.getMessage()); throw exception; } public void fatalError(SAXParseException exception) throws SAXException { LogFactory.getLogger().severe(exception.getMessage()); throw exception; } }); inputStream = resourceAccessor.getResourceAsStream(physicalChangeLogLocation); if (inputStream == null) { throw new ChangeLogParseException(physicalChangeLogLocation + " does not exist"); } XMLChangeLogSAXHandler contentHandler = new XMLChangeLogSAXHandler(physicalChangeLogLocation, resourceAccessor, changeLogParameters); xmlReader.setContentHandler(contentHandler); xmlReader.parse(new InputSource(inputStream)); return contentHandler.getDatabaseChangeLog(); } catch (ChangeLogParseException e) { throw e; } catch (IOException e) { throw new ChangeLogParseException("Error Reading Migration File: " + e.getMessage(), e); } catch (SAXParseException e) { throw new ChangeLogParseException("Error parsing line " + e.getLineNumber() + " column " + e.getColumnNumber() + " of " + physicalChangeLogLocation +": " + e.getMessage(), e); } catch (SAXException e) { Throwable parentCause = e.getException(); while (parentCause != null) { if (parentCause instanceof ChangeLogParseException) { throw ((ChangeLogParseException) parentCause); } parentCause = parentCause.getCause(); } String reason = e.getMessage(); String causeReason = null; if (e.getCause() != null) { causeReason = e.getCause().getMessage(); } if (reason == null) { if (causeReason != null) { reason = causeReason; } else { reason = "Unknown Reason"; } } throw new ChangeLogParseException("Invalid Migration File: " + reason, e); } catch (Exception e) { throw new ChangeLogParseException(e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { } } } } XMLChangeLogSAXParser(); } | XMLChangeLogSAXParser implements ChangeLogParser { public DatabaseChangeLog parse(String physicalChangeLogLocation, ChangeLogParameters changeLogParameters, ResourceAccessor resourceAccessor) throws ChangeLogParseException { InputStream inputStream = null; try { SAXParser parser = saxParserFactory.newSAXParser(); try { parser.setProperty("http: } catch (SAXNotRecognizedException e) { } catch (SAXNotSupportedException e) { } XMLReader xmlReader = parser.getXMLReader(); LiquibaseEntityResolver resolver=new LiquibaseEntityResolver(); resolver.useResoureAccessor(resourceAccessor,FilenameUtils.getFullPath(physicalChangeLogLocation)); xmlReader.setEntityResolver(resolver); xmlReader.setErrorHandler(new ErrorHandler() { public void warning(SAXParseException exception) throws SAXException { LogFactory.getLogger().warning(exception.getMessage()); throw exception; } public void error(SAXParseException exception) throws SAXException { LogFactory.getLogger().severe(exception.getMessage()); throw exception; } public void fatalError(SAXParseException exception) throws SAXException { LogFactory.getLogger().severe(exception.getMessage()); throw exception; } }); inputStream = resourceAccessor.getResourceAsStream(physicalChangeLogLocation); if (inputStream == null) { throw new ChangeLogParseException(physicalChangeLogLocation + " does not exist"); } XMLChangeLogSAXHandler contentHandler = new XMLChangeLogSAXHandler(physicalChangeLogLocation, resourceAccessor, changeLogParameters); xmlReader.setContentHandler(contentHandler); xmlReader.parse(new InputSource(inputStream)); return contentHandler.getDatabaseChangeLog(); } catch (ChangeLogParseException e) { throw e; } catch (IOException e) { throw new ChangeLogParseException("Error Reading Migration File: " + e.getMessage(), e); } catch (SAXParseException e) { throw new ChangeLogParseException("Error parsing line " + e.getLineNumber() + " column " + e.getColumnNumber() + " of " + physicalChangeLogLocation +": " + e.getMessage(), e); } catch (SAXException e) { Throwable parentCause = e.getException(); while (parentCause != null) { if (parentCause instanceof ChangeLogParseException) { throw ((ChangeLogParseException) parentCause); } parentCause = parentCause.getCause(); } String reason = e.getMessage(); String causeReason = null; if (e.getCause() != null) { causeReason = e.getCause().getMessage(); } if (reason == null) { if (causeReason != null) { reason = causeReason; } else { reason = "Unknown Reason"; } } throw new ChangeLogParseException("Invalid Migration File: " + reason, e); } catch (Exception e) { throw new ChangeLogParseException(e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { } } } } XMLChangeLogSAXParser(); int getPriority(); static String getSchemaVersion(); static String getDatabaseChangeLogNameSpace(); boolean supports(String changeLogFile, ResourceAccessor resourceAccessor); DatabaseChangeLog parse(String physicalChangeLogLocation, ChangeLogParameters changeLogParameters, ResourceAccessor resourceAccessor); } | XMLChangeLogSAXParser implements ChangeLogParser { public DatabaseChangeLog parse(String physicalChangeLogLocation, ChangeLogParameters changeLogParameters, ResourceAccessor resourceAccessor) throws ChangeLogParseException { InputStream inputStream = null; try { SAXParser parser = saxParserFactory.newSAXParser(); try { parser.setProperty("http: } catch (SAXNotRecognizedException e) { } catch (SAXNotSupportedException e) { } XMLReader xmlReader = parser.getXMLReader(); LiquibaseEntityResolver resolver=new LiquibaseEntityResolver(); resolver.useResoureAccessor(resourceAccessor,FilenameUtils.getFullPath(physicalChangeLogLocation)); xmlReader.setEntityResolver(resolver); xmlReader.setErrorHandler(new ErrorHandler() { public void warning(SAXParseException exception) throws SAXException { LogFactory.getLogger().warning(exception.getMessage()); throw exception; } public void error(SAXParseException exception) throws SAXException { LogFactory.getLogger().severe(exception.getMessage()); throw exception; } public void fatalError(SAXParseException exception) throws SAXException { LogFactory.getLogger().severe(exception.getMessage()); throw exception; } }); inputStream = resourceAccessor.getResourceAsStream(physicalChangeLogLocation); if (inputStream == null) { throw new ChangeLogParseException(physicalChangeLogLocation + " does not exist"); } XMLChangeLogSAXHandler contentHandler = new XMLChangeLogSAXHandler(physicalChangeLogLocation, resourceAccessor, changeLogParameters); xmlReader.setContentHandler(contentHandler); xmlReader.parse(new InputSource(inputStream)); return contentHandler.getDatabaseChangeLog(); } catch (ChangeLogParseException e) { throw e; } catch (IOException e) { throw new ChangeLogParseException("Error Reading Migration File: " + e.getMessage(), e); } catch (SAXParseException e) { throw new ChangeLogParseException("Error parsing line " + e.getLineNumber() + " column " + e.getColumnNumber() + " of " + physicalChangeLogLocation +": " + e.getMessage(), e); } catch (SAXException e) { Throwable parentCause = e.getException(); while (parentCause != null) { if (parentCause instanceof ChangeLogParseException) { throw ((ChangeLogParseException) parentCause); } parentCause = parentCause.getCause(); } String reason = e.getMessage(); String causeReason = null; if (e.getCause() != null) { causeReason = e.getCause().getMessage(); } if (reason == null) { if (causeReason != null) { reason = causeReason; } else { reason = "Unknown Reason"; } } throw new ChangeLogParseException("Invalid Migration File: " + reason, e); } catch (Exception e) { throw new ChangeLogParseException(e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { } } } } XMLChangeLogSAXParser(); int getPriority(); static String getSchemaVersion(); static String getDatabaseChangeLogNameSpace(); boolean supports(String changeLogFile, ResourceAccessor resourceAccessor); DatabaseChangeLog parse(String physicalChangeLogLocation, ChangeLogParameters changeLogParameters, ResourceAccessor resourceAccessor); } |
@Test public void testNestedChangeLog() throws Exception { final String nestedFileName = "liquibase/parser/core/xml/nestedChangeLog.xml"; DatabaseChangeLog changeLog = new XMLChangeLogSAXParser().parse("liquibase/parser/core/xml/nestedChangeLog.xml", new ChangeLogParameters(), new JUnitResourceAccessor()); nestedFileAssertions(changeLog, nestedFileName); } | public DatabaseChangeLog parse(String physicalChangeLogLocation, ChangeLogParameters changeLogParameters, ResourceAccessor resourceAccessor) throws ChangeLogParseException { InputStream inputStream = null; try { SAXParser parser = saxParserFactory.newSAXParser(); try { parser.setProperty("http: } catch (SAXNotRecognizedException e) { } catch (SAXNotSupportedException e) { } XMLReader xmlReader = parser.getXMLReader(); LiquibaseEntityResolver resolver=new LiquibaseEntityResolver(); resolver.useResoureAccessor(resourceAccessor,FilenameUtils.getFullPath(physicalChangeLogLocation)); xmlReader.setEntityResolver(resolver); xmlReader.setErrorHandler(new ErrorHandler() { public void warning(SAXParseException exception) throws SAXException { LogFactory.getLogger().warning(exception.getMessage()); throw exception; } public void error(SAXParseException exception) throws SAXException { LogFactory.getLogger().severe(exception.getMessage()); throw exception; } public void fatalError(SAXParseException exception) throws SAXException { LogFactory.getLogger().severe(exception.getMessage()); throw exception; } }); inputStream = resourceAccessor.getResourceAsStream(physicalChangeLogLocation); if (inputStream == null) { throw new ChangeLogParseException(physicalChangeLogLocation + " does not exist"); } XMLChangeLogSAXHandler contentHandler = new XMLChangeLogSAXHandler(physicalChangeLogLocation, resourceAccessor, changeLogParameters); xmlReader.setContentHandler(contentHandler); xmlReader.parse(new InputSource(inputStream)); return contentHandler.getDatabaseChangeLog(); } catch (ChangeLogParseException e) { throw e; } catch (IOException e) { throw new ChangeLogParseException("Error Reading Migration File: " + e.getMessage(), e); } catch (SAXParseException e) { throw new ChangeLogParseException("Error parsing line " + e.getLineNumber() + " column " + e.getColumnNumber() + " of " + physicalChangeLogLocation +": " + e.getMessage(), e); } catch (SAXException e) { Throwable parentCause = e.getException(); while (parentCause != null) { if (parentCause instanceof ChangeLogParseException) { throw ((ChangeLogParseException) parentCause); } parentCause = parentCause.getCause(); } String reason = e.getMessage(); String causeReason = null; if (e.getCause() != null) { causeReason = e.getCause().getMessage(); } if (reason == null) { if (causeReason != null) { reason = causeReason; } else { reason = "Unknown Reason"; } } throw new ChangeLogParseException("Invalid Migration File: " + reason, e); } catch (Exception e) { throw new ChangeLogParseException(e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { } } } } | XMLChangeLogSAXParser implements ChangeLogParser { public DatabaseChangeLog parse(String physicalChangeLogLocation, ChangeLogParameters changeLogParameters, ResourceAccessor resourceAccessor) throws ChangeLogParseException { InputStream inputStream = null; try { SAXParser parser = saxParserFactory.newSAXParser(); try { parser.setProperty("http: } catch (SAXNotRecognizedException e) { } catch (SAXNotSupportedException e) { } XMLReader xmlReader = parser.getXMLReader(); LiquibaseEntityResolver resolver=new LiquibaseEntityResolver(); resolver.useResoureAccessor(resourceAccessor,FilenameUtils.getFullPath(physicalChangeLogLocation)); xmlReader.setEntityResolver(resolver); xmlReader.setErrorHandler(new ErrorHandler() { public void warning(SAXParseException exception) throws SAXException { LogFactory.getLogger().warning(exception.getMessage()); throw exception; } public void error(SAXParseException exception) throws SAXException { LogFactory.getLogger().severe(exception.getMessage()); throw exception; } public void fatalError(SAXParseException exception) throws SAXException { LogFactory.getLogger().severe(exception.getMessage()); throw exception; } }); inputStream = resourceAccessor.getResourceAsStream(physicalChangeLogLocation); if (inputStream == null) { throw new ChangeLogParseException(physicalChangeLogLocation + " does not exist"); } XMLChangeLogSAXHandler contentHandler = new XMLChangeLogSAXHandler(physicalChangeLogLocation, resourceAccessor, changeLogParameters); xmlReader.setContentHandler(contentHandler); xmlReader.parse(new InputSource(inputStream)); return contentHandler.getDatabaseChangeLog(); } catch (ChangeLogParseException e) { throw e; } catch (IOException e) { throw new ChangeLogParseException("Error Reading Migration File: " + e.getMessage(), e); } catch (SAXParseException e) { throw new ChangeLogParseException("Error parsing line " + e.getLineNumber() + " column " + e.getColumnNumber() + " of " + physicalChangeLogLocation +": " + e.getMessage(), e); } catch (SAXException e) { Throwable parentCause = e.getException(); while (parentCause != null) { if (parentCause instanceof ChangeLogParseException) { throw ((ChangeLogParseException) parentCause); } parentCause = parentCause.getCause(); } String reason = e.getMessage(); String causeReason = null; if (e.getCause() != null) { causeReason = e.getCause().getMessage(); } if (reason == null) { if (causeReason != null) { reason = causeReason; } else { reason = "Unknown Reason"; } } throw new ChangeLogParseException("Invalid Migration File: " + reason, e); } catch (Exception e) { throw new ChangeLogParseException(e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { } } } } } | XMLChangeLogSAXParser implements ChangeLogParser { public DatabaseChangeLog parse(String physicalChangeLogLocation, ChangeLogParameters changeLogParameters, ResourceAccessor resourceAccessor) throws ChangeLogParseException { InputStream inputStream = null; try { SAXParser parser = saxParserFactory.newSAXParser(); try { parser.setProperty("http: } catch (SAXNotRecognizedException e) { } catch (SAXNotSupportedException e) { } XMLReader xmlReader = parser.getXMLReader(); LiquibaseEntityResolver resolver=new LiquibaseEntityResolver(); resolver.useResoureAccessor(resourceAccessor,FilenameUtils.getFullPath(physicalChangeLogLocation)); xmlReader.setEntityResolver(resolver); xmlReader.setErrorHandler(new ErrorHandler() { public void warning(SAXParseException exception) throws SAXException { LogFactory.getLogger().warning(exception.getMessage()); throw exception; } public void error(SAXParseException exception) throws SAXException { LogFactory.getLogger().severe(exception.getMessage()); throw exception; } public void fatalError(SAXParseException exception) throws SAXException { LogFactory.getLogger().severe(exception.getMessage()); throw exception; } }); inputStream = resourceAccessor.getResourceAsStream(physicalChangeLogLocation); if (inputStream == null) { throw new ChangeLogParseException(physicalChangeLogLocation + " does not exist"); } XMLChangeLogSAXHandler contentHandler = new XMLChangeLogSAXHandler(physicalChangeLogLocation, resourceAccessor, changeLogParameters); xmlReader.setContentHandler(contentHandler); xmlReader.parse(new InputSource(inputStream)); return contentHandler.getDatabaseChangeLog(); } catch (ChangeLogParseException e) { throw e; } catch (IOException e) { throw new ChangeLogParseException("Error Reading Migration File: " + e.getMessage(), e); } catch (SAXParseException e) { throw new ChangeLogParseException("Error parsing line " + e.getLineNumber() + " column " + e.getColumnNumber() + " of " + physicalChangeLogLocation +": " + e.getMessage(), e); } catch (SAXException e) { Throwable parentCause = e.getException(); while (parentCause != null) { if (parentCause instanceof ChangeLogParseException) { throw ((ChangeLogParseException) parentCause); } parentCause = parentCause.getCause(); } String reason = e.getMessage(); String causeReason = null; if (e.getCause() != null) { causeReason = e.getCause().getMessage(); } if (reason == null) { if (causeReason != null) { reason = causeReason; } else { reason = "Unknown Reason"; } } throw new ChangeLogParseException("Invalid Migration File: " + reason, e); } catch (Exception e) { throw new ChangeLogParseException(e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { } } } } XMLChangeLogSAXParser(); } | XMLChangeLogSAXParser implements ChangeLogParser { public DatabaseChangeLog parse(String physicalChangeLogLocation, ChangeLogParameters changeLogParameters, ResourceAccessor resourceAccessor) throws ChangeLogParseException { InputStream inputStream = null; try { SAXParser parser = saxParserFactory.newSAXParser(); try { parser.setProperty("http: } catch (SAXNotRecognizedException e) { } catch (SAXNotSupportedException e) { } XMLReader xmlReader = parser.getXMLReader(); LiquibaseEntityResolver resolver=new LiquibaseEntityResolver(); resolver.useResoureAccessor(resourceAccessor,FilenameUtils.getFullPath(physicalChangeLogLocation)); xmlReader.setEntityResolver(resolver); xmlReader.setErrorHandler(new ErrorHandler() { public void warning(SAXParseException exception) throws SAXException { LogFactory.getLogger().warning(exception.getMessage()); throw exception; } public void error(SAXParseException exception) throws SAXException { LogFactory.getLogger().severe(exception.getMessage()); throw exception; } public void fatalError(SAXParseException exception) throws SAXException { LogFactory.getLogger().severe(exception.getMessage()); throw exception; } }); inputStream = resourceAccessor.getResourceAsStream(physicalChangeLogLocation); if (inputStream == null) { throw new ChangeLogParseException(physicalChangeLogLocation + " does not exist"); } XMLChangeLogSAXHandler contentHandler = new XMLChangeLogSAXHandler(physicalChangeLogLocation, resourceAccessor, changeLogParameters); xmlReader.setContentHandler(contentHandler); xmlReader.parse(new InputSource(inputStream)); return contentHandler.getDatabaseChangeLog(); } catch (ChangeLogParseException e) { throw e; } catch (IOException e) { throw new ChangeLogParseException("Error Reading Migration File: " + e.getMessage(), e); } catch (SAXParseException e) { throw new ChangeLogParseException("Error parsing line " + e.getLineNumber() + " column " + e.getColumnNumber() + " of " + physicalChangeLogLocation +": " + e.getMessage(), e); } catch (SAXException e) { Throwable parentCause = e.getException(); while (parentCause != null) { if (parentCause instanceof ChangeLogParseException) { throw ((ChangeLogParseException) parentCause); } parentCause = parentCause.getCause(); } String reason = e.getMessage(); String causeReason = null; if (e.getCause() != null) { causeReason = e.getCause().getMessage(); } if (reason == null) { if (causeReason != null) { reason = causeReason; } else { reason = "Unknown Reason"; } } throw new ChangeLogParseException("Invalid Migration File: " + reason, e); } catch (Exception e) { throw new ChangeLogParseException(e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { } } } } XMLChangeLogSAXParser(); int getPriority(); static String getSchemaVersion(); static String getDatabaseChangeLogNameSpace(); boolean supports(String changeLogFile, ResourceAccessor resourceAccessor); DatabaseChangeLog parse(String physicalChangeLogLocation, ChangeLogParameters changeLogParameters, ResourceAccessor resourceAccessor); } | XMLChangeLogSAXParser implements ChangeLogParser { public DatabaseChangeLog parse(String physicalChangeLogLocation, ChangeLogParameters changeLogParameters, ResourceAccessor resourceAccessor) throws ChangeLogParseException { InputStream inputStream = null; try { SAXParser parser = saxParserFactory.newSAXParser(); try { parser.setProperty("http: } catch (SAXNotRecognizedException e) { } catch (SAXNotSupportedException e) { } XMLReader xmlReader = parser.getXMLReader(); LiquibaseEntityResolver resolver=new LiquibaseEntityResolver(); resolver.useResoureAccessor(resourceAccessor,FilenameUtils.getFullPath(physicalChangeLogLocation)); xmlReader.setEntityResolver(resolver); xmlReader.setErrorHandler(new ErrorHandler() { public void warning(SAXParseException exception) throws SAXException { LogFactory.getLogger().warning(exception.getMessage()); throw exception; } public void error(SAXParseException exception) throws SAXException { LogFactory.getLogger().severe(exception.getMessage()); throw exception; } public void fatalError(SAXParseException exception) throws SAXException { LogFactory.getLogger().severe(exception.getMessage()); throw exception; } }); inputStream = resourceAccessor.getResourceAsStream(physicalChangeLogLocation); if (inputStream == null) { throw new ChangeLogParseException(physicalChangeLogLocation + " does not exist"); } XMLChangeLogSAXHandler contentHandler = new XMLChangeLogSAXHandler(physicalChangeLogLocation, resourceAccessor, changeLogParameters); xmlReader.setContentHandler(contentHandler); xmlReader.parse(new InputSource(inputStream)); return contentHandler.getDatabaseChangeLog(); } catch (ChangeLogParseException e) { throw e; } catch (IOException e) { throw new ChangeLogParseException("Error Reading Migration File: " + e.getMessage(), e); } catch (SAXParseException e) { throw new ChangeLogParseException("Error parsing line " + e.getLineNumber() + " column " + e.getColumnNumber() + " of " + physicalChangeLogLocation +": " + e.getMessage(), e); } catch (SAXException e) { Throwable parentCause = e.getException(); while (parentCause != null) { if (parentCause instanceof ChangeLogParseException) { throw ((ChangeLogParseException) parentCause); } parentCause = parentCause.getCause(); } String reason = e.getMessage(); String causeReason = null; if (e.getCause() != null) { causeReason = e.getCause().getMessage(); } if (reason == null) { if (causeReason != null) { reason = causeReason; } else { reason = "Unknown Reason"; } } throw new ChangeLogParseException("Invalid Migration File: " + reason, e); } catch (Exception e) { throw new ChangeLogParseException(e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { } } } } XMLChangeLogSAXParser(); int getPriority(); static String getSchemaVersion(); static String getDatabaseChangeLogNameSpace(); boolean supports(String changeLogFile, ResourceAccessor resourceAccessor); DatabaseChangeLog parse(String physicalChangeLogLocation, ChangeLogParameters changeLogParameters, ResourceAccessor resourceAccessor); } |
@Test public void nestedRelativeChangeLog() throws Exception { final String nestedFileName = "liquibase/parser/core/xml/nestedRelativeChangeLog.xml"; DatabaseChangeLog changeLog = new XMLChangeLogSAXParser().parse(nestedFileName, new ChangeLogParameters(), new JUnitResourceAccessor()); nestedFileAssertions(changeLog, nestedFileName); } | public DatabaseChangeLog parse(String physicalChangeLogLocation, ChangeLogParameters changeLogParameters, ResourceAccessor resourceAccessor) throws ChangeLogParseException { InputStream inputStream = null; try { SAXParser parser = saxParserFactory.newSAXParser(); try { parser.setProperty("http: } catch (SAXNotRecognizedException e) { } catch (SAXNotSupportedException e) { } XMLReader xmlReader = parser.getXMLReader(); LiquibaseEntityResolver resolver=new LiquibaseEntityResolver(); resolver.useResoureAccessor(resourceAccessor,FilenameUtils.getFullPath(physicalChangeLogLocation)); xmlReader.setEntityResolver(resolver); xmlReader.setErrorHandler(new ErrorHandler() { public void warning(SAXParseException exception) throws SAXException { LogFactory.getLogger().warning(exception.getMessage()); throw exception; } public void error(SAXParseException exception) throws SAXException { LogFactory.getLogger().severe(exception.getMessage()); throw exception; } public void fatalError(SAXParseException exception) throws SAXException { LogFactory.getLogger().severe(exception.getMessage()); throw exception; } }); inputStream = resourceAccessor.getResourceAsStream(physicalChangeLogLocation); if (inputStream == null) { throw new ChangeLogParseException(physicalChangeLogLocation + " does not exist"); } XMLChangeLogSAXHandler contentHandler = new XMLChangeLogSAXHandler(physicalChangeLogLocation, resourceAccessor, changeLogParameters); xmlReader.setContentHandler(contentHandler); xmlReader.parse(new InputSource(inputStream)); return contentHandler.getDatabaseChangeLog(); } catch (ChangeLogParseException e) { throw e; } catch (IOException e) { throw new ChangeLogParseException("Error Reading Migration File: " + e.getMessage(), e); } catch (SAXParseException e) { throw new ChangeLogParseException("Error parsing line " + e.getLineNumber() + " column " + e.getColumnNumber() + " of " + physicalChangeLogLocation +": " + e.getMessage(), e); } catch (SAXException e) { Throwable parentCause = e.getException(); while (parentCause != null) { if (parentCause instanceof ChangeLogParseException) { throw ((ChangeLogParseException) parentCause); } parentCause = parentCause.getCause(); } String reason = e.getMessage(); String causeReason = null; if (e.getCause() != null) { causeReason = e.getCause().getMessage(); } if (reason == null) { if (causeReason != null) { reason = causeReason; } else { reason = "Unknown Reason"; } } throw new ChangeLogParseException("Invalid Migration File: " + reason, e); } catch (Exception e) { throw new ChangeLogParseException(e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { } } } } | XMLChangeLogSAXParser implements ChangeLogParser { public DatabaseChangeLog parse(String physicalChangeLogLocation, ChangeLogParameters changeLogParameters, ResourceAccessor resourceAccessor) throws ChangeLogParseException { InputStream inputStream = null; try { SAXParser parser = saxParserFactory.newSAXParser(); try { parser.setProperty("http: } catch (SAXNotRecognizedException e) { } catch (SAXNotSupportedException e) { } XMLReader xmlReader = parser.getXMLReader(); LiquibaseEntityResolver resolver=new LiquibaseEntityResolver(); resolver.useResoureAccessor(resourceAccessor,FilenameUtils.getFullPath(physicalChangeLogLocation)); xmlReader.setEntityResolver(resolver); xmlReader.setErrorHandler(new ErrorHandler() { public void warning(SAXParseException exception) throws SAXException { LogFactory.getLogger().warning(exception.getMessage()); throw exception; } public void error(SAXParseException exception) throws SAXException { LogFactory.getLogger().severe(exception.getMessage()); throw exception; } public void fatalError(SAXParseException exception) throws SAXException { LogFactory.getLogger().severe(exception.getMessage()); throw exception; } }); inputStream = resourceAccessor.getResourceAsStream(physicalChangeLogLocation); if (inputStream == null) { throw new ChangeLogParseException(physicalChangeLogLocation + " does not exist"); } XMLChangeLogSAXHandler contentHandler = new XMLChangeLogSAXHandler(physicalChangeLogLocation, resourceAccessor, changeLogParameters); xmlReader.setContentHandler(contentHandler); xmlReader.parse(new InputSource(inputStream)); return contentHandler.getDatabaseChangeLog(); } catch (ChangeLogParseException e) { throw e; } catch (IOException e) { throw new ChangeLogParseException("Error Reading Migration File: " + e.getMessage(), e); } catch (SAXParseException e) { throw new ChangeLogParseException("Error parsing line " + e.getLineNumber() + " column " + e.getColumnNumber() + " of " + physicalChangeLogLocation +": " + e.getMessage(), e); } catch (SAXException e) { Throwable parentCause = e.getException(); while (parentCause != null) { if (parentCause instanceof ChangeLogParseException) { throw ((ChangeLogParseException) parentCause); } parentCause = parentCause.getCause(); } String reason = e.getMessage(); String causeReason = null; if (e.getCause() != null) { causeReason = e.getCause().getMessage(); } if (reason == null) { if (causeReason != null) { reason = causeReason; } else { reason = "Unknown Reason"; } } throw new ChangeLogParseException("Invalid Migration File: " + reason, e); } catch (Exception e) { throw new ChangeLogParseException(e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { } } } } } | XMLChangeLogSAXParser implements ChangeLogParser { public DatabaseChangeLog parse(String physicalChangeLogLocation, ChangeLogParameters changeLogParameters, ResourceAccessor resourceAccessor) throws ChangeLogParseException { InputStream inputStream = null; try { SAXParser parser = saxParserFactory.newSAXParser(); try { parser.setProperty("http: } catch (SAXNotRecognizedException e) { } catch (SAXNotSupportedException e) { } XMLReader xmlReader = parser.getXMLReader(); LiquibaseEntityResolver resolver=new LiquibaseEntityResolver(); resolver.useResoureAccessor(resourceAccessor,FilenameUtils.getFullPath(physicalChangeLogLocation)); xmlReader.setEntityResolver(resolver); xmlReader.setErrorHandler(new ErrorHandler() { public void warning(SAXParseException exception) throws SAXException { LogFactory.getLogger().warning(exception.getMessage()); throw exception; } public void error(SAXParseException exception) throws SAXException { LogFactory.getLogger().severe(exception.getMessage()); throw exception; } public void fatalError(SAXParseException exception) throws SAXException { LogFactory.getLogger().severe(exception.getMessage()); throw exception; } }); inputStream = resourceAccessor.getResourceAsStream(physicalChangeLogLocation); if (inputStream == null) { throw new ChangeLogParseException(physicalChangeLogLocation + " does not exist"); } XMLChangeLogSAXHandler contentHandler = new XMLChangeLogSAXHandler(physicalChangeLogLocation, resourceAccessor, changeLogParameters); xmlReader.setContentHandler(contentHandler); xmlReader.parse(new InputSource(inputStream)); return contentHandler.getDatabaseChangeLog(); } catch (ChangeLogParseException e) { throw e; } catch (IOException e) { throw new ChangeLogParseException("Error Reading Migration File: " + e.getMessage(), e); } catch (SAXParseException e) { throw new ChangeLogParseException("Error parsing line " + e.getLineNumber() + " column " + e.getColumnNumber() + " of " + physicalChangeLogLocation +": " + e.getMessage(), e); } catch (SAXException e) { Throwable parentCause = e.getException(); while (parentCause != null) { if (parentCause instanceof ChangeLogParseException) { throw ((ChangeLogParseException) parentCause); } parentCause = parentCause.getCause(); } String reason = e.getMessage(); String causeReason = null; if (e.getCause() != null) { causeReason = e.getCause().getMessage(); } if (reason == null) { if (causeReason != null) { reason = causeReason; } else { reason = "Unknown Reason"; } } throw new ChangeLogParseException("Invalid Migration File: " + reason, e); } catch (Exception e) { throw new ChangeLogParseException(e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { } } } } XMLChangeLogSAXParser(); } | XMLChangeLogSAXParser implements ChangeLogParser { public DatabaseChangeLog parse(String physicalChangeLogLocation, ChangeLogParameters changeLogParameters, ResourceAccessor resourceAccessor) throws ChangeLogParseException { InputStream inputStream = null; try { SAXParser parser = saxParserFactory.newSAXParser(); try { parser.setProperty("http: } catch (SAXNotRecognizedException e) { } catch (SAXNotSupportedException e) { } XMLReader xmlReader = parser.getXMLReader(); LiquibaseEntityResolver resolver=new LiquibaseEntityResolver(); resolver.useResoureAccessor(resourceAccessor,FilenameUtils.getFullPath(physicalChangeLogLocation)); xmlReader.setEntityResolver(resolver); xmlReader.setErrorHandler(new ErrorHandler() { public void warning(SAXParseException exception) throws SAXException { LogFactory.getLogger().warning(exception.getMessage()); throw exception; } public void error(SAXParseException exception) throws SAXException { LogFactory.getLogger().severe(exception.getMessage()); throw exception; } public void fatalError(SAXParseException exception) throws SAXException { LogFactory.getLogger().severe(exception.getMessage()); throw exception; } }); inputStream = resourceAccessor.getResourceAsStream(physicalChangeLogLocation); if (inputStream == null) { throw new ChangeLogParseException(physicalChangeLogLocation + " does not exist"); } XMLChangeLogSAXHandler contentHandler = new XMLChangeLogSAXHandler(physicalChangeLogLocation, resourceAccessor, changeLogParameters); xmlReader.setContentHandler(contentHandler); xmlReader.parse(new InputSource(inputStream)); return contentHandler.getDatabaseChangeLog(); } catch (ChangeLogParseException e) { throw e; } catch (IOException e) { throw new ChangeLogParseException("Error Reading Migration File: " + e.getMessage(), e); } catch (SAXParseException e) { throw new ChangeLogParseException("Error parsing line " + e.getLineNumber() + " column " + e.getColumnNumber() + " of " + physicalChangeLogLocation +": " + e.getMessage(), e); } catch (SAXException e) { Throwable parentCause = e.getException(); while (parentCause != null) { if (parentCause instanceof ChangeLogParseException) { throw ((ChangeLogParseException) parentCause); } parentCause = parentCause.getCause(); } String reason = e.getMessage(); String causeReason = null; if (e.getCause() != null) { causeReason = e.getCause().getMessage(); } if (reason == null) { if (causeReason != null) { reason = causeReason; } else { reason = "Unknown Reason"; } } throw new ChangeLogParseException("Invalid Migration File: " + reason, e); } catch (Exception e) { throw new ChangeLogParseException(e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { } } } } XMLChangeLogSAXParser(); int getPriority(); static String getSchemaVersion(); static String getDatabaseChangeLogNameSpace(); boolean supports(String changeLogFile, ResourceAccessor resourceAccessor); DatabaseChangeLog parse(String physicalChangeLogLocation, ChangeLogParameters changeLogParameters, ResourceAccessor resourceAccessor); } | XMLChangeLogSAXParser implements ChangeLogParser { public DatabaseChangeLog parse(String physicalChangeLogLocation, ChangeLogParameters changeLogParameters, ResourceAccessor resourceAccessor) throws ChangeLogParseException { InputStream inputStream = null; try { SAXParser parser = saxParserFactory.newSAXParser(); try { parser.setProperty("http: } catch (SAXNotRecognizedException e) { } catch (SAXNotSupportedException e) { } XMLReader xmlReader = parser.getXMLReader(); LiquibaseEntityResolver resolver=new LiquibaseEntityResolver(); resolver.useResoureAccessor(resourceAccessor,FilenameUtils.getFullPath(physicalChangeLogLocation)); xmlReader.setEntityResolver(resolver); xmlReader.setErrorHandler(new ErrorHandler() { public void warning(SAXParseException exception) throws SAXException { LogFactory.getLogger().warning(exception.getMessage()); throw exception; } public void error(SAXParseException exception) throws SAXException { LogFactory.getLogger().severe(exception.getMessage()); throw exception; } public void fatalError(SAXParseException exception) throws SAXException { LogFactory.getLogger().severe(exception.getMessage()); throw exception; } }); inputStream = resourceAccessor.getResourceAsStream(physicalChangeLogLocation); if (inputStream == null) { throw new ChangeLogParseException(physicalChangeLogLocation + " does not exist"); } XMLChangeLogSAXHandler contentHandler = new XMLChangeLogSAXHandler(physicalChangeLogLocation, resourceAccessor, changeLogParameters); xmlReader.setContentHandler(contentHandler); xmlReader.parse(new InputSource(inputStream)); return contentHandler.getDatabaseChangeLog(); } catch (ChangeLogParseException e) { throw e; } catch (IOException e) { throw new ChangeLogParseException("Error Reading Migration File: " + e.getMessage(), e); } catch (SAXParseException e) { throw new ChangeLogParseException("Error parsing line " + e.getLineNumber() + " column " + e.getColumnNumber() + " of " + physicalChangeLogLocation +": " + e.getMessage(), e); } catch (SAXException e) { Throwable parentCause = e.getException(); while (parentCause != null) { if (parentCause instanceof ChangeLogParseException) { throw ((ChangeLogParseException) parentCause); } parentCause = parentCause.getCause(); } String reason = e.getMessage(); String causeReason = null; if (e.getCause() != null) { causeReason = e.getCause().getMessage(); } if (reason == null) { if (causeReason != null) { reason = causeReason; } else { reason = "Unknown Reason"; } } throw new ChangeLogParseException("Invalid Migration File: " + reason, e); } catch (Exception e) { throw new ChangeLogParseException(e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { } } } } XMLChangeLogSAXParser(); int getPriority(); static String getSchemaVersion(); static String getDatabaseChangeLogNameSpace(); boolean supports(String changeLogFile, ResourceAccessor resourceAccessor); DatabaseChangeLog parse(String physicalChangeLogLocation, ChangeLogParameters changeLogParameters, ResourceAccessor resourceAccessor); } |
@Test public void doubleNestedChangeLog() throws Exception { final String doubleNestedFileName = "liquibase/parser/core/xml/doubleNestedChangeLog.xml"; final String nestedFileName = "liquibase/parser/core/xml/nestedChangeLog.xml"; DatabaseChangeLog changeLog = new XMLChangeLogSAXParser().parse(doubleNestedFileName, new ChangeLogParameters(), new JUnitResourceAccessor()); doubleNestedFileAssertions(doubleNestedFileName, nestedFileName, changeLog); } | public DatabaseChangeLog parse(String physicalChangeLogLocation, ChangeLogParameters changeLogParameters, ResourceAccessor resourceAccessor) throws ChangeLogParseException { InputStream inputStream = null; try { SAXParser parser = saxParserFactory.newSAXParser(); try { parser.setProperty("http: } catch (SAXNotRecognizedException e) { } catch (SAXNotSupportedException e) { } XMLReader xmlReader = parser.getXMLReader(); LiquibaseEntityResolver resolver=new LiquibaseEntityResolver(); resolver.useResoureAccessor(resourceAccessor,FilenameUtils.getFullPath(physicalChangeLogLocation)); xmlReader.setEntityResolver(resolver); xmlReader.setErrorHandler(new ErrorHandler() { public void warning(SAXParseException exception) throws SAXException { LogFactory.getLogger().warning(exception.getMessage()); throw exception; } public void error(SAXParseException exception) throws SAXException { LogFactory.getLogger().severe(exception.getMessage()); throw exception; } public void fatalError(SAXParseException exception) throws SAXException { LogFactory.getLogger().severe(exception.getMessage()); throw exception; } }); inputStream = resourceAccessor.getResourceAsStream(physicalChangeLogLocation); if (inputStream == null) { throw new ChangeLogParseException(physicalChangeLogLocation + " does not exist"); } XMLChangeLogSAXHandler contentHandler = new XMLChangeLogSAXHandler(physicalChangeLogLocation, resourceAccessor, changeLogParameters); xmlReader.setContentHandler(contentHandler); xmlReader.parse(new InputSource(inputStream)); return contentHandler.getDatabaseChangeLog(); } catch (ChangeLogParseException e) { throw e; } catch (IOException e) { throw new ChangeLogParseException("Error Reading Migration File: " + e.getMessage(), e); } catch (SAXParseException e) { throw new ChangeLogParseException("Error parsing line " + e.getLineNumber() + " column " + e.getColumnNumber() + " of " + physicalChangeLogLocation +": " + e.getMessage(), e); } catch (SAXException e) { Throwable parentCause = e.getException(); while (parentCause != null) { if (parentCause instanceof ChangeLogParseException) { throw ((ChangeLogParseException) parentCause); } parentCause = parentCause.getCause(); } String reason = e.getMessage(); String causeReason = null; if (e.getCause() != null) { causeReason = e.getCause().getMessage(); } if (reason == null) { if (causeReason != null) { reason = causeReason; } else { reason = "Unknown Reason"; } } throw new ChangeLogParseException("Invalid Migration File: " + reason, e); } catch (Exception e) { throw new ChangeLogParseException(e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { } } } } | XMLChangeLogSAXParser implements ChangeLogParser { public DatabaseChangeLog parse(String physicalChangeLogLocation, ChangeLogParameters changeLogParameters, ResourceAccessor resourceAccessor) throws ChangeLogParseException { InputStream inputStream = null; try { SAXParser parser = saxParserFactory.newSAXParser(); try { parser.setProperty("http: } catch (SAXNotRecognizedException e) { } catch (SAXNotSupportedException e) { } XMLReader xmlReader = parser.getXMLReader(); LiquibaseEntityResolver resolver=new LiquibaseEntityResolver(); resolver.useResoureAccessor(resourceAccessor,FilenameUtils.getFullPath(physicalChangeLogLocation)); xmlReader.setEntityResolver(resolver); xmlReader.setErrorHandler(new ErrorHandler() { public void warning(SAXParseException exception) throws SAXException { LogFactory.getLogger().warning(exception.getMessage()); throw exception; } public void error(SAXParseException exception) throws SAXException { LogFactory.getLogger().severe(exception.getMessage()); throw exception; } public void fatalError(SAXParseException exception) throws SAXException { LogFactory.getLogger().severe(exception.getMessage()); throw exception; } }); inputStream = resourceAccessor.getResourceAsStream(physicalChangeLogLocation); if (inputStream == null) { throw new ChangeLogParseException(physicalChangeLogLocation + " does not exist"); } XMLChangeLogSAXHandler contentHandler = new XMLChangeLogSAXHandler(physicalChangeLogLocation, resourceAccessor, changeLogParameters); xmlReader.setContentHandler(contentHandler); xmlReader.parse(new InputSource(inputStream)); return contentHandler.getDatabaseChangeLog(); } catch (ChangeLogParseException e) { throw e; } catch (IOException e) { throw new ChangeLogParseException("Error Reading Migration File: " + e.getMessage(), e); } catch (SAXParseException e) { throw new ChangeLogParseException("Error parsing line " + e.getLineNumber() + " column " + e.getColumnNumber() + " of " + physicalChangeLogLocation +": " + e.getMessage(), e); } catch (SAXException e) { Throwable parentCause = e.getException(); while (parentCause != null) { if (parentCause instanceof ChangeLogParseException) { throw ((ChangeLogParseException) parentCause); } parentCause = parentCause.getCause(); } String reason = e.getMessage(); String causeReason = null; if (e.getCause() != null) { causeReason = e.getCause().getMessage(); } if (reason == null) { if (causeReason != null) { reason = causeReason; } else { reason = "Unknown Reason"; } } throw new ChangeLogParseException("Invalid Migration File: " + reason, e); } catch (Exception e) { throw new ChangeLogParseException(e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { } } } } } | XMLChangeLogSAXParser implements ChangeLogParser { public DatabaseChangeLog parse(String physicalChangeLogLocation, ChangeLogParameters changeLogParameters, ResourceAccessor resourceAccessor) throws ChangeLogParseException { InputStream inputStream = null; try { SAXParser parser = saxParserFactory.newSAXParser(); try { parser.setProperty("http: } catch (SAXNotRecognizedException e) { } catch (SAXNotSupportedException e) { } XMLReader xmlReader = parser.getXMLReader(); LiquibaseEntityResolver resolver=new LiquibaseEntityResolver(); resolver.useResoureAccessor(resourceAccessor,FilenameUtils.getFullPath(physicalChangeLogLocation)); xmlReader.setEntityResolver(resolver); xmlReader.setErrorHandler(new ErrorHandler() { public void warning(SAXParseException exception) throws SAXException { LogFactory.getLogger().warning(exception.getMessage()); throw exception; } public void error(SAXParseException exception) throws SAXException { LogFactory.getLogger().severe(exception.getMessage()); throw exception; } public void fatalError(SAXParseException exception) throws SAXException { LogFactory.getLogger().severe(exception.getMessage()); throw exception; } }); inputStream = resourceAccessor.getResourceAsStream(physicalChangeLogLocation); if (inputStream == null) { throw new ChangeLogParseException(physicalChangeLogLocation + " does not exist"); } XMLChangeLogSAXHandler contentHandler = new XMLChangeLogSAXHandler(physicalChangeLogLocation, resourceAccessor, changeLogParameters); xmlReader.setContentHandler(contentHandler); xmlReader.parse(new InputSource(inputStream)); return contentHandler.getDatabaseChangeLog(); } catch (ChangeLogParseException e) { throw e; } catch (IOException e) { throw new ChangeLogParseException("Error Reading Migration File: " + e.getMessage(), e); } catch (SAXParseException e) { throw new ChangeLogParseException("Error parsing line " + e.getLineNumber() + " column " + e.getColumnNumber() + " of " + physicalChangeLogLocation +": " + e.getMessage(), e); } catch (SAXException e) { Throwable parentCause = e.getException(); while (parentCause != null) { if (parentCause instanceof ChangeLogParseException) { throw ((ChangeLogParseException) parentCause); } parentCause = parentCause.getCause(); } String reason = e.getMessage(); String causeReason = null; if (e.getCause() != null) { causeReason = e.getCause().getMessage(); } if (reason == null) { if (causeReason != null) { reason = causeReason; } else { reason = "Unknown Reason"; } } throw new ChangeLogParseException("Invalid Migration File: " + reason, e); } catch (Exception e) { throw new ChangeLogParseException(e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { } } } } XMLChangeLogSAXParser(); } | XMLChangeLogSAXParser implements ChangeLogParser { public DatabaseChangeLog parse(String physicalChangeLogLocation, ChangeLogParameters changeLogParameters, ResourceAccessor resourceAccessor) throws ChangeLogParseException { InputStream inputStream = null; try { SAXParser parser = saxParserFactory.newSAXParser(); try { parser.setProperty("http: } catch (SAXNotRecognizedException e) { } catch (SAXNotSupportedException e) { } XMLReader xmlReader = parser.getXMLReader(); LiquibaseEntityResolver resolver=new LiquibaseEntityResolver(); resolver.useResoureAccessor(resourceAccessor,FilenameUtils.getFullPath(physicalChangeLogLocation)); xmlReader.setEntityResolver(resolver); xmlReader.setErrorHandler(new ErrorHandler() { public void warning(SAXParseException exception) throws SAXException { LogFactory.getLogger().warning(exception.getMessage()); throw exception; } public void error(SAXParseException exception) throws SAXException { LogFactory.getLogger().severe(exception.getMessage()); throw exception; } public void fatalError(SAXParseException exception) throws SAXException { LogFactory.getLogger().severe(exception.getMessage()); throw exception; } }); inputStream = resourceAccessor.getResourceAsStream(physicalChangeLogLocation); if (inputStream == null) { throw new ChangeLogParseException(physicalChangeLogLocation + " does not exist"); } XMLChangeLogSAXHandler contentHandler = new XMLChangeLogSAXHandler(physicalChangeLogLocation, resourceAccessor, changeLogParameters); xmlReader.setContentHandler(contentHandler); xmlReader.parse(new InputSource(inputStream)); return contentHandler.getDatabaseChangeLog(); } catch (ChangeLogParseException e) { throw e; } catch (IOException e) { throw new ChangeLogParseException("Error Reading Migration File: " + e.getMessage(), e); } catch (SAXParseException e) { throw new ChangeLogParseException("Error parsing line " + e.getLineNumber() + " column " + e.getColumnNumber() + " of " + physicalChangeLogLocation +": " + e.getMessage(), e); } catch (SAXException e) { Throwable parentCause = e.getException(); while (parentCause != null) { if (parentCause instanceof ChangeLogParseException) { throw ((ChangeLogParseException) parentCause); } parentCause = parentCause.getCause(); } String reason = e.getMessage(); String causeReason = null; if (e.getCause() != null) { causeReason = e.getCause().getMessage(); } if (reason == null) { if (causeReason != null) { reason = causeReason; } else { reason = "Unknown Reason"; } } throw new ChangeLogParseException("Invalid Migration File: " + reason, e); } catch (Exception e) { throw new ChangeLogParseException(e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { } } } } XMLChangeLogSAXParser(); int getPriority(); static String getSchemaVersion(); static String getDatabaseChangeLogNameSpace(); boolean supports(String changeLogFile, ResourceAccessor resourceAccessor); DatabaseChangeLog parse(String physicalChangeLogLocation, ChangeLogParameters changeLogParameters, ResourceAccessor resourceAccessor); } | XMLChangeLogSAXParser implements ChangeLogParser { public DatabaseChangeLog parse(String physicalChangeLogLocation, ChangeLogParameters changeLogParameters, ResourceAccessor resourceAccessor) throws ChangeLogParseException { InputStream inputStream = null; try { SAXParser parser = saxParserFactory.newSAXParser(); try { parser.setProperty("http: } catch (SAXNotRecognizedException e) { } catch (SAXNotSupportedException e) { } XMLReader xmlReader = parser.getXMLReader(); LiquibaseEntityResolver resolver=new LiquibaseEntityResolver(); resolver.useResoureAccessor(resourceAccessor,FilenameUtils.getFullPath(physicalChangeLogLocation)); xmlReader.setEntityResolver(resolver); xmlReader.setErrorHandler(new ErrorHandler() { public void warning(SAXParseException exception) throws SAXException { LogFactory.getLogger().warning(exception.getMessage()); throw exception; } public void error(SAXParseException exception) throws SAXException { LogFactory.getLogger().severe(exception.getMessage()); throw exception; } public void fatalError(SAXParseException exception) throws SAXException { LogFactory.getLogger().severe(exception.getMessage()); throw exception; } }); inputStream = resourceAccessor.getResourceAsStream(physicalChangeLogLocation); if (inputStream == null) { throw new ChangeLogParseException(physicalChangeLogLocation + " does not exist"); } XMLChangeLogSAXHandler contentHandler = new XMLChangeLogSAXHandler(physicalChangeLogLocation, resourceAccessor, changeLogParameters); xmlReader.setContentHandler(contentHandler); xmlReader.parse(new InputSource(inputStream)); return contentHandler.getDatabaseChangeLog(); } catch (ChangeLogParseException e) { throw e; } catch (IOException e) { throw new ChangeLogParseException("Error Reading Migration File: " + e.getMessage(), e); } catch (SAXParseException e) { throw new ChangeLogParseException("Error parsing line " + e.getLineNumber() + " column " + e.getColumnNumber() + " of " + physicalChangeLogLocation +": " + e.getMessage(), e); } catch (SAXException e) { Throwable parentCause = e.getException(); while (parentCause != null) { if (parentCause instanceof ChangeLogParseException) { throw ((ChangeLogParseException) parentCause); } parentCause = parentCause.getCause(); } String reason = e.getMessage(); String causeReason = null; if (e.getCause() != null) { causeReason = e.getCause().getMessage(); } if (reason == null) { if (causeReason != null) { reason = causeReason; } else { reason = "Unknown Reason"; } } throw new ChangeLogParseException("Invalid Migration File: " + reason, e); } catch (Exception e) { throw new ChangeLogParseException(e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { } } } } XMLChangeLogSAXParser(); int getPriority(); static String getSchemaVersion(); static String getDatabaseChangeLogNameSpace(); boolean supports(String changeLogFile, ResourceAccessor resourceAccessor); DatabaseChangeLog parse(String physicalChangeLogLocation, ChangeLogParameters changeLogParameters, ResourceAccessor resourceAccessor); } |