Search in sources :

Example 26 with Sql

use of liquibase.sql.Sql in project liquibase by liquibase.

the class TagDatabaseGenerator method generateSql.

@Override
public Sql[] generateSql(TagDatabaseStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
    String tableNameEscaped = database.escapeTableName(database.getLiquibaseCatalogName(), database.getLiquibaseSchemaName(), database.getDatabaseChangeLogTableName());
    String orderColumnNameEscaped = database.escapeObjectName("ORDEREXECUTED", Column.class);
    String dateColumnNameEscaped = database.escapeObjectName("DATEEXECUTED", Column.class);
    String tagColumnNameEscaped = database.escapeObjectName("TAG", Column.class);
    String tagEscaped = DataTypeFactory.getInstance().fromObject(statement.getTag(), database).objectToSql(statement.getTag(), database);
    if (database instanceof MySQLDatabase) {
        return new Sql[] { new UnparsedSql("UPDATE " + tableNameEscaped + " AS C " + "INNER JOIN (" + "SELECT " + orderColumnNameEscaped + ", " + dateColumnNameEscaped + " " + "FROM " + tableNameEscaped + " order by " + dateColumnNameEscaped + " desc, " + orderColumnNameEscaped + " desc limit 1) AS D " + "ON C." + orderColumnNameEscaped + " = D." + orderColumnNameEscaped + " " + "SET C." + tagColumnNameEscaped + " = " + tagEscaped) };
    } else if (database instanceof PostgresDatabase) {
        return new Sql[] { new UnparsedSql("UPDATE " + tableNameEscaped + " t SET TAG=" + tagEscaped + " FROM (SELECT " + dateColumnNameEscaped + ", " + orderColumnNameEscaped + " FROM " + tableNameEscaped + " ORDER BY " + dateColumnNameEscaped + " DESC, " + orderColumnNameEscaped + " DESC LIMIT 1) sub " + "WHERE t." + dateColumnNameEscaped + "=sub." + dateColumnNameEscaped + " AND t." + orderColumnNameEscaped + "=sub." + orderColumnNameEscaped) };
    } else if (database instanceof InformixDatabase) {
        String tempTableNameEscaped = database.escapeObjectName("max_order_temp", Table.class);
        return new Sql[] { new UnparsedSql("SELECT MAX(" + dateColumnNameEscaped + ") AS " + dateColumnNameEscaped + ", MAX(" + orderColumnNameEscaped + ") AS " + orderColumnNameEscaped + " " + "FROM " + tableNameEscaped + " " + "INTO TEMP " + tempTableNameEscaped + " WITH NO LOG"), new UnparsedSql("UPDATE " + tableNameEscaped + " " + "SET TAG = " + tagEscaped + " " + "WHERE " + dateColumnNameEscaped + " = (" + "SELECT " + dateColumnNameEscaped + " " + "FROM " + tempTableNameEscaped + ") AND " + orderColumnNameEscaped + " = (" + "SELECT " + orderColumnNameEscaped + " " + "FROM " + tempTableNameEscaped + ");"), new UnparsedSql("DROP TABLE " + tempTableNameEscaped + ";") };
    } else if (database instanceof MSSQLDatabase) {
        String changelogAliasEscaped = database.escapeObjectName("changelog", Table.class);
        String latestAliasEscaped = database.escapeObjectName("latest", Table.class);
        String idColumnEscaped = database.escapeObjectName("ID", Column.class);
        String authorColumnEscaped = database.escapeObjectName("AUTHOR", Column.class);
        String filenameColumnEscaped = database.escapeObjectName("FILENAME", Column.class);
        String topClause = "TOP (1)";
        try {
            if (database.getDatabaseMajorVersion() < 10) {
                // SQL Server 2005 or earlier
                topClause = "TOP 1";
            }
        } catch (DatabaseException ignored) {
        // assume SQL Server 2008 or later
        }
        return new Sql[] { new UnparsedSql("UPDATE " + changelogAliasEscaped + " " + "SET " + tagColumnNameEscaped + " = " + tagEscaped + " " + "FROM " + tableNameEscaped + " AS " + changelogAliasEscaped + " " + "INNER JOIN (" + "SELECT " + topClause + " " + idColumnEscaped + ", " + authorColumnEscaped + ", " + filenameColumnEscaped + " " + "FROM " + tableNameEscaped + " " + "ORDER BY " + dateColumnNameEscaped + " DESC, " + orderColumnNameEscaped + " DESC" + ") AS " + latestAliasEscaped + " " + "ON " + latestAliasEscaped + "." + idColumnEscaped + " = " + changelogAliasEscaped + "." + idColumnEscaped + " " + "AND " + latestAliasEscaped + "." + authorColumnEscaped + " = " + changelogAliasEscaped + "." + authorColumnEscaped + " " + "AND " + latestAliasEscaped + "." + filenameColumnEscaped + " = " + changelogAliasEscaped + "." + filenameColumnEscaped) };
    } else if (database instanceof OracleDatabase || database instanceof DB2Database) {
        String selectClause = "SELECT";
        String endClause = ")";
        String delimiter = "";
        if (database instanceof OracleDatabase) {
            selectClause = "SELECT * FROM (SELECT";
            endClause = ") where rownum=1)";
        } else if (database instanceof DB2Database) {
            endClause = " FETCH FIRST 1 ROWS ONLY)";
        }
        return new Sql[] { new UnparsedSql("MERGE INTO " + tableNameEscaped + " a " + "USING (" + selectClause + " " + orderColumnNameEscaped + ", " + dateColumnNameEscaped + " from " + tableNameEscaped + " order by " + dateColumnNameEscaped + " desc, " + orderColumnNameEscaped + " desc" + endClause + " b " + "ON ( a." + dateColumnNameEscaped + " = b." + dateColumnNameEscaped + " and a." + orderColumnNameEscaped + "=b." + orderColumnNameEscaped + " ) " + "WHEN MATCHED THEN " + "UPDATE SET  a.tag=" + tagEscaped + delimiter) };
    } else {
        //Only uses dateexecuted as a default. Depending on the timestamp resolution, multiple rows may be tagged which normally works fine but can cause confusion and some issues.
        //We cannot use orderexecuted alone because it is only guaranteed to be incrementing per update call.
        //TODO: Better handle other databases to use dateexecuted desc, orderexecuted desc.
        UpdateStatement updateStatement = new UpdateStatement(database.getLiquibaseCatalogName(), database.getLiquibaseSchemaName(), database.getDatabaseChangeLogTableName()).addNewColumnValue("TAG", statement.getTag()).setWhereClause(dateColumnNameEscaped + " = (" + "SELECT MAX(" + dateColumnNameEscaped + ") " + "FROM " + tableNameEscaped + ")");
        return SqlGeneratorFactory.getInstance().generateSql(updateStatement, database);
    }
}
Also used : UpdateStatement(liquibase.statement.core.UpdateStatement) Table(liquibase.structure.core.Table) UnparsedSql(liquibase.sql.UnparsedSql) Sql(liquibase.sql.Sql) UnparsedSql(liquibase.sql.UnparsedSql) Column(liquibase.structure.core.Column) DatabaseException(liquibase.exception.DatabaseException)

