liquibase.sqlgenerator.SqlGeneratorFactory Java Examples

The following examples show how to use liquibase.sqlgenerator.SqlGeneratorFactory. 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 File: AbstractJdbcDatabase.java    From jweb-cms with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void execute(final SqlStatement[] statements, final List<SqlVisitor> sqlVisitors) throws LiquibaseException {
    for (SqlStatement statement : statements) {
        if (statement.skipOnUnsupported() && !SqlGeneratorFactory.getInstance().supports(statement, this)) {
            continue;
        }
        LogService.getLog(getClass()).debug(LogType.LOG, "Executing Statement: " + statement);
        try {
            ExecutorService.getInstance().getExecutor(this).execute(statement, sqlVisitors);
        } catch (DatabaseException e) {
            if (statement.continueOnError()) {
                LogService.getLog(getClass()).severe(LogType.LOG, "Error executing statement '" + statement.toString() + "', but continuing", e);
            } else {
                throw e;
            }
        }
    }
}
 
Example #2
Source File: IndexGeneratorTest.java    From liquibase-mssql with Apache License 2.0 6 votes vote down vote up
@Test
public void integrates() throws DatabaseException {
    final AddColumnConfig firstColumnConfig = new AddColumnConfig();
    firstColumnConfig.setName("id");
    final AddColumnConfig secondColumnConfig = new AddColumnConfig();
    secondColumnConfig.setName("name");

    //Liquibase must find our mssql impl.
    Database database= DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new OfflineConnection("offline:mssql", null));

    CreateIndexStatement statement = new CreateIndexStatement(null, null, null, "TABLE_NAME", true, null, firstColumnConfig, secondColumnConfig);
    Sql[] sql = SqlGeneratorFactory.getInstance().generateSql(statement, database);
    assertEquals("CREATE UNIQUE INDEX ON [TABLE_NAME]([id], [name])", sql[0].toSql());

    statement = new CreateIndexStatementMSSQL(statement, "included, includedtoo", null);
    sql = SqlGeneratorFactory.getInstance().generateSql(statement, database);
    assertEquals("CREATE UNIQUE INDEX ON [TABLE_NAME]([id], [name]) INCLUDE ([included], [includedtoo])", sql[0].toSql());

    statement = new CreateIndexStatementMSSQL(statement, null, 50);
    sql = SqlGeneratorFactory.getInstance().generateSql(statement, database);
    assertEquals("CREATE UNIQUE INDEX ON [TABLE_NAME]([id], [name]) WITH (FILLFACTOR = 50)", sql[0].toSql());

    statement = new CreateIndexStatementMSSQL(statement, "included, includedtoo", 50);
    sql = SqlGeneratorFactory.getInstance().generateSql(statement, database);
    assertEquals("CREATE UNIQUE INDEX ON [TABLE_NAME]([id], [name]) INCLUDE ([included], [includedtoo]) WITH (FILLFACTOR = 50)", sql[0].toSql());
}
 
Example #3
Source File: PrimaryKeyGeneratorTest.java    From liquibase-mssql with Apache License 2.0 6 votes vote down vote up
@Test
public void integrates() throws DatabaseException {

  //Liquibase must find our mssql impl.
  Database database= DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new OfflineConnection("offline:mssql", null));

  AddPrimaryKeyStatement statement = new AddPrimaryKeyStatement("myCat", "mySchema", "myTable", "myCol", "myConstraint");
  statement.setClustered(true);

  Sql[] sql = SqlGeneratorFactory.getInstance().generateSql(statement, database);
  assertEquals("ALTER TABLE [mySchema].[myTable] ADD CONSTRAINT [myConstraint] PRIMARY KEY ([myCol])", sql[0].toSql());

  statement = new AddPrimaryKeyStatementMSSQL(statement, null);
  sql = SqlGeneratorFactory.getInstance().generateSql(statement, database);
  assertEquals("ALTER TABLE [mySchema].[myTable] ADD CONSTRAINT [myConstraint] PRIMARY KEY ([myCol])", sql[0].toSql());

  statement = new AddPrimaryKeyStatementMSSQL(statement, 50);
  sql = SqlGeneratorFactory.getInstance().generateSql(statement, database);
  assertEquals("ALTER TABLE [mySchema].[myTable] ADD CONSTRAINT [myConstraint] PRIMARY KEY ([myCol]) WITH (FILLFACTOR = 50)", sql[0].toSql());
}
 
Example #4
Source File: InsertGeneratorTest.java    From liquibase-mssql with Apache License 2.0 6 votes vote down vote up
@Test
public void integrates() throws DatabaseException {

    //Liquibase must find our mssql impl.
    Database database= DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new OfflineConnection("offline:mssql", null));

    InsertStatement statement = new InsertStatement(null, null, "TABLE_NAME");
    statement.addColumnValue("id", 1);
    statement.addColumnValue("name", "asdf");
    
    statement = new InsertStatementMSSQL(statement, true);

    Sql[] sql = SqlGeneratorFactory.getInstance().generateSql(statement, database);
    assertEquals(3, sql.length);

    for (Sql currentSql : sql) {
        assertSqlHasNoDanglingTokens(currentSql.toSql());
    }
}
 
