use of liquibase.exception.UnexpectedLiquibaseException in project liquibase by liquibase.
the class ReflectionSerializer method setValue.
public void setValue(Object object, String field, Object value) {
try {
Field foundField = findField(object, field);
foundField.setAccessible(true);
foundField.set(object, value);
} catch (Exception e) {
throw new UnexpectedLiquibaseException(e);
}
}
use of liquibase.exception.UnexpectedLiquibaseException in project liquibase by liquibase.
the class UniqueConstraintSnapshotGenerator method listColumns.
protected List<Map<String, ?>> listColumns(UniqueConstraint example, Database database, DatabaseSnapshot snapshot) throws DatabaseException {
Table table = example.getTable();
Schema schema = table.getSchema();
String name = example.getName();
boolean bulkQuery;
String sql;
String cacheKey = "uniqueConstraints-" + example.getClass().getSimpleName() + "-" + example.getSchema().toCatalogAndSchema().customize(database).toString();
String queryCountKey = "uniqueConstraints-" + example.getClass().getSimpleName() + "-queryCount";
Map<String, List<Map<String, ?>>> columnCache = (Map<String, List<Map<String, ?>>>) snapshot.getScratchData(cacheKey);
Integer columnQueryCount = (Integer) snapshot.getScratchData(queryCountKey);
if (columnQueryCount == null) {
columnQueryCount = 0;
}
if (columnCache == null) {
bulkQuery = (database instanceof OracleDatabase) && columnQueryCount > 3;
snapshot.setScratchData(queryCountKey, columnQueryCount + 1);
if (database instanceof MySQLDatabase || database instanceof HsqlDatabase) {
sql = "select const.CONSTRAINT_NAME, COLUMN_NAME " + "from " + database.getSystemSchema() + ".table_constraints const " + "join " + database.getSystemSchema() + ".key_column_usage col " + "on const.constraint_schema=col.constraint_schema " + "and const.table_name=col.table_name " + "and const.constraint_name=col.constraint_name " + "where const.constraint_schema='" + database.correctObjectName(schema.getCatalogName(), Catalog.class) + "' " + "and const.table_name='" + database.correctObjectName(example.getTable().getName(), Table.class) + "' " + "and const.constraint_name='" + database.correctObjectName(name, UniqueConstraint.class) + "'" + "order by ordinal_position";
} else if (database instanceof PostgresDatabase) {
sql = "select const.CONSTRAINT_NAME, COLUMN_NAME " + "from " + database.getSystemSchema() + ".table_constraints const " + "join " + database.getSystemSchema() + ".key_column_usage col " + "on const.constraint_schema=col.constraint_schema " + "and const.table_name=col.table_name " + "and const.constraint_name=col.constraint_name " + "where const.constraint_catalog='" + database.correctObjectName(schema.getCatalogName(), Catalog.class) + "' " + "and const.constraint_schema='" + database.correctObjectName(schema.getSchema().getName(), Schema.class) + "' " + "and const.table_name='" + database.correctObjectName(example.getTable().getName(), Table.class) + "' " + "and const.constraint_name='" + database.correctObjectName(name, UniqueConstraint.class) + "'" + "order by ordinal_position";
} else if (database instanceof MSSQLDatabase) {
if (database.getDatabaseMajorVersion() >= 9) {
sql = "SELECT " + "[kc].[name] AS [CONSTRAINT_NAME], " + "[c].[name] AS [COLUMN_NAME], " + "CASE [ic].[is_descending_key] WHEN 0 THEN N'A' WHEN 1 THEN N'D' END AS [ASC_OR_DESC] " + "FROM [sys].[schemas] AS [s] " + "INNER JOIN [sys].[tables] AS [t] " + "ON [t].[schema_id] = [s].[schema_id] " + "INNER JOIN [sys].[key_constraints] AS [kc] " + "ON [kc].[parent_object_id] = [t].[object_id] " + "INNER JOIN [sys].[indexes] AS [i] " + "ON [i].[object_id] = [kc].[parent_object_id] " + "AND [i].[index_id] = [kc].[unique_index_id] " + "INNER JOIN [sys].[index_columns] AS [ic] " + "ON [ic].[object_id] = [i].[object_id] " + "AND [ic].[index_id] = [i].[index_id] " + "INNER JOIN [sys].[columns] AS [c] " + "ON [c].[object_id] = [ic].[object_id] " + "AND [c].[column_id] = [ic].[column_id] " + "WHERE [s].[name] = N'" + database.escapeStringForDatabase(database.correctObjectName(schema.getName(), Schema.class)) + "' " + "AND [t].[name] = N'" + database.escapeStringForDatabase(database.correctObjectName(example.getTable().getName(), Table.class)) + "' " + "AND [kc].[name] = N'" + database.escapeStringForDatabase(database.correctObjectName(name, UniqueConstraint.class)) + "' " + "ORDER BY " + "[ic].[key_ordinal]";
} else if (database.getDatabaseMajorVersion() >= 8) {
sql = "SELECT " + "[kc].[name] AS [CONSTRAINT_NAME], " + "[c].[name] AS [COLUMN_NAME], " + "CASE INDEXKEY_PROPERTY([ic].[id], [ic].[indid], [ic].[keyno], 'IsDescending') WHEN 0 THEN N'A' WHEN 1 THEN N'D' END AS [ASC_OR_DESC] " + "FROM [dbo].[sysusers] AS [s] " + "INNER JOIN [dbo].[sysobjects] AS [t] " + "ON [t].[uid] = [s].[uid] " + "INNER JOIN [dbo].[sysobjects] AS [kc] " + "ON [kc].[parent_obj] = [t].[id] " + "INNER JOIN [dbo].[sysindexes] AS [i] " + "ON [i].[id] = [kc].[parent_obj] " + "AND [i].[name] = [kc].[name] " + "INNER JOIN [dbo].[sysindexkeys] AS [ic] " + "ON [ic].[id] = [i].[id] " + "AND [ic].[indid] = [i].[indid] " + "INNER JOIN [dbo].[syscolumns] AS [c] " + "ON [c].[id] = [ic].[id] " + "AND [c].[colid] = [ic].[colid] " + "WHERE [s].[name] = N'" + database.escapeStringForDatabase(database.correctObjectName(schema.getName(), Schema.class)) + "' " + "AND [t].[name] = N'" + database.escapeStringForDatabase(database.correctObjectName(example.getTable().getName(), Table.class)) + "' " + "AND [kc].[name] = N'" + database.escapeStringForDatabase(database.correctObjectName(name, UniqueConstraint.class)) + "' " + "ORDER BY " + "[ic].[keyno]";
} else {
sql = "SELECT " + "[TC].[CONSTRAINT_NAME], " + "[KCU].[COLUMN_NAME] " + "FROM [INFORMATION_SCHEMA].[TABLE_CONSTRAINTS] AS [TC] " + "INNER JOIN [INFORMATION_SCHEMA].[KEY_COLUMN_USAGE] AS [KCU] " + "ON [KCU].[CONSTRAINT_NAME] = [TC].[CONSTRAINT_NAME] " + "WHERE [TC].[CONSTRAINT_SCHEMA] = N'" + database.escapeStringForDatabase(database.correctObjectName(schema.getName(), Schema.class)) + "' " + "AND [TC].[TABLE_NAME] = N'" + database.escapeStringForDatabase(database.correctObjectName(example.getTable().getName(), Table.class)) + "' " + "AND [TC].[CONSTRAINT_NAME] = N'" + database.escapeStringForDatabase(database.correctObjectName(name, UniqueConstraint.class)) + "' " + "ORDER BY " + "[KCU].[ORDINAL_POSITION]";
}
} else if (database instanceof OracleDatabase) {
sql = "select ucc.owner as constraint_container, ucc.constraint_name as constraint_name, ucc.column_name " + "from all_cons_columns ucc " + "where " + (bulkQuery ? "" : "ucc.constraint_name='" + database.correctObjectName(name, UniqueConstraint.class) + "' and ") + "ucc.owner='" + database.correctObjectName(schema.getCatalogName(), Catalog.class) + "' " + "and ucc.table_name not like 'BIN$%' " + "order by ucc.position";
} else if (database instanceof DB2Database) {
if (((DB2Database) database).getDataServerType() == DataServerType.DB2I) {
sql = "select T1.constraint_name as CONSTRAINT_NAME, T2.COLUMN_NAME as COLUMN_NAME from QSYS2.TABLE_CONSTRAINTS T1, QSYS2.SYSCSTCOL T2\n" + "where T1.CONSTRAINT_TYPE='UNIQUE' and T1.CONSTRAINT_NAME=T2.CONSTRAINT_NAME\n" + "and T1.CONSTRAINT_SCHEMA='" + database.correctObjectName(schema.getName(), Schema.class) + "'\n" + "and T2.CONSTRAINT_SCHEMA='" + database.correctObjectName(schema.getName(), Schema.class) + "'\n" + //+ "\n"
"order by T2.COLUMN_NAME\n";
} else if (((DB2Database) database).getDataServerType() == DataServerType.DB2Z) {
sql = "select k.colname as column_name from sysibm.syskeycoluse k, sysibm.systabconst t " + "where k.constname = t.constname " + "and k.tbcreator = t.tbcreator " + "and t.type='U' " + "and k.constname='" + database.correctObjectName(name, UniqueConstraint.class) + "' " + "and t.tbcreator = '" + database.correctObjectName(schema.getName(), Schema.class) + "' " + "order by colseq";
} else {
sql = "select k.colname as column_name from syscat.keycoluse k, syscat.tabconst t " + "where k.constname = t.constname " + "and k.tabschema = t.tabschema " + "and t.type='U' " + "and k.constname='" + database.correctObjectName(name, UniqueConstraint.class) + "' " + "and t.tabschema = '" + database.correctObjectName(schema.getName(), Schema.class) + "' " + "order by colseq";
}
} else if (database instanceof DerbyDatabase) {
sql = "SELECT cg.descriptor as descriptor, t.tablename " + "FROM sys.sysconglomerates cg " + "JOIN sys.syskeys k ON cg.conglomerateid = k.conglomerateid " + "JOIN sys.sysconstraints c ON c.constraintid = k.constraintid " + "JOIN sys.systables t ON c.tableid = t.tableid " + "WHERE c.constraintname='" + database.correctObjectName(name, UniqueConstraint.class) + "'";
List<Map<String, ?>> rows = ExecutorService.getInstance().getExecutor(database).queryForList(new RawSqlStatement(sql));
List<Map<String, ?>> returnList = new ArrayList<Map<String, ?>>();
if (rows.size() == 0) {
return returnList;
} else if (rows.size() > 1) {
throw new UnexpectedLiquibaseException("Got multiple rows back querying unique constraints");
} else {
Map rowData = rows.get(0);
String descriptor = rowData.get("DESCRIPTOR").toString();
descriptor = descriptor.replaceFirst(".*\\(", "").replaceFirst("\\).*", "");
for (String columnNumber : StringUtils.splitAndTrim(descriptor, ",")) {
String columnName = (String) ExecutorService.getInstance().getExecutor(database).queryForObject(new RawSqlStatement("select c.columnname from sys.syscolumns c " + "join sys.systables t on t.tableid=c.referenceid " + "where t.tablename='" + rowData.get("TABLENAME") + "' and c.columnnumber=" + columnNumber), String.class);
Map<String, String> row = new HashMap<String, String>();
row.put("COLUMN_NAME", columnName);
returnList.add(row);
}
return returnList;
}
} else if (database instanceof FirebirdDatabase) {
sql = "SELECT RDB$INDEX_SEGMENTS.RDB$FIELD_NAME AS column_name " + "FROM RDB$INDEX_SEGMENTS " + "LEFT JOIN RDB$INDICES ON RDB$INDICES.RDB$INDEX_NAME = RDB$INDEX_SEGMENTS.RDB$INDEX_NAME " + "WHERE UPPER(RDB$INDICES.RDB$INDEX_NAME)='" + database.correctObjectName(name, UniqueConstraint.class) + "' " + "ORDER BY RDB$INDEX_SEGMENTS.RDB$FIELD_POSITION";
} else if (database instanceof SybaseASADatabase) {
sql = "select sysconstraint.constraint_name, syscolumn.column_name " + "from sysconstraint, syscolumn, systable " + "where sysconstraint.ref_object_id = syscolumn.object_id " + "and sysconstraint.table_object_id = systable.object_id " + "and sysconstraint.constraint_name = '" + database.correctObjectName(name, UniqueConstraint.class) + "' " + "and systable.table_name = '" + database.correctObjectName(example.getTable().getName(), Table.class) + "'";
} else {
String catalogName = database.correctObjectName(schema.getCatalogName(), Catalog.class);
String schemaName = database.correctObjectName(schema.getName(), Schema.class);
String constraintName = database.correctObjectName(name, UniqueConstraint.class);
String tableName = database.correctObjectName(table.getName(), Table.class);
sql = "select CONSTRAINT_NAME, COLUMN_LIST as COLUMN_NAME " + "from " + database.getSystemSchema() + ".constraints " + "where constraint_type='UNIQUE' ";
if (catalogName != null) {
sql += "and constraint_catalog='" + catalogName + "' ";
}
if (schemaName != null) {
sql += "and constraint_schema='" + schemaName + "' ";
}
if (tableName != null) {
sql += "and table_name='" + tableName + "' ";
}
if (constraintName != null) {
sql += "and constraint_name='" + constraintName + "'";
}
}
List<Map<String, ?>> rows = ExecutorService.getInstance().getExecutor(database).queryForList(new RawSqlStatement(sql));
if (bulkQuery) {
columnCache = new HashMap<String, List<Map<String, ?>>>();
snapshot.setScratchData(cacheKey, columnCache);
for (Map<String, ?> row : rows) {
String key = row.get("CONSTRAINT_CONTAINER") + "_" + row.get("CONSTRAINT_NAME");
List<Map<String, ?>> constraintRows = columnCache.get(key);
if (constraintRows == null) {
constraintRows = new ArrayList<Map<String, ?>>();
columnCache.put(key, constraintRows);
}
constraintRows.add(row);
}
return listColumns(example, database, snapshot);
} else {
return rows;
}
} else {
String lookupKey = schema.getName() + "_" + example.getName();
List<Map<String, ?>> rows = columnCache.get(lookupKey);
if (rows == null) {
rows = new ArrayList<Map<String, ?>>();
}
return rows;
}
}
use of liquibase.exception.UnexpectedLiquibaseException in project liquibase by liquibase.
the class AddColumnGenerator method addForeignKeyStatements.
protected void addForeignKeyStatements(AddColumnStatement statement, Database database, List<Sql> returnSql) {
for (ColumnConstraint constraint : statement.getConstraints()) {
if (constraint instanceof ForeignKeyConstraint) {
ForeignKeyConstraint fkConstraint = (ForeignKeyConstraint) constraint;
String refSchemaName = null;
String refTableName;
String refColName;
if (fkConstraint.getReferences() != null) {
Matcher referencesMatcher = Pattern.compile("([\\w\\._]+)\\(([\\w_]+)\\)").matcher(fkConstraint.getReferences());
if (!referencesMatcher.matches()) {
throw new UnexpectedLiquibaseException("Don't know how to find table and column names from " + fkConstraint.getReferences());
}
refTableName = referencesMatcher.group(1);
refColName = referencesMatcher.group(2);
} else {
refTableName = ((ForeignKeyConstraint) constraint).getReferencedTableName();
refColName = ((ForeignKeyConstraint) constraint).getReferencedColumnNames();
}
if (refTableName.indexOf(".") > 0) {
refSchemaName = refTableName.split("\\.")[0];
refTableName = refTableName.split("\\.")[1];
}
AddForeignKeyConstraintStatement addForeignKeyConstraintStatement = new AddForeignKeyConstraintStatement(fkConstraint.getForeignKeyName(), statement.getCatalogName(), statement.getSchemaName(), statement.getTableName(), ColumnConfig.arrayFromNames(statement.getColumnName()), null, refSchemaName, refTableName, ColumnConfig.arrayFromNames(refColName));
returnSql.addAll(Arrays.asList(SqlGeneratorFactory.getInstance().generateSql(addForeignKeyConstraintStatement, database)));
}
}
}
use of liquibase.exception.UnexpectedLiquibaseException in project liquibase by liquibase.
the class AbstractDatabaseObject method load.
@Override
public void load(ParsedNode parsedNode, ResourceAccessor resourceAccessor) throws ParsedNodeException {
for (ParsedNode child : parsedNode.getChildren()) {
String name = child.getName();
if (name.equals("snapshotId")) {
this.snapshotId = child.getValue(String.class);
continue;
}
Class propertyType = ObjectUtil.getPropertyType(this, name);
if (propertyType != null && Collection.class.isAssignableFrom(propertyType) && !(child.getValue() instanceof Collection)) {
if (this.attributes.get(name) == null) {
this.setAttribute(name, new ArrayList<Column>());
}
this.getAttribute(name, List.class).add(child.getValue());
} else {
Object childValue = child.getValue();
if (childValue != null && childValue instanceof String) {
Matcher matcher = Pattern.compile("(.*)!\\{(.*)\\}").matcher((String) childValue);
if (matcher.matches()) {
String stringValue = matcher.group(1);
try {
Class<?> aClass = Class.forName(matcher.group(2));
if (Date.class.isAssignableFrom(aClass)) {
Date date = new ISODateFormat().parse(stringValue);
childValue = aClass.getConstructor(long.class).newInstance(date.getTime());
} else if (Enum.class.isAssignableFrom(aClass)) {
childValue = Enum.valueOf((Class<? extends Enum>) aClass, stringValue);
} else {
childValue = aClass.getConstructor(String.class).newInstance(stringValue);
}
} catch (Exception e) {
throw new UnexpectedLiquibaseException(e);
}
}
}
this.attributes.put(name, childValue);
}
}
}
use of liquibase.exception.UnexpectedLiquibaseException in project liquibase by liquibase.
the class MarkChangeSetRanGenerator method generateSql.
@Override
public Sql[] generateSql(MarkChangeSetRanStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) {
String dateValue = database.getCurrentDateTimeFunction();
ChangeSet changeSet = statement.getChangeSet();
SqlStatement runStatement;
try {
if (statement.getExecType().equals(ChangeSet.ExecType.FAILED) || statement.getExecType().equals(ChangeSet.ExecType.SKIPPED)) {
//don't mark
return new Sql[0];
}
String tag = null;
for (Change change : changeSet.getChanges()) {
if (change instanceof TagDatabaseChange) {
TagDatabaseChange tagChange = (TagDatabaseChange) change;
tag = tagChange.getTag();
}
}
if (statement.getExecType().ranBefore) {
runStatement = new UpdateStatement(database.getLiquibaseCatalogName(), database.getLiquibaseSchemaName(), database.getDatabaseChangeLogTableName()).addNewColumnValue("DATEEXECUTED", new DatabaseFunction(dateValue)).addNewColumnValue("ORDEREXECUTED", ChangeLogHistoryServiceFactory.getInstance().getChangeLogService(database).getNextSequenceValue()).addNewColumnValue("MD5SUM", changeSet.generateCheckSum().toString()).addNewColumnValue("EXECTYPE", statement.getExecType().value).addNewColumnValue("DEPLOYMENT_ID", ChangeLogHistoryServiceFactory.getInstance().getChangeLogService(database).getDeploymentId()).setWhereClause(database.escapeObjectName("ID", Column.class) + " = ? " + "AND " + database.escapeObjectName("AUTHOR", Column.class) + " = ? " + "AND " + database.escapeObjectName("FILENAME", Column.class) + " = ?").addWhereParameters(changeSet.getId(), changeSet.getAuthor(), changeSet.getFilePath());
if (tag != null) {
((UpdateStatement) runStatement).addNewColumnValue("TAG", tag);
}
} else {
runStatement = new InsertStatement(database.getLiquibaseCatalogName(), database.getLiquibaseSchemaName(), database.getDatabaseChangeLogTableName()).addColumnValue("ID", changeSet.getId()).addColumnValue("AUTHOR", changeSet.getAuthor()).addColumnValue("FILENAME", changeSet.getFilePath()).addColumnValue("DATEEXECUTED", new DatabaseFunction(dateValue)).addColumnValue("ORDEREXECUTED", ChangeLogHistoryServiceFactory.getInstance().getChangeLogService(database).getNextSequenceValue()).addColumnValue("MD5SUM", changeSet.generateCheckSum().toString()).addColumnValue("DESCRIPTION", limitSize(changeSet.getDescription())).addColumnValue("COMMENTS", limitSize(StringUtils.trimToEmpty(changeSet.getComments()))).addColumnValue("EXECTYPE", statement.getExecType().value).addColumnValue("CONTEXTS", changeSet.getContexts() == null || changeSet.getContexts().isEmpty() ? null : changeSet.getContexts().toString()).addColumnValue("LABELS", changeSet.getLabels() == null || changeSet.getLabels().isEmpty() ? null : changeSet.getLabels().toString()).addColumnValue("LIQUIBASE", LiquibaseUtil.getBuildVersion().replaceAll("SNAPSHOT", "SNP")).addColumnValue("DEPLOYMENT_ID", ChangeLogHistoryServiceFactory.getInstance().getChangeLogService(database).getDeploymentId());
if (tag != null) {
((InsertStatement) runStatement).addColumnValue("TAG", tag);
}
}
} catch (LiquibaseException e) {
throw new UnexpectedLiquibaseException(e);
}
return SqlGeneratorFactory.getInstance().generateSql(runStatement, database);
}
Aggregations