Search in sources :

Example 6 with CatalogAndSchema

use of liquibase.CatalogAndSchema in project liquibase by liquibase.

the class PrimaryKeySnapshotGenerator method snapshotObject.

@Override
protected DatabaseObject snapshotObject(DatabaseObject example, DatabaseSnapshot snapshot) throws DatabaseException, InvalidExampleException {
    Database database = snapshot.getDatabase();
    Schema schema = example.getSchema();
    String searchTableName = null;
    if (((PrimaryKey) example).getTable() != null) {
        searchTableName = ((PrimaryKey) example).getTable().getName();
        searchTableName = database.correctObjectName(searchTableName, Table.class);
    }
    List<CachedRow> rs = null;
    try {
        JdbcDatabaseSnapshot.CachingDatabaseMetaData metaData = ((JdbcDatabaseSnapshot) snapshot).getMetaData();
        rs = metaData.getPrimaryKeys(((AbstractJdbcDatabase) database).getJdbcCatalogName(schema), ((AbstractJdbcDatabase) database).getJdbcSchemaName(schema), searchTableName);
        PrimaryKey returnKey = null;
        for (CachedRow row : rs) {
            if (example.getName() != null && !example.getName().equalsIgnoreCase(row.getString("PK_NAME"))) {
                continue;
            }
            String columnName = cleanNameFromDatabase(row.getString("COLUMN_NAME"), database);
            short position = row.getShort("KEY_SEQ");
            if (returnKey == null) {
                returnKey = new PrimaryKey();
                CatalogAndSchema tableSchema = ((AbstractJdbcDatabase) database).getSchemaFromJdbcInfo(row.getString("TABLE_CAT"), row.getString("TABLE_SCHEM"));
                returnKey.setTable((Table) new Table().setName(row.getString("TABLE_NAME")).setSchema(new Schema(tableSchema.getCatalogName(), tableSchema.getSchemaName())));
                returnKey.setName(row.getString("PK_NAME"));
            }
            if (database instanceof SQLiteDatabase) {
                //SQLite is zero based position?
                position = (short) (position + 1);
            }
            String ascOrDesc = row.getString("ASC_OR_DESC");
            Boolean descending = "D".equals(ascOrDesc) ? Boolean.TRUE : "A".equals(ascOrDesc) ? Boolean.FALSE : null;
            returnKey.addColumn(position - 1, new Column(columnName).setDescending(descending).setRelation(((PrimaryKey) example).getTable()));
        }
        if (returnKey != null) {
            Index exampleIndex = new Index().setTable(returnKey.getTable());
            exampleIndex.setColumns(returnKey.getColumns());
            returnKey.setBackingIndex(exampleIndex);
        }
        return returnKey;
    } catch (SQLException e) {
        throw new DatabaseException(e);
    }
}
Also used : CachedRow(liquibase.snapshot.CachedRow) SQLException(java.sql.SQLException) CatalogAndSchema(liquibase.CatalogAndSchema) CatalogAndSchema(liquibase.CatalogAndSchema) AbstractJdbcDatabase(liquibase.database.AbstractJdbcDatabase) SQLiteDatabase(liquibase.database.core.SQLiteDatabase) SQLiteDatabase(liquibase.database.core.SQLiteDatabase) MSSQLDatabase(liquibase.database.core.MSSQLDatabase) Database(liquibase.database.Database) AbstractJdbcDatabase(liquibase.database.AbstractJdbcDatabase) JdbcDatabaseSnapshot(liquibase.snapshot.JdbcDatabaseSnapshot) DatabaseException(liquibase.exception.DatabaseException)

Example 7 with CatalogAndSchema

use of liquibase.CatalogAndSchema in project liquibase by liquibase.

the class SchemaSnapshotGenerator method snapshotObject.

