Java Code Examples for liquibase.structure.core.Column

The following examples show how to use liquibase.structure.core.Column. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
@Override
public boolean isLiquibaseObject(final DatabaseObject object) {
    if (object instanceof Table) {
        Schema liquibaseSchema = new Schema(getLiquibaseCatalogName(), getLiquibaseSchemaName());
        if (DatabaseObjectComparatorFactory.getInstance().isSameObject(object, new Table().setName(getDatabaseChangeLogTableName()).setSchema(liquibaseSchema), null, this)) {
            return true;
        }
        return DatabaseObjectComparatorFactory.getInstance().isSameObject(object, new Table().setName(getDatabaseChangeLogLockTableName()).setSchema(liquibaseSchema), null, this);
    } else if (object instanceof Column) {
        return isLiquibaseObject(((Column) object).getRelation());
    } else if (object instanceof Index) {
        return isLiquibaseObject(((Index) object).getRelation());
    } else if (object instanceof PrimaryKey) {
        return isLiquibaseObject(((PrimaryKey) object).getTable());
    }
    return false;
}
 
Example 2
@Override
public String escapeColumnNameList(final String columnNames) {
    StringBuilder sb = new StringBuilder();
    for (String columnName : StringUtils.splitAndTrim(columnNames, ",")) {
        if (sb.length() > 0) {
            sb.append(", ");
        }
        boolean descending = false;
        if (columnName.matches("(?i).*\\s+DESC")) {
            columnName = columnName.replaceFirst("(?i)\\s+DESC$", "");
            descending = true;
        } else if (columnName.matches("(?i).*\\s+ASC")) {
            columnName = columnName.replaceFirst("(?i)\\s+ASC$", "");
        }
        sb.append(escapeObjectName(columnName, Column.class));
        if (descending) {
            sb.append(" DESC");
        }
    }
    return sb.toString();
}
 
Example 3
@Override
public Sql[] generateSql(RemoveChangeSetRanStatusStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
    ChangeSet changeSet = statement.getChangeSet();
    String tmpTable = UUID.randomUUID().toString().replaceAll("-", "");
    String catalogName = database.getLiquibaseCatalogName();
    String schemaName = database.getDefaultSchemaName();
    String tableName = database.getDatabaseChangeLogTableName();
    CreateTableAsSelectStatement createTableAsSelectStatement = new CreateTableAsSelectStatement(catalogName, schemaName, tableName, tmpTable)
            .addColumnNames("ID", "AUTHOR", "FILENAME", "DATEEXECUTED", "ORDEREXECUTED", "EXECTYPE", "MD5SUM", "DESCRIPTION", "COMMENTS", "TAG", "LIQUIBASE", "CONTEXTS", "LABELS", "DEPLOYMENT_ID")
            .setWhereCondition(database.escapeObjectName("ID", Column.class) + " != ? " +
                    "AND " + database.escapeObjectName("FILENAME", Column.class) + " != ?")
            .addWhereParameters(changeSet.getId(), changeSet.getFilePath());

    return CustomSqlGenerator.generateSql(database,
            createTableAsSelectStatement,
            new DropTableStatement(catalogName, schemaName, tableName, false),
            new RenameTableStatement(catalogName, schemaName, tmpTable, tableName));
}
 
