liquibase.database.Database Java Examples

The following examples show how to use liquibase.database.Database. 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: WktConversionUtils.java    From liquibase-spatial with 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 #2
Source File: LiquibaseSchemaTarget.java    From gradle-plugins with Apache License 2.0 6 votes vote down vote up
@Override
public void process(File generatedFile, File outputDirectory, SchemaGenConfig config) {
	try (Connection connection = setupDataSource(generatedFile); Connection emptyConnection = setupEmptySource()) {
		DatabaseFactory databaseFactory = DatabaseFactory.getInstance();
		Database database = databaseFactory.findCorrectDatabaseImplementation(new JdbcConnection(connection));
		Database emptyDatabase = databaseFactory.findCorrectDatabaseImplementation(new JdbcConnection(emptyConnection));

		DiffGeneratorFactory diffGeneratorFactory = DiffGeneratorFactory.getInstance();

		CompareControl compareControl = new CompareControl();
		DiffResult result = diffGeneratorFactory.compare(database, emptyDatabase, compareControl);

		DiffOutputControl outputControl = new DiffOutputControl();
		DiffToChangeLog changeLog = new DiffToChangeLog(result, outputControl);
		changeLog.setChangeSetAuthor(config.getLiquibase().getUser());
		changeLog.setIdRoot(config.getVersion());
		changeLog.generateChangeSets();

		File outputFile = new File(outputDirectory,
				config.getPackageName().replace(".", File.separator) + File.separator + config.getLiquibase().getFileName());
		outputFile.getParentFile().mkdirs();
		if (outputFile.exists()) {
			boolean deleted = outputFile.delete();
			if (!deleted) {
				throw new IllegalStateException("cannot delete " + outputFile.getAbsolutePath());
			}
		}
		changeLog.print(outputFile.getAbsolutePath(), new XMLChangeLogSerializer());

		if (config.getConstraintNamePrefix() != null) {
			String sql = FileUtils.readAsString(outputFile);
			sql = sql.replace("primaryKeyName=\"CONSTRAINT_", "primaryKeyName=\"" + config.getConstraintNamePrefix() + "CONSTRAINT_");
			FileUtils.writeString(sql, outputFile);
		}
	} catch (Exception e) {
		throw new IllegalStateException(e);
	}
}
 