Example #5
Source File: CustomInsertLockRecordGenerator.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public Sql[] generateSql(InitializeDatabaseChangeLogLockTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
    // get the IDs that are already in the database if migration
    Set<Integer> currentIds = new HashSet<>();
    if (statement instanceof CustomInitializeDatabaseChangeLogLockTableStatement) {
        currentIds = ((CustomInitializeDatabaseChangeLogLockTableStatement) statement).getCurrentIds();
    }

    // generate all the IDs that are currently missing in the lock table
    List<Sql> result = new ArrayList<>();
    for (DBLockProvider.Namespace lock : DBLockProvider.Namespace.values()) {
        if (!currentIds.contains(lock.getId())) {
            InsertStatement insertStatement = new InsertStatement(database.getLiquibaseCatalogName(), database.getLiquibaseSchemaName(), database.getDatabaseChangeLogLockTableName())
                    .addColumnValue("ID", lock.getId())
                    .addColumnValue("LOCKED", Boolean.FALSE);
            result.addAll(Arrays.asList(SqlGeneratorFactory.getInstance().generateSql(insertStatement, database)));
        }
    }

    return result.toArray(new Sql[result.size()]);
}
 
Example #6
Source File: AbstractJdbcDatabase.java    From jweb-cms with GNU Affero General Public License v3.0 5 votes vote down vote up
@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 #7
Source File: AbstractJdbcDatabase.java    From jweb-cms with GNU Affero General Public License v3.0 5 votes vote down vote up
@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 #8
Source File: HiveMarkChangeSetRanGenerator.java    From liquibase-impala with Apache License 2.0 5 votes vote down vote up
@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 #9
Source File: CustomSqlGenerator.java    From liquibase-impala with Apache License 2.0 5 votes vote down vote up
public static Sql[] generateSql(Database database, List<SqlStatement> statements) {
    List<Sql> sqls = new ArrayList<Sql>();
    SqlGeneratorFactory generatorFactory = SqlGeneratorFactory.getInstance();
    for (SqlStatement statement : statements) {
        sqls.addAll(Arrays.asList(generatorFactory.generateSql(statement, database)));
    }
    return sqls.toArray(new Sql[sqls.size()]);
}
 
Example #10
Source File: CustomSqlGenerator.java    From liquibase-impala with Apache License 2.0 5 votes vote down vote up
public static Sql[] generateSql(Database database, SqlStatement... statements) {
    List<Sql> sqls = new ArrayList<Sql>();
    SqlGeneratorFactory generatorFactory = SqlGeneratorFactory.getInstance();
    for (SqlStatement statement : statements) {
        sqls.addAll(Arrays.asList(generatorFactory.generateSql(statement, database)));
    }
    return sqls.toArray(new Sql[sqls.size()]);
}
 
