Search in sources :

Example 16 with UnexpectedLiquibaseException

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

the class ChangeParameterMetaData method setValue.

/**
     * Sets the value of this parameter on the given change.
     */
public void setValue(Change change, Object value) {
    if (value instanceof String && !dataType.equals("string")) {
        try {
            if (dataType.equals("bigInteger")) {
                value = new BigInteger((String) value);
            } else if (dataType.equals("databaseFunction")) {
                value = new DatabaseFunction((String) value);
            } else {
                throw new UnexpectedLiquibaseException("Unknown Data Type: " + dataType);
            }
        } catch (Throwable e) {
            throw new UnexpectedLiquibaseException("Cannot convert string value '" + value + "' to " + dataType + ": " + e.getMessage());
        }
    }
    try {
        for (PropertyDescriptor descriptor : PropertyUtils.getInstance().getDescriptors(change.getClass())) {
            if (descriptor.getDisplayName().equals(this.parameterName)) {
                Method writeMethod = descriptor.getWriteMethod();
                if (writeMethod == null) {
                    throw new UnexpectedLiquibaseException("Could not find writeMethod for " + this.parameterName);
                }
                Class<?> expectedWriteType = writeMethod.getParameterTypes()[0];
                if (value != null && !expectedWriteType.isAssignableFrom(value.getClass())) {
                    if (expectedWriteType.equals(String.class)) {
                        value = value.toString();
                    } else {
                        throw new UnexpectedLiquibaseException("Could not convert " + value.getClass().getName() + " to " + expectedWriteType.getName());
                    }
                }
                writeMethod.invoke(change, value);
            }
        }
    } catch (Exception e) {
        throw new UnexpectedLiquibaseException("Error setting " + this.parameterName + " to " + value, e);
    }
}
Also used : DatabaseFunction(liquibase.statement.DatabaseFunction) PropertyDescriptor(java.beans.PropertyDescriptor) BigInteger(java.math.BigInteger) Method(java.lang.reflect.Method) UnexpectedLiquibaseException(liquibase.exception.UnexpectedLiquibaseException) UnexpectedLiquibaseException(liquibase.exception.UnexpectedLiquibaseException)

Example 17 with UnexpectedLiquibaseException

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

the class Liquibase method generateChangeLog.

public void generateChangeLog(CatalogAndSchema catalogAndSchema, DiffToChangeLog changeLogWriter, PrintStream outputStream, ChangeLogSerializer changeLogSerializer, Class<? extends DatabaseObject>... snapshotTypes) throws DatabaseException, IOException, ParserConfigurationException {
    Set<Class<? extends DatabaseObject>> finalCompareTypes = null;
    if (snapshotTypes != null && snapshotTypes.length > 0) {
        finalCompareTypes = new HashSet<Class<? extends DatabaseObject>>(Arrays.asList(snapshotTypes));
    }
    SnapshotControl snapshotControl = new SnapshotControl(this.getDatabase(), snapshotTypes);
    CompareControl compareControl = new CompareControl(new CompareControl.SchemaComparison[] { new CompareControl.SchemaComparison(catalogAndSchema, catalogAndSchema) }, finalCompareTypes);
    //        compareControl.addStatusListener(new OutDiffStatusListener());
    DatabaseSnapshot originalDatabaseSnapshot = null;
    try {
        originalDatabaseSnapshot = SnapshotGeneratorFactory.getInstance().createSnapshot(compareControl.getSchemas(CompareControl.DatabaseRole.REFERENCE), getDatabase(), snapshotControl);
        DiffResult diffResult = DiffGeneratorFactory.getInstance().compare(originalDatabaseSnapshot, SnapshotGeneratorFactory.getInstance().createSnapshot(compareControl.getSchemas(CompareControl.DatabaseRole.REFERENCE), null, snapshotControl), compareControl);
        changeLogWriter.setDiffResult(diffResult);
        if (changeLogSerializer != null) {
            changeLogWriter.print(outputStream, changeLogSerializer);
        } else {
            changeLogWriter.print(outputStream);
        }
    } catch (InvalidExampleException e) {
        throw new UnexpectedLiquibaseException(e);
    }
}
Also used : InvalidExampleException(liquibase.snapshot.InvalidExampleException) DatabaseObject(liquibase.structure.DatabaseObject) CompareControl(liquibase.diff.compare.CompareControl) DiffResult(liquibase.diff.DiffResult) SnapshotControl(liquibase.snapshot.SnapshotControl) DatabaseSnapshot(liquibase.snapshot.DatabaseSnapshot) UnexpectedLiquibaseException(liquibase.exception.UnexpectedLiquibaseException)

Example 18 with UnexpectedLiquibaseException

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

the class DiffGeneratorFactory method compare.

public DiffResult compare(DatabaseSnapshot referenceSnapshot, DatabaseSnapshot comparisonSnapshot, CompareControl compareControl) throws DatabaseException {
    Database referenceDatabase = referenceSnapshot.getDatabase();
    Database comparisonDatabase;
    if (comparisonSnapshot == null) {
        comparisonDatabase = referenceSnapshot.getDatabase();
        try {
            comparisonSnapshot = new EmptyDatabaseSnapshot(referenceDatabase, referenceSnapshot.getSnapshotControl());
        } catch (InvalidExampleException e) {
            throw new UnexpectedLiquibaseException(e);
        }
    } else {
        comparisonDatabase = comparisonSnapshot.getDatabase();
    }
    return getGenerator(referenceDatabase, comparisonDatabase).compare(referenceSnapshot, comparisonSnapshot, compareControl);
}
Also used : Database(liquibase.database.Database) UnexpectedLiquibaseException(liquibase.exception.UnexpectedLiquibaseException)

Example 19 with UnexpectedLiquibaseException

use of liquibase.exception.UnexpectedLiquibaseException 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 20 with UnexpectedLiquibaseException

use of liquibase.exception.UnexpectedLiquibaseException 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)

Aggregations

UnexpectedLiquibaseException (liquibase.exception.UnexpectedLiquibaseException)75 DatabaseException (liquibase.exception.DatabaseException)12 IOException (java.io.IOException)10 Database (liquibase.database.Database)10 DatabaseObject (liquibase.structure.DatabaseObject)10 LiquibaseException (liquibase.exception.LiquibaseException)9 InvalidExampleException (liquibase.snapshot.InvalidExampleException)9 CatalogAndSchema (liquibase.CatalogAndSchema)8 InputStream (java.io.InputStream)7 ParsedNodeException (liquibase.parser.core.ParsedNodeException)7 SQLException (java.sql.SQLException)6 DatabaseFunction (liquibase.statement.DatabaseFunction)6 SqlStatement (liquibase.statement.SqlStatement)6 ArrayList (java.util.ArrayList)5 Matcher (java.util.regex.Matcher)5 Change (liquibase.change.Change)5 ColumnConfig (liquibase.change.ColumnConfig)5 Executor (liquibase.executor.Executor)5 Sql (liquibase.sql.Sql)5 InvocationTargetException (java.lang.reflect.InvocationTargetException)4