Java Code Examples for liquibase.change.Change

The following examples show how to use liquibase.change.Change. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: liquibase-percona   Source File: PerconaAddColumnChange.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected Change[] createInverses() {
    List<Change> inverses = new ArrayList<Change>();

    for (ColumnConfig aColumn : getColumns()) {
        if (aColumn.hasDefaultValue()) {
            DropDefaultValueChange dropChange = new DropDefaultValueChange();
            dropChange.setTableName(getTableName());
            dropChange.setColumnName(aColumn.getName());
            dropChange.setSchemaName(getSchemaName());
            dropChange.setCatalogName(getCatalogName());
            inverses.add(dropChange);
        }

        // that's the percona drop column change.
        PerconaDropColumnChange inverse = new PerconaDropColumnChange();
        inverse.setSchemaName(getSchemaName());
        inverse.setColumnName(aColumn.getName());
        inverse.setCatalogName(getCatalogName());
        inverse.setTableName(getTableName());
        inverses.add(inverse);
    }

    return inverses.toArray(new Change[inverses.size()]);
}
 
Example 2
@Override
public void saveStatements(final Change change, final List<SqlVisitor> sqlVisitors, final Writer writer) throws
    IOException {
    SqlStatement[] statements = change.generateStatements(this);
    for (SqlStatement statement : statements) {
        for (Sql sql : SqlGeneratorFactory.getInstance().generateSql(statement, this)) {
            writer.append(sql.toSql()).append(sql.getEndDelimiter()).append(StreamUtil.getLineSeparator()).append(StreamUtil.getLineSeparator());
        }
    }
}
 
Example 3
@Override
public void saveRollbackStatement(final Change change, final List<SqlVisitor> sqlVisitors, final Writer writer) throws IOException, LiquibaseException {
    SqlStatement[] statements = change.generateRollbackStatements(this);
    for (SqlStatement statement : statements) {
        for (Sql sql : SqlGeneratorFactory.getInstance().generateSql(statement, this)) {
            writer.append(sql.toSql()).append(sql.getEndDelimiter()).append("\n\n");
        }
    }
}
 
Example 4
@Override
public Sql[] generateSql(MarkChangeSetRanStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
    ChangeSet changeSet = statement.getChangeSet();

    SqlStatement runStatement;
    try {
        if (statement.getExecType().equals(ChangeSet.ExecType.FAILED) || statement.getExecType().equals(ChangeSet.ExecType.SKIPPED)) {
            return new Sql[0]; //don't mark
        }

        String tag = null;
        for (Change change : changeSet.getChanges()) {
            if (change instanceof TagDatabaseChange) {
                TagDatabaseChange tagChange = (TagDatabaseChange) change;
                tag = tagChange.getTag();
            }
        }

        runStatement = new HiveInsertStatement(database.getLiquibaseCatalogName(), database.getLiquibaseSchemaName(), database.getDatabaseChangeLogTableName())
                .addColumnValue(changeSet.getId())
                .addColumnValue(changeSet.getAuthor())
                .addColumnValue(changeSet.getFilePath())
                .addColumnValue(DateTimeUtils.getCurrentTS("yyyy-MM-dd HH:mm:ss"))
                .addColumnValue(ChangeLogHistoryServiceFactory.getInstance().getChangeLogService(database).getNextSequenceValue())
                .addColumnValue(statement.getExecType().value)
                .addColumnValue(changeSet.generateCheckSum().toString())
                .addColumnValue(changeSet.getDescription())
                .addColumnValue(StringUtils.trimToEmpty(changeSet.getComments()))
                .addColumnValue(tag == null ? "NULL" : tag)
                .addColumnValue(ChangeLogHistoryServiceFactory.getInstance().getChangeLogService(database).getDeploymentId())
                .addColumnValue(changeSet.getContexts() == null || changeSet.getContexts().isEmpty() ? null : changeSet.getContexts().toString())
                .addColumnValue(changeSet.getLabels() == null || changeSet.getLabels().isEmpty() ? null : changeSet.getLabels().toString())
                .addColumnValue(LiquibaseUtil.getBuildVersion());
    } catch (LiquibaseException e) {
        throw new UnexpectedLiquibaseException(e);
    }

    return SqlGeneratorFactory.getInstance().generateSql(runStatement, database);
}
 
Example 5
@Override
protected Change[] createInverses() {
    PerconaDropIndexChange inverse = new PerconaDropIndexChange();
    inverse.setIndexName(getIndexName());
    inverse.setCatalogName(getCatalogName());
    inverse.setSchemaName(getSchemaName());
    inverse.setTableName(getTableName());

    return new Change[] { inverse };
}
 
Example 6
@Override
protected Change[] createInverses() {
    // that's the percona drop unique constraint change
    PerconaDropUniqueConstraintChange inverse = new PerconaDropUniqueConstraintChange();
    inverse.setSchemaName(getSchemaName());
    inverse.setCatalogName(getCatalogName());
    inverse.setTableName(getTableName());
    inverse.setConstraintName(getConstraintName());

    return new Change[] { inverse };
}
 
