Java Code Examples for liquibase.database.Database#escapeTableName()

The following examples show how to use liquibase.database.Database#escapeTableName() . 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
Source File: InsertGenerator.java    From liquibase-mssql with Apache License 2.0 6 votes vote down vote up
@Override
public Sql[] generateSql(InsertStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
    Boolean identityInsertEnabled = false;
    if (statement instanceof InsertStatementMSSQL) {
        identityInsertEnabled = ((InsertStatementMSSQL)statement).getIdentityInsertEnabled();
    }
    if (identityInsertEnabled == null || !identityInsertEnabled) {
        return super.generateSql(statement, database, sqlGeneratorChain);
    }
    String tableName = database.escapeTableName(statement.getCatalogName(), statement.getSchemaName(), statement.getTableName());
    String enableIdentityInsert = "SET IDENTITY_INSERT " + tableName + " ON";
    String disableIdentityInsert = "SET IDENTITY_INSERT " + tableName + " OFF";
    String safelyEnableIdentityInsert = ifTableHasIdentityColumn(enableIdentityInsert, statement, database.getDefaultSchemaName());
    String safelyDisableIdentityInsert = ifTableHasIdentityColumn(disableIdentityInsert, statement, database.getDefaultSchemaName());

    List<Sql> sql = new ArrayList<Sql>(Arrays.asList(sqlGeneratorChain.generateSql(statement, database)));
    sql.add(0, new UnparsedSql(safelyEnableIdentityInsert));
    sql.add(new UnparsedSql(safelyDisableIdentityInsert));
    return sql.toArray(new Sql[sql.size()]);
}
 
Example 2
Source File: InsertSetGenerator.java    From liquibase-mssql with Apache License 2.0 6 votes vote down vote up
@Override
public Sql[] generateSql(InsertSetStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
    Boolean identityInsertEnabled = false;
    if (statement instanceof InsertSetStatementMSSQL) {
        identityInsertEnabled = ((InsertSetStatementMSSQL) statement).getIdentityInsertEnabled();
    }
    if (identityInsertEnabled == null || !identityInsertEnabled) {
        return super.generateSql(statement, database, sqlGeneratorChain);
    }
    String tableName = database.escapeTableName(statement.getCatalogName(), statement.getSchemaName(),
                    statement.getTableName());
    String enableIdentityInsert = "SET IDENTITY_INSERT " + tableName + " ON";
    String disableIdentityInsert = "SET IDENTITY_INSERT " + tableName + " OFF";
    String safelyEnableIdentityInsert = ifTableHasIdentityColumn(enableIdentityInsert, statement,
                    database.getDefaultSchemaName());
    String safelyDisableIdentityInsert = ifTableHasIdentityColumn(disableIdentityInsert, statement,
                    database.getDefaultSchemaName());

    List<Sql> sql = new ArrayList<Sql>(Arrays.asList(sqlGeneratorChain.generateSql(statement, database)));
    sql.add(0, new UnparsedSql(safelyEnableIdentityInsert));
    sql.add(new UnparsedSql(safelyDisableIdentityInsert));
    return sql.toArray(new Sql[sql.size()]);
}
 
Example 3
Source File: HiveDropColumnGenerator.java    From liquibase-impala with 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 4
Source File: RenameTableGenerator.java    From liquibase-impala with Apache License 2.0 5 votes vote down vote up
@Override
public Sql[] generateSql(RenameTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
    String sql = "ALTER TABLE " + database.escapeTableName(statement.getCatalogName(), statement.getSchemaName(),
            statement.getOldTableName()) + " RENAME TO " + database.escapeObjectName(statement.getNewTableName(), Table.class);
    return new Sql[]{
            new UnparsedSql(sql,
                    fetchAffectedOldTable(statement),
                    fetchAffectedNewTable(statement)
            )
    };
}
 
Example 5
Source File: ImpalaTagDatabaseGenerator.java    From liquibase-impala with Apache License 2.0 5 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.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 6
Source File: ImpalaInvalidateMetadataGenerator.java    From liquibase-impala with Apache License 2.0 5 votes vote down vote up
@Override
public Sql[] generateSql(InvalidateMetadataStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
    String catalogName = statement.getCatalogName();
    String schemaName = statement.getSchemaName();
    String tableName = statement.getTableName();
    String sql = "INVALIDATE METADATA " + database.escapeTableName(catalogName, schemaName, tableName);
    return new Sql[]{new UnparsedSql(sql, fetchAffectedTable(statement))};
}
 