Example 4
Source Project: liquibase-impala   Source File: HiveTagDatabaseGenerator.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Sql[] generateSql(TagDatabaseStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
    String catalogName = database.getLiquibaseCatalogName();
    String schemaName = database.getDefaultSchemaName();
    String tableName = database.getDatabaseChangeLogTableName();
    String tableNameEscaped = database.escapeObjectName(tableName, Table.class);
    String dateColumnNameEscaped = database.escapeObjectName("DATEEXECUTED", Column.class);
    String tagColumnNameEscaped = database.escapeObjectName("TAG", Column.class);
    String tempTable = UUID.randomUUID().toString().replaceAll("-", "");
    CreateTableAsSelectStatement createTableAsSelectStatement = new CreateTableAsSelectStatement(catalogName, schemaName, tableName, tempTable)
            .addColumnNames("ID", "AUTHOR", "FILENAME", "DATEEXECUTED", "ORDEREXECUTED", "EXECTYPE", "MD5SUM", "DESCRIPTION", "COMMENTS", "TAG", "LIQUIBASE", "CONTEXTS", "LABELS", "DEPLOYMENT_ID")
            .setWhereCondition(tableNameEscaped + "." + dateColumnNameEscaped + " NOT IN (SELECT MAX(" + tableNameEscaped + "." + dateColumnNameEscaped + ") " +
                    "FROM " + tableNameEscaped + ")");
    InsertAsSelectStatement insertAsSelectStatement = new InsertAsSelectStatement(catalogName, schemaName, tableName, tempTable)
            .addColumnNames("ID", "AUTHOR", "FILENAME", "DATEEXECUTED", "ORDEREXECUTED", "EXECTYPE", "MD5SUM", "DESCRIPTION", "COMMENTS", "'" + statement.getTag() + "'", "LIQUIBASE", "CONTEXTS", "LABELS", "DEPLOYMENT_ID")
            .setWhereCondition(tableNameEscaped + "." + dateColumnNameEscaped + " IN (SELECT MAX(" + tableNameEscaped + "." + dateColumnNameEscaped + ") FROM " + tableNameEscaped + ") AND ("
                    + tableNameEscaped + "." + tagColumnNameEscaped + " IS NULL OR " + tableNameEscaped + "." + tagColumnNameEscaped + " != ?)").addWhereParameters(statement.getTag());

    return CustomSqlGenerator.generateSql(database,
            createTableAsSelectStatement,
            insertAsSelectStatement,
            new DropTableStatement(catalogName, schemaName, tableName, false),
            new RenameTableStatement(catalogName, schemaName, tempTable, tableName));
}
 
Example 5
@Override
public Sql[] generateSql(RemoveChangeSetRanStatusStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
    ChangeSet changeSet = statement.getChangeSet();
    String tmpTable = UUID.randomUUID().toString().replaceAll("-", "");
    String catalogName = database.getLiquibaseCatalogName();
    String schemaName = database.getDefaultSchemaName();
    String tableName = database.getDatabaseChangeLogTableName();
    CreateTableAsSelectStatement createTableAsSelectStatement = new CreateTableAsSelectStatement(catalogName, schemaName, tableName, tmpTable)
            .addColumnNames("ID", "AUTHOR", "FILENAME", "DATEEXECUTED", "ORDEREXECUTED", "EXECTYPE", "MD5SUM", "DESCRIPTION", "COMMENTS", "TAG", "LIQUIBASE", "CONTEXTS", "LABELS", "DEPLOYMENT_ID")
            .setWhereCondition(" NOT (" + database.escapeObjectName("ID", Column.class) + " = ? " +
                    "AND " + database.escapeObjectName("FILENAME", Column.class) + " = ?)")
            .addWhereParameters(changeSet.getId(), changeSet.getFilePath());

    return CustomSqlGenerator.generateSql(database,
            UserSessionSettings.syncDdlStart(),
            createTableAsSelectStatement,
            new DropTableStatement(catalogName, schemaName, tableName, false),
            new RenameTableStatement(catalogName, schemaName, tmpTable, tableName),
            UserSessionSettings.syncDdlStop());
}
 
Example 6
/**
 * Generates the SQL for inserting the necessary record into the
 * <code>USER_SDO_GEOM_METADATA</code> table. This record must be present prior to creating the
 * spatial index.
 * 
 * @param statement
 *           the create spatial index statement.
 * @param database
 *           the database instance.
 * @return the SQL to insert the metadata record.
 */