@Override
protected DatabaseObject snapshotObject(DatabaseObject example, DatabaseSnapshot snapshot) throws DatabaseException, InvalidExampleException {
    Database database = snapshot.getDatabase();
    Schema match = null;
    String catalogName = ((Schema) example).getCatalogName();
    String schemaName = example.getName();
    if (database.supportsSchemas()) {
        if (catalogName == null) {
            catalogName = database.getDefaultCatalogName();
        }
        if (schemaName == null) {
            schemaName = database.getDefaultSchemaName();
        }
    } else {
        if (database.supportsCatalogs()) {
            if (catalogName == null && schemaName != null) {
                catalogName = schemaName;
                schemaName = null;
            }
        } else {
            catalogName = null;
            schemaName = null;
        }
    }
    example = new Schema(catalogName, schemaName);
    // use LEGACY quoting since we're dealing with system objects
    ObjectQuotingStrategy currentStrategy = database.getObjectQuotingStrategy();
    database.setObjectQuotingStrategy(ObjectQuotingStrategy.LEGACY);
    try {
        if (database.supportsSchemas()) {
            for (String tableSchema : getDatabaseSchemaNames(database)) {
                CatalogAndSchema schemaFromJdbcInfo = toCatalogAndSchema(tableSchema, database);
                Catalog catalog = new Catalog(schemaFromJdbcInfo.getCatalogName());
                Schema schema = new Schema(catalog, tableSchema);
                if (DatabaseObjectComparatorFactory.getInstance().isSameObject(schema, example, snapshot.getSchemaComparisons(), database)) {
                    if (match == null) {
                        match = schema;
                    } else {
                        throw new InvalidExampleException("Found multiple catalog/schemas matching " + ((Schema) example).getCatalogName() + "." + example.getName());
                    }
                }
            }
        } else {
            Catalog catalog = new Catalog(catalogName);
            match = new Schema(catalog, catalogName);
        }
    } catch (SQLException e) {
        throw new DatabaseException(e);
    } finally {
        database.setObjectQuotingStrategy(currentStrategy);
    }
    if (match != null && (match.getName() == null || match.getName().equalsIgnoreCase(database.getDefaultSchemaName()))) {
        match.setDefault(true);
    }
    return match;
}
Also used : InvalidExampleException(liquibase.snapshot.InvalidExampleException) SQLException(java.sql.SQLException) Schema(liquibase.structure.core.Schema) CatalogAndSchema(liquibase.CatalogAndSchema) Database(liquibase.database.Database) AbstractJdbcDatabase(liquibase.database.AbstractJdbcDatabase) CatalogAndSchema(liquibase.CatalogAndSchema) DatabaseException(liquibase.exception.DatabaseException) ObjectQuotingStrategy(liquibase.database.ObjectQuotingStrategy) Catalog(liquibase.structure.core.Catalog)

Example 8 with CatalogAndSchema

use of liquibase.CatalogAndSchema in project liquibase by liquibase.

the class TableSnapshotGenerator method readTable.

protected Table readTable(CachedRow tableMetadataResultSet, Database database) throws SQLException, DatabaseException {
    String rawTableName = tableMetadataResultSet.getString("TABLE_NAME");
    String rawSchemaName = StringUtils.trimToNull(tableMetadataResultSet.getString("TABLE_SCHEM"));
    String rawCatalogName = StringUtils.trimToNull(tableMetadataResultSet.getString("TABLE_CAT"));
    String remarks = StringUtils.trimToNull(tableMetadataResultSet.getString("REMARKS"));
    if (remarks != null) {
        //come back escaped sometimes
        remarks = remarks.replace("''", "'");
    }
    Table table = new Table().setName(cleanNameFromDatabase(rawTableName, database));
    table.setRemarks(remarks);
    CatalogAndSchema schemaFromJdbcInfo = ((AbstractJdbcDatabase) database).getSchemaFromJdbcInfo(rawCatalogName, rawSchemaName);
    table.setSchema(new Schema(schemaFromJdbcInfo.getCatalogName(), schemaFromJdbcInfo.getSchemaName()));
    if ("Y".equals(tableMetadataResultSet.getString("TEMPORARY"))) {
        table.setAttribute("temporary", "GLOBAL");
        String duration = tableMetadataResultSet.getString("DURATION");
        if (duration != null && duration.equals("SYS$TRANSACTION")) {
            table.setAttribute("duration", "ON COMMIT DELETE ROWS");
        } else if (duration != null && duration.equals("SYS$SESSION")) {
            table.setAttribute("duration", "ON COMMIT PRESERVE ROWS");
        }
    }
    return table;
}
Also used : CatalogAndSchema(liquibase.CatalogAndSchema) CatalogAndSchema(liquibase.CatalogAndSchema) AbstractJdbcDatabase(liquibase.database.AbstractJdbcDatabase)

