Search in sources :

Example 61 with UnexpectedLiquibaseException

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

the class StringChangeLogSerializer method serializeObject.

private String serializeObject(LiquibaseSerializable objectToSerialize, int indent) {
    try {
        StringBuffer buffer = new StringBuffer();
        buffer.append("[");
        SortedSet<String> values = new TreeSet<String>();
        for (String field : objectToSerialize.getSerializableFields()) {
            Object value = objectToSerialize.getSerializableFieldValue(field);
            if (value == null) {
                continue;
            }
            if (!fieldFilter.include(objectToSerialize, field, value)) {
                continue;
            }
            if (value instanceof LiquibaseSerializable) {
                values.add(indent(indent) + serializeObject((LiquibaseSerializable) value, indent + 1));
            } else {
                if (value != null) {
                    if (value instanceof Map) {
                        values.add(indent(indent) + field + "=" + serializeObject((Map) value, indent + 1));
                    } else if (value instanceof Collection) {
                        values.add(indent(indent) + field + "=" + serializeObject((Collection) value, indent + 1));
                    } else if (value instanceof Object[]) {
                        values.add(indent(indent) + field + "=" + serializeObject((Object[]) value, indent + 1));
                    } else {
                        String valueString = value.toString();
                        if (value instanceof Double || value instanceof Float) {
                            //java 6 adds additional zeros to the end of doubles and floats
                            if (valueString.contains(".")) {
                                valueString = valueString.replaceFirst("(\\.[0-9]+)0+$", "$1");
                                valueString = valueString.replaceFirst("\\.0+$", "");
                            }
                        }
                        values.add(indent(indent) + field + "=\"" + valueString + "\"");
                    }
                }
            }
        }
        if (values.size() > 0) {
            buffer.append("\n");
            buffer.append(StringUtils.join(values, "\n"));
            buffer.append("\n");
        }
        buffer.append(indent(indent - 1)).append("]");
        //standardize all newline chars
        return buffer.toString().replace("\r\n", "\n").replace("\r", "\n");
    } catch (Exception e) {
        throw new UnexpectedLiquibaseException(e);
    }
}
Also used : LiquibaseSerializable(liquibase.serializer.LiquibaseSerializable) UnexpectedLiquibaseException(liquibase.exception.UnexpectedLiquibaseException) UnexpectedLiquibaseException(liquibase.exception.UnexpectedLiquibaseException)

Example 62 with UnexpectedLiquibaseException

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

the class StringSnapshotSerializerReadable method serialize.

@Override
public String serialize(LiquibaseSerializable object, boolean pretty) {
    try {
        StringBuilder buffer = new StringBuilder();
        DatabaseSnapshot snapshot = ((DatabaseSnapshot) object);
        Database database = snapshot.getDatabase();
        buffer.append("Database snapshot for ").append(database.getConnection().getURL()).append("\n");
        addDivider(buffer);
        buffer.append("Database type: ").append(database.getDatabaseProductName()).append("\n");
        buffer.append("Database version: ").append(database.getDatabaseProductVersion()).append("\n");
        buffer.append("Database user: ").append(database.getConnection().getConnectionUserName()).append("\n");
        SnapshotControl snapshotControl = snapshot.getSnapshotControl();
        List<Class> includedTypes = sort(snapshotControl.getTypesToInclude());
        buffer.append("Included types:\n").append(StringUtils.indent(StringUtils.join(includedTypes, "\n", new StringUtils.StringUtilsFormatter<Class>() {

            @Override
            public String toString(Class obj) {
                return obj.getName();
            }
        }))).append("\n");
        List<Schema> schemas = sort(snapshot.get(Schema.class), new Comparator<Schema>() {

            @Override
            public int compare(Schema o1, Schema o2) {
                return o1.toString().compareTo(o2.toString());
            }
        });
        for (Schema schema : schemas) {
            if (database.supportsSchemas()) {
                buffer.append("\nCatalog & Schema: ").append(schema.getCatalogName()).append(" / ").append(schema.getName()).append("\n");
            } else {
                buffer.append("\nCatalog: ").append(schema.getCatalogName()).append("\n");
            }
            StringBuilder catalogBuffer = new StringBuilder();
            for (Class type : includedTypes) {
                if (type.equals(Schema.class) || type.equals(Catalog.class) || type.equals(Column.class)) {
                    continue;
                }
                List<DatabaseObject> objects = new ArrayList<DatabaseObject>(snapshot.get(type));
                ListIterator<DatabaseObject> iterator = objects.listIterator();
                while (iterator.hasNext()) {
                    DatabaseObject next = iterator.next();
                    if (next instanceof DatabaseLevelObject) {
                        continue;
                    }
                    Schema objectSchema = next.getSchema();
                    if (objectSchema == null) {
                        if (!(next instanceof CatalogLevelObject) || !((CatalogLevelObject) next).getCatalog().equals(schema.getCatalog())) {
                            iterator.remove();
                        }
                    } else if (!objectSchema.equals(schema)) {
                        iterator.remove();
                    }
                }
                outputObjects(objects, type, catalogBuffer);
            }
            buffer.append(StringUtils.indent(catalogBuffer.toString(), INDENT_LENGTH));
        }
        //standardize all newline chars
        return buffer.toString().replace("\r\n", "\n").replace("\r", "\n");
    } catch (Exception e) {
        throw new UnexpectedLiquibaseException(e);
    }
}
Also used : CatalogLevelObject(liquibase.structure.CatalogLevelObject) UnexpectedLiquibaseException(liquibase.exception.UnexpectedLiquibaseException) DatabaseLevelObject(liquibase.structure.DatabaseLevelObject) Database(liquibase.database.Database) DatabaseObject(liquibase.structure.DatabaseObject) DatabaseSnapshot(liquibase.snapshot.DatabaseSnapshot) SnapshotControl(liquibase.snapshot.SnapshotControl) UnexpectedLiquibaseException(liquibase.exception.UnexpectedLiquibaseException)

