use of liquibase.statement.SequenceNextValueFunction in project liquibase by liquibase.
the class AddAutoIncrementChange method generateStatements.
@Override
public SqlStatement[] generateStatements(Database database) {
if (database instanceof PostgresDatabase) {
String sequenceName = (getTableName() + "_" + getColumnName() + "_seq");
String escapedTableName = database.escapeObjectName(getTableName(), Table.class);
String escapedColumnName = database.escapeObjectName(getColumnName(), Table.class);
if (escapedTableName != null && escapedColumnName != null && !escapedTableName.startsWith("\"") && !escapedColumnName.startsWith("\"")) {
sequenceName = sequenceName.toLowerCase();
}
String schemaPrefix;
if (this.schemaName == null) {
schemaPrefix = database.getDefaultSchemaName();
} else {
schemaPrefix = this.schemaName;
}
if (schemaPrefix == null) {
schemaPrefix = "";
} else {
schemaPrefix = schemaPrefix + ".";
}
return new SqlStatement[] { new CreateSequenceStatement(catalogName, this.schemaName, sequenceName), new SetNullableStatement(catalogName, this.schemaName, getTableName(), getColumnName(), null, false), new AddDefaultValueStatement(catalogName, this.schemaName, getTableName(), getColumnName(), getColumnDataType(), new SequenceNextValueFunction(schemaPrefix + sequenceName)) };
}
return new SqlStatement[] { new AddAutoIncrementStatement(getCatalogName(), getSchemaName(), getTableName(), getColumnName(), getColumnDataType(), getStartWith(), getIncrementBy()) };
}
use of liquibase.statement.SequenceNextValueFunction in project liquibase by liquibase.
the class CreateTableGenerator method generateSql.
@Override
public Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
if (database instanceof InformixDatabase) {
AbstractSqlGenerator<CreateTableStatement> gen = new CreateTableGeneratorInformix();
return gen.generateSql(statement, database, sqlGeneratorChain);
}
List<Sql> additionalSql = new ArrayList<Sql>();
StringBuffer buffer = new StringBuffer();
buffer.append("CREATE TABLE ").append(database.escapeTableName(statement.getCatalogName(), statement.getSchemaName(), statement.getTableName())).append(" ");
buffer.append("(");
boolean isSinglePrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() == 1;
boolean isPrimaryKeyAutoIncrement = false;
Iterator<String> columnIterator = statement.getColumns().iterator();
List<String> primaryKeyColumns = new LinkedList<String>();
BigInteger mysqlTableOptionStartWith = null;
while (columnIterator.hasNext()) {
String column = columnIterator.next();
DatabaseDataType columnType = statement.getColumnTypes().get(column).toDatabaseDataType(database);
buffer.append(database.escapeColumnName(statement.getCatalogName(), statement.getSchemaName(), statement.getTableName(), column, true));
buffer.append(" ").append(columnType);
AutoIncrementConstraint autoIncrementConstraint = null;
for (AutoIncrementConstraint currentAutoIncrementConstraint : statement.getAutoIncrementConstraints()) {
if (column.equals(currentAutoIncrementConstraint.getColumnName())) {
autoIncrementConstraint = currentAutoIncrementConstraint;
break;
}
}
boolean isAutoIncrementColumn = autoIncrementConstraint != null;
boolean isPrimaryKeyColumn = statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().contains(column);
isPrimaryKeyAutoIncrement = isPrimaryKeyAutoIncrement || isPrimaryKeyColumn && isAutoIncrementColumn;
if (isPrimaryKeyColumn) {
primaryKeyColumns.add(column);
}
if ((database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyColumn && isAutoIncrementColumn) {
String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName());
if (pkName == null) {
pkName = database.generatePrimaryKeyName(statement.getTableName());
}
if (pkName != null) {
buffer.append(" CONSTRAINT ");
buffer.append(database.escapeConstraintName(pkName));
}
buffer.append(" PRIMARY KEY");
}
// for the serial data type in postgres, there should be no default value
if (!columnType.isAutoIncrement() && statement.getDefaultValue(column) != null) {
Object defaultValue = statement.getDefaultValue(column);
if (database instanceof MSSQLDatabase) {
String constraintName = statement.getDefaultValueConstraintName(column);
if (constraintName == null) {
constraintName = ((MSSQLDatabase) database).generateDefaultConstraintName(statement.getTableName(), column);
}
buffer.append(" CONSTRAINT ").append(database.escapeObjectName(constraintName, ForeignKey.class));
}
if (database instanceof OracleDatabase && statement.getDefaultValue(column).toString().startsWith("GENERATED ALWAYS ")) {
buffer.append(" ");
} else {
buffer.append(" DEFAULT ");
}
if (defaultValue instanceof SequenceNextValueFunction) {
buffer.append(database.generateDatabaseFunctionValue((SequenceNextValueFunction) defaultValue));
} else {
buffer.append(statement.getColumnTypes().get(column).objectToSql(defaultValue, database));
}
}
if (isAutoIncrementColumn) {
// TODO: check if database supports auto increment on non primary key column
if (database.supportsAutoIncrement()) {
String autoIncrementClause = database.getAutoIncrementClause(autoIncrementConstraint.getStartWith(), autoIncrementConstraint.getIncrementBy());
if (!"".equals(autoIncrementClause)) {
buffer.append(" ").append(autoIncrementClause);
}
if (autoIncrementConstraint.getStartWith() != null) {
if (database instanceof PostgresDatabase) {
String sequenceName = statement.getTableName() + "_" + column + "_seq";
additionalSql.add(new UnparsedSql("alter sequence " + database.escapeSequenceName(statement.getCatalogName(), statement.getSchemaName(), sequenceName) + " start with " + autoIncrementConstraint.getStartWith(), new Sequence().setName(sequenceName).setSchema(statement.getCatalogName(), statement.getSchemaName())));
} else if (database instanceof MySQLDatabase) {
mysqlTableOptionStartWith = autoIncrementConstraint.getStartWith();
}
}
} else {
LogFactory.getLogger().warning(database.getShortName() + " does not support autoincrement columns as requested for " + (database.escapeTableName(statement.getCatalogName(), statement.getSchemaName(), statement.getTableName())));
}
}
if (statement.getNotNullColumns().contains(column)) {
buffer.append(" NOT NULL");
} else {
if (database instanceof SybaseDatabase || database instanceof SybaseASADatabase || database instanceof MySQLDatabase || (database instanceof MSSQLDatabase && columnType.toString().toLowerCase().contains("timestamp"))) {
buffer.append(" NULL");
}
}
if (database instanceof InformixDatabase && isSinglePrimaryKeyColumn && isPrimaryKeyColumn) {
//buffer.append(" PRIMARY KEY");
}
if (database instanceof MySQLDatabase && statement.getColumnRemarks(column) != null) {
buffer.append(" COMMENT '" + database.escapeStringForDatabase(statement.getColumnRemarks(column)) + "'");
}
if (columnIterator.hasNext()) {
buffer.append(", ");
}
}
buffer.append(",");
if (!((database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyAutoIncrement) && !((database instanceof InformixDatabase) && isSinglePrimaryKeyColumn)) {
if (statement.getPrimaryKeyConstraint() != null && statement.getPrimaryKeyConstraint().getColumns().size() > 0) {
if (database.supportsPrimaryKeyNames()) {
String pkName = StringUtils.trimToNull(statement.getPrimaryKeyConstraint().getConstraintName());
if (pkName == null) {
// TODO ORA-00972: identifier is too long
// If tableName lenght is more then 28 symbols
// then generated pkName will be incorrect
pkName = database.generatePrimaryKeyName(statement.getTableName());
}
if (pkName != null) {
buffer.append(" CONSTRAINT ");
buffer.append(database.escapeConstraintName(pkName));
}
}
buffer.append(" PRIMARY KEY (");
buffer.append(database.escapeColumnNameList(StringUtils.join(statement.getPrimaryKeyConstraint().getColumns(), ", ")));
buffer.append(")");
// Setting up table space for PK's index if it exist
if ((database instanceof OracleDatabase || database instanceof PostgresDatabase) && statement.getPrimaryKeyConstraint().getTablespace() != null) {
buffer.append(" USING INDEX TABLESPACE ");
buffer.append(statement.getPrimaryKeyConstraint().getTablespace());
}
buffer.append(",");
}
}
for (ForeignKeyConstraint fkConstraint : statement.getForeignKeyConstraints()) {
if (!(database instanceof InformixDatabase)) {
buffer.append(" CONSTRAINT ");
buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName()));
}
String referencesString = fkConstraint.getReferences();
buffer.append(" FOREIGN KEY (").append(database.escapeColumnName(statement.getCatalogName(), statement.getSchemaName(), statement.getTableName(), fkConstraint.getColumn())).append(") REFERENCES ");
if (referencesString != null) {
if (!referencesString.contains(".") && database.getDefaultSchemaName() != null && database.getOutputDefaultSchema()) {
referencesString = database.escapeObjectName(database.getDefaultSchemaName(), Schema.class) + "." + referencesString;
}
buffer.append(referencesString);
} else {
buffer.append(database.escapeObjectName(fkConstraint.getReferencedTableCatalogName(), fkConstraint.getReferencedTableSchemaName(), fkConstraint.getReferencedTableName(), Table.class)).append("(").append(database.escapeColumnNameList(fkConstraint.getReferencedColumnNames())).append(")");
}
if (fkConstraint.isDeleteCascade()) {
buffer.append(" ON DELETE CASCADE");
}
if ((database instanceof InformixDatabase)) {
buffer.append(" CONSTRAINT ");
buffer.append(database.escapeConstraintName(fkConstraint.getForeignKeyName()));
}
if (fkConstraint.isInitiallyDeferred()) {
buffer.append(" INITIALLY DEFERRED");
}
if (fkConstraint.isDeferrable()) {
buffer.append(" DEFERRABLE");
}
buffer.append(",");
}
for (UniqueConstraint uniqueConstraint : statement.getUniqueConstraints()) {
if (uniqueConstraint.getConstraintName() != null && !constraintNameAfterUnique(database)) {
buffer.append(" CONSTRAINT ");
buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName()));
}
buffer.append(" UNIQUE (");
buffer.append(database.escapeColumnNameList(StringUtils.join(uniqueConstraint.getColumns(), ", ")));
buffer.append(")");
if (uniqueConstraint.getConstraintName() != null && constraintNameAfterUnique(database)) {
buffer.append(" CONSTRAINT ");
buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName()));
}
buffer.append(",");
}
// if (constraints != null && constraints.getCheckConstraint() != null) {
// buffer.append(constraints.getCheckConstraint()).append(" ");
// }
// }
String sql = buffer.toString().replaceFirst(",\\s*$", "") + ")";
if (database instanceof MySQLDatabase && mysqlTableOptionStartWith != null) {
LogFactory.getLogger().info("[MySQL] Using last startWith statement (" + mysqlTableOptionStartWith.toString() + ") as table option.");
sql += " " + ((MySQLDatabase) database).getTableOptionAutoIncrementStartWithClause(mysqlTableOptionStartWith);
}
if (statement.getTablespace() != null && database.supportsTablespaces()) {
if (database instanceof MSSQLDatabase || database instanceof SybaseASADatabase) {
sql += " ON " + statement.getTablespace();
} else if (database instanceof DB2Database || database instanceof InformixDatabase) {
sql += " IN " + statement.getTablespace();
} else {
sql += " TABLESPACE " + statement.getTablespace();
}
}
if (database instanceof MySQLDatabase && statement.getRemarks() != null) {
sql += " COMMENT='" + database.escapeStringForDatabase(statement.getRemarks()) + "' ";
}
additionalSql.add(0, new UnparsedSql(sql, getAffectedTable(statement)));
return additionalSql.toArray(new Sql[additionalSql.size()]);
}
use of liquibase.statement.SequenceNextValueFunction in project liquibase by liquibase.
the class AddDefaultValueGenerator method validate.
@Override
public ValidationErrors validate(AddDefaultValueStatement addDefaultValueStatement, Database database, SqlGeneratorChain sqlGeneratorChain) {
Object defaultValue = addDefaultValueStatement.getDefaultValue();
ValidationErrors validationErrors = new ValidationErrors();
validationErrors.checkRequiredField("defaultValue", defaultValue);
validationErrors.checkRequiredField("columnName", addDefaultValueStatement.getColumnName());
validationErrors.checkRequiredField("tableName", addDefaultValueStatement.getTableName());
if (!database.supportsSequences() && defaultValue instanceof SequenceNextValueFunction) {
validationErrors.addError("Database " + database.getShortName() + " does not support sequences");
}
if (database instanceof HsqlDatabase) {
if (defaultValue instanceof SequenceNextValueFunction) {
validationErrors.addError("Database " + database.getShortName() + " does not support adding sequence-based default values");
} else if (defaultValue instanceof DatabaseFunction && !HsqlDatabase.supportsDefaultValueComputed(addDefaultValueStatement.getColumnDataType(), defaultValue.toString())) {
validationErrors.addError("Database " + database.getShortName() + " does not support adding function-based default values");
}
}
String columnDataType = addDefaultValueStatement.getColumnDataType();
if (columnDataType != null) {
LiquibaseDataType dataType = DataTypeFactory.getInstance().fromDescription(columnDataType, database);
boolean typeMismatch = false;
if (dataType instanceof BooleanType) {
if (!(defaultValue instanceof Boolean)) {
typeMismatch = true;
}
} else if (dataType instanceof CharType) {
if (!(defaultValue instanceof String) && !(defaultValue instanceof DatabaseFunction)) {
typeMismatch = true;
}
}
if (typeMismatch) {
validationErrors.addError("Default value of " + defaultValue + " does not match defined type of " + columnDataType);
}
}
return validationErrors;
}
use of liquibase.statement.SequenceNextValueFunction in project liquibase by liquibase.
the class AddDefaultValueGeneratorPostgres method generateSql.
@Override
public Sql[] generateSql(final AddDefaultValueStatement statement, final Database database, final SqlGeneratorChain sqlGeneratorChain) {
if (!(statement.getDefaultValue() instanceof SequenceNextValueFunction)) {
return super.generateSql(statement, database, sqlGeneratorChain);
}
List<Sql> commands = new ArrayList<Sql>(Arrays.asList(super.generateSql(statement, database, sqlGeneratorChain)));
// for postgres, we need to also set the sequence to be owned by this table for true serial like functionality.
// this will allow a drop table cascade to remove the sequence as well.
SequenceNextValueFunction sequenceFunction = (SequenceNextValueFunction) statement.getDefaultValue();
String sequenceName = sequenceFunction.getValue();
String sequenceSchemaName = sequenceFunction.getSequenceSchemaName();
String sequence = database.escapeObjectName(null, sequenceSchemaName, sequenceName, Sequence.class);
Sql alterSequenceOwner = new UnparsedSql("ALTER SEQUENCE " + sequence + " OWNED BY " + database.escapeTableName(statement.getCatalogName(), statement.getSchemaName(), statement.getTableName()) + "." + database.escapeObjectName(statement.getColumnName(), Column.class), getAffectedColumn(statement), getAffectedSequence(sequenceFunction));
commands.add(alterSequenceOwner);
return commands.toArray(new Sql[commands.size()]);
}
use of liquibase.statement.SequenceNextValueFunction in project liquibase by liquibase.
the class ObjectUtil method setProperty.
public static void setProperty(Object object, String propertyName, String propertyValue) {
Method method = getWriteMethod(object, propertyName);
if (method == null) {
throw new UnexpectedLiquibaseException("Property '" + propertyName + "' not found on object type " + object.getClass().getName());
}
Class<?> parameterType = method.getParameterTypes()[0];
Object finalValue = propertyValue;
if (parameterType.equals(Boolean.class) || parameterType.equals(boolean.class)) {
finalValue = Boolean.valueOf(propertyValue);
} else if (parameterType.equals(Integer.class)) {
finalValue = Integer.valueOf(propertyValue);
} else if (parameterType.equals(Long.class)) {
finalValue = Long.valueOf(propertyValue);
} else if (parameterType.equals(BigInteger.class)) {
finalValue = new BigInteger(propertyValue);
} else if (parameterType.equals(BigDecimal.class)) {
finalValue = new BigDecimal(propertyValue);
} else if (parameterType.equals(DatabaseFunction.class)) {
finalValue = new DatabaseFunction(propertyValue);
} else if (parameterType.equals(SequenceNextValueFunction.class)) {
finalValue = new SequenceNextValueFunction(propertyValue);
} else if (parameterType.equals(SequenceCurrentValueFunction.class)) {
finalValue = new SequenceCurrentValueFunction(propertyValue);
} else if (Enum.class.isAssignableFrom(parameterType)) {
finalValue = Enum.valueOf((Class<Enum>) parameterType, propertyValue);
}
try {
method.invoke(object, finalValue);
} catch (IllegalAccessException e) {
throw new UnexpectedLiquibaseException(e);
} catch (IllegalArgumentException e) {
throw new UnexpectedLiquibaseException("Cannot call " + method.toString() + " with value of type " + finalValue.getClass().getName());
} catch (InvocationTargetException e) {
throw new UnexpectedLiquibaseException(e);
}
}
Aggregations