Example 9 with CatalogAndSchema

use of liquibase.CatalogAndSchema in project liquibase by liquibase.

the class CreateViewGenerator method generateSql.

@Override
public Sql[] generateSql(CreateViewStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
    if (database instanceof InformixDatabase) {
        return new CreateViewGeneratorInformix().generateSql(statement, database, sqlGeneratorChain);
    }
    List<Sql> sql = new ArrayList<Sql>();
    StringClauses viewDefinition = SqlParser.parse(statement.getSelectQuery(), true, true);
    if (!statement.isFullDefinition()) {
        viewDefinition.prepend(" ").prepend("AS").prepend(" ").prepend(database.escapeViewName(statement.getCatalogName(), statement.getSchemaName(), statement.getViewName())).prepend(" ").prepend("VIEW").prepend(" ").prepend("CREATE");
    }
    if (statement.isReplaceIfExists()) {
        if (database instanceof FirebirdDatabase) {
            viewDefinition.replaceIfExists("CREATE", "RECREATE");
        } else if (database instanceof SybaseASADatabase && statement.getSelectQuery().toLowerCase().startsWith("create view")) {
        // Sybase ASA saves view definitions with header.
        } else if (database instanceof MSSQLDatabase) {
            //from http://stackoverflow.com/questions/163246/sql-server-equivalent-to-oracles-create-or-replace-view
            CatalogAndSchema schema = new CatalogAndSchema(statement.getCatalogName(), statement.getSchemaName()).customize(database);
            sql.add(new UnparsedSql("IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[" + schema.getSchemaName() + "].[" + statement.getViewName() + "]'))\n" + "    EXEC sp_executesql N'CREATE VIEW [" + schema.getSchemaName() + "].[" + statement.getViewName() + "] AS SELECT ''This is a code stub which will be replaced by an Alter Statement'' as [code_stub]'"));
            viewDefinition.replaceIfExists("CREATE", "ALTER");
        } else if (database instanceof PostgresDatabase) {
            sql.add(new UnparsedSql("DROP VIEW IF EXISTS " + database.escapeViewName(statement.getCatalogName(), statement.getSchemaName(), statement.getViewName())));
        } else {
            if (!viewDefinition.contains("replace")) {
                viewDefinition.replace("CREATE", "CREATE OR REPLACE");
            }
        }
    }
    sql.add(new UnparsedSql(viewDefinition.toString(), getAffectedView(statement)));
    return sql.toArray(new Sql[sql.size()]);
}
Also used : UnparsedSql(liquibase.sql.UnparsedSql) ArrayList(java.util.ArrayList) CatalogAndSchema(liquibase.CatalogAndSchema) Sql(liquibase.sql.Sql) UnparsedSql(liquibase.sql.UnparsedSql) StringClauses(liquibase.util.StringClauses)

Example 10 with CatalogAndSchema

use of liquibase.CatalogAndSchema in project liquibase by liquibase.

the class FindForeignKeyConstraintsGeneratorOracle method generateSql.

