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 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 #2
Source File: AbstractJdbcDatabase.java    From jweb-cms with 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 #3
Source File: HiveStandardChangeLogHistoryService.java    From liquibase-impala with 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 #4
Source File: JpaUpdate1_2_0_Beta1.java    From keycloak with 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 File: AbstractJdbcDatabase.java    From jweb-cms with 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 #6
Source File: AbstractJdbcDatabase.java    From jweb-cms with 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 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 #8
Source File: JpaUpdate1_2_0_Beta1.java    From keycloak with 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 #9
Source File: CustomLockService.java    From keycloak with 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 #10
Source File: QuarkusJpaUpdaterProvider.java    From keycloak with 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 File: AbstractJdbcDatabase.java    From jweb-cms with 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 #12
Source File: JpaUpdate1_2_0_Beta1.java    From keycloak with 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 #13
Source File: DropGeometryColumnGeneratorGeoDBTest.java    From liquibase-spatial with 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 #14
Source File: LiquibaseHelper.java    From FROST-Server with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static boolean doUpgrades(Connection connection, String liquibaseChangelogFilename, Writer out) throws UpgradeFailedException, IOException {
    try {
        Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(connection));
        runLiquibaseUpdate(liquibaseChangelogFilename, database, out);
    } catch (DatabaseException ex) {
        outputError(ex, out, "Failed to initialise database");
        return false;
    }
    return true;
}
 
Example #15
Source File: MySQL8VarcharType.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public DatabaseDataType toDatabaseDataType(Database database) {
    if (database instanceof MySQLDatabase) {
        try {
            if (database.getDatabaseMajorVersion() >= 8 && getSize() > 255) {
                return new DatabaseDataType(database.escapeDataTypeName("TEXT"), getSize());
            }
        } catch (DatabaseException e) {
            throw new RuntimeException(e);
        }
    }
    return super.toDatabaseDataType(database);
}
 
Example #16
Source File: LiquibaseHelper.java    From FROST-Server with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static String checkForUpgrades(Connection connection, String liquibaseChangelogFilename) {
    StringWriter out = new StringWriter();
    try {
        Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(connection));
        runLiquibaseCheck(liquibaseChangelogFilename, database, out);
    } catch (DatabaseException ex) {
        outputError(ex, out, "Failed to initialise database");
    }
    return out.toString();
}
 
Example #17
Source File: DatabaseConfiguration.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
private void closeDatabase(Liquibase liquibase) {
    if (liquibase != null) {
        Database database = liquibase.getDatabase();
        if (database != null) {
            try {
                database.close();
            } catch (DatabaseException e) {
                LOGGER.warn("Error closing database", e);
            }
        }
    }
}
 
Example #18
Source File: FormEngineConfiguration.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
private void closeDatabase(Liquibase liquibase) {
    if (liquibase != null) {
        Database database = liquibase.getDatabase();
        if (database != null) {
            try {
                database.close();
            } catch (DatabaseException e) {
                logger.warn("Error closing database", e);
            }
        }
    }
}
 
Example #19
Source File: AbstractDataTransformationChange.java    From multiapps-controller with 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 #20
Source File: DatabaseConfiguration.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
private void closeDatabase(Liquibase liquibase) {
    if (liquibase != null) {
        Database database = liquibase.getDatabase();
        if (database != null) {
            try {
                database.close();
            } catch (DatabaseException e) {
                LOGGER.warn("Error closing database", e);
            }
        }
    }
}
 
Example #21
Source File: EventRegistryEngineConfiguration.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
private void closeDatabase(Liquibase liquibase) {
    if (liquibase != null) {
        Database database = liquibase.getDatabase();
        if (database != null) {
            try {
                database.close();
            } catch (DatabaseException e) {
                logger.warn("Error closing database", e);
            }
        }
    }
}
 
Example #22
Source File: PerconaChangeUtil.java    From liquibase-percona with Apache License 2.0 5 votes vote down vote up
public static boolean isConnected(Database database) {
    try {
        if (database.getConnection() != null) {
            return !database.getConnection().isClosed();
        }
        return false;
    } catch (DatabaseException e) {
        return false;
    }
}
 
Example #23
Source File: LiquibaseDBLockProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void destroyLockInfo() {
    KeycloakModelUtils.suspendJtaTransaction(session.getKeycloakSessionFactory(), () -> {
        lazyInit();

        try {
            this.lockService.destroy();
            dbConnection.commit();
            logger.debug("Destroyed lock table");
        } catch (DatabaseException | SQLException de) {
            logger.error("Failed to destroy lock table");
            safeRollbackConnection();
        }
    });
}
 
Example #24
Source File: LiquibaseBasedSchemaManager.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
protected void closeDatabase(Liquibase liquibase) {
    if (liquibase != null) {
        Database database = liquibase.getDatabase();
        if (database != null) {
            // do not close the shared connection if a command context is currently active
            if (Context.getCommandContext() == null) {
                try {
                    database.close();
                } catch (DatabaseException e) {
                    logger.warn("Error closing database for {}", context, e);
                }
            }
        }
    }
}
 
Example #25
Source File: HiveStandardChangeLogHistoryService.java    From liquibase-impala with Apache License 2.0 5 votes vote down vote up
@Override
public void removeFromHistory(final ChangeSet changeSet) throws DatabaseException {
    Database database = getDatabase();
    ExecutorService.getInstance().getExecutor(database).execute(new RemoveChangeSetRanStatusStatement(changeSet));
    getDatabase().commit();

    if (this.ranChangeSetList != null) {
        this.ranChangeSetList.remove(new RanChangeSet(changeSet));
    }
}
 
Example #26
Source File: HiveStandardChangeLogHistoryService.java    From liquibase-impala with Apache License 2.0 5 votes vote down vote up
@Override
public void setExecType(ChangeSet changeSet, ChangeSet.ExecType execType) throws DatabaseException {
    Database database = getDatabase();

    ExecutorService.getInstance().getExecutor(database).execute(new MarkChangeSetRanStatement(changeSet, execType));
    getDatabase().commit();
    if (this.ranChangeSetList != null) {
        this.ranChangeSetList.add(new RanChangeSet(changeSet, execType, null, null));
    }

}
 
Example #27
Source File: HiveStandardChangeLogHistoryService.java    From liquibase-impala with Apache License 2.0 5 votes vote down vote up
@Override
protected void replaceChecksum(ChangeSet changeSet) throws DatabaseException {
    ExecutorService.getInstance().getExecutor(getDatabase()).execute(new UpdateChangeSetChecksumStatement(changeSet));

    getDatabase().commit();
    reset();
}
 
Example #28
Source File: HiveStandardChangeLogHistoryService.java    From liquibase-impala with 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;
}
 
Example #29
Source File: AbstractChange.java    From multiapps-controller with 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 File: HiveStandardChangeLogHistoryService.java    From liquibase-impala with Apache License 2.0 5 votes vote down vote up
@Override
public RanChangeSet getRanChangeSet(final ChangeSet changeSet) throws DatabaseException, DatabaseHistoryException {
    if (!hasDatabaseChangeLogTable()) {
        return null;
    }

    return super.getRanChangeSet(changeSet);
}