protected String generateInsertMetadataSql(final CreateSpatialIndexStatement statement,
      final Database database) {
   final StringBuilder sql = new StringBuilder();
   sql.append("INSERT INTO user_sdo_geom_metadata ");
   sql.append("(table_name, column_name, diminfo, srid) ");
   final String tableName = statement.getTableName().trim();
   sql.append("VALUES ('").append(database.correctObjectName(tableName, Table.class));
   final String columnName = statement.getColumns()[0].trim();
   sql.append("', '").append(database.correctObjectName(columnName, Column.class));
   sql.append("', SDO_DIM_ARRAY(");
   sql.append("SDO_DIM_ELEMENT('Longitude', -180, 180, 0.005), ");
   sql.append("SDO_DIM_ELEMENT('Latitude', -90, 90, 0.005))");
   final Integer srid = statement.getSrid();
   if (srid == null) {
      sql.append(", NULL");
   } else {
      sql.append(", ").append(OracleSpatialUtils.EPSG_TO_ORACLE_FUNCTION).append("(")
            .append(srid).append(")");
   }
   sql.append(")");
   return sql.toString();
}
 
Example 7
@Override
public Sql[] generateSql(final DropColumnStatement statement, final Database database,
      final SqlGeneratorChain sqlGeneratorChain) {

   String schemaName = statement.getSchemaName();
   if (schemaName == null) {
      schemaName = database.getDefaultSchemaName();
   }
   final String tableName = statement.getTableName();
   final String columnName = statement.getColumnName();
   final boolean isGeometryColumn = GeometryColumnsUtils.isGeometryColumn(database, schemaName,
         tableName, columnName);
   final List<Sql> list = new ArrayList<Sql>();
   if (isGeometryColumn) {
      dropSpatialIndexIfExists(statement.getCatalogName(), schemaName, tableName, database, list);
      final String sql = "CALL DropGeometryColumn('" + schemaName + "', '" + tableName + "', '"
            + columnName + "')";
      final Column column = getAffectedColumn(statement);
      final Sql dropGeometryColumn = new UnparsedSql(sql, column);
      list.add(dropGeometryColumn);
   } else {
      list.addAll(Arrays.asList(sqlGeneratorChain.generateSql(statement, database)));
   }
   return list.toArray(new Sql[list.size()]);
}
 
Example 8
/**
 * Generates the {@link Index} example (taken from {@link IndexExistsPrecondition}).
 *
 * @param database
 *           the database instance.
 * @param schema
 *           the schema instance.
 * @param tableName
 *           the table name of the index.
 * @return the index example.
 */
protected Index getIndexExample(final Database database, final Schema schema,
      final String tableName) {
   final Index example = new Index();
   if (tableName != null) {
      example.setTable((Table) new Table().setName(
            database.correctObjectName(getTableName(), Table.class)).setSchema(schema));
   }
   example.setName(database.correctObjectName(getIndexName(), Index.class));
   if (StringUtils.trimToNull(getColumnNames()) != null) {
      for (final String columnName : getColumnNames().split("\\s*,\\s*")) {
         final Column column = new Column(database.correctObjectName(columnName, Column.class));
         example.getColumns().add(column);
      }
   }
   return example;
}
 
Example 9
@Override
public void check(Database database) throws CustomPreconditionFailedException, CustomPreconditionErrorException {
    Column column = new Column(this.columnNames);
    UniqueConstraint uniqueConstraint = new UniqueConstraint(this.constraintName, null, null, this.tableName, column);
    boolean markFailed = false;
    try {
        if (!SnapshotGeneratorFactory.getInstance().has(uniqueConstraint, database)) {
            markFailed = true;
        }
    } catch (Exception e) {
        throw new CustomPreconditionErrorException("custom precondition check errored", e);
    }

    if (markFailed) {
        throw new CustomPreconditionFailedException(this.constraintName + " doesn't exist");
    }
}
 
Example 10
@Override
public String escapeColumnName(String catalogName, String schemaName, String tableName, String columnName, boolean quoteNamesThatMayBeFunctions) {
    if (quotingStrategy == ObjectQuotingStrategy.QUOTE_ALL_OBJECTS) {
        return quoteObject(columnName, Column.class);
    }

    if (columnName.contains("(")) {
        if (quoteNamesThatMayBeFunctions) {
            return quoteObject(columnName, Column.class);
        } else {
            return columnName;
        }
    }
    return escapeObjectName(columnName, Column.class);
}
 
