liquibase.database.jvm.JdbcConnection Java Examples

The following examples show how to use liquibase.database.jvm.JdbcConnection. 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: DBTestUtils.java    From trellis with 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 #2
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 #3
Source File: GeometryColumnsUtilsTest.java    From liquibase-spatial with Apache License 2.0 6 votes vote down vote up
@DataProvider
public Object[][] geometryColumnsExistsTestData() throws SQLException {
   // Create an H2 database instance without geometry_columns table.
   final Database noGeometryColumnsDatabase = new H2Database();
   noGeometryColumnsDatabase.setConnection(new JdbcConnection(DriverManager
         .getConnection("jdbc:h2:mem:target/noGeometryColumns")));

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

   Statement statement = connection.createStatement();
   statement
         .execute("CREATE TABLE geometry_columns (f_table_schema VARCHAR(128), "
               + "f_table_name VARCHAR(128), f_geometry_column VARCHAR(128), coord_dimension INT, "
               + "srid INT, type VARCHAR(30))");
   statement.close();
   return new Object[][] {
         new Object[] { noGeometryColumnsDatabase, false },
         new Object[] { geometryColumnsDatabase, true } };
}
 
Example #4
Source File: LiquibaseIT.java    From liquibase-spatial with 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 #5
Source File: LiquibaseIT.java    From liquibase-spatial with 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 #6
Source File: AbstractJdbcDatabase.java    From jweb-cms with GNU Affero General Public License v3.0 6 votes vote down vote up
@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 #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: OracleSpatialUtils.java    From liquibase-spatial with Apache License 2.0 6 votes vote down vote up
/**
 * Queries to the database to convert the given EPSG SRID to the corresponding Oracle SRID.
 *
 * @param srid
 *           the EPSG SRID.
 * @param database
 *           the database instance.
 * @return the corresponding Oracle SRID.
 */
public static String loadOracleSrid(final String srid, final Database database) {
   final String oracleSrid;
   final JdbcConnection jdbcConnection = (JdbcConnection) database.getConnection();
   final Connection connection = jdbcConnection.getUnderlyingConnection();
   Statement statement = null;
   try {
      statement = connection.createStatement();
      final ResultSet resultSet = statement.executeQuery("SELECT " + EPSG_TO_ORACLE_FUNCTION
            + "(" + srid + ") FROM dual");
      resultSet.next();
      oracleSrid = resultSet.getString(1);
   } catch (final SQLException e) {
      throw new UnexpectedLiquibaseException("Failed to find the Oracle SRID for EPSG:" + srid,
            e);
   } finally {
      try {
         statement.close();
      } catch (final SQLException ignore) {
      }
   }
   return oracleSrid;
}
 
Example #10
Source File: DropConfigurationRegistryUniqueConstraintPostgresqlChange.java    From multiapps-controller with Apache License 2.0 6 votes vote down vote up
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 #11
Source File: LiquibasePreparer.java    From otj-pg-embedded with 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 #12
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 #13
Source File: GenerateCartUUIDs.java    From DataHubSystem with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void execute (Database database) throws CustomChangeException
{
   JdbcConnection databaseConnection =
      (JdbcConnection) database.getConnection ();
   try
   {         
      PreparedStatement getCarts =
         databaseConnection.prepareStatement ("SELECT ID FROM PRODUCTCARTS");
      ResultSet res = getCarts.executeQuery ();
      while (res.next ())
      {
         String uuid = UUID.randomUUID ().toString ();
         PreparedStatement updateCart =
            databaseConnection
               .prepareStatement ("UPDATE PRODUCTCARTS SET UUID = '" + uuid +
                  "' WHERE ID = " + res.getObject ("ID"));
         updateCart.execute ();
         updateCart.close ();

         PreparedStatement updateProductsLink =
            databaseConnection
               .prepareStatement ("UPDATE CART_PRODUCTS SET CART_UUID = '" +
                  uuid + "' WHERE CART_ID = " + res.getObject ("ID"));
         updateProductsLink.execute ();
         updateProductsLink.close ();
      }
      getCarts.close ();
   }
   catch (Exception e)
   {
      e.printStackTrace ();
   }
   
}
 
