Java Code Examples for liquibase.sqlgenerator.SqlGeneratorChain

The following examples show how to use liquibase.sqlgenerator.SqlGeneratorChain. 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
@Override
public Sql[] generateSql(RemoveChangeSetRanStatusStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
    ChangeSet changeSet = statement.getChangeSet();
    String tmpTable = UUID.randomUUID().toString().replaceAll("-", "");
    String catalogName = database.getLiquibaseCatalogName();
    String schemaName = database.getDefaultSchemaName();
    String tableName = database.getDatabaseChangeLogTableName();
    CreateTableAsSelectStatement createTableAsSelectStatement = new CreateTableAsSelectStatement(catalogName, schemaName, tableName, tmpTable)
            .addColumnNames("ID", "AUTHOR", "FILENAME", "DATEEXECUTED", "ORDEREXECUTED", "EXECTYPE", "MD5SUM", "DESCRIPTION", "COMMENTS", "TAG", "LIQUIBASE", "CONTEXTS", "LABELS", "DEPLOYMENT_ID")
            .setWhereCondition(database.escapeObjectName("ID", Column.class) + " != ? " +
                    "AND " + database.escapeObjectName("FILENAME", Column.class) + " != ?")
            .addWhereParameters(changeSet.getId(), changeSet.getFilePath());

    return CustomSqlGenerator.generateSql(database,
            createTableAsSelectStatement,
            new DropTableStatement(catalogName, schemaName, tableName, false),
            new RenameTableStatement(catalogName, schemaName, tmpTable, tableName));
}
 
Example 2
Source Project: liquibase-impala   Source File: HiveDropColumnGenerator.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public ValidationErrors validate(DropColumnStatement dropColumnStatement, Database database, SqlGeneratorChain sqlGeneratorChain) {
    if (dropColumnStatement.isMultiple()) {
        ValidationErrors validationErrors = new ValidationErrors();
        DropColumnStatement firstColumn = dropColumnStatement.getColumns().get(0);

        for (DropColumnStatement drop : dropColumnStatement.getColumns()) {
            validationErrors.addAll(validateSingleColumn(drop));
            if (drop.getTableName() != null && !drop.getTableName().equals(firstColumn.getTableName())) {
                validationErrors.addError("All columns must be targeted at the same table");
            }
            if (drop.isMultiple()) {
                validationErrors.addError("Nested multiple drop column statements are not supported");
            }
        }
        return validationErrors;
    } else {
        return validateSingleColumn(dropColumnStatement);
    }
}
 
Example 3
Source Project: liquibase-impala   Source File: HiveTagDatabaseGenerator.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Sql[] generateSql(TagDatabaseStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
    String catalogName = database.getLiquibaseCatalogName();
    String schemaName = database.getDefaultSchemaName();
    String tableName = database.getDatabaseChangeLogTableName();
    String tableNameEscaped = database.escapeObjectName(tableName, Table.class);
    String dateColumnNameEscaped = database.escapeObjectName("DATEEXECUTED", Column.class);
    String tagColumnNameEscaped = database.escapeObjectName("TAG", Column.class);
    String tempTable = UUID.randomUUID().toString().replaceAll("-", "");
    CreateTableAsSelectStatement createTableAsSelectStatement = new CreateTableAsSelectStatement(catalogName, schemaName, tableName, tempTable)
            .addColumnNames("ID", "AUTHOR", "FILENAME", "DATEEXECUTED", "ORDEREXECUTED", "EXECTYPE", "MD5SUM", "DESCRIPTION", "COMMENTS", "TAG", "LIQUIBASE", "CONTEXTS", "LABELS", "DEPLOYMENT_ID")
            .setWhereCondition(tableNameEscaped + "." + dateColumnNameEscaped + " NOT IN (SELECT MAX(" + tableNameEscaped + "." + dateColumnNameEscaped + ") " +
                    "FROM " + tableNameEscaped + ")");
    InsertAsSelectStatement insertAsSelectStatement = new InsertAsSelectStatement(catalogName, schemaName, tableName, tempTable)
            .addColumnNames("ID", "AUTHOR", "FILENAME", "DATEEXECUTED", "ORDEREXECUTED", "EXECTYPE", "MD5SUM", "DESCRIPTION", "COMMENTS", "'" + statement.getTag() + "'", "LIQUIBASE", "CONTEXTS", "LABELS", "DEPLOYMENT_ID")
            .setWhereCondition(tableNameEscaped + "." + dateColumnNameEscaped + " IN (SELECT MAX(" + tableNameEscaped + "." + dateColumnNameEscaped + ") FROM " + tableNameEscaped + ") AND ("
                    + tableNameEscaped + "." + tagColumnNameEscaped + " IS NULL OR " + tableNameEscaped + "." + tagColumnNameEscaped + " != ?)").addWhereParameters(statement.getTag());

    return CustomSqlGenerator.generateSql(database,
            createTableAsSelectStatement,
            insertAsSelectStatement,
            new DropTableStatement(catalogName, schemaName, tableName, false),
            new RenameTableStatement(catalogName, schemaName, tempTable, tableName));
}
 
