Java Code Examples for liquibase.database.jvm.JdbcConnection

The following examples show how to use liquibase.database.jvm.JdbcConnection. 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: keycloak   Source File: DropAllServlet.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void init() throws ServletException {
    super.init();

    try {
        Connection connection = dataSource.getConnection();
        Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(connection));
        String dbName = database.getShortName();
        if (dbName.contains("postgres")) {
            deleteAllDataPostgresql(connection);
        } else if (dbName.contains("mssql")) {
            deleteAllDataMssql(connection);
        } else {
            Liquibase liquibase = new Liquibase((String) null, null, database);
            liquibase.dropAll();
        }
    } catch (Throwable e) {
        log.error(e);
        throw new ServletException(e);
    }
    log.warn("All Keycloak tables successfully dropped");
}
 
Example 2
@Override
public boolean isCaseSensitive() {
    if (caseSensitive == null) {
        if ((connection != null) && (connection instanceof JdbcConnection)) {
            try {
                caseSensitive = ((JdbcConnection) connection).getUnderlyingConnection().getMetaData().supportsMixedCaseIdentifiers();
            } catch (SQLException e) {
                LogService.getLog(getClass()).warning(LogType.LOG, "Cannot determine case sensitivity from JDBC driver", e);
            }
        }
    }

    if (caseSensitive == null) {
        return false;
    } else {
        return caseSensitive.booleanValue();
    }
}
 
Example 3
private String retrieveConstraintName(JdbcConnection jdbcConnection) throws Exception {
    PreparedStatement preparedStatement = null;
    ResultSet result = null;

    try {
        String searchQuery = getSearchQuery();
        preparedStatement = jdbcConnection.prepareStatement(searchQuery);
        result = preparedStatement.executeQuery();
        result.next();
        String constraintName = result.getString(CONSTRAINT_NAME_COLUMN);
        logger.info(String.format("Executed statement '%s' returned constraint name: %s", searchQuery, constraintName));
        return constraintName;
    } finally {
        JdbcUtil.closeQuietly(result);
        JdbcUtil.closeQuietly(preparedStatement);
    }
}
 
Example 4
Source Project: multiapps   Source File: TestDataSourceProvider.java    License: Apache License 2.0 6 votes vote down vote up
public static DataSource getDataSource(String liquibaseChangelogLocation) throws Exception {
    // create a hsql in memory connection
    Connection connection = createH2InMemory();

    // Create the schema for unit testing
    Database liquibaseDb = DatabaseFactory.getInstance()
                                          .findCorrectDatabaseImplementation(new JdbcConnection(connection));
    Liquibase lq = new Liquibase(liquibaseChangelogLocation, new ClassLoaderResourceAccessor(), liquibaseDb);
    try {
        lq.update("");
    } catch (MigrationFailedException e) {
        // catch the exception because in PopulateConfigurationRegistrySpaceIdColumnChange liquibase change there is rest call
        if (e.getCause()
             .getClass() != UnexpectedLiquibaseException.class) {
            throw e;
        }
    }

    // Initialize the fileService to use our in-memory connection through a pool emulation (so
    // that close releases rather than close)
    return new SingleConnectionDataSource(connection, true);
}
 
Example 5
Source Project: trellis   Source File: DBTestUtils.java    License: Apache License 2.0 6 votes vote down vote up
static EmbeddedPostgres setupDatabase(final String directory) {
    try {
        final EmbeddedPostgres pg = EmbeddedPostgres.builder()
            .setDataDirectory(directory + separator + "pgdata-" + new RandomStringGenerator
                        .Builder().withinRange('a', 'z').build().generate(10)).start();

        // Set up database migrations
        try (final Connection c = pg.getPostgresDatabase().getConnection()) {
            final Liquibase liquibase = new Liquibase("org/trellisldp/jdbc/migrations.yml",
                    new ClassLoaderResourceAccessor(),
                    new JdbcConnection(c));
            final Contexts ctx = null;
            liquibase.update(ctx);
        }
        return pg;
    } catch (final IOException | SQLException | LiquibaseException ex) {
        LOGGER.error("Error setting up tests", ex);
    }
    return null;
}
 
Example 6
Source Project: otj-pg-embedded   Source File: LiquibasePreparer.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void prepare(DataSource ds) throws SQLException {
    Connection connection = null;
    try {
        connection = ds.getConnection();
        Database database = getInstance().findCorrectDatabaseImplementation(new JdbcConnection(connection));
        Liquibase liquibase = new Liquibase(location, new ClassLoaderResourceAccessor(), database);
        liquibase.update(contexts);
    } catch (LiquibaseException e) {
        throw new SQLException(e);
    } finally {
        if (connection != null) {
            connection.rollback();
            connection.close();
        }
    }
}
 