Example #14
Source File: LiquibaseImpl.java    From iaf with Apache License 2.0 5 votes vote down vote up
public LiquibaseImpl(IbisContext ibisContext, ClassLoader classLoader, JdbcConnection connection, String configurationName, String changeLogFile) throws LiquibaseException {
	this.ibisContext = ibisContext;
	this.configurationName = configurationName;

	ClassLoaderResourceAccessor resourceOpener = new ClassLoaderResourceAccessor(classLoader);

	this.liquibase = new Liquibase(changeLogFile, resourceOpener, connection);
	this.liquibase.validate();
}
 
Example #15
Source File: CertificateBlobToBase64.java    From aerogear-unifiedpush-server with Apache License 2.0 5 votes vote down vote up
@Override
public SqlStatement[] generateStatements(Database database) throws CustomChangeException {
    List<SqlStatement> statements = new ArrayList<>();

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

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

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

        }
        conn.commit();

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

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

}
 
Example #16
Source File: GetRidOfApiKeysMigration.java    From aerogear-unifiedpush-server with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(Database database) throws CustomChangeException {
    Connection conn = ((JdbcConnection) (database.getConnection())).getWrappedConnection();
    try {
        conn.setAutoCommit(false);
        List<InstallationData> list = new ArrayList<>();
        String query = "select installation.id as installation_id," +
                " installation.variant_id as installation_variant_id," +
                " variant.id as variant_id," +
                " variant.api_key as variant_api_key" +
                " from installation join variant on installation.variant_id = variant.api_key";
        PreparedStatement statement = conn.prepareStatement(query);
        ResultSet rs = statement.executeQuery();
        while (rs.next()) {
            String installationId = rs.getString("installation_id");
            String installationVariantId = rs.getString("installation_variant_id");
            String variantId = rs.getString("variant_id");
            String variantApiKey = rs.getString("variant_api_key");
            list.add(new InstallationData(installationId,variantId));
        }
        String update = "update installation" +
                " set variant_id = ?" +
                " where id = ?";
        PreparedStatement updateInstallationsStatement = conn.prepareStatement(update);
        for (InstallationData data: list) {
            updateInstallationsStatement.setString(1, data.variantId);
            updateInstallationsStatement.setString(2, data.installationId);
            updateInstallationsStatement.executeUpdate();
        }

        conn.commit();
    } catch (SQLException e) {
        e.printStackTrace();
    }
}
 
Example #17
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 #18
Source File: LiquibaseService.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
@Override
public Liquibase newConnectedLiquibase() throws SQLException, LiquibaseException
{
    config.refresh();
    DatabaseConnection dbConnection = new JdbcConnection( dataSource.get().getConnection() );
    return new Liquibase( config.get().changeLog().get(),
                          new ClassLoaderResourceAccessor(),
                          dbConnection );
}
 
Example #19
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 #20
Source File: GenerateRestrictionUUIDs.java    From DataHubSystem with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void execute (Database database) throws CustomChangeException
{
   JdbcConnection databaseConnection =
      (JdbcConnection) database.getConnection ();
   try
   {         
      PreparedStatement getRestrictions =
         databaseConnection.prepareStatement ("SELECT ID FROM ACCESS_RESTRICTION");
      ResultSet res = getRestrictions.executeQuery ();
      while (res.next ())
      {
         String uuid = UUID.randomUUID ().toString ();
         PreparedStatement updateRestrictions =
            databaseConnection
               .prepareStatement ("UPDATE ACCESS_RESTRICTION SET UUID = '" + uuid +
                  "' WHERE ID = " + res.getObject ("ID"));
         updateRestrictions.execute ();
         updateRestrictions.close ();

         PreparedStatement updateUserRestricitons =
            databaseConnection
               .prepareStatement ("UPDATE USER_RESTRICTIONS SET RESTRICTION_UUID = '" +
                  uuid + "' WHERE RESTRICTION_ID = " + res.getObject ("ID"));
         updateUserRestricitons.execute ();
         updateUserRestricitons.close ();
      }
      getRestrictions.close ();
   }
   catch (Exception e)
   {
      e.printStackTrace ();
   }
   
}
 
Example #21
Source File: DbScriptUtil.java    From flowable-engine with 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/flowable-admin/TEST-db.properties"));
    Connection connection = DriverManager.getConnection(properties.getProperty("spring.datasource.url"),
            properties.getProperty("spring.datasource.username"), properties.getProperty("spring.datasource.password"));
    DatabaseConnection databaseConnection = new JdbcConnection(connection);
    return databaseConnection;
}
 
