Search in sources :

Example 96 with DatabaseException

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

the class LoggingExecutor method outputStatement.

private void outputStatement(SqlStatement sql, List<SqlVisitor> sqlVisitors) throws DatabaseException {
    try {
        if (SqlGeneratorFactory.getInstance().generateStatementsVolatile(sql, database)) {
            throw new DatabaseException(sql.getClass().getSimpleName() + " requires access to up to date database " + "metadata which is not available in SQL output mode");
        }
        if (sql instanceof ExecutablePreparedStatement) {
            output.write("WARNING: This statement uses a prepared statement which cannot be execute directly " + "by this script. Only works in 'update' mode\n\n");
        }
        for (String statement : applyVisitors(sql, sqlVisitors)) {
            if (statement == null) {
                continue;
            }
            // remove trailing "/"
            if (database instanceof OracleDatabase) {
                // all trailing "/"s
                while (statement.matches("(?s).*[\\s\\r\\n]*/[\\s\\r\\n]*$")) {
                    statement = statement.replaceFirst("[\\s\\r\\n]*/[\\s\\r\\n]*$", "");
                }
            }
            output.write(statement);
            if ((database instanceof MSSQLDatabase) || (database instanceof SybaseDatabase) || (database instanceof SybaseASADatabase)) {
                output.write(StreamUtil.getLineSeparator());
                output.write("GO");
            } else {
                String endDelimiter = ";";
                String potentialDelimiter = null;
                if (sql instanceof RawSqlStatement) {
                    potentialDelimiter = ((RawSqlStatement) sql).getEndDelimiter();
                } else if (sql instanceof CreateProcedureStatement) {
                    potentialDelimiter = ((CreateProcedureStatement) sql).getEndDelimiter();
                }
                if (potentialDelimiter != null) {
                    // ignore trailing $ as a regexp to determine if it should be output
                    potentialDelimiter = potentialDelimiter.replaceFirst("\\$$", "");
                    if (potentialDelimiter.replaceAll("\\n", "\n").replace("\\r", "\r").matches("[;/\r\n\\w@\\-]+")) {
                        endDelimiter = potentialDelimiter;
                    }
                }
                endDelimiter = endDelimiter.replace("\\n", "\n");
                endDelimiter = endDelimiter.replace("\\r", "\r");
                if (!statement.endsWith(endDelimiter)) {
                    output.write(endDelimiter);
                }
            }
            output.write(StreamUtil.getLineSeparator());
            output.write(StreamUtil.getLineSeparator());
        }
    } catch (IOException e) {
        throw new DatabaseException(e);
    }
}
Also used : OracleDatabase(liquibase.database.core.OracleDatabase) SybaseASADatabase(liquibase.database.core.SybaseASADatabase) SybaseDatabase(liquibase.database.core.SybaseDatabase) MSSQLDatabase(liquibase.database.core.MSSQLDatabase) IOException(java.io.IOException) DatabaseException(liquibase.exception.DatabaseException) ExecutablePreparedStatement(liquibase.statement.ExecutablePreparedStatement)

Example 97 with DatabaseException

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

the class LoggingExecutor method comment.

@Override
public void comment(String message) throws DatabaseException {
    try {
        output.write(database.getLineComment());
        output.write(" ");
        output.write(message);
        output.write(StreamUtil.getLineSeparator());
    } catch (IOException e) {
        throw new DatabaseException(e);
    }
}
Also used : IOException(java.io.IOException) DatabaseException(liquibase.exception.DatabaseException)

Example 98 with DatabaseException

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

the class ForeignKeySnapshotGenerator method snapshotObject.