Example 7
@Override
protected Change[] createInverses() {
    // that's the percona drop foreign key constraint change
    PerconaDropForeignKeyConstraintChange inverse = new PerconaDropForeignKeyConstraintChange();
    inverse.setBaseTableCatalogName(getBaseTableCatalogName());
    inverse.setBaseTableSchemaName(getBaseTableSchemaName());
    inverse.setBaseTableName(getBaseTableName());
    inverse.setConstraintName(getConstraintName());

    return new Change[] { inverse };
}
 
Example 8
Source Project: liquibase-percona   Source File: ChangeLogParserTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testReadLiquibaseUsePerconaFlagYAML() throws Exception {
    DatabaseChangeLog changelog = loadChangeLog("test-changelog.yaml");
    Assertions.assertEquals(2, changelog.getChangeSets().size());
    ChangeSet addColumnChangeset = changelog.getChangeSets().get(1);
    Change change = addColumnChangeset.getChanges().get(0);
    Assertions.assertEquals(PerconaAddColumnChange.class, change.getClass());
    Assertions.assertNotNull(((PerconaAddColumnChange)change).getUsePercona());
    Assertions.assertFalse(((PerconaAddColumnChange)change).getUsePercona());
}
 
Example 9
Source Project: liquibase-percona   Source File: ChangeLogParserTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testReadLiquibaseUsePerconaFlagXML() throws Exception {
    DatabaseChangeLog changelog = loadChangeLog("test-changelog.xml");
    Assertions.assertEquals(2, changelog.getChangeSets().size());
    ChangeSet addColumnChangeset = changelog.getChangeSets().get(1);
    Change change = addColumnChangeset.getChanges().get(0);
    Assertions.assertEquals(PerconaAddColumnChange.class, change.getClass());
    Assertions.assertNotNull(((PerconaAddColumnChange)change).getUsePercona());
    Assertions.assertFalse(((PerconaAddColumnChange)change).getUsePercona());
}
 
Example 10
Source Project: liquibase-percona   Source File: ChangeLogParserTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testReadLiquibaseUsePerconaFlagXMLPercona() throws Exception {
    DatabaseChangeLog changelog = loadChangeLog("test-changelog-percona.xml");
    Assertions.assertEquals(2, changelog.getChangeSets().size());
    ChangeSet addColumnChangeset = changelog.getChangeSets().get(1);
    Change change = addColumnChangeset.getChanges().get(0);
    Assertions.assertEquals(PerconaAddColumnChange.class, change.getClass());
    Assertions.assertNotNull(((PerconaAddColumnChange)change).getUsePercona());
    Assertions.assertFalse(((PerconaAddColumnChange)change).getUsePercona());
}
 
Example 11
@Override
protected Change[] createInverses() {
   final DropSpatialIndexChange inverse = new DropSpatialIndexChange();
   inverse.setCatalogName(getCatalogName());
   inverse.setSchemaName(getSchemaName());
   inverse.setTableName(getTableName());
   inverse.setIndexName(getIndexName());

   return new Change[] { inverse };
}
 
