Java Code Examples for liquibase.database.DatabaseFactory

The following examples show how to use liquibase.database.DatabaseFactory. 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: 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 2
Source Project: flux   Source File: MigrationsRunner.java    License: Apache License 2.0 6 votes vote down vote up
public void migrate(String dbName) {
    try {
        Configuration configuration = yamlConfiguration.subset(dbName + ".Hibernate");
        Properties properties = new Properties();
        properties.put("user", configuration.getProperty("hibernate.connection.username"));
        properties.put("password", configuration.getProperty("hibernate.connection.password"));
        Class.forName("com.mysql.jdbc.Driver").newInstance();
        String url = (String) configuration.getProperty("hibernate.connection.url");
        java.sql.Connection connection = DriverManager.getConnection(url, properties);
        Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(connection));
        ClassLoader classLoader = getClass().getClassLoader();
        File file = new File(classLoader.getResource(dbName +  "/migrations.xml").getFile());
        Liquibase liquibase = new Liquibase(file.getCanonicalPath(), new FileSystemResourceAccessor(), database);
        liquibase.update(new Contexts());
    } catch (Exception e) {
        System.err.println("Unable to perform database migration.");
        e.printStackTrace();
    }
}
 
Example 3
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 4
Source Project: liquibase-mssql   Source File: PrimaryKeyGeneratorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void integrates() throws DatabaseException {

  //Liquibase must find our mssql impl.
  Database database= DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new OfflineConnection("offline:mssql", null));

  AddPrimaryKeyStatement statement = new AddPrimaryKeyStatement("myCat", "mySchema", "myTable", "myCol", "myConstraint");
  statement.setClustered(true);

  Sql[] sql = SqlGeneratorFactory.getInstance().generateSql(statement, database);
  assertEquals("ALTER TABLE [mySchema].[myTable] ADD CONSTRAINT [myConstraint] PRIMARY KEY ([myCol])", sql[0].toSql());

  statement = new AddPrimaryKeyStatementMSSQL(statement, null);
  sql = SqlGeneratorFactory.getInstance().generateSql(statement, database);
  assertEquals("ALTER TABLE [mySchema].[myTable] ADD CONSTRAINT [myConstraint] PRIMARY KEY ([myCol])", sql[0].toSql());

  statement = new AddPrimaryKeyStatementMSSQL(statement, 50);
  sql = SqlGeneratorFactory.getInstance().generateSql(statement, database);
  assertEquals("ALTER TABLE [mySchema].[myTable] ADD CONSTRAINT [myConstraint] PRIMARY KEY ([myCol]) WITH (FILLFACTOR = 50)", sql[0].toSql());
}
 
Example 5
Source Project: liquibase-mssql   Source File: InsertGeneratorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void integrates() throws DatabaseException {

    //Liquibase must find our mssql impl.
    Database database= DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new OfflineConnection("offline:mssql", null));

    InsertStatement statement = new InsertStatement(null, null, "TABLE_NAME");
    statement.addColumnValue("id", 1);
    statement.addColumnValue("name", "asdf");
    
    statement = new InsertStatementMSSQL(statement, true);

    Sql[] sql = SqlGeneratorFactory.getInstance().generateSql(statement, database);
    assertEquals(3, sql.length);

    for (Sql currentSql : sql) {
        assertSqlHasNoDanglingTokens(currentSql.toSql());
    }
}
 
Example 6
Source Project: aerogear-unifiedpush-server   Source File: MigratorTest.java    License: Apache License 2.0 6 votes vote down vote up
private void initDatabase() throws Exception {
    String url = System.getProperty("jdbc.url");
    String username = System.getProperty("jdbc.username", "unifiedpush");
    String password = System.getProperty("jdbc.password", "unifiedpush");

    if (url == null) {
        assumeTrue("Skip test on Windows, because mysql-connector-mxj has issue on new versions, see http://stackoverflow.com/questions/9520536/missingresourceexception-running-mxj-for-mysql for more details.", !IS_OS_WINDOWS);

        embeddedMysqlDatabase = new EmbeddedMysqlDatabase();
        embeddedMysqlDatabase.start("unifiedpush");

        url = embeddedMysqlDatabase.getUrl();
        username = "root";
        password = "";
    }

    database = DatabaseFactory.getInstance().openDatabase(url, username, password, null, resourceAccessor);
}
 
