Search in sources :

Example 16 with ColumnConfig

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

the class StandardChangeLogHistoryService method init.

public void init() throws DatabaseException {
    if (serviceInitialized) {
        return;
    }
    Database database = getDatabase();
    Executor executor = ExecutorService.getInstance().getExecutor(database);
    Table changeLogTable = null;
    try {
        changeLogTable = SnapshotGeneratorFactory.getInstance().getDatabaseChangeLogTable(new SnapshotControl(database, false, Table.class, Column.class), database);
    } catch (LiquibaseException e) {
        throw new UnexpectedLiquibaseException(e);
    }
    List<SqlStatement> statementsToExecute = new ArrayList<SqlStatement>();
    boolean changeLogCreateAttempted = false;
    if (changeLogTable != null) {
        boolean hasDescription = changeLogTable.getColumn("DESCRIPTION") != null;
        boolean hasComments = changeLogTable.getColumn("COMMENTS") != null;
        boolean hasTag = changeLogTable.getColumn("TAG") != null;
        boolean hasLiquibase = changeLogTable.getColumn("LIQUIBASE") != null;
        boolean hasContexts = changeLogTable.getColumn("CONTEXTS") != null;
        boolean hasLabels = changeLogTable.getColumn("LABELS") != null;
        boolean liquibaseColumnNotRightSize = false;
        if (!(this.getDatabase() instanceof SQLiteDatabase)) {
            DataType type = changeLogTable.getColumn("LIQUIBASE").getType();
            if (type.getTypeName().toLowerCase().startsWith("varchar")) {
                Integer columnSize = type.getColumnSize();
                liquibaseColumnNotRightSize = columnSize != null && columnSize < 20;
            } else {
                liquibaseColumnNotRightSize = false;
            }
        }
        boolean hasOrderExecuted = changeLogTable.getColumn("ORDEREXECUTED") != null;
        boolean checksumNotRightSize = false;
        if (!(this.getDatabase() instanceof SQLiteDatabase)) {
            DataType type = changeLogTable.getColumn("MD5SUM").getType();
            if (type.getTypeName().toLowerCase().startsWith("varchar")) {
                Integer columnSize = type.getColumnSize();
                checksumNotRightSize = columnSize != null && columnSize < 35;
            } else {
                liquibaseColumnNotRightSize = false;
            }
        }
        boolean hasExecTypeColumn = changeLogTable.getColumn("EXECTYPE") != null;
        String charTypeName = getCharTypeName();
        boolean hasDeploymentIdColumn = changeLogTable.getColumn("DEPLOYMENT_ID") != null;
        if (!hasDescription) {
            executor.comment("Adding missing databasechangelog.description column");
            statementsToExecute.add(new AddColumnStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "DESCRIPTION", charTypeName + "(255)", null));
        }
        if (!hasTag) {
            executor.comment("Adding missing databasechangelog.tag column");
            statementsToExecute.add(new AddColumnStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "TAG", charTypeName + "(255)", null));
        }
        if (!hasComments) {
            executor.comment("Adding missing databasechangelog.comments column");
            statementsToExecute.add(new AddColumnStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "COMMENTS", charTypeName + "(255)", null));
        }
        if (!hasLiquibase) {
            executor.comment("Adding missing databasechangelog.liquibase column");
            statementsToExecute.add(new AddColumnStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "LIQUIBASE", charTypeName + "(20)", null));
        }
        if (!hasOrderExecuted) {
            executor.comment("Adding missing databasechangelog.orderexecuted column");
            statementsToExecute.add(new AddColumnStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "ORDEREXECUTED", "int", null));
            statementsToExecute.add(new UpdateStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName()).addNewColumnValue("ORDEREXECUTED", -1));
            statementsToExecute.add(new SetNullableStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "ORDEREXECUTED", "int", false));
        }
        if (checksumNotRightSize) {
            executor.comment("Modifying size of databasechangelog.md5sum column");
            statementsToExecute.add(new ModifyDataTypeStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "MD5SUM", charTypeName + "(35)"));
        }
        if (liquibaseColumnNotRightSize) {
            executor.comment("Modifying size of databasechangelog.liquibase column");
            statementsToExecute.add(new ModifyDataTypeStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "LIQUIBASE", charTypeName + "(20)"));
        }
        if (!hasExecTypeColumn) {
            executor.comment("Adding missing databasechangelog.exectype column");
            statementsToExecute.add(new AddColumnStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "EXECTYPE", charTypeName + "(10)", null));
            statementsToExecute.add(new UpdateStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName()).addNewColumnValue("EXECTYPE", "EXECUTED"));
            statementsToExecute.add(new SetNullableStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "EXECTYPE", charTypeName + "(10)", false));
        }
        if (hasContexts) {
            Integer columnSize = changeLogTable.getColumn("CONTEXTS").getType().getColumnSize();
            if (columnSize != null && columnSize < Integer.parseInt(getContextsSize())) {
                executor.comment("Modifying size of databasechangelog.contexts column");
                statementsToExecute.add(new ModifyDataTypeStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "CONTEXTS", charTypeName + "(" + getContextsSize() + ")"));
            }
        } else {
            executor.comment("Adding missing databasechangelog.contexts column");
            statementsToExecute.add(new AddColumnStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "CONTEXTS", charTypeName + "(" + getContextsSize() + ")", null));
        }
        if (hasLabels) {
            Integer columnSize = changeLogTable.getColumn("LABELS").getType().getColumnSize();
            if (columnSize != null && columnSize < Integer.parseInt(getLabelsSize())) {
                executor.comment("Modifying size of databasechangelog.labels column");
                statementsToExecute.add(new ModifyDataTypeStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "LABELS", charTypeName + "(" + getLabelsSize() + ")"));
            }
        } else {
            executor.comment("Adding missing databasechangelog.labels column");
            statementsToExecute.add(new AddColumnStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "LABELS", charTypeName + "(" + getLabelsSize() + ")", null));
        }
        if (!hasDeploymentIdColumn) {
            executor.comment("Adding missing databasechangelog.deployment_id column");
            statementsToExecute.add(new AddColumnStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "DEPLOYMENT_ID", "VARCHAR(10)", null));
            if (database instanceof DB2Database) {
                statementsToExecute.add(new ReorganizeTableStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName()));
            }
        }
        List<Map<String, ?>> md5sumRS = ExecutorService.getInstance().getExecutor(database).queryForList(new SelectFromDatabaseChangeLogStatement(new SelectFromDatabaseChangeLogStatement.ByNotNullCheckSum(), new ColumnConfig().setName("MD5SUM")).setLimit(1));
        if (md5sumRS.size() > 0) {
            String md5sum = md5sumRS.get(0).get("MD5SUM").toString();
            if (!md5sum.startsWith(CheckSum.getCurrentVersion() + ":")) {
                executor.comment("DatabaseChangeLog checksums are an incompatible version.  Setting them to null so they will be updated on next database update");
                databaseChecksumsCompatible = false;
                statementsToExecute.add(new RawSqlStatement("UPDATE " + getDatabase().escapeTableName(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName()) + " " + "SET " + getDatabase().escapeObjectName("MD5SUM", Column.class) + " = NULL"));
            }
        }
    } else if (!changeLogCreateAttempted) {
        executor.comment("Create Database Change Log Table");
        SqlStatement createTableStatement = new CreateDatabaseChangeLogTableStatement();
        if (!canCreateChangeLogTable()) {
            throw new DatabaseException("Cannot create " + getDatabase().escapeTableName(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName()) + " table for your getDatabase().\n\n" + "Please construct it manually using the following SQL as a base and re-run Liquibase:\n\n" + createTableStatement);
        }
        // If there is no table in the database for recording change history create one.
        statementsToExecute.add(createTableStatement);
        LogFactory.getLogger().info("Creating database history table with name: " + getDatabase().escapeTableName(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName()));
    }
    for (SqlStatement sql : statementsToExecute) {
        if (SqlGeneratorFactory.getInstance().supports(sql, database)) {
            executor.execute(sql);
            getDatabase().commit();
        } else {
            LogFactory.getLogger().info("Cannot run " + sql.getClass().getSimpleName() + " on " + getDatabase().getShortName() + " when checking databasechangelog table");
        }
    }
    serviceInitialized = true;
}
Also used : DB2Database(liquibase.database.core.DB2Database) ColumnConfig(liquibase.change.ColumnConfig) SqlStatement(liquibase.statement.SqlStatement) Executor(liquibase.executor.Executor) SQLiteDatabase(liquibase.database.core.SQLiteDatabase) DB2Database(liquibase.database.core.DB2Database) MSSQLDatabase(liquibase.database.core.MSSQLDatabase) Database(liquibase.database.Database) DataType(liquibase.structure.core.DataType) SnapshotControl(liquibase.snapshot.SnapshotControl) Table(liquibase.structure.core.Table) SQLiteDatabase(liquibase.database.core.SQLiteDatabase) UnexpectedLiquibaseException(liquibase.exception.UnexpectedLiquibaseException) LiquibaseException(liquibase.exception.LiquibaseException) UnexpectedLiquibaseException(liquibase.exception.UnexpectedLiquibaseException) DatabaseException(liquibase.exception.DatabaseException)

