liquibase.exception.DatabaseException Java Examples

The following examples show how to use liquibase.exception.DatabaseException. 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: jweb-cms   Author: chifei   File: AbstractJdbcDatabase.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void setConnection(final DatabaseConnection conn) {
    LogService.getLog(getClass()).debug(LogType.LOG, "Connected to " + conn.getConnectionUserName() + "@" + conn.getURL());
    this.connection = conn;
    try {
        boolean autoCommit = conn.getAutoCommit();
        if (autoCommit == getAutoCommitMode()) {
            // Don't adjust the auto-commit mode if it's already what the database wants it to be.
            LogService.getLog(getClass()).debug(LogType.LOG, "Not adjusting the auto commit mode; it is already " + autoCommit);
        } else {
            // Store the previous auto-commit mode, because the connection needs to be restored to it when this
            // AbstractDatabase type is closed. This is important for systems which use connection pools.
            previousAutoCommit = autoCommit;

            LogService.getLog(getClass()).debug(LogType.LOG, "Setting auto commit to " + getAutoCommitMode() + " from " + autoCommit);
            connection.setAutoCommit(getAutoCommitMode());

        }
    } catch (DatabaseException e) {
        LogService.getLog(getClass()).warning(LogType.LOG, "Cannot set auto commit to " + getAutoCommitMode() + " on connection");
    }

    this.connection.attached(this);
}
 
Example #2
Source Project: jweb-cms   Author: chifei   File: AbstractJdbcDatabase.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public String getDefaultCatalogName() {
    if (defaultCatalogName == null) {
        if ((defaultSchemaName != null) && !this.supportsSchemas()) {
            return defaultSchemaName;
        }

        if (connection != null) {
            try {
                defaultCatalogName = getConnectionCatalogName();
            } catch (DatabaseException e) {
                LogService.getLog(getClass()).info(LogType.LOG, "Error getting default catalog", e);
            }
        }
    }
    return defaultCatalogName;
}
 
Example #3
Source Project: keycloak   Author: keycloak   File: CustomLockService.java    License: Apache License 2.0 6 votes vote down vote up
private Set<Integer> currentIdsInDatabaseChangeLogLockTable() throws DatabaseException {
    try {
        Executor executor = ExecutorService.getInstance().getExecutor(database);
        String idColumnName = database.escapeColumnName(database.getLiquibaseCatalogName(),
                database.getLiquibaseSchemaName(),
                database.getDatabaseChangeLogLockTableName(),
                "ID");
        String lockTableName = database.escapeTableName(database.getLiquibaseCatalogName(),
                database.getLiquibaseSchemaName(),
                database.getDatabaseChangeLogLockTableName());
        SqlStatement sqlStatement = new RawSqlStatement("SELECT " + idColumnName + " FROM " + lockTableName);
        List<Map<String, ?>> rows = executor.queryForList(sqlStatement);
        Set<Integer> ids = rows.stream().map(columnMap -> ((Number) columnMap.get("ID")).intValue()).collect(Collectors.toSet());
        database.commit();
        return ids;
    } catch (UnexpectedLiquibaseException ulie) {
        // It can happen with MariaDB Galera 10.1 that UnexpectedLiquibaseException is rethrown due the DB lock.
        // It is sufficient to just rollback transaction and retry in that case.
        if (ulie.getCause() != null && ulie.getCause() instanceof DatabaseException) {
            throw (DatabaseException) ulie.getCause();
        } else {
            throw ulie;
        }
    }
}
 
