Search in sources :

Example 1 with Table

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

the class AddColumnChange method checkStatus.

@Override
public ChangeStatus checkStatus(Database database) {
    ChangeStatus result = new ChangeStatus();
    try {
        for (AddColumnConfig column : getColumns()) {
            Column snapshot = SnapshotGeneratorFactory.getInstance().createSnapshot(new Column(Table.class, getCatalogName(), getSchemaName(), getTableName(), column.getName()), database);
            result.assertComplete(snapshot != null, "Column " + column.getName() + " does not exist");
            if (snapshot != null) {
                PrimaryKey snapshotPK = ((Table) snapshot.getRelation()).getPrimaryKey();
                ConstraintsConfig constraints = column.getConstraints();
                if (constraints != null) {
                    result.assertComplete(constraints.isPrimaryKey() == (snapshotPK != null && snapshotPK.getColumnNames().contains(column.getName())), "Column " + column.getName() + " not set as primary key");
                }
            }
        }
    } catch (Exception e) {
        return result.unknown(e);
    }
    return result;
}
Also used : Table(liquibase.structure.core.Table) Column(liquibase.structure.core.Column) PrimaryKey(liquibase.structure.core.PrimaryKey)

Example 2 with Table

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

the class CreateTableChange method checkStatus.

@Override
public ChangeStatus checkStatus(Database database) {
    try {
        Table example = (Table) new Table().setName(getTableName()).setSchema(getCatalogName(), getSchemaName());
        ChangeStatus status = new ChangeStatus();
        Table tableSnapshot = SnapshotGeneratorFactory.getInstance().createSnapshot(example, database);
        status.assertComplete(tableSnapshot != null, "Table does not exist");
        if (tableSnapshot != null) {
            for (ColumnConfig columnConfig : getColumns()) {
                Column columnSnapshot = SnapshotGeneratorFactory.getInstance().createSnapshot(new Column(columnConfig).setRelation(tableSnapshot), database);
                status.assertCorrect(columnSnapshot != null, "Column " + columnConfig.getName() + " is missing");
                if (columnSnapshot != null) {
                    ConstraintsConfig constraints = columnConfig.getConstraints();
                    if (constraints != null) {
                        if (constraints.isPrimaryKey() != null && constraints.isPrimaryKey()) {
                            PrimaryKey tablePk = tableSnapshot.getPrimaryKey();
                            status.assertCorrect(tablePk != null && tablePk.getColumnNamesAsList().contains(columnConfig.getName()), "Column " + columnConfig.getName() + " is not part of the primary key");
                        }
                        if (constraints.isNullable() != null) {
                            if (constraints.isNullable()) {
                                status.assertCorrect(columnSnapshot.isNullable() == null || columnSnapshot.isNullable(), "Column " + columnConfig.getName() + " nullability does not match");
                            } else {
                                status.assertCorrect(columnSnapshot.isNullable() != null && !columnSnapshot.isNullable(), "Column " + columnConfig.getName() + " nullability does not match");
                            }
                        }
                    }
                }
            }
        }
        return status;
    } catch (Exception e) {
        return new ChangeStatus().unknown(e);
    }
}
Also used : Table(liquibase.structure.core.Table) Column(liquibase.structure.core.Column) PrimaryKey(liquibase.structure.core.PrimaryKey) ParseException(java.text.ParseException)

Example 3 with Table

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

the class ChangedTableChangeGenerator method fixChanged.

@Override
public Change[] fixChanged(DatabaseObject changedObject, ObjectDifferences differences, DiffOutputControl control, Database referenceDatabase, final Database comparisonDatabase, ChangeGeneratorChain chain) {
    Table table = (Table) changedObject;
    Difference changedRemarks = differences.getDifference("remarks");
    if (changedRemarks != null) {
        SetTableRemarksChange change = new SetTableRemarksChange();
        if (control.getIncludeCatalog()) {
            change.setCatalogName(table.getSchema().getCatalogName());
        }
        if (control.getIncludeSchema()) {
            change.setSchemaName(table.getSchema().getName());
        }
        change.setTableName(table.getName());
        change.setRemarks(table.getRemarks());
        return new Change[] { change };
    }
    return null;
}
Also used : Table(liquibase.structure.core.Table) Difference(liquibase.diff.Difference) SetTableRemarksChange(liquibase.change.core.SetTableRemarksChange) Change(liquibase.change.Change) SetTableRemarksChange(liquibase.change.core.SetTableRemarksChange)