@Override
public Sql[] generateSql(FindForeignKeyConstraintsStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
    CatalogAndSchema baseTableSchema = new CatalogAndSchema(statement.getBaseTableCatalogName(), statement.getBaseTableSchemaName()).customize(database);
    StringBuilder sb = new StringBuilder();
    sb.append("SELECT ");
    sb.append("BASE.TABLE_NAME as ").append(FindForeignKeyConstraintsStatement.RESULT_COLUMN_BASE_TABLE_NAME).append(", ");
    sb.append("BCOLS.COLUMN_NAME as ").append(FindForeignKeyConstraintsStatement.RESULT_COLUMN_BASE_TABLE_COLUMN_NAME).append(", ");
    sb.append("FRGN.TABLE_NAME ").append(FindForeignKeyConstraintsStatement.RESULT_COLUMN_FOREIGN_TABLE_NAME).append(", ");
    sb.append("FCOLS.COLUMN_NAME as ").append(FindForeignKeyConstraintsStatement.RESULT_COLUMN_FOREIGN_COLUMN_NAME).append(", ");
    sb.append("BASE.CONSTRAINT_NAME as ").append(FindForeignKeyConstraintsStatement.RESULT_COLUMN_CONSTRAINT_NAME).append(" ");
    sb.append("FROM ALL_CONSTRAINTS BASE,");
    sb.append("     ALL_CONSTRAINTS FRGN,");
    sb.append("     ALL_CONS_COLUMNS BCOLS,");
    sb.append("     ALL_CONS_COLUMNS FCOLS ");
    sb.append("WHERE BASE.R_OWNER = FRGN.OWNER ");
    sb.append("AND BASE.R_CONSTRAINT_NAME = FRGN.CONSTRAINT_NAME ");
    sb.append("AND BASE.OWNER = BCOLS.OWNER ");
    sb.append("AND BASE.CONSTRAINT_NAME = BCOLS.CONSTRAINT_NAME ");
    sb.append("AND FRGN.OWNER = FCOLS.OWNER ");
    sb.append("AND FRGN.CONSTRAINT_NAME = FCOLS.CONSTRAINT_NAME ");
    sb.append("AND BASE.TABLE_NAME =  '").append(statement.getBaseTableName().toUpperCase()).append("' ");
    sb.append("AND BASE.CONSTRAINT_TYPE = 'R' ");
    sb.append("AND BASE.OWNER = '").append(baseTableSchema.getSchemaName()).append("'");
    return new Sql[] { new UnparsedSql(sb.toString()) };
}
Also used : UnparsedSql(liquibase.sql.UnparsedSql) CatalogAndSchema(liquibase.CatalogAndSchema) UnparsedSql(liquibase.sql.UnparsedSql) Sql(liquibase.sql.Sql)

Aggregations

CatalogAndSchema (liquibase.CatalogAndSchema)36 Database (liquibase.database.Database)9 DatabaseException (liquibase.exception.DatabaseException)9 CompareControl (liquibase.diff.compare.CompareControl)8 UnexpectedLiquibaseException (liquibase.exception.UnexpectedLiquibaseException)7 Sql (liquibase.sql.Sql)7 UnparsedSql (liquibase.sql.UnparsedSql)7 Liquibase (liquibase.Liquibase)5 AbstractJdbcDatabase (liquibase.database.AbstractJdbcDatabase)5 InvalidExampleException (liquibase.snapshot.InvalidExampleException)5 SQLException (java.sql.SQLException)4 ArrayList (java.util.ArrayList)4 ObjectQuotingStrategy (liquibase.database.ObjectQuotingStrategy)4 MSSQLDatabase (liquibase.database.core.MSSQLDatabase)4 DiffOutputControl (liquibase.diff.output.DiffOutputControl)4 LiquibaseException (liquibase.exception.LiquibaseException)4 LockService (liquibase.lockservice.LockService)3 SnapshotControl (liquibase.snapshot.SnapshotControl)3 Schema (liquibase.structure.core.Schema)3 IOException (java.io.IOException)2