Java Code Examples for liquibase.util.StringUtils

The following examples show how to use liquibase.util.StringUtils. 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 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 2
@Override
public String generateAlterStatement(Database database) {
    StringBuilder alter = new StringBuilder();

    alter.append("ADD ");
    if (StringUtil.isNotEmpty(getConstraintName())) {
        alter.append("CONSTRAINT ");
        alter.append(database.escapeConstraintName(getConstraintName()));
        alter.append(" ");
    }
    alter.append("UNIQUE (");
    List<String> columns = StringUtils.splitAndTrim(getColumnNames(), ",");
    if (columns == null) columns = Collections.emptyList();
    alter.append(database.escapeColumnNameList(StringUtils.join(columns, ", ")));
    alter.append(")");

    return alter.toString();
}
 
Example 3
/**
 * 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 4
@Override
public Sql[] generateSql(MarkChangeSetRanStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
    ChangeSet changeSet = statement.getChangeSet();

    SqlStatement runStatement;
    try {
        if (statement.getExecType().equals(ChangeSet.ExecType.FAILED) || statement.getExecType().equals(ChangeSet.ExecType.SKIPPED)) {
            return new Sql[0]; //don't mark
        }

        String tag = null;
        for (Change change : changeSet.getChanges()) {
            if (change instanceof TagDatabaseChange) {
                TagDatabaseChange tagChange = (TagDatabaseChange) change;
                tag = tagChange.getTag();
            }
        }

        runStatement = new HiveInsertStatement(database.getLiquibaseCatalogName(), database.getLiquibaseSchemaName(), database.getDatabaseChangeLogTableName())
                .addColumnValue(changeSet.getId())
                .addColumnValue(changeSet.getAuthor())
                .addColumnValue(changeSet.getFilePath())
                .addColumnValue(DateTimeUtils.getCurrentTS("yyyy-MM-dd HH:mm:ss"))
                .addColumnValue(ChangeLogHistoryServiceFactory.getInstance().getChangeLogService(database).getNextSequenceValue())
                .addColumnValue(statement.getExecType().value)
                .addColumnValue(changeSet.generateCheckSum().toString())
                .addColumnValue(changeSet.getDescription())
                .addColumnValue(StringUtils.trimToEmpty(changeSet.getComments()))
                .addColumnValue(tag == null ? "NULL" : tag)
                .addColumnValue(ChangeLogHistoryServiceFactory.getInstance().getChangeLogService(database).getDeploymentId())
                .addColumnValue(changeSet.getContexts() == null || changeSet.getContexts().isEmpty() ? null : changeSet.getContexts().toString())
                .addColumnValue(changeSet.getLabels() == null || changeSet.getLabels().isEmpty() ? null : changeSet.getLabels().toString())
                .addColumnValue(LiquibaseUtil.getBuildVersion());
    } catch (LiquibaseException e) {
        throw new UnexpectedLiquibaseException(e);
    }

    return SqlGeneratorFactory.getInstance().generateSql(runStatement, database);
}
 
Example 5
protected String getFieldString(String fieldName) {
    for (FieldExtension fieldExtension : decisionTask.getFieldExtensions()) {
        if (fieldName.equals(fieldExtension.getFieldName())) {
            if (StringUtils.isNotEmpty(fieldExtension.getStringValue())) {
                return fieldExtension.getStringValue();
                
            } else if (StringUtils.isNotEmpty(fieldExtension.getExpression())) {
                return fieldExtension.getExpression();
            }
        }
    }
    
    return null;
}
 
Example 6
Source Project: liquibase-spatial   Source File: OracleSpatialUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Converts the given EPSG SRID to the corresponding Oracle SRID.
 *
 * @param srid
 *           the EPSG SRID.
 * @param database
 *           the database instance.
 * @return the corresponding Oracle SRID.
 */
public static String getOracleSrid(final String srid, final Database database) {
   final String oracleSrid;
   if (StringUtils.trimToNull(srid) == null) {
      oracleSrid = null;
   } else if (EPSG_TO_ORACLE_MAP.containsKey(srid)) {
      oracleSrid = EPSG_TO_ORACLE_MAP.get(srid);
   } else {
      oracleSrid = loadOracleSrid(srid, database);
      EPSG_TO_ORACLE_MAP.put(srid, oracleSrid);
   }
   return oracleSrid;
}
 