Example 63 with UnexpectedLiquibaseException

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

the class CatalogSnapshotGenerator method snapshotObject.

@Override
protected DatabaseObject snapshotObject(DatabaseObject example, DatabaseSnapshot snapshot) throws DatabaseException, InvalidExampleException {
    if (!(example instanceof Catalog)) {
        throw new UnexpectedLiquibaseException("Unexpected example type: " + example.getClass().getName());
    }
    Database database = snapshot.getDatabase();
    Catalog match = null;
    String catalogName = example.getName();
    if (catalogName == null && database.supportsCatalogs()) {
        catalogName = database.getDefaultCatalogName();
    }
    example = new Catalog(catalogName);
    try {
        for (String potentialCatalogName : getDatabaseCatalogNames(database)) {
            Catalog catalog = new Catalog(potentialCatalogName);
            if (DatabaseObjectComparatorFactory.getInstance().isSameObject(catalog, example, snapshot.getSchemaComparisons(), database)) {
                if (match == null) {
                    match = catalog;
                } else {
                    throw new InvalidExampleException("Found multiple catalogs matching " + example.getName());
                }
            }
        }
    } catch (SQLException e) {
        throw new DatabaseException(e);
    }
    if (match != null && isDefaultCatalog(match, database)) {
        match.setDefault(true);
    }
    return match;
}
Also used : InvalidExampleException(liquibase.snapshot.InvalidExampleException) SQLException(java.sql.SQLException) Database(liquibase.database.Database) AbstractJdbcDatabase(liquibase.database.AbstractJdbcDatabase) UnexpectedLiquibaseException(liquibase.exception.UnexpectedLiquibaseException) DatabaseException(liquibase.exception.DatabaseException) Catalog(liquibase.structure.core.Catalog)

Example 64 with UnexpectedLiquibaseException

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

the class ColumnSnapshotGenerator method readColumn.

