Java Code Examples for liquibase.statement.SqlStatement

The following examples show how to use liquibase.statement.SqlStatement. 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
/**
 * Overwrite this method to get the default schema name for the connection.
 * If you only need to change the statement that obtains the current schema then override
 *
 * @see AbstractJdbcDatabase#getConnectionSchemaNameCallStatement()
 */
protected String getConnectionSchemaName() {
    if (connection == null) {
        return null;
    }
    if (connection instanceof OfflineConnection) {
        return ((OfflineConnection) connection).getSchema();
    }

    try {
        SqlStatement currentSchemaStatement = getConnectionSchemaNameCallStatement();
        return ExecutorService.getInstance().getExecutor(this).
            queryForObject(currentSchemaStatement, String.class);
    } catch (Exception e) {
        LogService.getLog(getClass()).info(LogType.LOG, "Error getting default schema", e);
    }
    return null;
}
 
Example 2
@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 3
@Test
public void testUpdateSQL() {
    enableLogging();

    SqlStatement[] statements = generateStatements();
    Assertions.assertEquals(3, statements.length);
    Assertions.assertEquals(CommentStatement.class, statements[0].getClass());
    Assertions.assertEquals("pt-online-schema-change "
            + "--alter-foreign-keys-method=auto "
            + "--nocheck-unique-key-change "
            + "--alter=\"" + alterText + "\" "
            + "--host=localhost --port=3306 --user=user --password=*** --execute D=testdb,t=address",
            ((CommentStatement)statements[0]).getText());
    Assertions.assertEquals(CommentStatement.class, statements[1].getClass());
    Assertions.assertEquals(DropForeignKeyConstraintStatement.class, statements[2].getClass());
}
 
Example 4
@Test
public void testUpdateSQL() {
    enableLogging();

    SqlStatement[] statements = generateStatements();
    Assertions.assertEquals(3, statements.length);
    Assertions.assertEquals(CommentStatement.class, statements[0].getClass());
    Assertions.assertEquals("pt-online-schema-change "
            + "--alter-foreign-keys-method=auto "
            + "--nocheck-unique-key-change "
            + "--alter=\"ADD COLUMN new_column INT NULL\" "
            + "--host=localhost --port=3306 --user=user --password=*** --execute D=testdb,t=person",
            ((CommentStatement)statements[0]).getText());
    Assertions.assertEquals(CommentStatement.class, statements[1].getClass());
    Assertions.assertEquals(AddColumnStatement.class, statements[2].getClass());
}
 
Example 5
@Test
public void testRollbackSQL() throws RollbackImpossibleException {
    enableLogging();

    SqlStatement[] statements = generateRollbackStatements();
    Assertions.assertEquals(3, statements.length);
    Assertions.assertEquals(CommentStatement.class, statements[0].getClass());
    Assertions.assertEquals("pt-online-schema-change "
            + "--alter-foreign-keys-method=auto "
            + "--nocheck-unique-key-change "
            + "--alter=\"DROP COLUMN new_column\" "
            + "--host=localhost --port=3306 --user=user --password=*** --execute D=testdb,t=person",
            ((CommentStatement)statements[0]).getText());
    Assertions.assertEquals(CommentStatement.class, statements[1].getClass());
    Assertions.assertEquals(DropColumnStatement.class, statements[2].getClass());
}
 
Example 6
@Test
public void testUpdateSQL() {
    enableLogging();

    SqlStatement[] statements = generateStatements();
    Assertions.assertEquals(3, statements.length);
    Assertions.assertEquals(CommentStatement.class, statements[0].getClass());
    Assertions.assertEquals("pt-online-schema-change "
            + "--alter-foreign-keys-method=auto "
            + "--nocheck-unique-key-change "
            + "--alter=\"" + alterText + "\" "
            + "--host=localhost --port=3306 --user=user --password=*** --execute D=testdb,t=person",
            ((CommentStatement)statements[0]).getText());
    Assertions.assertEquals(CommentStatement.class, statements[1].getClass());
    Assertions.assertEquals(AddUniqueConstraintStatement.class, statements[2].getClass());
}
 
Example 7
@Test
public void testRollbackSQL() throws RollbackImpossibleException {
    enableLogging();

    SqlStatement[] statements = generateRollbackStatements();
    Assertions.assertEquals(3, statements.length);
    Assertions.assertEquals(CommentStatement.class, statements[0].getClass());
    Assertions.assertEquals("pt-online-schema-change "
            + "--alter-foreign-keys-method=auto "
            + "--nocheck-unique-key-change "
            + "--alter=\"" + alterRollbackText + "\" "
            + "--host=localhost --port=3306 --user=user --password=*** --execute D=testdb,t=person",
            ((CommentStatement)statements[0]).getText());
    Assertions.assertEquals(CommentStatement.class, statements[1].getClass());
    Assertions.assertEquals(DropUniqueConstraintStatement.class, statements[2].getClass());
}
 
