Search in sources :

Example 51 with DatabaseException

use of liquibase.exception.DatabaseException in project liquibase by liquibase.

the class TableSnapshotGenerator method addTo.

@Override
protected void addTo(DatabaseObject foundObject, DatabaseSnapshot snapshot) throws DatabaseException, InvalidExampleException {
    if (!snapshot.getSnapshotControl().shouldInclude(Table.class)) {
        return;
    }
    if (foundObject instanceof Schema) {
        Database database = snapshot.getDatabase();
        Schema schema = (Schema) foundObject;
        List<CachedRow> tableMetaDataRs = null;
        try {
            tableMetaDataRs = ((JdbcDatabaseSnapshot) snapshot).getMetaDataFromCache().getTables(((AbstractJdbcDatabase) database).getJdbcCatalogName(schema), ((AbstractJdbcDatabase) database).getJdbcSchemaName(schema), null);
            for (CachedRow row : tableMetaDataRs) {
                String tableName = row.getString("TABLE_NAME");
                Table tableExample = (Table) new Table().setName(cleanNameFromDatabase(tableName, database)).setSchema(schema);
                schema.addDatabaseObject(tableExample);
            }
        } catch (SQLException e) {
            throw new DatabaseException(e);
        }
    }
}
Also used : CachedRow(liquibase.snapshot.CachedRow) Table(liquibase.structure.core.Table) SQLException(java.sql.SQLException) Schema(liquibase.structure.core.Schema) CatalogAndSchema(liquibase.CatalogAndSchema) Database(liquibase.database.Database) AbstractJdbcDatabase(liquibase.database.AbstractJdbcDatabase) JdbcDatabaseSnapshot(liquibase.snapshot.JdbcDatabaseSnapshot) AbstractJdbcDatabase(liquibase.database.AbstractJdbcDatabase) DatabaseException(liquibase.exception.DatabaseException)

Example 52 with DatabaseException

use of liquibase.exception.DatabaseException in project liquibase by liquibase.

the class UniqueConstraintSnapshotGenerator method addTo.

@Override
protected void addTo(DatabaseObject foundObject, DatabaseSnapshot snapshot) throws DatabaseException {
    if (!snapshot.getSnapshotControl().shouldInclude(UniqueConstraint.class)) {
        return;
    }
    if (foundObject instanceof Table) {
        Table table = (Table) foundObject;
        Database database = snapshot.getDatabase();
        Schema schema;
        schema = table.getSchema();
        List<CachedRow> metadata;
        try {
            metadata = listConstraints(table, snapshot, schema);
        } catch (SQLException e) {
            throw new DatabaseException(e);
        }
        Set<String> seenConstraints = new HashSet<>();
        for (CachedRow constraint : metadata) {
            UniqueConstraint uq = new UniqueConstraint().setName(cleanNameFromDatabase((String) constraint.get("CONSTRAINT_NAME"), database)).setRelation(table);
            if (constraint.containsColumn("INDEX_NAME")) {
                uq.setBackingIndex(new Index((String) constraint.get("INDEX_NAME"), (String) constraint.get("INDEX_CATALOG"), (String) constraint.get("INDEX_SCHEMA"), table.getName()));
            }
            if ("CLUSTERED".equals(constraint.get("TYPE_DESC"))) {
                uq.setClustered(true);
            }
            if (seenConstraints.add(uq.getName())) {
                table.getUniqueConstraints().add(uq);
            }
        }
    }
}
Also used : CachedRow(liquibase.snapshot.CachedRow) Table(liquibase.structure.core.Table) SQLException(java.sql.SQLException) Schema(liquibase.structure.core.Schema) Database(liquibase.database.Database) UniqueConstraint(liquibase.structure.core.UniqueConstraint) Index(liquibase.structure.core.Index) DatabaseException(liquibase.exception.DatabaseException) HashSet(java.util.HashSet)

Example 53 with DatabaseException

use of liquibase.exception.DatabaseException in project liquibase by liquibase.

the class ColumnSnapshotGenerator method addTo.

