Search in sources :

Example 21 with Change

use of liquibase.change.Change in project liquibase by liquibase.

the class ChangedTableChangeGenerator method fixChanged.

@Override
public Change[] fixChanged(DatabaseObject changedObject, ObjectDifferences differences, DiffOutputControl control, Database referenceDatabase, final Database comparisonDatabase, ChangeGeneratorChain chain) {
    Table table = (Table) changedObject;
    Difference changedRemarks = differences.getDifference("remarks");
    if (changedRemarks != null) {
        SetTableRemarksChange change = new SetTableRemarksChange();
        if (control.getIncludeCatalog()) {
            change.setCatalogName(table.getSchema().getCatalogName());
        }
        if (control.getIncludeSchema()) {
            change.setSchemaName(table.getSchema().getName());
        }
        change.setTableName(table.getName());
        change.setRemarks(table.getRemarks());
        return new Change[] { change };
    }
    return null;
}
Also used : Table(liquibase.structure.core.Table) Difference(liquibase.diff.Difference) SetTableRemarksChange(liquibase.change.core.SetTableRemarksChange) Change(liquibase.change.Change) SetTableRemarksChange(liquibase.change.core.SetTableRemarksChange)

Example 22 with Change

use of liquibase.change.Change in project liquibase by liquibase.

the class ChangedViewChangeGenerator method fixChanged.

@Override
public Change[] fixChanged(DatabaseObject changedObject, ObjectDifferences differences, DiffOutputControl control, Database referenceDatabase, final Database comparisonDatabase, ChangeGeneratorChain chain) {
    View view = (View) changedObject;
    CreateViewChange change = createViewChange();
    change.setViewName(view.getName());
    change.setReplaceIfExists(true);
    if (control.getIncludeCatalog()) {
        change.setCatalogName(view.getSchema().getCatalogName());
    }
    if (control.getIncludeSchema()) {
        change.setSchemaName(view.getSchema().getName());
    }
    String selectQuery = view.getDefinition();
    boolean fullDefinitionOverridden = false;
    if (selectQuery == null) {
        selectQuery = "COULD NOT DETERMINE VIEW QUERY";
    } else if (comparisonDatabase instanceof OracleDatabase && view.getColumns() != null && view.getColumns().size() > 0) {
        String viewName;
        if (change.getCatalogName() == null && change.getSchemaName() == null) {
            viewName = comparisonDatabase.escapeObjectName(change.getViewName(), View.class);
        } else {
            viewName = comparisonDatabase.escapeViewName(change.getCatalogName(), change.getSchemaName(), change.getViewName());
        }
        selectQuery = "CREATE OR REPLACE FORCE VIEW " + viewName + " (" + StringUtils.join(view.getColumns(), ", ", new StringUtils.StringUtilsFormatter() {

            @Override
            public String toString(Object obj) {
                if (((Column) obj).getComputed() != null && ((Column) obj).getComputed()) {
                    return ((Column) obj).getName();
                } else {
                    return comparisonDatabase.escapeColumnName(null, null, null, ((Column) obj).getName(), false);
                }
            }
        }) + ") AS " + selectQuery;
        change.setFullDefinition(true);
        fullDefinitionOverridden = true;
    }
    change.setSelectQuery(selectQuery);
    if (!fullDefinitionOverridden) {
        change.setFullDefinition(view.getContainsFullDefinition());
    }
    return new Change[] { change };
}
Also used : OracleDatabase(liquibase.database.core.OracleDatabase) Column(liquibase.structure.core.Column) CreateViewChange(liquibase.change.core.CreateViewChange) DatabaseObject(liquibase.structure.DatabaseObject) Change(liquibase.change.Change) CreateViewChange(liquibase.change.core.CreateViewChange) View(liquibase.structure.core.View)

Example 23 with Change

use of liquibase.change.Change in project liquibase by liquibase.

the class MissingDataChangeGenerator method fixMissing.