Example 11
Source Project: liquibase-impala   Source File: HiveDropColumnGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private Sql[] generateMultipleColumnSql(DropColumnStatement dropColumnStatement, Database database, Map<String, String> columnsPreserved) {
    if (columnsPreserved == null) {
        throw new UnexpectedLiquibaseException("no columns to preserve");
    }
    List<Sql> result = new ArrayList<Sql>();
    Map<String, String> columnsPreservedCopy = new HashMap<String, String>(columnsPreserved);
    String alterTable;
    List<DropColumnStatement> columns = null;

    if (dropColumnStatement.isMultiple()) {
        columns = dropColumnStatement.getColumns();
        for (DropColumnStatement statement : columns) {
            columnsPreservedCopy.remove(statement.getColumnName());
        }
        alterTable = "ALTER TABLE " + database.escapeTableName(columns.get(0).getCatalogName(), columns.get(0).getSchemaName(), columns.get(0).getTableName()) + " REPLACE COLUMNS (";
    } else {
        columnsPreservedCopy.remove(dropColumnStatement.getColumnName());
        alterTable = "ALTER TABLE " + database.escapeTableName(dropColumnStatement.getCatalogName(), dropColumnStatement.getSchemaName(), dropColumnStatement.getTableName()) + " REPLACE COLUMNS (";
    }

    int i = 0;
    for (String columnName : columnsPreservedCopy.keySet()) {
        alterTable += database.escapeObjectName(columnName, Column.class) + " " + columnsPreservedCopy.get(columnName);
        if (i < columnsPreservedCopy.size() - 1) {
            alterTable += ",";
        } else {
            alterTable += ")";
        }
        i++;
    }

    if (dropColumnStatement.isMultiple()) {
        result.add(new UnparsedSql(alterTable, getAffectedColumns(columns)));
    } else {
        result.add(new UnparsedSql(alterTable, getAffectedColumn(dropColumnStatement)));
    }
    return result.toArray(new Sql[result.size()]);
}
 
Example 12
Source Project: liquibase-impala   Source File: HiveDropColumnGenerator.java    License: Apache License 2.0 5 votes vote down vote up
private Column[] getAffectedColumns(List<DropColumnStatement> columns) {
    List<Column> affected = new ArrayList<Column>();
    for (DropColumnStatement column : columns) {
        affected.add(getAffectedColumn(column));
    }
    return affected.toArray(new Column[affected.size()]);
}
 
Example 13
@Override
public Sql[] generateSql(TagDatabaseStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
    String catalogName = database.getLiquibaseCatalogName();
    String schemaName = database.getDefaultSchemaName();
    String tableName = database.getDatabaseChangeLogTableName();
    String tableNameEscaped = database.escapeTableName(catalogName, schemaName, tableName);
    String dateColumnNameEscaped = database.escapeObjectName("DATEEXECUTED", Column.class);
    String tagColumnNameEscaped = database.escapeObjectName("TAG", Column.class);
    String tmpTable = UUID.randomUUID().toString().replaceAll("-", "");
    CreateTableAsSelectStatement createTableAsSelectStatement = new CreateTableAsSelectStatement(catalogName, schemaName, tableName, tmpTable)
            .addColumnNames("ID", "AUTHOR", "FILENAME", "DATEEXECUTED", "ORDEREXECUTED", "EXECTYPE", "MD5SUM", "DESCRIPTION", "COMMENTS", "TAG", "LIQUIBASE", "CONTEXTS", "LABELS", "DEPLOYMENT_ID")
            .setWhereCondition(dateColumnNameEscaped + " != (SELECT MAX(" + dateColumnNameEscaped + ") " +
                    "FROM " + tableNameEscaped + ")");
    InsertAsSelectStatement insertAsSelectStatement = new InsertAsSelectStatement(database.getLiquibaseCatalogName(), database.getLiquibaseSchemaName(), database.getDatabaseChangeLogTableName(), tmpTable)
            .addColumnNames("ID", "AUTHOR", "FILENAME", "DATEEXECUTED", "ORDEREXECUTED", "EXECTYPE", "MD5SUM", "DESCRIPTION", "COMMENTS", "'" + statement.getTag() + "'", "LIQUIBASE", "CONTEXTS", "LABELS", "DEPLOYMENT_ID")
            .setWhereCondition(dateColumnNameEscaped + " = (SELECT MAX(" + dateColumnNameEscaped + ") FROM " + tableNameEscaped + ") AND ("
                    + tagColumnNameEscaped + " IS NULL OR " + tagColumnNameEscaped + " != ?)")
            .addWhereParameters(statement.getTag());

    return CustomSqlGenerator.generateSql(database,
            UserSessionSettings.syncDdlStart(),
            createTableAsSelectStatement,
            insertAsSelectStatement,
            new DropTableStatement(catalogName, schemaName, tableName, false),
            new RenameTableStatement(catalogName, schemaName, tmpTable, tableName),
            UserSessionSettings.syncDdlStop());
}
 