Example 4 with Table

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

the class MissingDataExternalFileChangeGenerator 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(100);
        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));
        }
        String fileName = table.getName().toLowerCase() + ".csv";
        if (dataDir != null) {
            fileName = dataDir + "/" + fileName;
            File parentDir = new File(dataDir);
            if (!parentDir.exists()) {
                parentDir.mkdirs();
            }
            if (!parentDir.isDirectory()) {
                throw new RuntimeException(parentDir + " is not a directory");
            }
        }
        CSVWriter outputFile = new CSVWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName), LiquibaseConfiguration.getInstance().getConfiguration(GlobalConfiguration.class).getOutputEncoding())));
        String[] dataTypes = new String[columnNames.size()];
        String[] line = new String[columnNames.size()];
        for (int i = 0; i < columnNames.size(); i++) {
            line[i] = columnNames.get(i);
        }
        outputFile.writeNext(line);
        int rowNum = 0;
        while (rs.next()) {
            line = new String[columnNames.size()];
            for (int i = 0; i < columnNames.size(); i++) {
                Object value = JdbcUtils.getResultSetValue(rs, i + 1);
                if (dataTypes[i] == null && value != null) {
                    if (value instanceof Number) {
                        dataTypes[i] = "NUMERIC";
                    } else if (value instanceof Boolean) {
                        dataTypes[i] = "BOOLEAN";
                    } else if (value instanceof Date) {
                        dataTypes[i] = "DATE";
                    } else {
                        dataTypes[i] = "STRING";
                    }
                }
                if (value == null) {
                    line[i] = "NULL";
                } else {
                    if (value instanceof Date) {
                        line[i] = new ISODateFormat().format(((Date) value));
                    } else {
                        line[i] = value.toString();
                    }
                }
            }
            outputFile.writeNext(line);
            rowNum++;
            if (rowNum % 5000 == 0) {
                outputFile.flush();
            }
        }
        outputFile.flush();
        outputFile.close();
        LoadDataChange change = new LoadDataChange();
        change.setFile(fileName);
        change.setEncoding(LiquibaseConfiguration.getInstance().getConfiguration(GlobalConfiguration.class).getOutputEncoding());
        if (outputControl.getIncludeCatalog()) {
            change.setCatalogName(table.getSchema().getCatalogName());
        }
        if (outputControl.getIncludeSchema()) {
            change.setSchemaName(table.getSchema().getName());
        }
        change.setTableName(table.getName());
        for (int i = 0; i < columnNames.size(); i++) {
            String colName = columnNames.get(i);
            LoadDataColumnConfig columnConfig = new LoadDataColumnConfig();
            columnConfig.setHeader(colName);
            columnConfig.setName(colName);
            columnConfig.setType(dataTypes[i]);
            change.addColumn(columnConfig);
        }
        return new Change[] { change };
    } 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 : SQLException(java.sql.SQLException) ArrayList(java.util.ArrayList) CSVWriter(liquibase.util.csv.CSVWriter) BufferedWriter(java.io.BufferedWriter) ISODateFormat(liquibase.util.ISODateFormat) ResultSet(java.sql.ResultSet) LoadDataColumnConfig(liquibase.change.core.LoadDataColumnConfig) LoadDataChange(liquibase.change.core.LoadDataChange) Table(liquibase.structure.core.Table) Statement(java.sql.Statement) Data(liquibase.structure.core.Data) Change(liquibase.change.Change) LoadDataChange(liquibase.change.core.LoadDataChange) Date(java.util.Date) SQLException(java.sql.SQLException) UnexpectedLiquibaseException(liquibase.exception.UnexpectedLiquibaseException) FileOutputStream(java.io.FileOutputStream) OutputStreamWriter(java.io.OutputStreamWriter) DatabaseObject(liquibase.structure.DatabaseObject) File(java.io.File) UnexpectedLiquibaseException(liquibase.exception.UnexpectedLiquibaseException)

Example 5 with Table

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

the class IndexComparator 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 = ((Index) 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) Index(liquibase.structure.core.Index)

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