Example 7
/**
 * Generates the SQL for creating the spatial index.
 * 
 * @param statement
 *           the create spatial index statement.
 * @param database
 *           the database instance.
 * @return the SQL to create a spatial index.
 */
protected String generateCreateIndexSql(final CreateSpatialIndexStatement statement,
      final Database database) {
   final StringBuilder sql = new StringBuilder();
   sql.append("CREATE INDEX ");
   final String schemaName = statement.getTableSchemaName();
   final String catalogName = statement.getTableCatalogName();
   final String indexName = statement.getIndexName();
   sql.append(database.escapeIndexName(catalogName, schemaName, indexName));
   sql.append(" ON ");
   final String tableName = statement.getTableName();
   sql.append(database.escapeTableName(catalogName, schemaName, tableName)).append(" (");
   final Iterator<String> iterator = Arrays.asList(statement.getColumns()).iterator();
   final String column = iterator.next();
   sql.append(database.escapeColumnName(catalogName, statement.getTableSchemaName(), tableName,
         column));
   sql.append(") INDEXTYPE IS mdsys.spatial_index");

   // Generate and add the optional parameters.
   final Collection<String> parameters = getParameters(statement);
   if (parameters != null && !parameters.isEmpty()) {
      sql.append(" PARAMETERS ('");
      sql.append(StringUtils.join(parameters, " "));
      sql.append("')");
   }
   return sql.toString();
}
 
Example 8
/**
 * Creates the parameters to the spatial index creation statement.
 * 
 * @param statement
 *           the statement.
 * @return the optional parameters for the <code>CREATE INDEX</code> statement.
 */
protected Collection<String> getParameters(final CreateSpatialIndexStatement statement) {
   final Collection<String> parameters = new ArrayList<String>();
   if (StringUtils.trimToNull(statement.getGeometryType()) != null) {
      final String gType = getGtype(statement.getGeometryType().trim());
      if (gType != null) {
         parameters.add("layer_gtype=" + gType);
      }
   }
   if (StringUtils.trimToNull(statement.getTablespace()) != null) {
      parameters.add("tablespace=" + statement.getTablespace().trim());
   }
   return parameters;
}
 
Example 9
/**
 * Generates the table name containing the Hatbox index.
 *
 * @return the Hatbox table name.
 */
protected String getHatboxTableName() {
   final String tableName;
   if (!StringUtils.hasUpperCase(getTableName())) {
      tableName = getTableName() + "_hatbox";
   } else {
      tableName = getTableName() + "_HATBOX";
   }
   return tableName;
}
 
Example 10
@Override
public String getConfirmationMessage() {
   final StringBuilder message = new StringBuilder("Spatial index");
   if (StringUtils.trimToNull(getIndexName()) != null) {
      message.append(' ').append(getIndexName().trim());
   }
   message.append(" created");
   if (StringUtils.trimToNull(getTableName()) != null) {
      message.append(" on ").append(getTableName().trim());
   }
   return message.toString();
}
 
Example 11
Source Project: liquibase-spatial   Source File: DropSpatialIndexChange.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public String getConfirmationMessage() {
   final StringBuilder message = new StringBuilder("Spatial index");
   if (StringUtils.trimToNull(getIndexName()) != null) {
      message.append(' ').append(getIndexName().trim());
   }
   message.append(" dropped");
   if (StringUtils.trimToNull(getTableName()) != null) {
      message.append(" from ").append(getTableName().trim());
   }
   return message.toString();
}
 