@Override
protected DatabaseObject snapshotObject(DatabaseObject example, DatabaseSnapshot snapshot) throws DatabaseException, InvalidExampleException {
    Database database = snapshot.getDatabase();
    List<CachedRow> importedKeyMetadataResultSet;
    try {
        Table fkTable = ((ForeignKey) example).getForeignKeyTable();
        String searchCatalog = ((AbstractJdbcDatabase) database).getJdbcCatalogName(fkTable.getSchema());
        String searchSchema = ((AbstractJdbcDatabase) database).getJdbcSchemaName(fkTable.getSchema());
        String searchTableName = database.correctObjectName(fkTable.getName(), Table.class);
        importedKeyMetadataResultSet = ((JdbcDatabaseSnapshot) snapshot).getMetaDataFromCache().getForeignKeys(searchCatalog, searchSchema, searchTableName, example.getName());
        ForeignKey foreignKey = null;
        for (CachedRow row : importedKeyMetadataResultSet) {
            String fk_name = cleanNameFromDatabase(row.getString("FK_NAME"), database);
            if (snapshot.getDatabase().isCaseSensitive()) {
                if (!fk_name.equals(example.getName())) {
                    continue;
                } else if (!fk_name.equalsIgnoreCase(example.getName())) {
                    continue;
                }
            }
            if (foreignKey == null) {
                foreignKey = new ForeignKey();
            }
            foreignKey.setName(fk_name);
            String fkTableCatalog = cleanNameFromDatabase(row.getString(METADATA_FKTABLE_CAT), database);
            String fkTableSchema = cleanNameFromDatabase(row.getString(METADATA_FKTABLE_SCHEM), database);
            String fkTableName = cleanNameFromDatabase(row.getString(METADATA_FKTABLE_NAME), database);
            Table foreignKeyTable = new Table().setName(fkTableName);
            foreignKeyTable.setSchema(new Schema(new Catalog(fkTableCatalog), fkTableSchema));
            foreignKey.setForeignKeyTable(foreignKeyTable);
            Column fkColumn = new Column(cleanNameFromDatabase(row.getString(METADATA_FKCOLUMN_NAME), database)).setRelation(foreignKeyTable);
            boolean alreadyAdded = false;
            for (Column existing : foreignKey.getForeignKeyColumns()) {
                if (DatabaseObjectComparatorFactory.getInstance().isSameObject(existing, fkColumn, snapshot.getSchemaComparisons(), database)) {
                    // already added. One is probably an alias
                    alreadyAdded = true;
                }
            }
            if (alreadyAdded) {
                break;
            }
            CatalogAndSchema pkTableSchema = ((AbstractJdbcDatabase) database).getSchemaFromJdbcInfo(row.getString(METADATA_PKTABLE_CAT), row.getString(METADATA_PKTABLE_SCHEM));
            Table tempPkTable = (Table) new Table().setName(row.getString(METADATA_PKTABLE_NAME)).setSchema(new Schema(pkTableSchema.getCatalogName(), pkTableSchema.getSchemaName()));
            foreignKey.setPrimaryKeyTable(tempPkTable);
            Column pkColumn = new Column(cleanNameFromDatabase(row.getString(METADATA_PKCOLUMN_NAME), database)).setRelation(tempPkTable);
            foreignKey.addForeignKeyColumn(fkColumn);
            foreignKey.addPrimaryKeyColumn(pkColumn);
            // DB2 on z/OS doesn't support ON UPDATE
            if (!(database instanceof Db2zDatabase)) {
                ForeignKeyConstraintType updateRule = convertToForeignKeyConstraintType(row.getInt(METADATA_UPDATE_RULE), database);
                foreignKey.setUpdateRule(updateRule);
            }
            ForeignKeyConstraintType deleteRule = convertToForeignKeyConstraintType(row.getInt(METADATA_DELETE_RULE), database);
            foreignKey.setDeleteRule(deleteRule);
            short deferrability = row.getShort(METADATA_DEFERRABILITY);
            // it should be set to DatabaseMetaData.importedKeyNotDeferrable(7)
            if ((deferrability == 0) || (deferrability == DatabaseMetaData.importedKeyNotDeferrable)) {
                foreignKey.setDeferrable(false);
                foreignKey.setInitiallyDeferred(false);
            } else if (deferrability == DatabaseMetaData.importedKeyInitiallyDeferred) {
                foreignKey.setDeferrable(true);
                foreignKey.setInitiallyDeferred(true);
            } else if (deferrability == DatabaseMetaData.importedKeyInitiallyImmediate) {
                foreignKey.setDeferrable(true);
                foreignKey.setInitiallyDeferred(false);
            } else {
                throw new RuntimeException("Unknown deferrability result: " + deferrability);
            }
            setValidateOptionIfAvailable(database, foreignKey, row);
            Index exampleIndex = new Index().setRelation(foreignKey.getForeignKeyTable());
            exampleIndex.getColumns().addAll(foreignKey.getForeignKeyColumns());
            exampleIndex.addAssociatedWith(Index.MARK_FOREIGN_KEY);
            foreignKey.setBackingIndex(exampleIndex);
        }
        if (snapshot.get(ForeignKey.class).contains(foreignKey)) {
            return null;
        }
        return foreignKey;
    } catch (Exception e) {
        throw new DatabaseException(e);
    }
}
Also used : CachedRow(liquibase.snapshot.CachedRow) CatalogAndSchema(liquibase.CatalogAndSchema) CatalogAndSchema(liquibase.CatalogAndSchema) AbstractJdbcDatabase(liquibase.database.AbstractJdbcDatabase) InvalidExampleException(liquibase.snapshot.InvalidExampleException) DatabaseException(liquibase.exception.DatabaseException) SQLException(java.sql.SQLException) Db2zDatabase(liquibase.database.core.Db2zDatabase) DB2Database(liquibase.database.core.DB2Database) Db2zDatabase(liquibase.database.core.Db2zDatabase) MSSQLDatabase(liquibase.database.core.MSSQLDatabase) OracleDatabase(liquibase.database.core.OracleDatabase) Database(liquibase.database.Database) MariaDBDatabase(liquibase.database.core.MariaDBDatabase) MySQLDatabase(liquibase.database.core.MySQLDatabase) AbstractJdbcDatabase(liquibase.database.AbstractJdbcDatabase) JdbcDatabaseSnapshot(liquibase.snapshot.JdbcDatabaseSnapshot) DatabaseException(liquibase.exception.DatabaseException)