Example #4
Source Project: keycloak   Author: keycloak   File: JpaUpdate1_2_0_Beta1.java    License: Apache License 2.0 6 votes vote down vote up
protected void convertSocialToIdFedUsers() throws SQLException, DatabaseException {
    String federatedIdentityTableName = database.correctObjectName("FEDERATED_IDENTITY", Table.class);
    PreparedStatement statement = jdbcConnection.prepareStatement("select REALM_ID, USER_ID, SOCIAL_PROVIDER, SOCIAL_USER_ID, SOCIAL_USERNAME from " + getTableName("USER_SOCIAL_LINK"));
    try {
        ResultSet resultSet = statement.executeQuery();
        try {
            int count = 0;
            while (resultSet.next()) {
                InsertStatement insert = new InsertStatement(null, null, federatedIdentityTableName)
                        .addColumnValue("REALM_ID", resultSet.getString("REALM_ID"))
                        .addColumnValue("USER_ID", resultSet.getString("USER_ID"))
                        .addColumnValue("IDENTITY_PROVIDER", resultSet.getString("SOCIAL_PROVIDER"))
                        .addColumnValue("FEDERATED_USER_ID", resultSet.getString("SOCIAL_USER_ID"))
                        .addColumnValue("FEDERATED_USERNAME", resultSet.getString("SOCIAL_USERNAME"));
                count++;
                statements.add(insert);
            }

            confirmationMessage.append("Updating " + count + " social links to federated identities. ");
        } finally {
            resultSet.close();
        }
    } finally {
        statement.close();
    }
}
 
Example #5
Source Project: jweb-cms   Author: chifei   File: AbstractJdbcDatabase.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void close() throws DatabaseException {
    ExecutorService.getInstance().clearExecutor(this);
    DatabaseConnection connection = getConnection();
    if (connection != null) {
        if (previousAutoCommit != null) {
            try {
                connection.setAutoCommit(previousAutoCommit);
            } catch (DatabaseException e) {
                LogService.getLog(getClass()).warning(LogType.LOG, "Failed to restore the auto commit to " + previousAutoCommit);

                throw e;
            }
        }
        connection.close();
    }
}
 
Example #6
Source Project: jweb-cms   Author: chifei   File: AbstractJdbcDatabase.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void execute(final SqlStatement[] statements, final List<SqlVisitor> sqlVisitors) throws LiquibaseException {
    for (SqlStatement statement : statements) {
        if (statement.skipOnUnsupported() && !SqlGeneratorFactory.getInstance().supports(statement, this)) {
            continue;
        }
        LogService.getLog(getClass()).debug(LogType.LOG, "Executing Statement: " + statement);
        try {
            ExecutorService.getInstance().getExecutor(this).execute(statement, sqlVisitors);
        } catch (DatabaseException e) {
            if (statement.continueOnError()) {
                LogService.getLog(getClass()).severe(LogType.LOG, "Error executing statement '" + statement.toString() + "', but continuing", e);
            } else {
                throw e;
            }
        }
    }
}
 
Example #7
Source Project: keycloak   Author: keycloak   File: JpaUpdate1_2_0_Beta1.java    License: Apache License 2.0 6 votes vote down vote up
private String getAdminRoleId() throws SQLException, DatabaseException {
    PreparedStatement statement = jdbcConnection.prepareStatement("select ID from " + getTableName("KEYCLOAK_ROLE") + " where NAME = ? AND REALM = ?");
    statement.setString(1, AdminRoles.ADMIN);
    statement.setString(2, Config.getAdminRealm());

    try {
        ResultSet resultSet = statement.executeQuery();
        try {
            if (resultSet.next()) {
                return resultSet.getString("ID");
            } else {
                throw new IllegalStateException("Couldn't find ID of 'admin' role in 'master' realm");
            }
        } finally {
            resultSet.close();
        }
    } finally {
        statement.close();
    }
}
 
Example #8
Source Project: liquibase-mssql   Author: sabomichal   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 #9
Source Project: liquibase-impala   Author: eselyavka   File: HiveStandardChangeLogHistoryService.java    License: Apache License 2.0 6 votes vote down vote up
@Override
    public void tag(final String tagString) throws DatabaseException {
        Database database = getDatabase();
        Executor executor = ExecutorService.getInstance().getExecutor(database);
        try {
            int totalRows = ExecutorService.getInstance().getExecutor(database).queryForInt(new SelectFromDatabaseChangeLogStatement(new ColumnConfig().setName("COUNT(*)", true)));
            if (totalRows == 0) {
                ChangeSet emptyChangeSet = new ChangeSet(String.valueOf(new Date().getTime()), "liquibase", false, false, "liquibase-internal", null, null, getDatabase().getObjectQuotingStrategy(), null);
                this.setExecType(emptyChangeSet, ChangeSet.ExecType.EXECUTED);
            }

//            Timestamp lastExecutedDate = (Timestamp) this.getExecutor().queryForObject(createChangeToTagSQL(), Timestamp.class);
            executor.execute(new TagDatabaseStatement(tagString));
            getDatabase().commit();

            if (this.ranChangeSetList != null) {
                ranChangeSetList.get(ranChangeSetList.size() - 1).setTag(tagString);
            }
        } catch (Exception e) {
            throw new DatabaseException(e);
        }
    }
 