Example 27 with Sql

use of liquibase.sql.Sql 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());
    String sql = "SELECT " + (database instanceof MSSQLDatabase && statement.getLimit() != null ? "TOP " + statement.getLimit() + " " : "") + StringUtils.join(columnsToSelect, ",", new StringUtils.StringUtilsFormatter<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 DB2Database) {
            sql += " FETCH FIRST " + statement.getLimit() + " ROWS ONLY";
        }
    }
    return new Sql[] { new UnparsedSql(sql) };
}
Also used : ColumnConfig(liquibase.change.ColumnConfig) UnparsedSql(liquibase.sql.UnparsedSql) SelectFromDatabaseChangeLogStatement(liquibase.statement.core.SelectFromDatabaseChangeLogStatement) Sql(liquibase.sql.Sql) UnparsedSql(liquibase.sql.UnparsedSql) StringUtils(liquibase.util.StringUtils) UnexpectedLiquibaseException(liquibase.exception.UnexpectedLiquibaseException)

Example 28 with Sql

use of liquibase.sql.Sql in project liquibase by liquibase.

the class CreateTableGeneratorTest method testAutoIncrementDerbyDatabase.

@Test
public void testAutoIncrementDerbyDatabase() throws Exception {
    for (Database database : TestContext.getInstance().getAllDatabases()) {
        if (database instanceof DerbyDatabase) {
            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());
        }
    }
}
Also used : AutoIncrementConstraint(liquibase.statement.AutoIncrementConstraint) DerbyDatabase(liquibase.database.core.DerbyDatabase) CreateTableStatement(liquibase.statement.core.CreateTableStatement) SQLiteDatabase(liquibase.database.core.SQLiteDatabase) DerbyDatabase(liquibase.database.core.DerbyDatabase) DB2Database(liquibase.database.core.DB2Database) H2Database(liquibase.database.core.H2Database) MSSQLDatabase(liquibase.database.core.MSSQLDatabase) MySQLDatabase(liquibase.database.core.MySQLDatabase) PostgresDatabase(liquibase.database.core.PostgresDatabase) OracleDatabase(liquibase.database.core.OracleDatabase) SybaseDatabase(liquibase.database.core.SybaseDatabase) SybaseASADatabase(liquibase.database.core.SybaseASADatabase) Database(liquibase.database.Database) HsqlDatabase(liquibase.database.core.HsqlDatabase) Sql(liquibase.sql.Sql) AbstractSqlGeneratorTest(liquibase.sqlgenerator.AbstractSqlGeneratorTest) Test(org.junit.Test)