Example 4
@Override
public Sql[] generateSql(CreateDatabaseChangeLogTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
    String TypeNameChar = "STRING";

    CreateTableStatement createTableStatement = new CreateTableStatement(database.getLiquibaseCatalogName(), database.getLiquibaseSchemaName(), database.getDatabaseChangeLogTableName())
            .setTablespace(database.getLiquibaseTablespaceName())
            .addColumn("ID", DataTypeFactory.getInstance().fromDescription(TypeNameChar, database))
            .addColumn("AUTHOR", DataTypeFactory.getInstance().fromDescription(TypeNameChar, database))
            .addColumn("FILENAME", DataTypeFactory.getInstance().fromDescription(TypeNameChar, database))
            .addColumn("DATEEXECUTED", DataTypeFactory.getInstance().fromDescription("TIMESTAMP", database))
            .addColumn("ORDEREXECUTED", DataTypeFactory.getInstance().fromDescription("INT", database))
            .addColumn("EXECTYPE", DataTypeFactory.getInstance().fromDescription(TypeNameChar, database))
            .addColumn("MD5SUM", DataTypeFactory.getInstance().fromDescription(TypeNameChar, database))
            .addColumn("DESCRIPTION", DataTypeFactory.getInstance().fromDescription(TypeNameChar, database))
            .addColumn("COMMENTS", DataTypeFactory.getInstance().fromDescription(TypeNameChar, database))
            .addColumn("TAG", DataTypeFactory.getInstance().fromDescription(TypeNameChar, database))
            .addColumn("LIQUIBASE", DataTypeFactory.getInstance().fromDescription(TypeNameChar, database))
            .addColumn("CONTEXTS", DataTypeFactory.getInstance().fromDescription(TypeNameChar, database))
            .addColumn("LABELS", DataTypeFactory.getInstance().fromDescription(TypeNameChar, database))
            .addColumn("DEPLOYMENT_ID", DataTypeFactory.getInstance().fromDescription(TypeNameChar, database));

    return CustomSqlGenerator.generateSql(database, UserSessionSettings.syncDdlStart(), createTableStatement, UserSessionSettings.syncDdlStop());
}
 
Example 5
@Override
public Sql[] generateSql(RemoveChangeSetRanStatusStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
    ChangeSet changeSet = statement.getChangeSet();
    String tmpTable = UUID.randomUUID().toString().replaceAll("-", "");
    String catalogName = database.getLiquibaseCatalogName();
    String schemaName = database.getDefaultSchemaName();
    String tableName = database.getDatabaseChangeLogTableName();
    CreateTableAsSelectStatement createTableAsSelectStatement = new CreateTableAsSelectStatement(catalogName, schemaName, tableName, tmpTable)
            .addColumnNames("ID", "AUTHOR", "FILENAME", "DATEEXECUTED", "ORDEREXECUTED", "EXECTYPE", "MD5SUM", "DESCRIPTION", "COMMENTS", "TAG", "LIQUIBASE", "CONTEXTS", "LABELS", "DEPLOYMENT_ID")
            .setWhereCondition(" NOT (" + database.escapeObjectName("ID", Column.class) + " = ? " +
                    "AND " + database.escapeObjectName("FILENAME", Column.class) + " = ?)")
            .addWhereParameters(changeSet.getId(), changeSet.getFilePath());

    return CustomSqlGenerator.generateSql(database,
            UserSessionSettings.syncDdlStart(),
            createTableAsSelectStatement,
            new DropTableStatement(catalogName, schemaName, tableName, false),
            new RenameTableStatement(catalogName, schemaName, tmpTable, tableName),
            UserSessionSettings.syncDdlStop());
}
 