Example 12
@Override
public void dropDatabaseObjects(final CatalogAndSchema schemaToDrop) throws LiquibaseException {
    ObjectQuotingStrategy currentStrategy = this.getObjectQuotingStrategy();
    this.setObjectQuotingStrategy(ObjectQuotingStrategy.QUOTE_ALL_OBJECTS);
    try {
        DatabaseSnapshot snapshot;
        try {
            final SnapshotControl snapshotControl = new SnapshotControl(this);
            final Set<Class<? extends DatabaseObject>> typesToInclude = snapshotControl.getTypesToInclude();

            //We do not need to remove indexes and primary/unique keys explicitly. They should be removed
            //as part of tables.
            typesToInclude.remove(Index.class);
            typesToInclude.remove(PrimaryKey.class);
            typesToInclude.remove(UniqueConstraint.class);

            if (supportsForeignKeyDisable()) {
                //We do not remove ForeignKey because they will be disabled and removed as parts of tables.
                typesToInclude.remove(ForeignKey.class);
            }

            final long createSnapshotStarted = System.currentTimeMillis();
            snapshot = SnapshotGeneratorFactory.getInstance().createSnapshot(schemaToDrop, this, snapshotControl);
            LogService.getLog(getClass()).debug(LogType.LOG, String.format("Database snapshot generated in %d ms. Snapshot includes: %s", System.currentTimeMillis() - createSnapshotStarted, typesToInclude));
        } catch (LiquibaseException e) {
            throw new UnexpectedLiquibaseException(e);
        }

        final long changeSetStarted = System.currentTimeMillis();
        CompareControl compareControl = new CompareControl(
            new CompareControl.SchemaComparison[]{
                new CompareControl.SchemaComparison(
                    CatalogAndSchema.DEFAULT,
                    schemaToDrop)},
            snapshot.getSnapshotControl().getTypesToInclude());
        DiffResult diffResult = DiffGeneratorFactory.getInstance().compare(
            new EmptyDatabaseSnapshot(this),
            snapshot,
            compareControl);

        List<ChangeSet> changeSets = new DiffToChangeLog(diffResult, new DiffOutputControl(true, true, false, null).addIncludedSchema(schemaToDrop)).generateChangeSets();
        LogService.getLog(getClass()).debug(LogType.LOG, String.format("ChangeSet to Remove Database Objects generated in %d ms.", System.currentTimeMillis() - changeSetStarted));

        boolean previousAutoCommit = this.getAutoCommitMode();
        this.commit(); //clear out currently executed statements
        this.setAutoCommit(false); //some DDL doesn't work in autocommit mode
        final boolean reEnableFK = supportsForeignKeyDisable() && disableForeignKeyChecks();
        try {
            for (ChangeSet changeSet : changeSets) {
                changeSet.setFailOnError(false);
                for (Change change : changeSet.getChanges()) {
                    if (change instanceof DropTableChange) {
                        ((DropTableChange) change).setCascadeConstraints(true);
                    }
                    SqlStatement[] sqlStatements = change.generateStatements(this);
                    for (SqlStatement statement : sqlStatements) {
                        ExecutorService.getInstance().getExecutor(this).execute(statement);
                    }

                }
                this.commit();
            }
        } finally {
            if (reEnableFK) {
                enableForeignKeyChecks();
            }
        }

        ChangeLogHistoryServiceFactory.getInstance().getChangeLogService(this).destroy();
        LockServiceFactory.getInstance().getLockService(this).destroy();

        this.setAutoCommit(previousAutoCommit);
        LogService.getLog(getClass()).info(LogType.LOG, String.format("Successfully deleted all supported object types in schema %s.", schemaToDrop.toString()));
    } finally {
        this.setObjectQuotingStrategy(currentStrategy);
        this.commit();
    }
}
 
Example 13
@Override
public void executeStatements(final Change change, final DatabaseChangeLog changeLog, final List<SqlVisitor> sqlVisitors) throws LiquibaseException {
    SqlStatement[] statements = change.generateStatements(this);

    execute(statements, sqlVisitors);
}
 
Example 14
@Override
public void executeRollbackStatements(final Change change, final List<SqlVisitor> sqlVisitors) throws LiquibaseException {
    final SqlStatement[] statements = change.generateRollbackStatements(this);
    executeRollbackStatements(statements, sqlVisitors);
}
 
Example 15
Source Project: liquibase-percona   Source File: PerconaChangeUtil.java    License: Apache License 2.0 4 votes vote down vote up
public static SqlStatement[] generateStatements(PerconaChange change,
        Database database, SqlStatement[] originalStatements) {

    String changeSetId = "unknown changeset id";
    if (change instanceof Change) {
        ChangeSet changeSet = ((Change)change).getChangeSet();
        if (changeSet != null) {
            changeSetId = changeSet.getId() + ":" + changeSet.getAuthor();
        }
    }

    if (change.getUsePercona() == null && !Configuration.getDefaultOn()) {
        log.debug("Not using percona toolkit, because property " + Configuration.DEFAULT_ON + " is false. " + changeSetId + ":" + change.getChangeName());
        return originalStatements;
    }
    if (change.getUsePercona() != null && !change.getUsePercona()) {
        log.debug("Not using percona toolkit, because usePercona flag is false for " + changeSetId + ":" + change.getChangeName());
        return originalStatements;
    }
    if (Configuration.skipChange(change.getChangeName())) {
        maybeLog("Not using percona toolkit, because skipChange for "
                + change.getChangeName() + " is active (property: " + Configuration.SKIP_CHANGES + ")!");
        return originalStatements;
    }

    List<SqlStatement> statements = new ArrayList<SqlStatement>(Arrays.asList(originalStatements));

    if (database instanceof MySQLDatabase) {
        if (PTOnlineSchemaChangeStatement.isAvailable()) {
            PTOnlineSchemaChangeStatement statement = new PTOnlineSchemaChangeStatement(
                    change.getTargetDatabaseName(),
                    change.getTargetTableName(),
                    change.generateAlterStatement(database));

            if (isDryRun(database)) {
                CommentStatement commentStatement = new CommentStatement(statement.printCommand(database));

                if (Configuration.noAlterSqlDryMode()) {
                    statements.clear();
                    statements.add(0, commentStatement);
                } else {
                    statements.add(0, commentStatement);
                    statements.add(1, new CommentStatement("Instead of the following statements, pt-online-schema-change will be used"));
                }
            } else {
                statements.clear();
                statements.add(statement);
            }
        } else {
            if (Configuration.failIfNoPT()) {
                throw new RuntimeException("No percona toolkit found!");
            }
            maybeLog("Not using percona toolkit, because it is not available!");
        }
    }

    return statements.toArray(new SqlStatement[statements.size()]);
}