Example 7
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 8
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 9
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 10
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 11
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 12
Source Project: activiti6-boot2   Source File: DbScriptUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static void dropSchema() throws Exception {
    System.out.println("Dropping schema");
    DatabaseConnection databaseConnection = createDbConnection();
    Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(databaseConnection);

    Liquibase liquibase = new Liquibase("META-INF/liquibase/db-changelog.xml", new ClassLoaderResourceAccessor(), database);
    liquibase.dropAll();

    closeDatabase(database, databaseConnection);
}
 
Example 13
Source Project: activiti6-boot2   Source File: DbScriptUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static void dropSchema() throws Exception {
    System.out.println("Dropping schema");
    DatabaseConnection databaseConnection = createDbConnection();
    Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(databaseConnection);
    
    Liquibase liquibase = new Liquibase("META-INF/liquibase/db-changelog-onpremise.xml", new ClassLoaderResourceAccessor(), database);
    liquibase.dropAll();
    
    closeDatabase(database, databaseConnection);
}
 
Example 14
Source Project: activiti6-boot2   Source File: DmnEngineConfiguration.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/dmn/db/liquibase/activiti-dmn-db-changelog.xml", new ClassLoaderResourceAccessor(), database);

    if (DB_SCHEMA_UPDATE_DROP_CREATE.equals(databaseSchemaUpdate)) {
      logger.debug("Dropping and creating schema DMN");
      liquibase.dropAll();
      liquibase.update("dmn");
    } else if (DB_SCHEMA_UPDATE_TRUE.equals(databaseSchemaUpdate)) {
      logger.debug("Updating schema DMN");
      liquibase.update("dmn");
    } else if (DB_SCHEMA_UPDATE_FALSE.equals(databaseSchemaUpdate)) {
      logger.debug("Validating schema DMN");
      liquibase.validate();
    }
  } catch (Exception e) {
    throw new ActivitiDmnException("Error initialising dmn data model");
  }
}
 
Example 15
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 16
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 17
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 18
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 19
Source Project: airsonic   Source File: SpringLiquibase.java    License: GNU General Public License v3.0 5 votes vote down vote up
private void overrideHsqlDbImplementation(DatabaseFactory factory) {
    List<Database> implementedDatabases = factory.getImplementedDatabases();
    factory.clearRegistry();
    removeCurrentHsqlDb(implementedDatabases);
    implementedDatabases.forEach(factory::register);
    factory.register(new HsqlDatabase());
}
 
Example 20
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 21
@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 22
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 23
public static boolean doUpgrades(Connection connection, String liquibaseChangelogFilename, Writer out) throws UpgradeFailedException, IOException {
    try {
        Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(connection));
        runLiquibaseUpdate(liquibaseChangelogFilename, database, out);
    } catch (DatabaseException ex) {
        outputError(ex, out, "Failed to initialise database");
        return false;
    }
    return true;
}
 
Example 24
void initDatabase(final DataSource dataSource) {
    try (Connection connection = dataSource.getConnection()){
        Liquibase liquibase = new liquibase.Liquibase("liquibase/changelog/db.changelog.yml", new ClassLoaderResourceAccessor(),
                        DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(connection)));
        liquibase.update(new Contexts());
    } catch (LiquibaseException | SQLException e) {
        throw new RuntimeException(e);
    }
}
 
Example 25
Source Project: jpa-unit   Source File: AbstractLiquibaseTest.java    License: Apache License 2.0 5 votes vote down vote up
@Bootstrapping
public static void prepareDataBase(final DataSource ds) throws Exception {
    final Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(ds.getConnection()));
    final Liquibase liquibase = new Liquibase("changelog/changelog.xml", new ClassLoaderResourceAccessor(), database);
    liquibase.dropAll();
    liquibase.update((String) null);
}
 
Example 26
Source Project: flowable-engine   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/flowable/dmn/db/liquibase/flowable-dmn-db-changelog.xml", new ClassLoaderResourceAccessor(), database);
        liquibase.dropAll();
        liquibase.getDatabase().close();

    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 27
