liquibase.sql.UnparsedSql Java Examples

The following examples show how to use liquibase.sql.UnparsedSql. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DropStoredProcedureGeneratorMSSQL.java    From liquibase-mssql with Apache License 2.0 6 votes vote down vote up
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 #2
Source File: AddGeometryColumnGeneratorGeoDBTest.java    From liquibase-spatial with Apache License 2.0 6 votes vote down vote up
@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 #3
Source File: InsertSetGenerator.java    From liquibase-mssql with 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 #4
Source File: DropSpatialTableGeneratorGeoDB.java    From liquibase-spatial with Apache License 2.0 6 votes vote down vote up
@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 #5
Source File: DropGeometryColumnGeneratorGeoDB.java    From liquibase-spatial with Apache License 2.0 6 votes vote down vote up
@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 #6
Source File: CreateSpatialIndexGeneratorPostgreSQL.java    From liquibase-spatial with Apache License 2.0 6 votes vote down vote up
@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 #7
Source File: InsertGenerator.java    From liquibase-mssql with 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 #8
Source File: DropSpatialIndexGeneratorGeoDB.java    From liquibase-spatial with Apache License 2.0 6 votes vote down vote up
@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 #9
Source File: DropSpatialTableGeneratorOracle.java    From liquibase-spatial with Apache License 2.0 6 votes vote down vote up
@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 #10
Source File: CreateSpatialIndexGeneratorMySQL.java    From liquibase-spatial with Apache License 2.0 6 votes vote down vote up
@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
Source File: DropSpatialIndexGeneratorOracle.java    From liquibase-spatial with Apache License 2.0 5 votes vote down vote up
@Override
public Sql[] generateSql(final DropSpatialIndexStatement statement, final Database database,
      final SqlGeneratorChain sqlGeneratorChain) {
   final String indexName = statement.getIndexName();
   final Index example = new Index().setName(indexName);
   if (statement.getTableName() != null) {
      example.setTable((Table) new Table().setName(statement.getTableName()).setSchema(
            statement.getTableCatalogName(), statement.getTableSchemaName()));
   }
   Index index;
   try {
      index = SnapshotGeneratorFactory.getInstance().createSnapshot(example, database);
   } catch (final Exception e) {
      throw new UnexpectedLiquibaseException("Failed to create a snapshot of '" + indexName
            + "'", e);
   }

   final String tableName = index.getTable().getName();
   final Column column = index.getColumns().get(0);

   final StringBuilder sql = new StringBuilder();
   sql.append("DELETE FROM user_sdo_geom_metadata ");
   sql.append("WHERE table_name = '").append(database.correctObjectName(tableName, Table.class));
   sql.append("' AND column_name = '").append(
         database.correctObjectName(column.getName(), Column.class));
   sql.append("'");
   final UnparsedSql deleteMetadata = new UnparsedSql(sql.toString(),
         new View().setName("user_sdo_geom_metadata"));
   return new Sql[] { deleteMetadata };
}
 
Example #12
Source File: AddPrimaryKeyGeneratorMSSQL.java    From liquibase-mssql with Apache License 2.0 5 votes vote down vote up
/**
 * The extension's implementation is essentially a copy/paste of the default implementation, with the following changes:
 *
 * 1) Removed other database platform specific logic other than MSSQL (purely to simplify)
 *
 * 2) Added support for setting fillFactor
 *
 * @param statement
 * @param database
 * @param sqlGeneratorChain
 * @return
 */
private Sql[] generateMSSQLSql(AddPrimaryKeyStatementMSSQL statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
  String sql;
  if (statement.getConstraintName() == null) {
    sql = "ALTER TABLE " + database.escapeTableName(statement.getCatalogName(), statement.getSchemaName(), statement.getTableName()) + " ADD PRIMARY KEY (" + database.escapeColumnNameList(statement.getColumnNames()) + ")";
  } else {
    sql = "ALTER TABLE " + database.escapeTableName(statement.getCatalogName(), statement.getSchemaName(), statement.getTableName()) + " ADD CONSTRAINT " + database.escapeConstraintName(statement.getConstraintName())+" PRIMARY KEY";
    if (!statement.isClustered()) {
      sql += " NONCLUSTERED";
    }
    sql += " (" + database.escapeColumnNameList(statement.getColumnNames()) + ")";
  }

  // the only new feature being added is support for fillFactor
  sql += " WITH (FILLFACTOR = " + statement.getFillFactor() + ")";

  if (StringUtils.trimToNull(statement.getTablespace()) != null && database.supportsTablespaces()) {
    sql += " ON "+statement.getTablespace();
  }

  if (statement.getForIndexName() != null) {
    sql += " USING INDEX "+database.escapeObjectName(statement.getForIndexCatalogName(), statement.getForIndexSchemaName(), statement.getForIndexName(), Index.class);
  }

  return new Sql[] {
      new UnparsedSql(sql, getAffectedPrimaryKey(statement))
  };
}
 