Example 12
/**
 * 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 13
@Override
public String escapeObjectName(String catalogName, String schemaName, final String objectName,
                               final Class<? extends DatabaseObject> objectType) {
    if (supportsSchemas()) {
        catalogName = StringUtils.trimToNull(catalogName);
        schemaName = StringUtils.trimToNull(schemaName);

        if (catalogName == null) {
            catalogName = this.getDefaultCatalogName();
        }
        if (schemaName == null) {
            schemaName = this.getDefaultSchemaName();
        }

        if (!supportsCatalogInObjectName(objectType)) {
            catalogName = null;
        }
        if ((catalogName == null) && (schemaName == null)) {
            return escapeObjectName(objectName, objectType);
        } else if ((catalogName == null) || !this.supportsCatalogInObjectName(objectType)) {
            if (isDefaultSchema(catalogName, schemaName) && !getOutputDefaultSchema()) {
                return escapeObjectName(objectName, objectType);
            } else {
                return escapeObjectName(schemaName, Schema.class) + "." + escapeObjectName(objectName, objectType);
            }
        } else {
            if (isDefaultSchema(catalogName, schemaName) && !getOutputDefaultSchema() && !getOutputDefaultCatalog
                ()) {
                return escapeObjectName(objectName, objectType);
            } else if (isDefaultSchema(catalogName, schemaName) && !getOutputDefaultCatalog()) {
                return escapeObjectName(schemaName, Schema.class) + "." + escapeObjectName(objectName, objectType);
            } else {
                return escapeObjectName(catalogName, Catalog.class) + "." + escapeObjectName(schemaName, Schema.class) + "." + escapeObjectName(objectName, objectType);
            }
        }
    } else if (supportsCatalogs()) {
        catalogName = StringUtils.trimToNull(catalogName);
        schemaName = StringUtils.trimToNull(schemaName);

        if (catalogName != null) {
            if (getOutputDefaultCatalog()) {
                return escapeObjectName(catalogName, Catalog.class) + "." + escapeObjectName(objectName, objectType);
            } else {
                if (!defaultCatalogSet && isDefaultCatalog(catalogName)) {
                    return escapeObjectName(objectName, objectType);
                } else {
                    return escapeObjectName(catalogName, Catalog.class) + "." + escapeObjectName(objectName, objectType);
                }
            }
        } else {

            //they actually mean catalog name
            if (schemaName != null) {
                if (getOutputDefaultCatalog()) {
                    return escapeObjectName(schemaName, Catalog.class) + "." + escapeObjectName(objectName, objectType);
                } else {
                    if (!defaultCatalogSet && isDefaultCatalog(schemaName)) {
                        return escapeObjectName(objectName, objectType);
                    } else {
                        return escapeObjectName(schemaName, Catalog.class) + "." + escapeObjectName(objectName, objectType);
                    }
                }
            } else {
                catalogName = this.getDefaultCatalogName();

                if (catalogName == null) {
                    return escapeObjectName(objectName, objectType);
                } else {
                    if (defaultCatalogSet || (isDefaultCatalog(catalogName) && getOutputDefaultCatalog())) {
                        return escapeObjectName(catalogName, Catalog.class) + "." + escapeObjectName(objectName, objectType);
                    } else {
                        return escapeObjectName(objectName, objectType);
                    }
                }
            }
        }

    } else {
        return escapeObjectName(objectName, objectType);
    }
}
 
Example 14
@Override
public String generateAlterStatement(Database database) {
    StringBuilder alter = new StringBuilder();

    alter.append("ADD CONSTRAINT ");
    if (StringUtil.isNotEmpty(getConstraintName())) {
        alter.append(database.escapeConstraintName(getConstraintName())).append(" ");
    }
    alter.append("FOREIGN KEY ");

    alter.append("(");
    List<String> baseColumns = StringUtils.splitAndTrim(getBaseColumnNames(), ",");
    if (baseColumns == null) baseColumns = Collections.emptyList();
    alter.append(database.escapeColumnNameList(StringUtils.join(baseColumns, ", ")));
    alter.append(") ");

    alter.append("REFERENCES ");
    String referencedTable = PerconaChangeUtil.resolveReferencedPerconaTableName(getBaseTableName(), getReferencedTableName());
    alter.append(database.escapeTableName(getReferencedTableCatalogName(), getReferencedTableSchemaName(), referencedTable)).append(" ");
    alter.append("(");
    List<String> referencedColumns = StringUtils.splitAndTrim(getReferencedColumnNames(), ",");
    if (referencedColumns == null) referencedColumns = Collections.emptyList();
    alter.append(database.escapeColumnNameList(StringUtils.join(referencedColumns, ", ")));
    alter.append(")");

    if (getOnDelete() != null) {
        alter.append(" ON DELETE ").append(getOnDelete());
    }
    if (getOnUpdate() != null) {
        alter.append(" ON UPDATE ").append(getOnUpdate());
    }

    if (getDeferrable() != null && getDeferrable()) {
        alter.append(" DEFERRABLE");
    }
    if (getInitiallyDeferred() != null && getInitiallyDeferred()) {
        alter.append(" INITIALLY DEFERRED");
    }

    return alter.toString();
}
 
Example 15
@Override
public Sql[] generateSql(final AddColumnStatement statement,
      final Database database, final SqlGeneratorChain sqlGeneratorChain) {

   GeometryType geometryType = null;
   final LiquibaseDataType dataType = DataTypeFactory.getInstance()
         .fromDescription(statement.getColumnType(), database);
   if (dataType instanceof GeometryType) {
      geometryType = (GeometryType) dataType;
   }

   final boolean isGeometryColumn = geometryType != null;

   // The AddGeometryColumn procedure handles the column already being
   // present, so let a
   // downstream SQL generator handle the typical column addition logic (e.g.
   // placement in the
   // table) then invoke the procedure.
   final List<Sql> list = new ArrayList<Sql>();
   list.addAll(Arrays.asList(sqlGeneratorChain.generateSql(statement,
         database)));
   if (isGeometryColumn) {
      String schemaName = statement.getSchemaName();
      if (schemaName == null) {
         schemaName = database.getDefaultSchemaName();
      }
      final String tableName = statement.getTableName();
      final String columnName = statement.getColumnName();

      final int srid = geometryType.getSRID();
      final String geomType = StringUtils.trimToNull(geometryType
            .getGeometryType()) == null ? "'Geometry'" : "'"
            + database.escapeStringForDatabase(geometryType
                  .getGeometryType()) + "'";
      final String sql = "CALL AddGeometryColumn('" + schemaName + "', '"
            + tableName + "', '" + columnName + "', " + srid + ", "
            + geomType + ", 2)";
      final Sql addGeometryColumn = new UnparsedSql(sql);
      list.add(addGeometryColumn);
   }
   return list.toArray(new Sql[list.size()]);
}
 
Example 16
Source Project: liquibase-mssql   Source File: CreateIndexGeneratorMSSQL.java    License: Apache License 2.0 4 votes vote down vote up
private Sql[] generateMSSQLSql(CreateIndexStatementMSSQL statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
  StringBuilder builder = new StringBuilder();

  // Basically copied from liquibase.sqlgenerator.core.CreateIndexGenerator
  builder.append("CREATE ");
  if (statement.isUnique() != null && statement.isUnique()) {
    builder.append("UNIQUE ");
  }
  
  if (statement.isClustered() != null) {
      if (statement.isClustered()) {
          builder.append("CLUSTERED ");
      } else {
          builder.append("NONCLUSTERED ");
      }
  }
  
  builder.append("INDEX ");

  if (statement.getIndexName() != null) {
    String indexSchema = statement.getTableSchemaName();
    builder.append(database.escapeIndexName(statement.getTableCatalogName(), indexSchema, statement.getIndexName())).append(" ");
  }
  builder.append("ON ");
  builder.append(database.escapeTableName(statement.getTableCatalogName(), statement.getTableSchemaName(), statement.getTableName())).append("(");
  Iterator<AddColumnConfig> iterator = Arrays.asList(statement.getColumns()).iterator();
  while (iterator.hasNext()) {
    AddColumnConfig column = iterator.next();
    builder.append(database.escapeColumnName(statement.getTableCatalogName(), statement.getTableSchemaName(), statement.getTableName(), column.getName()));
    if (column.getDescending() != null && column.getDescending()) {
        builder.append(" DESC");
    }
    if (iterator.hasNext()) {
      builder.append(", ");
    }
  }
  if (statement.getIncludedColumns() != null && ! statement.getIncludedColumns().isEmpty()) {
    builder.append(") INCLUDE (");
    builder.append(database.escapeColumnNameList(statement.getIncludedColumns()));
  }
  builder.append(")");
  if (statement.getFillFactor() != null) {
    builder.append(" WITH (FILLFACTOR = ").append(statement.getFillFactor()).append(")");
  }
  // This block simplified, since we know we have MSSQLDatabase
  if (StringUtils.trimToNull(statement.getTablespace()) != null) {
    builder.append(" ON ").append(statement.getTablespace());
  }

  return new Sql[]{new UnparsedSql(builder.toString(), getAffectedIndex(statement))};
}