src_fm_fc_ms_ff
stringlengths 43
86.8k
| target
stringlengths 20
276k
|
---|---|
ChangeLogParameters { public Object getValue(String key) { ChangeLogParameter parameter = findParameter(key); return parameter != null ? parameter.getValue() : null; } ChangeLogParameters(); ChangeLogParameters(Database currentDatabase); void addContext(String context); void setContexts(Collection<String> contexts); void set(String paramter, Object value); void set(String key, String value, String contexts, String databases); Object getValue(String key); boolean hasValue(String key); String expandExpressions(String string); } | @Test public void getParameterValue_systemProperty() { ChangeLogParameters changeLogParameters = new ChangeLogParameters(); assertEquals(System.getProperty("user.name"), changeLogParameters.getValue("user.name")); } |
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 splitOngo() { String sql = "some sql\ngo\nmore sql"; String[] result = StringUtils.splitSQL(sql, null); assertEquals(2,result.length); assertEquals("some sql",result[0]); assertEquals("more sql",result[1]); }
@Test public void splitOnGO() { String sql = "some sql\nGO\nmore sql"; String[] result = StringUtils.splitSQL(sql, null); assertEquals(2,result.length); assertEquals("some sql",result[0]); assertEquals("more sql",result[1]); }
@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); }
@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]); } |
RollbackVisitor implements ChangeSetVisitor { public void visit(ChangeSet changeSet, DatabaseChangeLog databaseChangeLog, Database database) throws LiquibaseException { LogFactory.getLogger().info("Rolling Back Changeset:" + changeSet); changeSet.rollback(this.database); this.database.removeRanStatus(changeSet); this.database.commit(); } RollbackVisitor(Database database); Direction getDirection(); void visit(ChangeSet changeSet, DatabaseChangeLog databaseChangeLog, Database database); } | @Test public void visit() throws Exception { Database database = createMock(Database.class); ChangeSet changeSet = createMock(ChangeSet.class); changeSet.rollback(database); expectLastCall(); database.removeRanStatus(changeSet); expectLastCall(); database.commit(); expectLastCall(); replay(changeSet); replay(database); RollbackVisitor visitor = new RollbackVisitor(database); visitor.visit(changeSet, new DatabaseChangeLog(), database); verify(database); verify(changeSet); } |
UpdateVisitor implements ChangeSetVisitor { public void visit(ChangeSet changeSet, DatabaseChangeLog databaseChangeLog, Database database) throws LiquibaseException { ChangeSet.RunStatus runStatus = this.database.getRunStatus(changeSet); log.debug("Running Changeset:" + changeSet); ChangeSet.ExecType execType = changeSet.execute(databaseChangeLog, this.database); if (!runStatus.equals(ChangeSet.RunStatus.NOT_RAN)) { execType = ChangeSet.ExecType.RERAN; } this.database.markChangeSetExecStatus(changeSet, execType); this.database.commit(); } UpdateVisitor(Database database); Direction getDirection(); void visit(ChangeSet changeSet, DatabaseChangeLog databaseChangeLog, Database database); } | @Test public void visit_unrun() throws Exception { Database database = createMock(Database.class); ChangeSet changeSet = createMock(ChangeSet.class); expect(changeSet.execute(new DatabaseChangeLog("test.xml"), database)).andReturn(ChangeSet.ExecType.EXECUTED); expect(database.getRunStatus(changeSet)).andReturn(ChangeSet.RunStatus.NOT_RAN); database.markChangeSetExecStatus(changeSet, ChangeSet.ExecType.EXECUTED); expectLastCall(); database.commit(); expectLastCall(); replay(changeSet); replay(database); UpdateVisitor visitor = new UpdateVisitor(database); visitor.visit(changeSet, new DatabaseChangeLog("test.xml"), database); verify(database); verify(changeSet); } |
SqlGeneratorChain { public Sql[] generateSql(SqlStatement statement, Database database) { if (sqlGenerators == null) { return null; } if (!sqlGenerators.hasNext()) { return new Sql[0]; } return sqlGenerators.next().generateSql(statement, database, this); } SqlGeneratorChain(SortedSet<SqlGenerator> sqlGenerators); Sql[] generateSql(SqlStatement statement, Database database); Warnings warn(SqlStatement statement, Database database); ValidationErrors validate(SqlStatement statement, Database database); } | @Test public void generateSql_nullGenerators() { SqlGeneratorChain chain = new SqlGeneratorChain(null); assertNull(chain.generateSql(new MockSqlStatement(), new MockDatabase())); }
@Test public void generateSql_noGenerators() { SortedSet<SqlGenerator> generators = new TreeSet<SqlGenerator>(new SqlGeneratorComparator()); SqlGeneratorChain chain = new SqlGeneratorChain(generators); assertEquals(0, chain.generateSql(new MockSqlStatement(), new MockDatabase()).length); }
@Test public void generateSql_oneGenerators() { SortedSet<SqlGenerator> generators = new TreeSet<SqlGenerator>(new SqlGeneratorComparator()); generators.add(new MockSqlGenerator(1, "A1", "A2")); SqlGeneratorChain chain = new SqlGeneratorChain(generators); Sql[] sql = chain.generateSql(new MockSqlStatement(), new MockDatabase()); assertEquals(2, sql.length); assertEquals("A1", sql[0].toSql()); assertEquals("A2", sql[1].toSql()); }
@Test public void generateSql_twoGenerators() { SortedSet<SqlGenerator> generators = new TreeSet<SqlGenerator>(new SqlGeneratorComparator()); generators.add(new MockSqlGenerator(2, "B1", "B2")); generators.add(new MockSqlGenerator(1, "A1", "A2")); SqlGeneratorChain chain = new SqlGeneratorChain(generators); Sql[] sql = chain.generateSql(new MockSqlStatement(), new MockDatabase()); assertEquals(4, sql.length); assertEquals("B1", sql[0].toSql()); assertEquals("B2", sql[1].toSql()); assertEquals("A1", sql[2].toSql()); assertEquals("A2", sql[3].toSql()); }
@Test public void generateSql_threeGenerators() { SortedSet<SqlGenerator> generators = new TreeSet<SqlGenerator>(new SqlGeneratorComparator()); generators.add(new MockSqlGenerator(2, "B1", "B2")); generators.add(new MockSqlGenerator(1, "A1", "A2")); generators.add(new MockSqlGenerator(3, "C1", "C2")); SqlGeneratorChain chain = new SqlGeneratorChain(generators); Sql[] sql = chain.generateSql(new MockSqlStatement(), new MockDatabase()); assertEquals(6, sql.length); assertEquals("C1", sql[0].toSql()); assertEquals("C2", sql[1].toSql()); assertEquals("B1", sql[2].toSql()); assertEquals("B2", sql[3].toSql()); assertEquals("A1", sql[4].toSql()); assertEquals("A2", sql[5].toSql()); } |
SqlGeneratorChain { public ValidationErrors validate(SqlStatement statement, Database database) { if (sqlGenerators == null || !sqlGenerators.hasNext()) { return new ValidationErrors(); } return sqlGenerators.next().validate(statement, database, this); } SqlGeneratorChain(SortedSet<SqlGenerator> sqlGenerators); Sql[] generateSql(SqlStatement statement, Database database); Warnings warn(SqlStatement statement, Database database); ValidationErrors validate(SqlStatement statement, Database database); } | @Test public void validate_nullGenerators() { SqlGeneratorChain chain = new SqlGeneratorChain(null); ValidationErrors validationErrors = chain.validate(new MockSqlStatement(), new MockDatabase()); assertFalse(validationErrors.hasErrors()); }
@Test public void validate_oneGenerators_noErrors() { SortedSet<SqlGenerator> generators = new TreeSet<SqlGenerator>(new SqlGeneratorComparator()); generators.add(new MockSqlGenerator(1, "A1", "A2")); SqlGeneratorChain chain = new SqlGeneratorChain(generators); ValidationErrors validationErrors = chain.validate(new MockSqlStatement(), new MockDatabase()); assertFalse(validationErrors.hasErrors()); }
@Test public void validate_oneGenerators_hasErrors() { SortedSet<SqlGenerator> generators = new TreeSet<SqlGenerator>(new SqlGeneratorComparator()); generators.add(new MockSqlGenerator(1, "A1", "A2").addValidationError("E1")); SqlGeneratorChain chain = new SqlGeneratorChain(generators); ValidationErrors validationErrors = chain.validate(new MockSqlStatement(), new MockDatabase()); assertTrue(validationErrors.hasErrors()); }
@Test public void validate_twoGenerators_noErrors() { SortedSet<SqlGenerator> generators = new TreeSet<SqlGenerator>(new SqlGeneratorComparator()); generators.add(new MockSqlGenerator(2, "B1", "B2")); generators.add(new MockSqlGenerator(1, "A1", "A2")); SqlGeneratorChain chain = new SqlGeneratorChain(generators); ValidationErrors validationErrors = chain.validate(new MockSqlStatement(), new MockDatabase()); assertFalse(validationErrors.hasErrors()); }
@Test public void validate_twoGenerators_firstHasErrors() { SortedSet<SqlGenerator> generators = new TreeSet<SqlGenerator>(new SqlGeneratorComparator()); generators.add(new MockSqlGenerator(2, "B1", "B2").addValidationError("E1")); generators.add(new MockSqlGenerator(1, "A1", "A2")); SqlGeneratorChain chain = new SqlGeneratorChain(generators); ValidationErrors validationErrors = chain.validate(new MockSqlStatement(), new MockDatabase()); assertTrue(validationErrors.hasErrors()); }
@Test public void validate_twoGenerators_secondHasErrors() { SortedSet<SqlGenerator> generators = new TreeSet<SqlGenerator>(new SqlGeneratorComparator()); generators.add(new MockSqlGenerator(2, "B1", "B2")); generators.add(new MockSqlGenerator(1, "A1", "A2").addValidationError("E1")); SqlGeneratorChain chain = new SqlGeneratorChain(generators); ValidationErrors validationErrors = chain.validate(new MockSqlStatement(), new MockDatabase()); assertTrue(validationErrors.hasErrors()); } |
DropIndexGenerator extends AbstractSqlGenerator<DropIndexStatement> { public Sql[] generateSql(DropIndexStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { List<String> associatedWith = StringUtils.splitAndTrim(statement.getAssociatedWith(), ","); if (associatedWith != null) { if (associatedWith.contains(Index.MARK_PRIMARY_KEY)|| associatedWith.contains(Index.MARK_UNIQUE_CONSTRAINT)) { return new Sql[0]; } else if (associatedWith.contains(Index.MARK_FOREIGN_KEY) ) { if (!(database instanceof OracleDatabase || database instanceof MSSQLDatabase)) { return new Sql[0]; } } } String schemaName = statement.getTableSchemaName(); if (database instanceof MySQLDatabase) { return new Sql[] {new UnparsedSql("DROP INDEX " + database.escapeIndexName(null, statement.getIndexName()) + " ON " + database.escapeTableName(schemaName, statement.getTableName())) }; } else if (database instanceof MSSQLDatabase) { return new Sql[] {new UnparsedSql("DROP INDEX " + database.escapeTableName(schemaName, statement.getTableName()) + "." + database.escapeIndexName(null, statement.getIndexName())) }; } else if (database instanceof PostgresDatabase) { return new Sql[]{new UnparsedSql("DROP INDEX " + database.escapeIndexName(schemaName, statement.getIndexName()))}; } return new Sql[] {new UnparsedSql("DROP INDEX " + database.escapeIndexName(schemaName, statement.getIndexName())) }; } ValidationErrors validate(DropIndexStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain); Sql[] generateSql(DropIndexStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain); } | @Test public void shouldDropIndexInPostgreSQL() throws Exception { DropIndexGenerator dropIndexGenerator = new DropIndexGenerator(); DropIndexStatement statement = new DropIndexStatement("indexName", "defaultSchema", "aTable", null); Database database = new PostgresDatabase(); SortedSet<SqlGenerator> sqlGenerators = new TreeSet<SqlGenerator>(); SqlGeneratorChain sqlGenerationChain = new SqlGeneratorChain(sqlGenerators); Sql[] sqls = dropIndexGenerator.generateSql(statement, database, sqlGenerationChain); assertEquals("DROP INDEX \"defaultSchema\".\"indexName\"", sqls[0].toSql()); statement = new DropIndexStatement("index_name", "default_schema", "a_table", null); sqls = dropIndexGenerator.generateSql(statement, database, sqlGenerationChain); assertEquals("DROP INDEX default_schema.index_name", sqls[0].toSql()); statement = new DropIndexStatement("index_name", null, "a_table", null); sqls = dropIndexGenerator.generateSql(statement, database, sqlGenerationChain); assertEquals("DROP INDEX index_name", sqls[0].toSql()); } |
AddColumnGeneratorDefaultClauseBeforeNotNull extends AddColumnGenerator { @Override public ValidationErrors validate(AddColumnStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { ValidationErrors validationErrors = super.validate(statement, database, sqlGeneratorChain); if (database instanceof DerbyDatabase && statement.isAutoIncrement()) { validationErrors.addError("Cannot add an identity column to a database"); } return validationErrors; } @Override int getPriority(); @Override boolean supports(AddColumnStatement statement, Database database); @Override ValidationErrors validate(AddColumnStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain); @Override Sql[] generateSql(AddColumnStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain); } | @Test public void validate_noAutoIncrementWithDerby() { ValidationErrors validationErrors = generatorUnderTest.validate(new AddColumnStatement(null, "table_name", "column_name", "int", null, new AutoIncrementConstraint("column_name")), new DerbyDatabase(), new MockSqlGeneratorChain()); assertTrue(validationErrors.getErrorMessages().contains("Cannot add an identity column to a database")); } |
InsertOrUpdateGeneratorMSSQL extends InsertOrUpdateGenerator { protected String getRecordCheck(InsertOrUpdateStatement insertOrUpdateStatement, Database database, String whereClause) { StringBuffer recordCheck = new StringBuffer(); recordCheck.append("DECLARE @reccount integer\n"); recordCheck.append("SELECT @reccount = count(*) FROM "); recordCheck.append(database.escapeTableName(insertOrUpdateStatement.getSchemaName(),insertOrUpdateStatement.getTableName())); recordCheck.append(" WHERE "); recordCheck.append(whereClause); recordCheck.append("\n"); recordCheck.append("IF @reccount = 0\n"); return recordCheck.toString(); } boolean supports(InsertOrUpdateStatement statement, Database database); @Override Sql[] generateSql(InsertOrUpdateStatement insertOrUpdateStatement, Database database, SqlGeneratorChain sqlGeneratorChain); } | @Test public void getRecordCheck(){ InsertOrUpdateGeneratorMSSQL generator = new InsertOrUpdateGeneratorMSSQL(); MSSQLDatabase database = new MSSQLDatabase(); InsertOrUpdateStatement statement = new InsertOrUpdateStatement("myschema","mytable","pk_col1"); statement.addColumnValue("pk_col1","value1"); statement.addColumnValue("col2","value2"); String where = "1 = 1"; Class c = InsertOrUpdateGenerator.class.getClass(); String recordCheck = (String)invokePrivateMethod(generator,"getRecordCheck", new Object[] {statement,database,where}); Integer lineNumber = 0; String[] lines = recordCheck.split("\n"); assertEquals("DECLARE @reccount integer", lines[lineNumber]); lineNumber++; assertEquals("SELECT @reccount = count(*) FROM [myschema].[mytable] WHERE " + where, lines[lineNumber]); lineNumber++; assertEquals("IF @reccount = 0", lines[lineNumber]); } |
InsertOrUpdateGeneratorMSSQL extends InsertOrUpdateGenerator { protected String getElse(Database database) { return "ELSE\n"; } boolean supports(InsertOrUpdateStatement statement, Database database); @Override Sql[] generateSql(InsertOrUpdateStatement insertOrUpdateStatement, Database database, SqlGeneratorChain sqlGeneratorChain); } | @Test public void getElse(){ InsertOrUpdateGeneratorMSSQL generator = new InsertOrUpdateGeneratorMSSQL(); MSSQLDatabase database = new MSSQLDatabase(); InsertOrUpdateStatement statement = new InsertOrUpdateStatement("myschema","mytable","pk_col1"); statement.addColumnValue("pk_col1","value1"); statement.addColumnValue("col2","value2"); String where = "1 = 1"; Class c = InsertOrUpdateGenerator.class.getClass(); String insertStatement = (String)invokePrivateMethod(generator,"getElse", new Object[] {database}); Integer lineNumber = 0; String[] lines = insertStatement.split("\n"); assertEquals("ELSE", lines[lineNumber]); } |
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 testWithColumnWithDefaultValue() { for (Database database : TestContext.getInstance().getAllDatabases()) { if (database instanceof OracleDatabase) { CreateTableStatement statement = new CreateTableStatement(SCHEMA_NAME, TABLE_NAME); statement.addColumn(COLUMN_NAME1, TypeConverterFactory.getInstance().findTypeConverter(database).getDataType("java.sql.Types.TIMESTAMP", false), new ColumnConfig().setDefaultValue("null").getDefaultValueObject()); if (shouldBeImplementation(database)) { assertEquals("CREATE TABLE SCHEMA_NAME.TABLE_NAME (COLUMN1_NAME TIMESTAMP DEFAULT null)", this.generatorUnderTest.generateSql(statement, database, null)[0].toSql()); } } } }
@Test public void testWithColumnSpecificIntType() { for (Database database : TestContext.getInstance().getAllDatabases()) { CreateTableStatement statement = new CreateTableStatement(SCHEMA_NAME, TABLE_NAME); statement.addColumn(COLUMN_NAME1, TypeConverterFactory.getInstance().findTypeConverter(database).getDataType("int(11) unsigned", false)); if (database instanceof MySQLDatabase) { assertEquals("CREATE TABLE `SCHEMA_NAME`.`TABLE_NAME` (`COLUMN1_NAME` INT(11) unsigned)", this.generatorUnderTest.generateSql(statement, database, null)[0].toSql()); } } }
@Test public void testAutoIncrementDB2Database() throws Exception { for (Database database : TestContext.getInstance().getAllDatabases()) { if (database instanceof DB2Database) { 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 GENERATED BY DEFAULT AS IDENTITY)", generatedSql[0].toSql()); } } }
@Test public void testAutoIncrementStartWithDB2Database() throws Exception { for (Database database : TestContext.getInstance().getAllDatabases()) { if (database instanceof DB2Database) { 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 BIGINT GENERATED BY DEFAULT AS IDENTITY (START WITH 0))", generatedSql[0].toSql()); } } }
@Test public void testAutoIncrementStartWithIncrementByDB2Database() throws Exception { for (Database database : TestContext.getInstance().getAllDatabases()) { if (database instanceof DB2Database) { 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 BIGINT GENERATED BY DEFAULT AS IDENTITY (START WITH 0, INCREMENT BY 10))", generatedSql[0].toSql()); } } }
@Test public void testAutoIncrementDerbyDatabase() throws Exception { for (Database database : TestContext.getInstance().getAllDatabases()) { if (database instanceof DerbyDatabase) { 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 GENERATED BY DEFAULT AS IDENTITY)", generatedSql[0].toSql()); } } }
@Test public void testAutoIncrementStartWithDerbyDatabase() throws Exception { for (Database database : TestContext.getInstance().getAllDatabases()) { if (database instanceof DerbyDatabase) { 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 BIGINT GENERATED BY DEFAULT AS IDENTITY (START WITH 0))", generatedSql[0].toSql()); } } }
@Test public void testAutoIncrementStartWithIncrementByDerbyDatabase() throws Exception { for (Database database : TestContext.getInstance().getAllDatabases()) { if (database instanceof DerbyDatabase) { 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 BIGINT GENERATED BY DEFAULT AS IDENTITY (START WITH 0, INCREMENT BY 10))", generatedSql[0].toSql()); } } }
@Test public void testAutoIncrementH2Database() throws Exception { for (Database database : TestContext.getInstance().getAllDatabases()) { if (database instanceof H2Database) { 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 GENERATED BY DEFAULT AS IDENTITY)", generatedSql[0].toSql()); } } }
@Test public void testAutoIncrementStartWithH2Database() throws Exception { for (Database database : TestContext.getInstance().getAllDatabases()) { if (database instanceof H2Database) { 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 BIGINT GENERATED BY DEFAULT AS IDENTITY (START WITH 0))", generatedSql[0].toSql()); } } }
@Test public void testAutoIncrementStartWithIncrementByH2Database() throws Exception { for (Database database : TestContext.getInstance().getAllDatabases()) { if (database instanceof H2Database) { 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 BIGINT GENERATED BY DEFAULT AS IDENTITY (START WITH 0, INCREMENT BY 10))", generatedSql[0].toSql()); } } }
@Test public void testAutoIncrementHsqlDatabase() throws Exception { for (Database database : TestContext.getInstance().getAllDatabases()) { if (database instanceof HsqlDatabase) { 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 GENERATED BY DEFAULT AS IDENTITY)", generatedSql[0].toSql()); } } }
@Test public void testAutoIncrementStartWithHsqlDatabase() throws Exception { for (Database database : TestContext.getInstance().getAllDatabases()) { if (database instanceof HsqlDatabase) { CreateTableStatement statement = new CreateTableStatement(SCHEMA_NAME, TABLE_NAME); statement.addColumn( COLUMN_NAME1, TypeConverterFactory.getInstance().findTypeConverter(database).getDataType("BIGINT", true), new AutoIncrementConstraint(COLUMN_NAME1, BigInteger.ONE, null) ); Sql[] generatedSql = this.generatorUnderTest.generateSql(statement, database, null); assertEquals("CREATE TABLE SCHEMA_NAME.TABLE_NAME (COLUMN1_NAME BIGINT GENERATED BY DEFAULT AS IDENTITY (START WITH 1))", generatedSql[0].toSql()); } } }
@Test public void testAutoIncrementStartWithIncrementByHsqlDatabase() throws Exception { for (Database database : TestContext.getInstance().getAllDatabases()) { if (database instanceof HsqlDatabase) { CreateTableStatement statement = new CreateTableStatement(SCHEMA_NAME, TABLE_NAME); statement.addColumn( COLUMN_NAME1, TypeConverterFactory.getInstance().findTypeConverter(database).getDataType("BIGINT", true), new AutoIncrementConstraint(COLUMN_NAME1, BigInteger.ONE, BigInteger.TEN) ); Sql[] generatedSql = this.generatorUnderTest.generateSql(statement, database, null); assertEquals("CREATE TABLE SCHEMA_NAME.TABLE_NAME (COLUMN1_NAME BIGINT GENERATED BY DEFAULT AS IDENTITY (START WITH 1, INCREMENT BY 10))", generatedSql[0].toSql()); } } }
@Test public void testAutoIncrementMSSQLDatabase() throws Exception { for (Database database : TestContext.getInstance().getAllDatabases()) { if (database instanceof MSSQLDatabase) { 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)", generatedSql[0].toSql()); } } }
@Test public void testAutoIncrementStartWithMSSQLDatabase() throws Exception { for (Database database : TestContext.getInstance().getAllDatabases()) { if (database instanceof MSSQLDatabase) { 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] BIGINT IDENTITY (0))", generatedSql[0].toSql()); } } }
@Test public void testAutoIncrementStartWithIncrementByMSSQLDatabase() throws Exception { for (Database database : TestContext.getInstance().getAllDatabases()) { if (database instanceof MSSQLDatabase) { 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] BIGINT IDENTITY (0, 10))", generatedSql[0].toSql()); } } }
@Test public void testAutoIncrementMySQLDatabase() throws Exception { for (Database database : TestContext.getInstance().getAllDatabases()) { if (database instanceof MySQLDatabase) { 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 AUTO_INCREMENT)", generatedSql[0].toSql()); } } }
@Test public void testAutoIncrementStartWithMySQLDatabase() throws Exception { for (Database database : TestContext.getInstance().getAllDatabases()) { if (database instanceof MySQLDatabase) { 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 AUTO_INCREMENT=2)", generatedSql[0].toSql()); } } }
@Test public void testAutoIncrementStartWithIncrementByMySQLDatabase() throws Exception { for (Database database : TestContext.getInstance().getAllDatabases()) { if (database instanceof MySQLDatabase) { 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 AUTO_INCREMENT=2)", generatedSql[0].toSql()); } } }
@Test public void testAutoIncrementPostgresDatabase() 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) ); Sql[] generatedSql = this.generatorUnderTest.generateSql(statement, database, null); assertEquals("CREATE TABLE SCHEMA_NAME.TABLE_NAME (COLUMN1_NAME bigserial)", generatedSql[0].toSql()); } } }
@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()); } } }
@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()); } } }
@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()); } } }
@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()); } } }
@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()); } } }
@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()); } } }
@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()); } } }
@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()); } } }
@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()); } } }
@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()); } } }
@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()); } } } |
AutoIncrementConstraint implements ColumnConstraint { public String getColumnName() { return columnName; } AutoIncrementConstraint(); AutoIncrementConstraint(String columnName); AutoIncrementConstraint(
String columnName, BigInteger startWith, BigInteger incrementBy); String getColumnName(); AutoIncrementConstraint setColumnName(String columnName); BigInteger getStartWith(); AutoIncrementConstraint setStartWith(BigInteger startWith); BigInteger getIncrementBy(); AutoIncrementConstraint setIncrementBy(BigInteger incrementBy); } | @Test public void ctor() { AutoIncrementConstraint constraint = new AutoIncrementConstraint("COL_NAME"); assertEquals("COL_NAME", constraint.getColumnName()); } |
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 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()); }
@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()); } |
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 getInstance() { assertNotNull(SqlGeneratorFactory.getInstance()); assertTrue(SqlGeneratorFactory.getInstance() == SqlGeneratorFactory.getInstance()); } |
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 register() { SqlGeneratorFactory.getInstance().getGenerators().clear(); assertEquals(0, SqlGeneratorFactory.getInstance().getGenerators().size()); SqlGeneratorFactory.getInstance().register(new MockSqlGenerator(1, "A1")); assertEquals(1, SqlGeneratorFactory.getInstance().getGenerators().size()); } |
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 reset() { SqlGeneratorFactory instance1 = SqlGeneratorFactory.getInstance(); SqlGeneratorFactory.reset(); assertFalse(instance1 == SqlGeneratorFactory.getInstance()); } |
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 getGenerators() { SortedSet<SqlGenerator> allGenerators = SqlGeneratorFactory.getInstance().getGenerators(new AddAutoIncrementStatement(null, "person", "name", "varchar(255)", null, null), new H2Database()); assertNotNull(allGenerators); assertEquals(1, allGenerators.size()); } |
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 getInstance() { assertNotNull(PreconditionFactory.getInstance()); assertTrue(PreconditionFactory.getInstance() == PreconditionFactory.getInstance()); } |
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 register() { PreconditionFactory.getInstance().getPreconditions().clear(); assertEquals(0, PreconditionFactory.getInstance().getPreconditions().size()); PreconditionFactory.getInstance().register(MockPrecondition.class); assertEquals(1, PreconditionFactory.getInstance().getPreconditions().size()); } |
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 reset() { PreconditionFactory instance1 = PreconditionFactory.getInstance(); PreconditionFactory.reset(); assertFalse(instance1 == PreconditionFactory.getInstance()); } |
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 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); }
@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); }
@Test public void convertMigrateToUpdate() throws Exception { String[] args = new String[]{ "--promptForNonLocalDatabase=false", "migrate", }; Main cli = new Main(); cli.parseOptions(args); assertEquals("update", cli.command); }
@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); }
@Test(expected = CommandLineParsingException.class) public void parameterWithoutDash() throws Exception { String[] args = new String[]{ "promptForNonLocalDatabase=true", "update", }; Main cli = new Main(); cli.parseOptions(args); }
@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); }
@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()); }
@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); }
@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); } |
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(expected = CommandLineParsingException.class) public void configureNonExistantClassloaderLocation() throws Exception { Main cli = new Main(); cli.classpath = "badClasspathLocation"; cli.configureClassLoader(); } |
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 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); }
@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); }
@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())); } |
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 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); } |
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 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()); } |
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 testGetStreamContents() throws IOException { byte[] contents = "TEST2".getBytes(); ByteArrayInputStream stream = new ByteArrayInputStream(contents); String result = StreamUtil.getStreamContents(stream); assertEquals("TEST2", result); } |
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 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"); } } } |
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 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), " ")); } |
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 testVersionArg() throws IOException, CommandLineParsingException { Main.main(new String[] {"--version"}); } |
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); } | @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()); } |
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 { 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()); } |
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(); } | @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()); } |
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 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()); } |
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 testGetReaderContents() throws IOException { String contents = "TEST"; StringReader reader = new StringReader(contents); String result = StreamUtil.getReaderContents(reader); assertEquals(contents, result); } |
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(); } | @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()); } |
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 { 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()); } |
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 { CreateProcedureChange refactoring = new CreateProcedureChange(); assertEquals("Stored procedure created", refactoring.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 { refactoring.setOldTableName("OLD_NAME"); refactoring.setNewTableName("NEW_NAME"); assertEquals("Table OLD_NAME renamed to NEW_NAME", refactoring.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 { assertEquals("Custom SQL executed", refactoring.getConfirmationMessage()); } |
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 { DropIndexChange refactoring = new DropIndexChange(); refactoring.setIndexName("IDX_NAME"); refactoring.setTableName("TABLE_NAME"); assertEquals("Index IDX_NAME dropped from table TABLE_NAME", refactoring.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 { refactoring.setTag("TAG_NAME"); assertEquals("Tag 'TAG_NAME' applied to database", refactoring.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 { 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()); } |
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 { assertEquals("Column TABLE_NAME.oldColName renamed to newColName", refactoring.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(); } | @Override @Test public void getConfirmationMessage() throws Exception { AlterSequenceChange refactoring = new AlterSequenceChange(); refactoring.setSequenceName("SEQ_NAME"); assertEquals("Sequence SEQ_NAME altered", refactoring.getConfirmationMessage()); } |
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); } | @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); }
@Test public void testComputeMD5InputStream() { ByteArrayInputStream bais = new ByteArrayInputStream(TEST_STRING.getBytes()); String hexString = MD5Util.computeMD5(bais); assertEquals(TEST_STRING_MD5_HASH, hexString); } |
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 { DropForeignKeyConstraintChange change = new DropForeignKeyConstraintChange(); change.setBaseTableSchemaName("SCHEMA_NAME"); change.setBaseTableName("TABLE_NAME"); change.setConstraintName("FK_NAME"); assertEquals("Foreign key FK_NAME dropped", change.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(); } | @Override @Test public void getConfirmationMessage() throws Exception { assertEquals("Table TAB_NAME dropped", change.getConfirmationMessage()); } |
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 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()); }
@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()); } |
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 primaryKeyNullThrowsException() { LoadUpdateDataChange change = new LoadUpdateDataChange(); try { change.setPrimaryKey(null); fail("setPrimaryKey did not throw InvalidArgumentException as expected."); } catch(LiquibaseException e) { } } |
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); } | @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()); } |
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 { AddUniqueConstraintChange change = new AddUniqueConstraintChange(); change.setTableName("TABLE_NAME"); change.setColumnNames("COL_HERE"); assertEquals("Unique constraint added to TABLE_NAME(COL_HERE)", change.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 { 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()); } |
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 { refactoring.setOldViewName("OLD_NAME"); refactoring.setNewViewName("NEW_NAME"); assertEquals("View OLD_NAME renamed to NEW_NAME", refactoring.getConfirmationMessage()); } |
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(); } | @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()); } |
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 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()); } |
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 { CreateViewChange change = new CreateViewChange(); change.setViewName("VIEW_NAME"); assertEquals("View VIEW_NAME created", change.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 { assertEquals("Unique constraint UQ_CONSTRAINT dropped from TAB_NAME", change.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 getConfirmationMessage() throws Exception { change.setTableName("TAB_NAME"); assertEquals("Table TAB_NAME created", change.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 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()); } |
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 { assertEquals("New row inserted into TABLE_NAME", refactoring.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 { DropViewChange change = new DropViewChange(); change.setViewName("VIEW_NAME"); assertEquals("View VIEW_NAME dropped", change.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 { DropColumnChange change = new DropColumnChange(); change.setTableName("TABLE_NAME"); change.setColumnName("COL_HERE"); assertEquals("Column TABLE_NAME.COL_HERE dropped", change.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 { DropNotNullConstraintChange change = new DropNotNullConstraintChange(); change.setTableName("TABLE_NAME"); change.setColumnName("COL_HERE"); assertEquals("Null constraint dropped from TABLE_NAME.COL_HERE", change.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(); } | @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()); } |
RegexMatcher { public boolean allMatchedInSequentialOrder() { return allMatched; } RegexMatcher(String text,String [] regexToMatch); boolean allMatchedInSequentialOrder(); } | @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()); } |
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(); } | @Override @Test public void getConfirmationMessage() throws Exception { assertEquals("Sequence SEQ_NAME dropped", change.getConfirmationMessage()); } |
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 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()); }
@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()); }
@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()); } |
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); } | @Override @Test public void getConfirmationMessage() throws Exception { change.setPath(fileName); assertEquals("SQL in file " + fileName + " executed", change.getConfirmationMessage()); } |
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 { CreateIndexChange refactoring = new CreateIndexChange(); refactoring.setIndexName("IDX_TEST"); assertEquals("Index IDX_TEST created", refactoring.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 { 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()); } |
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 { AddPrimaryKeyChange change = new AddPrimaryKeyChange(); change.setTableName("TABLE_NAME"); change.setColumnNames("COL_HERE"); assertEquals("Primary key added to TABLE_NAME (COL_HERE)", change.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(); } | @Override @Test public void getConfirmationMessage() throws Exception { CreateSequenceChange change = new CreateSequenceChange(); change.setSequenceName("SEQ_NAME"); assertEquals("Sequence SEQ_NAME created", change.getConfirmationMessage()); } |
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 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()); } } } |
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 escapeTableName_noSchema() { Database database = getDatabase(); assertEquals("tableName", database.escapeTableName(null, "tableName")); }
@Test public void escapeTableName_withSchema() { Database database = getDatabase(); assertEquals("schemaName.tableName", database.escapeTableName("schemaName", "tableName")); } |
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 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)); } } |
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 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()); } } } |
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 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); }
@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()); }
@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()); }
@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()); }
@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); }
@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); }
@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); }
@Test public void doubleNestedRelativeChangeLog() throws Exception { final String doubleNestedFileName = "liquibase/parser/core/xml/doubleNestedRelativeChangeLog.xml"; final String nestedFileName = "liquibase/parser/core/xml/nestedRelativeChangeLog.xml"; DatabaseChangeLog changeLog = new XMLChangeLogSAXParser().parse(doubleNestedFileName, new ChangeLogParameters(), new JUnitResourceAccessor()); doubleNestedFileAssertions(doubleNestedFileName, nestedFileName, changeLog); }
@Test public void missingChangeLog() throws Exception { try { @SuppressWarnings("unused") DatabaseChangeLog changeLog = new XMLChangeLogSAXParser().parse("liquibase/changelog/parser/xml/missingChangeLog.xml", new ChangeLogParameters(), new JUnitResourceAccessor()); } catch (Exception e) { assertTrue(e instanceof ChangeLogParseException); assertEquals("liquibase/changelog/parser/xml/missingChangeLog.xml does not exist", e.getMessage()); } }
@Test public void malformedChangeLog() throws Exception { try { DatabaseChangeLog changeLog = new XMLChangeLogSAXParser().parse("liquibase/parser/core/xml/malformedChangeLog.xml", new ChangeLogParameters(), new JUnitResourceAccessor()); } catch (Exception e) { assertTrue(e instanceof ChangeLogParseException); assertTrue(e.getMessage().startsWith("Error parsing line")); } }
@Test public void otherNamespaceAttributesChangeLog() 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); }
@Test public void rawSqlParameter() throws Exception { ChangeLogParameters params = new ChangeLogParameters(); params.set("tablename", "rawsql"); DatabaseChangeLog changeLog = new XMLChangeLogSAXParser().parse("liquibase/parser/core/xml/rawSqlParameters.xml", params, new JUnitResourceAccessor()); assertEquals("liquibase/parser/core/xml/rawSqlParameters.xml", changeLog.getLogicalFilePath()); assertEquals("liquibase/parser/core/xml/rawSqlParameters.xml", changeLog.getPhysicalFilePath()); assertEquals(1, changeLog.getChangeSets().size()); ChangeSet changeSet = changeLog.getChangeSets().get(0); assertEquals("paikens", changeSet.getAuthor()); assertEquals("1", changeSet.getId()); assertEquals("liquibase/parser/core/xml/rawSqlParameters.xml", changeSet.getFilePath()); assertEquals(1, changeSet.getChanges().size()); assertTrue(changeSet.getChanges().get(0) instanceof RawSQLChange); assertEquals("create table rawsql;", ((RawSQLChange) changeSet.getChanges().get(0)).getSql()); assertEquals(1, changeSet.getRollBackChanges().length); assertTrue(changeSet.getRollBackChanges()[0] instanceof RawSQLChange); assertEquals("drop table rawsql", ((RawSQLChange) changeSet.getRollBackChanges()[0]).getSql()); } |
LiquibaseEntityResolver implements EntityResolver2 { public InputSource resolveEntity(String name, String publicId, String baseURI, String systemId) throws SAXException, IOException { InputSource resolved=null; if(systemId!=null && systemId.toLowerCase().endsWith(".xsd")) { resolved=tryResolveLiquibaseSchema(systemId, publicId); } if(resolved==null && resourceAccessor!=null && basePath!=null && systemId!=null) { resolved=tryResolveFromResourceAccessor(systemId); } return resolved; } LiquibaseEntityResolver(); void useResoureAccessor(ResourceAccessor resourceAccessor,String basePath); InputSource resolveEntity(String name, String publicId, String baseURI, String systemId); InputSource getExternalSubset(String name, String baseURI); InputSource resolveEntity(String publicId, String systemId); } | @Test public void resolveSchemas() throws Exception { LiquibaseEntityResolver liquibaseSchemaResolver = new LiquibaseEntityResolver(); assertNotNull(liquibaseSchemaResolver.resolveEntity(null, null, null, "http: assertNull(liquibaseSchemaResolver.resolveEntity(null,null,null, "http: } |
FormattedSqlChangeLogParser implements ChangeLogParser { public boolean supports(String changeLogFile, ResourceAccessor resourceAccessor) { BufferedReader reader = null; try { if (changeLogFile.endsWith(".sql")) { reader = new BufferedReader(new InputStreamReader(openChangeLogFile(changeLogFile, resourceAccessor))); return reader.readLine().matches("\\-\\-\\s*liquibase formatted.*"); } else { return false; } } catch (IOException e) { LogFactory.getLogger().debug("Exception reading " + changeLogFile, e); return false; } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { LogFactory.getLogger().debug("Exception closing " + changeLogFile, e); } } } } boolean supports(String changeLogFile, ResourceAccessor resourceAccessor); int getPriority(); DatabaseChangeLog parse(String physicalChangeLogLocation, ChangeLogParameters changeLogParameters, ResourceAccessor resourceAccessor); } | @Test public void supports() throws Exception { assertTrue(new MockFormattedSqlChangeLogParser(VALID_CHANGELOG).supports("asdf.sql", new JUnitResourceAccessor())); assertFalse(new MockFormattedSqlChangeLogParser(INVALID_CHANGELOG).supports("asdf.sql", new JUnitResourceAccessor())); } |
FormattedSqlChangeLogParser implements ChangeLogParser { public DatabaseChangeLog parse(String physicalChangeLogLocation, ChangeLogParameters changeLogParameters, ResourceAccessor resourceAccessor) throws ChangeLogParseException { DatabaseChangeLog changeLog = new DatabaseChangeLog(); changeLog.setPhysicalFilePath(physicalChangeLogLocation); BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(openChangeLogFile(physicalChangeLogLocation, resourceAccessor))); StringBuffer currentSql = new StringBuffer(); StringBuffer currentRollbackSql = new StringBuffer(); ChangeSet changeSet = null; RawSQLChange change = null; Pattern changeSetPattern = Pattern.compile("\\-\\-[\\s]*changeset (\\S+):(\\S+).*", Pattern.CASE_INSENSITIVE); Pattern rollbackPattern = Pattern.compile("\\s*\\-\\-[\\s]*rollback (.*)", Pattern.CASE_INSENSITIVE); Pattern preconditionsPattern = Pattern.compile("\\s*\\-\\-[\\s]*preconditions(.*)", Pattern.CASE_INSENSITIVE); Pattern preconditionPattern = Pattern.compile("\\s*\\-\\-[\\s]*precondition\\-([a-zA-Z0-9-]+) (.*)", Pattern.CASE_INSENSITIVE); Pattern stripCommentsPattern = Pattern.compile(".*stripComments:(\\w+).*", Pattern.CASE_INSENSITIVE); Pattern splitStatementsPattern = Pattern.compile(".*splitStatements:(\\w+).*", Pattern.CASE_INSENSITIVE); Pattern endDelimiterPattern = Pattern.compile(".*endDelimiter:(\\w+).*", Pattern.CASE_INSENSITIVE); Pattern runOnChangePattern = Pattern.compile(".*runOnChange:(\\w+).*", Pattern.CASE_INSENSITIVE); Pattern runAlwaysPattern = Pattern.compile(".*runAlways:(\\w+).*", Pattern.CASE_INSENSITIVE); Pattern contextPattern = Pattern.compile(".*context:(\\S+).*", Pattern.CASE_INSENSITIVE); Pattern runInTransactionPattern = Pattern.compile(".*runInTransaction:(\\w+).*", Pattern.CASE_INSENSITIVE); Pattern dbmsPattern = Pattern.compile(".*dbms:(\\w+).*", Pattern.CASE_INSENSITIVE); Pattern failOnErrorPattern = Pattern.compile(".*failOnError:(\\w+).*", Pattern.CASE_INSENSITIVE); Pattern onFailPattern = Pattern.compile(".*onFail:(\\w+).*", Pattern.CASE_INSENSITIVE); Pattern onErrorPattern = Pattern.compile(".*onError:(\\w+).*", Pattern.CASE_INSENSITIVE); Pattern onUpdateSqlPattern = Pattern.compile(".*onUpdateSQL:(\\w+).*", Pattern.CASE_INSENSITIVE); String line; while ((line = reader.readLine()) != null) { Matcher changeSetPatternMatcher = changeSetPattern.matcher(line); if (changeSetPatternMatcher.matches()) { String finalCurrentSql = changeLogParameters.expandExpressions(StringUtils.trimToNull(currentSql.toString())); if (changeSet != null) { if (finalCurrentSql == null) { throw new ChangeLogParseException("No SQL for changeset " + changeSet.toString(false)); } change.setSql(finalCurrentSql); if (StringUtils.trimToNull(currentRollbackSql.toString()) != null) { try { if (currentRollbackSql.toString().trim().toLowerCase().matches("^not required.*")) { changeSet.addRollbackChange(new EmptyChange()); } else { RawSQLChange rollbackChange = new RawSQLChange(); rollbackChange.setSql(changeLogParameters.expandExpressions(currentRollbackSql.toString())); changeSet.addRollbackChange(rollbackChange); } } catch (UnsupportedChangeException e) { throw new RuntimeException(e); } } } Matcher stripCommentsPatternMatcher = stripCommentsPattern.matcher(line); Matcher splitStatementsPatternMatcher = splitStatementsPattern.matcher(line); Matcher endDelimiterPatternMatcher = endDelimiterPattern.matcher(line); Matcher runOnChangePatternMatcher = runOnChangePattern.matcher(line); Matcher runAlwaysPatternMatcher = runAlwaysPattern.matcher(line); Matcher contextPatternMatcher = contextPattern.matcher(line); Matcher runInTransactionPatternMatcher = runInTransactionPattern.matcher(line); Matcher dbmsPatternMatcher = dbmsPattern.matcher(line); Matcher failOnErrorPatternMatcher = failOnErrorPattern.matcher(line); boolean stripComments = parseBoolean(stripCommentsPatternMatcher, changeSet, true); boolean splitStatements = parseBoolean(splitStatementsPatternMatcher, changeSet, true); boolean runOnChange = parseBoolean(runOnChangePatternMatcher, changeSet, false); boolean runAlways = parseBoolean(runAlwaysPatternMatcher, changeSet, false); boolean runInTransaction = parseBoolean(runInTransactionPatternMatcher, changeSet, true); boolean failOnError = parseBoolean(failOnErrorPatternMatcher, changeSet, true); String endDelimiter = parseString(endDelimiterPatternMatcher); String context = parseString(contextPatternMatcher); String dbms = parseString(dbmsPatternMatcher); changeSet = new ChangeSet(changeSetPatternMatcher.group(2), changeSetPatternMatcher.group(1), runAlways, runOnChange, physicalChangeLogLocation, context, dbms, runInTransaction); changeSet.setFailOnError(failOnError); changeLog.addChangeSet(changeSet); change = new RawSQLChange(); change.setSql(finalCurrentSql); change.setResourceAccessor(resourceAccessor); change.setSplitStatements(splitStatements); change.setStripComments(stripComments); change.setEndDelimiter(endDelimiter); changeSet.addChange(change); currentSql = new StringBuffer(); currentRollbackSql = new StringBuffer(); } else { if (changeSet != null) { Matcher rollbackMatcher = rollbackPattern.matcher(line); Matcher preconditionsMatcher = preconditionsPattern.matcher(line); Matcher preconditionMatcher = preconditionPattern.matcher(line); if (rollbackMatcher.matches()) { if (rollbackMatcher.groupCount() == 1) { currentRollbackSql.append(rollbackMatcher.group(1)).append("\n"); } } else if (preconditionsMatcher.matches()) { if (preconditionsMatcher.groupCount() == 1) { String body = preconditionsMatcher.group(1); Matcher onFailMatcher = onFailPattern.matcher(body); Matcher onErrorMatcher = onErrorPattern.matcher(body); Matcher onUpdateSqlMatcher = onUpdateSqlPattern.matcher(body); PreconditionContainer pc = new PreconditionContainer(); pc.setOnFail(StringUtils.trimToNull(parseString(onFailMatcher))); pc.setOnError(StringUtils.trimToNull(parseString(onErrorMatcher))); pc.setOnSqlOutput(StringUtils.trimToNull(parseString(onUpdateSqlMatcher))); changeSet.setPreconditions(pc); } } else if (preconditionMatcher.matches()) { if (changeSet.getPreconditions() == null) { changeSet.setPreconditions(new PreconditionContainer()); } if (preconditionMatcher.groupCount() == 2) { String name = StringUtils.trimToNull(preconditionMatcher.group(1)); if (name != null) { String body = preconditionMatcher.group(2).trim(); if ("sql-check".equals(name)) { changeSet.getPreconditions().addNestedPrecondition(parseSqlCheckCondition(body)); } else { throw new ChangeLogParseException("The '" + name + "' precondition type is not supported."); } } } } else { currentSql.append(line).append("\n"); } } } } if (changeSet != null) { change.setSql(changeLogParameters.expandExpressions(StringUtils.trimToNull(currentSql.toString()))); if (StringUtils.trimToNull(currentRollbackSql.toString()) != null) { try { if (currentRollbackSql.toString().trim().toLowerCase().matches("^not required.*")) { changeSet.addRollbackChange(new EmptyChange()); } else { RawSQLChange rollbackChange = new RawSQLChange(); rollbackChange.setSql(changeLogParameters.expandExpressions(currentRollbackSql.toString())); changeSet.addRollbackChange(rollbackChange); } } catch (UnsupportedChangeException e) { throw new RuntimeException(e); } } } } catch (IOException e) { throw new ChangeLogParseException(e); } finally { if (reader != null) { try { reader.close(); } catch (IOException ignore) { } } } return changeLog; } boolean supports(String changeLogFile, ResourceAccessor resourceAccessor); int getPriority(); DatabaseChangeLog parse(String physicalChangeLogLocation, ChangeLogParameters changeLogParameters, ResourceAccessor resourceAccessor); } | @Test(expected = ChangeLogParseException.class) public void invalidPrecondition() throws Exception{ new MockFormattedSqlChangeLogParser(INVALID_CHANGELOG_INVALID_PRECONDITION).parse("asdf.sql", new ChangeLogParameters(), new JUnitResourceAccessor()); }
@Test public void parse() throws Exception { ChangeLogParameters params = new ChangeLogParameters(); params.set("tablename", "table4"); DatabaseChangeLog changeLog = new MockFormattedSqlChangeLogParser(VALID_CHANGELOG).parse("asdf.sql", params, new JUnitResourceAccessor()); assertEquals("asdf.sql", changeLog.getLogicalFilePath()); assertEquals(8, changeLog.getChangeSets().size()); assertEquals("nvoxland", changeLog.getChangeSets().get(0).getAuthor()); assertEquals("1", changeLog.getChangeSets().get(0).getId()); assertEquals(1, changeLog.getChangeSets().get(0).getChanges().size()); assertEquals("select * from table1;", ((RawSQLChange) changeLog.getChangeSets().get(0).getChanges().get(0)).getSql()); assertNull(((RawSQLChange) changeLog.getChangeSets().get(0).getChanges().get(0)).getEndDelimiter()); assertTrue(((RawSQLChange) changeLog.getChangeSets().get(0).getChanges().get(0)).isSplittingStatements()); assertTrue(((RawSQLChange) changeLog.getChangeSets().get(0).getChanges().get(0)).isStrippingComments()); assertFalse(changeLog.getChangeSets().get(0).isAlwaysRun()); assertFalse(changeLog.getChangeSets().get(0).isRunOnChange()); assertTrue(changeLog.getChangeSets().get(0).isRunInTransaction()); assertNull(changeLog.getChangeSets().get(0).getContexts()); assertNull(changeLog.getChangeSets().get(0).getDbmsSet()); assertEquals("nvoxland", changeLog.getChangeSets().get(1).getAuthor()); assertEquals("2", changeLog.getChangeSets().get(1).getId()); assertEquals(1, changeLog.getChangeSets().get(1).getChanges().size()); assertEquals("create table table1 (\n" + " id int primary key\n" + ");", ((RawSQLChange) changeLog.getChangeSets().get(1).getChanges().get(0)).getSql()); assertEquals("X", ((RawSQLChange) changeLog.getChangeSets().get(1).getChanges().get(0)).getEndDelimiter()); assertFalse(((RawSQLChange) changeLog.getChangeSets().get(1).getChanges().get(0)).isSplittingStatements()); assertFalse(((RawSQLChange) changeLog.getChangeSets().get(1).getChanges().get(0)).isStrippingComments()); assertEquals("X", ((RawSQLChange) changeLog.getChangeSets().get(1).getChanges().get(0)).getEndDelimiter()); assertFalse(((RawSQLChange) changeLog.getChangeSets().get(1).getChanges().get(0)).isSplittingStatements()); assertFalse(((RawSQLChange) changeLog.getChangeSets().get(1).getChanges().get(0)).isStrippingComments()); assertTrue(changeLog.getChangeSets().get(1).isAlwaysRun()); assertTrue(changeLog.getChangeSets().get(1).isRunOnChange()); assertFalse(changeLog.getChangeSets().get(1).isRunInTransaction()); assertEquals("y", StringUtils.join(changeLog.getChangeSets().get(1).getContexts(), ",")); assertEquals("mysql", StringUtils.join(changeLog.getChangeSets().get(1).getDbmsSet(), ",")); assertEquals(1, changeLog.getChangeSets().get(1).getRollBackChanges().length); assertEquals("delete from table1;\n" + "drop table table1;", ((RawSQLChange) changeLog.getChangeSets().get(1).getRollBackChanges()[0]).getSql()); assertEquals("nvoxland", changeLog.getChangeSets().get(2).getAuthor()); assertEquals("3", changeLog.getChangeSets().get(2).getId()); assertEquals(1, changeLog.getChangeSets().get(2).getChanges().size()); assertEquals("create table table2 (\n" + " id int primary key\n" + ");\n" + "create table table3 (\n" + " id int primary key\n" + ");", ((RawSQLChange) changeLog.getChangeSets().get(2).getChanges().get(0)).getSql()); assertNull(((RawSQLChange) changeLog.getChangeSets().get(2).getChanges().get(0)).getEndDelimiter()); assertTrue(((RawSQLChange) changeLog.getChangeSets().get(2).getChanges().get(0)).isSplittingStatements()); assertTrue(((RawSQLChange) changeLog.getChangeSets().get(2).getChanges().get(0)).isStrippingComments()); assertEquals(1, changeLog.getChangeSets().get(2).getRollBackChanges().length); assertTrue(changeLog.getChangeSets().get(2).getRollBackChanges()[0] instanceof RawSQLChange); assertEquals("drop table table2;", ((RawSQLChange) changeLog.getChangeSets().get(2).getRollBackChanges()[0]).getSql()); assertEquals("alwyn", changeLog.getChangeSets().get(3).getAuthor()); assertEquals("4", changeLog.getChangeSets().get(3).getId()); assertEquals(1, changeLog.getChangeSets().get(3).getRollBackChanges().length); assertTrue(changeLog.getChangeSets().get(3).getRollBackChanges()[0] instanceof EmptyChange); assertEquals("nvoxland", changeLog.getChangeSets().get(4).getAuthor()); assertEquals("5", changeLog.getChangeSets().get(4).getId()); assertEquals(1, changeLog.getChangeSets().get(4).getRollBackChanges().length); assertTrue(changeLog.getChangeSets().get(4).getRollBackChanges()[0] instanceof EmptyChange); assertEquals("paikens", changeLog.getChangeSets().get(5).getAuthor()); assertEquals("6", changeLog.getChangeSets().get(5).getId()); assertEquals(1, changeLog.getChangeSets().get(5).getChanges().size()); assertTrue(changeLog.getChangeSets().get(5).getChanges().get(0) instanceof RawSQLChange); assertEquals("create table table4 (\n" + " id int primary key\n" + ");", ((RawSQLChange) changeLog.getChangeSets().get(5).getChanges().get(0)).getSql()); assertEquals(1, changeLog.getChangeSets().get(5).getRollBackChanges().length); assertTrue(changeLog.getChangeSets().get(5).getRollBackChanges()[0] instanceof RawSQLChange); assertEquals("drop table table4;", ((RawSQLChange) changeLog.getChangeSets().get(5).getRollBackChanges()[0]).getSql()); assertEquals("mysql", changeLog.getChangeSets().get(6).getAuthor()); assertEquals("1", changeLog.getChangeSets().get(6).getId()); assertEquals(1, changeLog.getChangeSets().get(6).getChanges().size()); assertTrue(changeLog.getChangeSets().get(6).getChanges().get(0) instanceof RawSQLChange); assertEquals("create table mysql_boo (\n" + " id int primary key\n" + ");", ((RawSQLChange) changeLog.getChangeSets().get(6).getChanges().get(0)).getSql()); assertEquals(1, changeLog.getChangeSets().get(6).getRollBackChanges().length); assertTrue(changeLog.getChangeSets().get(6).getRollBackChanges()[0] instanceof RawSQLChange); assertEquals("drop table mysql_boo;", ((RawSQLChange) changeLog.getChangeSets().get(6).getRollBackChanges()[0]).getSql()); ChangeSet cs = changeLog.getChangeSets().get(7); assertEquals("bboisvert", cs.getAuthor()); assertEquals("with_preconditions", cs.getId()); PreconditionContainer pc = cs.getPreconditions(); assertNotNull(pc); assertEquals(PreconditionContainer.FailOption.MARK_RAN, pc.getOnFail()); assertEquals(PreconditionContainer.ErrorOption.HALT, pc.getOnError()); assertEquals(PreconditionContainer.OnSqlOutputOption.FAIL, pc.getOnSqlOutput()); assertEquals(2, pc.getNestedPreconditions().size()); assertTrue(pc.getNestedPreconditions().get(0) instanceof SqlPrecondition); SqlPrecondition p0 = (SqlPrecondition) pc.getNestedPreconditions().get(0); assertEquals("0 table(s)", p0.getExpectedResult()); assertEquals("select count(*) || ' table(s)' from information_schema.tables where table_name = 'my_table'", p0.getSql()); assertTrue(pc.getNestedPreconditions().get(1) instanceof SqlPrecondition); SqlPrecondition p1 = (SqlPrecondition) pc.getNestedPreconditions().get(1); assertEquals("0", p1.getExpectedResult()); assertEquals("select count(*) from information_schema.columns where table_name = 'my_table' and column_name = 'id'", p1.getSql()); assertEquals(1, cs.getChanges().size()); assertTrue(cs.getChanges().get(0) instanceof RawSQLChange); assertEquals("create table my_table (\n" + " id int primary key\n" + ");", ((RawSQLChange) cs.getChanges().get(0)).getSql()); assertEquals(1, cs.getRollBackChanges().length); assertTrue(cs.getRollBackChanges()[0] instanceof RawSQLChange); assertEquals("drop table my_table;", ((RawSQLChange) cs.getRollBackChanges()[0]).getSql()); } |
ChangeLogParserFactory { public static ChangeLogParserFactory getInstance() { if (instance == null) { instance = new ChangeLogParserFactory(); } return instance; } private ChangeLogParserFactory(); static void reset(); static ChangeLogParserFactory getInstance(); List<ChangeLogParser> getParsers(); ChangeLogParser getParser(String fileNameOrExtension, ResourceAccessor resourceAccessor); void register(ChangeLogParser changeLogParser); void unregister(ChangeLogParser changeLogParser); } | @Test public void getInstance() { assertNotNull(ChangeLogParserFactory.getInstance()); assertTrue(ChangeLogParserFactory.getInstance() == ChangeLogParserFactory.getInstance()); } |
ChangeLogParserFactory { public void register(ChangeLogParser changeLogParser) { parsers.add(changeLogParser); Collections.sort(parsers, changelogParserComparator); } private ChangeLogParserFactory(); static void reset(); static ChangeLogParserFactory getInstance(); List<ChangeLogParser> getParsers(); ChangeLogParser getParser(String fileNameOrExtension, ResourceAccessor resourceAccessor); void register(ChangeLogParser changeLogParser); void unregister(ChangeLogParser changeLogParser); } | @Test public void register() { ChangeLogParserFactory.getInstance().getParsers().clear(); assertEquals(0, ChangeLogParserFactory.getInstance().getParsers().size()); ChangeLogParserFactory.getInstance().register(new MockChangeLogParser("mock")); assertEquals(1, ChangeLogParserFactory.getInstance().getParsers().size()); } |
CacheDatabase extends AbstractDatabase { @Override public boolean supportsSequences() { return false; } String getCurrentDateTimeFunction(); String getDefaultDriver(String url); int getPriority(); String getTypeName(); boolean isCorrectDatabaseImplementation(DatabaseConnection conn); boolean supportsInitiallyDeferrableColumns(); @Override String getLineComment(); @Override boolean supportsSequences(); boolean supportsTablespaces(); @Override boolean supportsAutoIncrement(); @Override String getViewDefinition(String schemaName, String viewName); static final String PRODUCT_NAME; } | @Test public void supportsSequences() { assertFalse(database.supportsSequences()); } |
ChangeLogParserFactory { public static void reset() { instance = new ChangeLogParserFactory(); } private ChangeLogParserFactory(); static void reset(); static ChangeLogParserFactory getInstance(); List<ChangeLogParser> getParsers(); ChangeLogParser getParser(String fileNameOrExtension, ResourceAccessor resourceAccessor); void register(ChangeLogParser changeLogParser); void unregister(ChangeLogParser changeLogParser); } | @Test public void reset() { ChangeLogParserFactory instance1 = ChangeLogParserFactory.getInstance(); ChangeLogParserFactory.reset(); assertFalse(instance1 == ChangeLogParserFactory.getInstance()); } |
ChangeLogParserFactory { public List<ChangeLogParser> getParsers() { return parsers; } private ChangeLogParserFactory(); static void reset(); static ChangeLogParserFactory getInstance(); List<ChangeLogParser> getParsers(); ChangeLogParser getParser(String fileNameOrExtension, ResourceAccessor resourceAccessor); void register(ChangeLogParser changeLogParser); void unregister(ChangeLogParser changeLogParser); } | @Test public void getParsers() throws Exception { ChangeLogParser parser = ChangeLogParserFactory.getInstance().getParser("asdf.xml", new JUnitResourceAccessor()); assertNotNull(parser); assertTrue(parser instanceof XMLChangeLogSAXParser); } |
ServiceLocator { public static void reset() { instance = new ServiceLocator(); } protected ServiceLocator(); protected ServiceLocator(ResourceAccessor accessor); protected ServiceLocator(PackageScanClassResolver classResolver); protected ServiceLocator(PackageScanClassResolver classResolver, ResourceAccessor accessor); static ServiceLocator getInstance(); static void setInstance(ServiceLocator newInstance); void setResourceAccessor(ResourceAccessor resourceAccessor); void addPackageToScan(String packageName); Class findClass(Class requiredInterface); Class[] findClasses(Class requiredInterface); Object newInstance(Class requiredInterface); static void reset(); } | @Test public void reset() { ServiceLocator instance1 = ServiceLocator.getInstance(); ServiceLocator.reset(); assertFalse(instance1 == ServiceLocator.getInstance()); } |
ServiceLocator { public Class[] findClasses(Class requiredInterface) throws ServiceNotFoundException { logger.debug("ServiceLocator.findClasses for "+requiredInterface.getName()); try { Class.forName(requiredInterface.getName()); if (!classesBySuperclass.containsKey(requiredInterface)) { classesBySuperclass.put(requiredInterface, findClassesImpl(requiredInterface)); } } catch (Exception e) { throw new ServiceNotFoundException(e); } List<Class> classes = classesBySuperclass.get(requiredInterface); HashSet<Class> uniqueClasses = new HashSet<Class>(classes); return uniqueClasses.toArray(new Class[uniqueClasses.size()]); } protected ServiceLocator(); protected ServiceLocator(ResourceAccessor accessor); protected ServiceLocator(PackageScanClassResolver classResolver); protected ServiceLocator(PackageScanClassResolver classResolver, ResourceAccessor accessor); static ServiceLocator getInstance(); static void setInstance(ServiceLocator newInstance); void setResourceAccessor(ResourceAccessor resourceAccessor); void addPackageToScan(String packageName); Class findClass(Class requiredInterface); Class[] findClasses(Class requiredInterface); Object newInstance(Class requiredInterface); static void reset(); } | @Test public void getClasses() throws Exception { Class[] classes = serviceLocator.findClasses(ChangeLogParser.class); assertTrue(classes.length > 0); } |
ServiceLocator { public Class findClass(Class requiredInterface) throws ServiceNotFoundException { if (requiredInterface == Logger.class ) { return DefaultLogger.class; } else if ( requiredInterface == Executor.class ) { return JdbcExecutor.class; } else { throw new ServiceNotFoundException("Could not find implementation of " + requiredInterface.getName()); } } protected ServiceLocator(); protected ServiceLocator(ResourceAccessor accessor); protected ServiceLocator(PackageScanClassResolver classResolver); protected ServiceLocator(PackageScanClassResolver classResolver, ResourceAccessor accessor); static ServiceLocator getInstance(); static void setInstance(ServiceLocator newInstance); void setResourceAccessor(ResourceAccessor resourceAccessor); void addPackageToScan(String packageName); Class findClass(Class requiredInterface); Class[] findClasses(Class requiredInterface); Object newInstance(Class requiredInterface); static void reset(); } | @Test public void findClass() throws Exception { Class[] classes = serviceLocator.findClasses(Database.class); for (Class clazz : classes) { assertFalse(clazz.getName()+" is abstract", Modifier.isAbstract(clazz.getModifiers())); assertFalse(clazz.getName()+" is an interface", Modifier.isInterface(clazz.getModifiers())); assertNotNull(clazz.getConstructors()); } assertTrue(classes.length > 0); } |
LockService { public static LockService getInstance(Database database) { if (!instances.containsKey(database)) { instances.put(database, new LockService(database)); } return instances.get(database); } private LockService(Database database); static LockService getInstance(Database database); void setChangeLogLockWaitTime(long changeLogLockWaitTime); void setChangeLogLockRecheckTime(long changeLogLocRecheckTime); boolean hasChangeLogLock(); void waitForLock(); boolean acquireLock(); void releaseLock(); DatabaseChangeLogLock[] listLocks(); void forceReleaseLock(); void reset(); static void resetAll(); } | @Test public void getInstance() { final Database oracle1 = new OracleDatabase() { @Override public boolean equals(Object o) { return o == this; } }; final Database oracle2 = new OracleDatabase() { @Override public boolean equals(Object o) { return o == this; } }; final Database mysql = new MySQLDatabase() { @Override public boolean equals(Object o) { return o == this; } }; assertNotNull(LockService.getInstance(oracle1)); assertNotNull(LockService.getInstance(oracle2)); assertNotNull(LockService.getInstance(mysql)); assertTrue(LockService.getInstance(oracle1) == LockService.getInstance(oracle1)); assertTrue(LockService.getInstance(oracle2) == LockService.getInstance(oracle2)); assertTrue(LockService.getInstance(mysql) == LockService.getInstance(mysql)); assertTrue(LockService.getInstance(oracle1) != LockService.getInstance(oracle2)); assertTrue(LockService.getInstance(oracle1) != LockService.getInstance(mysql)); } |
CacheDatabase extends AbstractDatabase { @Override public String getLineComment() { return "--"; } String getCurrentDateTimeFunction(); String getDefaultDriver(String url); int getPriority(); String getTypeName(); boolean isCorrectDatabaseImplementation(DatabaseConnection conn); boolean supportsInitiallyDeferrableColumns(); @Override String getLineComment(); @Override boolean supportsSequences(); boolean supportsTablespaces(); @Override boolean supportsAutoIncrement(); @Override String getViewDefinition(String schemaName, String viewName); static final String PRODUCT_NAME; } | @Test public void getLineComment() { Assert.assertEquals("--", database.getLineComment()); } |
CacheDatabase extends AbstractDatabase { public String getDefaultDriver(String url) { if (url.startsWith("jdbc:Cache")) { return "com.intersys.jdbc.CacheDriver"; } return null; } String getCurrentDateTimeFunction(); String getDefaultDriver(String url); int getPriority(); String getTypeName(); boolean isCorrectDatabaseImplementation(DatabaseConnection conn); boolean supportsInitiallyDeferrableColumns(); @Override String getLineComment(); @Override boolean supportsSequences(); boolean supportsTablespaces(); @Override boolean supportsAutoIncrement(); @Override String getViewDefinition(String schemaName, String viewName); static final String PRODUCT_NAME; } | @Test public void getDefaultDriver() { Assert.assertEquals("com.intersys.jdbc.CacheDriver", database.getDefaultDriver("jdbc:Cache: } |
CacheDatabase extends AbstractDatabase { public String getTypeName() { return "cache"; } String getCurrentDateTimeFunction(); String getDefaultDriver(String url); int getPriority(); String getTypeName(); boolean isCorrectDatabaseImplementation(DatabaseConnection conn); boolean supportsInitiallyDeferrableColumns(); @Override String getLineComment(); @Override boolean supportsSequences(); boolean supportsTablespaces(); @Override boolean supportsAutoIncrement(); @Override String getViewDefinition(String schemaName, String viewName); static final String PRODUCT_NAME; } | @Test public void getTypeName() { Assert.assertEquals("cache", database.getTypeName()); } |
CacheDatabase extends AbstractDatabase { public String getCurrentDateTimeFunction() { if (currentDateTimeFunction != null) { return currentDateTimeFunction; } return "SYSDATE"; } String getCurrentDateTimeFunction(); String getDefaultDriver(String url); int getPriority(); String getTypeName(); boolean isCorrectDatabaseImplementation(DatabaseConnection conn); boolean supportsInitiallyDeferrableColumns(); @Override String getLineComment(); @Override boolean supportsSequences(); boolean supportsTablespaces(); @Override boolean supportsAutoIncrement(); @Override String getViewDefinition(String schemaName, String viewName); static final String PRODUCT_NAME; } | @Override @Test public void getCurrentDateTimeFunction() { Assert.assertEquals("SYSDATE", database.getCurrentDateTimeFunction()); } |
CacheDatabase extends AbstractDatabase { public boolean supportsInitiallyDeferrableColumns() { return false; } String getCurrentDateTimeFunction(); String getDefaultDriver(String url); int getPriority(); String getTypeName(); boolean isCorrectDatabaseImplementation(DatabaseConnection conn); boolean supportsInitiallyDeferrableColumns(); @Override String getLineComment(); @Override boolean supportsSequences(); boolean supportsTablespaces(); @Override boolean supportsAutoIncrement(); @Override String getViewDefinition(String schemaName, String viewName); static final String PRODUCT_NAME; } | @Override @Test public void supportsInitiallyDeferrableColumns() { assertFalse(database.supportsInitiallyDeferrableColumns()); } |
PostgresDatabase extends AbstractDatabase { public boolean supportsInitiallyDeferrableColumns() { return true; } PostgresDatabase(); @Override void setConnection(DatabaseConnection conn); String getTypeName(); @Override Set<String> getSystemTablesAndViews(); int getPriority(); boolean supportsInitiallyDeferrableColumns(); boolean isCorrectDatabaseImplementation(DatabaseConnection conn); String getDefaultDriver(String url); @Override boolean supportsSequences(); String getCurrentDateTimeFunction(); @Override String getDefaultCatalogName(); @Override String getDatabaseChangeLogTableName(); @Override String getDatabaseChangeLogLockTableName(); @Override boolean isSystemTable(String catalogName, String schemaName, String tableName); boolean supportsTablespaces(); @Override String getAutoIncrementClause(); @Override boolean generateAutoIncrementStartWith(BigInteger startWith); @Override boolean generateAutoIncrementBy(BigInteger incrementBy); @Override String convertRequestedSchemaToSchema(String requestedSchema); @Override String convertRequestedSchemaToCatalog(String requestedSchema); @Override String escapeDatabaseObject(String objectName); @Override boolean isReservedWord(String tableName); @Override String escapeIndexName(String schemaName, String indexName); static final String PRODUCT_NAME; } | @Override @Test public void supportsInitiallyDeferrableColumns() { assertTrue(getDatabase().supportsInitiallyDeferrableColumns()); } |
PostgresDatabase extends AbstractDatabase { public String getCurrentDateTimeFunction() { if (currentDateTimeFunction != null) { return currentDateTimeFunction; } return "NOW()"; } PostgresDatabase(); @Override void setConnection(DatabaseConnection conn); String getTypeName(); @Override Set<String> getSystemTablesAndViews(); int getPriority(); boolean supportsInitiallyDeferrableColumns(); boolean isCorrectDatabaseImplementation(DatabaseConnection conn); String getDefaultDriver(String url); @Override boolean supportsSequences(); String getCurrentDateTimeFunction(); @Override String getDefaultCatalogName(); @Override String getDatabaseChangeLogTableName(); @Override String getDatabaseChangeLogLockTableName(); @Override boolean isSystemTable(String catalogName, String schemaName, String tableName); boolean supportsTablespaces(); @Override String getAutoIncrementClause(); @Override boolean generateAutoIncrementStartWith(BigInteger startWith); @Override boolean generateAutoIncrementBy(BigInteger incrementBy); @Override String convertRequestedSchemaToSchema(String requestedSchema); @Override String convertRequestedSchemaToCatalog(String requestedSchema); @Override String escapeDatabaseObject(String objectName); @Override boolean isReservedWord(String tableName); @Override String escapeIndexName(String schemaName, String indexName); static final String PRODUCT_NAME; } | @Override @Test public void getCurrentDateTimeFunction() { Assert.assertEquals("NOW()", getDatabase().getCurrentDateTimeFunction()); } |
OracleDatabase extends AbstractDatabase { public boolean supportsInitiallyDeferrableColumns() { return true; } OracleDatabase(); int getPriority(); @Override void setConnection(DatabaseConnection conn); String getTypeName(); @Override String generatePrimaryKeyName(String tableName); boolean supportsInitiallyDeferrableColumns(); @Override String escapeDatabaseObject(String objectName); @Override boolean isReservedWord(String objectName); @Override boolean supportsSequences(); boolean isCorrectDatabaseImplementation(DatabaseConnection conn); String getDefaultDriver(String url); String getCurrentDateTimeFunction(); @Override String escapeIndexName(String schemaName, String indexName); @Override String getDateLiteral(String isoDate); @Override boolean isSystemTable(String catalogName, String schemaName, String tableName); @Override boolean shouldQuoteValue(String value); boolean supportsTablespaces(); @Override boolean supportsAutoIncrement(); @Override boolean supportsRestrictForeignKeys(); static final String PRODUCT_NAME; } | @Override @Test public void supportsInitiallyDeferrableColumns() { assertTrue(getDatabase().supportsInitiallyDeferrableColumns()); } |
OracleDatabase extends AbstractDatabase { public String getCurrentDateTimeFunction() { if (currentDateTimeFunction != null) { return currentDateTimeFunction; } return "SYSTIMESTAMP"; } OracleDatabase(); int getPriority(); @Override void setConnection(DatabaseConnection conn); String getTypeName(); @Override String generatePrimaryKeyName(String tableName); boolean supportsInitiallyDeferrableColumns(); @Override String escapeDatabaseObject(String objectName); @Override boolean isReservedWord(String objectName); @Override boolean supportsSequences(); boolean isCorrectDatabaseImplementation(DatabaseConnection conn); String getDefaultDriver(String url); String getCurrentDateTimeFunction(); @Override String escapeIndexName(String schemaName, String indexName); @Override String getDateLiteral(String isoDate); @Override boolean isSystemTable(String catalogName, String schemaName, String tableName); @Override boolean shouldQuoteValue(String value); boolean supportsTablespaces(); @Override boolean supportsAutoIncrement(); @Override boolean supportsRestrictForeignKeys(); static final String PRODUCT_NAME; } | @Override @Test public void getCurrentDateTimeFunction() { Assert.assertEquals("SYSTIMESTAMP", getDatabase().getCurrentDateTimeFunction()); } |
SybaseDatabase extends AbstractDatabase { boolean isSybaseProductName(String dbProductName) { return "Adaptive Server Enterprise".equals(dbProductName) || "Sybase SQL Server".equals(dbProductName) || "sql server".equals(dbProductName) || "ASE".equals(dbProductName); } SybaseDatabase(); String getProductName(); String getTypeName(); int getPriority(); @Override boolean supportsDDLInTransaction(); @Override Set<String> getSystemTablesAndViews(); boolean supportsInitiallyDeferrableColumns(); @Override boolean supportsSequences(); boolean isCorrectDatabaseImplementation(DatabaseConnection conn); String getDefaultDriver(String url); String getCurrentDateTimeFunction(); @Override String getDefaultCatalogName(); @Override String getConcatSql(String... values); boolean supportsTablespaces(); @Override boolean isSystemTable(String catalogName, String schemaName, String tableName); @Override boolean isSystemView(String catalogName, String schemaName, String viewName); String generateDefaultConstraintName(String tableName, String columnName); @Override String convertRequestedSchemaToCatalog(String requestedSchema); @Override String convertRequestedSchemaToSchema(String requestedSchema); @Override boolean supportsRestrictForeignKeys(); @Override String escapeDatabaseObject(String objectName); @Override String getViewDefinition(String schemaName, String viewName); @Override int getDatabaseMajorVersion(); @Override int getDatabaseMinorVersion(); @Override String escapeIndexName(String schemaName, String indexName); static final String PRODUCT_NAME; } | @Test public void testIsSybaseProductName() { SybaseDatabase database = new SybaseDatabase(); assertTrue("Sybase SQL Server is a valid product name", database.isSybaseProductName("Sybase SQL Server")); assertTrue("sql server is a valid product name", database.isSybaseProductName("sql server")); assertTrue("ASE is a valid product name", database.isSybaseProductName("ASE")); assertTrue("Adaptive Server Enterprise is a valid product name", database.isSybaseProductName("Adaptive Server Enterprise")); } |
SybaseDatabase extends AbstractDatabase { @Override public String getViewDefinition(String schemaName, String viewName) throws DatabaseException { GetViewDefinitionStatement statement = new GetViewDefinitionStatement(convertRequestedSchemaToSchema(schemaName), viewName); Executor executor = ExecutorService.getInstance().getExecutor(this); @SuppressWarnings("unchecked") List<String> definitionRows = (List<String>) executor.queryForList(statement, String.class); StringBuilder definition = new StringBuilder(); for (String d : definitionRows) { definition.append(d); } return definition.toString(); } SybaseDatabase(); String getProductName(); String getTypeName(); int getPriority(); @Override boolean supportsDDLInTransaction(); @Override Set<String> getSystemTablesAndViews(); boolean supportsInitiallyDeferrableColumns(); @Override boolean supportsSequences(); boolean isCorrectDatabaseImplementation(DatabaseConnection conn); String getDefaultDriver(String url); String getCurrentDateTimeFunction(); @Override String getDefaultCatalogName(); @Override String getConcatSql(String... values); boolean supportsTablespaces(); @Override boolean isSystemTable(String catalogName, String schemaName, String tableName); @Override boolean isSystemView(String catalogName, String schemaName, String viewName); String generateDefaultConstraintName(String tableName, String columnName); @Override String convertRequestedSchemaToCatalog(String requestedSchema); @Override String convertRequestedSchemaToSchema(String requestedSchema); @Override boolean supportsRestrictForeignKeys(); @Override String escapeDatabaseObject(String objectName); @Override String getViewDefinition(String schemaName, String viewName); @Override int getDatabaseMajorVersion(); @Override int getDatabaseMinorVersion(); @Override String escapeIndexName(String schemaName, String indexName); static final String PRODUCT_NAME; } | @Test public void testGetViewDefinitionWhenNoRows() throws Exception { SybaseDatabase database = new SybaseDatabase(); configureExecutor(database); assertEquals("", database.getViewDefinition("dbo", "view_name")); }
@Test public void testGetViewDefinitionWhenSingleRow() throws Exception { SybaseDatabase database = new SybaseDatabase(); configureExecutor(database, "foo"); assertEquals("foo", database.getViewDefinition("dbo", "view_name")); }
@Test public void testGetViewDefinitionWhenMultipleRows() throws Exception { SybaseDatabase database = new SybaseDatabase(); configureExecutor(database, "foo", " bar", " bat"); assertEquals("foo bar bat", database.getViewDefinition("dbo", "view_name")); } |