Example 7
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 8
Source Project: liquibase-spatial   Source File: LiquibaseIT.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Tests Liquibase updating and rolling back the database.
 *
 * @param changeLogFile
 *           the database change log to use in the {@link Liquibase#update(Contexts) update}.
 * @throws LiquibaseException
 *            if Liquibase fails to initialize or run the update.
 * @throws SQLException
 *            if unable to get the database connection.
 */
@Test(dataProvider = "databaseUrlProvider", enabled = false)
public void testLiquibaseUpdateTestingRollback(final String changeLogFile)
      throws LiquibaseException, SQLException {
   final Connection connection = getConnection();
   final JdbcConnection jdbcConnection = new JdbcConnection(connection);
   try {
      final ResourceAccessor resourceAccessor = new ClassLoaderResourceAccessor();
      final Liquibase liquibase = createLiquibase(changeLogFile, resourceAccessor,
            jdbcConnection);
      final Contexts contexts = null;
      final LabelExpression labels = new LabelExpression();
      liquibase.updateTestingRollback(contexts, labels);
      final List<ChangeSet> unrunChangeSets = liquibase.listUnrunChangeSets(contexts, labels);
      assertTrue(unrunChangeSets.isEmpty(), "All change sets should have run");
   } finally {
      jdbcConnection.rollback();
      jdbcConnection.close();
   }
}
 
Example 9
Source Project: liquibase-spatial   Source File: LiquibaseIT.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Tests Liquibase updating the database.
 *
 * @param changeLogFile
 *           the database change log to use in the {@link Liquibase#update(Contexts) update}.
 * @throws LiquibaseException
 *            if Liquibase fails to initialize or run the update.
 * @throws SQLException
 *            if unable to get the database connection.
 */
@Test(dataProvider = "databaseUrlProvider")
public void testLiquibaseUpdate(final String changeLogFile) throws LiquibaseException,
SQLException {
   final Connection connection = getConnection();
   final JdbcConnection jdbcConnection = new JdbcConnection(connection);
   try {
      final ResourceAccessor resourceAccessor = new ClassLoaderResourceAccessor();
      final Liquibase liquibase = createLiquibase(changeLogFile, resourceAccessor,
            jdbcConnection);
      final Contexts contexts = null;
      liquibase.update(contexts);
      final List<ChangeSet> unrunChangeSets = liquibase.listUnrunChangeSets(contexts);
      assertTrue(unrunChangeSets.isEmpty(), "All change sets should have run");
   } finally {
      jdbcConnection.rollback();
      jdbcConnection.close();
   }
}
 
Example 10
@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 11
Source Project: hmdm-server   Source File: AbstractLiquibaseModule.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * <p>Configures this module. Applies the recent changes from the {@link #getChangeLogResourcePath()} change log to
 * database.</p>
 */
protected final void configure() {
    try (Connection connection = this.getConnection()) {
        Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(connection));
        Liquibase liquibase = new Liquibase(getChangeLogResourcePath(), getResourceAccessor(), database);
        String usageScenario = this.context.getInitParameter("usage.scenario");
        String contexts = getContexts(usageScenario);
        liquibase.update(contexts);
    } catch (LiquibaseException | SQLException e) {
        log.error(e.getMessage(), e);
        throw new RuntimeException(e);
    }
}
 
Example 12
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 13
Source Project: activiti6-boot2   Source File: DbSchemaDrop.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
  try {
    FormEngine formEngine = FormEngines.getDefaultFormEngine();
    DataSource dataSource = formEngine.getFormEngineConfiguration().getDataSource();
    
    DatabaseConnection connection = new JdbcConnection(dataSource.getConnection());
    Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(connection);
    database.setDatabaseChangeLogTableName(FormEngineConfiguration.LIQUIBASE_CHANGELOG_PREFIX+database.getDatabaseChangeLogTableName());
    database.setDatabaseChangeLogLockTableName(FormEngineConfiguration.LIQUIBASE_CHANGELOG_PREFIX+database.getDatabaseChangeLogLockTableName());
    
    if (StringUtils.isNotEmpty(formEngine.getFormEngineConfiguration().getDatabaseSchema())) {
      database.setDefaultSchemaName(formEngine.getFormEngineConfiguration().getDatabaseSchema());
      database.setLiquibaseSchemaName(formEngine.getFormEngineConfiguration().getDatabaseSchema());
    }
    
    if (StringUtils.isNotEmpty(formEngine.getFormEngineConfiguration().getDatabaseCatalog())) {
      database.setDefaultCatalogName(formEngine.getFormEngineConfiguration().getDatabaseCatalog());
      database.setLiquibaseCatalogName(formEngine.getFormEngineConfiguration().getDatabaseCatalog());
    }

    Liquibase liquibase = new Liquibase("org/activiti/form/db/liquibase/activiti-form-db-changelog.xml", new ClassLoaderResourceAccessor(), database);
    liquibase.dropAll();
    
  } catch (Exception e) {
    e.printStackTrace();
  }
}
 
Example 14
Source Project: activiti6-boot2   Source File: FormEngineConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
public void initDbSchema() {
  try {
    DatabaseConnection connection = new JdbcConnection(dataSource.getConnection());
    Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(connection);
    database.setDatabaseChangeLogTableName(LIQUIBASE_CHANGELOG_PREFIX+database.getDatabaseChangeLogTableName());
    database.setDatabaseChangeLogLockTableName(LIQUIBASE_CHANGELOG_PREFIX+database.getDatabaseChangeLogLockTableName());
    
    if (StringUtils.isNotEmpty(databaseSchema)) {
      database.setDefaultSchemaName(databaseSchema);
      database.setLiquibaseSchemaName(databaseSchema);
    }
    
    if (StringUtils.isNotEmpty(databaseCatalog)) {
      database.setDefaultCatalogName(databaseCatalog);
      database.setLiquibaseCatalogName(databaseCatalog);
    }

    Liquibase liquibase = new Liquibase("org/activiti/form/db/liquibase/activiti-form-db-changelog.xml", new ClassLoaderResourceAccessor(), database);

    if (DB_SCHEMA_UPDATE_DROP_CREATE.equals(databaseSchemaUpdate)) {
      logger.debug("Dropping and creating schema FORM");
      liquibase.dropAll();
      liquibase.update("form");
    } else if (DB_SCHEMA_UPDATE_TRUE.equals(databaseSchemaUpdate)) {
      logger.debug("Updating schema FORM");
      liquibase.update("form");
    } else if (DB_SCHEMA_UPDATE_FALSE.equals(databaseSchemaUpdate)) {
      logger.debug("Validating schema FORM");
      liquibase.validate();
    }
  } catch (Exception e) {
    throw new ActivitiFormException("Error initialising form data schema", e);
  }
}
 
Example 15
Source Project: activiti6-boot2   Source File: DbScriptUtil.java    License: Apache License 2.0 5 votes vote down vote up
protected static DatabaseConnection createDbConnection() throws Exception {
    Properties properties = new Properties();
    properties.load(DbScriptUtil.class.getClassLoader().getResourceAsStream("META-INF/activiti-admin/TEST-db.properties"));
    Connection connection = DriverManager.getConnection(properties.getProperty("datasource.url"),
            properties.getProperty("datasource.username"), properties.getProperty("datasource.password"));
    DatabaseConnection databaseConnection = new JdbcConnection(connection);
    return databaseConnection;
}
 
Example 16
Source Project: activiti6-boot2   Source File: DbScriptUtil.java    License: Apache License 2.0 5 votes vote down vote up
protected static DatabaseConnection createDbConnection() throws Exception {
    Properties properties = new Properties();
    properties.load(DbScriptUtil.class.getClassLoader().getResourceAsStream("META-INF/activiti-app-test/TEST-db.properties"));
    Connection connection = DriverManager.getConnection(properties.getProperty("datasource.url"), 
            properties.getProperty("datasource.username"), properties.getProperty("datasource.password"));
    DatabaseConnection databaseConnection = new JdbcConnection(connection);
    return databaseConnection;
}
 
Example 17
Source Project: activiti6-boot2   Source File: DbSchemaDrop.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
  try {
    DmnEngine dmnEngine = DmnEngines.getDefaultDmnEngine();
    DataSource dataSource = dmnEngine.getDmnEngineConfiguration().getDataSource();
    
    DatabaseConnection connection = new JdbcConnection(dataSource.getConnection());
    Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(connection);
    database.setDatabaseChangeLogTableName(DmnEngineConfiguration.LIQUIBASE_CHANGELOG_PREFIX+database.getDatabaseChangeLogTableName());
    database.setDatabaseChangeLogLockTableName(DmnEngineConfiguration.LIQUIBASE_CHANGELOG_PREFIX+database.getDatabaseChangeLogLockTableName());
    
    if (StringUtils.isNotEmpty(dmnEngine.getDmnEngineConfiguration().getDatabaseSchema())) {
      database.setDefaultSchemaName(dmnEngine.getDmnEngineConfiguration().getDatabaseSchema());
      database.setLiquibaseSchemaName(dmnEngine.getDmnEngineConfiguration().getDatabaseSchema());
    }
    
    if (StringUtils.isNotEmpty(dmnEngine.getDmnEngineConfiguration().getDatabaseCatalog())) {
      database.setDefaultCatalogName(dmnEngine.getDmnEngineConfiguration().getDatabaseCatalog());
      database.setLiquibaseCatalogName(dmnEngine.getDmnEngineConfiguration().getDatabaseCatalog());
    }

    Liquibase liquibase = new Liquibase("org/activiti/dmn/db/liquibase/activiti-dmn-db-changelog.xml", new ClassLoaderResourceAccessor(), database);
    liquibase.dropAll();
    
  } catch (Exception e) {
    e.printStackTrace();
  }
}
 
