Search in sources :

Example 1 with InformixDatabase

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

the class InsertDataChange method generateStatements.

@Override
public SqlStatement[] generateStatements(Database database) {
    boolean needsPreparedStatement = false;
    for (ColumnConfig column : columns) {
        if (column.getValueBlobFile() != null) {
            needsPreparedStatement = true;
        }
        if (column.getValueClobFile() != null) {
            needsPreparedStatement = true;
        }
        if (!needsPreparedStatement && database instanceof InformixDatabase) {
            if (column.getValue() != null) {
                try {
                    Column snapshot = SnapshotGeneratorFactory.getInstance().createSnapshot(new Column(column), database);
                    if (snapshot != null) {
                        needsPreparedStatement = true;
                    }
                } catch (Exception ignore) {
                //assume it's not a clob
                }
            }
        }
    }
    if (needsPreparedStatement) {
        return new SqlStatement[] { new InsertExecutablePreparedStatement(database, catalogName, schemaName, tableName, columns, getChangeSet(), this.getResourceAccessor()) };
    }
    InsertStatement statement = new InsertStatement(getCatalogName(), getSchemaName(), getTableName());
    for (ColumnConfig column : columns) {
        if (database.supportsAutoIncrement() && column.isAutoIncrement() != null && column.isAutoIncrement()) {
            // skip auto increment columns as they will be generated by the database
            continue;
        }
        statement.addColumnValue(column.getName(), column.getValueObject());
    }
    return new SqlStatement[] { statement };
}
Also used : SqlStatement(liquibase.statement.SqlStatement) InformixDatabase(liquibase.database.core.InformixDatabase) Column(liquibase.structure.core.Column) InsertExecutablePreparedStatement(liquibase.statement.InsertExecutablePreparedStatement) InvalidExampleException(liquibase.snapshot.InvalidExampleException) DatabaseException(liquibase.exception.DatabaseException) InsertStatement(liquibase.statement.core.InsertStatement)

Example 2 with InformixDatabase

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

the class MissingTableChangeGenerator method setDefaultValue.

public static void setDefaultValue(ColumnConfig columnConfig, Column column, Database database) {
    LiquibaseDataType dataType = DataTypeFactory.getInstance().from(column.getType(), database);
    Object defaultValue = column.getDefaultValue();
    if (defaultValue == null) {
    // do nothing
    } else if (column.isAutoIncrement()) {
    // do nothing
    } else if (defaultValue instanceof Date) {
        columnConfig.setDefaultValueDate((Date) defaultValue);
    } else if (defaultValue instanceof Boolean) {
        columnConfig.setDefaultValueBoolean(((Boolean) defaultValue));
    } else if (defaultValue instanceof Number) {
        columnConfig.setDefaultValueNumeric(((Number) defaultValue));
    } else if (defaultValue instanceof DatabaseFunction) {
        DatabaseFunction function = (DatabaseFunction) defaultValue;
        if ("current".equals(function.getValue())) {
            if (database instanceof InformixDatabase) {
                if (dataType instanceof DateTimeType) {
                    if (dataType.getAdditionalInformation() == null || dataType.getAdditionalInformation().length() == 0) {
                        if (dataType.getParameters() != null && dataType.getParameters().length > 0) {
                            String parameter = String.valueOf(dataType.getParameters()[0]);
                            if ("4365".equals(parameter)) {
                                function = new DatabaseFunction("current year to fraction(3)");
                            }
                            if ("3594".equals(parameter)) {
                                function = new DatabaseFunction("current year to second");
                            }
                            if ("3080".equals(parameter)) {
                                function = new DatabaseFunction("current year to minute");
                            }
                            if ("2052".equals(parameter)) {
                                function = new DatabaseFunction("current year to day");
                            }
                        }
                    }
                }
            }
        }
        columnConfig.setDefaultValueComputed(function);
    } else {
        String defaultValueString = null;
        try {
            defaultValueString = DataTypeFactory.getInstance().from(column.getType(), database).objectToSql(defaultValue, database);
        } catch (NullPointerException e) {
            throw e;
        }
        if (defaultValueString != null) {
            defaultValueString = defaultValueString.replaceFirst("'", "").replaceAll("'$", "");
        }
        columnConfig.setDefaultValue(defaultValueString);
    }
    columnConfig.setDefaultValueConstraintName(column.getDefaultValueConstraintName());
}
Also used : DateTimeType(liquibase.datatype.core.DateTimeType) InformixDatabase(liquibase.database.core.InformixDatabase) DatabaseFunction(liquibase.statement.DatabaseFunction) LiquibaseDataType(liquibase.datatype.LiquibaseDataType) DatabaseObject(liquibase.structure.DatabaseObject) Date(java.util.Date)

Example 3 with InformixDatabase