Example #22
Source File: GeometryColumnsUtils.java    From liquibase-spatial with Apache License 2.0 5 votes vote down vote up
/**
 * Determines if the given column is in <code>GEOMETRY_COLUMNS</code>.
 * 
 * @param database
 *           the database to query.
 * @param schemaName
 *           the schema name.
 * @param tableName
 *           the table name.
 * @param columnName
 *           the column name.
 * @return <code>true</code> if the column is a geometry column.
 */
public static boolean isGeometryColumn(final Database database,
      final String schemaName, final String tableName,
      final String columnName) {
   boolean isSpatialColumn = false;
   Statement jdbcStatement = null;
   try {
      if (geometryColumnsExists(database)) {
         final String query = "SELECT * FROM geometry_columns WHERE f_table_schema = '"
               + (schemaName == null ? database.getDefaultSchemaName()
                     : schemaName)
               + "' AND f_table_name = '"
               + tableName
               + "' AND upper(f_geometry_column) = '"
               + columnName.toUpperCase() + "'";
         final DatabaseConnection databaseConnection = database
               .getConnection();
         final JdbcConnection jdbcConnection = (JdbcConnection) databaseConnection;
         jdbcStatement = jdbcConnection.getUnderlyingConnection()
               .createStatement();
         final ResultSet rs = jdbcStatement.executeQuery(query);
         isSpatialColumn = rs.next();
      }
   } catch (final SQLException e) {
      throw new UnexpectedLiquibaseException(
            "Failed to determine if the column to be dropped is a geometry column",
            e);
   } finally {
      if (jdbcStatement != null) {
         try {
            jdbcStatement.close();
         } catch (final SQLException ignore) {
         }
      }
   }
   return isSpatialColumn;
}
 
Example #23
Source File: RemoveLFUStrategy.java    From DataHubSystem with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void execute (Database database) throws CustomChangeException
{
   JdbcConnection databaseConnection =
      (JdbcConnection) database.getConnection ();
   try
   {
      PreparedStatement getEvictions =
         databaseConnection
            .prepareStatement ("SELECT ID,STRATEGY FROM EVICTION");
      ResultSet res = getEvictions.executeQuery ();
      
      while (res.next ())
      {
         Integer strategy = (Integer) res.getObject ("STRATEGY");
         if (strategy == 2)
         {
            // 2 (old LFU) -> 0 (None)
            strategy = 0;
         }
         if (strategy == 3)
         {
            // 3 (old FIFO) -> 2 (new FIFO)
            strategy = 2;
         }
         PreparedStatement updateStrategy =
            databaseConnection
               .prepareStatement ("UPDATE EVICTION SET STRATEGY = '" +
                     strategy+"' WHERE ID = "+res.getObject ("ID"));
         updateStrategy.execute ();
         updateStrategy.close ();
      }
      getEvictions.close ();         
   }
   catch (Exception e)
   {
      LOGGER.error("Error during liquibase update 'removeLFUStrategy'", e);
   }
}
 
Example #24
Source File: MoveOwnerInProduct.java    From DataHubSystem with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void execute (Database database) throws CustomChangeException
{
   JdbcConnection databaseConnection =
      (JdbcConnection) database.getConnection ();
   try
   {
      PreparedStatement getOwners =
         databaseConnection
            .prepareStatement ("SELECT o.USER_ID, p.ID FROM OWNER o, " +
                  "PRODUCTS p WHERE o.OWNEROFPRODUCT = p.IDENTIFIER");
      ResultSet res = getOwners.executeQuery ();

      while (res.next ())
      {
         Long productIdentifier = (Long) res.getObject ("ID");   
         Long userIdentifier = (Long) res.getObject ("USER_ID");  
         PreparedStatement updateOwner =
            databaseConnection
               .prepareStatement ("UPDATE PRODUCTS SET OWNER_ID = " +
                     userIdentifier+" WHERE ID = "+productIdentifier);
         updateOwner.execute ();
         updateOwner.close();
      }
      getOwners.close ();
   }
   catch (Exception e)
   {
      LOGGER.error("Error during liquibase update 'MoveOwnerInProduct'", e);
   }
}
 
Example #25
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 #26
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 #27
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 #28
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 #29
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 #30
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);
    }
}