Example 17 with ColumnConfig

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

the class StandardChangeLogHistoryService method tag.

/**
     * Tags the database changelog with the given string.
     */
@Override
public void tag(final String tagString) throws DatabaseException {
    Database database = getDatabase();
    Executor executor = ExecutorService.getInstance().getExecutor(database);
    try {
        int totalRows = ExecutorService.getInstance().getExecutor(database).queryForInt(new SelectFromDatabaseChangeLogStatement(new ColumnConfig().setName("COUNT(*)", true)));
        if (totalRows == 0) {
            ChangeSet emptyChangeSet = new ChangeSet(String.valueOf(new Date().getTime()), "liquibase", false, false, "liquibase-internal", null, null, getDatabase().getObjectQuotingStrategy(), null);
            this.setExecType(emptyChangeSet, ChangeSet.ExecType.EXECUTED);
        }
        //            Timestamp lastExecutedDate = (Timestamp) this.getExecutor().queryForObject(createChangeToTagSQL(), Timestamp.class);
        executor.execute(new TagDatabaseStatement(tagString));
        getDatabase().commit();
        if (this.ranChangeSetList != null) {
            ranChangeSetList.get(ranChangeSetList.size() - 1).setTag(tagString);
        }
    } catch (Exception e) {
        throw new DatabaseException(e);
    }
}
Also used : Executor(liquibase.executor.Executor) ColumnConfig(liquibase.change.ColumnConfig) SQLiteDatabase(liquibase.database.core.SQLiteDatabase) DB2Database(liquibase.database.core.DB2Database) MSSQLDatabase(liquibase.database.core.MSSQLDatabase) Database(liquibase.database.Database) DatabaseException(liquibase.exception.DatabaseException) UnexpectedLiquibaseException(liquibase.exception.UnexpectedLiquibaseException) DatabaseHistoryException(liquibase.exception.DatabaseHistoryException) ParseException(java.text.ParseException) InvalidExampleException(liquibase.snapshot.InvalidExampleException) DatabaseException(liquibase.exception.DatabaseException) LiquibaseException(liquibase.exception.LiquibaseException)

