Search in sources :

Example 1 with DB2Database

use of liquibase.database.core.DB2Database in project liquibase by liquibase.

the class DiffToChangeLog method addDependencies.

/**
     * Adds dependencies to the graph as schema.object_name.
     */
protected void addDependencies(DependencyUtil.DependencyGraph<String> graph, List<String> schemas, Collection<DatabaseObject> missingObjects, Database database) throws DatabaseException {
    if (database instanceof DB2Database) {
        Executor executor = ExecutorService.getInstance().getExecutor(database);
        List<Map<String, ?>> rs = executor.queryForList(new RawSqlStatement("select TABSCHEMA, TABNAME, BSCHEMA, BNAME from syscat.tabdep where (" + StringUtils.join(schemas, " OR ", new StringUtils.StringUtilsFormatter<String>() {

            @Override
            public String toString(String obj) {
                return "TABSCHEMA='" + obj + "'";
            }
        }) + ")"));
        for (Map<String, ?> row : rs) {
            String tabName = StringUtils.trimToNull((String) row.get("TABSCHEMA")) + "." + StringUtils.trimToNull((String) row.get("TABNAME"));
            String bName = StringUtils.trimToNull((String) row.get("BSCHEMA")) + "." + StringUtils.trimToNull((String) row.get("BNAME"));
            graph.add(bName, tabName);
        }
    } else if (database instanceof OracleDatabase) {
        Executor executor = ExecutorService.getInstance().getExecutor(database);
        List<Map<String, ?>> rs = executor.queryForList(new RawSqlStatement("select OWNER, NAME, REFERENCED_OWNER, REFERENCED_NAME from DBA_DEPENDENCIES where REFERENCED_OWNER != 'SYS' AND NOT(NAME LIKE 'BIN$%') AND NOT(OWNER = REFERENCED_OWNER AND NAME = REFERENCED_NAME) AND (" + StringUtils.join(schemas, " OR ", new StringUtils.StringUtilsFormatter<String>() {

            @Override
            public String toString(String obj) {
                return "OWNER='" + obj + "'";
            }
        }) + ")"));
        for (Map<String, ?> row : rs) {
            String tabName = StringUtils.trimToNull((String) row.get("OWNER")) + "." + StringUtils.trimToNull((String) row.get("NAME"));
            String bName = StringUtils.trimToNull((String) row.get("REFERENCED_OWNER")) + "." + StringUtils.trimToNull((String) row.get("REFERENCED_NAME"));
            graph.add(bName, tabName);
        }
    } else if (database instanceof MSSQLDatabase && database.getDatabaseMajorVersion() >= 9) {
        Executor executor = ExecutorService.getInstance().getExecutor(database);
        String sql = "select object_schema_name(referencing_id) as referencing_schema_name, object_name(referencing_id) as referencing_name, object_name(referenced_id) as referenced_name, object_schema_name(referenced_id) as referenced_schema_name  from sys.sql_expression_dependencies depz where (" + StringUtils.join(schemas, " OR ", new StringUtils.StringUtilsFormatter<String>() {

            @Override
            public String toString(String obj) {
                return "object_schema_name(referenced_id)='" + obj + "'";
            }
        }) + ")";
        sql += " UNION select object_schema_name(object_id) as referencing_schema_name, object_name(object_id) as referencing_name, object_name(parent_object_id) as referenced_name, object_schema_name(parent_object_id) as referenced_schema_name " + "from sys.objects " + "where parent_object_id > 0 " + "and is_ms_shipped=0 " + "and (" + StringUtils.join(schemas, " OR ", new StringUtils.StringUtilsFormatter<String>() {

            @Override
            public String toString(String obj) {
                return "object_schema_name(object_id)='" + obj + "'";
            }
        }) + ")";
        sql += " UNION select object_schema_name(fk.object_id) as referencing_schema_name, fk.name as referencing_name, i.name as referenced_name, object_schema_name(i.object_id) as referenced_schema_name " + "from sys.foreign_keys fk " + "join sys.indexes i on fk.referenced_object_id=i.object_id and fk.key_index_id=i.index_id " + "where fk.is_ms_shipped=0 " + "and (" + StringUtils.join(schemas, " OR ", new StringUtils.StringUtilsFormatter<String>() {

            @Override
            public String toString(String obj) {
                return "object_schema_name(fk.object_id)='" + obj + "'";
            }
        }) + ")";
        sql += " UNION select object_schema_name(i.object_id) as referencing_schema_name, object_name(i.object_id) as referencing_name, s.name as referenced_name, null as referenced_schema_name " + "from sys.indexes i " + "join sys.partition_schemes s on i.data_space_id = s.data_space_id";
        sql += " UNION select null as referencing_schema_name, s.name as referencing_name, f.name as referenced_name, null as referenced_schema_name from sys.partition_functions f " + "join sys.partition_schemes s on s.function_id=f.function_id";
        sql += " UNION select null as referencing_schema_name, s.name as referencing_name, fg.name as referenced_name, null as referenced_schema_name from sys.partition_schemes s " + "join sys.destination_data_spaces ds on s.data_space_id=ds.partition_scheme_id " + "join sys.filegroups fg on ds.data_space_id=fg.data_space_id";
        //get data file -> filegroup dependencies
        sql += " UNION select distinct null as referencing_schema_name, f.name as referencing_name, ds.name as referenced_name, null as referenced_schema_name from sys.database_files f " + "join sys.data_spaces ds on f.data_space_id=ds.data_space_id " + "where f.data_space_id > 1";
        //get table -> filestream dependencies
        sql += " UNION select object_schema_name(t.object_id) as referencing_schema_name, t.name as referencing_name, ds.name as referenced_name, null as referenced_schema_name from sys.tables t " + "join sys.data_spaces ds on t.filestream_data_space_id=ds.data_space_id " + "where t.filestream_data_space_id > 1";
        //get table -> filestream dependencies
        sql += " UNION select object_schema_name(t.object_id) as referencing_schema_name, t.name as referencing_name, ds.name as referenced_name, null as referenced_schema_name from sys.tables t " + "join sys.data_spaces ds on t.lob_data_space_id=ds.data_space_id " + "where t.lob_data_space_id > 1";
        //get index -> filegroup dependencies
        sql += " UNION select object_schema_name(i.object_id) as referencing_schema_name, i.name as referencing_name, ds.name as referenced_name, null as referenced_schema_name from sys.indexes i " + "join sys.data_spaces ds on i.data_space_id=ds.data_space_id " + "where i.data_space_id > 1";
        //get index -> table dependencies
        sql += " UNION select object_schema_name(i.object_id) as referencing_schema_name, i.name as referencing_name, object_name(i.object_id) as referenced_name, object_schema_name(i.object_id) as referenced_schema_name from sys.indexes i " + "where " + StringUtils.join(schemas, " OR ", new StringUtils.StringUtilsFormatter<String>() {

            @Override
            public String toString(String obj) {
                return "object_schema_name(i.object_id)='" + obj + "'";
            }
        });
        //get schema -> base object dependencies
        sql += " UNION SELECT SCHEMA_NAME(SCHEMA_ID) as referencing_schema_name, name as referencing_name, PARSENAME(BASE_OBJECT_NAME,1) AS referenced_name, (CASE WHEN PARSENAME(BASE_OBJECT_NAME,2) IS NULL THEN schema_name(schema_id) else PARSENAME(BASE_OBJECT_NAME,2) END) AS referenced_schema_name FROM SYS.SYNONYMS WHERE is_ms_shipped='false' AND " + StringUtils.join(schemas, " OR ", new StringUtils.StringUtilsFormatter<String>() {

            @Override
            public String toString(String obj) {
                return "SCHEMA_NAME(SCHEMA_ID)='" + obj + "'";
            }
        });
        List<Map<String, ?>> rs = executor.queryForList(new RawSqlStatement(sql));
        if (rs.size() > 0) {
            for (Map<String, ?> row : rs) {
                String bName = StringUtils.trimToNull((String) row.get("REFERENCED_SCHEMA_NAME")) + "." + StringUtils.trimToNull((String) row.get("REFERENCED_NAME"));
                String tabName = StringUtils.trimToNull((String) row.get("REFERENCING_SCHEMA_NAME")) + "." + StringUtils.trimToNull((String) row.get("REFERENCING_NAME"));
                if (!bName.equals(tabName)) {
                    graph.add(bName, tabName);
                }
            }
        }
    }
}
Also used : DB2Database(liquibase.database.core.DB2Database) RawSqlStatement(liquibase.statement.core.RawSqlStatement) OracleDatabase(liquibase.database.core.OracleDatabase) Executor(liquibase.executor.Executor) StringUtils(liquibase.util.StringUtils) MSSQLDatabase(liquibase.database.core.MSSQLDatabase)