Example 29 with Sql

use of liquibase.sql.Sql in project liquibase by liquibase.

the class CreateTableGeneratorTest method testAutoIncrementHsqlDatabase.

@Test
public void testAutoIncrementHsqlDatabase() throws Exception {
    for (Database database : TestContext.getInstance().getAllDatabases()) {
        if (database instanceof HsqlDatabase) {
            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 SCHEMA_NAME.TABLE_NAME (COLUMN1_NAME BIGINT GENERATED BY DEFAULT AS IDENTITY)", generatedSql[0].toSql());
        }
    }
}
Also used : HsqlDatabase(liquibase.database.core.HsqlDatabase) AutoIncrementConstraint(liquibase.statement.AutoIncrementConstraint) CreateTableStatement(liquibase.statement.core.CreateTableStatement) SQLiteDatabase(liquibase.database.core.SQLiteDatabase) DerbyDatabase(liquibase.database.core.DerbyDatabase) DB2Database(liquibase.database.core.DB2Database) H2Database(liquibase.database.core.H2Database) MSSQLDatabase(liquibase.database.core.MSSQLDatabase) MySQLDatabase(liquibase.database.core.MySQLDatabase) PostgresDatabase(liquibase.database.core.PostgresDatabase) OracleDatabase(liquibase.database.core.OracleDatabase) SybaseDatabase(liquibase.database.core.SybaseDatabase) SybaseASADatabase(liquibase.database.core.SybaseASADatabase) Database(liquibase.database.Database) HsqlDatabase(liquibase.database.core.HsqlDatabase) Sql(liquibase.sql.Sql) AbstractSqlGeneratorTest(liquibase.sqlgenerator.AbstractSqlGeneratorTest) Test(org.junit.Test)

Example 30 with Sql

use of liquibase.sql.Sql in project liquibase by liquibase.

the class CreateTableGeneratorTest method testAutoIncrementDB2Database.

//    @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 testAutoIncrementDB2Database() throws Exception {
    for (Database database : TestContext.getInstance().getAllDatabases()) {
        if (database instanceof DB2Database) {
            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());
        }
    }
}
Also used : DB2Database(liquibase.database.core.DB2Database) AutoIncrementConstraint(liquibase.statement.AutoIncrementConstraint) CreateTableStatement(liquibase.statement.core.CreateTableStatement) SQLiteDatabase(liquibase.database.core.SQLiteDatabase) DerbyDatabase(liquibase.database.core.DerbyDatabase) DB2Database(liquibase.database.core.DB2Database) H2Database(liquibase.database.core.H2Database) MSSQLDatabase(liquibase.database.core.MSSQLDatabase) MySQLDatabase(liquibase.database.core.MySQLDatabase) PostgresDatabase(liquibase.database.core.PostgresDatabase) OracleDatabase(liquibase.database.core.OracleDatabase) SybaseDatabase(liquibase.database.core.SybaseDatabase) SybaseASADatabase(liquibase.database.core.SybaseASADatabase) Database(liquibase.database.Database) HsqlDatabase(liquibase.database.core.HsqlDatabase) Sql(liquibase.sql.Sql) AbstractSqlGeneratorTest(liquibase.sqlgenerator.AbstractSqlGeneratorTest) Test(org.junit.Test)

Aggregations

Sql (liquibase.sql.Sql)95 Test (org.junit.Test)55 Database (liquibase.database.Database)42 MSSQLDatabase (liquibase.database.core.MSSQLDatabase)40 AbstractSqlGeneratorTest (liquibase.sqlgenerator.AbstractSqlGeneratorTest)37 OracleDatabase (liquibase.database.core.OracleDatabase)36 PostgresDatabase (liquibase.database.core.PostgresDatabase)36 MySQLDatabase (liquibase.database.core.MySQLDatabase)35 DB2Database (liquibase.database.core.DB2Database)33 SQLiteDatabase (liquibase.database.core.SQLiteDatabase)33 SybaseDatabase (liquibase.database.core.SybaseDatabase)33 AutoIncrementConstraint (liquibase.statement.AutoIncrementConstraint)33 HsqlDatabase (liquibase.database.core.HsqlDatabase)32 SybaseASADatabase (liquibase.database.core.SybaseASADatabase)32 CreateTableStatement (liquibase.statement.core.CreateTableStatement)32 DerbyDatabase (liquibase.database.core.DerbyDatabase)31 H2Database (liquibase.database.core.H2Database)31 UnparsedSql (liquibase.sql.UnparsedSql)31 ArrayList (java.util.ArrayList)11 CatalogAndSchema (liquibase.CatalogAndSchema)8