Example 18 with ColumnConfig

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

the class SQLiteDatabase method getAlterTableStatements.

public static List<SqlStatement> getAlterTableStatements(AlterTableVisitor alterTableVisitor, Database database, String catalogName, String schemaName, String tableName) throws DatabaseException {
    List<SqlStatement> statements = new ArrayList<SqlStatement>();
    Table table = null;
    try {
        table = SnapshotGeneratorFactory.getInstance().createSnapshot((Table) new Table().setName(tableName).setSchema(new Schema(new Catalog(null), null)), database);
        List<ColumnConfig> createColumns = new ArrayList<ColumnConfig>();
        List<ColumnConfig> copyColumns = new ArrayList<ColumnConfig>();
        if (table != null) {
            for (Column column : table.getColumns()) {
                ColumnConfig new_column = new ColumnConfig(column);
                if (alterTableVisitor.createThisColumn(new_column)) {
                    createColumns.add(new_column);
                }
                ColumnConfig copy_column = new ColumnConfig(column);
                if (alterTableVisitor.copyThisColumn(copy_column)) {
                    copyColumns.add(copy_column);
                }
            }
        }
        for (ColumnConfig column : alterTableVisitor.getColumnsToAdd()) {
            if (alterTableVisitor.createThisColumn(column)) {
                createColumns.add(column);
            }
            if (alterTableVisitor.copyThisColumn(column)) {
                copyColumns.add(column);
            }
        }
        List<Index> newIndices = new ArrayList<Index>();
        for (Index index : SnapshotGeneratorFactory.getInstance().createSnapshot(new CatalogAndSchema(catalogName, schemaName), database, new SnapshotControl(database, Index.class)).get(Index.class)) {
            if (index.getTable().getName().equalsIgnoreCase(tableName)) {
                if (alterTableVisitor.createThisIndex(index)) {
                    newIndices.add(index);
                }
            }
        }
        // rename table
        String temp_table_name = tableName + "_temporary";
        statements.addAll(Arrays.asList(new RenameTableStatement(catalogName, schemaName, tableName, temp_table_name)));
        // create temporary table
        CreateTableChange ct_change_tmp = new CreateTableChange();
        ct_change_tmp.setSchemaName(schemaName);
        ct_change_tmp.setTableName(tableName);
        for (ColumnConfig column : createColumns) {
            ct_change_tmp.addColumn(column);
        }
        statements.addAll(Arrays.asList(ct_change_tmp.generateStatements(database)));
        // copy rows to temporary table
        statements.addAll(Arrays.asList(new CopyRowsStatement(temp_table_name, tableName, copyColumns)));
        // delete original table
        statements.addAll(Arrays.asList(new DropTableStatement(catalogName, schemaName, temp_table_name, false)));
        // validate indices
        statements.addAll(Arrays.asList(new ReindexStatement(catalogName, schemaName, tableName)));
        // add remaining indices
        for (Index index_config : newIndices) {
            AddColumnConfig[] columns = new AddColumnConfig[index_config.getColumns().size()];
            for (int i = 0; i < index_config.getColumns().size(); i++) {
                columns[i] = new AddColumnConfig(index_config.getColumns().get(i));
            }
            statements.addAll(Arrays.asList(new CreateIndexStatement(index_config.getName(), catalogName, schemaName, tableName, index_config.isUnique(), index_config.getAssociatedWithAsString(), columns)));
        }
        return statements;
    } catch (InvalidExampleException e) {
        throw new UnexpectedLiquibaseException(e);
    }
}
Also used : ColumnConfig(liquibase.change.ColumnConfig) AddColumnConfig(liquibase.change.AddColumnConfig) CatalogAndSchema(liquibase.CatalogAndSchema) SqlStatement(liquibase.statement.SqlStatement) InvalidExampleException(liquibase.snapshot.InvalidExampleException) SnapshotControl(liquibase.snapshot.SnapshotControl) CatalogAndSchema(liquibase.CatalogAndSchema) CreateTableChange(liquibase.change.core.CreateTableChange) AddColumnConfig(liquibase.change.AddColumnConfig) UnexpectedLiquibaseException(liquibase.exception.UnexpectedLiquibaseException)