Example 14
@Override
public Sql[] generateSql(final DropSpatialIndexStatement statement, final Database database,
      final SqlGeneratorChain sqlGeneratorChain) {
   final String indexName = statement.getIndexName();
   final Index example = new Index().setName(indexName);
   if (statement.getTableName() != null) {
      example.setTable((Table) new Table().setName(statement.getTableName()).setSchema(
            statement.getTableCatalogName(), statement.getTableSchemaName()));
   }
   Index index;
   try {
      index = SnapshotGeneratorFactory.getInstance().createSnapshot(example, database);
   } catch (final Exception e) {
      throw new UnexpectedLiquibaseException("Failed to create a snapshot of '" + indexName
            + "'", e);
   }

   final String tableName = index.getTable().getName();
   final Column column = index.getColumns().get(0);

   final StringBuilder sql = new StringBuilder();
   sql.append("DELETE FROM user_sdo_geom_metadata ");
   sql.append("WHERE table_name = '").append(database.correctObjectName(tableName, Table.class));
   sql.append("' AND column_name = '").append(
         database.correctObjectName(column.getName(), Column.class));
   sql.append("'");
   final UnparsedSql deleteMetadata = new UnparsedSql(sql.toString(),
         new View().setName("user_sdo_geom_metadata"));
   return new Sql[] { deleteMetadata };
}
 
Example 15
/**
 * Generates the SQL for deleting any existing record from the
 * <code>USER_SDO_GEOM_METADATA</code> table. Typically this record shouldn't be present but we
 * must ensure that it does not already exist.
 * 
 * @param statement
 *           the create spatial index statement.
 * @param database
 *           the database instance.
 * @return the SQL to delete any existing metadata record.
 */
protected String generateDeleteMetadataSql(final CreateSpatialIndexStatement statement,
      final Database database) {
   final StringBuilder sql = new StringBuilder();
   sql.append("DELETE FROM user_sdo_geom_metadata ");
   final String tableName = statement.getTableName().trim();
   sql.append("WHERE table_name = '").append(database.correctObjectName(tableName, Table.class));
   final String columnName = statement.getColumns()[0].trim();
   sql.append("' AND column_name = '").append(
         database.correctObjectName(columnName, Column.class));
   sql.append("'");
   return sql.toString();
}
 
Example 16
@Override
public String escapeColumnName(final String catalogName, final String schemaName, final String tableName, final String columnName) {
    return escapeObjectName(columnName, Column.class);
}
 
Example 17
Source Project: jweb-cms   Source File: Main.java    License: GNU Affero General Public License v3.0 4 votes vote down vote up
private static Class[] snapTypes() {
    return new Class[]{UniqueConstraint.class, Sequence.class, Table.class, View.class, ForeignKey.class, PrimaryKey.class, Index.class, Column.class, Data.class};
}
 
Example 18
Source Project: liquibase-impala   Source File: HiveDropColumnGenerator.java    License: Apache License 2.0 4 votes vote down vote up
private Column getAffectedColumn(DropColumnStatement statement) {
    return new Column().setName(statement.getColumnName()).setRelation(new Table().setName(statement.getTableName()).setSchema(statement.getCatalogName(), statement.getSchemaName()));
}
 