Example #13
Source File: CreateSpatialIndexGeneratorGeoDB.java    From liquibase-spatial with Apache License 2.0 5 votes vote down vote up
/**
 * @see liquibase.sqlgenerator.SqlGenerator#generateSql(liquibase.statement.SqlStatement,
 *      liquibase.database.Database, liquibase.sqlgenerator.SqlGeneratorChain)
 */
@Override
public Sql[] generateSql(final CreateSpatialIndexStatement 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(".CreateSpatialIndex(");

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

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

   // Add the column name parameter.
   final String columnName = statement.getColumns()[0];
   sql.append("'").append(columnName).append("'");
   sql.append(", ");

   // Add the SRID parameter.
   final int srid = statement.getSrid();
   sql.append("'").append(srid).append("'");
   sql.append(')');
   final Table hatboxTable = new Table().setName(database.correctObjectName(tableName
         + "_HATBOX", Table.class));
   hatboxTable.setSchema(catalogName, schemaName);
   final UnparsedSql spatialize = new UnparsedSql(sql.toString(), hatboxTable);

   return new Sql[] { spatialize };
}
 
Example #14
Source File: HiveDropColumnGenerator.java    From liquibase-impala with 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()]);
}
 
Example #15
Source File: CreateSpatialIndexGeneratorOracle.java    From liquibase-spatial with Apache License 2.0 5 votes vote down vote up
@Override
public Sql[] generateSql(final CreateSpatialIndexStatement statement, final Database database,
      final SqlGeneratorChain sqlGeneratorChain) {
   final View metadataView = new View().setName("USER_SDO_GEOM_METADATA");
   final String deleteMetadataSql = generateDeleteMetadataSql(statement, database);
   final Sql deleteMetadata = new UnparsedSql(deleteMetadataSql, metadataView);
   final String insertMetadataSql = generateInsertMetadataSql(statement, database);
   final Sql insertMetadata = new UnparsedSql(insertMetadataSql, metadataView);
   final String createIndexSql = generateCreateIndexSql(statement, database);
   final Sql createIndex = new UnparsedSql(createIndexSql, getAffectedIndex(statement));
   return new Sql[] { deleteMetadata, insertMetadata, createIndex };
}
 
Example #16
Source File: ImpalaCreateTableAsSelectGenerator.java    From liquibase-impala with Apache License 2.0 5 votes vote down vote up
@Override
public Sql[] generateSql(CreateTableAsSelectStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
    StringBuilder sql = new StringBuilder("CREATE TABLE ").append(database.escapeTableName(statement.getCatalogName(),
            statement.getSchemaName(), statement.getDestTableName())).append(" AS SELECT ");
    generateColumnNames(sql, statement, database);
    sql.append(" FROM ").append(database.escapeTableName(statement.getCatalogName(), statement.getSchemaName(), statement.getTableName()));
    if (statement.getWhereCondition() != null) {
        sql.append(" WHERE ").append(replacePredicatePlaceholders(database, statement.getWhereCondition(), statement.getWhereColumnNames(), statement.getWhereParameters()));
    }
    return new Sql[]{new UnparsedSql(sql.toString(), fetchAffectedTable(statement))};
}
 
Example #17
Source File: ImpalaInvalidateMetadataGenerator.java    From liquibase-impala with Apache License 2.0 5 votes vote down vote up
@Override
public Sql[] generateSql(InvalidateMetadataStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
    String catalogName = statement.getCatalogName();
    String schemaName = statement.getSchemaName();
    String tableName = statement.getTableName();
    String sql = "INVALIDATE METADATA " + database.escapeTableName(catalogName, schemaName, tableName);
    return new Sql[]{new UnparsedSql(sql, fetchAffectedTable(statement))};
}
 
Example #18
Source File: CreateTableAsSelectGenerator.java    From liquibase-impala with Apache License 2.0 5 votes vote down vote up
@Override
public Sql[] generateSql(CreateTableAsSelectStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
    StringBuilder sql = new StringBuilder("CREATE TABLE ").append(database.escapeTableName(statement.getCatalogName(),
            statement.getSchemaName(), statement.getDestTableName())).append(" AS SELECT ");
    generateColumnNames(sql, statement, database);
    sql.append(" FROM ").append(database.escapeTableName(statement.getCatalogName(), statement.getSchemaName(), statement.getTableName()));
    if (statement.getWhereCondition() != null) {
        sql.append(" WHERE ").append(replacePredicatePlaceholders(database, statement.getWhereCondition(), statement.getWhereColumnNames(), statement.getWhereParameters()));
    }
    return new Sql[]{new UnparsedSql(sql.toString(), fetchAffectedTable(statement))};
}
 