Example #3
Source File: OracleSpatialUtils.java    From liquibase-spatial with 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 #4
Source File: DropSpatialIndexGeneratorGeoDB.java    From liquibase-spatial with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #5
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 #6
Source File: GeometryColumnsUtilsTest.java    From liquibase-spatial with Apache License 2.0 6 votes vote down vote up
@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 #7
Source File: ImpalaRemoveChangeSetRanStatusGenerator.java    From liquibase-impala with Apache License 2.0 6 votes vote down vote up
@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 #8
Source File: GeometryType.java    From liquibase-spatial with 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 #9
Source File: DropSpatialIndexChange.java    From liquibase-spatial with 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 #10
Source File: WktConversionUtilsTest.java    From liquibase-spatial with 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 #11
Source File: CustomInsertLockRecordGenerator.java    From keycloak with 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 #12
Source File: IndexGeneratorTest.java    From liquibase-mssql with 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 #13
Source File: PerconaModifyDataTypeChange.java    From liquibase-percona with Apache License 2.0 6 votes vote down vote up
@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 #14
Source File: InsertAsSelectGenerator.java    From liquibase-impala with 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
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 #16
Source File: SpatialIndexExistsPrecondition.java    From liquibase-spatial with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #17
Source File: CreateSpatialIndexChange.java    From liquibase-spatial with Apache License 2.0 6 votes vote down vote up
/**
 * @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 #18
Source File: EventRegistryEngineConfiguration.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
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 #19
Source File: PerconaForeignKeyService.java    From liquibase-percona with Apache License 2.0 5 votes vote down vote up
/**
 * 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 #20
Source File: GenerateRestrictionUUIDs.java    From DataHubSystem with GNU Affero General Public License v3.0 5 votes vote down vote up
@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 #21
Source File: LiquibaseHelper.java    From FROST-Server with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static String checkForUpgrades(Connection connection, String liquibaseChangelogFilename) {
    StringWriter out = new StringWriter();
    try {
        Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(connection));
        runLiquibaseCheck(liquibaseChangelogFilename, database, out);
    } catch (DatabaseException ex) {
        outputError(ex, out, "Failed to initialise database");
    }
    return out.toString();
}
 
Example #22
Source File: PerconaAddColumnChange.java    From liquibase-percona with Apache License 2.0 5 votes vote down vote up
String convertColumnToSql(AddColumnConfig column, Database database) {
    String nullable = "";
    ConstraintsConfig constraintsConfig = column.getConstraints();
    if (constraintsConfig != null && !constraintsConfig.isNullable()) {
        nullable = " NOT NULL";
    } else {
        nullable = " NULL";
    }
    String defaultValue =  "";
    if (column.getDefaultValueObject() != null) {
        defaultValue = " DEFAULT " + DataTypeFactory.getInstance().fromObject(column.getDefaultValueObject(), database).objectToSql(column.getDefaultValueObject(), database);
    }
    String comment = "";
    if (StringUtil.isNotEmpty(column.getRemarks())) {
        comment += " COMMENT '" + column.getRemarks() + "'";
    }
    String after = "";
    if (StringUtil.isNotEmpty(column.getAfterColumn())) {
        after += " AFTER " + database.escapeColumnName(null, null, null, column.getAfterColumn());
    }

    String constraints = "";
    constraints += addForeignKeyConstraint(column, database);
    constraints += addUniqueKeyConstraint(column, database);

    return "ADD COLUMN " + database.escapeColumnName(null, null, null, column.getName())
            + " " + DataTypeFactory.getInstance().fromDescription(column.getType(), database).toDatabaseDataType(database)
            + nullable
            + defaultValue
            + comment
            + after
            + constraints;
}
 
Example #23
Source File: HiveInitializeDatabaseChangeLogLockTableGenerator.java    From liquibase-impala with Apache License 2.0 5 votes vote down vote up
@Override
public Sql[] generateSql(InitializeDatabaseChangeLogLockTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
    String catalogName = database.getLiquibaseCatalogName();
    String schemaName = database.getDefaultSchemaName();
    String tableName = database.getDatabaseChangeLogLockTableName();
    HiveInsertStatement insertStatementHive = new HiveInsertStatement(catalogName, schemaName, tableName)
            .addColumnValue(1)
            .addColumnValue(Boolean.FALSE)
            .addColumnValue("NULL")
            .addColumnValue("NULL");

    return CustomSqlGenerator.generateSql(database,
            new TruncateTableStatement(catalogName, schemaName, tableName),
            insertStatementHive);
}
 
Example #24
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 #25
Source File: CertificateBlobToBase64.java    From aerogear-unifiedpush-server with Apache License 2.0 5 votes vote down vote up
@Override
public SqlStatement[] generateStatements(Database database) throws CustomChangeException {
    List<SqlStatement> statements = new ArrayList<>();

    Connection conn = ((JdbcConnection) (database.getConnection())).getWrappedConnection();

    try {
        conn.setAutoCommit(false);
        ResultSet resultSet = conn.createStatement().executeQuery("SELECT id, certificate from ios_variant");
        while (resultSet.next()) {
            String id = resultSet.getString("id");
            Blob blob = resultSet.getBlob("certificate");
            InputStream certificate = blob.getBinaryStream();
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            int bytesRead = -1;
            byte[] buffer = new byte[1024];
            while ((bytesRead = certificate.read(buffer)) != -1) {
                stream.write(buffer, 0, bytesRead);
            }
            final String certificateData = Base64.getEncoder().encodeToString(stream.toByteArray());

            UpdateStatement updateStatement = new UpdateStatement(null, null, "ios_variant")
                    .addNewColumnValue("cert_data", certificateData)
                    .setWhereClause("id='" + id + "'");
            statements.add(updateStatement);

        }
        conn.commit();

        if (!statements.isEmpty()) {
            confirmationMessage = "updated certificate data successfully";
        }

        return statements.toArray(new SqlStatement[statements.size()]);
    } catch (Exception e) {
        throw new CustomChangeException("Failed to migrate certificate data");
    }

}
 
Example #26
Source File: MetastoreBinaryType.java    From liquibase-impala with Apache License 2.0 5 votes vote down vote up
@Override
public DatabaseDataType toDatabaseDataType(Database database) {
    if (database instanceof HiveMetastoreDatabase) {
        return new DatabaseDataType("BINARY");
    }

    return super.toDatabaseDataType(database);
}
 
Example #27
Source File: CustomSqlGenerator.java    From liquibase-impala with Apache License 2.0 5 votes vote down vote up
public static Sql[] generateSql(Database database, SqlStatement... statements) {
    List<Sql> sqls = new ArrayList<Sql>();
    SqlGeneratorFactory generatorFactory = SqlGeneratorFactory.getInstance();
    for (SqlStatement statement : statements) {
        sqls.addAll(Arrays.asList(generatorFactory.generateSql(statement, database)));
    }
    return sqls.toArray(new Sql[sqls.size()]);
}
 
Example #28
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 #29
Source File: HiveStandardChangeLogHistoryService.java    From liquibase-impala with Apache License 2.0 5 votes vote down vote up
@Override
public void destroy() throws DatabaseException {
    Database database = getDatabase();
    try {
        if (SnapshotGeneratorFactory.getInstance().has(new Table().setName(database.getDatabaseChangeLogTableName()).setSchema(database.getLiquibaseCatalogName(), database.getLiquibaseSchemaName()), database)) {
            ExecutorService.getInstance().getExecutor(database).execute(new DropTableStatement(database.getLiquibaseCatalogName(), database.getLiquibaseSchemaName(), database.getDatabaseChangeLogTableName(), false));
        }
        reset();
    } catch (InvalidExampleException e) {
        throw new UnexpectedLiquibaseException(e);
    }
}
 
Example #30
Source File: DefaultTenantProvisioningService.java    From cloud-s4-sdk-examples with Apache License 2.0 5 votes vote down vote up
@Override
public void subscribeTenant(final String tenantId) {
    String defaultSchemaName;
    try {
        Validate.isTrue(isValidTenantId(tenantId), String.format("Invalid tenant id: \"%s\"", tenantId));
        final String schemaName = TenantUtil.createSchemaName(tenantId);

        final Connection connection = dataSource.getConnection();
        final Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(connection));
        try (Statement statement = connection.createStatement()) {
            statement.execute(String.format("CREATE SCHEMA IF NOT EXISTS \"%s\"", schemaName));
            connection.commit();

            defaultSchemaName = database.getDefaultSchemaName();
            database.setDefaultSchemaName(schemaName);

            final String filePath = LIQUIBASE_PATH;
            final Liquibase liquibase = new liquibase.Liquibase(filePath,
                    new ClassLoaderResourceAccessor(), database);

            liquibase.update(new Contexts(), new LabelExpression());
            database.setDefaultSchemaName(defaultSchemaName);
        }

    } catch (SQLException | LiquibaseException | IllegalArgumentException e) {
        final BadRequestException badRequestException = new BadRequestException();
        logger.error("Tenant subscription failed for {}.", tenantId, e);
        throw badRequestException;
    }
}