Search in sources :

Example 6 with CreateTableChange

use of liquibase.change.core.CreateTableChange in project liquibase by liquibase.

the class ValidatingVisitorTest method visit_setupException.

@Test
public void visit_setupException() throws Exception {
    changeSet1.addChange(new CreateTableChange() {

        @Override
        public void finishInitialization() throws SetupException {
            throw new SetupException("Test message");
        }
    });
    ValidatingVisitor handler = new ValidatingVisitor(new ArrayList<RanChangeSet>());
    handler.visit(changeSet1, new DatabaseChangeLog(), null, null);
    assertEquals(1, handler.getSetupExceptions().size());
    assertEquals("Test message", handler.getSetupExceptions().get(0).getMessage());
    assertFalse(handler.validationPassed());
}
Also used : SetupException(liquibase.exception.SetupException) CreateTableChange(liquibase.change.core.CreateTableChange) DatabaseChangeLog(liquibase.changelog.DatabaseChangeLog) RanChangeSet(liquibase.changelog.RanChangeSet) Test(org.junit.Test)

Example 7 with CreateTableChange

use of liquibase.change.core.CreateTableChange in project liquibase by liquibase.

the class AbstractJdbcDatabaseTest method executeRollbackStatements_WithChangeOverload_ShouldNotIncludeAppendTextFromApplyToRollbackFalseVisitor.

@Test
public void executeRollbackStatements_WithChangeOverload_ShouldNotIncludeAppendTextFromApplyToRollbackFalseVisitor() throws Exception {
    Database database = getDatabase();
    final MockExecutor mockExecutor = new MockExecutor();
    ExecutorService.getInstance().setExecutor(database, mockExecutor);
    final List<SqlVisitor> sqlVisitors = new ArrayList<SqlVisitor>();
    final CreateTableChange change = new CreateTableChange();
    change.setTableName("test_table");
    final AppendSqlVisitor appendSqlVisitor = new AppendSqlVisitor();
    appendSqlVisitor.setApplyToRollback(false);
    appendSqlVisitor.setValue(" SHOULD NOT BE APPENDED");
    sqlVisitors.add(appendSqlVisitor);
    database.executeRollbackStatements(change, sqlVisitors);
    assertEquals("DROP TABLE test_table;", mockExecutor.getRanSql().trim());
}
Also used : AppendSqlVisitor(liquibase.sql.visitor.AppendSqlVisitor) MockExecutor(liquibase.sdk.executor.MockExecutor) ArrayList(java.util.ArrayList) CreateTableChange(liquibase.change.core.CreateTableChange) SqlVisitor(liquibase.sql.visitor.SqlVisitor) AppendSqlVisitor(liquibase.sql.visitor.AppendSqlVisitor) Test(org.junit.Test)

Example 8 with CreateTableChange

use of liquibase.change.core.CreateTableChange in project liquibase by liquibase.

the class SQLiteDatabase method getAlterTableStatements.