Example #19
Source File: InsertAsSelectGenerator.java    From liquibase-impala with Apache License 2.0 5 votes vote down vote up
@Override
public Sql[] generateSql(InsertAsSelectStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
    String catalogName = statement.getCatalogName();
    String schemaName = statement.getSchemaName();
    String tableName = statement.getTableName();
    StringBuilder sql = new StringBuilder("INSERT INTO ").append(database.escapeTableName(statement.getCatalogName(),
            statement.getSchemaName(), statement.getDestTableName())).append(" SELECT ");
    generateColumnNames(sql, statement, database);
    sql.append(" FROM ").append(database.escapeTableName(catalogName, schemaName, tableName));
    if (statement.getWhereCondition() != null) {
        sql.append(" WHERE ").append(replacePredicatePlaceholders(database, statement.getWhereCondition(), statement.getWhereColumnNames(), statement.getWhereParameters()));
    }
    return new Sql[]{new UnparsedSql(sql.toString(), fetchAffectedTable(statement))};
}
 
Example #20
Source File: RenameTableGenerator.java    From liquibase-impala with Apache License 2.0 5 votes vote down vote up
@Override
public Sql[] generateSql(RenameTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
    String sql = "ALTER TABLE " + database.escapeTableName(statement.getCatalogName(), statement.getSchemaName(),
            statement.getOldTableName()) + " RENAME TO " + database.escapeObjectName(statement.getNewTableName(), Table.class);
    return new Sql[]{
            new UnparsedSql(sql,
                    fetchAffectedOldTable(statement),
                    fetchAffectedNewTable(statement)
            )
    };
}
 
Example #21
Source File: CustomLockDatabaseChangeLogGenerator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private Sql generateSelectForUpdate(Database database, int id) {
    String catalog = database.getLiquibaseCatalogName();
    String schema = database.getLiquibaseSchemaName();
    String rawLockTableName = database.getDatabaseChangeLogLockTableName();

    String lockTableName = database.escapeTableName(catalog, schema, rawLockTableName);
    String idColumnName  = database.escapeColumnName(catalog, schema, rawLockTableName, "ID");

    String sqlBase = "SELECT " + idColumnName + " FROM " + lockTableName;
    String sqlWhere = " WHERE " + idColumnName + "=" + id;

    String sql;
    if (database instanceof MySQLDatabase || database instanceof PostgresDatabase || database instanceof H2Database ||
            database instanceof OracleDatabase) {
        sql = sqlBase + sqlWhere + " FOR UPDATE";
    } else if (database instanceof MSSQLDatabase) {
        sql = sqlBase + " WITH (UPDLOCK, ROWLOCK)" + sqlWhere;
    } else if (database instanceof DB2Database) {
        sql = sqlBase + sqlWhere +  " FOR READ ONLY WITH RS USE AND KEEP UPDATE LOCKS";
    } else {
        sql = sqlBase + sqlWhere;
        logger.warnf("No direct support for database %s . Database lock may not work correctly", database.getClass().getName());
    }

    logger.debugf("SQL command for pessimistic lock: %s", sql);
    
    return new UnparsedSql(sql);
}
 
Example #22
Source File: AddGeometryColumnGeneratorGeoDB.java    From liquibase-spatial with Apache License 2.0 4 votes vote down vote up
@Override
public Sql[] generateSql(final AddColumnStatement statement,
      final Database database, final SqlGeneratorChain sqlGeneratorChain) {

   GeometryType geometryType = null;
   final LiquibaseDataType dataType = DataTypeFactory.getInstance()
         .fromDescription(statement.getColumnType(), database);
   if (dataType instanceof GeometryType) {
      geometryType = (GeometryType) dataType;
   }

   final boolean isGeometryColumn = geometryType != null;

   // The AddGeometryColumn procedure handles the column already being
   // present, so let a
   // downstream SQL generator handle the typical column addition logic (e.g.
   // placement in the
   // table) then invoke the procedure.
   final List<Sql> list = new ArrayList<Sql>();
   list.addAll(Arrays.asList(sqlGeneratorChain.generateSql(statement,
         database)));
   if (isGeometryColumn) {
      String schemaName = statement.getSchemaName();
      if (schemaName == null) {
         schemaName = database.getDefaultSchemaName();
      }
      final String tableName = statement.getTableName();
      final String columnName = statement.getColumnName();

      final int srid = geometryType.getSRID();
      final String geomType = StringUtils.trimToNull(geometryType
            .getGeometryType()) == null ? "'Geometry'" : "'"
            + database.escapeStringForDatabase(geometryType
                  .getGeometryType()) + "'";
      final String sql = "CALL AddGeometryColumn('" + schemaName + "', '"
            + tableName + "', '" + columnName + "', " + srid + ", "
            + geomType + ", 2)";
      final Sql addGeometryColumn = new UnparsedSql(sql);
      list.add(addGeometryColumn);
   }
   return list.toArray(new Sql[list.size()]);
}
 