Example 19
@Override
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>();

    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 hasOrderExecuted = changeLogTable.getColumn("ORDEREXECUTED") != null;
        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, null));
        }
        if (!hasTag) {
            executor.comment("Adding missing databasechangelog.tag column");
            statementsToExecute.add(new AddColumnStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "TAG", charTypeName, null));
        }
        if (!hasComments) {
            executor.comment("Adding missing databasechangelog.comments column");
            statementsToExecute.add(new AddColumnStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "COMMENTS", charTypeName, null));
        }
        if (!hasLiquibase) {
            executor.comment("Adding missing databasechangelog.liquibase column");
            statementsToExecute.add(new AddColumnStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "LIQUIBASE", charTypeName, null));
        }
        if (!hasOrderExecuted) {
            executor.comment("Adding missing databasechangelog.orderexecuted column");
            statementsToExecute.add(new AddColumnStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "ORDEREXECUTED", "int", null));
        }
        if (!hasExecTypeColumn) {
            executor.comment("Adding missing databasechangelog.exectype column");
            statementsToExecute.add(new AddColumnStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "EXECTYPE", charTypeName, null));
        }

        if (!hasContexts) {
            executor.comment("Adding missing databasechangelog.contexts column");
            statementsToExecute.add(new AddColumnStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "CONTEXTS", charTypeName, null));
        }

        if (!hasLabels) {
            executor.comment("Adding missing databasechangelog.labels column");
            statementsToExecute.add(new AddColumnStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "LABELS", charTypeName, null));
        }

        if (!hasDeploymentIdColumn) {
            executor.comment("Adding missing databasechangelog.deployment_id column");
            statementsToExecute.add(new AddColumnStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "DEPLOYMENT_ID", charTypeName, null));
        }
    } else {
        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);
        LOG.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 {
            LOG.info("Cannot run " + sql.getClass().getSimpleName() + " on " + getDatabase().getShortName() + " when checking databasechangelog table");
        }
    }
    serviceInitialized = true;
}
 
Example 20
Source Project: keycloak   Source File: RemoveDuplicateOfflineSessions.java    License: Apache License 2.0 4 votes vote down vote up
@Override
protected void generateStatementsImpl() throws CustomChangeException {
    Set<String> clientSessionIdsToDelete = new HashSet<>();

    String tableName = getTableName("OFFLINE_CLIENT_SESSION");
    String colClientSessionId = database.correctObjectName("CLIENT_SESSION_ID", Column.class);

    try (PreparedStatement ps = connection.prepareStatement(String.format(
        "SELECT t.CLIENT_SESSION_ID, t.USER_SESSION_ID, t.CLIENT_ID, t.OFFLINE_FLAG" +
        "  FROM %1$s t," +
        "    (SELECT USER_SESSION_ID, CLIENT_ID, OFFLINE_FLAG" +
        "      FROM %1$s" +
        "    GROUP BY USER_SESSION_ID, CLIENT_ID, OFFLINE_FLAG" +
        "    HAVING COUNT(*) > 1) t1" +
        "  WHERE t.USER_SESSION_ID = t1.USER_SESSION_ID" +
        "    AND t.CLIENT_ID = t1.CLIENT_ID" +
        "    AND t.OFFLINE_FLAG = t1.OFFLINE_FLAG" +
        "  ORDER BY t.USER_SESSION_ID, t.CLIENT_ID, t.OFFLINE_FLAG", tableName));

        ResultSet resultSet = ps.executeQuery()
      ) {
        // Find out all offending duplicates, keep first row only
        Key origKey = new Key(null, null, null);
        while (resultSet.next()) {
            String clientSessionId = resultSet.getString(1);
            Key key = new Key(resultSet.getString(2), resultSet.getString(3), resultSet.getString(4));

            if (key.equals(origKey)) {
                clientSessionIdsToDelete.add(clientSessionId);
            } else {
                origKey = key;
            }
        }
    } catch (Exception e) {
        throw new CustomChangeException(getTaskId() + ": Exception when updating data from previous version", e);
    }

    AtomicInteger ai = new AtomicInteger();
    clientSessionIdsToDelete.stream()
      .collect(Collectors.groupingByConcurrent(id -> ai.getAndIncrement() / 20, Collectors.toList())) // Split into chunks of at most 20 items

      .values().stream()
      .map(ids -> new DeleteStatement(null, null, "OFFLINE_CLIENT_SESSION")
        .setWhere(":name IN (" + ids.stream().map(id -> "?").collect(Collectors.joining(",")) + ")")
        .addWhereColumnName(colClientSessionId)
        .addWhereParameters(ids.toArray())
      )
      .forEach(statements::add);
}
 
