Java Code Examples for liquibase.database.Database

The following examples show how to use liquibase.database.Database. 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
Source Project: liquibase-spatial   Source File: GeometryType.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @see liquibase.datatype.LiquibaseDataType#sqlToObject(java.lang.String,
 *      liquibase.database.Database)
 */
@Override
public Object sqlToObject(final String value, final Database database) {
   final Geometry returnValue;
   if (value == null || value.equalsIgnoreCase("null")) {
      returnValue = null;
   } else {
      final WKTReader reader = new WKTReader();
      try {
         // TODO: Check for SRID.
         returnValue = reader.read(value);
      } catch (final ParseException e) {
         throw new UnexpectedLiquibaseException("Cannot parse " + value + " to a Geometry", e);
      }
   }
   return returnValue;
}
 
Example 2
@DataProvider
public Object[][] geometryColumnsExistsTestData() throws SQLException {
   // Create an H2 database instance without geometry_columns table.
   final Database noGeometryColumnsDatabase = new H2Database();
   noGeometryColumnsDatabase.setConnection(new JdbcConnection(DriverManager
         .getConnection("jdbc:h2:mem:target/noGeometryColumns")));

   final Database geometryColumnsDatabase = new H2Database();
   Connection connection = DriverManager
         .getConnection("jdbc:h2:mem:target/geometryColumns");
   DatabaseConnection conn = new JdbcConnection(connection);
   geometryColumnsDatabase.setConnection(conn);

   Statement statement = connection.createStatement();
   statement
         .execute("CREATE TABLE geometry_columns (f_table_schema VARCHAR(128), "
               + "f_table_name VARCHAR(128), f_geometry_column VARCHAR(128), coord_dimension INT, "
               + "srid INT, type VARCHAR(30))");
   statement.close();
   return new Object[][] {
         new Object[] { noGeometryColumnsDatabase, false },
         new Object[] { geometryColumnsDatabase, true } };
}
 
Example 3
Source Project: liquibase-spatial   Source File: WktConversionUtilsTest.java    License: Apache License 2.0 6 votes vote down vote up
@DataProvider
public Object[][] handleColumnValueTestData() {
   final Database database = mock(Database.class);
   final WktInsertOrUpdateGenerator generator = mock(WktInsertOrUpdateGenerator.class);
   when(generator.convertToFunction(anyString(), anyString(), eq(database))).thenAnswer(
         new Answer<String>() {
            @Override
            public String answer(final InvocationOnMock invocation) throws Throwable {
               return invocation.getArguments()[0] + "," + invocation.getArguments()[1];
            }
         });
   final String wkt = "POINT(0 0)";
   final String srid = "SRID=4326";
   return new Object[][] { new Object[] { null, database, generator, null },
         new Object[] { 12345, database, generator, 12345 },
         new Object[] { "test", database, generator, "test" },
         new Object[] { wkt, database, generator, wkt + ",null" },
         new Object[] { srid + ";" + wkt, database, generator, wkt + ",4326" }, };
}
 
Example 4
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 5
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 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
/**
 * @see liquibase.change.AbstractChange#validate(liquibase.database.Database)
 */
@Override
public ValidationErrors validate(final Database database) {
   final ValidationErrors validationErrors = new ValidationErrors();
   if (this.srid != null) {
      if (!this.srid.matches("[0-9]+")) {
         validationErrors.addError("The SRID must be numeric");
      }
   }

   if (!validationErrors.hasErrors()) {
      validationErrors.addAll(super.validate(database));
   }

   return validationErrors;
}
 
Example 8
/**
 * 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 9
Source Project: liquibase-spatial   Source File: OracleSpatialUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Queries to the database to convert the given EPSG SRID to the corresponding Oracle SRID.
 *
 * @param srid
 *           the EPSG SRID.
 * @param database
 *           the database instance.
 * @return the corresponding Oracle SRID.
 */
public static String loadOracleSrid(final String srid, final Database database) {
   final String oracleSrid;
   final JdbcConnection jdbcConnection = (JdbcConnection) database.getConnection();
   final Connection connection = jdbcConnection.getUnderlyingConnection();
   Statement statement = null;
   try {
      statement = connection.createStatement();
      final ResultSet resultSet = statement.executeQuery("SELECT " + EPSG_TO_ORACLE_FUNCTION
            + "(" + srid + ") FROM dual");
      resultSet.next();
      oracleSrid = resultSet.getString(1);
   } catch (final SQLException e) {
      throw new UnexpectedLiquibaseException("Failed to find the Oracle SRID for EPSG:" + srid,
            e);
   } finally {
      try {
         statement.close();
      } catch (final SQLException ignore) {
      }
   }
   return oracleSrid;
}
 
Example 10
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 11
@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 12
Source Project: liquibase-spatial   Source File: WktConversionUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Converts the given Well-Known Text and SRID to the appropriate function
 * call for the database.
 * 
 * @param wkt
 *           the Well-Known Text string.
 * @param srid
 *           the SRID string which may be an empty string.
 * @param database
 *           the database instance.
 * @param generator
 *           the SQL generator.
 * @return the string that converts the WKT to a database-specific geometry.
 */