Example 18
Source Project: jweb-cms   Source File: Launcher.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
public boolean isMigrationNeeded() throws SQLException, LiquibaseException {
    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);
        return !liquibase.tagExists("0.9.0");
    }
}
 
Example 19
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 20
@Override
public boolean supportsBatchUpdates() throws DatabaseException {
    if (connection instanceof OfflineConnection) {
        return false;
    } else if (connection instanceof JdbcConnection) {
        return ((JdbcConnection) getConnection()).supportsBatchUpdates();
    } else {
        // Normally, the connection can only be one of the two above types. But if, for whatever reason, it is
        // not, let's err on the safe side.
        return false;
    }
}
 
Example 21
Source Project: jweb-cms   Source File: Main.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
public static void main(String[] args) throws LiquibaseException, SQLException, IOException, ParserConfigurationException {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setUrl("jdbc:mysql://localhost:3306/main?useUnicode=true&characterEncoding=utf8&autoReconnect=true&useSSL=false&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC");
    dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
    dataSource.setUsername("root");

    java.sql.Connection connection = dataSource.getConnection();
    Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(connection));
    Liquibase liquibase = new Liquibase("db-changes.yml", new ClassLoaderResourceAccessor(), database);

    CatalogAndSchema catalogAndSchema = new CatalogAndSchema(null, "main");
    DiffToChangeLog changeLog = new DiffToChangeLog(new DiffOutputControl(false, false, true, null));

    liquibase.generateChangeLog(catalogAndSchema, changeLog, new PrintStream(new FileOutputStream("./change-logs.yml")), new YamlChangeLogSerializer(), snapTypes());
}
 
