use of liquibase.database.core.AbstractDb2Database in project liquibase by liquibase.
the class CreateIndexGenerator method generateSql.
/**
* Generate a CREATE INDEX SQL statement.
* Here, we are walking on thin ice, because the SQL Foundation standard (ISO/IEC 9075-2) does not concern itself
* with indexes at all and leaves them as an implementation-specific detail at the discretion of each RDBMS vendor.
* However, there is some common ground to most RDBMS, and we try to make an educated guess on how a CREATE INDEX
* statement might look like if we have no specific handler for the DBMS.
* @param statement A CreateIndexStatement with the desired properties of the SQL to be generated
* @param database The DBMS for whose SQL dialect the statement is to be made
* @param sqlGeneratorChain The other SQL generators in the same chain (but this method is not interested in them)
* @return An array of Sql objects containing the generated SQL statement(s).
*/
@Override
public Sql[] generateSql(CreateIndexStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
if (database instanceof OracleDatabase) {
/*
* Oracle automatically creates indexes for PRIMARY KEY and UNIQUE constraints, but does not do so
* for FOREIGN KEY constraints, though it is highly recommended to do to avoid potentially severe
* performance problems when deleting rows from the parent table or changing the key column(s) in the
* parent table.
*/
List<String> associatedWith = StringUtil.splitAndTrim(statement.getAssociatedWith(), ",");
if ((associatedWith != null) && (associatedWith.contains(Index.MARK_PRIMARY_KEY) || associatedWith.contains(Index.MARK_UNIQUE_CONSTRAINT))) {
return new Sql[0];
}
} else {
// Default filter of index creation:
// creation of all indexes with associations are switched off.
List<String> associatedWith = StringUtil.splitAndTrim(statement.getAssociatedWith(), ",");
if ((associatedWith != null) && (associatedWith.contains(Index.MARK_PRIMARY_KEY) || associatedWith.contains(Index.MARK_UNIQUE_CONSTRAINT) || associatedWith.contains(Index.MARK_FOREIGN_KEY))) {
return new Sql[0];
}
}
StringBuilder buffer = new StringBuilder();
buffer.append("CREATE ");
if ((statement.isUnique() != null) && statement.isUnique()) {
buffer.append("UNIQUE ");
}
if (database instanceof MSSQLDatabase) {
if (statement.isClustered() != null) {
if (statement.isClustered()) {
buffer.append("CLUSTERED ");
} else {
buffer.append("NONCLUSTERED ");
}
}
}
buffer.append("INDEX ");
if (statement.getIndexName() != null) {
String indexSchema = statement.getTableSchemaName();
buffer.append(database.escapeIndexName(statement.getTableCatalogName(), indexSchema, statement.getIndexName())).append(" ");
}
buffer.append("ON ");
if ((database instanceof OracleDatabase) && (statement.isClustered() != null) && statement.isClustered()) {
buffer.append("CLUSTER ");
}
buffer.append(database.escapeTableName(statement.getTableCatalogName(), statement.getTableSchemaName(), statement.getTableName())).append("(");
Iterator<AddColumnConfig> iterator = Arrays.asList(statement.getColumns()).iterator();
while (iterator.hasNext()) {
AddColumnConfig column = iterator.next();
if (column.getComputed() == null) {
buffer.append(database.escapeColumnName(statement.getTableCatalogName(), statement.getTableSchemaName(), statement.getTableName(), column.getName(), false));
} else {
if (column.getComputed()) {
buffer.append(column.getName());
} else {
buffer.append(database.escapeColumnName(statement.getTableCatalogName(), statement.getTableSchemaName(), statement.getTableName(), column.getName()));
}
}
if ((column.getDescending() != null) && column.getDescending()) {
buffer.append(" DESC");
}
if (iterator.hasNext()) {
buffer.append(", ");
}
}
buffer.append(")");
if ((StringUtil.trimToNull(statement.getTablespace()) != null) && database.supportsTablespaces()) {
if ((database instanceof MSSQLDatabase) || (database instanceof SybaseASADatabase)) {
buffer.append(" ON ").append(statement.getTablespace());
} else if ((database instanceof AbstractDb2Database) || (database instanceof InformixDatabase)) {
buffer.append(" IN ").append(statement.getTablespace());
} else {
buffer.append(" TABLESPACE ").append(statement.getTablespace());
}
}
if ((database instanceof AbstractDb2Database) && (statement.isClustered() != null) && statement.isClustered()) {
buffer.append(" CLUSTER");
}
return new Sql[] { new UnparsedSql(buffer.toString(), getAffectedIndex(statement)) };
}
use of liquibase.database.core.AbstractDb2Database in project liquibase by liquibase.
the class SelectFromDatabaseChangeLogGenerator method generateSql.
@Override
public Sql[] generateSql(SelectFromDatabaseChangeLogStatement statement, final Database database, SqlGeneratorChain sqlGeneratorChain) {
List<ColumnConfig> columnsToSelect = Arrays.asList(statement.getColumnsToSelect());
// use LEGACY quoting since we're dealing with system objects
ObjectQuotingStrategy currentStrategy = database.getObjectQuotingStrategy();
database.setObjectQuotingStrategy(ObjectQuotingStrategy.LEGACY);
try {
String sql = "SELECT " + (database instanceof MSSQLDatabase && statement.getLimit() != null ? "TOP " + statement.getLimit() + " " : "") + StringUtil.join(columnsToSelect, ",", new StringUtil.StringUtilFormatter<ColumnConfig>() {
@Override
public String toString(ColumnConfig column) {
if ((column.getComputed() != null) && column.getComputed()) {
return column.getName();
} else {
return database.escapeColumnName(null, null, null, column.getName());
}
}
}).toUpperCase() + " FROM " + database.escapeTableName(database.getLiquibaseCatalogName(), database.getLiquibaseSchemaName(), database.getDatabaseChangeLogTableName());
SelectFromDatabaseChangeLogStatement.WhereClause whereClause = statement.getWhereClause();
if (whereClause != null) {
if (whereClause instanceof SelectFromDatabaseChangeLogStatement.ByTag) {
sql += " WHERE " + database.escapeColumnName(null, null, null, "TAG") + "='" + ((SelectFromDatabaseChangeLogStatement.ByTag) whereClause).getTagName() + "'";
} else if (whereClause instanceof SelectFromDatabaseChangeLogStatement.ByNotNullCheckSum) {
sql += " WHERE " + database.escapeColumnName(null, null, null, "MD5SUM") + " IS NOT NULL";
} else {
throw new UnexpectedLiquibaseException("Unknown where clause type: " + whereClause.getClass().getName());
}
}
if ((statement.getOrderByColumns() != null) && (statement.getOrderByColumns().length > 0)) {
sql += " ORDER BY ";
Iterator<String> orderBy = Arrays.asList(statement.getOrderByColumns()).iterator();
while (orderBy.hasNext()) {
String orderColumn = orderBy.next();
String[] orderColumnData = orderColumn.split(" ");
sql += database.escapeColumnName(null, null, null, orderColumnData[0]);
if (orderColumnData.length == 2) {
sql += " ";
sql += orderColumnData[1].toUpperCase();
}
if (orderBy.hasNext()) {
sql += ", ";
}
}
}
if (statement.getLimit() != null) {
if (database instanceof OracleDatabase) {
if (whereClause == null) {
sql += " WHERE ROWNUM=" + statement.getLimit();
} else {
sql += " AND ROWNUM=" + statement.getLimit();
}
} else if ((database instanceof MySQLDatabase) || (database instanceof PostgresDatabase)) {
sql += " LIMIT " + statement.getLimit();
} else if (database instanceof AbstractDb2Database) {
sql += " FETCH FIRST " + statement.getLimit() + " ROWS ONLY";
}
}
return new Sql[] { new UnparsedSql(sql) };
} finally {
database.setObjectQuotingStrategy(currentStrategy);
}
}
use of liquibase.database.core.AbstractDb2Database in project liquibase by liquibase.
the class CreateTableGenerator method generateSql.
@Override
public Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
List<Sql> additionalSql = new ArrayList<>();
StringBuilder buffer = new StringBuilder();
buffer.append("CREATE TABLE ").append(database.escapeTableName(statement.getCatalogName(), 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();
BigInteger mysqlTableOptionStartWith = null;
/* We have reached the point after "CREATE TABLE ... (" and will now iterate through the column list. */
while (columnIterator.hasNext()) {
String column = columnIterator.next();
DatabaseDataType columnType = null;
if (statement.getColumnTypes().get(column) != null) {
columnType = statement.getColumnTypes().get(column).toDatabaseDataType(database);
}
if (columnType == null) {
buffer.append(database.escapeColumnName(statement.getCatalogName(), statement.getSchemaName(), statement.getTableName(), column, false));
} else {
buffer.append(database.escapeColumnName(statement.getCatalogName(), statement.getSchemaName(), statement.getTableName(), column, !statement.isComputed(column)));
buffer.append(" ").append(columnType);
}
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 = StringUtil.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");
}
// for the serial data type in postgres, there should be no default value
if (columnType != null && !columnType.isAutoIncrement() && (statement.getDefaultValue(column) != null)) {
Object defaultValue = statement.getDefaultValue(column);
if (database instanceof MSSQLDatabase) {
String constraintName = statement.getDefaultValueConstraintName(column);
if (constraintName == null) {
constraintName = ((MSSQLDatabase) database).generateDefaultConstraintName(statement.getTableName(), column);
}
buffer.append(" CONSTRAINT ").append(database.escapeObjectName(constraintName, ForeignKey.class));
}
if (((database instanceof OracleDatabase) || (database instanceof PostgresDatabase)) && statement.getDefaultValue(column).toString().startsWith("GENERATED ALWAYS ")) {
buffer.append(" ");
} else if (database instanceof Db2zDatabase && statement.getDefaultValue(column).toString().contains("CURRENT TIMESTAMP") || statement.getDefaultValue(column).toString().contains("IDENTITY GENERATED BY DEFAULT")) {
buffer.append(" ");
} else {
buffer.append(" DEFAULT ");
}
if (defaultValue instanceof DatabaseFunction) {
buffer.append(database.generateDatabaseFunctionValue((DatabaseFunction) defaultValue));
} else if (database instanceof Db2zDatabase) {
if (statement.getDefaultValue(column).toString().contains("CURRENT TIMESTAMP")) {
buffer.append("");
}
if (statement.getDefaultValue(column).toString().contains("IDENTITY GENERATED BY DEFAULT")) {
buffer.append("GENERATED BY DEFAULT AS IDENTITY");
}
if (statement.getDefaultValue(column).toString().contains("CURRENT USER")) {
buffer.append("SESSION_USER ");
}
if (statement.getDefaultValue(column).toString().contains("CURRENT SQLID")) {
buffer.append("CURRENT SQLID ");
}
} else {
buffer.append(statement.getColumnTypes().get(column).objectToSql(defaultValue, database));
}
}
if (isAutoIncrementColumn) {
if (database instanceof PostgresDatabase && buffer.toString().toLowerCase().endsWith("serial")) {
// don't add more info
} else if (database.supportsAutoIncrement()) {
// TODO: check if database supports auto increment on non primary key column
String autoIncrementClause = database.getAutoIncrementClause(autoIncrementConstraint.getStartWith(), autoIncrementConstraint.getIncrementBy(), autoIncrementConstraint.getGenerationType(), autoIncrementConstraint.getDefaultOnNull());
if (!"".equals(autoIncrementClause)) {
buffer.append(" ").append(autoIncrementClause);
}
if (autoIncrementConstraint.getStartWith() != null) {
if (database instanceof PostgresDatabase) {
int majorVersion = 9;
try {
majorVersion = database.getDatabaseMajorVersion();
} catch (DatabaseException e) {
// ignore
}
if (majorVersion < 10) {
String sequenceName = statement.getTableName() + "_" + column + "_seq";
additionalSql.add(new UnparsedSql("alter sequence " + database.escapeSequenceName(statement.getCatalogName(), statement.getSchemaName(), sequenceName) + " start with " + autoIncrementConstraint.getStartWith(), new Sequence().setName(sequenceName).setSchema(statement.getCatalogName(), statement.getSchemaName())));
}
} else if (database instanceof MySQLDatabase) {
mysqlTableOptionStartWith = autoIncrementConstraint.getStartWith();
}
}
} else {
Scope.getCurrentScope().getLog(getClass()).warning(database.getShortName() + " does not support autoincrement columns as requested for " + (database.escapeTableName(statement.getCatalogName(), statement.getSchemaName(), statement.getTableName())));
}
}
// Do we have a NOT NULL constraint for this column?
if (statement.getNotNullColumns().get(column) != null) {
if (!database.supportsNotNullConstraintNames()) {
buffer.append(" NOT NULL");
} else {
/* Determine if the NOT NULL constraint has a name. */
NotNullConstraint nnConstraintForThisColumn = statement.getNotNullColumns().get(column);
String nncName = StringUtil.trimToNull(nnConstraintForThisColumn.getConstraintName());
if (nncName == null) {
buffer.append(" NOT NULL");
} else {
buffer.append(" CONSTRAINT ");
buffer.append(database.escapeConstraintName(nncName));
buffer.append(" NOT NULL");
}
if (!nnConstraintForThisColumn.shouldValidateNullable()) {
if (database instanceof OracleDatabase) {
buffer.append(" ENABLE NOVALIDATE ");
}
}
}
// does the DB support constraint names?
} else {
if (columnType != null && ((database instanceof SybaseDatabase) || (database instanceof SybaseASADatabase) || (database instanceof MySQLDatabase) || ((database instanceof MSSQLDatabase) && columnType.toString().toLowerCase().contains("timestamp")))) {
buffer.append(" NULL");
}
// Do we need to specify NULL explicitly?
}
if ((database instanceof MySQLDatabase) && (statement.getColumnRemarks(column) != null)) {
buffer.append(" COMMENT '" + database.escapeStringForDatabase(statement.getColumnRemarks(column)) + "'");
}
if (columnIterator.hasNext()) {
buffer.append(", ");
}
}
buffer.append(",");
if (!((database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyAutoIncrement)) {
if ((statement.getPrimaryKeyConstraint() != null) && !statement.getPrimaryKeyConstraint().getColumns().isEmpty()) {
if (database.supportsPrimaryKeyNames()) {
String pkName = StringUtil.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName());
if (pkName == null) {
// TODO ORA-00972: identifier is too long
// If tableName lenght is more then 28 symbols
// then generated pkName will be incorrect
pkName = database.generatePrimaryKeyName(statement.getTableName());
}
if (pkName != null) {
buffer.append(" CONSTRAINT ");
buffer.append(database.escapeConstraintName(pkName));
}
}
buffer.append(" PRIMARY KEY (");
buffer.append(database.escapeColumnNameList(StringUtil.join(statement.getPrimaryKeyConstraint().getColumns(), ", ")));
buffer.append(")");
// Setting up table space for PK's index if it exist
if (((database instanceof OracleDatabase) || (database instanceof PostgresDatabase)) && (statement.getPrimaryKeyConstraint().getTablespace() != null)) {
buffer.append(" USING INDEX TABLESPACE ");
buffer.append(statement.getPrimaryKeyConstraint().getTablespace());
}
buffer.append(!statement.getPrimaryKeyConstraint().shouldValidatePrimaryKey() ? " ENABLE NOVALIDATE " : "");
if (database.supportsInitiallyDeferrableColumns()) {
if (statement.getPrimaryKeyConstraint().isInitiallyDeferred()) {
buffer.append(" INITIALLY DEFERRED");
}
if (statement.getPrimaryKeyConstraint().isDeferrable()) {
buffer.append(" DEFERRABLE");
}
}
buffer.append(",");
}
}
for (ForeignKeyConstraint fkConstraint : statement.getForeignKeyConstraints()) {
if (!(database instanceof InformixDatabase)) {
buffer.append(" CONSTRAINT ");
buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName()));
}
String referencesString = fkConstraint.getReferences();
buffer.append(" FOREIGN KEY (").append(database.escapeColumnName(statement.getCatalogName(), statement.getSchemaName(), statement.getTableName(), fkConstraint.getColumn())).append(") REFERENCES ");
if (referencesString != null) {
if (!referencesString.contains(".") && (database.getDefaultSchemaName() != null) && database.getOutputDefaultSchema()) {
referencesString = database.escapeObjectName(database.getDefaultSchemaName(), Schema.class) + "." + referencesString;
}
buffer.append(referencesString);
} else {
buffer.append(database.escapeObjectName(fkConstraint.getReferencedTableCatalogName(), fkConstraint.getReferencedTableSchemaName(), fkConstraint.getReferencedTableName(), Table.class)).append("(").append(database.escapeColumnNameList(fkConstraint.getReferencedColumnNames())).append(")");
}
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");
}
if (database instanceof OracleDatabase) {
buffer.append(!fkConstraint.shouldValidateForeignKey() ? " ENABLE NOVALIDATE " : "");
}
buffer.append(",");
}
/*
* In the current syntax, UNIQUE constraints can only be set per column on table creation.
* To alleviate this problem we combine the columns of unique constraints that have the same name.
*/
LinkedHashMap<String, UniqueConstraint> namedUniqueConstraints = new LinkedHashMap<>();
List<UniqueConstraint> unnamedUniqueConstraints = new LinkedList<>();
for (UniqueConstraint uniqueConstraint : statement.getUniqueConstraints()) {
if (uniqueConstraint.getConstraintName() == null) {
// Only combine uniqueConstraints that have a name.
unnamedUniqueConstraints.add(uniqueConstraint);
} else {
String constraintName = uniqueConstraint.getConstraintName();
UniqueConstraint existingConstraint = namedUniqueConstraints.get(constraintName);
if (existingConstraint != null) {
if (uniqueConstraint.shouldValidateUnique()) {
// if validateUnique = true on only one column, make sure it is true
existingConstraint.setValidateUnique(true);
}
existingConstraint.getColumns().addAll(uniqueConstraint.getColumns());
} else {
// if we haven't seen the constraint before put it in the map.
namedUniqueConstraints.put(constraintName, uniqueConstraint);
}
}
}
unnamedUniqueConstraints.addAll(namedUniqueConstraints.values());
for (UniqueConstraint uniqueConstraint : unnamedUniqueConstraints) {
if (uniqueConstraint.getConstraintName() != null) {
buffer.append(" CONSTRAINT ");
buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName()));
}
buffer.append(" UNIQUE (");
buffer.append(database.escapeColumnNameList(StringUtil.join(uniqueConstraint.getColumns(), ", ")));
buffer.append(")");
if (database instanceof OracleDatabase) {
buffer.append(!uniqueConstraint.shouldValidateUnique() ? " ENABLE NOVALIDATE " : "");
}
buffer.append(",");
}
/*
* Here, the list of columns and constraints in the form
* ( column1, ..., columnN, constraint1, ..., constraintN,
* ends. We cannot leave an expression like ", )", so we remove the last comma.
*/
String sql = buffer.toString().replaceFirst(",\\s*$", "") + ")";
if ((database instanceof MySQLDatabase) && (mysqlTableOptionStartWith != null)) {
Scope.getCurrentScope().getLog(getClass()).info("[MySQL] Using last startWith statement (" + mysqlTableOptionStartWith.toString() + ") as table option.");
sql += " " + ((MySQLDatabase) database).getTableOptionAutoIncrementStartWithClause(mysqlTableOptionStartWith);
}
if ((statement.getTablespace() != null) && database.supportsTablespaces()) {
if ((database instanceof MSSQLDatabase) || (database instanceof SybaseASADatabase)) {
sql += " ON " + statement.getTablespace();
} else if ((database instanceof AbstractDb2Database) || (database instanceof InformixDatabase)) {
sql += " IN " + statement.getTablespace();
} else {
sql += " TABLESPACE " + statement.getTablespace();
}
}
if ((database instanceof MySQLDatabase) && (statement.getRemarks() != null)) {
sql += " COMMENT='" + database.escapeStringForDatabase(statement.getRemarks()) + "' ";
}
additionalSql.add(0, new UnparsedSql(sql, getAffectedTable(statement)));
return additionalSql.toArray(new Sql[additionalSql.size()]);
}
use of liquibase.database.core.AbstractDb2Database in project liquibase by liquibase.
the class CreateTableGeneratorTest method testAutoIncrementDB2Database.
@Test
public void testAutoIncrementDB2Database() throws Exception {
for (Database database : TestContext.getInstance().getAllDatabases()) {
if (database instanceof AbstractDb2Database) {
CreateTableStatement statement = new CreateTableStatement(CATALOG_NAME, SCHEMA_NAME, TABLE_NAME);
statement.addColumn(COLUMN_NAME1, DataTypeFactory.getInstance().fromDescription("BIGINT{autoIncrement:true}", database), new AutoIncrementConstraint(COLUMN_NAME1));
Sql[] generatedSql = this.generatorUnderTest.generateSql(statement, database, null);
assertEquals("CREATE TABLE \"CATALOG_NAME\".TABLE_NAME (COLUMN1_NAME BIGINT GENERATED BY DEFAULT AS IDENTITY)", generatedSql[0].toSql());
}
}
}
use of liquibase.database.core.AbstractDb2Database in project liquibase by liquibase.
the class CreateTableGeneratorTest method testDefaultValueCurrentTimestampDB2Database.
// @Test
// public void createTable_standard() throws Exception {
// new DatabaseTestTemplate().testOnAvailableDatabases(
// new SqlStatementDatabaseTest(null, new CreateTableStatement(null, TABLE_NAME)
// .addPrimaryKeyColumn("id", "int", null, null)
// .addColumn("name", "varchar(255)")
// .addColumn("username", "varchar(255)", "'NEWUSER'")) {
//
// protected void preExecuteAssert(DatabaseSnapshotGenerator snapshot) {
// assertNull(snapshot.getTable(TABLE_NAME));
// }
//
// protected void postExecuteAssert(DatabaseSnapshotGenerator snapshot) {
// Table table = snapshot.getTable(TABLE_NAME);
// assertEquals(TABLE_NAME.toUpperCase(), table.getName().toUpperCase());
// assertNotNull(table.getColumn("id"));
// assertNotNull(table.getColumn("name"));
// assertNotNull(table.getColumn("username"));
//
// assertTrue(table.getColumn("id").isPrimaryKey());
//
// assertNull(table.getColumn("name").getDefaultValue());
// assertTrue(table.getColumn("username").getDefaultValue().toString().indexOf("NEWUSER") >= 0);
//
// assertFalse(table.getColumn("id").isAutoIncrement());
// }
//
// });
// }
//
// @Test
// public void createTable_autoincrementPK() throws Exception {
// new DatabaseTestTemplate().testOnAvailableDatabases(
// new SqlStatementDatabaseTest(null, new CreateTableStatement(null, TABLE_NAME)
// .addPrimaryKeyColumn("id", "int",null, null)
// .addColumn("name", "varchar(255)")
// .addColumn("username", "varchar(255)", "'NEWUSER'")
// .addColumnConstraint(new AutoIncrementConstraint("id"))) {
//
// protected boolean supportsTest(Database database) {
// return database.supportsAutoIncrement();
// }
//
// protected boolean expectedException(Database database, DatabaseException exception) {
// return !database.supportsAutoIncrement();
// }
//
// protected void preExecuteAssert(DatabaseSnapshotGenerator snapshot) {
// assertNull(snapshot.getTable(TABLE_NAME));
// }
//
// protected void postExecuteAssert(DatabaseSnapshotGenerator snapshot) {
// Table table = snapshot.getTable(TABLE_NAME);
// assertEquals(TABLE_NAME.toUpperCase(), table.getName().toUpperCase());
// assertNotNull(table.getColumn("id"));
// assertTrue(table.getColumn("id").isPrimaryKey());
// assertTrue(table.getColumn("id").isAutoIncrement());
// }
// });
// }
//
// @Test
// public void createTable_foreignKeyColumn() throws Exception {
// final String foreignKeyName = "fk_test_parent";
// new DatabaseTestTemplate().testOnAvailableDatabases(
// new SqlStatementDatabaseTest(null, new CreateTableStatement(null, TABLE_NAME)
// .addPrimaryKeyColumn("id", "int", null, null)
// .addColumn("name", "varchar(255)")
// .addColumn("parent_id", "int", new ForeignKeyConstraint(foreignKeyName, TABLE_NAME + "(id)"))) {
//
// protected void preExecuteAssert(DatabaseSnapshotGenerator snapshot) {
// assertNull(snapshot.getTable(TABLE_NAME));
// }
//
// protected void postExecuteAssert(DatabaseSnapshotGenerator snapshot) {
// Table table = snapshot.getTable(TABLE_NAME);
// assertEquals(TABLE_NAME.toUpperCase(), table.getName().toUpperCase());
// assertNotNull(table.getColumn("id"));
//
// ForeignKey foundForeignKey = snapshot.getForeignKey(foreignKeyName);
// assertNotNull(foundForeignKey);
// assertEquals(TABLE_NAME, foundForeignKey.getPrimaryKeyTable().getName().toUpperCase());
// assertEquals("ID", foundForeignKey.getPrimaryKeyColumns().toUpperCase());
// assertEquals(TABLE_NAME, foundForeignKey.getForeignKeyTable().getName().toUpperCase());
// assertEquals("PARENT_ID", foundForeignKey.getForeignKeyColumns().toUpperCase());
//
// }
//
// });
// }
//
// @Test
// public void createTable_deferrableForeignKeyColumn() throws Exception {
// final String foreignKeyName = "fk_test_parent";
//
// new DatabaseTestTemplate().testOnAvailableDatabases(
// new SqlStatementDatabaseTest(null, new CreateTableStatement(null, TABLE_NAME)
// .addPrimaryKeyColumn("id", "int", null, null)
// .addColumn("name", "varchar(255)")
// .addColumn("parent_id", "int",
// new ForeignKeyConstraint(foreignKeyName, TABLE_NAME + "(id)")
// .setDeferrable(true)
// .setInitiallyDeferred(true))) {
//
// protected boolean expectedException(Database database, DatabaseException exception) {
// return !database.supportsInitiallyDeferrableColumns();
// }
//
// protected void preExecuteAssert(DatabaseSnapshotGenerator snapshot) {
// assertNull(snapshot.getTable(TABLE_NAME));
// }
//
// protected void postExecuteAssert(DatabaseSnapshotGenerator snapshot) {
// Table table = snapshot.getTable(TABLE_NAME);
// assertEquals(TABLE_NAME.toUpperCase(), table.getName().toUpperCase());
// assertNotNull(table.getColumn("id"));
//
// ForeignKey foundForeignKey = snapshot.getForeignKey(foreignKeyName);
// assertNotNull(foundForeignKey);
// assertEquals(TABLE_NAME, foundForeignKey.getPrimaryKeyTable().getName().toUpperCase());
// assertEquals("ID", foundForeignKey.getPrimaryKeyColumns().toUpperCase());
// assertEquals(TABLE_NAME, foundForeignKey.getForeignKeyTable().getName().toUpperCase());
// assertEquals("PARENT_ID", foundForeignKey.getForeignKeyColumns().toUpperCase());
// assertTrue(foundForeignKey.isDeferrable());
// assertTrue(foundForeignKey.isInitiallyDeferred());
// }
//
// });
// }
//
// @Test
// public void createTable_deleteCascadeForeignKeyColumn() throws Exception {
// final String foreignKeyName = "fk_test_parent";
//
// new DatabaseTestTemplate().testOnAvailableDatabases(
// new SqlStatementDatabaseTest(null, new CreateTableStatement(null, TABLE_NAME)
// .addPrimaryKeyColumn("id", "int", null, null)
// .addColumn("name", "varchar(255)")
// .addColumn("parent_id", "int", new ForeignKeyConstraint(foreignKeyName, FK_TABLE_NAME + "(id)").setDeleteCascade(true))) {
//
// protected void setup(Database database) throws Exception {
// new Executor(database).execute(new CreateTableStatement(null, FK_TABLE_NAME)
// .addPrimaryKeyColumn("id", "int",null, null)
// .addColumn("name", "varchar(255)"));
// super.setup(database);
// }
//
// protected void preExecuteAssert(DatabaseSnapshotGenerator snapshot) {
// assertNull(snapshot.getTable(TABLE_NAME));
// }
//
// protected void postExecuteAssert(DatabaseSnapshotGenerator snapshot) {
// Table table = snapshot.getTable(TABLE_NAME);
// assertEquals(TABLE_NAME.toUpperCase(), table.getName().toUpperCase());
// assertNotNull(table.getColumn("id"));
//
// ForeignKey foundForeignKey = snapshot.getForeignKey(foreignKeyName);
// assertNotNull(foundForeignKey);
// assertEquals(FK_TABLE_NAME, foundForeignKey.getPrimaryKeyTable().getName().toUpperCase());
// assertEquals("ID", foundForeignKey.getPrimaryKeyColumns().toUpperCase());
// assertEquals(TABLE_NAME, foundForeignKey.getForeignKeyTable().getName().toUpperCase());
// assertEquals("PARENT_ID", foundForeignKey.getForeignKeyColumns().toUpperCase());
// //TODO: test when tested by diff assertTrue(foundForeignKey.isDeleteCascade());
// }
//
// });
// }
//
// @Test
// public void createTable_uniqueColumn() throws Exception {
// new DatabaseTestTemplate().testOnAvailableDatabases(
// new SqlStatementDatabaseTest(null, new CreateTableStatement(null, TABLE_NAME)
// .addPrimaryKeyColumn("id", "int",null, null)
// .addColumn("name", "varchar(255)")
// .addColumn("username", "int", new UniqueConstraint("UQ_TESTCT_ID"), new NotNullConstraint())) {
//
// protected boolean expectedException(Database database) {
// return !(database instanceof HsqlDatabase) || database instanceof H2Database;
// }
//
// protected void preExecuteAssert(DatabaseSnapshotGenerator snapshot) {
// assertNull(snapshot.getTable(TABLE_NAME));
// }
//
// protected void postExecuteAssert(DatabaseSnapshotGenerator snapshot) {
// Table table = snapshot.getTable(TABLE_NAME);
// assertEquals(TABLE_NAME.toUpperCase(), table.getName().toUpperCase());
// assertNotNull(table.getColumn("id"));
//
// //todo: actually test for uniqueness when diff can check for it assertTrue(table.getColumn("username").isUnique());
// }
//
// });
// }
//
// @Test
// public void addPrimaryKeyColumn_oneColumn() {
// CreateTableStatement statement = new CreateTableStatement(null, "tableName");
// statement.addPrimaryKeyColumn("id", "int", null, null);
//
// assertEquals(1, statement.getPrimaryKeyConstraint().getColumns().size());
// }
//
// @Test
// public void addPrimaryKeyColumn_multiColumn() {
// CreateTableStatement statement = new CreateTableStatement(null, "tableName");
// statement.addPrimaryKeyColumn("id1", "int", null, null);
// statement.addPrimaryKeyColumn("id2", "int", null, null);
//
// assertEquals(2, statement.getPrimaryKeyConstraint().getColumns().size());
// }
//
// @Test
// public void addColumnConstraint_notNullConstraint() {
// CreateTableStatement statement = new CreateTableStatement(null, "tableName");
// statement.addColumn("id", "int");
//
// assertFalse(statement.getNotNullColumns().contains("id"));
//
// statement.addColumnConstraint(new NotNullConstraint("id"));
//
// assertTrue(statement.getNotNullColumns().contains("id"));
// }
//
// @Test
// public void addColumnConstraint_ForeignKeyConstraint() {
// CreateTableStatement statement = new CreateTableStatement(null, "tableName");
// statement.addColumn("id", "int");
//
// assertEquals(0, statement.getForeignKeyConstraints().size());
//
// statement.addColumnConstraint(new ForeignKeyConstraint("fk_test", "fkTable(id)").setColumns("id"));
//
// assertEquals(1, statement.getForeignKeyConstraints().size());
// assertEquals("fk_test", statement.getForeignKeyConstraints().iterator().next().getForeignKeyName());
// }
//
// @Test
// public void addColumnConstraint_UniqueConstraint() {
// CreateTableStatement statement = new CreateTableStatement(null, "tableName");
// statement.addColumn("id", "int");
//
// assertEquals(0, statement.getUniqueConstraints().size());
//
// statement.addColumnConstraint(new UniqueConstraint("uq_test").addColumns("id"));
//
// assertEquals(1, statement.getUniqueConstraints().size());
// assertEquals("uq_test", statement.getUniqueConstraints().iterator().next().getConstraintName());
// }
//
// @Test
// public void createTable_tablespace() throws Exception {
// new DatabaseTestTemplate().testOnAvailableDatabases(
// new SqlStatementDatabaseTest(null, new CreateTableStatement(null, TABLE_NAME)
// .addPrimaryKeyColumn("id", "int", null, null)
// .addColumn("name", "varchar(255)")
// .addColumn("username", "varchar(255)", "'NEWUSER'")
// .setTablespace("liquibase2")) {
//
// protected boolean expectedException(Database database, DatabaseException exception) {
// return !database.supportsTablespaces();
// }
//
// protected void preExecuteAssert(DatabaseSnapshotGenerator snapshot) {
// assertNull(snapshot.getTable(TABLE_NAME));
// }
//
// protected void postExecuteAssert(DatabaseSnapshotGenerator snapshot) {
// Table table = snapshot.getTable(TABLE_NAME);
// assertEquals(TABLE_NAME.toUpperCase(), table.getName().toUpperCase());
//
// //todo: test that tablespace is correct when diff returns it
// }
// });
// }
//
// @Test
// public void createTable_altSchema() throws Exception {
// new DatabaseTestTemplate().testOnAvailableDatabases(
// new SqlStatementDatabaseTest(TestContext.ALT_SCHEMA, new CreateTableStatement(TestContext.ALT_SCHEMA, TABLE_NAME)
// .addPrimaryKeyColumn("id", "int", null, null)
// .addColumn("name", "varchar(255)")
// .addColumn("username", "varchar(255)", "'NEWUSER'")) {
//
// protected void preExecuteAssert(DatabaseSnapshotGenerator snapshot) {
// assertNull(snapshot.getTable(TABLE_NAME));
// }
//
// protected void postExecuteAssert(DatabaseSnapshotGenerator snapshot) {
// Table table = snapshot.getTable(TABLE_NAME);
// assertNotNull(table);
// assertEquals(TABLE_NAME.toUpperCase(), table.getName().toUpperCase());
// }
// });
// }
@Test
public void testDefaultValueCurrentTimestampDB2Database() throws Exception {
for (Database database : TestContext.getInstance().getAllDatabases()) {
if (database instanceof AbstractDb2Database) {
CreateTableStatement statement = new CreateTableStatement(CATALOG_NAME, SCHEMA_NAME, TABLE_NAME);
statement.addColumn(COLUMN_NAME1, DataTypeFactory.getInstance().fromDescription("datetime", database), new DatabaseFunction("current_timestamp"));
Sql[] generatedSql = this.generatorUnderTest.generateSql(statement, database, null);
assertEquals("CREATE TABLE \"CATALOG_NAME\".TABLE_NAME (COLUMN1_NAME TIMESTAMP DEFAULT CURRENT TIMESTAMP)", generatedSql[0].toSql());
}
}
}
Aggregations