Example 6
@Override
public Sql[] generateSql(LockDatabaseChangeLogStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
    String catalogName = database.getLiquibaseCatalogName();
    String schemaName = database.getDefaultSchemaName();
    String tableName = database.getDatabaseChangeLogLockTableName();
    InsertStatement insertStatement = new InsertStatement(catalogName, schemaName, tableName)
            .addColumnValue("ID", 1)
            .addColumnValue("LOCKED", Boolean.TRUE)
            .addColumnValue("LOCKEDBY", hostname + " [" + hostaddress + "]")
            .addColumnValue("LOCKGRANTED", DateTimeUtils.getCurrentTS("yyyy-MM-dd HH:mm:ss"));

    return CustomSqlGenerator.generateSql(database,
            UserSessionSettings.syncDdlStart(),
            new TruncateTableStatement(catalogName, schemaName, tableName),
            insertStatement,
            UserSessionSettings.syncDdlStop());
}
 
Example 7
@Override
public Sql[] generateSql(final DropSpatialIndexStatement statement,
      final Database database, final SqlGeneratorChain sqlGeneratorChain) {
   final String catalogName = statement.getTableCatalogName();
   String schemaName = statement.getTableSchemaName();
   if (schemaName == null) {
      schemaName = database.getDefaultSchemaName();
   }

   final StringBuilder sql = new StringBuilder("CALL ");
   sql.append(schemaName).append(".DropSpatialIndex(");

   // Add the schema name parameter.
   sql.append("'").append(database.escapeStringForDatabase(schemaName)).append("'");
   sql.append(", ");

   // Add the table name parameter.
   final String tableName = statement.getTableName();
   sql.append("'").append(database.escapeStringForDatabase(tableName)).append("'");
   sql.append(')');

   final Table hatboxTable = new Table().setName(tableName + "_HATBOX");
   hatboxTable.setSchema(catalogName, schemaName);
   final UnparsedSql spatialize = new UnparsedSql(sql.toString(), hatboxTable);
   return new Sql[] { spatialize };
}
 
Example 8
@Override
public Sql[] generateSql(final CreateTableStatement statement, final Database database,
      final SqlGeneratorChain sqlGeneratorChain) {
   final List<Sql> list = new ArrayList<Sql>(Arrays.asList(sqlGeneratorChain.generateSql(
         statement, database)));
   for (final Entry<String, LiquibaseDataType> entry : statement.getColumnTypes().entrySet()) {
      if (entry.getValue() instanceof GeometryType) {
         final String columnName = entry.getKey();
         final GeometryType geometryType = (GeometryType) entry.getValue();
         final AddGeometryColumnGeneratorGeoDB generator = new AddGeometryColumnGeneratorGeoDB();
         final AddColumnStatement addColumnStatement = new AddColumnStatement(
               statement.getCatalogName(), statement.getSchemaName(), statement.getTableName(),
               columnName, geometryType.toString(), null);
         @SuppressWarnings("rawtypes")
         final SqlGeneratorChain emptyChain = new SqlGeneratorChain(new TreeSet<SqlGenerator>());
         final Sql[] addGeometryColumnSql = generator.generateSql(addColumnStatement, database,
               emptyChain);
         list.addAll(Arrays.asList(addGeometryColumnSql));
      }
   }
   return list.toArray(new Sql[list.size()]);
}
 