use of liquibase.database.core.InformixDatabase 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 4 with InformixDatabase

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

the class CreateIndexGeneratorPostgres method generateSql.

@Override
public Sql[] generateSql(CreateIndexStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
    // Default filter of index creation:
    // creation of all indexes with associations are switched off.
    List<String> associatedWith = StringUtils.splitAndTrim(statement.getAssociatedWith(), ",");
    if (associatedWith != null && (associatedWith.contains(Index.MARK_PRIMARY_KEY) || associatedWith.contains(Index.MARK_UNIQUE_CONSTRAINT) || associatedWith.contains(Index.MARK_FOREIGN_KEY))) {
        return new Sql[0];
    }
    StringBuilder buffer = new StringBuilder();
    buffer.append("CREATE ");
    if (statement.isUnique() != null && statement.isUnique()) {
        buffer.append("UNIQUE ");
    }
    buffer.append("INDEX ");
    if (statement.getIndexName() != null) {
        // for postgres setting the schema name for the index name is invalid
        buffer.append(database.escapeObjectName(statement.getIndexName(), Index.class)).append(" ");
    }
    buffer.append("ON ");
    buffer.append(database.escapeTableName(statement.getTableCatalogName(), statement.getTableSchemaName(), statement.getTableName())).append("(");
    Iterator<AddColumnConfig> iterator = Arrays.asList(statement.getColumns()).iterator();
    while (iterator.hasNext()) {
        AddColumnConfig column = iterator.next();
        if (column.getComputed() == null) {
            buffer.append(database.escapeColumnName(statement.getTableCatalogName(), statement.getTableSchemaName(), statement.getTableName(), column.getName(), false));
        } else {
            if (column.getComputed()) {
                buffer.append(column.getName());
            } else {
                buffer.append(database.escapeColumnName(statement.getTableCatalogName(), statement.getTableSchemaName(), statement.getTableName(), column.getName()));
            }
        }
        if (iterator.hasNext()) {
            buffer.append(", ");
        }
    }
    buffer.append(")");
    if (StringUtils.trimToNull(statement.getTablespace()) != null && database.supportsTablespaces()) {
        if (database instanceof MSSQLDatabase || database instanceof SybaseASADatabase) {
            buffer.append(" ON ").append(statement.getTablespace());
        } else if (database instanceof DB2Database || database instanceof InformixDatabase) {
            buffer.append(" IN ").append(statement.getTablespace());
        } else {
            buffer.append(" TABLESPACE ").append(statement.getTablespace());
        }
    }
    if (statement.isClustered() != null && statement.isClustered()) {
        return new Sql[] { new UnparsedSql(buffer.toString(), getAffectedIndex(statement)), new UnparsedSql("CLUSTER " + database.escapeTableName(statement.getTableCatalogName(), statement.getTableSchemaName(), statement.getTableName()) + " USING " + database.escapeObjectName(statement.getIndexName(), Index.class)) };
    } else {
        return new Sql[] { new UnparsedSql(buffer.toString(), getAffectedIndex(statement)) };
    }
}
Also used : SybaseASADatabase(liquibase.database.core.SybaseASADatabase) DB2Database(liquibase.database.core.DB2Database) InformixDatabase(liquibase.database.core.InformixDatabase) UnparsedSql(liquibase.sql.UnparsedSql) AddColumnConfig(liquibase.change.AddColumnConfig) MSSQLDatabase(liquibase.database.core.MSSQLDatabase) Sql(liquibase.sql.Sql) UnparsedSql(liquibase.sql.UnparsedSql)

Example 5 with InformixDatabase

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

the class ViewSnapshotGenerator method snapshotObject.