@Override
public Change[] fixMissing(DatabaseObject missingObject, DiffOutputControl outputControl, Database referenceDatabase, Database comparisionDatabase, ChangeGeneratorChain chain) {
    Statement stmt = null;
    ResultSet rs = null;
    try {
        Data data = (Data) missingObject;
        Table table = data.getTable();
        if (referenceDatabase.isLiquibaseObject(table)) {
            return null;
        }
        String sql = "SELECT * FROM " + referenceDatabase.escapeTableName(table.getSchema().getCatalogName(), table.getSchema().getName(), table.getName());
        stmt = ((JdbcConnection) referenceDatabase.getConnection()).createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
        stmt.setFetchSize(1000);
        rs = stmt.executeQuery(sql);
        List<String> columnNames = new ArrayList<String>();
        for (int i = 0; i < rs.getMetaData().getColumnCount(); i++) {
            columnNames.add(rs.getMetaData().getColumnName(i + 1));
        }
        List<Change> changes = new ArrayList<Change>();
        while (rs.next()) {
            InsertDataChange change = new InsertDataChange();
            if (outputControl.getIncludeCatalog()) {
                change.setCatalogName(table.getSchema().getCatalogName());
            }
            if (outputControl.getIncludeSchema()) {
                change.setSchemaName(table.getSchema().getName());
            }
            change.setTableName(table.getName());
            // loop over all columns for this row
            for (int i = 0; i < columnNames.size(); i++) {
                ColumnConfig column = new ColumnConfig();
                column.setName(columnNames.get(i));
                Object value = JdbcUtils.getResultSetValue(rs, i + 1);
                if (value == null) {
                    column.setValue(null);
                } else if (value instanceof Number) {
                    column.setValueNumeric((Number) value);
                } else if (value instanceof Boolean) {
                    column.setValueBoolean((Boolean) value);
                } else if (value instanceof Date) {
                    column.setValueDate((Date) value);
                } else if (value instanceof byte[]) {
                    if (referenceDatabase instanceof InformixDatabase) {
                        column.setValue(new String((byte[]) value, LiquibaseConfiguration.getInstance().getConfiguration(GlobalConfiguration.class).getOutputEncoding()));
                    }
                    column.setValueComputed(new DatabaseFunction("UNSUPPORTED FOR DIFF: BINARY DATA"));
                } else {
                    // fall back to simple string
                    column.setValue(value.toString().replace("\\", "\\\\"));
                }
                change.addColumn(column);
            }
            // for each row, add a new change
            // (there will be one group per table)
            changes.add(change);
        }
        return changes.toArray(new Change[changes.size()]);
    } catch (Exception e) {
        throw new UnexpectedLiquibaseException(e);
    } finally {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException ignore) {
            }
        }
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException ignore) {
            }
        }
    }
}
Also used : GlobalConfiguration(liquibase.configuration.GlobalConfiguration) ColumnConfig(liquibase.change.ColumnConfig) DatabaseFunction(liquibase.statement.DatabaseFunction) ArrayList(java.util.ArrayList) InsertDataChange(liquibase.change.core.InsertDataChange) Change(liquibase.change.Change) Date(java.util.Date) UnexpectedLiquibaseException(liquibase.exception.UnexpectedLiquibaseException) InsertDataChange(liquibase.change.core.InsertDataChange) InformixDatabase(liquibase.database.core.InformixDatabase) DatabaseObject(liquibase.structure.DatabaseObject) UnexpectedLiquibaseException(liquibase.exception.UnexpectedLiquibaseException)

Example 24 with Change

use of liquibase.change.Change in project liquibase by liquibase.

the class MissingDataExternalFileChangeGenerator method fixMissing.