@Override
protected void addTo(DatabaseObject foundObject, DatabaseSnapshot snapshot) throws DatabaseException {
    if (!snapshot.getSnapshotControl().shouldInclude(Column.class)) {
        return;
    }
    if (foundObject instanceof Relation) {
        Database database = snapshot.getDatabase();
        Relation relation = (Relation) foundObject;
        List<CachedRow> allColumnsMetadataRs;
        try {
            JdbcDatabaseSnapshot.CachingDatabaseMetaData databaseMetaData = ((JdbcDatabaseSnapshot) snapshot).getMetaDataFromCache();
            Schema schema;
            schema = relation.getSchema();
            allColumnsMetadataRs = databaseMetaData.getColumns(((AbstractJdbcDatabase) database).getJdbcCatalogName(schema), ((AbstractJdbcDatabase) database).getJdbcSchemaName(schema), relation.getName(), null);
            List<CachedRow> metaDataNotNullConst = databaseMetaData.getNotNullConst(schema.getCatalogName(), schema.getName(), relation.getName());
            /*
                 * Microsoft SQL Server, SAP SQL Anywhere and probably other RDBMS guarantee non-duplicate
                 * ORDINAL_POSITIONs for the columns of a single table. But they do not guarantee there are no gaps
                 * in that integers (e.g. if columns have been deleted). So we need to check for that and renumber
                 * if needed.
                 */
            TreeMap<Integer, CachedRow> treeSet = new TreeMap<>();
            for (CachedRow row : allColumnsMetadataRs) {
                treeSet.put(row.getInt("ORDINAL_POSITION"), row);
            }
            Logger log = Scope.getCurrentScope().getLog(getClass());
            // Now we can iterate through the sorted list and repair if needed.
            int currentOrdinal = 0;
            for (CachedRow row : treeSet.values()) {
                currentOrdinal++;
                int rsOrdinal = row.getInt("ORDINAL_POSITION");
                if (rsOrdinal != currentOrdinal) {
                    log.fine(String.format("Repairing ORDINAL_POSITION with gaps for table=%s, column name=%s, " + "bad ordinal=%d, new ordinal=%d", relation.getName(), row.getString("COLUMN_NAME"), rsOrdinal, currentOrdinal));
                    row.set("ORDINAL_POSITION", currentOrdinal);
                }
            }
            // Iterate through all (repaired) rows and add the columns to our result.
            for (CachedRow row : allColumnsMetadataRs) {
                Column column = readColumn(row, relation, database);
                setAutoIncrementDetails(column, database, snapshot);
                populateValidateNullableIfNeeded(column, metaDataNotNullConst, database);
                column.setAttribute(LIQUIBASE_COMPLETE, !column.isNullable());
                relation.getColumns().add(column);
            }
        } catch (SQLException e) {
            throw new DatabaseException(e);
        }
    }
}
Also used : CachedRow(liquibase.snapshot.CachedRow) TreeMap(java.util.TreeMap) Logger(liquibase.logging.Logger) AbstractJdbcDatabase(liquibase.database.AbstractJdbcDatabase) AbstractJdbcDatabase(liquibase.database.AbstractJdbcDatabase) Database(liquibase.database.Database) JdbcDatabaseSnapshot(liquibase.snapshot.JdbcDatabaseSnapshot) DatabaseException(liquibase.exception.DatabaseException)

Example 54 with DatabaseException

use of liquibase.exception.DatabaseException in project liquibase by liquibase.

the class InternalDropAllCommandStep method run.

@Override
public void run(CommandResultsBuilder resultsBuilder) throws Exception {
    CommandScope commandScope = resultsBuilder.getCommandScope();
    BufferedLogService bufferLog = new BufferedLogService();
    validateConnectionAndProjectIdsDependingOnApiKey(commandScope);
    Operation dropAllOperation;
    LockService lockService = LockServiceFactory.getInstance().getLockService(commandScope.getArgumentValue(DATABASE_ARG));
    HubUpdater hubUpdater;
    try {
        lockService.waitForLock();
        DatabaseChangeLog changeLog;
        HubRegisterResponse hubRegisterResponse = null;
        if (StringUtil.isNotEmpty(commandScope.getArgumentValue(CHANGELOG_FILE_ARG))) {
            // Let the user know they can register for Hub
            changeLog = parseChangeLogFile(commandScope.getArgumentValue(CHANGELOG_FILE_ARG));
            hubUpdater = new HubUpdater(new Date(), changeLog, commandScope.getArgumentValue(DATABASE_ARG));
            hubRegisterResponse = hubUpdater.register(commandScope.getArgumentValue(CHANGELOG_FILE_ARG));
            // Access the HubChangeLog and check to see if we should run syncHub
            HubChangeLog hubChangeLog = getHubChangeLog(changeLog);
            checkForRegisteredChangeLog(changeLog, hubChangeLog);
        } else {
            hubUpdater = new HubUpdater(new Date(), commandScope.getArgumentValue(DATABASE_ARG));
            hubRegisterResponse = hubUpdater.register(null);
        }
        Connection hubConnection = getHubConnection(commandScope);
        attachProjectToConnection(commandScope, hubConnection, hubRegisterResponse);
        dropAllOperation = hubUpdater.preUpdateHub("DROPALL", "drop-all", hubConnection);
        try {
            for (CatalogAndSchema schema : commandScope.getArgumentValue(SCHEMAS_ARG)) {
                log.info("Dropping Database Objects in schema: " + schema);
                checkLiquibaseTables(commandScope.getArgumentValue(DATABASE_ARG));
                commandScope.getArgumentValue(DATABASE_ARG).dropDatabaseObjects(schema);
            }
        } catch (LiquibaseException liquibaseException) {
            hubUpdater.postUpdateHubExceptionHandling(dropAllOperation, bufferLog, liquibaseException.getMessage());
            return;
        }
        final HubServiceFactory hubServiceFactory = Scope.getCurrentScope().getSingleton(HubServiceFactory.class);
        String apiKey = StringUtil.trimToNull(HubConfiguration.LIQUIBASE_HUB_API_KEY.getCurrentValue());
        if (apiKey != null && hubServiceFactory.isOnline()) {
            hubUpdater.syncHub(commandScope.getArgumentValue(CHANGELOG_FILE_ARG), hubConnection);
            hubUpdater.postUpdateHub(dropAllOperation, bufferLog);
        }
    } catch (DatabaseException e) {
        throw e;
    } catch (Exception e) {
        throw new DatabaseException(e);
    } finally {
        lockService.releaseLock();
        lockService.destroy();
        resetServices();
    }
    Scope.getCurrentScope().getUI().sendMessage("All objects dropped from " + commandScope.getArgumentValue(DATABASE_ARG).getConnection().getConnectionUserName() + "@" + commandScope.getArgumentValue(DATABASE_ARG).getConnection().getURL());
    resultsBuilder.addResult("statusCode", 0);
}
Also used : LockService(liquibase.lockservice.LockService) DatabaseConnection(liquibase.database.DatabaseConnection) CatalogAndSchema(liquibase.CatalogAndSchema) BufferedLogService(liquibase.logging.core.BufferedLogService) DatabaseChangeLog(liquibase.changelog.DatabaseChangeLog) Date(java.util.Date) DatabaseException(liquibase.exception.DatabaseException) CommandExecutionException(liquibase.exception.CommandExecutionException) LiquibaseException(liquibase.exception.LiquibaseException) LiquibaseException(liquibase.exception.LiquibaseException) DatabaseException(liquibase.exception.DatabaseException)