Example 9
@Override
public ValidationErrors validate(final AddColumnStatement statement,
      final Database database, final SqlGeneratorChain sqlGeneratorChain) {
   final ValidationErrors errors = new ValidationErrors();
   final LiquibaseDataType dataType = DataTypeFactory.getInstance()
         .fromDescription(statement.getColumnType(), database);

   // Ensure that the SRID parameter is provided.
   if (dataType instanceof GeometryType) {
      final GeometryType geometryType = (GeometryType) dataType;
      if (geometryType.getSRID() == null) {
         errors.addError("The SRID parameter is required on the geometry type");
      }
   }
   final ValidationErrors chainErrors = sqlGeneratorChain.validate(
         statement, database);
   if (chainErrors != null) {
      errors.addAll(chainErrors);
   }
   return errors;
}
 
Example 10
@Override
public Sql[] generateSql(final CreateSpatialIndexStatement statement, final Database database,
      final SqlGeneratorChain sqlGeneratorChain) {
   final StringBuilder sql = new StringBuilder();
   sql.append("CREATE SPATIAL INDEX ");
   final String indexSchema = statement.getTableSchemaName();
   sql.append(database.escapeIndexName(statement.getTableCatalogName(), indexSchema,
         statement.getIndexName()));
   sql.append(" ON ");
   sql.append(
         database.escapeTableName(statement.getTableCatalogName(),
               statement.getTableSchemaName(), statement.getTableName())).append("(");
   final Iterator<String> iterator = Arrays.asList(statement.getColumns()).iterator();
   final String column = iterator.next();
   sql.append(database.escapeColumnName(statement.getTableCatalogName(),
         statement.getTableSchemaName(), statement.getTableName(), column));
   sql.append(")");
   final Sql createIndex = new UnparsedSql(sql.toString(), getAffectedIndex(statement));
   return new Sql[] { createIndex };
}
 
Example 11
@Override
public Sql[] generateSql(final DropTableStatement statement, final Database database,
      final SqlGeneratorChain sqlGeneratorChain) {
   final StringBuilder sql = new StringBuilder();
   sql.append("DELETE FROM user_sdo_geom_metadata ");
   sql.append("WHERE table_name = '").append(
         database.correctObjectName(statement.getTableName(), Table.class));
   sql.append("'");
   final UnparsedSql deleteMetadata = new UnparsedSql(sql.toString(),
         new View().setName("user_sdo_geom_metadata"));

   // First delete the record then perform the standard behavior.
   final List<Sql> list = new ArrayList<Sql>();
   list.add(deleteMetadata);
   list.addAll(Arrays.asList(sqlGeneratorChain.generateSql(statement, database)));
   return list.toArray(new Sql[list.size()]);
}
 
Example 12
@Override
public Sql[] generateSql(final CreateSpatialIndexStatement statement, final Database database,
      final SqlGeneratorChain sqlGeneratorChain) {
   final StringBuilder sql = new StringBuilder();
   sql.append("CREATE INDEX ");
   sql.append(database.escapeObjectName(statement.getIndexName(), Index.class));
   sql.append(" ON ");
   sql.append(database.escapeTableName(statement.getTableCatalogName(),
         statement.getTableSchemaName(), statement.getTableName()));
   sql.append(" USING GIST ").append("(");
   final Iterator<String> iterator = Arrays.asList(statement.getColumns()).iterator();
   while (iterator.hasNext()) {
      final String column = iterator.next();
      sql.append(database.escapeColumnName(statement.getTableCatalogName(),
            statement.getTableSchemaName(), statement.getTableName(), column));
      if (iterator.hasNext()) {
         sql.append(", ");
      }
   }
   sql.append(")");
   final Sql createIndex = new UnparsedSql(sql.toString(), getAffectedIndex(statement));
   return new Sql[] { createIndex };
}
 