Example 8
@Test
public void testUpdateSQL() {
    enableLogging();

    SqlStatement[] statements = generateStatements();
    Assertions.assertEquals(3, statements.length);
    Assertions.assertEquals(CommentStatement.class, statements[0].getClass());
    Assertions.assertEquals("pt-online-schema-change "
            + "--alter-foreign-keys-method=auto "
            + "--nocheck-unique-key-change "
            + "--alter=\"" + alterText + "\" "
            + "--host=localhost --port=3306 --user=user --password=*** --execute D=testdb,t=person",
            ((CommentStatement)statements[0]).getText());
    Assertions.assertEquals(CommentStatement.class, statements[1].getClass());
    Assertions.assertEquals(DropUniqueConstraintStatement.class, statements[2].getClass());
}
 
Example 9
@Test
public void testUpdateSQL() {
    enableLogging();

    SqlStatement[] statements = generateStatements();
    Assertions.assertEquals(3, statements.length);
    Assertions.assertEquals(CommentStatement.class, statements[0].getClass());
    Assertions.assertEquals("pt-online-schema-change "
            + "--alter-foreign-keys-method=auto "
            + "--nocheck-unique-key-change "
            + "--alter=\"DROP COLUMN col_test\" "
            + "--host=localhost --port=3306 --user=user --password=*** --execute D=testdb,t=person",
            ((CommentStatement)statements[0]).getText());
    Assertions.assertEquals(CommentStatement.class, statements[1].getClass());
    Assertions.assertEquals(DropColumnStatement.class, statements[2].getClass());
}
 
Example 10
@Test
public void testUpdateSQL() {
    enableLogging();

    SqlStatement[] statements = generateStatements();
    Assertions.assertEquals(3, statements.length);
    Assertions.assertEquals(CommentStatement.class, statements[0].getClass());
    Assertions.assertEquals("pt-online-schema-change "
            + "--alter-foreign-keys-method=auto "
            + "--nocheck-unique-key-change "
            + "--alter=\"ADD UNIQUE INDEX theIndexName (indexedColumn)\" "
            + "--host=localhost --port=3306 --user=user --password=*** --execute D=testdb,t=person",
            ((CommentStatement)statements[0]).getText());
    Assertions.assertEquals(CommentStatement.class, statements[1].getClass());
    Assertions.assertEquals(CreateIndexStatement.class, statements[2].getClass());
}
 
Example 11
@Test
public void testUpdateSQL() {
    enableLogging();

    SqlStatement[] statements = generateStatements();
    Assertions.assertEquals(3, statements.length);
    Assertions.assertEquals(CommentStatement.class, statements[0].getClass());
    Assertions.assertEquals("pt-online-schema-change "
            + "--alter-foreign-keys-method=auto "
            + "--nocheck-unique-key-change "
            + "--alter=\"" + alterText + "\" "
            + "--host=localhost --port=3306 --user=user --password=*** --execute D=testdb,t=address",
            ((CommentStatement)statements[0]).getText());
    Assertions.assertEquals(CommentStatement.class, statements[1].getClass());
    Assertions.assertEquals(AddForeignKeyConstraintStatement.class, statements[2].getClass());
}
 
Example 12
@Test
public void testRollbackSQL() throws RollbackImpossibleException {
    enableLogging();

    SqlStatement[] statements = generateRollbackStatements();
    Assertions.assertEquals(3, statements.length);
    Assertions.assertEquals(CommentStatement.class, statements[0].getClass());
    Assertions.assertEquals("pt-online-schema-change "
            + "--alter-foreign-keys-method=auto "
            + "--nocheck-unique-key-change "
            + "--alter=\"" + alterRollbackText + "\" "
            + "--host=localhost --port=3306 --user=user --password=*** --execute D=testdb,t=address",
            ((CommentStatement)statements[0]).getText());
    Assertions.assertEquals(CommentStatement.class, statements[1].getClass());
    Assertions.assertEquals(DropForeignKeyConstraintStatement.class, statements[2].getClass());
}
 
Example 13
@Override
public SqlStatement[] generateStatements(final Database database) {
   final String[] columns = new String[this.columns.size()];
   int ii = 0;
   for (final ColumnConfig columnConfig : this.columns) {
      columns[ii++] = columnConfig.getName();
   }

   // Parse the string SRID into an integer.
   Integer srid = null;
   if (getSrid() != null) {
      srid = Integer.valueOf(getSrid());
   }

   final CreateSpatialIndexStatement statement = new CreateSpatialIndexStatement(
         getIndexName(), getCatalogName(), getSchemaName(), getTableName(), columns,
         getTablespace(), getGeometryType(), srid);
   return new SqlStatement[] { statement };
}
 