Example 7
Source File: PerconaAddColumnChange.java    From liquibase-percona with Apache License 2.0 5 votes vote down vote up
private String addForeignKeyConstraint(AddColumnConfig column, Database database) {
    String result = "";
    ConstraintsConfig constraintsConfig = column.getConstraints();
    if (constraintsConfig != null && (StringUtil.isNotEmpty(constraintsConfig.getReferences()) || StringUtil.isNotEmpty(constraintsConfig.getReferencedTableName()) )) {
        result += ", ADD ";
        if (StringUtil.isNotEmpty(constraintsConfig.getForeignKeyName())) {
            result += "CONSTRAINT " + database.escapeConstraintName(constraintsConfig.getForeignKeyName()) + " ";
        }
        result +=  "FOREIGN KEY ("
                + database.escapeColumnName(null, null, null, column.getName()) + ") REFERENCES ";

        String referencedTable;
        String referencedColumn;

        if (StringUtil.isNotEmpty(constraintsConfig.getReferences())) {
            Matcher references = Pattern.compile("([\\w\\._]+)\\(([\\w_]+)\\)").matcher(constraintsConfig.getReferences());
            if (!references.matches()) {
                throw new UnexpectedLiquibaseException("Unable to get table name and column name from " + constraintsConfig.getReferences());
            }
            referencedTable = references.group(1);
            referencedColumn = references.group(2);
        } else {
            referencedTable = constraintsConfig.getReferencedTableName();
            referencedColumn = constraintsConfig.getReferencedColumnNames();
        }

        referencedTable = PerconaChangeUtil.resolveReferencedPerconaTableName(getTableName(), referencedTable);

        result += database.escapeTableName(null, null, referencedTable) + "(";
        result += database.escapeColumnName(null, null, null, referencedColumn);
        result += ")";
    }
    return result;
}
 
Example 8
Source File: AddPrimaryKeyGeneratorMSSQL.java    From liquibase-mssql with Apache License 2.0 5 votes vote down vote up
/**
 * The extension's implementation is essentially a copy/paste of the default implementation, with the following changes:
 *
 * 1) Removed other database platform specific logic other than MSSQL (purely to simplify)
 *
 * 2) Added support for setting fillFactor
 *
 * @param statement
 * @param database
 * @param sqlGeneratorChain
 * @return
 */
private Sql[] generateMSSQLSql(AddPrimaryKeyStatementMSSQL statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
  String sql;
  if (statement.getConstraintName() == null) {
    sql = "ALTER TABLE " + database.escapeTableName(statement.getCatalogName(), statement.getSchemaName(), statement.getTableName()) + " ADD PRIMARY KEY (" + database.escapeColumnNameList(statement.getColumnNames()) + ")";
  } else {
    sql = "ALTER TABLE " + database.escapeTableName(statement.getCatalogName(), statement.getSchemaName(), statement.getTableName()) + " ADD CONSTRAINT " + database.escapeConstraintName(statement.getConstraintName())+" PRIMARY KEY";
    if (!statement.isClustered()) {
      sql += " NONCLUSTERED";
    }
    sql += " (" + database.escapeColumnNameList(statement.getColumnNames()) + ")";
  }

  // the only new feature being added is support for fillFactor
  sql += " WITH (FILLFACTOR = " + statement.getFillFactor() + ")";

  if (StringUtils.trimToNull(statement.getTablespace()) != null && database.supportsTablespaces()) {
    sql += " ON "+statement.getTablespace();
  }

  if (statement.getForIndexName() != null) {
    sql += " USING INDEX "+database.escapeObjectName(statement.getForIndexCatalogName(), statement.getForIndexSchemaName(), statement.getForIndexName(), Index.class);
  }

  return new Sql[] {
      new UnparsedSql(sql, getAffectedPrimaryKey(statement))
  };
}
 
Example 9
Source File: CustomLockDatabaseChangeLogGenerator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private Sql generateSelectForUpdate(Database database, int id) {
    String catalog = database.getLiquibaseCatalogName();
    String schema = database.getLiquibaseSchemaName();
    String rawLockTableName = database.getDatabaseChangeLogLockTableName();

    String lockTableName = database.escapeTableName(catalog, schema, rawLockTableName);
    String idColumnName  = database.escapeColumnName(catalog, schema, rawLockTableName, "ID");

    String sqlBase = "SELECT " + idColumnName + " FROM " + lockTableName;
    String sqlWhere = " WHERE " + idColumnName + "=" + id;

    String sql;
    if (database instanceof MySQLDatabase || database instanceof PostgresDatabase || database instanceof H2Database ||
            database instanceof OracleDatabase) {
        sql = sqlBase + sqlWhere + " FOR UPDATE";
    } else if (database instanceof MSSQLDatabase) {
        sql = sqlBase + " WITH (UPDLOCK, ROWLOCK)" + sqlWhere;
    } else if (database instanceof DB2Database) {
        sql = sqlBase + sqlWhere +  " FOR READ ONLY WITH RS USE AND KEEP UPDATE LOCKS";
    } else {
        sql = sqlBase + sqlWhere;
        logger.warnf("No direct support for database %s . Database lock may not work correctly", database.getClass().getName());
    }

    logger.debugf("SQL command for pessimistic lock: %s", sql);
    
    return new UnparsedSql(sql);
}
 
Example 10
Source File: TruncateGenerator.java    From liquibase-impala with Apache License 2.0 4 votes vote down vote up
@Override
public Sql[] generateSql(TruncateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
    final String sql = "TRUNCATE TABLE " + database.escapeTableName(statement.getCatalogName(),
            statement.getSchemaName(), statement.getTableName());
    return new Sql[]{new UnparsedSql(sql, fetchAffectedTable(statement))};
}
 
Example 11
Source File: ImpalaRefreshTableGenerator.java    From liquibase-impala with Apache License 2.0 4 votes vote down vote up
@Override
public Sql[] generateSql(RefreshTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
    String sql = "REFRESH " + database.escapeTableName(statement.getCatalogName(), statement.getSchemaName(), statement.getTableName());
    return new Sql[]{new UnparsedSql(sql, fetchAffectedTable(statement))};
}