Example #11
Source File: HiveStandardChangeLogHistoryService.java    From liquibase-impala with Apache License 2.0 4 votes vote down vote up
@Override
public void init() throws DatabaseException {
    if (serviceInitialized) {
        return;
    }
    Database database = getDatabase();
    Executor executor = ExecutorService.getInstance().getExecutor(database);

    Table changeLogTable = null;
    try {
        changeLogTable = SnapshotGeneratorFactory.getInstance().getDatabaseChangeLogTable(new SnapshotControl(database, false, Table.class, Column.class), database);
    } catch (LiquibaseException e) {
        throw new UnexpectedLiquibaseException(e);
    }

    List<SqlStatement> statementsToExecute = new ArrayList<SqlStatement>();

    if (changeLogTable != null) {
        boolean hasDescription = changeLogTable.getColumn("DESCRIPTION") != null;
        boolean hasComments = changeLogTable.getColumn("COMMENTS") != null;
        boolean hasTag = changeLogTable.getColumn("TAG") != null;
        boolean hasLiquibase = changeLogTable.getColumn("LIQUIBASE") != null;
        boolean hasContexts = changeLogTable.getColumn("CONTEXTS") != null;
        boolean hasLabels = changeLogTable.getColumn("LABELS") != null;
        boolean hasOrderExecuted = changeLogTable.getColumn("ORDEREXECUTED") != null;
        boolean hasExecTypeColumn = changeLogTable.getColumn("EXECTYPE") != null;
        String charTypeName = getCharTypeName();
        boolean hasDeploymentIdColumn = changeLogTable.getColumn("DEPLOYMENT_ID") != null;

        if (!hasDescription) {
            executor.comment("Adding missing databasechangelog.description column");
            statementsToExecute.add(new AddColumnStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "DESCRIPTION", charTypeName, null));
        }
        if (!hasTag) {
            executor.comment("Adding missing databasechangelog.tag column");
            statementsToExecute.add(new AddColumnStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "TAG", charTypeName, null));
        }
        if (!hasComments) {
            executor.comment("Adding missing databasechangelog.comments column");
            statementsToExecute.add(new AddColumnStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "COMMENTS", charTypeName, null));
        }
        if (!hasLiquibase) {
            executor.comment("Adding missing databasechangelog.liquibase column");
            statementsToExecute.add(new AddColumnStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "LIQUIBASE", charTypeName, null));
        }
        if (!hasOrderExecuted) {
            executor.comment("Adding missing databasechangelog.orderexecuted column");
            statementsToExecute.add(new AddColumnStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "ORDEREXECUTED", "int", null));
        }
        if (!hasExecTypeColumn) {
            executor.comment("Adding missing databasechangelog.exectype column");
            statementsToExecute.add(new AddColumnStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "EXECTYPE", charTypeName, null));
        }

        if (!hasContexts) {
            executor.comment("Adding missing databasechangelog.contexts column");
            statementsToExecute.add(new AddColumnStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "CONTEXTS", charTypeName, null));
        }

        if (!hasLabels) {
            executor.comment("Adding missing databasechangelog.labels column");
            statementsToExecute.add(new AddColumnStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "LABELS", charTypeName, null));
        }

        if (!hasDeploymentIdColumn) {
            executor.comment("Adding missing databasechangelog.deployment_id column");
            statementsToExecute.add(new AddColumnStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "DEPLOYMENT_ID", charTypeName, null));
        }
    } else {
        executor.comment("Create Database Change Log Table");
        SqlStatement createTableStatement = new CreateDatabaseChangeLogTableStatement();
        if (!canCreateChangeLogTable()) {
            throw new DatabaseException("Cannot create " + getDatabase().escapeTableName(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName()) + " table for your getDatabase().\n\n" +
                    "Please construct it manually using the following SQL as a base and re-run Liquibase:\n\n" +
                    createTableStatement);
        }
        // If there is no table in the database for recording change history create one.
        statementsToExecute.add(createTableStatement);
        LOG.info("Creating database history table with name: " + getDatabase().escapeTableName(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName()));
    }

    for (SqlStatement sql : statementsToExecute) {
        if (SqlGeneratorFactory.getInstance().supports(sql, database)) {
            executor.execute(sql);
            getDatabase().commit();
        } else {
            LOG.info("Cannot run " + sql.getClass().getSimpleName() + " on " + getDatabase().getShortName() + " when checking databasechangelog table");
        }
    }
    serviceInitialized = true;
}
 
Example #12
Source File: DefaultLiquibaseConnectionProvider.java    From keycloak with Apache License 2.0 4 votes vote down vote up
protected void baseLiquibaseInitialization() {
    ServiceLocator sl = ServiceLocator.getInstance();
    sl.setResourceAccessor(new ClassLoaderResourceAccessor(getClass().getClassLoader()));

    if (!System.getProperties().containsKey("liquibase.scan.packages")) {
        if (sl.getPackages().remove("liquibase.core")) {
            sl.addPackageToScan("liquibase.core.xml");
        }

        if (sl.getPackages().remove("liquibase.parser")) {
            sl.addPackageToScan("liquibase.parser.core.xml");
        }

        if (sl.getPackages().remove("liquibase.serializer")) {
            sl.addPackageToScan("liquibase.serializer.core.xml");
        }

        sl.getPackages().remove("liquibase.ext");
        sl.getPackages().remove("liquibase.sdk");

        String lockPackageName = DummyLockService.class.getPackage().getName();
        logger.debugf("Added package %s to liquibase", lockPackageName);
        sl.addPackageToScan(lockPackageName);
    }

    LogFactory.setInstance(new LogWrapper());

    // Adding PostgresPlus support to liquibase
    DatabaseFactory.getInstance().register(new PostgresPlusDatabase());
    // Adding newer version of MySQL/MariaDB support to liquibase
    DatabaseFactory.getInstance().register(new UpdatedMySqlDatabase());
    DatabaseFactory.getInstance().register(new UpdatedMariaDBDatabase());

    // Adding CustomVarcharType for MySQL 8 and newer
    DataTypeFactory.getInstance().register(MySQL8VarcharType.class);

    // Change command for creating lock and drop DELETE lock record from it
    SqlGeneratorFactory.getInstance().register(new CustomInsertLockRecordGenerator());

    // Use "SELECT FOR UPDATE" for locking database
    SqlGeneratorFactory.getInstance().register(new CustomLockDatabaseChangeLogGenerator());
}