public static String convertToFunction(final String wkt, final String srid,
      final Database database, final WktInsertOrUpdateGenerator generator) {
   if (wkt == null || wkt.equals("")) {
      throw new IllegalArgumentException(
            "The Well-Known Text cannot be null or empty");
   }
   if (generator == null) {
      throw new IllegalArgumentException("The generator cannot be null or empty");
   }
   final String geomFromTextFunction = generator.getGeomFromWktFunction();
   String function = geomFromTextFunction + "('" + wkt + "'";
   if (srid != null && !srid.equals("")) {
      function += ", " + srid;
   } else if (generator.isSridRequiredInFunction(database)) {
      throw new IllegalArgumentException("An SRID was not provided with '" + wkt
            + "' but is required in call to '" + geomFromTextFunction + "'");
   }
   function += ")";
   return function;
}
 
Example 13
/**
 * Generates the {@link Index} example (taken from {@link IndexExistsPrecondition}).
 *
 * @param database
 *           the database instance.
 * @param schema
 *           the schema instance.
 * @param tableName
 *           the table name of the index.
 * @return the index example.
 */
protected Index getIndexExample(final Database database, final Schema schema,
      final String tableName) {
   final Index example = new Index();
   if (tableName != null) {
      example.setTable((Table) new Table().setName(
            database.correctObjectName(getTableName(), Table.class)).setSchema(schema));
   }
   example.setName(database.correctObjectName(getIndexName(), Index.class));
   if (StringUtils.trimToNull(getColumnNames()) != null) {
      for (final String columnName : getColumnNames().split("\\s*,\\s*")) {
         final Column column = new Column(database.correctObjectName(columnName, Column.class));
         example.getColumns().add(column);
      }
   }
   return example;
}
 
Example 14
Source Project: liquibase-impala   Source File: InsertAsSelectGenerator.java    License: Apache License 2.0 6 votes vote down vote up
private void generateColumnNames(StringBuilder sql, InsertAsSelectStatement statement, Database database) {
    String catalogName = statement.getCatalogName();
    String schemaName = statement.getSchemaName();
    String tableName = statement.getTableName();
    for (String column : statement.getColumnNames()) {
        if (column.startsWith("'") && column.endsWith("'")) {
            sql.append(column).append(", ");
        } else {
            sql.append(database.escapeColumnName(catalogName, schemaName, tableName, column)).append(", ");
        }
    }
    sql.deleteCharAt(sql.lastIndexOf(" "));
    int lastComma = sql.lastIndexOf(",");
    if (lastComma >= 0) {
        sql.deleteCharAt(lastComma);
    }
}
 
Example 15
@Override
public String generateAlterStatement(Database database) {
    StringBuilder alter = new StringBuilder();

    alter.append("MODIFY ");
    String columnName = database.escapeColumnName(getCatalogName(), getSchemaName(), getTableName(), getColumnName());
    alter.append(columnName);

    alter.append(' ');
    if (getNewDataType() != null) {
        String dataType = String.valueOf(DataTypeFactory.getInstance().fromDescription(getNewDataType(), database).toDatabaseDataType(database));
        alter.append(dataType);
    }

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

   // GeoDB doesn't use a tradition index structure so don't issue the normal DROP INDEX
   // statement.
   if (!(database instanceof DerbyDatabase) && !(database instanceof H2Database)) {
      final DropIndexStatement dropIndex = new DropIndexStatement(this.indexName,
            this.catalogName, this.schemaName, this.tableName, null);
      statements.add(dropIndex);
   }
   return statements.toArray(new SqlStatement[statements.size()]);
}
 
Example 17
@Override
public void execute (Database database) throws CustomChangeException
{
   JdbcConnection databaseConnection =
      (JdbcConnection) database.getConnection ();
   try
   {         
      PreparedStatement getRestrictions =
         databaseConnection.prepareStatement ("SELECT ID FROM ACCESS_RESTRICTION");
      ResultSet res = getRestrictions.executeQuery ();
      while (res.next ())
      {
         String uuid = UUID.randomUUID ().toString ();
         PreparedStatement updateRestrictions =
            databaseConnection
               .prepareStatement ("UPDATE ACCESS_RESTRICTION SET UUID = '" + uuid +
                  "' WHERE ID = " + res.getObject ("ID"));
         updateRestrictions.execute ();
         updateRestrictions.close ();

         PreparedStatement updateUserRestricitons =
            databaseConnection
               .prepareStatement ("UPDATE USER_RESTRICTIONS SET RESTRICTION_UUID = '" +
                  uuid + "' WHERE RESTRICTION_ID = " + res.getObject ("ID"));
         updateUserRestricitons.execute ();
         updateUserRestricitons.close ();
      }
      getRestrictions.close ();
   }
   catch (Exception e)
   {
      e.printStackTrace ();
   }
   
}
 