@Override
public Change[] fixMissing(DatabaseObject missingObject, DiffOutputControl outputControl, Database referenceDatabase, Database comparisionDatabase, ChangeGeneratorChain chain) {
    Statement stmt = null;
    ResultSet rs = null;
    try {
        Data data = (Data) missingObject;
        Table table = data.getTable();
        if (referenceDatabase.isLiquibaseObject(table)) {
            return null;
        }
        String sql = "SELECT * FROM " + referenceDatabase.escapeTableName(table.getSchema().getCatalogName(), table.getSchema().getName(), table.getName());
        stmt = ((JdbcConnection) referenceDatabase.getConnection()).createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
        stmt.setFetchSize(100);
        rs = stmt.executeQuery(sql);
        List<String> columnNames = new ArrayList<String>();
        for (int i = 0; i < rs.getMetaData().getColumnCount(); i++) {
            columnNames.add(rs.getMetaData().getColumnName(i + 1));
        }
        String fileName = table.getName().toLowerCase() + ".csv";
        if (dataDir != null) {
            fileName = dataDir + "/" + fileName;
            File parentDir = new File(dataDir);
            if (!parentDir.exists()) {
                parentDir.mkdirs();
            }
            if (!parentDir.isDirectory()) {
                throw new RuntimeException(parentDir + " is not a directory");
            }
        }
        CSVWriter outputFile = new CSVWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName), LiquibaseConfiguration.getInstance().getConfiguration(GlobalConfiguration.class).getOutputEncoding())));
        String[] dataTypes = new String[columnNames.size()];
        String[] line = new String[columnNames.size()];
        for (int i = 0; i < columnNames.size(); i++) {
            line[i] = columnNames.get(i);
        }
        outputFile.writeNext(line);
        int rowNum = 0;
        while (rs.next()) {
            line = new String[columnNames.size()];
            for (int i = 0; i < columnNames.size(); i++) {
                Object value = JdbcUtils.getResultSetValue(rs, i + 1);
                if (dataTypes[i] == null && value != null) {
                    if (value instanceof Number) {
                        dataTypes[i] = "NUMERIC";
                    } else if (value instanceof Boolean) {
                        dataTypes[i] = "BOOLEAN";
                    } else if (value instanceof Date) {
                        dataTypes[i] = "DATE";
                    } else {
                        dataTypes[i] = "STRING";
                    }
                }
                if (value == null) {
                    line[i] = "NULL";
                } else {
                    if (value instanceof Date) {
                        line[i] = new ISODateFormat().format(((Date) value));
                    } else {
                        line[i] = value.toString();
                    }
                }
            }
            outputFile.writeNext(line);
            rowNum++;
            if (rowNum % 5000 == 0) {
                outputFile.flush();
            }
        }
        outputFile.flush();
        outputFile.close();
        LoadDataChange change = new LoadDataChange();
        change.setFile(fileName);
        change.setEncoding(LiquibaseConfiguration.getInstance().getConfiguration(GlobalConfiguration.class).getOutputEncoding());
        if (outputControl.getIncludeCatalog()) {
            change.setCatalogName(table.getSchema().getCatalogName());
        }
        if (outputControl.getIncludeSchema()) {
            change.setSchemaName(table.getSchema().getName());
        }
        change.setTableName(table.getName());
        for (int i = 0; i < columnNames.size(); i++) {
            String colName = columnNames.get(i);
            LoadDataColumnConfig columnConfig = new LoadDataColumnConfig();
            columnConfig.setHeader(colName);
            columnConfig.setName(colName);
            columnConfig.setType(dataTypes[i]);
            change.addColumn(columnConfig);
        }
        return new Change[] { change };
    } catch (Exception e) {
        throw new UnexpectedLiquibaseException(e);
    } finally {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException ignore) {
            }
        }
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException ignore) {
            }
        }
    }
}
Also used : SQLException(java.sql.SQLException) ArrayList(java.util.ArrayList) CSVWriter(liquibase.util.csv.CSVWriter) BufferedWriter(java.io.BufferedWriter) ISODateFormat(liquibase.util.ISODateFormat) ResultSet(java.sql.ResultSet) LoadDataColumnConfig(liquibase.change.core.LoadDataColumnConfig) LoadDataChange(liquibase.change.core.LoadDataChange) Table(liquibase.structure.core.Table) Statement(java.sql.Statement) Data(liquibase.structure.core.Data) Change(liquibase.change.Change) LoadDataChange(liquibase.change.core.LoadDataChange) Date(java.util.Date) SQLException(java.sql.SQLException) UnexpectedLiquibaseException(liquibase.exception.UnexpectedLiquibaseException) FileOutputStream(java.io.FileOutputStream) OutputStreamWriter(java.io.OutputStreamWriter) DatabaseObject(liquibase.structure.DatabaseObject) File(java.io.File) UnexpectedLiquibaseException(liquibase.exception.UnexpectedLiquibaseException)

Example 25 with Change

use of liquibase.change.Change in project liquibase by liquibase.

the class MarkChangeSetRanGenerator method generateSql.