Example 13
@Override
public Sql[] generateSql(final DropColumnStatement statement, final Database database,
      final SqlGeneratorChain sqlGeneratorChain) {

   String schemaName = statement.getSchemaName();
   if (schemaName == null) {
      schemaName = database.getDefaultSchemaName();
   }
   final String tableName = statement.getTableName();
   final String columnName = statement.getColumnName();
   final boolean isGeometryColumn = GeometryColumnsUtils.isGeometryColumn(database, schemaName,
         tableName, columnName);
   final List<Sql> list = new ArrayList<Sql>();
   if (isGeometryColumn) {
      dropSpatialIndexIfExists(statement.getCatalogName(), schemaName, tableName, database, list);
      final String sql = "CALL DropGeometryColumn('" + schemaName + "', '" + tableName + "', '"
            + columnName + "')";
      final Column column = getAffectedColumn(statement);
      final Sql dropGeometryColumn = new UnparsedSql(sql, column);
      list.add(dropGeometryColumn);
   } else {
      list.addAll(Arrays.asList(sqlGeneratorChain.generateSql(statement, database)));
   }
   return list.toArray(new Sql[list.size()]);
}
 
Example 14
@Override
public Sql[] generateSql(final DropTableStatement statement, final Database database,
      final SqlGeneratorChain sqlGeneratorChain) {
   final List<Sql> list = new ArrayList<Sql>();
   String schemaName = statement.getSchemaName();
   if (schemaName == null) {
      schemaName = database.getDefaultSchemaName();
   }
   final String tableName = statement.getTableName();

   // If the table has a geometry column, drop it first.
   if (GeometryColumnsUtils.hasGeometryColumn(database, schemaName, tableName)) {
      dropSpatialIndexIfExists(statement.getCatalogName(), schemaName, tableName, database, list);
      final String sql = "CALL DropGeometryColumns('" + schemaName + "', '" + tableName + "')";
      final Sql addGeometryColumn = new UnparsedSql(sql);
      list.add(addGeometryColumn);
   }
   list.addAll(Arrays.asList(sqlGeneratorChain.generateSql(statement, database)));
   return list.toArray(new Sql[list.size()]);
}
 
Example 15
/**
 * Tests
 * {@link CreateSpatialIndexGeneratorMySQL#generateSql(CreateSpatialIndexStatement, Database, SqlGeneratorChain)}
 * with a variety of inputs.
 * 
 * @param statement
 */
@Test(dataProvider = "generateSqlTestData")
public void testGenerateSql(final CreateSpatialIndexStatement statement) {
   final CreateSpatialIndexGeneratorMySQL generator = new CreateSpatialIndexGeneratorMySQL();
   final Database database = new MySQLDatabase();
   final SqlGeneratorChain sqlGeneratorChain = mock(SqlGeneratorChain.class);
   final Sql[] result = generator.generateSql(statement, database, sqlGeneratorChain);
   assertNotNull(result);
   assertEquals(result.length, 1);
   final String sql = result[0].toSql();
   String pattern = "(?i)CREATE SPATIAL INDEX " + statement.getIndexName() + " ON ";
   if (statement.getTableCatalogName() != null) {
      pattern += statement.getTableCatalogName() + '.';
   } else if (statement.getTableSchemaName() != null) {
      pattern += statement.getTableSchemaName() + '.';
   }
   pattern += statement.getTableName() + "\\(" + statement.getColumns()[0] + "\\)";
   assertTrue(sql.matches(pattern), "'" + sql + "' does not match the pattern '" + pattern + "'");
   assertNotNull(result[0].getAffectedDatabaseObjects());
   assertTrue(result[0].getAffectedDatabaseObjects().size() > 1, result[0]
         .getAffectedDatabaseObjects().toString());
}
 
Example 16
/**
 * Tests
 * {@link DropSpatialTableGeneratorOracle#generateSql(DropTableStatement, Database, SqlGeneratorChain)}
 */