Example 14
Source Project: liquibase-spatial   Source File: DropSpatialIndexChange.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Generates a {@link DropSpatialIndexStatement} followed by a {@link DropIndexStatement}, if
 * applicable. The first statement allows extra clean-up when dropping an index. The second
 * statement leverages the normal <code>DROP INDEX</code> logic.
 */
@Override
public SqlStatement[] generateStatements(final Database database) {
   final Collection<SqlStatement> statements = new ArrayList<SqlStatement>();
   // MySQL and PostgreSQL only need the normal DROP INDEX statement.
   if (!(database instanceof MySQLDatabase) && !(database instanceof PostgresDatabase)) {
      final DropSpatialIndexStatement dropSpatialIndex = new DropSpatialIndexStatement(
            this.indexName, this.catalogName, this.schemaName, this.tableName);
      statements.add(dropSpatialIndex);
   }

   // GeoDB doesn't use a tradition index structure so don't issue the normal DROP INDEX
   // statement.
   if (!(database instanceof DerbyDatabase) && !(database instanceof H2Database)) {
      final DropIndexStatement dropIndex = new DropIndexStatement(this.indexName,
            this.catalogName, this.schemaName, this.tableName, null);
      statements.add(dropIndex);
   }
   return statements.toArray(new SqlStatement[statements.size()]);
}
 
Example 15
Source Project: liquibase-mssql   Source File: InsertDataChangeMSSQL.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public SqlStatement[] generateStatements(Database database) {
    SqlStatement[] statements = super.generateStatements(database);
    if (!MSSQLDatabase.PRODUCT_NAME.equals(database.getDatabaseProductName())) {
    	return statements;
    }
    List<SqlStatement> wrappedStatements = new ArrayList<SqlStatement>(statements.length);
    for (SqlStatement statement : statements) {
        if (statement instanceof InsertStatement) {
            wrappedStatements.add(new InsertStatementMSSQL((InsertStatement) statement, identityInsertEnabled));
        } else {
            wrappedStatements.add(statement);
        }
    }
    return wrappedStatements.toArray(new SqlStatement[0]);
}
 
Example 16
Source Project: liquibase-mssql   Source File: CreateIndexChangeMSSQL.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public SqlStatement[] generateStatements(Database database) {
  SqlStatement[] statements = super.generateStatements(database);
  if (!MSSQLDatabase.PRODUCT_NAME.equals(database.getDatabaseProductName())) {
  	return statements;
  }

  List<SqlStatement> extendedStatements = new ArrayList<SqlStatement>(statements.length);
  for (SqlStatement statement : statements) {
    if (statement instanceof CreateIndexStatement) {
      extendedStatements.add(new CreateIndexStatementMSSQL((CreateIndexStatement)statement, includedColumns, fillFactor));
    } else {
      extendedStatements.add(statement);
    }
  }

  return extendedStatements.toArray(new SqlStatement[0]);
}
 
Example 17
Source Project: liquibase-mssql   Source File: LoadDataChangeMSSQL.java    License: Apache License 2.0 6 votes vote down vote up
@Override
   public SqlStatement[] generateStatements(Database database) {
SqlStatement[] statements = super.generateStatements(database);
   if (!MSSQLDatabase.PRODUCT_NAME.equals(database.getDatabaseProductName())) {
   	return statements;
   }
List<SqlStatement> wrappedStatements = new ArrayList<SqlStatement>(statements.length);
for (SqlStatement statement : statements) {
    if (statement instanceof InsertStatement) {
	wrappedStatements.add(new InsertStatementMSSQL((InsertStatement) statement, identityInsertEnabled));
    } else if(statement instanceof InsertSetStatement) {
        wrappedStatements.add(new InsertSetStatementMSSQL((InsertSetStatement) statement, identityInsertEnabled));
    } else {
	wrappedStatements.add(statement);
    }
}
return wrappedStatements.toArray(new SqlStatement[0]);
   }
 