Example #23
Source File: CreateIndexGeneratorMSSQL.java    From liquibase-mssql with Apache License 2.0 4 votes vote down vote up
private Sql[] generateMSSQLSql(CreateIndexStatementMSSQL statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
  StringBuilder builder = new StringBuilder();

  // Basically copied from liquibase.sqlgenerator.core.CreateIndexGenerator
  builder.append("CREATE ");
  if (statement.isUnique() != null && statement.isUnique()) {
    builder.append("UNIQUE ");
  }
  
  if (statement.isClustered() != null) {
      if (statement.isClustered()) {
          builder.append("CLUSTERED ");
      } else {
          builder.append("NONCLUSTERED ");
      }
  }
  
  builder.append("INDEX ");

  if (statement.getIndexName() != null) {
    String indexSchema = statement.getTableSchemaName();
    builder.append(database.escapeIndexName(statement.getTableCatalogName(), indexSchema, statement.getIndexName())).append(" ");
  }
  builder.append("ON ");
  builder.append(database.escapeTableName(statement.getTableCatalogName(), statement.getTableSchemaName(), statement.getTableName())).append("(");
  Iterator<AddColumnConfig> iterator = Arrays.asList(statement.getColumns()).iterator();
  while (iterator.hasNext()) {
    AddColumnConfig column = iterator.next();
    builder.append(database.escapeColumnName(statement.getTableCatalogName(), statement.getTableSchemaName(), statement.getTableName(), column.getName()));
    if (column.getDescending() != null && column.getDescending()) {
        builder.append(" DESC");
    }
    if (iterator.hasNext()) {
      builder.append(", ");
    }
  }
  if (statement.getIncludedColumns() != null && ! statement.getIncludedColumns().isEmpty()) {
    builder.append(") INCLUDE (");
    builder.append(database.escapeColumnNameList(statement.getIncludedColumns()));
  }
  builder.append(")");
  if (statement.getFillFactor() != null) {
    builder.append(" WITH (FILLFACTOR = ").append(statement.getFillFactor()).append(")");
  }
  // This block simplified, since we know we have MSSQLDatabase
  if (StringUtils.trimToNull(statement.getTablespace()) != null) {
    builder.append(" ON ").append(statement.getTablespace());
  }

  return new Sql[]{new UnparsedSql(builder.toString(), getAffectedIndex(statement))};
}
 
Example #24
Source File: ImpalaRefreshTableGenerator.java    From liquibase-impala with Apache License 2.0 4 votes vote down vote up
@Override
public Sql[] generateSql(RefreshTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
    String sql = "REFRESH " + database.escapeTableName(statement.getCatalogName(), statement.getSchemaName(), statement.getTableName());
    return new Sql[]{new UnparsedSql(sql, fetchAffectedTable(statement))};
}
 
Example #25
Source File: SetGenerator.java    From liquibase-impala with Apache License 2.0 4 votes vote down vote up
@Override
public Sql[] generateSql(SetStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
    String sql = "SET " + statement.getQueryOption() + "=" + statement.getOptionValue();
    return new Sql[]{new UnparsedSql(sql, new Schema().getName())};
}
 
Example #26
Source File: TruncateGenerator.java    From liquibase-impala with Apache License 2.0 4 votes vote down vote up
@Override
public Sql[] generateSql(TruncateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
    final String sql = "TRUNCATE TABLE " + database.escapeTableName(statement.getCatalogName(),
            statement.getSchemaName(), statement.getTableName());
    return new Sql[]{new UnparsedSql(sql, fetchAffectedTable(statement))};
}
 
Example #27
Source File: HiveInsertGenerator.java    From liquibase-impala with Apache License 2.0 3 votes vote down vote up
@Override
public Sql[] generateSql(HiveInsertStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {

    StringBuilder sql = new StringBuilder();

    generateHeader(sql, statement, database);
    generateValues(sql, statement, database);

    return new Sql[]{new UnparsedSql(sql.toString(), getAffectedTable(statement))};
}