@Test
public void testGenerateSql() {
   final DropSpatialTableGeneratorOracle generator = new DropSpatialTableGeneratorOracle();
   final Database database = new OracleDatabase();
   final SqlGeneratorChain sqlGeneratorChain = mock(SqlGeneratorChain.class);
   final DropTableStatement statement = new DropTableStatement("catalog_name", "schema_name",
         "table_name", true);
   final Sql comment = new SingleLineComment("No-op", "--");
   when(sqlGeneratorChain.generateSql(statement, database)).thenReturn(new Sql[] { comment });
   final Sql[] result = generator.generateSql(statement, database, sqlGeneratorChain);
   assertNotNull(result);
   assertEquals(result.length, 2);
   assertEquals(result[1], comment);

   // Verify the DELETE statement.
   final String deleteSql = result[0].toSql();
   String deletePattern = "(?i)DELETE FROM user_sdo_geom_metadata ";
   deletePattern += "WHERE table_name = '" + statement.getTableName().toUpperCase();
   deletePattern += "'";
   assertTrue(deleteSql.matches(deletePattern), "'" + deleteSql
         + "' does not match the pattern '" + deletePattern + "'");
   assertNotNull(result[0].getAffectedDatabaseObjects());
   assertTrue(result[0].getAffectedDatabaseObjects().size() >= 1, result[0]
         .getAffectedDatabaseObjects().toString());
}
 
Example 17
@Test(dataProvider = "generateSqlTestData")
public void testGenerateSql(final AddColumnStatement statement, final Database database,
      final Sql[] expected) {
   final AddGeometryColumnGeneratorGeoDB generator = new AddGeometryColumnGeneratorGeoDB();
   final SqlGeneratorChain sqlGeneratorChain = mock(SqlGeneratorChain.class);
   when(sqlGeneratorChain.generateSql(statement, database)).thenReturn(new Sql[0]);
   final Sql[] result = generator.generateSql(statement, database, sqlGeneratorChain);
   assertEquals(result.length, expected.length);
   if (result.length > 0) {
      for (int ii = 0; ii < result.length; ii++) {
         final Sql resultSql = result[ii];
         final Sql expectedSql = expected[ii];
         assertEquals(resultSql.toSql(), expectedSql.toSql());
      }
   }
}
 
Example 18
@Test(dataProvider = "generateSqlTestData")
public void testGenerateSql(final DropColumnStatement statement, final Database database,
      final Sql[] expected) throws DatabaseException {
   final DropGeometryColumnGeneratorGeoDB generator = new DropGeometryColumnGeneratorGeoDB();
   final SqlGeneratorChain sqlGeneratorChain = mock(SqlGeneratorChain.class);
   when(sqlGeneratorChain.generateSql(statement, database)).thenReturn(new Sql[0]);
   final Sql[] result = generator.generateSql(statement, database, sqlGeneratorChain);
   assertEquals(result.length, expected.length);
   if (result.length > 0) {
      for (int ii = 0; ii < result.length; ii++) {
         final Sql resultSql = result[ii];
         final Sql expectedSql = expected[ii];
         assertEquals(resultSql.toSql(), expectedSql.toSql());
      }
   }
}
 
Example 19
/**
 * Tests
 * {@link CreateSpatialIndexGeneratorPostgreSQL#generateSql(CreateSpatialIndexStatement, Database, SqlGeneratorChain)}
 * with a variety of inputs.
 * 
 * @param statement
 */
@Test(dataProvider = "generateSqlTestData")
public void testGenerateSql(final CreateSpatialIndexStatement statement) {
   final CreateSpatialIndexGeneratorPostgreSQL generator = new CreateSpatialIndexGeneratorPostgreSQL();
   final Database database = new PostgresDatabase();
   final SqlGeneratorChain sqlGeneratorChain = mock(SqlGeneratorChain.class);
   final Sql[] result = generator.generateSql(statement, database, sqlGeneratorChain);
   assertNotNull(result);
   assertEquals(result.length, 1);
   final String sql = result[0].toSql();
   String pattern = "(?i)CREATE INDEX ";
   pattern += statement.getIndexName() + " ON ";
   if (statement.getTableSchemaName() != null) {
      pattern += statement.getTableSchemaName() + '.';
   }
   pattern += statement.getTableName() + " USING GIST \\(" + statement.getColumns()[0];
   if (statement.getColumns().length > 1) {
      pattern += ", " + statement.getColumns()[1];
   }
   pattern += "\\)";
   assertTrue(sql.matches(pattern), "'" + sql + "' does not match the pattern '" + pattern + "'");
   assertNotNull(result[0].getAffectedDatabaseObjects());
   assertTrue(result[0].getAffectedDatabaseObjects().size() > 1, result[0]
         .getAffectedDatabaseObjects().toString());
}
 