@Override
public Sql[] generateSql(MarkChangeSetRanStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
    String dateValue = database.getCurrentDateTimeFunction();
    ChangeSet changeSet = statement.getChangeSet();
    SqlStatement runStatement;
    try {
        if (statement.getExecType().equals(ChangeSet.ExecType.FAILED) || statement.getExecType().equals(ChangeSet.ExecType.SKIPPED)) {
            //don't mark
            return new Sql[0];
        }
        String tag = null;
        for (Change change : changeSet.getChanges()) {
            if (change instanceof TagDatabaseChange) {
                TagDatabaseChange tagChange = (TagDatabaseChange) change;
                tag = tagChange.getTag();
            }
        }
        if (statement.getExecType().ranBefore) {
            runStatement = new UpdateStatement(database.getLiquibaseCatalogName(), database.getLiquibaseSchemaName(), database.getDatabaseChangeLogTableName()).addNewColumnValue("DATEEXECUTED", new DatabaseFunction(dateValue)).addNewColumnValue("ORDEREXECUTED", ChangeLogHistoryServiceFactory.getInstance().getChangeLogService(database).getNextSequenceValue()).addNewColumnValue("MD5SUM", changeSet.generateCheckSum().toString()).addNewColumnValue("EXECTYPE", statement.getExecType().value).addNewColumnValue("DEPLOYMENT_ID", ChangeLogHistoryServiceFactory.getInstance().getChangeLogService(database).getDeploymentId()).setWhereClause(database.escapeObjectName("ID", Column.class) + " = ? " + "AND " + database.escapeObjectName("AUTHOR", Column.class) + " = ? " + "AND " + database.escapeObjectName("FILENAME", Column.class) + " = ?").addWhereParameters(changeSet.getId(), changeSet.getAuthor(), changeSet.getFilePath());
            if (tag != null) {
                ((UpdateStatement) runStatement).addNewColumnValue("TAG", tag);
            }
        } else {
            runStatement = new InsertStatement(database.getLiquibaseCatalogName(), database.getLiquibaseSchemaName(), database.getDatabaseChangeLogTableName()).addColumnValue("ID", changeSet.getId()).addColumnValue("AUTHOR", changeSet.getAuthor()).addColumnValue("FILENAME", changeSet.getFilePath()).addColumnValue("DATEEXECUTED", new DatabaseFunction(dateValue)).addColumnValue("ORDEREXECUTED", ChangeLogHistoryServiceFactory.getInstance().getChangeLogService(database).getNextSequenceValue()).addColumnValue("MD5SUM", changeSet.generateCheckSum().toString()).addColumnValue("DESCRIPTION", limitSize(changeSet.getDescription())).addColumnValue("COMMENTS", limitSize(StringUtils.trimToEmpty(changeSet.getComments()))).addColumnValue("EXECTYPE", statement.getExecType().value).addColumnValue("CONTEXTS", changeSet.getContexts() == null || changeSet.getContexts().isEmpty() ? null : changeSet.getContexts().toString()).addColumnValue("LABELS", changeSet.getLabels() == null || changeSet.getLabels().isEmpty() ? null : changeSet.getLabels().toString()).addColumnValue("LIQUIBASE", LiquibaseUtil.getBuildVersion().replaceAll("SNAPSHOT", "SNP")).addColumnValue("DEPLOYMENT_ID", ChangeLogHistoryServiceFactory.getInstance().getChangeLogService(database).getDeploymentId());
            if (tag != null) {
                ((InsertStatement) runStatement).addColumnValue("TAG", tag);
            }
        }
    } catch (LiquibaseException e) {
        throw new UnexpectedLiquibaseException(e);
    }
    return SqlGeneratorFactory.getInstance().generateSql(runStatement, database);
}
Also used : SqlStatement(liquibase.statement.SqlStatement) UpdateStatement(liquibase.statement.core.UpdateStatement) DatabaseFunction(liquibase.statement.DatabaseFunction) Column(liquibase.structure.core.Column) TagDatabaseChange(liquibase.change.core.TagDatabaseChange) Change(liquibase.change.Change) TagDatabaseChange(liquibase.change.core.TagDatabaseChange) LiquibaseException(liquibase.exception.LiquibaseException) UnexpectedLiquibaseException(liquibase.exception.UnexpectedLiquibaseException) ChangeSet(liquibase.changelog.ChangeSet) UnexpectedLiquibaseException(liquibase.exception.UnexpectedLiquibaseException) InsertStatement(liquibase.statement.core.InsertStatement) Sql(liquibase.sql.Sql)

Aggregations

Change (liquibase.change.Change)44 ArrayList (java.util.ArrayList)9 Column (liquibase.structure.core.Column)9 ChangeSet (liquibase.changelog.ChangeSet)7 DatabaseObject (liquibase.structure.DatabaseObject)7 DbmsTargetedChange (liquibase.change.DbmsTargetedChange)6 EmptyChange (liquibase.change.core.EmptyChange)6 RawSQLChange (liquibase.change.core.RawSQLChange)6 OracleDatabase (liquibase.database.core.OracleDatabase)6 Database (liquibase.database.Database)4 MSSQLDatabase (liquibase.database.core.MSSQLDatabase)4 UnexpectedLiquibaseException (liquibase.exception.UnexpectedLiquibaseException)4 AddColumnConfig (liquibase.change.AddColumnConfig)3 ChangeFactory (liquibase.change.ChangeFactory)3 ChangeMetaData (liquibase.change.ChangeMetaData)3 ChangeParameterMetaData (liquibase.change.ChangeParameterMetaData)3 CreateIndexChange (liquibase.change.core.CreateIndexChange)3 Difference (liquibase.diff.Difference)3 Executor (liquibase.executor.Executor)3 ParsedNodeException (liquibase.parser.core.ParsedNodeException)3