liquibase.database.DatabaseFactory Java Examples

The following examples show how to use liquibase.database.DatabaseFactory. 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: DropAllServlet.java    From keycloak with 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
Source File: MigratorTest.java    From aerogear-unifiedpush-server with 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 #3
Source File: InsertGeneratorTest.java    From liquibase-mssql with 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 #4
Source File: PrimaryKeyGeneratorTest.java    From liquibase-mssql with 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 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 #6
Source File: MigrationsRunner.java    From flux with 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 #7
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 #8
Source File: TestDataSourceProvider.java    From multiapps with 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 #9
Source File: ModelDBHibernateUtil.java    From modeldb with Apache License 2.0 5 votes vote down vote up
private static void createTablesLiquibaseMigration(MetadataSources metaDataSrc)
    throws LiquibaseException, SQLException, InterruptedException {
  // Get database connection
  try (Connection con =
      metaDataSrc.getServiceRegistry().getService(ConnectionProvider.class).getConnection()) {
    JdbcConnection jdbcCon = new JdbcConnection(con);

    // Overwrite default liquibase table names by custom
    GlobalConfiguration liquibaseConfiguration =
        LiquibaseConfiguration.getInstance().getConfiguration(GlobalConfiguration.class);
    liquibaseConfiguration.setDatabaseChangeLogLockWaitTime(1L);

    // Initialize Liquibase and run the update
    Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(jdbcCon);
    String rootPath = System.getProperty(ModelDBConstants.userDir);
    rootPath = rootPath + "\\src\\main\\resources\\liquibase\\db-changelog-1.0.xml";
    Liquibase liquibase = new Liquibase(rootPath, new FileSystemResourceAccessor(), database);

    boolean liquibaseExecuted = false;
    while (!liquibaseExecuted) {
      try {
        liquibase.update(new Contexts(), new LabelExpression());
        liquibaseExecuted = true;
      } catch (LockException ex) {
        LOGGER.warn(
            "ModelDBHibernateUtil createTablesLiquibaseMigration() getting LockException ", ex);
        releaseLiquibaseLock(metaDataSrc);
      }
    }
  }
}
 
Example #10
Source File: DbScriptUtil.java    From flowable-engine with 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 #11
Source File: AbstractLiquibaseModule.java    From hmdm-server with 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 File: DbSchemaDrop.java    From flowable-engine with 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 #13
Source File: DbSchemaDrop.java    From flowable-engine with 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 #14
Source File: DbSchemaDrop.java    From flowable-engine with 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();
    }
}
 
Example #15
Source File: QuarkusLiquibaseConnectionProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public Liquibase getLiquibaseForCustomUpdate(Connection connection, String defaultSchema, String changelogLocation, ClassLoader classloader, String changelogTableName) throws LiquibaseException {
    Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(connection));
    if (defaultSchema != null) {
        database.setDefaultSchemaName(defaultSchema);
    }

    ResourceAccessor resourceAccessor = new ClassLoaderResourceAccessor(classloader);
    database.setDatabaseChangeLogTableName(changelogTableName);

    logger.debugf("Using changelog file %s and changelogTableName %s", changelogLocation, database.getDatabaseChangeLogTableName());

    return new Liquibase(changelogLocation, resourceAccessor, database);
}
 
Example #16
Source File: DbSchemaDrop.java    From flowable-engine with 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 #17
Source File: QuarkusLiquibaseConnectionProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public Liquibase getLiquibase(Connection connection, String defaultSchema) throws LiquibaseException {
    Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(connection));
    if (defaultSchema != null) {
        database.setDefaultSchemaName(defaultSchema);
    }

    String changelog = QuarkusJpaUpdaterProvider.CHANGELOG;

    logger.debugf("Using changelog file %s and changelogTableName %s", changelog, database.getDatabaseChangeLogTableName());

    return new Liquibase(changelog, resourceAccessor, database);
}
 
Example #18
Source File: SingularityCuratorTestBase.java    From Singularity with Apache License 2.0 5 votes vote down vote up
@BeforeAll
public void setup() throws Exception {
  JerseyGuiceUtils.reset();
  singularityTestModule = new SingularityTestModule(useDBTests, customConfigSetup);

  singularityTestModule.getInjector().injectMembers(this);
  singularityTestModule.start();
  leaderCacheCoordinator.activateLeaderCache();
  configuration.setThreadpoolShutdownDelayInSeconds(0);
  if (useDBTests) {
    Handle handle = dbiProvider.get().open();
    handle.getConnection().setAutoCommit(true);

    Database database = DatabaseFactory
      .getInstance()
      .findCorrectDatabaseImplementation(new JdbcConnection(handle.getConnection()));

    Liquibase liquibase = new Liquibase(
      "singularity_test.sql",
      new FileSystemResourceAccessor(),
      database
    );
    liquibase.update((String) null);

    try {
      database.close();
      handle.close();
    } catch (Throwable t) {}
  }
}
 
Example #19
Source File: DefaultLiquibaseConnectionProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public Liquibase getLiquibase(Connection connection, String defaultSchema) throws LiquibaseException {
    Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(connection));
    if (defaultSchema != null) {
        database.setDefaultSchemaName(defaultSchema);
    }

    String changelog = LiquibaseJpaUpdaterProvider.CHANGELOG;
    ResourceAccessor resourceAccessor = new ClassLoaderResourceAccessor(getClass().getClassLoader());

    logger.debugf("Using changelog file %s and changelogTableName %s", changelog, database.getDatabaseChangeLogTableName());
    
    return new Liquibase(changelog, resourceAccessor, database);
}
 
Example #20
Source File: DefaultLiquibaseConnectionProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public Liquibase getLiquibaseForCustomUpdate(Connection connection, String defaultSchema, String changelogLocation, ClassLoader classloader, String changelogTableName) throws LiquibaseException {
    Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(connection));
    if (defaultSchema != null) {
        database.setDefaultSchemaName(defaultSchema);
    }

    ResourceAccessor resourceAccessor = new ClassLoaderResourceAccessor(classloader);
    database.setDatabaseChangeLogTableName(changelogTableName);

    logger.debugf("Using changelog file %s and changelogTableName %s", changelogLocation, database.getDatabaseChangeLogTableName());

    return new Liquibase(changelogLocation, resourceAccessor, database);
}
 
Example #21
Source File: Launcher.java    From jweb-cms with 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 #22
Source File: LiquibaseFactory.java    From quarkus with 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 #23
Source File: DbSchemaDrop.java    From activiti6-boot2 with 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 #24
Source File: FormEngineConfiguration.java    From activiti6-boot2 with 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 #25
Source File: DbScriptUtil.java    From activiti6-boot2 with 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 #26
Source File: DbScriptUtil.java    From activiti6-boot2 with 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 #27
Source File: DmnEngineConfiguration.java    From activiti6-boot2 with 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 #28
Source File: DbSchemaDrop.java    From activiti6-boot2 with 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 #29
Source File: Launcher.java    From jweb-cms with 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 #30
Source File: Main.java    From jweb-cms with 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());
}