Example 2 with DB2Database

use of liquibase.database.core.DB2Database in project liquibase by liquibase.

the class DatabaseTestContext method openConnection.

private DatabaseConnection openConnection(final String url) throws Exception {
    if (connectionsAttempted.containsKey(url)) {
        JdbcConnection connection = (JdbcConnection) connectionsByUrl.get(url);
        if (connection == null) {
            return null;
        } else if (connection.getUnderlyingConnection().isClosed()) {
            connectionsByUrl.put(url, openDatabaseConnection(url));
        }
        return connectionsByUrl.get(url);
    }
    connectionsAttempted.put(url, Boolean.TRUE);
    if (System.getProperty(TEST_DATABASES_PROPERTY) != null) {
        boolean shouldTest = false;
        String[] databasesToTest = System.getProperty(TEST_DATABASES_PROPERTY).split("\\s*,\\s*");
        for (String database : databasesToTest) {
            if (url.indexOf(database) >= 0) {
                shouldTest = true;
            }
        }
        if (!shouldTest) {
            System.out.println("test.databases system property forbids testing against " + url);
            return null;
        } else {
            System.out.println("Will be tested against " + url);
        }
    }
    DatabaseConnection connection = openDatabaseConnection(url);
    if (connection == null) {
        return null;
    }
    Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(connection);
    final DatabaseConnection databaseConnection = database.getConnection();
    if (databaseConnection.getAutoCommit()) {
        databaseConnection.setAutoCommit(false);
    }
    try {
        if (url.startsWith("jdbc:hsql")) {
            ((JdbcConnection) databaseConnection).getUnderlyingConnection().createStatement().execute("CREATE SCHEMA " + ALT_SCHEMA + " AUTHORIZATION DBA");
        } else if (url.startsWith("jdbc:sqlserver") || url.startsWith("jdbc:postgresql") || url.startsWith("jdbc:h2")) {
            ((JdbcConnection) databaseConnection).getUnderlyingConnection().createStatement().execute("CREATE SCHEMA " + ALT_SCHEMA);
        }
        if (!databaseConnection.getAutoCommit()) {
            databaseConnection.commit();
        }
    } catch (SQLException e) {
        //schema already exists
        ;
    } finally {
        try {
            databaseConnection.rollback();
        } catch (DatabaseException e) {
            if (database instanceof DB2Database) {
            //                    expected, there is a problem with it
            } else {
                throw e;
            }
        }
    }
    connectionsByUrl.put(url, databaseConnection);
    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                try {
                    if (!((JdbcConnection) databaseConnection).getUnderlyingConnection().getAutoCommit()) {
                        ((JdbcConnection) databaseConnection).getUnderlyingConnection().rollback();
                    }
                } catch (SQLException e) {
                    ;
                }
                ((JdbcConnection) databaseConnection).getUnderlyingConnection().close();
            } catch (SQLException e) {
                System.out.println("Could not close " + url);
                e.printStackTrace();
            }
        }
    }));
    return databaseConnection;
}
Also used : DB2Database(liquibase.database.core.DB2Database) SQLException(java.sql.SQLException) SQLiteDatabase(liquibase.database.core.SQLiteDatabase) DB2Database(liquibase.database.core.DB2Database) MockDatabase(liquibase.sdk.database.MockDatabase) ExampleCustomDatabase(liquibase.database.example.ExampleCustomDatabase) JdbcConnection(liquibase.database.jvm.JdbcConnection) DatabaseException(liquibase.exception.DatabaseException)