protected Column readColumn(CachedRow columnMetadataResultSet, Relation table, Database database) throws SQLException, DatabaseException {
    String rawTableName = (String) columnMetadataResultSet.get("TABLE_NAME");
    String rawColumnName = (String) columnMetadataResultSet.get("COLUMN_NAME");
    String rawSchemaName = StringUtils.trimToNull((String) columnMetadataResultSet.get("TABLE_SCHEM"));
    String rawCatalogName = StringUtils.trimToNull((String) columnMetadataResultSet.get("TABLE_CAT"));
    String remarks = StringUtils.trimToNull((String) columnMetadataResultSet.get("REMARKS"));
    if (remarks != null) {
        //come back escaped sometimes
        remarks = remarks.replace("''", "'");
    }
    Integer position = columnMetadataResultSet.getInt("ORDINAL_POSITION");
    Column column = new Column();
    column.setName(StringUtils.trimToNull(rawColumnName));
    column.setRelation(table);
    column.setRemarks(remarks);
    column.setOrder(position);
    if (database instanceof OracleDatabase) {
        String nullable = columnMetadataResultSet.getString("NULLABLE");
        if (nullable.equals("Y")) {
            column.setNullable(true);
        } else {
            column.setNullable(false);
        }
    } else {
        int nullable = columnMetadataResultSet.getInt("NULLABLE");
        if (nullable == DatabaseMetaData.columnNoNulls) {
            column.setNullable(false);
        } else if (nullable == DatabaseMetaData.columnNullable) {
            column.setNullable(true);
        } else if (nullable == DatabaseMetaData.columnNullableUnknown) {
            LogFactory.getLogger().info("Unknown nullable state for column " + column.toString() + ". Assuming nullable");
            column.setNullable(true);
        }
    }
    if (database.supportsAutoIncrement()) {
        if (table instanceof Table) {
            if (database instanceof OracleDatabase) {
                String data_default = StringUtils.trimToEmpty((String) columnMetadataResultSet.get("DATA_DEFAULT")).toLowerCase();
                if (data_default.contains("iseq$$") && data_default.endsWith("nextval")) {
                    column.setAutoIncrementInformation(new Column.AutoIncrementInformation());
                }
            } else {
                if (columnMetadataResultSet.containsColumn("IS_AUTOINCREMENT")) {
                    String isAutoincrement = (String) columnMetadataResultSet.get("IS_AUTOINCREMENT");
                    isAutoincrement = StringUtils.trimToNull(isAutoincrement);
                    if (isAutoincrement == null) {
                        column.setAutoIncrementInformation(null);
                    } else if (isAutoincrement.equals("YES")) {
                        column.setAutoIncrementInformation(new Column.AutoIncrementInformation());
                    } else if (isAutoincrement.equals("NO")) {
                        column.setAutoIncrementInformation(null);
                    } else if (isAutoincrement.equals("")) {
                        LogFactory.getLogger().info("Unknown auto increment state for column " + column.toString() + ". Assuming not auto increment");
                        column.setAutoIncrementInformation(null);
                    } else {
                        throw new UnexpectedLiquibaseException("Unknown is_autoincrement value: '" + isAutoincrement + "'");
                    }
                } else {
                    //probably older version of java, need to select from the column to find out if it is auto-increment
                    String selectStatement;
                    if (database.getDatabaseProductName().startsWith("DB2 UDB for AS/400")) {
                        selectStatement = "select " + database.escapeColumnName(rawCatalogName, rawSchemaName, rawTableName, rawColumnName) + " from " + rawSchemaName + "." + rawTableName + " where 0=1";
                        LogFactory.getLogger().debug("rawCatalogName : <" + rawCatalogName + ">");
                        LogFactory.getLogger().debug("rawSchemaName : <" + rawSchemaName + ">");
                        LogFactory.getLogger().debug("rawTableName : <" + rawTableName + ">");
                        LogFactory.getLogger().debug("raw selectStatement : <" + selectStatement + ">");
                    } else {
                        selectStatement = "select " + database.escapeColumnName(rawCatalogName, rawSchemaName, rawTableName, rawColumnName) + " from " + database.escapeTableName(rawCatalogName, rawSchemaName, rawTableName) + " where 0=1";
                    }
                    LogFactory.getLogger().debug("Checking " + rawTableName + "." + rawCatalogName + " for auto-increment with SQL: '" + selectStatement + "'");
                    Connection underlyingConnection = ((JdbcConnection) database.getConnection()).getUnderlyingConnection();
                    Statement statement = null;
                    ResultSet columnSelectRS = null;
                    try {
                        statement = underlyingConnection.createStatement();
                        columnSelectRS = statement.executeQuery(selectStatement);
                        if (columnSelectRS.getMetaData().isAutoIncrement(1)) {
                            column.setAutoIncrementInformation(new Column.AutoIncrementInformation());
                        } else {
                            column.setAutoIncrementInformation(null);
                        }
                    } finally {
                        try {
                            if (statement != null) {
                                statement.close();
                            }
                        } catch (SQLException ignore) {
                        }
                        if (columnSelectRS != null) {
                            columnSelectRS.close();
                        }
                    }
                }
            }
        }
    }
    DataType type = readDataType(columnMetadataResultSet, column, database);
    column.setType(type);
    Object defaultValue = readDefaultValue(columnMetadataResultSet, column, database);
    if (defaultValue != null && defaultValue instanceof DatabaseFunction && ((DatabaseFunction) defaultValue).getValue().matches("\\w+")) {
        defaultValue = new DatabaseFunction(((DatabaseFunction) defaultValue).getValue().toUpperCase());
    }
    column.setDefaultValue(defaultValue);
    column.setDefaultValueConstraintName(columnMetadataResultSet.getString("COLUMN_DEF_NAME"));
    return column;
}
Also used : DatabaseFunction(liquibase.statement.DatabaseFunction) RawSqlStatement(liquibase.statement.core.RawSqlStatement) OfflineConnection(liquibase.database.OfflineConnection) JdbcConnection(liquibase.database.jvm.JdbcConnection) JdbcConnection(liquibase.database.jvm.JdbcConnection) DatabaseObject(liquibase.structure.DatabaseObject) UnexpectedLiquibaseException(liquibase.exception.UnexpectedLiquibaseException)

Example 65 with UnexpectedLiquibaseException

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

the class AbstractLiquibaseSerializable method convertEscaped.

protected Object convertEscaped(Object value) {
    if (value == null) {
        return null;
    }
    Matcher matcher = Pattern.compile("(.*)!\\{(.*)\\}").matcher((String) value);
    if (matcher.matches()) {
        String stringValue = matcher.group(1);
        try {
            Class<?> aClass = Class.forName(matcher.group(2));
            if (Date.class.isAssignableFrom(aClass)) {
                Date date = new ISODateFormat().parse(stringValue);
                value = aClass.getConstructor(long.class).newInstance(date.getTime());
            } else if (Enum.class.isAssignableFrom(aClass)) {
                value = Enum.valueOf((Class<? extends Enum>) aClass, stringValue);
            } else {
                value = aClass.getConstructor(String.class).newInstance(stringValue);
            }
        } catch (Exception e) {
            throw new UnexpectedLiquibaseException(e);
        }
    }
    return value;
}
Also used : ISODateFormat(liquibase.util.ISODateFormat) UnexpectedLiquibaseException(liquibase.exception.UnexpectedLiquibaseException) ParsedNodeException(liquibase.parser.core.ParsedNodeException) 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