Example 18
@Override
public Sql[] generateSql(LockDatabaseChangeLogStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {

    Sql selectForUpdateSql = generateSelectForUpdate(database,
            (statement instanceof CustomLockDatabaseChangeLogStatement)?
                    ((CustomLockDatabaseChangeLogStatement) statement).getId() : 1);

    return new Sql[] { selectForUpdateSql };
}
 
Example 19
Source Project: quarkus   Source File: LiquibaseFactory.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates the liquibase instance.
 * 
 * @return the liquibase.
 */
public Liquibase createLiquibase() {
    try {
        ResourceAccessor resourceAccessor = new ClassLoaderResourceAccessor(Thread.currentThread().getContextClassLoader());

        Database database = DatabaseFactory.getInstance()
                .findCorrectDatabaseImplementation(new JdbcConnection(dataSource.getConnection()));
        ;
        if (database != null) {
            database.setDatabaseChangeLogLockTableName(config.databaseChangeLogLockTableName);
            database.setDatabaseChangeLogTableName(config.databaseChangeLogTableName);
            config.liquibaseCatalogName.ifPresent(database::setLiquibaseCatalogName);
            config.liquibaseSchemaName.ifPresent(database::setLiquibaseSchemaName);
            config.liquibaseTablespaceName.ifPresent(database::setLiquibaseTablespaceName);

            if (config.defaultCatalogName.isPresent()) {
                database.setDefaultCatalogName(config.defaultCatalogName.get());
            }
            if (config.defaultSchemaName.isPresent()) {
                database.setDefaultSchemaName(config.defaultSchemaName.get());
            }
        }
        return new Liquibase(config.changeLog, resourceAccessor, database);

    } catch (Exception ex) {
        throw new IllegalStateException(ex);
    }
}
 
Example 20
Source Project: keycloak   Source File: MySQL8VarcharType.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public DatabaseDataType toDatabaseDataType(Database database) {
    if (database instanceof MySQLDatabase) {
        try {
            if (database.getDatabaseMajorVersion() >= 8 && getSize() > 255) {
                return new DatabaseDataType(database.escapeDataTypeName("TEXT"), getSize());
            }
        } catch (DatabaseException e) {
            throw new RuntimeException(e);
        }
    }
    return super.toDatabaseDataType(database);
}
 
Example 21
Source Project: liquibase-impala   Source File: MetastoreTextType.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public DatabaseDataType toDatabaseDataType(Database database) {
    if (database instanceof HiveMetastoreDatabase) {
        return new DatabaseDataType("STRING", getParameters());
    }

    return super.toDatabaseDataType(database);
}
 
Example 22
Source Project: jweb-cms   Source File: Launcher.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
public void migrate() throws SQLException, LiquibaseException {
    logger.info("migrating database");
    App app = new App(dir);
    DataSource dataSource = new DataSourceFactory(app.options("database", DatabaseOptions.class)).setDir(dir).build();
    try (Connection connection = dataSource.getConnection()) {
        Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(connection));
        Liquibase liquibase = new Liquibase("conf/db/change-logs.yml", new ClassLoaderResourceAccessor(), database);
        liquibase.update("");
        liquibase.tag("0.9.0");
    }
}
 
Example 23
Source Project: liquibase-percona   Source File: PerconaDropIndexChange.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public String generateAlterStatement( Database database )
{
    StringBuilder alter = new StringBuilder();

    alter.append( "DROP ");
    alter.append( "INDEX " );

    if (this.getIndexName() != null) {
        alter.append(database.escapeIndexName(this.getCatalogName(), this.getSchemaName(), this.getIndexName()));
    }

    return alter.toString();
}
 
Example 24
@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 25
/**
 * Creates an example of the database object for which to check.
 *
 * @param database
 *           the database instance.
 * @param tableName
 *           the table name of the index.
 * @return the database object example.
 */
public DatabaseObject getExample(final Database database, final String tableName) {
   final Schema schema = new Schema(getCatalogName(), getSchemaName());
   final DatabaseObject example;

   // For GeoDB, the index is another table.
   if (database instanceof DerbyDatabase || database instanceof H2Database) {
      final String correctedTableName = database.correctObjectName(getHatboxTableName(),
            Table.class);
      example = new Table().setName(correctedTableName).setSchema(schema);
   } else {
      example = getIndexExample(database, schema, tableName);
   }
   return example;
}
 
Example 26
/**
 * @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 27
/**
 * pt-osc changes the constraint names to avoid collisions.
 * It prefixes the original name with 0, 1 or 2 underscores.
 *
 * @param database the database
 * @param change the foreign key constraint change
 * @return the prefixed constraint name
 */
public String determineCurrentConstraintName(Database database, PerconaDropForeignKeyConstraintChange change) {
    // start with best guess without looking at the database
    String constraintName = change.getConstraintName();

    if (enabled && !PerconaChangeUtil.isDryRun(database) && PerconaChangeUtil.isConnected(database)) {
        constraintName = findForeignKey(database, change);
    }
    return prefixConstraintName(constraintName);
}
 
Example 28
private void closeDatabase(Liquibase liquibase) {
    if (liquibase != null) {
        Database database = liquibase.getDatabase();
        if (database != null) {
            try {
                database.close();
            } catch (DatabaseException e) {
                logger.warn("Error closing database", e);
            }
        }
    }
}
 
Example 29
@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 30
@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);
}