Example 3 with DB2Database

use of liquibase.database.core.DB2Database in project liquibase by liquibase.

the class DropColumnChange method generateSingleColumn.

private SqlStatement[] generateSingleColumn(Database database) throws DatabaseException {
    if (database instanceof SQLiteDatabase) {
        // return special statements for SQLite databases
        return generateStatementsForSQLiteDatabase(database);
    }
    List<SqlStatement> statements = new ArrayList<>();
    statements.add(new DropColumnStatement(getCatalogName(), getSchemaName(), getTableName(), getColumnName()));
    if (database instanceof DB2Database) {
        statements.add(new ReorganizeTableStatement(getCatalogName(), getSchemaName(), getTableName()));
    }
    return statements.toArray(new SqlStatement[statements.size()]);
}
Also used : DB2Database(liquibase.database.core.DB2Database) SqlStatement(liquibase.statement.SqlStatement) SQLiteDatabase(liquibase.database.core.SQLiteDatabase) ReorganizeTableStatement(liquibase.statement.core.ReorganizeTableStatement) ArrayList(java.util.ArrayList) DropColumnStatement(liquibase.statement.core.DropColumnStatement)

Example 4 with DB2Database

use of liquibase.database.core.DB2Database in project liquibase by liquibase.

the class RenameTableChange method generateStatements.

@Override
public SqlStatement[] generateStatements(Database database) {
    List<SqlStatement> statements = new ArrayList<>();
    statements.add(new RenameTableStatement(getCatalogName(), getSchemaName(), getOldTableName(), getNewTableName()));
    if (database instanceof DB2Database) {
        statements.add(new ReorganizeTableStatement(getCatalogName(), getSchemaName(), getNewTableName()));
    }
    return statements.toArray(new SqlStatement[statements.size()]);
}
Also used : DB2Database(liquibase.database.core.DB2Database) SqlStatement(liquibase.statement.SqlStatement) ReorganizeTableStatement(liquibase.statement.core.ReorganizeTableStatement) ArrayList(java.util.ArrayList) RenameTableStatement(liquibase.statement.core.RenameTableStatement)