Example 22
private void dropConstraint(JdbcConnection jdbcConnection, String constraintName) throws Exception {
    Statement statement = null;

    try {
        statement = jdbcConnection.createStatement();
        String dropQuery = String.format(DROP_QUERY, constraintName);
        statement.execute(dropQuery);
        logger.info(String.format("Executed statement '%s'.", dropQuery));
    } finally {
        JdbcUtil.closeQuietly(statement);
    }
}
 
Example 23
@Override
protected void executeInTransaction(JdbcConnection jdbcConnection) throws Exception {
    OriginalDataType retrievedData = retrieveData(jdbcConnection);
    TransformedDataType transformedData = transformData(retrievedData);
    alterTable(jdbcConnection);
    updateTable(jdbcConnection, transformedData);
}
 
Example 24
public OriginalDataType retrieveData(JdbcConnection jdbcConnection) throws DatabaseException, SQLException {
    PreparedStatement preparedStatement = null;
    OriginalDataType result = null;

    try {
        preparedStatement = jdbcConnection.prepareStatement(getSelectStatement(), ResultSet.TYPE_FORWARD_ONLY,
                                                            ResultSet.CONCUR_READ_ONLY);
        ResultSet resultSet = preparedStatement.executeQuery();
        result = extractData(resultSet);
        resultSet.close();
    } finally {
        JdbcUtil.closeQuietly(preparedStatement);
    }
    return result;
}
 
Example 25
public void updateTable(JdbcConnection jdbcConnection, TransformedDataType transformedData) throws DatabaseException, SQLException {
    PreparedStatement preparedStatement = null;

    try {
        preparedStatement = jdbcConnection.prepareStatement(getUpdateStatement());
        setUpdateStatementParameters(preparedStatement, transformedData);
        preparedStatement.executeBatch();
    } finally {
        JdbcUtil.closeQuietly(preparedStatement);
    }
}
 
Example 26
private void executeStatement(JdbcConnection jdbcConnection, String statement) throws DatabaseException, SQLException {
    PreparedStatement preparedStatement = null;
    try {
        preparedStatement = jdbcConnection.prepareStatement(statement);
        preparedStatement.execute();
    } finally {
        JdbcUtil.closeQuietly(preparedStatement);
    }
}
 
Example 27
Source Project: multiapps-controller   Source File: AbstractChange.java    License: Apache License 2.0 5 votes vote down vote up
private void attemptToRollbackTransaction(JdbcConnection jdbcConnection) {
    try {
        jdbcConnection.rollback();
    } catch (DatabaseException e) {
        logger.warn(Messages.COULD_NOT_ROLLBACK_TRANSACTION, e);
    }
}
 
Example 28
Source Project: gradle-plugins   Source File: LiquibaseSchemaTarget.java    License: Apache License 2.0 5 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 29
@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;
    }
}
 
Example 30
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();
}