Example #10
Source Project: keycloak   Author: keycloak   File: QuarkusJpaUpdaterProvider.java    License: Apache License 2.0 6 votes vote down vote up
private void outputChangeLogTableCreationScript(Liquibase liquibase, final Writer exportWriter) throws DatabaseException {
    Database database = liquibase.getDatabase();

    Executor oldTemplate = ExecutorService.getInstance().getExecutor(database);
    LoggingExecutor executor = new LoggingExecutor(ExecutorService.getInstance().getExecutor(database), exportWriter, database);
    ExecutorService.getInstance().setExecutor(database, executor);

    executor.comment("*********************************************************************");
    executor.comment("* Keycloak database creation script - apply this script to empty DB *");
    executor.comment("*********************************************************************" + StreamUtil.getLineSeparator());

    executor.execute(new CreateDatabaseChangeLogTableStatement());
    // DatabaseChangeLogLockTable is created before this code is executed and recreated if it does not exist automatically
    // in org.keycloak.connections.jpa.updater.liquibase.lock.CustomLockService.init() called indirectly from
    // KeycloakApplication constructor (search for waitForLock() call). Hence it is not included in the creation script.

    executor.comment("*********************************************************************" + StreamUtil.getLineSeparator());

    ExecutorService.getInstance().setExecutor(database, oldTemplate);
}
 
Example #11
Source Project: keycloak   Author: keycloak   File: JpaUpdate1_2_0_Beta1.java    License: Apache License 2.0 6 votes vote down vote up
protected void addNewRealmAdminRoles() throws SQLException, DatabaseException {
    PreparedStatement statement = jdbcConnection.prepareStatement("select CLIENT.ID REALM_ADMIN_APP_ID, CLIENT.REALM_ID REALM_ID, KEYCLOAK_ROLE.ID ADMIN_ROLE_ID from " +
            getTableName("CLIENT") + " CLIENT," + getTableName("KEYCLOAK_ROLE") + " KEYCLOAK_ROLE where KEYCLOAK_ROLE.APPLICATION = CLIENT.ID AND CLIENT.NAME = 'realm-management' AND KEYCLOAK_ROLE.NAME = ?");
    statement.setString(1, AdminRoles.REALM_ADMIN);

    try {
        ResultSet resultSet = statement.executeQuery();
        try {

            while (resultSet.next()) {
                String realmAdminAppId = resultSet.getString("REALM_ADMIN_APP_ID");
                String realmId = resultSet.getString("REALM_ID");
                String adminRoleId = resultSet.getString("ADMIN_ROLE_ID");

                addAdminRole(AdminRoles.VIEW_IDENTITY_PROVIDERS, realmId, realmAdminAppId, adminRoleId);
                addAdminRole(AdminRoles.MANAGE_IDENTITY_PROVIDERS, realmId, realmAdminAppId, adminRoleId);
            }
        } finally {
            resultSet.close();
        }
    } finally {
        statement.close();
    }
}
 
Example #12
Source Project: liquibase-spatial   Author: lonnyj   File: DropGeometryColumnGeneratorGeoDBTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test(dataProvider = "generateSqlTestData")
public void testGenerateSql(final DropColumnStatement statement, final Database database,
      final Sql[] expected) throws DatabaseException {
   final DropGeometryColumnGeneratorGeoDB generator = new DropGeometryColumnGeneratorGeoDB();
   final SqlGeneratorChain sqlGeneratorChain = mock(SqlGeneratorChain.class);
   when(sqlGeneratorChain.generateSql(statement, database)).thenReturn(new Sql[0]);
   final Sql[] result = generator.generateSql(statement, database, sqlGeneratorChain);
   assertEquals(result.length, expected.length);
   if (result.length > 0) {
      for (int ii = 0; ii < result.length; ii++) {
         final Sql resultSql = result[ii];
         final Sql expectedSql = expected[ii];
         assertEquals(resultSql.toSql(), expectedSql.toSql());
      }
   }
}
 