Example 55 with DatabaseException

use of liquibase.exception.DatabaseException in project liquibase by liquibase.

the class SQLiteDatabase method getAlterTableSqls.

/**
 * Uses {@link SqlGeneratorFactory} to generate {@link Sql} for the specified visitor and db objects.
 *
 * @param database
 * @param alterTableVisitor
 * @param catalogName
 * @param schemaName
 * @param tableName
 * @return
 */
public static Sql[] getAlterTableSqls(Database database, SQLiteDatabase.AlterTableVisitor alterTableVisitor, String catalogName, String schemaName, String tableName) {
    Sql[] generatedSqls;
    try {
        List<SqlStatement> statements = SQLiteDatabase.getAlterTableStatements(alterTableVisitor, database, catalogName, schemaName, tableName);
        // convert from SqlStatement to Sql
        SqlStatement[] sqlStatements = new SqlStatement[statements.size()];
        sqlStatements = statements.toArray(sqlStatements);
        generatedSqls = SqlGeneratorFactory.getInstance().generateSql(sqlStatements, database);
    } catch (DatabaseException e) {
        throw new UnexpectedLiquibaseException(e);
    }
    return generatedSqls;
}
Also used : SqlStatement(liquibase.statement.SqlStatement) DatabaseException(liquibase.exception.DatabaseException) UnexpectedLiquibaseException(liquibase.exception.UnexpectedLiquibaseException) Sql(liquibase.sql.Sql)

Aggregations

DatabaseException (liquibase.exception.DatabaseException)139 SQLException (java.sql.SQLException)65 JdbcConnection (liquibase.database.jvm.JdbcConnection)34 PreparedStatement (java.sql.PreparedStatement)33 ResultSet (java.sql.ResultSet)28 Statement (java.sql.Statement)24 Database (liquibase.database.Database)24 UnexpectedLiquibaseException (liquibase.exception.UnexpectedLiquibaseException)24 CustomChangeException (liquibase.exception.CustomChangeException)22 CatalogAndSchema (liquibase.CatalogAndSchema)17 LiquibaseException (liquibase.exception.LiquibaseException)16 AbstractJdbcDatabase (liquibase.database.AbstractJdbcDatabase)14 InvalidExampleException (liquibase.snapshot.InvalidExampleException)14 RawSqlStatement (liquibase.statement.core.RawSqlStatement)14 MSSQLDatabase (liquibase.database.core.MSSQLDatabase)13 CachedRow (liquibase.snapshot.CachedRow)13 SqlStatement (liquibase.statement.SqlStatement)13 DatabaseConnection (liquibase.database.DatabaseConnection)12 JdbcDatabaseSnapshot (liquibase.snapshot.JdbcDatabaseSnapshot)12 ArrayList (java.util.ArrayList)11