Java Code Examples for liquibase.sql.Sql

The following examples show how to use liquibase.sql.Sql. 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: 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 3
@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 4
@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 5
@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 6
@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 7
/**
 * Generates the SQL statement to drop the spatial index if it exists.
 * 
 * @param statement
 *           the drop spatial index statement.
 * @param database
 *           the database.
 * @return the drop spatial index statement, if the index exists.
 */
public Sql[] generateSqlIfExists(final DropSpatialIndexStatement statement,
      final Database database) {
   final String catalogName = statement.getTableCatalogName();
   final String schemaName = statement.getTableSchemaName();
   final String tableName = statement.getTableName();
   final SpatialIndexExistsPrecondition precondition = new SpatialIndexExistsPrecondition();
   precondition.setCatalogName(catalogName);
   precondition.setSchemaName(schemaName);
   precondition.setTableName(tableName);
   final DatabaseObject example = precondition.getExample(database, tableName);
   try {
      // If a spatial index exists on the table, drop it.
      if (SnapshotGeneratorFactory.getInstance().has(example, database)) {
         return generateSql(statement, database, null);
      }
   } catch (final Exception e) {
      throw new UnexpectedLiquibaseException(e);
   }
   return new Sql[0];
}
 
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 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 10
@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 11
@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 12
@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 13
@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 14
/**
 * 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 15
/**
 * 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 16
@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 17
@DataProvider
public Object[][] generateSqlTestData() {
   final Database database = new H2Database();

   final AddColumnStatement notGeometry = new AddColumnStatement(null, null, null, null,
         "BOOLEAN", null);

   final AddColumnStatement nullSchema = new AddColumnStatement(null, null, "TEST", "COLUMN",
         "Geometry(Point, 4327)", null);
   final Sql nullSchemaExpected = new UnparsedSql("CALL AddGeometryColumn('"
         + database.getDefaultSchemaName() + "', 'TEST', 'COLUMN', 4327, 'Point', 2)");

   final AddColumnStatement complete = new AddColumnStatement(null,
         database.getDefaultSchemaName(), "TEST", "COLUMN", "Geometry(Geometry,4326)", null);
   final Sql completeExpected = new UnparsedSql("CALL AddGeometryColumn('"
         + database.getDefaultSchemaName() + "', 'TEST', 'COLUMN', 4326, 'Geometry', 2)");

   return new Object[][] { new Object[] { notGeometry, database, new Sql[0] },
         new Object[] { nullSchema, database, new Sql[] { nullSchemaExpected } },
         new Object[] { complete, database, new Sql[] { completeExpected } }, };
}
 
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: liquibase-mssql   Source File: IndexGeneratorTest.java    License: 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 24
Source Project: liquibase-mssql   Source File: PrimaryKeyGeneratorTest.java    License: 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 25
Source Project: liquibase-mssql   Source File: InsertGeneratorTest.java    License: 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 26
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 27
@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 28
@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 29
@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 30
Source Project: liquibase-impala   Source File: HiveDropColumnGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private Sql[] generateMultipleColumnSql(DropColumnStatement dropColumnStatement, Database database, Map<String, String> columnsPreserved) {
    if (columnsPreserved == null) {
        throw new UnexpectedLiquibaseException("no columns to preserve");
    }
    List<Sql> result = new ArrayList<Sql>();
    Map<String, String> columnsPreservedCopy = new HashMap<String, String>(columnsPreserved);
    String alterTable;
    List<DropColumnStatement> columns = null;

    if (dropColumnStatement.isMultiple()) {
        columns = dropColumnStatement.getColumns();
        for (DropColumnStatement statement : columns) {
            columnsPreservedCopy.remove(statement.getColumnName());
        }
        alterTable = "ALTER TABLE " + database.escapeTableName(columns.get(0).getCatalogName(), columns.get(0).getSchemaName(), columns.get(0).getTableName()) + " REPLACE COLUMNS (";
    } else {
        columnsPreservedCopy.remove(dropColumnStatement.getColumnName());
        alterTable = "ALTER TABLE " + database.escapeTableName(dropColumnStatement.getCatalogName(), dropColumnStatement.getSchemaName(), dropColumnStatement.getTableName()) + " REPLACE COLUMNS (";
    }

    int i = 0;
    for (String columnName : columnsPreservedCopy.keySet()) {
        alterTable += database.escapeObjectName(columnName, Column.class) + " " + columnsPreservedCopy.get(columnName);
        if (i < columnsPreservedCopy.size() - 1) {
            alterTable += ",";
        } else {
            alterTable += ")";
        }
        i++;
    }

    if (dropColumnStatement.isMultiple()) {
        result.add(new UnparsedSql(alterTable, getAffectedColumns(columns)));
    } else {
        result.add(new UnparsedSql(alterTable, getAffectedColumn(dropColumnStatement)));
    }
    return result.toArray(new Sql[result.size()]);
}