Example 20
Source Project: liquibase-mssql   Source File: InsertGenerator.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Sql[] generateSql(InsertStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
    Boolean identityInsertEnabled = false;
    if (statement instanceof InsertStatementMSSQL) {
        identityInsertEnabled = ((InsertStatementMSSQL)statement).getIdentityInsertEnabled();
    }
    if (identityInsertEnabled == null || !identityInsertEnabled) {
        return super.generateSql(statement, database, sqlGeneratorChain);
    }
    String tableName = database.escapeTableName(statement.getCatalogName(), statement.getSchemaName(), statement.getTableName());
    String enableIdentityInsert = "SET IDENTITY_INSERT " + tableName + " ON";
    String disableIdentityInsert = "SET IDENTITY_INSERT " + tableName + " OFF";
    String safelyEnableIdentityInsert = ifTableHasIdentityColumn(enableIdentityInsert, statement, database.getDefaultSchemaName());
    String safelyDisableIdentityInsert = ifTableHasIdentityColumn(disableIdentityInsert, statement, database.getDefaultSchemaName());

    List<Sql> sql = new ArrayList<Sql>(Arrays.asList(sqlGeneratorChain.generateSql(statement, database)));
    sql.add(0, new UnparsedSql(safelyEnableIdentityInsert));
    sql.add(new UnparsedSql(safelyDisableIdentityInsert));
    return sql.toArray(new Sql[sql.size()]);
}
 
Example 21
Source Project: liquibase-mssql   Source File: InsertSetGenerator.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Sql[] generateSql(InsertSetStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
    Boolean identityInsertEnabled = false;
    if (statement instanceof InsertSetStatementMSSQL) {
        identityInsertEnabled = ((InsertSetStatementMSSQL) statement).getIdentityInsertEnabled();
    }
    if (identityInsertEnabled == null || !identityInsertEnabled) {
        return super.generateSql(statement, database, sqlGeneratorChain);
    }
    String tableName = database.escapeTableName(statement.getCatalogName(), statement.getSchemaName(),
                    statement.getTableName());
    String enableIdentityInsert = "SET IDENTITY_INSERT " + tableName + " ON";
    String disableIdentityInsert = "SET IDENTITY_INSERT " + tableName + " OFF";
    String safelyEnableIdentityInsert = ifTableHasIdentityColumn(enableIdentityInsert, statement,
                    database.getDefaultSchemaName());
    String safelyDisableIdentityInsert = ifTableHasIdentityColumn(disableIdentityInsert, statement,
                    database.getDefaultSchemaName());

    List<Sql> sql = new ArrayList<Sql>(Arrays.asList(sqlGeneratorChain.generateSql(statement, database)));
    sql.add(0, new UnparsedSql(safelyEnableIdentityInsert));
    sql.add(new UnparsedSql(safelyDisableIdentityInsert));
    return sql.toArray(new Sql[sql.size()]);
}
 
Example 22
public Sql[] generateSql(DropStoredProcedureStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
    StringBuilder sql = new StringBuilder();
    sql.append("declare @procName varchar(500)\n");
    sql.append("declare cur cursor\n");
    sql.append("for select [name] from sys.objects where type = 'p' AND is_ms_shipped = 0\n");
    sql.append("open cur\n");
    sql.append("fetch next from cur into @procName\n");
    sql.append("while @@fetch_status = 0\n");
    sql.append("begin\n");
    sql.append("exec('drop procedure ' + @procName)\n");
    sql.append("fetch next from cur into @procName\n");
    sql.append("end\n");
    sql.append("close cur\n");
    sql.append("deallocate cur\n");
    
    return (new Sql[] {
        new UnparsedSql(sql.toString(), new DatabaseObject[0])
    });
}
 