Example 21
Source Project: keycloak   Source File: LiquibaseJpaUpdaterProvider.java    License: Apache License 2.0 4 votes vote down vote up
protected void updateChangeSet(Liquibase liquibase, Connection connection, Writer exportWriter) throws LiquibaseException, SQLException {
    String changelog = liquibase.getChangeLogFile();
    Database database = liquibase.getDatabase();
    Table changelogTable = SnapshotGeneratorFactory.getInstance().getDatabaseChangeLogTable(new SnapshotControl(database, false, Table.class, Column.class), database);

    if (changelogTable != null) {
        boolean hasDeploymentIdColumn = changelogTable.getColumn(DEPLOYMENT_ID_COLUMN) != null;

        // create DEPLOYMENT_ID column if it doesn't exist
        if (!hasDeploymentIdColumn) {
            ChangeLogHistoryService changelogHistoryService = ChangeLogHistoryServiceFactory.getInstance().getChangeLogService(database);
            changelogHistoryService.generateDeploymentId();
            String deploymentId = changelogHistoryService.getDeploymentId();

            logger.debugv("Adding missing column {0}={1} to {2} table", DEPLOYMENT_ID_COLUMN, deploymentId,changelogTable.getName());

            List<SqlStatement> statementsToExecute = new ArrayList<>();
            statementsToExecute.add(new AddColumnStatement(database.getLiquibaseCatalogName(), database.getLiquibaseSchemaName(),
                    changelogTable.getName(), DEPLOYMENT_ID_COLUMN, "VARCHAR(10)", null));
            statementsToExecute.add(new UpdateStatement(database.getLiquibaseCatalogName(), database.getLiquibaseSchemaName(), changelogTable.getName())
                    .addNewColumnValue(DEPLOYMENT_ID_COLUMN, deploymentId));
            statementsToExecute.add(new SetNullableStatement(database.getLiquibaseCatalogName(), database.getLiquibaseSchemaName(),
                    changelogTable.getName(), DEPLOYMENT_ID_COLUMN, "VARCHAR(10)", false));

            ExecutorService executorService = ExecutorService.getInstance();
            Executor executor = executorService.getExecutor(liquibase.getDatabase());

            for (SqlStatement sql : statementsToExecute) {
                executor.execute(sql);
                database.commit();
            }
        }
    }

    List<ChangeSet> changeSets = getLiquibaseUnrunChangeSets(liquibase);
    if (!changeSets.isEmpty()) {
        List<RanChangeSet> ranChangeSets = liquibase.getDatabase().getRanChangeSetList();
        if (ranChangeSets.isEmpty()) {
            logger.infov("Initializing database schema. Using changelog {0}", changelog);
        } else {
            if (logger.isDebugEnabled()) {
                logger.debugv("Updating database from {0} to {1}. Using changelog {2}", ranChangeSets.get(ranChangeSets.size() - 1).getId(), changeSets.get(changeSets.size() - 1).getId(), changelog);
            } else {
                logger.infov("Updating database. Using changelog {0}", changelog);
            }
        }

        if (exportWriter != null) {
            if (ranChangeSets.isEmpty()) {
                outputChangeLogTableCreationScript(liquibase, exportWriter);
            }
            liquibase.update((Contexts) null, new LabelExpression(), exportWriter, false);
        } else {
            liquibase.update((Contexts) null);
        }

        logger.debugv("Completed database update for changelog {0}", changelog);
    } else {
        logger.debugv("Database is up to date for changelog {0}", changelog);
    }

    // Needs to restart liquibase services to clear ChangeLogHistoryServiceFactory.getInstance().
    // See https://issues.jboss.org/browse/KEYCLOAK-3769 for discussion relevant to why reset needs to be here
    resetLiquibaseServices(liquibase);
}
 