Example 19 with ColumnConfig

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

the class YamlChangeLogSerializerTest method serialize__change.

@Test
public void serialize__change() {
    ChangeSet changeSet = new ChangeSet("test1", "nvoxland", false, true, "/test/me.txt", null, null, null);
    CreateTableChange change = new CreateTableChange();
    change.setTableName("testTable");
    change.addColumn(new ColumnConfig().setName("id").setType("int"));
    change.addColumn(new ColumnConfig().setName("name").setType("varchar(255)"));
    changeSet.addChange(change);
    String out = new YamlChangeLogSerializer().serialize(changeSet, false);
    System.out.println(out);
}
Also used : ColumnConfig(liquibase.change.ColumnConfig) CreateTableChange(liquibase.change.core.CreateTableChange) ChangeSet(liquibase.changelog.ChangeSet) Test(org.junit.Test)

Example 20 with ColumnConfig

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

the class XMLChangeLogSerializerTest method createNode_InsertDataChange.

@Test
public void createNode_InsertDataChange() throws Exception {
    InsertDataChange refactoring = new InsertDataChange();
    refactoring.setTableName("TABLE_NAME");
    ColumnConfig col1 = new ColumnConfig();
    col1.setName("id");
    col1.setValueNumeric("123");
    ColumnConfig col2 = new ColumnConfig();
    col2.setName("name");
    col2.setValue("Andrew");
    ColumnConfig col3 = new ColumnConfig();
    col3.setName("age");
    col3.setValueNumeric("21");
    ColumnConfig col4 = new ColumnConfig();
    col4.setName("height");
    col4.setValueNumeric("1.78");
    refactoring.addColumn(col1);
    refactoring.addColumn(col2);
    refactoring.addColumn(col3);
    refactoring.addColumn(col4);
    Element node = new XMLChangeLogSerializer(DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument()).createNode(refactoring);
    assertEquals("insert", node.getTagName());
    assertEquals("TABLE_NAME", node.getAttribute("tableName"));
    NodeList columns = node.getChildNodes();
    assertEquals(4, columns.getLength());
    assertEquals("column", ((Element) columns.item(0)).getTagName());
    assertEquals("id", ((Element) columns.item(0)).getAttribute("name"));
    assertEquals("123", ((Element) columns.item(0)).getAttribute("valueNumeric"));
    assertEquals("column", ((Element) columns.item(1)).getTagName());
    assertEquals("name", ((Element) columns.item(1)).getAttribute("name"));
    assertEquals("Andrew", ((Element) columns.item(1)).getAttribute("value"));
    assertEquals("column", ((Element) columns.item(2)).getTagName());
    assertEquals("age", ((Element) columns.item(2)).getAttribute("name"));
    assertEquals("21", ((Element) columns.item(2)).getAttribute("valueNumeric"));
    assertEquals("column", ((Element) columns.item(3)).getTagName());
    assertEquals("height", ((Element) columns.item(3)).getAttribute("name"));
    assertEquals("1.78", ((Element) columns.item(3)).getAttribute("valueNumeric"));
}
Also used : ColumnConfig(liquibase.change.ColumnConfig) AddColumnConfig(liquibase.change.AddColumnConfig) Element(org.w3c.dom.Element) NodeList(org.w3c.dom.NodeList) Test(org.junit.Test)

Aggregations

ColumnConfig (liquibase.change.ColumnConfig)28 Test (org.junit.Test)14 UnexpectedLiquibaseException (liquibase.exception.UnexpectedLiquibaseException)6 AddColumnConfig (liquibase.change.AddColumnConfig)5 CreateTableChange (liquibase.change.core.CreateTableChange)5 MSSQLDatabase (liquibase.database.core.MSSQLDatabase)5 SQLiteDatabase (liquibase.database.core.SQLiteDatabase)5 DatabaseException (liquibase.exception.DatabaseException)5 Sql (liquibase.sql.Sql)5 PostgresDatabase (liquibase.database.core.PostgresDatabase)4 SqlStatement (liquibase.statement.SqlStatement)4 ArrayList (java.util.ArrayList)3 ConstraintsConfig (liquibase.change.ConstraintsConfig)3 Database (liquibase.database.Database)3 DB2Database (liquibase.database.core.DB2Database)3 MySQLDatabase (liquibase.database.core.MySQLDatabase)3 UnparsedSql (liquibase.sql.UnparsedSql)3 AddUniqueConstraintStatement (liquibase.statement.core.AddUniqueConstraintStatement)3 Column (liquibase.structure.core.Column)3 IOException (java.io.IOException)2