Source Project: flowable-engine   Source File: DbScriptUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static void dropSchema() throws Exception {
    System.out.println("Dropping schema");
    DatabaseConnection databaseConnection = createDbConnection();
    Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(databaseConnection);

    Liquibase liquibase = new Liquibase("META-INF/liquibase/db-changelog.xml", new ClassLoaderResourceAccessor(), database);
    liquibase.dropAll();

    closeDatabase(database, databaseConnection);
}
 
Example 28
Source Project: flowable-engine   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/flowable/form/db/liquibase/flowable-form-db-changelog.xml", new ClassLoaderResourceAccessor(), database);
        liquibase.dropAll();
        liquibase.getDatabase().close();

    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 29
Source Project: flowable-engine   Source File: DbSchemaDrop.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    try {
        ContentEngine contentEngine = ContentEngines.getDefaultContentEngine();
        DataSource dataSource = contentEngine.getContentEngineConfiguration().getDataSource();

        DatabaseConnection connection = new JdbcConnection(dataSource.getConnection());
        Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(connection);
        database.setDatabaseChangeLogTableName(ContentEngineConfiguration.LIQUIBASE_CHANGELOG_PREFIX + database.getDatabaseChangeLogTableName());
        database.setDatabaseChangeLogLockTableName(ContentEngineConfiguration.LIQUIBASE_CHANGELOG_PREFIX + database.getDatabaseChangeLogLockTableName());

        if (StringUtils.isNotEmpty(contentEngine.getContentEngineConfiguration().getDatabaseSchema())) {
            database.setDefaultSchemaName(contentEngine.getContentEngineConfiguration().getDatabaseSchema());
            database.setLiquibaseSchemaName(contentEngine.getContentEngineConfiguration().getDatabaseSchema());
        }

        if (StringUtils.isNotEmpty(contentEngine.getContentEngineConfiguration().getDatabaseCatalog())) {
            database.setDefaultCatalogName(contentEngine.getContentEngineConfiguration().getDatabaseCatalog());
            database.setLiquibaseCatalogName(contentEngine.getContentEngineConfiguration().getDatabaseCatalog());
        }

        Liquibase liquibase = new Liquibase("org/flowable/content/db/liquibase/flowable-content-db-changelog.xml", new ClassLoaderResourceAccessor(), database);
        liquibase.dropAll();
        liquibase.getDatabase().close();

    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 30
Source Project: flowable-engine   Source File: DbSchemaDrop.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    try {
        EventRegistryEngine eventRegistryEngine = EventRegistryEngines.getDefaultEventRegistryEngine();
        EventRegistryEngineConfiguration eventRegistryEngineConfiguration = eventRegistryEngine.getEventRegistryEngineConfiguration();
        DataSource dataSource = eventRegistryEngineConfiguration.getDataSource();

        DatabaseConnection connection = new JdbcConnection(dataSource.getConnection());
        Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(connection);
        database.setDatabaseChangeLogTableName(EventRegistryEngineConfiguration.LIQUIBASE_CHANGELOG_PREFIX + database.getDatabaseChangeLogTableName());
        database.setDatabaseChangeLogLockTableName(EventRegistryEngineConfiguration.LIQUIBASE_CHANGELOG_PREFIX + database.getDatabaseChangeLogLockTableName());

        if (StringUtils.isNotEmpty(eventRegistryEngineConfiguration.getDatabaseSchema())) {
            database.setDefaultSchemaName(eventRegistryEngineConfiguration.getDatabaseSchema());
            database.setLiquibaseSchemaName(eventRegistryEngineConfiguration.getDatabaseSchema());
        }

        if (StringUtils.isNotEmpty(eventRegistryEngineConfiguration.getDatabaseCatalog())) {
            database.setDefaultCatalogName(eventRegistryEngineConfiguration.getDatabaseCatalog());
            database.setLiquibaseCatalogName(eventRegistryEngineConfiguration.getDatabaseCatalog());
        }

        Liquibase liquibase = new Liquibase("org/flowable/eventregistry/db/liquibase/flowable-eventregistry-db-changelog.xml", new ClassLoaderResourceAccessor(), database);
        liquibase.dropAll();
        liquibase.getDatabase().close();

    } catch (Exception e) {
        e.printStackTrace();
    }
}