public static List<SqlStatement> getAlterTableStatements(AlterTableVisitor alterTableVisitor, Database database, String catalogName, String schemaName, String tableName) throws DatabaseException {
    List<SqlStatement> statements = new ArrayList<SqlStatement>();
    Table table = null;
    try {
        table = SnapshotGeneratorFactory.getInstance().createSnapshot((Table) new Table().setName(tableName).setSchema(new Schema(new Catalog(null), null)), database);
        List<ColumnConfig> createColumns = new ArrayList<ColumnConfig>();
        List<ColumnConfig> copyColumns = new ArrayList<ColumnConfig>();
        if (table != null) {
            for (Column column : table.getColumns()) {
                ColumnConfig new_column = new ColumnConfig(column);
                if (alterTableVisitor.createThisColumn(new_column)) {
                    createColumns.add(new_column);
                }
                ColumnConfig copy_column = new ColumnConfig(column);
                if (alterTableVisitor.copyThisColumn(copy_column)) {
                    copyColumns.add(copy_column);
                }
            }
        }
        for (ColumnConfig column : alterTableVisitor.getColumnsToAdd()) {
            if (alterTableVisitor.createThisColumn(column)) {
                createColumns.add(column);
            }
            if (alterTableVisitor.copyThisColumn(column)) {
                copyColumns.add(column);
            }
        }
        List<Index> newIndices = new ArrayList<Index>();
        for (Index index : SnapshotGeneratorFactory.getInstance().createSnapshot(new CatalogAndSchema(catalogName, schemaName), database, new SnapshotControl(database, Index.class)).get(Index.class)) {
            if (index.getTable().getName().equalsIgnoreCase(tableName)) {
                if (alterTableVisitor.createThisIndex(index)) {
                    newIndices.add(index);
                }
            }
        }
        // rename table
        String temp_table_name = tableName + "_temporary";
        statements.addAll(Arrays.asList(new RenameTableStatement(catalogName, schemaName, tableName, temp_table_name)));
        // create temporary table
        CreateTableChange ct_change_tmp = new CreateTableChange();
        ct_change_tmp.setSchemaName(schemaName);
        ct_change_tmp.setTableName(tableName);
        for (ColumnConfig column : createColumns) {
            ct_change_tmp.addColumn(column);
        }
        statements.addAll(Arrays.asList(ct_change_tmp.generateStatements(database)));
        // copy rows to temporary table
        statements.addAll(Arrays.asList(new CopyRowsStatement(temp_table_name, tableName, copyColumns)));
        // delete original table
        statements.addAll(Arrays.asList(new DropTableStatement(catalogName, schemaName, temp_table_name, false)));
        // validate indices
        statements.addAll(Arrays.asList(new ReindexStatement(catalogName, schemaName, tableName)));
        // add remaining indices
        for (Index index_config : newIndices) {
            AddColumnConfig[] columns = new AddColumnConfig[index_config.getColumns().size()];
            for (int i = 0; i < index_config.getColumns().size(); i++) {
                columns[i] = new AddColumnConfig(index_config.getColumns().get(i));
            }
            statements.addAll(Arrays.asList(new CreateIndexStatement(index_config.getName(), catalogName, schemaName, tableName, index_config.isUnique(), index_config.getAssociatedWithAsString(), columns)));
        }
        return statements;
    } catch (InvalidExampleException e) {
        throw new UnexpectedLiquibaseException(e);
    }
}
Also used : ColumnConfig(liquibase.change.ColumnConfig) AddColumnConfig(liquibase.change.AddColumnConfig) CatalogAndSchema(liquibase.CatalogAndSchema) SqlStatement(liquibase.statement.SqlStatement) InvalidExampleException(liquibase.snapshot.InvalidExampleException) SnapshotControl(liquibase.snapshot.SnapshotControl) CatalogAndSchema(liquibase.CatalogAndSchema) CreateTableChange(liquibase.change.core.CreateTableChange) AddColumnConfig(liquibase.change.AddColumnConfig) UnexpectedLiquibaseException(liquibase.exception.UnexpectedLiquibaseException)

Example 9 with CreateTableChange

use of liquibase.change.core.CreateTableChange in project liquibase by liquibase.

the class YamlChangeLogSerializerTest method serialize__change.

@Test
public void serialize__change() {
    ChangeSet changeSet = new ChangeSet("test1", "nvoxland", false, true, "/test/me.txt", null, null, null);
    CreateTableChange change = new CreateTableChange();
    change.setTableName("testTable");
    change.addColumn(new ColumnConfig().setName("id").setType("int"));
    change.addColumn(new ColumnConfig().setName("name").setType("varchar(255)"));
    changeSet.addChange(change);
    String out = new YamlChangeLogSerializer().serialize(changeSet, false);
    System.out.println(out);
}
Also used : ColumnConfig(liquibase.change.ColumnConfig) CreateTableChange(liquibase.change.core.CreateTableChange) ChangeSet(liquibase.changelog.ChangeSet) Test(org.junit.Test)

Example 10 with CreateTableChange

use of liquibase.change.core.CreateTableChange in project liquibase by liquibase.

the class MissingTableChangeGenerator method fixMissing.