Example 22
Source Project: keycloak   Source File: QuarkusJpaUpdaterProvider.java    License: Apache License 2.0 4 votes vote down vote up
protected void updateChangeSet(Liquibase liquibase, Writer exportWriter) throws LiquibaseException  {
    String changelog = liquibase.getChangeLogFile();
    Database database = liquibase.getDatabase();
    Table changelogTable = SnapshotGeneratorFactory.getInstance().getDatabaseChangeLogTable(new SnapshotControl(database, false, Table.class, Column.class), database);

    if (changelogTable != null) {
        boolean hasDeploymentIdColumn = changelogTable.getColumn(DEPLOYMENT_ID_COLUMN) != null;

        // create DEPLOYMENT_ID column if it doesn't exist
        if (!hasDeploymentIdColumn) {
            ChangeLogHistoryService changelogHistoryService = ChangeLogHistoryServiceFactory.getInstance().getChangeLogService(database);
            changelogHistoryService.generateDeploymentId();
            String deploymentId = changelogHistoryService.getDeploymentId();

            logger.debugv("Adding missing column {0}={1} to {2} table", DEPLOYMENT_ID_COLUMN, deploymentId,changelogTable.getName());

            List<SqlStatement> statementsToExecute = new ArrayList<>();
            statementsToExecute.add(new AddColumnStatement(database.getLiquibaseCatalogName(), database.getLiquibaseSchemaName(),
                    changelogTable.getName(), DEPLOYMENT_ID_COLUMN, "VARCHAR(10)", null));
            statementsToExecute.add(new UpdateStatement(database.getLiquibaseCatalogName(), database.getLiquibaseSchemaName(), changelogTable.getName())
                    .addNewColumnValue(DEPLOYMENT_ID_COLUMN, deploymentId));
            statementsToExecute.add(new SetNullableStatement(database.getLiquibaseCatalogName(), database.getLiquibaseSchemaName(),
                    changelogTable.getName(), DEPLOYMENT_ID_COLUMN, "VARCHAR(10)", false));

            ExecutorService executorService = ExecutorService.getInstance();
            Executor executor = executorService.getExecutor(liquibase.getDatabase());

            for (SqlStatement sql : statementsToExecute) {
                executor.execute(sql);
                database.commit();
            }
        }
    }

    List<ChangeSet> changeSets = getLiquibaseUnrunChangeSets(liquibase);
    if (!changeSets.isEmpty()) {
        List<RanChangeSet> ranChangeSets = liquibase.getDatabase().getRanChangeSetList();
        if (ranChangeSets.isEmpty()) {
            logger.infov("Initializing database schema. Using changelog {0}", changelog);
        } else {
            if (logger.isDebugEnabled()) {
                logger.debugv("Updating database from {0} to {1}. Using changelog {2}", ranChangeSets.get(ranChangeSets.size() - 1).getId(), changeSets.get(changeSets.size() - 1).getId(), changelog);
            } else {
                logger.infov("Updating database. Using changelog {0}", changelog);
            }
        }

        if (exportWriter != null) {
            if (ranChangeSets.isEmpty()) {
                outputChangeLogTableCreationScript(liquibase, exportWriter);
            }
            liquibase.update((Contexts) null, new LabelExpression(), exportWriter, false);
        } else {
            liquibase.update((Contexts) null);
        }

        logger.debugv("Completed database update for changelog {0}", changelog);
    } else {
        logger.debugv("Database is up to date for changelog {0}", changelog);
    }

    // Needs to restart liquibase services to clear ChangeLogHistoryServiceFactory.getInstance().
    // See https://issues.jboss.org/browse/KEYCLOAK-3769 for discussion relevant to why reset needs to be here
    resetLiquibaseServices(liquibase);
}