Example 99 with DatabaseException

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

the class ForeignKeySnapshotGenerator method addTo.

// public Boolean has(DatabaseObject example, DatabaseSnapshot snapshot, SnapshotGeneratorChain chain) throws DatabaseException {
// if (example instanceof ForeignKey) {
// Database database = snapshot.getDatabase();
// String searchCatalog = database.getJdbcCatalogName(example.getSchema());
// String searchSchema = database.getJdbcSchemaName(example.getSchema());
// String searchTableName = null;
// if (((ForeignKey) example).getForeignKeyTable() != null) {
// searchTableName = ((ForeignKey) example).getForeignKeyTable().getName();
// }
// String fkName = example.getName();
// 
// ResultSet rs = null;
// try {
// rs = getMetaDataFromCache(database).getForeignKeys(searchCatalog, searchSchema, searchTableName);
// while (rs.next()) {
// if (fkName.equals(rs.getString("FK_NAME"))) {
// return true;
// }
// }
// return false;
// } catch (SQLException e) {
// throw new DatabaseException(e);
// } finally {
// if (rs != null) {
// try {
// rs.close();
// } catch (SQLException ignored) { }
// }
// }
// } else {
// return chain.has(example, snapshot);
// }
// }
@Override
protected void addTo(DatabaseObject foundObject, DatabaseSnapshot snapshot) throws DatabaseException, InvalidExampleException {
    if (!snapshot.getSnapshotControl().shouldInclude(ForeignKey.class)) {
        return;
    }
    if (foundObject instanceof Table) {
        Table table = (Table) foundObject;
        Database database = snapshot.getDatabase();
        Schema schema;
        schema = table.getSchema();
        Set<String> seenFks = new HashSet<>();
        List<CachedRow> importedKeyMetadataResultSet;
        try {
            importedKeyMetadataResultSet = ((JdbcDatabaseSnapshot) snapshot).getMetaDataFromCache().getForeignKeys(((AbstractJdbcDatabase) database).getJdbcCatalogName(schema), ((AbstractJdbcDatabase) database).getJdbcSchemaName(schema), database.correctObjectName(table.getName(), Table.class), null);
            for (CachedRow row : importedKeyMetadataResultSet) {
                ForeignKey fk = new ForeignKey().setName(row.getString("FK_NAME")).setForeignKeyTable(table);
                if (seenFks.add(fk.getName())) {
                    table.getOutgoingForeignKeys().add(fk);
                }
            }
        } catch (Exception e) {
            throw new DatabaseException(e);
        }
    }
}
Also used : CachedRow(liquibase.snapshot.CachedRow) CatalogAndSchema(liquibase.CatalogAndSchema) AbstractJdbcDatabase(liquibase.database.AbstractJdbcDatabase) InvalidExampleException(liquibase.snapshot.InvalidExampleException) DatabaseException(liquibase.exception.DatabaseException) SQLException(java.sql.SQLException) DB2Database(liquibase.database.core.DB2Database) Db2zDatabase(liquibase.database.core.Db2zDatabase) MSSQLDatabase(liquibase.database.core.MSSQLDatabase) OracleDatabase(liquibase.database.core.OracleDatabase) Database(liquibase.database.Database) MariaDBDatabase(liquibase.database.core.MariaDBDatabase) MySQLDatabase(liquibase.database.core.MySQLDatabase) AbstractJdbcDatabase(liquibase.database.AbstractJdbcDatabase) JdbcDatabaseSnapshot(liquibase.snapshot.JdbcDatabaseSnapshot) DatabaseException(liquibase.exception.DatabaseException) HashSet(java.util.HashSet)

Example 100 with DatabaseException

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

the class DatabaseSnapshot method getSerializableFieldValue.

@Override
public Object getSerializableFieldValue(String field) {
    switch(field) {
        case "snapshotControl":
            return snapshotControl;
        case "objects":
            return allFound;
        case "referencedObjects":
            return referencedObjects;
        case "metadata":
            return metadata;
        case "created":
            return new ISODateFormat().format(new Timestamp(new Date().getTime()));
        case "database":
            Map<String, Object> map = new HashMap<>();
            map.put("shortName", database.getShortName());
            map.put("productName", database.getDatabaseProductName());
            map.put("url", database.getConnection().getURL());
            try {
                map.put("majorVersion", String.valueOf(database.getDatabaseMajorVersion()));
                map.put("minorVersion", String.valueOf(database.getDatabaseMinorVersion()));
                map.put("productVersion", database.getDatabaseProductVersion());
                map.put("user", database.getConnection().getConnectionUserName());
            } catch (DatabaseException e) {
            // ok
            }
            return map;
        default:
            throw new UnexpectedLiquibaseException("Unknown field: " + field);
    }
}
Also used : ISODateFormat(liquibase.util.ISODateFormat) DatabaseObject(liquibase.structure.DatabaseObject) Timestamp(java.sql.Timestamp) DatabaseException(liquibase.exception.DatabaseException) UnexpectedLiquibaseException(liquibase.exception.UnexpectedLiquibaseException)

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