@Override
public Change[] fixMissing(DatabaseObject missingObject, DiffOutputControl control, Database referenceDatabase, Database comparisonDatabase, ChangeGeneratorChain chain) {
    Table missingTable = (Table) missingObject;
    PrimaryKey primaryKey = missingTable.getPrimaryKey();
    //        if (control.diffResult.getReferenceSnapshot().getDatabase().isLiquibaseTable(missingTable.getSchema().toCatalogAndSchema(), missingTable.getName())) {
    //            continue;
    //        }
    CreateTableChange change = createCreateTableChange();
    change.setTableName(missingTable.getName());
    if (control.getIncludeCatalog()) {
        change.setCatalogName(missingTable.getSchema().getCatalogName());
    }
    if (control.getIncludeSchema()) {
        change.setSchemaName(missingTable.getSchema().getName());
    }
    if (missingTable.getRemarks() != null) {
        change.setRemarks(missingTable.getRemarks());
    }
    for (Column column : missingTable.getColumns()) {
        ColumnConfig columnConfig = new ColumnConfig();
        columnConfig.setName(column.getName());
        LiquibaseDataType ldt = DataTypeFactory.getInstance().from(column.getType(), referenceDatabase);
        DatabaseDataType ddt = ldt.toDatabaseDataType(comparisonDatabase);
        String typeString = ddt.toString();
        if (comparisonDatabase instanceof MSSQLDatabase) {
            typeString = comparisonDatabase.unescapeDataTypeString(typeString);
        }
        columnConfig.setType(typeString);
        if (column.isAutoIncrement()) {
            columnConfig.setAutoIncrement(true);
        }
        ConstraintsConfig constraintsConfig = null;
        // In MySQL, the primary key must be specified at creation for an autoincrement column
        if (column.isAutoIncrement() && primaryKey != null && primaryKey.getColumns().size() == 1 && primaryKey.getColumnNamesAsList().contains(column.getName())) {
            if (referenceDatabase instanceof MSSQLDatabase && primaryKey.getBackingIndex() != null && primaryKey.getBackingIndex().getClustered() != null && !primaryKey.getBackingIndex().getClustered()) {
            // have to handle PK as a separate statement
            } else if (referenceDatabase instanceof PostgresDatabase && primaryKey.getBackingIndex() != null && primaryKey.getBackingIndex().getClustered() != null && primaryKey.getBackingIndex().getClustered()) {
            // have to handle PK as a separate statement
            } else {
                constraintsConfig = new ConstraintsConfig();
                if (shouldAddPrimarykeyToConstraints(missingObject, control, referenceDatabase, comparisonDatabase)) {
                    constraintsConfig.setPrimaryKey(true);
                    constraintsConfig.setPrimaryKeyTablespace(primaryKey.getTablespace());
                    // MySQL sets some primary key names as PRIMARY which is invalid
                    if (comparisonDatabase instanceof MySQLDatabase && "PRIMARY".equals(primaryKey.getName())) {
                        constraintsConfig.setPrimaryKeyName(null);
                    } else {
                        constraintsConfig.setPrimaryKeyName(primaryKey.getName());
                    }
                    control.setAlreadyHandledMissing(primaryKey);
                    control.setAlreadyHandledMissing(primaryKey.getBackingIndex());
                } else {
                    constraintsConfig.setNullable(false);
                }
            }
        } else if (column.isNullable() != null && !column.isNullable()) {
            constraintsConfig = new ConstraintsConfig();
            constraintsConfig.setNullable(false);
        }
        if (constraintsConfig != null) {
            columnConfig.setConstraints(constraintsConfig);
        }
        setDefaultValue(columnConfig, column, referenceDatabase);
        if (column.getRemarks() != null) {
            columnConfig.setRemarks(column.getRemarks());
        }
        if (column.getAutoIncrementInformation() != null) {
            BigInteger startWith = column.getAutoIncrementInformation().getStartWith();
            BigInteger incrementBy = column.getAutoIncrementInformation().getIncrementBy();
            if (startWith != null && !startWith.equals(BigInteger.ONE)) {
                columnConfig.setStartWith(startWith);
            }
            if (incrementBy != null && !incrementBy.equals(BigInteger.ONE)) {
                columnConfig.setIncrementBy(incrementBy);
            }
        }
        change.addColumn(columnConfig);
        control.setAlreadyHandledMissing(column);
    }
    return new Change[] { change };
}
Also used : Table(liquibase.structure.core.Table) ColumnConfig(liquibase.change.ColumnConfig) LiquibaseDataType(liquibase.datatype.LiquibaseDataType) PrimaryKey(liquibase.structure.core.PrimaryKey) MySQLDatabase(liquibase.database.core.MySQLDatabase) Change(liquibase.change.Change) CreateTableChange(liquibase.change.core.CreateTableChange) PostgresDatabase(liquibase.database.core.PostgresDatabase) DatabaseDataType(liquibase.datatype.DatabaseDataType) Column(liquibase.structure.core.Column) CreateTableChange(liquibase.change.core.CreateTableChange) ConstraintsConfig(liquibase.change.ConstraintsConfig) BigInteger(java.math.BigInteger) MSSQLDatabase(liquibase.database.core.MSSQLDatabase)

Aggregations

CreateTableChange (liquibase.change.core.CreateTableChange)12 Test (org.junit.Test)9 ColumnConfig (liquibase.change.ColumnConfig)5 DatabaseChangeLog (liquibase.changelog.DatabaseChangeLog)5 RanChangeSet (liquibase.changelog.RanChangeSet)5 ArrayList (java.util.ArrayList)4 MockDatabase (liquibase.sdk.database.MockDatabase)3 AddAutoIncrementChange (liquibase.change.core.AddAutoIncrementChange)2 DropTableChange (liquibase.change.core.DropTableChange)2 ChangeSet (liquibase.changelog.ChangeSet)2 Database (liquibase.database.Database)2 ValidationErrors (liquibase.exception.ValidationErrors)2 MockExecutor (liquibase.sdk.executor.MockExecutor)2 AppendSqlVisitor (liquibase.sql.visitor.AppendSqlVisitor)2 SqlVisitor (liquibase.sql.visitor.SqlVisitor)2 BigInteger (java.math.BigInteger)1 CatalogAndSchema (liquibase.CatalogAndSchema)1 AddColumnConfig (liquibase.change.AddColumnConfig)1 Change (liquibase.change.Change)1 ConstraintsConfig (liquibase.change.ConstraintsConfig)1