Example 23
Source Project: keycloak   Source File: CustomInsertLockRecordGenerator.java    License: 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 24
@Override
public Sql[] generateSql(LockDatabaseChangeLogStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
    String catalogName = database.getLiquibaseCatalogName();
    String schemaName = database.getDefaultSchemaName();
    String tableName = database.getDatabaseChangeLogLockTableName();
    HiveInsertStatement hiveInsertStatement = new HiveInsertStatement(catalogName, schemaName, tableName);
    hiveInsertStatement.addColumnValue(1);
    hiveInsertStatement.addColumnValue(Boolean.TRUE);
    hiveInsertStatement.addColumnValue(hostname + " (" + hostaddress + ")");
    hiveInsertStatement.addColumnValue(DateTimeUtils.getCurrentTS("yyyy-MM-dd HH:mm:ss"));

    return CustomSqlGenerator.generateSql(database,
            new TruncateTableStatement(catalogName, schemaName, tableName),
            hiveInsertStatement);
}
 
Example 25
Source Project: liquibase-impala   Source File: HiveInsertGenerator.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ValidationErrors validate(HiveInsertStatement insertStatement, Database database, SqlGeneratorChain sqlGeneratorChain) {
    ValidationErrors validationErrors = new ValidationErrors();
    validationErrors.checkRequiredField("tableName", insertStatement.getTableName());
    validationErrors.checkRequiredField("columns", insertStatement.getColumnValues());

    return validationErrors;
}
 
Example 26
@Override
public Sql[] generateSql(UnlockDatabaseChangeLogStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
    String catalogName = database.getLiquibaseCatalogName();
    String schemaName = database.getDefaultSchemaName();
    String tableName = database.getDatabaseChangeLogLockTableName();
    HiveInsertStatement hiveInsertStatement = new HiveInsertStatement(catalogName, schemaName, tableName)
            .addColumnValue(1)
            .addColumnValue(Boolean.FALSE)
            .addColumnValue("NULL")
            .addColumnValue("NULL");

    return CustomSqlGenerator.generateSql(database,
            new TruncateTableStatement(catalogName, schemaName, tableName),
            hiveInsertStatement);
}
 
Example 27
@Override
public Sql[] generateSql(InitializeDatabaseChangeLogLockTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
    String catalogName = database.getLiquibaseCatalogName();
    String schemaName = database.getDefaultSchemaName();
    String tableName = database.getDatabaseChangeLogLockTableName();
    HiveInsertStatement insertStatementHive = new HiveInsertStatement(catalogName, schemaName, tableName)
            .addColumnValue(1)
            .addColumnValue(Boolean.FALSE)
            .addColumnValue("NULL")
            .addColumnValue("NULL");

    return CustomSqlGenerator.generateSql(database,
            new TruncateTableStatement(catalogName, schemaName, tableName),
            insertStatementHive);
}
 
Example 28
@Override
public ValidationErrors validate(MarkChangeSetRanStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
    ValidationErrors validationErrors = new ValidationErrors();
    validationErrors.checkRequiredField("changeSet", statement.getChangeSet());

    return validationErrors;
}
 
Example 29
@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 30
@Override
public Sql[] generateSql(CreateDatabaseChangeLogLockTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
    CreateTableStatement createTableStatement = new CreateTableStatement(database.getLiquibaseCatalogName(), database.getLiquibaseSchemaName(), database.getDatabaseChangeLogLockTableName())
            .addColumn("ID", DataTypeFactory.getInstance().fromDescription("INT", database))
            .addColumn("LOCKED", DataTypeFactory.getInstance().fromDescription("BOOLEAN", database))
            .addColumn("LOCKGRANTED", DataTypeFactory.getInstance().fromDescription("TIMESTAMP", database))
            .addColumn("LOCKEDBY", DataTypeFactory.getInstance().fromDescription("STRING", database));

    return CustomSqlGenerator.generateSql(database, UserSessionSettings.syncDdlStart(), createTableStatement, UserSessionSettings.syncDdlStop());
}