Search in sources :

Example 1 with MySQLDatabase

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

the class LoadDataChange method generateStatements.

@Override
public SqlStatement[] generateStatements(Database database) {
    CSVReader reader = null;
    try {
        reader = getCSVReader();
        if (reader == null) {
            throw new UnexpectedLiquibaseException("Unable to read file " + this.getFile());
        }
        String[] headers = reader.readNext();
        if (headers == null) {
            throw new UnexpectedLiquibaseException("Data file " + getFile() + " was empty");
        }
        List<SqlStatement> statements = new ArrayList<SqlStatement>();
        boolean anyPreparedStatements = false;
        String[] line;
        // Start at '1' to take into account the header (already processed)
        int lineNumber = 1;
        boolean isCommentingEnabled = StringUtils.isNotEmpty(commentLineStartsWith);
        while ((line = reader.readNext()) != null) {
            lineNumber++;
            if (line.length == 0 || (line.length == 1 && StringUtils.trimToNull(line[0]) == null) || (isCommentingEnabled && isLineCommented(line))) {
                //nothing on this line
                continue;
            }
            // (Failure could indicate unquoted strings with commas, for example).
            if (line.length != headers.length) {
                throw new UnexpectedLiquibaseException("CSV file " + getFile() + " Line " + lineNumber + " has " + line.length + " values defined, Header has " + headers.length + ". Numbers MUST be equal (check for unquoted string with embedded commas)");
            }
            boolean needsPreparedStatement = false;
            List<ColumnConfig> columns = new ArrayList<ColumnConfig>();
            for (int i = 0; i < headers.length; i++) {
                Object value = line[i];
                String columnName = headers[i].trim();
                ColumnConfig valueConfig = new ColumnConfig();
                ColumnConfig columnConfig = getColumnConfig(i, headers[i].trim());
                if (columnConfig != null) {
                    if ("skip".equalsIgnoreCase(columnConfig.getType())) {
                        continue;
                    }
                    // don't overwrite header name unless there is actually a value to override it with
                    if (columnConfig.getName() != null) {
                        columnName = columnConfig.getName();
                    }
                    valueConfig.setName(columnName);
                    if (columnConfig.getType() != null) {
                        if (columnConfig.getType().equalsIgnoreCase("BOOLEAN")) {
                            if (value.toString().equalsIgnoreCase("NULL")) {
                                valueConfig.setValue(null);
                            } else {
                                valueConfig.setValueBoolean(BooleanParser.parseBoolean(value.toString().toLowerCase()));
                            }
                        } else if (columnConfig.getType().equalsIgnoreCase("NUMERIC")) {
                            if (value.toString().equalsIgnoreCase("NULL")) {
                                valueConfig.setValue(null);
                            } else {
                                valueConfig.setValueNumeric(value.toString());
                            }
                        } else if (columnConfig.getType().toLowerCase().contains("date") || columnConfig.getType().toLowerCase().contains("time")) {
                            if (value.toString().equalsIgnoreCase("NULL")) {
                                valueConfig.setValue(null);
                            } else {
                                valueConfig.setValueDate(value.toString());
                            }
                        } else if (columnConfig.getType().equalsIgnoreCase("STRING")) {
                            if (value.toString().equalsIgnoreCase("NULL")) {
                                valueConfig.setValue(null);
                            } else {
                                valueConfig.setValue(value.toString());
                            }
                        } else if (columnConfig.getType().equalsIgnoreCase("COMPUTED")) {
                            if (value.toString().equalsIgnoreCase("NULL")) {
                                valueConfig.setValue(null);
                            } else {
                                liquibase.statement.DatabaseFunction function = new liquibase.statement.DatabaseFunction(value.toString());
                                valueConfig.setValueComputed(function);
                            }
                        } else if (columnConfig.getType().equalsIgnoreCase("SEQUENCE")) {
                            String sequenceName;
                            if (value.toString().equalsIgnoreCase("NULL")) {
                                sequenceName = columnConfig.getDefaultValue();
                                if (sequenceName == null) {
                                    throw new UnexpectedLiquibaseException("Must set a sequence name in the loadData column defaultValue attribute");
                                }
                            } else {
                                sequenceName = value.toString();
                            }
                            liquibase.statement.SequenceNextValueFunction function = new liquibase.statement.SequenceNextValueFunction(sequenceName);
                            valueConfig.setValueComputed(function);
                        } else if (columnConfig.getType().equalsIgnoreCase("BLOB")) {
                            if (value.toString().equalsIgnoreCase("NULL")) {
                                valueConfig.setValue(null);
                            } else {
                                valueConfig.setValueBlobFile(value.toString());
                                needsPreparedStatement = true;
                            }
                        } else if (columnConfig.getType().equalsIgnoreCase("CLOB")) {
                            if (value.toString().equalsIgnoreCase("NULL")) {
                                valueConfig.setValue(null);
                            } else {
                                valueConfig.setValueClobFile(value.toString());
                                needsPreparedStatement = true;
                            }
                        } else {
                            throw new UnexpectedLiquibaseException("loadData type of " + columnConfig.getType() + " is not supported.  Please use BOOLEAN, NUMERIC, DATE, STRING, COMPUTED, SEQUENCE or SKIP");
                        }
                    }
                } else {
                    if (columnName.contains("(") || columnName.contains(")") && database instanceof AbstractJdbcDatabase) {
                        columnName = ((AbstractJdbcDatabase) database).quoteObject(columnName, Column.class);
                    }
                    valueConfig.setName(columnName);
                    if (value == null || value.toString().equalsIgnoreCase("NULL")) {
                        // value is always going to be a string unless overridden by ColumnConfig
                        valueConfig.setValue((String) value);
                    } else {
                        valueConfig.setValue(value.toString());
                    }
                }
                columns.add(valueConfig);
            }
            if (needsPreparedStatement) {
                anyPreparedStatements = true;
                statements.add(new InsertExecutablePreparedStatement(database, getCatalogName(), getSchemaName(), getTableName(), columns, getChangeSet(), getResourceAccessor()));
            } else {
                InsertStatement insertStatement = this.createStatement(getCatalogName(), getSchemaName(), getTableName());
                for (ColumnConfig column : columns) {
                    String columnName = column.getName();
                    Object value = column.getValueObject();
                    if (value == null) {
                        value = "NULL";
                    }
                    insertStatement.addColumnValue(columnName, value);
                }
                statements.add(insertStatement);
            }
        }
        if (anyPreparedStatements) {
            return statements.toArray(new SqlStatement[statements.size()]);
        } else {
            InsertSetStatement statementSet = this.createStatementSet(getCatalogName(), getSchemaName(), getTableName());
            for (SqlStatement stmt : statements) {
                statementSet.addInsertStatement((InsertStatement) stmt);
            }
            if (database instanceof MSSQLDatabase || database instanceof MySQLDatabase || database instanceof PostgresDatabase) {
                List<InsertStatement> innerStatements = statementSet.getStatements();
                if (innerStatements != null && innerStatements.size() > 0 && innerStatements.get(0) instanceof InsertOrUpdateStatement) {
                    //cannot do insert or update in a single statement
                    return statementSet.getStatementsArray();
                }
                // we only return a single "statement" - it's capable of emitting multiple sub-statements, should the need arise, on generation.
                return new SqlStatement[] { statementSet };
            } else {
                return statementSet.getStatementsArray();
            }
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (UnexpectedLiquibaseException ule) {
        if (getChangeSet() != null && getChangeSet().getFailOnError() != null && !getChangeSet().getFailOnError()) {
            Logger log = LogFactory.getLogger();
            log.info("Change set " + getChangeSet().toString(false) + " failed, but failOnError was false.  Error: " + ule.getMessage());
            return new SqlStatement[0];
        } else {
            throw ule;
        }
    } finally {
        if (null != reader) {
            try {
                reader.close();
            } catch (IOException e) {
                ;
            }
        }
    }
}
Also used : InsertOrUpdateStatement(liquibase.statement.core.InsertOrUpdateStatement) ColumnConfig(liquibase.change.ColumnConfig) Logger(liquibase.logging.Logger) InsertStatement(liquibase.statement.core.InsertStatement) SqlStatement(liquibase.statement.SqlStatement) Column(liquibase.structure.core.Column) MSSQLDatabase(liquibase.database.core.MSSQLDatabase) InsertExecutablePreparedStatement(liquibase.statement.InsertExecutablePreparedStatement) CSVReader(liquibase.util.csv.CSVReader) MySQLDatabase(liquibase.database.core.MySQLDatabase) IOException(java.io.IOException) AbstractJdbcDatabase(liquibase.database.AbstractJdbcDatabase) PostgresDatabase(liquibase.database.core.PostgresDatabase) InsertSetStatement(liquibase.statement.core.InsertSetStatement) UnexpectedLiquibaseException(liquibase.exception.UnexpectedLiquibaseException)

Example 2 with MySQLDatabase

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

the class CreateTableChange method generateStatements.

@Override
public SqlStatement[] generateStatements(Database database) {
    CreateTableStatement statement = generateCreateTableStatement();
    for (ColumnConfig column : getColumns()) {
        ConstraintsConfig constraints = column.getConstraints();
        boolean isAutoIncrement = column.isAutoIncrement() != null && column.isAutoIncrement();
        Object defaultValue = column.getDefaultValueObject();
        LiquibaseDataType columnType = DataTypeFactory.getInstance().fromDescription(column.getType() + (isAutoIncrement ? "{autoIncrement:true}" : ""), database);
        if (constraints != null && constraints.isPrimaryKey() != null && constraints.isPrimaryKey()) {
            statement.addPrimaryKeyColumn(column.getName(), columnType, defaultValue, constraints.getPrimaryKeyName(), constraints.getPrimaryKeyTablespace());
        } else {
            statement.addColumn(column.getName(), columnType, column.getDefaultValueConstraintName(), defaultValue, column.getRemarks());
        }
        if (constraints != null) {
            if (constraints.isNullable() != null && !constraints.isNullable()) {
                statement.addColumnConstraint(new NotNullConstraint(column.getName()));
            }
            if (constraints.getReferences() != null || (constraints.getReferencedTableName() != null && constraints.getReferencedColumnNames() != null)) {
                if (StringUtils.trimToNull(constraints.getForeignKeyName()) == null) {
                    throw new UnexpectedLiquibaseException("createTable with references requires foreignKeyName");
                }
                ForeignKeyConstraint fkConstraint = new ForeignKeyConstraint(constraints.getForeignKeyName(), constraints.getReferences(), constraints.getReferencedTableName(), constraints.getReferencedColumnNames());
                fkConstraint.setReferencedTableCatalogName(constraints.getReferencedTableCatalogName());
                fkConstraint.setReferencedTableSchemaName(constraints.getReferencedTableSchemaName());
                fkConstraint.setColumn(column.getName());
                fkConstraint.setDeleteCascade(constraints.isDeleteCascade() != null && constraints.isDeleteCascade());
                fkConstraint.setInitiallyDeferred(constraints.isInitiallyDeferred() != null && constraints.isInitiallyDeferred());
                fkConstraint.setDeferrable(constraints.isDeferrable() != null && constraints.isDeferrable());
                statement.addColumnConstraint(fkConstraint);
            }
            if (constraints.isUnique() != null && constraints.isUnique()) {
                statement.addColumnConstraint(new UniqueConstraint(constraints.getUniqueConstraintName()).addColumns(column.getName()));
            }
        }
        if (isAutoIncrement) {
            statement.addColumnConstraint(new AutoIncrementConstraint(column.getName(), column.getStartWith(), column.getIncrementBy()));
        }
    }
    statement.setTablespace(StringUtils.trimToNull(getTablespace()));
    List<SqlStatement> statements = new ArrayList<SqlStatement>();
    statements.add(statement);
    if (StringUtils.trimToNull(remarks) != null) {
        SetTableRemarksStatement remarksStatement = new SetTableRemarksStatement(catalogName, schemaName, tableName, remarks);
        if (SqlGeneratorFactory.getInstance().supports(remarksStatement, database)) {
            statements.add(remarksStatement);
        }
    }
    for (ColumnConfig column : getColumns()) {
        String columnRemarks = StringUtils.trimToNull(column.getRemarks());
        if (columnRemarks != null) {
            SetColumnRemarksStatement remarksStatement = new SetColumnRemarksStatement(catalogName, schemaName, tableName, column.getName(), columnRemarks);
            if (!(database instanceof MySQLDatabase) && SqlGeneratorFactory.getInstance().supports(remarksStatement, database)) {
                statements.add(remarksStatement);
            }
        }
    }
    return statements.toArray(new SqlStatement[statements.size()]);
}
Also used : CreateTableStatement(liquibase.statement.core.CreateTableStatement) LiquibaseDataType(liquibase.datatype.LiquibaseDataType) SetTableRemarksStatement(liquibase.statement.core.SetTableRemarksStatement) ArrayList(java.util.ArrayList) MySQLDatabase(liquibase.database.core.MySQLDatabase) SetColumnRemarksStatement(liquibase.statement.core.SetColumnRemarksStatement)

Example 3 with MySQLDatabase

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

the class AddAutoIncrementGeneratorMySQL method generateSql.

@Override
public Sql[] generateSql(final AddAutoIncrementStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
    Sql[] sql = super.generateSql(statement, database, sqlGeneratorChain);
    if (statement.getStartWith() != null) {
        MySQLDatabase mysqlDatabase = (MySQLDatabase) database;
        String alterTableSql = "ALTER TABLE " + mysqlDatabase.escapeTableName(statement.getCatalogName(), statement.getSchemaName(), statement.getTableName()) + " " + mysqlDatabase.getTableOptionAutoIncrementStartWithClause(statement.getStartWith());
        sql = concact(sql, new UnparsedSql(alterTableSql, getAffectedTable(statement)));
    }
    return sql;
}
Also used : UnparsedSql(liquibase.sql.UnparsedSql) MySQLDatabase(liquibase.database.core.MySQLDatabase) UnparsedSql(liquibase.sql.UnparsedSql) Sql(liquibase.sql.Sql)

Example 4 with MySQLDatabase

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

the class GetViewDefinitionGenerator method generateSql.

@Override
public Sql[] generateSql(GetViewDefinitionStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
    CatalogAndSchema schema = new CatalogAndSchema(statement.getCatalogName(), statement.getSchemaName()).customize(database);
    String sql;
    if (database instanceof MSSQLDatabase)
        sql = "select VIEW_DEFINITION from INFORMATION_SCHEMA.VIEWS where TABLE_NAME='" + database.correctObjectName(statement.getViewName(), View.class) + "'";
    else
        sql = "select view_definition from information_schema.views where table_name='" + database.correctObjectName(statement.getViewName(), View.class) + "'";
    if (database instanceof MySQLDatabase) {
        sql += " and table_schema='" + schema.getCatalogName() + "'";
    } else {
        if (database.supportsSchemas()) {
            String schemaName = schema.getSchemaName();
            if (schemaName != null) {
                if (database instanceof MSSQLDatabase)
                    sql += " and TABLE_SCHEMA='" + schemaName + "'";
                else
                    sql += " and table_schema='" + schemaName + "'";
            }
        }
        if (database.supportsCatalogs()) {
            String catalogName = schema.getCatalogName();
            if (catalogName != null) {
                if (database instanceof MSSQLDatabase)
                    sql += " and TABLE_CATALOG='" + catalogName + "'";
                else
                    sql += " and table_catalog='" + catalogName + "'";
            }
        }
    }
    return new Sql[] { new UnparsedSql(sql) };
}
Also used : UnparsedSql(liquibase.sql.UnparsedSql) MySQLDatabase(liquibase.database.core.MySQLDatabase) MSSQLDatabase(liquibase.database.core.MSSQLDatabase) CatalogAndSchema(liquibase.CatalogAndSchema) UnparsedSql(liquibase.sql.UnparsedSql) Sql(liquibase.sql.Sql)

Example 5 with MySQLDatabase

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

the class ChangeMetaDataTest method getRequiredParameters.

@Test
public void getRequiredParameters() {
    HashSet<ChangeParameterMetaData> parameters = new HashSet<ChangeParameterMetaData>();
    parameters.add(new ChangeParameterMetaData(new ExampleAbstractChange(), "noneRequired", "x", null, null, null, Integer.class, new String[] { "none" }, null, null, null));
    parameters.add(new ChangeParameterMetaData(new ExampleAbstractChange(), "allRequired", "x", null, null, null, Integer.class, new String[] { "all" }, null, null, null));
    parameters.add(new ChangeParameterMetaData(new ExampleAbstractChange(), "h2Required", "x", null, null, null, Integer.class, new String[] { "h2" }, null, null, null));
    parameters.add(new ChangeParameterMetaData(new ExampleAbstractChange(), "oracleRequired", "x", null, null, null, Integer.class, new String[] { "oracle" }, null, null, null));
    ChangeMetaData changeMetaData = new ChangeMetaData("x", "y", 1, null, null, parameters);
    assertSetsEqual(new String[] { "allRequired", "h2Required" }, changeMetaData.getRequiredParameters(new H2Database()).keySet());
    assertSetsEqual(new String[] { "allRequired", "oracleRequired" }, changeMetaData.getRequiredParameters(new OracleDatabase()).keySet());
    assertSetsEqual(new String[] { "allRequired" }, changeMetaData.getRequiredParameters(new MySQLDatabase()).keySet());
}
Also used : OracleDatabase(liquibase.database.core.OracleDatabase) MySQLDatabase(liquibase.database.core.MySQLDatabase) H2Database(liquibase.database.core.H2Database) HashSet(java.util.HashSet) Test(org.junit.Test)

Aggregations

MySQLDatabase (liquibase.database.core.MySQLDatabase)21 Test (org.junit.Test)14 OracleDatabase (liquibase.database.core.OracleDatabase)9 MSSQLDatabase (liquibase.database.core.MSSQLDatabase)7 Sql (liquibase.sql.Sql)7 H2Database (liquibase.database.core.H2Database)6 AbstractSqlGeneratorTest (liquibase.sqlgenerator.AbstractSqlGeneratorTest)6 Database (liquibase.database.Database)5 DB2Database (liquibase.database.core.DB2Database)5 PostgresDatabase (liquibase.database.core.PostgresDatabase)5 DerbyDatabase (liquibase.database.core.DerbyDatabase)4 SQLiteDatabase (liquibase.database.core.SQLiteDatabase)4 MockSqlGeneratorChain (liquibase.sqlgenerator.MockSqlGeneratorChain)4 AutoIncrementConstraint (liquibase.statement.AutoIncrementConstraint)4 CreateTableStatement (liquibase.statement.core.CreateTableStatement)4 HsqlDatabase (liquibase.database.core.HsqlDatabase)3 SybaseASADatabase (liquibase.database.core.SybaseASADatabase)3 SybaseDatabase (liquibase.database.core.SybaseDatabase)3 LiquibaseDataType (liquibase.datatype.LiquibaseDataType)3 AddColumnStatement (liquibase.statement.core.AddColumnStatement)3