//    public Boolean has(DatabaseObject example, DatabaseSnapshot snapshot, SnapshotGeneratorChain chain) throws DatabaseException {
//        Database database = snapshot.getDatabase();
//        if (!(example instanceof View)) {
//            return chain.has(example, snapshot);
//        }
//        String viewName = example.getName();
//        Schema schema = example.getSchema();
//        try {
//            ResultSet rs = getMetaData(database).getTables(database.getJdbcCatalogName(schema), database.getJdbcSchemaName(schema), database.correctObjectName(viewName, View.class), new String[]{"VIEW"});
//            try {
//                return rs.next();
//            } finally {
//                try {
//                    rs.close();
//                } catch (SQLException ignore) {
//                }
//            }
//        } catch (SQLException e) {
//            throw new DatabaseException(e);
//        }
//    }
@Override
protected DatabaseObject snapshotObject(DatabaseObject example, DatabaseSnapshot snapshot) throws DatabaseException {
    if (((View) example).getDefinition() != null) {
        return example;
    }
    Database database = snapshot.getDatabase();
    Schema schema = example.getSchema();
    List<CachedRow> viewsMetadataRs = null;
    try {
        viewsMetadataRs = ((JdbcDatabaseSnapshot) snapshot).getMetaData().getViews(((AbstractJdbcDatabase) database).getJdbcCatalogName(schema), ((AbstractJdbcDatabase) database).getJdbcSchemaName(schema), example.getName());
        if (viewsMetadataRs.size() > 0) {
            CachedRow row = viewsMetadataRs.get(0);
            String rawViewName = row.getString("TABLE_NAME");
            String rawSchemaName = StringUtils.trimToNull(row.getString("TABLE_SCHEM"));
            String rawCatalogName = StringUtils.trimToNull(row.getString("TABLE_CAT"));
            String remarks = row.getString("REMARKS");
            if (remarks != null) {
                //come back escaped sometimes
                remarks = remarks.replace("''", "'");
            }
            View view = new View().setName(cleanNameFromDatabase(rawViewName, database));
            view.setRemarks(remarks);
            CatalogAndSchema schemaFromJdbcInfo = ((AbstractJdbcDatabase) database).getSchemaFromJdbcInfo(rawCatalogName, rawSchemaName);
            view.setSchema(new Schema(schemaFromJdbcInfo.getCatalogName(), schemaFromJdbcInfo.getSchemaName()));
            try {
                String definition = database.getViewDefinition(schemaFromJdbcInfo, view.getName());
                if (definition.startsWith("FULL_DEFINITION: ")) {
                    definition = definition.replaceFirst("^FULL_DEFINITION: ", "");
                    view.setContainsFullDefinition(true);
                }
                // remove strange zero-termination seen on some Oracle view definitions
                int length = definition.length();
                if (definition.charAt(length - 1) == 0) {
                    definition = definition.substring(0, length - 1);
                }
                if (database instanceof InformixDatabase) {
                    // Cleanup
                    definition = definition.trim();
                    definition = definition.replaceAll("\\s*,\\s*", ", ");
                    definition = definition.replaceAll("\\s*;", "");
                    // Strip the schema definition because it can optionally be included in the tag attribute
                    definition = definition.replaceAll("(?i)\"" + view.getSchema().getName() + "\"\\.", "");
                }
                view.setDefinition(definition);
            } catch (DatabaseException e) {
                throw new DatabaseException("Error getting " + database.getConnection().getURL() + " view with " + new GetViewDefinitionStatement(view.getSchema().getCatalogName(), view.getSchema().getName(), rawViewName), e);
            }
            return view;
        } else {
            return null;
        }
    } catch (SQLException e) {
        throw new DatabaseException(e);
    }
}
Also used : CachedRow(liquibase.snapshot.CachedRow) SQLException(java.sql.SQLException) Schema(liquibase.structure.core.Schema) CatalogAndSchema(liquibase.CatalogAndSchema) CatalogAndSchema(liquibase.CatalogAndSchema) AbstractJdbcDatabase(liquibase.database.AbstractJdbcDatabase) View(liquibase.structure.core.View) GetViewDefinitionStatement(liquibase.statement.core.GetViewDefinitionStatement) InformixDatabase(liquibase.database.core.InformixDatabase) OracleDatabase(liquibase.database.core.OracleDatabase) InformixDatabase(liquibase.database.core.InformixDatabase) Database(liquibase.database.Database) AbstractJdbcDatabase(liquibase.database.AbstractJdbcDatabase) JdbcDatabaseSnapshot(liquibase.snapshot.JdbcDatabaseSnapshot) DatabaseException(liquibase.exception.DatabaseException)

Aggregations

InformixDatabase (liquibase.database.core.InformixDatabase)5 Date (java.util.Date)2 DatabaseException (liquibase.exception.DatabaseException)2 DatabaseFunction (liquibase.statement.DatabaseFunction)2 DatabaseObject (liquibase.structure.DatabaseObject)2 SQLException (java.sql.SQLException)1 ArrayList (java.util.ArrayList)1 CatalogAndSchema (liquibase.CatalogAndSchema)1 AddColumnConfig (liquibase.change.AddColumnConfig)1 Change (liquibase.change.Change)1 ColumnConfig (liquibase.change.ColumnConfig)1 InsertDataChange (liquibase.change.core.InsertDataChange)1 GlobalConfiguration (liquibase.configuration.GlobalConfiguration)1 AbstractJdbcDatabase (liquibase.database.AbstractJdbcDatabase)1 Database (liquibase.database.Database)1 DB2Database (liquibase.database.core.DB2Database)1 MSSQLDatabase (liquibase.database.core.MSSQLDatabase)1 OracleDatabase (liquibase.database.core.OracleDatabase)1 SybaseASADatabase (liquibase.database.core.SybaseASADatabase)1 LiquibaseDataType (liquibase.datatype.LiquibaseDataType)1