use of liquibase.exception.DatabaseException in project liquibase by liquibase.
the class CreateTableGenerator method generateSql.
@Override
public Sql[] generateSql(CreateTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
List<Sql> additionalSql = new ArrayList<>();
StringBuilder buffer = new StringBuilder();
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();
BigInteger mysqlTableOptionStartWith = null;
/* We have reached the point after "CREATE TABLE ... (" and will now iterate through the column list. */
while (columnIterator.hasNext()) {
String column = columnIterator.next();
DatabaseDataType columnType = null;
if (statement.getColumnTypes().get(column) != null) {
columnType = statement.getColumnTypes().get(column).toDatabaseDataType(database);
}
if (columnType == null) {
buffer.append(database.escapeColumnName(statement.getCatalogName(), statement.getSchemaName(), statement.getTableName(), column, false));
} else {
buffer.append(database.escapeColumnName(statement.getCatalogName(), statement.getSchemaName(), statement.getTableName(), column, !statement.isComputed(column)));
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 ((database instanceof SQLiteDatabase) && isSinglePrimaryKeyColumn && isPrimaryKeyColumn && isAutoIncrementColumn) {
String pkName = StringUtil.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 != null && !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) || (database instanceof PostgresDatabase)) && statement.getDefaultValue(column).toString().startsWith("GENERATED ALWAYS ")) {
buffer.append(" ");
} else if (database instanceof Db2zDatabase && statement.getDefaultValue(column).toString().contains("CURRENT TIMESTAMP") || statement.getDefaultValue(column).toString().contains("IDENTITY GENERATED BY DEFAULT")) {
buffer.append(" ");
} else {
buffer.append(" DEFAULT ");
}
if (defaultValue instanceof DatabaseFunction) {
buffer.append(database.generateDatabaseFunctionValue((DatabaseFunction) defaultValue));
} else if (database instanceof Db2zDatabase) {
if (statement.getDefaultValue(column).toString().contains("CURRENT TIMESTAMP")) {
buffer.append("");
}
if (statement.getDefaultValue(column).toString().contains("IDENTITY GENERATED BY DEFAULT")) {
buffer.append("GENERATED BY DEFAULT AS IDENTITY");
}
if (statement.getDefaultValue(column).toString().contains("CURRENT USER")) {
buffer.append("SESSION_USER ");
}
if (statement.getDefaultValue(column).toString().contains("CURRENT SQLID")) {
buffer.append("CURRENT SQLID ");
}
} else {
buffer.append(statement.getColumnTypes().get(column).objectToSql(defaultValue, database));
}
}
if (isAutoIncrementColumn) {
if (database instanceof PostgresDatabase && buffer.toString().toLowerCase().endsWith("serial")) {
// don't add more info
} else if (database.supportsAutoIncrement()) {
// TODO: check if database supports auto increment on non primary key column
String autoIncrementClause = database.getAutoIncrementClause(autoIncrementConstraint.getStartWith(), autoIncrementConstraint.getIncrementBy(), autoIncrementConstraint.getGenerationType(), autoIncrementConstraint.getDefaultOnNull());
if (!"".equals(autoIncrementClause)) {
buffer.append(" ").append(autoIncrementClause);
}
if (autoIncrementConstraint.getStartWith() != null) {
if (database instanceof PostgresDatabase) {
int majorVersion = 9;
try {
majorVersion = database.getDatabaseMajorVersion();
} catch (DatabaseException e) {
// ignore
}
if (majorVersion < 10) {
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 {
Scope.getCurrentScope().getLog(getClass()).warning(database.getShortName() + " does not support autoincrement columns as requested for " + (database.escapeTableName(statement.getCatalogName(), statement.getSchemaName(), statement.getTableName())));
}
}
// Do we have a NOT NULL constraint for this column?
if (statement.getNotNullColumns().get(column) != null) {
if (!database.supportsNotNullConstraintNames()) {
buffer.append(" NOT NULL");
} else {
/* Determine if the NOT NULL constraint has a name. */
NotNullConstraint nnConstraintForThisColumn = statement.getNotNullColumns().get(column);
String nncName = StringUtil.trimToNull(nnConstraintForThisColumn.getConstraintName());
if (nncName == null) {
buffer.append(" NOT NULL");
} else {
buffer.append(" CONSTRAINT ");
buffer.append(database.escapeConstraintName(nncName));
buffer.append(" NOT NULL");
}
if (!nnConstraintForThisColumn.shouldValidateNullable()) {
if (database instanceof OracleDatabase) {
buffer.append(" ENABLE NOVALIDATE ");
}
}
}
// does the DB support constraint names?
} else {
if (columnType != null && ((database instanceof SybaseDatabase) || (database instanceof SybaseASADatabase) || (database instanceof MySQLDatabase) || ((database instanceof MSSQLDatabase) && columnType.toString().toLowerCase().contains("timestamp")))) {
buffer.append(" NULL");
}
// Do we need to specify NULL explicitly?
}
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)) {
if ((statement.getPrimaryKeyConstraint() != null) && !statement.getPrimaryKeyConstraint().getColumns().isEmpty()) {
if (database.supportsPrimaryKeyNames()) {
String pkName = StringUtil.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(StringUtil.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(!statement.getPrimaryKeyConstraint().shouldValidatePrimaryKey() ? " ENABLE NOVALIDATE " : "");
if (database.supportsInitiallyDeferrableColumns()) {
if (statement.getPrimaryKeyConstraint().isInitiallyDeferred()) {
buffer.append(" INITIALLY DEFERRED");
}
if (statement.getPrimaryKeyConstraint().isDeferrable()) {
buffer.append(" DEFERRABLE");
}
}
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");
}
if (database instanceof OracleDatabase) {
buffer.append(!fkConstraint.shouldValidateForeignKey() ? " ENABLE NOVALIDATE " : "");
}
buffer.append(",");
}
/*
* In the current syntax, UNIQUE constraints can only be set per column on table creation.
* To alleviate this problem we combine the columns of unique constraints that have the same name.
*/
LinkedHashMap<String, UniqueConstraint> namedUniqueConstraints = new LinkedHashMap<>();
List<UniqueConstraint> unnamedUniqueConstraints = new LinkedList<>();
for (UniqueConstraint uniqueConstraint : statement.getUniqueConstraints()) {
if (uniqueConstraint.getConstraintName() == null) {
// Only combine uniqueConstraints that have a name.
unnamedUniqueConstraints.add(uniqueConstraint);
} else {
String constraintName = uniqueConstraint.getConstraintName();
UniqueConstraint existingConstraint = namedUniqueConstraints.get(constraintName);
if (existingConstraint != null) {
if (uniqueConstraint.shouldValidateUnique()) {
// if validateUnique = true on only one column, make sure it is true
existingConstraint.setValidateUnique(true);
}
existingConstraint.getColumns().addAll(uniqueConstraint.getColumns());
} else {
// if we haven't seen the constraint before put it in the map.
namedUniqueConstraints.put(constraintName, uniqueConstraint);
}
}
}
unnamedUniqueConstraints.addAll(namedUniqueConstraints.values());
for (UniqueConstraint uniqueConstraint : unnamedUniqueConstraints) {
if (uniqueConstraint.getConstraintName() != null) {
buffer.append(" CONSTRAINT ");
buffer.append(database.escapeConstraintName(uniqueConstraint.getConstraintName()));
}
buffer.append(" UNIQUE (");
buffer.append(database.escapeColumnNameList(StringUtil.join(uniqueConstraint.getColumns(), ", ")));
buffer.append(")");
if (database instanceof OracleDatabase) {
buffer.append(!uniqueConstraint.shouldValidateUnique() ? " ENABLE NOVALIDATE " : "");
}
buffer.append(",");
}
/*
* Here, the list of columns and constraints in the form
* ( column1, ..., columnN, constraint1, ..., constraintN,
* ends. We cannot leave an expression like ", )", so we remove the last comma.
*/
String sql = buffer.toString().replaceFirst(",\\s*$", "") + ")";
if ((database instanceof MySQLDatabase) && (mysqlTableOptionStartWith != null)) {
Scope.getCurrentScope().getLog(getClass()).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 AbstractDb2Database) || (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.exception.DatabaseException in project liquibase by liquibase.
the class SnapshotGeneratorFactory method has.
/**
* Checks if a specific object is present in a database
* @param example The DatabaseObject to check for existence
* @param database The DBMS in which the object might exist
* @return true if object existence can be confirmed, false otherweise
* @throws DatabaseException If a problem occurs in the DBMS-specific code
* @throws InvalidExampleException If the object cannot be checked properly, e.g. if the object name is ambiguous
*/
public boolean has(DatabaseObject example, Database database) throws DatabaseException, InvalidExampleException {
// @todo I have seen duplicates in types - maybe convert the List into a Set? Need to understand it more thoroughly.
List<Class<? extends DatabaseObject>> types = new ArrayList<>(getContainerTypes(example.getClass(), database));
types.add(example.getClass());
// @todo Actually, there may be extreme cases (distorted table statistics etc.) where a COUNT(*) might not be so cheap. Maybe SELECT a dummy constant is the better way?
if ((example instanceof Table) && (example.getName().equals(database.getDatabaseChangeLogTableName()) || example.getName().equals(database.getDatabaseChangeLogLockTableName()))) {
try {
Scope.getCurrentScope().getSingleton(ExecutorService.class).getExecutor("jdbc", database).queryForInt(new RawSqlStatement("SELECT COUNT(*) FROM " + database.escapeObjectName(database.getLiquibaseCatalogName(), database.getLiquibaseSchemaName(), example.getName(), Table.class)));
return true;
} catch (DatabaseException e) {
if (database instanceof PostgresDatabase) {
// throws "current transaction is aborted" unless we roll back the connection
database.rollback();
}
return false;
}
}
/*
* If the query is about another object, try to create a snapshot of the of the object (or used the cached
* snapshot. If that works, we count that as confirmation of existence.
*/
SnapshotControl snapshotControl = (new SnapshotControl(database, false, types.toArray(new Class[types.size()])));
snapshotControl.setWarnIfObjectNotFound(false);
if (createSnapshot(example, database, snapshotControl) != null) {
return true;
}
CatalogAndSchema catalogAndSchema;
if (example.getSchema() == null) {
catalogAndSchema = database.getDefaultSchema();
} else {
catalogAndSchema = example.getSchema().toCatalogAndSchema();
}
DatabaseSnapshot snapshot = createSnapshot(catalogAndSchema, database, new SnapshotControl(database, false, example.getClass()).setWarnIfObjectNotFound(false));
for (DatabaseObject obj : snapshot.get(example.getClass())) {
if (DatabaseObjectComparatorFactory.getInstance().isSameObject(example, obj, null, database)) {
return true;
}
}
return false;
}
use of liquibase.exception.DatabaseException in project liquibase by liquibase.
the class ForeignKeySnapshotGenerator method driverUsesSpFkeys.
/*
* Sql server JDBC drivers prior to 6.3.3 used sp_fkeys to determine the delete/cascade metadata.
* The sp_fkeys stored procedure spec says that returned integer values of 0, 1, 2, or 4
* translate to cascade, noAction, SetNull, or SetDefault which are not the values in the JDBC
* standard.
*
* If this method returns true, the sp_fkeys values should be used. Otherwise use the standard jdbc logic
*
* The change in logic went in with https://github.com/Microsoft/mssql-jdbc/pull/490
*/
private boolean driverUsesSpFkeys(Database database) throws DatabaseException {
if (!(database instanceof MSSQLDatabase)) {
return false;
}
DatabaseConnection connection = database.getConnection();
if (!(connection instanceof JdbcConnection)) {
return false;
}
try {
DatabaseMetaData metaData = ((JdbcConnection) connection).getMetaData();
int driverMajorVersion = metaData.getDriverMajorVersion();
int driverMinorVersion = metaData.getDriverMinorVersion();
String driverName = metaData.getDriverName();
if (!driverName.startsWith("Microsoft")) {
return false;
}
if (driverMajorVersion > 6 || (driverMajorVersion == 6 && driverMinorVersion >= 3)) {
return false;
}
return true;
} catch (SQLException e) {
throw new DatabaseException(e);
}
}
use of liquibase.exception.DatabaseException in project liquibase by liquibase.
the class SchemaSnapshotGenerator method snapshotObject.
@Override
protected DatabaseObject snapshotObject(DatabaseObject example, DatabaseSnapshot snapshot) throws DatabaseException, InvalidExampleException {
Database database = snapshot.getDatabase();
Schema match = null;
String catalogName = ((Schema) example).getCatalogName();
String schemaName = example.getName();
if (database.supportsSchemas()) {
if (catalogName == null) {
catalogName = database.getDefaultCatalogName();
}
if (schemaName == null) {
schemaName = database.getDefaultSchemaName();
}
} else {
if (database.supportsCatalogs()) {
if ((catalogName == null) && (schemaName != null)) {
catalogName = schemaName;
schemaName = null;
}
} else {
catalogName = null;
schemaName = null;
}
}
example = new Schema(catalogName, schemaName);
// use LEGACY quoting since we're dealing with system objects
ObjectQuotingStrategy currentStrategy = database.getObjectQuotingStrategy();
database.setObjectQuotingStrategy(ObjectQuotingStrategy.LEGACY);
try {
if (database.supportsSchemas()) {
for (String tableSchema : getDatabaseSchemaNames(database)) {
CatalogAndSchema schemaFromJdbcInfo = toCatalogAndSchema(tableSchema, database);
Catalog catalog = new Catalog(schemaFromJdbcInfo.getCatalogName());
Schema schema = new Schema(catalog, tableSchema);
if (DatabaseObjectComparatorFactory.getInstance().isSameObject(schema, example, snapshot.getSchemaComparisons(), database)) {
if (match == null) {
match = schema;
} else {
throw new InvalidExampleException("Found multiple catalog/schemas matching " + ((Schema) example).getCatalogName() + "." + example.getName());
}
}
}
} else {
// name as equal to the catalog name.
if (((Schema) example).getCatalog().isDefault()) {
match = new Schema(((Schema) example).getCatalog(), catalogName);
} else {
/* Before we confirm the schema/catalog existence, we must first check if the catalog exists. */
Catalog catalog = ((Schema) example).getCatalog();
String[] dbCatalogNames = getDatabaseCatalogNames(database);
for (String candidateCatalogName : dbCatalogNames) {
if (catalog.equals(new Catalog(candidateCatalogName))) {
match = new Schema(catalog, catalogName);
}
}
}
}
} catch (SQLException e) {
throw new DatabaseException(e);
} finally {
database.setObjectQuotingStrategy(currentStrategy);
}
if ((match != null) && ((match.getName() == null) || match.getName().equalsIgnoreCase(database.getDefaultSchemaName()))) {
match.setDefault(true);
}
return match;
}
use of liquibase.exception.DatabaseException in project liquibase by liquibase.
the class TableSnapshotGenerator method snapshotObject.
@Override
protected DatabaseObject snapshotObject(DatabaseObject example, DatabaseSnapshot snapshot) throws DatabaseException {
Database database = snapshot.getDatabase();
String objectName = example.getName();
Schema schema = example.getSchema();
List<CachedRow> rs = null;
try {
JdbcDatabaseSnapshot.CachingDatabaseMetaData metaData = ((JdbcDatabaseSnapshot) snapshot).getMetaDataFromCache();
rs = metaData.getTables(((AbstractJdbcDatabase) database).getJdbcCatalogName(schema), ((AbstractJdbcDatabase) database).getJdbcSchemaName(schema), objectName);
Table table;
if (!rs.isEmpty()) {
table = readTable(rs.get(0), database);
} else {
return null;
}
return table;
} catch (SQLException e) {
throw new DatabaseException(e);
}
}
Aggregations