Example 5 with DB2Database

use of liquibase.database.core.DB2Database in project liquibase by liquibase.

the class AddNotNullConstraintChange method generateStatements.

@Override
public SqlStatement[] generateStatements(Database database) {
    List<SqlStatement> statements = new ArrayList<>();
    if (defaultNullValue != null && !defaultNullValue.equalsIgnoreCase("null")) {
        final String columnDataType = this.getColumnDataType();
        Object finalDefaultNullValue = defaultNullValue;
        if (columnDataType != null) {
            final LiquibaseDataType datatype = DataTypeFactory.getInstance().fromDescription(columnDataType, database);
            if (datatype instanceof BooleanType) {
                // need to detect a boolean or bit type and handle it correctly sometimes or it is not converted to the correct datatype
                finalDefaultNullValue = datatype.objectToSql(finalDefaultNullValue, database);
                if (finalDefaultNullValue.equals("0")) {
                    finalDefaultNullValue = 0;
                } else if (finalDefaultNullValue.equals("1")) {
                    finalDefaultNullValue = 1;
                }
                if (columnDataType.toLowerCase().contains("bit")) {
                    if (BooleanUtil.parseBoolean(finalDefaultNullValue.toString())) {
                        finalDefaultNullValue = 1;
                    } else {
                        finalDefaultNullValue = 0;
                    }
                }
                if (database instanceof PostgresDatabase) {
                    if (finalDefaultNullValue.equals(0)) {
                        finalDefaultNullValue = new DatabaseFunction("B'0'");
                    } else if (finalDefaultNullValue.equals(1)) {
                        finalDefaultNullValue = new DatabaseFunction("B'1'");
                    }
                }
            }
        }
        statements.add(new UpdateStatement(getCatalogName(), getSchemaName(), getTableName()).addNewColumnValue(getColumnName(), finalDefaultNullValue).setWhereClause(database.escapeObjectName(getColumnName(), Column.class) + " IS NULL"));
    }
    statements.add(new SetNullableStatement(getCatalogName(), getSchemaName(), getTableName(), getColumnName(), getColumnDataType(), false, getConstraintName(), shouldValidate));
    if (database instanceof DB2Database) {
        statements.add(new ReorganizeTableStatement(getCatalogName(), getSchemaName(), getTableName()));
    }
    return statements.toArray(new SqlStatement[statements.size()]);
}
Also used : DB2Database(liquibase.database.core.DB2Database) UpdateStatement(liquibase.statement.core.UpdateStatement) DatabaseFunction(liquibase.statement.DatabaseFunction) ReorganizeTableStatement(liquibase.statement.core.ReorganizeTableStatement) LiquibaseDataType(liquibase.datatype.LiquibaseDataType) ArrayList(java.util.ArrayList) BooleanType(liquibase.datatype.core.BooleanType) SqlStatement(liquibase.statement.SqlStatement) PostgresDatabase(liquibase.database.core.PostgresDatabase) SetNullableStatement(liquibase.statement.core.SetNullableStatement) Column(liquibase.structure.core.Column)

Aggregations

DB2Database (liquibase.database.core.DB2Database)12 SqlStatement (liquibase.statement.SqlStatement)9 ReorganizeTableStatement (liquibase.statement.core.ReorganizeTableStatement)8 ArrayList (java.util.ArrayList)6 SQLiteDatabase (liquibase.database.core.SQLiteDatabase)5 MSSQLDatabase (liquibase.database.core.MSSQLDatabase)3 DatabaseException (liquibase.exception.DatabaseException)3 Executor (liquibase.executor.Executor)3 DropColumnStatement (liquibase.statement.core.DropColumnStatement)3 SQLException (java.sql.SQLException)2 OracleDatabase (liquibase.database.core.OracleDatabase)2 LiquibaseException (liquibase.exception.LiquibaseException)2 UnexpectedLiquibaseException (liquibase.exception.UnexpectedLiquibaseException)2 ExecutorService (liquibase.executor.ExecutorService)2 RawSqlStatement (liquibase.statement.core.RawSqlStatement)2 Column (liquibase.structure.core.Column)2 ColumnConfig (liquibase.change.ColumnConfig)1 AddColumnChange (liquibase.change.core.AddColumnChange)1 Database (liquibase.database.Database)1 Db2zDatabase (liquibase.database.core.Db2zDatabase)1