Search in sources :

Example 21 with Table

use of liquibase.structure.core.Table in project liquibase by liquibase.

the class UniqueConstraintComparator method hash.

@Override
public String[] hash(DatabaseObject databaseObject, Database accordingTo, DatabaseObjectComparatorChain chain) {
    List<String> hashes = new ArrayList<String>();
    if (databaseObject.getName() != null) {
        hashes.add(databaseObject.getName().toLowerCase());
    }
    Table table = ((UniqueConstraint) databaseObject).getTable();
    if (table != null) {
        hashes.addAll(Arrays.asList(DatabaseObjectComparatorFactory.getInstance().hash(table, chain.getSchemaComparisons(), accordingTo)));
    }
    return hashes.toArray(new String[hashes.size()]);
}
Also used : Table(liquibase.structure.core.Table) ArrayList(java.util.ArrayList) UniqueConstraint(liquibase.structure.core.UniqueConstraint)

Example 22 with Table

use of liquibase.structure.core.Table in project liquibase by liquibase.

the class MissingTableChangeGenerator method fixMissing.

@Override
public Change[] fixMissing(DatabaseObject missingObject, DiffOutputControl control, Database referenceDatabase, Database comparisonDatabase, ChangeGeneratorChain chain) {
    Table missingTable = (Table) missingObject;
    PrimaryKey primaryKey = missingTable.getPrimaryKey();
    //        if (control.diffResult.getReferenceSnapshot().getDatabase().isLiquibaseTable(missingTable.getSchema().toCatalogAndSchema(), missingTable.getName())) {
    //            continue;
    //        }
    CreateTableChange change = createCreateTableChange();
    change.setTableName(missingTable.getName());
    if (control.getIncludeCatalog()) {
        change.setCatalogName(missingTable.getSchema().getCatalogName());
    }
    if (control.getIncludeSchema()) {
        change.setSchemaName(missingTable.getSchema().getName());
    }
    if (missingTable.getRemarks() != null) {
        change.setRemarks(missingTable.getRemarks());
    }
    for (Column column : missingTable.getColumns()) {
        ColumnConfig columnConfig = new ColumnConfig();
        columnConfig.setName(column.getName());
        LiquibaseDataType ldt = DataTypeFactory.getInstance().from(column.getType(), referenceDatabase);
        DatabaseDataType ddt = ldt.toDatabaseDataType(comparisonDatabase);
        String typeString = ddt.toString();
        if (comparisonDatabase instanceof MSSQLDatabase) {
            typeString = comparisonDatabase.unescapeDataTypeString(typeString);
        }
        columnConfig.setType(typeString);
        if (column.isAutoIncrement()) {
            columnConfig.setAutoIncrement(true);
        }
        ConstraintsConfig constraintsConfig = null;
        // In MySQL, the primary key must be specified at creation for an autoincrement column
        if (column.isAutoIncrement() && primaryKey != null && primaryKey.getColumns().size() == 1 && primaryKey.getColumnNamesAsList().contains(column.getName())) {
            if (referenceDatabase instanceof MSSQLDatabase && primaryKey.getBackingIndex() != null && primaryKey.getBackingIndex().getClustered() != null && !primaryKey.getBackingIndex().getClustered()) {
            // have to handle PK as a separate statement
            } else if (referenceDatabase instanceof PostgresDatabase && primaryKey.getBackingIndex() != null && primaryKey.getBackingIndex().getClustered() != null && primaryKey.getBackingIndex().getClustered()) {
            // have to handle PK as a separate statement
            } else {
                constraintsConfig = new ConstraintsConfig();
                if (shouldAddPrimarykeyToConstraints(missingObject, control, referenceDatabase, comparisonDatabase)) {
                    constraintsConfig.setPrimaryKey(true);
                    constraintsConfig.setPrimaryKeyTablespace(primaryKey.getTablespace());
                    // MySQL sets some primary key names as PRIMARY which is invalid
                    if (comparisonDatabase instanceof MySQLDatabase && "PRIMARY".equals(primaryKey.getName())) {
                        constraintsConfig.setPrimaryKeyName(null);
                    } else {
                        constraintsConfig.setPrimaryKeyName(primaryKey.getName());
                    }
                    control.setAlreadyHandledMissing(primaryKey);
                    control.setAlreadyHandledMissing(primaryKey.getBackingIndex());
                } else {
                    constraintsConfig.setNullable(false);
                }
            }
        } else if (column.isNullable() != null && !column.isNullable()) {
            constraintsConfig = new ConstraintsConfig();
            constraintsConfig.setNullable(false);
        }
        if (constraintsConfig != null) {
            columnConfig.setConstraints(constraintsConfig);
        }
        setDefaultValue(columnConfig, column, referenceDatabase);
        if (column.getRemarks() != null) {
            columnConfig.setRemarks(column.getRemarks());
        }
        if (column.getAutoIncrementInformation() != null) {
            BigInteger startWith = column.getAutoIncrementInformation().getStartWith();
            BigInteger incrementBy = column.getAutoIncrementInformation().getIncrementBy();
            if (startWith != null && !startWith.equals(BigInteger.ONE)) {
                columnConfig.setStartWith(startWith);
            }
            if (incrementBy != null && !incrementBy.equals(BigInteger.ONE)) {
                columnConfig.setIncrementBy(incrementBy);
            }
        }
        change.addColumn(columnConfig);
        control.setAlreadyHandledMissing(column);
    }
    return new Change[] { change };
}
Also used : Table(liquibase.structure.core.Table) ColumnConfig(liquibase.change.ColumnConfig) LiquibaseDataType(liquibase.datatype.LiquibaseDataType) PrimaryKey(liquibase.structure.core.PrimaryKey) MySQLDatabase(liquibase.database.core.MySQLDatabase) Change(liquibase.change.Change) CreateTableChange(liquibase.change.core.CreateTableChange) PostgresDatabase(liquibase.database.core.PostgresDatabase) DatabaseDataType(liquibase.datatype.DatabaseDataType) Column(liquibase.structure.core.Column) CreateTableChange(liquibase.change.core.CreateTableChange) ConstraintsConfig(liquibase.change.ConstraintsConfig) BigInteger(java.math.BigInteger) MSSQLDatabase(liquibase.database.core.MSSQLDatabase)