Example 18
Source Project: liquibase-mssql   Source File: AddPrimaryKeyChangeMSSQL.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public SqlStatement[] generateStatements(Database database) {
  SqlStatement[] statements = super.generateStatements(database);
  if (!MSSQLDatabase.PRODUCT_NAME.equals(database.getDatabaseProductName())) {
  	return statements;
  }
  List<SqlStatement> extendedStatements = new ArrayList<SqlStatement>(statements.length);

  for (SqlStatement statement : statements) {
    if (statement instanceof AddPrimaryKeyStatement) {
      extendedStatements.add(new AddPrimaryKeyStatementMSSQL((AddPrimaryKeyStatement)statement, fillFactor));
    } else {
      extendedStatements.add(statement);
    }
  }

  return extendedStatements.toArray(new SqlStatement[0]);
}
 
Example 19
Source Project: keycloak   Source File: CustomLockService.java    License: Apache License 2.0 6 votes vote down vote up
private Set<Integer> currentIdsInDatabaseChangeLogLockTable() throws DatabaseException {
    try {
        Executor executor = ExecutorService.getInstance().getExecutor(database);
        String idColumnName = database.escapeColumnName(database.getLiquibaseCatalogName(),
                database.getLiquibaseSchemaName(),
                database.getDatabaseChangeLogLockTableName(),
                "ID");
        String lockTableName = database.escapeTableName(database.getLiquibaseCatalogName(),
                database.getLiquibaseSchemaName(),
                database.getDatabaseChangeLogLockTableName());
        SqlStatement sqlStatement = new RawSqlStatement("SELECT " + idColumnName + " FROM " + lockTableName);
        List<Map<String, ?>> rows = executor.queryForList(sqlStatement);
        Set<Integer> ids = rows.stream().map(columnMap -> ((Number) columnMap.get("ID")).intValue()).collect(Collectors.toSet());
        database.commit();
        return ids;
    } catch (UnexpectedLiquibaseException ulie) {
        // It can happen with MariaDB Galera 10.1 that UnexpectedLiquibaseException is rethrown due the DB lock.
        // It is sufficient to just rollback transaction and retry in that case.
        if (ulie.getCause() != null && ulie.getCause() instanceof DatabaseException) {
            throw (DatabaseException) ulie.getCause();
        } else {
            throw ulie;
        }
    }
}
 
Example 20
@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 21
@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 22
@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 23
Source Project: liquibase-impala   Source File: CustomSqlGenerator.java    License: 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 24
Source Project: liquibase-impala   Source File: CustomSqlGenerator.java    License: 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 25
Source Project: liquibase-impala   Source File: ImpalaDatabase.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void execute(SqlStatement[] statements, List<SqlVisitor> sqlVisitors) throws LiquibaseException {
    if (syncDdl) {
        List<SqlStatement> sqlStatementList = new ArrayList<SqlStatement>();
        sqlStatementList.add(UserSessionSettings.syncDdlStart());
        sqlStatementList.addAll(Arrays.asList(statements));
        sqlStatementList.add(UserSessionSettings.syncDdlStop());
        SqlStatement[] wrappedStatements = new SqlStatement[sqlStatementList.size()];
        sqlStatementList.toArray(wrappedStatements);
        super.execute(wrappedStatements, sqlVisitors);
    } else {
        super.execute(statements, sqlVisitors);
    }
}
 
Example 26
@Override
public SqlStatement[] generateStatements( Database database )
{
    return PerconaChangeUtil.generateStatements(this,
                database,
                super.generateStatements(database));
}
 
Example 27
@Override
public SqlStatement[] generateStatements( Database database )
{
    return PerconaChangeUtil.generateStatements(this,
                database,
                super.generateStatements(database));
}
 
Example 28
Source Project: liquibase-percona   Source File: PerconaDropIndexChange.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public SqlStatement[] generateStatements( Database database )
{
    return PerconaChangeUtil.generateStatements(this,
                database,
                super.generateStatements(database));
}
 
Example 29
@Test
public void testWithoutPercona() {
    PTOnlineSchemaChangeStatement.available = false;
    SqlStatement[] statements = generateStatements();
    Assertions.assertEquals(1, statements.length);
    Assertions.assertEquals(DropForeignKeyConstraintStatement.class, statements[0].getClass());
}
 
Example 30
@Test
public void testUpdateSQLNoAlterSqlDryMode() {
    enableLogging();
    System.setProperty(Configuration.NO_ALTER_SQL_DRY_MODE, "true");

    SqlStatement[] statements = generateStatements();
    Assertions.assertEquals(1, statements.length);
    Assertions.assertEquals(CommentStatement.class, statements[0].getClass());
    Assertions.assertEquals("pt-online-schema-change "
            + "--alter-foreign-keys-method=auto "
            + "--nocheck-unique-key-change "
            + "--alter=\"" + alterText + "\" "
            + "--host=localhost --port=3306 --user=user --password=*** --execute D=testdb,t=address",
            ((CommentStatement)statements[0]).getText());
}