Example #13
Source Project: liquibase-mssql   Author: sabomichal   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 #14
Source Project: jweb-cms   Author: chifei   File: AbstractJdbcDatabase.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public String getDatabaseProductName() {
    if (connection == null) {
        return getDefaultDatabaseProductName();
    }

    try {
        return connection.getDatabaseProductName();
    } catch (DatabaseException e) {
        throw new RuntimeException("Cannot get database name");
    }
}
 
Example #15
Source Project: jweb-cms   Author: chifei   File: AbstractJdbcDatabase.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public String getDatabaseProductVersion() throws DatabaseException {
    if (connection == null) {
        return null;
    }

    try {
        return connection.getDatabaseProductVersion();
    } catch (DatabaseException e) {
        throw new DatabaseException(e);
    }
}
 
Example #16
Source Project: jweb-cms   Author: chifei   File: AbstractJdbcDatabase.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public int getDatabaseMajorVersion() throws DatabaseException {
    if (connection == null) {
        return 999;
    }
    try {
        return connection.getDatabaseMajorVersion();
    } catch (DatabaseException e) {
        throw new DatabaseException(e);
    }
}
 
Example #17
Source Project: jweb-cms   Author: chifei   File: AbstractJdbcDatabase.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public int getDatabaseMinorVersion() throws DatabaseException {
    if (connection == null) {
        return -1;
    }
    try {
        return connection.getDatabaseMinorVersion();
    } catch (DatabaseException e) {
        throw new DatabaseException(e);
    }
}
 
Example #18
Source Project: jweb-cms   Author: chifei   File: AbstractJdbcDatabase.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public String getViewDefinition(CatalogAndSchema schema, final String viewName) throws DatabaseException {
    schema = schema.customize(this);
    String definition = ExecutorService.getInstance().getExecutor(this).queryForObject(new GetViewDefinitionStatement(schema.getCatalogName(), schema.getSchemaName(), viewName), String.class);
    if (definition == null) {
        return null;
    }
    return CREATE_VIEW_AS_PATTERN.matcher(definition).replaceFirst("");
}
 
Example #19
Source Project: jweb-cms   Author: chifei   File: AbstractJdbcDatabase.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void rollback() throws DatabaseException {
    try {
        getConnection().rollback();
    } catch (DatabaseException e) {
        throw new DatabaseException(e);
    }
}
 
Example #20
Source Project: jweb-cms   Author: chifei   File: AbstractJdbcDatabase.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public boolean isAutoCommit() throws DatabaseException {
    try {
        return getConnection().getAutoCommit();
    } catch (DatabaseException e) {
        throw new DatabaseException(e);
    }
}
 
Example #21
Source Project: jweb-cms   Author: chifei   File: AbstractJdbcDatabase.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void setAutoCommit(final boolean b) throws DatabaseException {
    try {
        getConnection().setAutoCommit(b);
    } catch (DatabaseException e) {
        throw new DatabaseException(e);
    }
}
 
Example #22
Source Project: jweb-cms   Author: chifei   File: AbstractJdbcDatabase.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Default implementation, just look for "local" IPs. If the database returns a null URL we return false since we don't know it's safe to run the update.
 *
 * @throws DatabaseException
 */
@Override
public boolean isSafeToRunUpdate() throws DatabaseException {
    DatabaseConnection connection = getConnection();
    if (connection == null) {
        return true;
    }
    String url = connection.getURL();
    if (url == null) {
        return false;
    }
    return (url.contains("localhost")) || (url.contains("127.0.0.1"));
}
 
Example #23
Source Project: jweb-cms   Author: chifei   File: AbstractJdbcDatabase.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public boolean supportsBatchUpdates() throws DatabaseException {
    if (connection instanceof OfflineConnection) {
        return false;
    } else if (connection instanceof JdbcConnection) {
        return ((JdbcConnection) getConnection()).supportsBatchUpdates();
    } else {
        // Normally, the connection can only be one of the two above types. But if, for whatever reason, it is
        // not, let's err on the safe side.
        return false;
    }
}
 