Example 23 with Table

use of liquibase.structure.core.Table in project liquibase by liquibase.

the class StandardLockService method destroy.

@Override
public void destroy() throws DatabaseException {
    try {
        if (SnapshotGeneratorFactory.getInstance().has(new Table().setName(database.getDatabaseChangeLogLockTableName()).setSchema(database.getLiquibaseCatalogName(), database.getLiquibaseSchemaName()), database)) {
            ExecutorService.getInstance().getExecutor(database).execute(new DropTableStatement(database.getLiquibaseCatalogName(), database.getLiquibaseSchemaName(), database.getDatabaseChangeLogLockTableName(), false));
            hasDatabaseChangeLogLockTable = null;
        }
        reset();
    } catch (InvalidExampleException e) {
        throw new UnexpectedLiquibaseException(e);
    }
}
Also used : InvalidExampleException(liquibase.snapshot.InvalidExampleException) Table(liquibase.structure.core.Table) UnexpectedLiquibaseException(liquibase.exception.UnexpectedLiquibaseException)

Example 24 with Table

use of liquibase.structure.core.Table in project liquibase by liquibase.

the class ColumnExistsPrecondition method checkFast.

private void checkFast(Database database, DatabaseChangeLog changeLog) throws PreconditionFailedException, PreconditionErrorException {
    Statement statement = null;
    try {
        statement = ((JdbcConnection) database.getConnection()).createStatement();
        String schemaName = getSchemaName();
        if (schemaName == null) {
            schemaName = database.getDefaultSchemaName();
        }
        String tableName = getTableName();
        String columnName = getColumnName();
        if (database instanceof PostgresDatabase) {
            String sql = "SELECT 1 FROM pg_attribute a WHERE EXISTS (SELECT 1 FROM pg_class JOIN pg_catalog.pg_namespace ns ON ns.oid = pg_class.relnamespace WHERE lower(ns.nspname)='" + schemaName.toLowerCase() + "' AND lower(relname) = lower('" + tableName + "') AND pg_class.oid = a.attrelid) AND lower(a.attname) = lower('" + columnName + "');";
            try {
                ResultSet rs = statement.executeQuery(sql);
                try {
                    if (rs.next()) {
                        return;
                    } else {
                        // column or table does not exist
                        throw new PreconditionFailedException(format("Column %s.%s.%s does not exist", schemaName, tableName, columnName), changeLog, this);
                    }
                } finally {
                    rs.close();
                }
            } catch (SQLException e) {
                throw new PreconditionErrorException(e, changeLog, this);
            }
        }
        try {
            String sql = format("select t.%s from %s.%s t where 0=1", database.escapeColumnNameList(columnName), database.escapeObjectName(schemaName, Schema.class), database.escapeObjectName(tableName, Table.class));
            statement.executeQuery(sql).close();
            // column exists
            return;
        } catch (SQLException e) {
            // column or table does not exist
            throw new PreconditionFailedException(format("Column %s.%s.%s does not exist", schemaName, tableName, columnName), changeLog, this);
        }
    } catch (DatabaseException e) {
        throw new PreconditionErrorException(e, changeLog, this);
    } finally {
        JdbcUtils.closeStatement(statement);
    }
}
Also used : PostgresDatabase(liquibase.database.core.PostgresDatabase) Table(liquibase.structure.core.Table) SQLException(java.sql.SQLException) Statement(java.sql.Statement) Schema(liquibase.structure.core.Schema) ResultSet(java.sql.ResultSet)