Example #24
Source Project: airsonic   Author: airsonic   File: HsqlDatabase.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean supportsSchemas() {
    try {
        if (getDatabaseMajorVersion() < 2) {
            return false;
        } else {
            return super.supportsSchemas();
        }
    } catch (DatabaseException e) {
        return false;
    }
}
 
Example #25
Source Project: airsonic   Author: airsonic   File: DbmsVersionPrecondition.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public void check(Database database) throws CustomPreconditionFailedException, CustomPreconditionErrorException {
    try {
        int dbMajor = database.getDatabaseMajorVersion();
        int dbMinor = database.getDatabaseMinorVersion();
        if (major != null && !major.equals(dbMajor)) {
            throw new CustomPreconditionFailedException("DBMS Major Version Precondition failed: expected " + major + ", got " + dbMajor);
        }
        if (minor != null && !minor.equals(dbMinor)) {
            throw new CustomPreconditionFailedException("DBMS Minor Version Precondition failed: expected " + minor + ", got " + dbMinor);
        }
    } catch (DatabaseException e) {
        throw new CustomPreconditionErrorException(e.getMessage());
    }
}
 
Example #26
Source Project: multiapps-controller   Author: cloudfoundry-incubator   File: AbstractDataTransformationChange.java    License: Apache License 2.0 5 votes vote down vote up
public OriginalDataType retrieveData(JdbcConnection jdbcConnection) throws DatabaseException, SQLException {
    PreparedStatement preparedStatement = null;
    OriginalDataType result = null;

    try {
        preparedStatement = jdbcConnection.prepareStatement(getSelectStatement(), ResultSet.TYPE_FORWARD_ONLY,
                                                            ResultSet.CONCUR_READ_ONLY);
        ResultSet resultSet = preparedStatement.executeQuery();
        result = extractData(resultSet);
        resultSet.close();
    } finally {
        JdbcUtil.closeQuietly(preparedStatement);
    }
    return result;
}
 
Example #27
Source Project: multiapps-controller   Author: cloudfoundry-incubator   File: AbstractDataTransformationChange.java    License: Apache License 2.0 5 votes vote down vote up
public void updateTable(JdbcConnection jdbcConnection, TransformedDataType transformedData) throws DatabaseException, SQLException {
    PreparedStatement preparedStatement = null;

    try {
        preparedStatement = jdbcConnection.prepareStatement(getUpdateStatement());
        setUpdateStatementParameters(preparedStatement, transformedData);
        preparedStatement.executeBatch();
    } finally {
        JdbcUtil.closeQuietly(preparedStatement);
    }
}
 
Example #28
Source Project: multiapps-controller   Author: cloudfoundry-incubator   File: AbstractDataTransformationChange.java    License: Apache License 2.0 5 votes vote down vote up
private void executeStatement(JdbcConnection jdbcConnection, String statement) throws DatabaseException, SQLException {
    PreparedStatement preparedStatement = null;
    try {
        preparedStatement = jdbcConnection.prepareStatement(statement);
        preparedStatement.execute();
    } finally {
        JdbcUtil.closeQuietly(preparedStatement);
    }
}
 
Example #29
Source Project: multiapps-controller   Author: cloudfoundry-incubator   File: AbstractChange.java    License: Apache License 2.0 5 votes vote down vote up
private void attemptToRollbackTransaction(JdbcConnection jdbcConnection) {
    try {
        jdbcConnection.rollback();
    } catch (DatabaseException e) {
        logger.warn(Messages.COULD_NOT_ROLLBACK_TRANSACTION, e);
    }
}
 
Example #30
Source Project: liquibase-impala   Author: eselyavka   File: HiveStandardChangeLogHistoryService.java    License: Apache License 2.0 5 votes vote down vote up
private boolean hasDatabaseChangeLogTable() throws DatabaseException {
    if (hasDatabaseChangeLogTable == null) {
        try {
            hasDatabaseChangeLogTable = SnapshotGeneratorFactory.getInstance().hasDatabaseChangeLogTable(getDatabase());
        } catch (LiquibaseException e) {
            throw new UnexpectedLiquibaseException(e);
        }
    }
    return hasDatabaseChangeLogTable;
}