Example 25 with Table

use of liquibase.structure.core.Table in project liquibase by liquibase.

the class ForeignKeyExistsPrecondition method check.

@Override
public void check(Database database, DatabaseChangeLog changeLog, ChangeSet changeSet) throws PreconditionFailedException, PreconditionErrorException {
    try {
        ForeignKey example = new ForeignKey();
        example.setName(getForeignKeyName());
        example.setForeignKeyTable(new Table());
        if (StringUtils.trimToNull(getForeignKeyTableName()) != null) {
            example.getForeignKeyTable().setName(getForeignKeyTableName());
        }
        example.getForeignKeyTable().setSchema(new Schema(getCatalogName(), getSchemaName()));
        if (!SnapshotGeneratorFactory.getInstance().has(example, database)) {
            throw new PreconditionFailedException("Foreign Key " + database.escapeIndexName(catalogName, schemaName, foreignKeyName) + " does not exist", changeLog, this);
        }
    } catch (PreconditionFailedException e) {
        throw e;
    } catch (Exception e) {
        throw new PreconditionErrorException(e, changeLog, this);
    }
}
Also used : Table(liquibase.structure.core.Table) Schema(liquibase.structure.core.Schema) ForeignKey(liquibase.structure.core.ForeignKey)

Aggregations

Table (liquibase.structure.core.Table)28 Column (liquibase.structure.core.Column)13 Schema (liquibase.structure.core.Schema)7 DatabaseException (liquibase.exception.DatabaseException)5 UnexpectedLiquibaseException (liquibase.exception.UnexpectedLiquibaseException)5 SnapshotControl (liquibase.snapshot.SnapshotControl)5 MSSQLDatabase (liquibase.database.core.MSSQLDatabase)4 DatabaseSnapshot (liquibase.snapshot.DatabaseSnapshot)4 ArrayList (java.util.ArrayList)3 Liquibase (liquibase.Liquibase)3 Change (liquibase.change.Change)3 PostgresDatabase (liquibase.database.core.PostgresDatabase)3 EmptyDatabaseSnapshot (liquibase.snapshot.EmptyDatabaseSnapshot)3 ForeignKey (liquibase.structure.core.ForeignKey)3 PrimaryKey (liquibase.structure.core.PrimaryKey)3 Test (org.junit.Test)3 ResultSet (java.sql.ResultSet)2 SQLException (java.sql.SQLException)2 Statement (java.sql.Statement)2 Date (java.util.Date)2