void createPrimaryKey() { if (!isOneToMany()) { PrimaryKey pk = new PrimaryKey(); pk.addColumns(getKey().getColumnIterator()); // index should be last column listed boolean isFormula = false; Iterator iter = getIndex().getColumnIterator(); while (iter.hasNext()) { if (((Selectable) iter.next()).isFormula()) isFormula = true; } if (isFormula) { // if it is a formula index, use the element columns in the PK pk.addColumns(getElement().getColumnIterator()); } else { pk.addColumns(getIndex().getColumnIterator()); } getCollectionTable().setPrimaryKey(pk); } else { // don't create a unique key, 'cos some // databases don't like a UK on nullable // columns /*ArrayList list = new ArrayList(); list.addAll( getKey().getConstraintColumns() ); list.addAll( getIndex().getConstraintColumns() ); getCollectionTable().createUniqueKey(list);*/ } }
private boolean isSameAsPrimaryKeyColumns(UniqueKey uniqueKey) { if (primaryKey == null || !primaryKey.columnIterator().hasNext()) { // happens for many-to-many tables return false; } return primaryKey.getColumns().containsAll(uniqueKey.getColumns()) && uniqueKey.getColumns().containsAll(primaryKey.getColumns()); }
public static Map<PrimaryKey, Map<String, Object>> convertData( List<Map<String, Object>> data, DBTable t) { Map<PrimaryKey, Map<String, Object>> result = new HashMap<PrimaryKey, Map<String, Object>>(); for (Map<String, Object> map : data) { PrimaryKey key = new PrimaryKey(); for (DBColumn c : t.getPrimaryKey().getColumns()) { key.addKeyValue(map.get(c.getColumnName())); } result.put(key, map); } return result; }
/** * Called when the column is removed from its table. Removes the column from all table constraints * and indexes, then invalidates it. */ void remove() { Table table = getTable(); if (table == null) return; Schema schema = table.getSchema(); if (schema != null && schema.getSchemaGroup() != null) { Schema[] schemas = schema.getSchemaGroup().getSchemas(); Table[] tabs; ForeignKey[] fks; Column[] cols; Column[] pks; for (int i = 0; i < schemas.length; i++) { tabs = schemas[i].getTables(); for (int j = 0; j < tabs.length; j++) { fks = tabs[j].getForeignKeys(); for (int k = 0; k < fks.length; k++) { cols = fks[k].getColumns(); pks = fks[k].getPrimaryKeyColumns(); for (int l = 0; l < cols.length; l++) if (this.equals(cols[l]) || this.equals(pks[l])) fks[k].removeJoin(cols[l]); cols = fks[k].getConstantColumns(); for (int l = 0; l < cols.length; l++) if (this.equals(cols[l])) fks[k].removeJoin(cols[l]); pks = fks[k].getConstantPrimaryKeyColumns(); for (int l = 0; l < pks.length; l++) if (this.equals(pks[l])) fks[k].removeJoin(pks[l]); if (fks[k].getColumns().length == 0 && fks[k].getConstantColumns().length == 0) tabs[j].removeForeignKey(fks[k]); } } } } Index[] idxs = table.getIndexes(); for (int i = 0; i < idxs.length; i++) if (idxs[i].removeColumn(this) && idxs[i].getColumns().length == 0) table.removeIndex(idxs[i]); Unique[] unqs = table.getUniques(); for (int i = 0; i < unqs.length; i++) if (unqs[i].removeColumn(this) && unqs[i].getColumns().length == 0) table.removeUnique(unqs[i]); PrimaryKey pk = table.getPrimaryKey(); if (pk != null && pk.removeColumn(this) && pk.getColumns().length == 0) table.removePrimaryKey(); _table = null; }
public static List<Map<String, Object>> read(ResultSet rs, DBTable t) throws SQLException { List<Map<String, Object>> data = new ArrayList<Map<String, Object>>(); List<DBColumn> pkc = t.getPrimaryKey().getColumns(); while (rs.next()) { PrimaryKey key = new PrimaryKey(); for (DBColumn c : pkc) { key.addKeyValue(rs.getObject(c.getColumnName())); } Map<String, Object> fieldValues = new HashMap<String, Object>(); for (DBColumn c : t.getColumns()) { fieldValues.put(c.getColumnName(), rs.getObject(c.getColumnName())); } data.add(fieldValues); } return data; }
@Test public void update_all_should_work_properly() { List<Duo> before = findAll(); assertThat(before.size(), equalTo(6)); assertThat(before.get(0).toString(), equalTo("Duo{id=1, a=A, b=A}")); assertThat(before.get(1).toString(), equalTo("Duo{id=2, a=A, b=B}")); assertThat(before.get(2).toString(), equalTo("Duo{id=3, a=A, b=C}")); assertThat(before.get(3).toString(), equalTo("Duo{id=4, a=B, b=A}")); assertThat(before.get(4).toString(), equalTo("Duo{id=5, a=B, b=B}")); assertThat(before.get(5).toString(), equalTo("Duo{id=6, a=B, b=C}")); Duo duo = new Duo("XXX", "ZZZ"); atomicMerge.update(duo).with(PrimaryKey.id(3)); List<Duo> after = findAll(); assertThat(after.size(), equalTo(6)); assertThat(after.get(0).toString(), equalTo("Duo{id=1, a=A, b=A}")); assertThat(after.get(1).toString(), equalTo("Duo{id=2, a=A, b=B}")); assertThat(after.get(2).toString(), equalTo("Duo{id=3, a=XXX, b=ZZZ}")); assertThat(after.get(3).toString(), equalTo("Duo{id=4, a=B, b=A}")); assertThat(after.get(4).toString(), equalTo("Duo{id=5, a=B, b=B}")); assertThat(after.get(5).toString(), equalTo("Duo{id=6, a=B, b=C}")); }
public void primaryKey(PrimaryKey pk) { Iterator pkColumns = pk.columns().iterator(); while (pkColumns.hasNext()) { if (!columns.contains(pkColumns.next())) { throw new IllegalArgumentException("No such column"); } } this.primaryKey = pk; }
public static String getPk(Table table) { PrimaryKey pk = table.getPrimaryKey(); StringBuffer buf = new StringBuffer(); buf.append("{\n"); printJsonValue(buf, "pkName", pk.getPrimaryKeyName(), false); buf.append("\"columns\": [\n"); int i = 1; int size = pk.getPrimaryKeyColumns().size(); for (PrimaryKeyColumn col : pk.getPrimaryKeyColumns()) { buf.append("{\n"); printJsonValue(buf, "name", col.getColumnName(), true); buf.append("}\n"); if (i != size) { buf.append(","); } i++; } buf.append("]\n"); buf.append("}\n"); return buf.toString(); }
public void refreshPrimaryKeys(DatabaseMetaData metaData) throws SQLException { primaryKeys.clear(); ResultSet rs = null; try { rs = metaData.getPrimaryKeys(catalog, schema, name); while (rs.next()) { PrimaryKey pk = new PrimaryKey(); primaryKeys.add(pk); pk.setOwner(this); pk.setColumnName(rs.getString("COLUMN_NAME")); pk.setKeySequence(rs.getShort("KEY_SEQ")); pk.setName(rs.getString("PK_NAME")); } } catch (SQLException sqle) { throw sqle; } finally { try { rs.close(); } catch (Exception ex) { } } }
public void toCreateSQL(PrintWriter out) { out.println("CREATE TABLE " + name + " ("); for (Iterator<Column> i = columns.iterator(); i.hasNext(); ) { Column c = i.next(); out.print(" " + c.getName() + " " + c.getTypeName()); if (c.getNullable() == DatabaseMetaData.columnNoNulls) out.print(" NOT NULL"); if (i.hasNext()) out.println(','); } if (!primaryKeys.isEmpty()) { out.println(','); Iterator<PrimaryKey> i = primaryKeys.iterator(); PrimaryKey pk = i.next(); out.print(" "); if (pk.getName() != null) { out.print("CONSTRAINT " + pk.getName() + " "); } out.print("PRIMARY KEY (" + pk.getColumnName()); while (i.hasNext()) { pk = i.next(); out.print(", " + pk.getColumnName()); } out.print(")"); } if (!foreignKeys.isEmpty()) { out.println(','); for (Iterator<ForeignKey> i = foreignKeys.iterator(); i.hasNext(); ) { ForeignKey fk = i.next(); out.print(" "); if (fk.getName() != null) out.print("CONSTRAINT " + fk.getName() + " "); out.print("FOREIGN KEY (" + fk.getColumnName() + ") REFERENCES " + fk.getPkTableName()); if (fk.getPkColumnName() != null) out.print(" (" + fk.getPkColumnName() + ")"); if (i.hasNext()) out.println(','); } } out.println(); out.print(")"); }
@Override protected String getKey(final PrimaryKey value) { return value.getColumnName(); }
public boolean Validate(ParserSession PS, Schema ParentSchema, int pos) { int Errs = PS.getErrorCount(); _ParentSchema = ParentSchema; LOG.debug(" Validating Enumeration " + _Name + "."); // Mandatories if (TextUtil.isNullOrEmpty(_Name) == true) return PS.AddError( "Schema '" + _ParentSchema.getFullName() + "' is declaring an enumeration '" + _Name + "' without a name."); if (ValidationHelper.isValidIdentifier(_Name) == false) return PS.AddError( "Schema '" + _ParentSchema.getFullName() + "' is declaring an enumeration '" + _Name + "' with a name which is not valid. " + ValidationHelper._ValidIdentifierMessage); if (TextUtil.isNullOrEmpty(_Description) == true) return PS.AddError( "Schema '" + _ParentSchema.getFullName() + "' is declaring an enumeration '" + _Name + "' without a description."); if (_Id == null) return PS.AddError( "Schema '" + _ParentSchema.getFullName() + "' is declaring an enumeration '" + _Name + "' without an Id type."); if (_Value == null) return PS.AddError( "Schema '" + _ParentSchema.getFullName() + "' is declaring an enumeration '" + _Name + "' without a Value type."); Object O = new Object(); O._FST = FrameworkSourcedType.ENUMERATION; O._Name = _Name; O._Description = _Description; Column C = new Column( "id", _Id._TypeStr, _Id._Size, false, ColumnMode.NORMAL, true, null, "The id for this enumeration."); O._Columns.add(C); C = new Column( "value", _Value._TypeStr, _Value._Size, false, ColumnMode.NORMAL, true, null, "The value for this enumeration."); O._Columns.add(C); C = new Column( "label", ColumnType.STRING.toString(), 254, false, ColumnMode.NORMAL, false, ProtectionType.ABSOLUTE, "The label for this enumeration."); O._Columns.add(C); C = new Column( "deactivated", ColumnType.DATETIME.toString(), null, true, ColumnMode.NORMAL, false, null, "The label for this enumeration."); C._FrameworkManaged = true; O._Columns.add(C); PrimaryKey PK = new PrimaryKey(); PK._Columns = new String[] {"id"}; O._PrimaryKey = PK; O._Indices = new ArrayList<Index>(); Index I = new Index(); I._Name = "Id"; I._Columns = new String[] {"id"}; I._Db = true; O._Indices.add(I); I = new Index(); I._Name = "Value"; I._Columns = new String[] {"value"}; I._Db = true; O._Indices.add(I); I = new Index(); I._Name = "All"; I._OrderBy = new String[] {"id"}; I._Db = false; O._Indices.add(I); _ParentSchema._Objects.add(pos, O); return Errs == PS.getErrorCount(); }
public boolean removePrimaryKey(PrimaryKey primaryKey) { primaryKey.setOwner(null); return primaryKeys.remove(primaryKey); }
public void addPrimaryKey(PrimaryKey primaryKey) { primaryKeys.add(primaryKey); primaryKey.setOwner(this); }
@Override public Change[] fixMissing( DatabaseObject missingObject, DiffOutputControl control, Database referenceDatabase, Database comparisonDatabase, ChangeGeneratorChain chain) { List<Change> returnList = new ArrayList<Change>(); PrimaryKey pk = (PrimaryKey) missingObject; AddPrimaryKeyChange change = new AddPrimaryKeyChange(); change.setTableName(pk.getTable().getName()); if (control.getIncludeCatalog()) { change.setCatalogName(pk.getTable().getSchema().getCatalogName()); } if (control.getIncludeSchema()) { change.setSchemaName(pk.getTable().getSchema().getName()); } change.setConstraintName(pk.getName()); change.setColumnNames(pk.getColumnNames()); if (control.getIncludeTablespace()) { change.setTablespace(pk.getTablespace()); } if (referenceDatabase instanceof MSSQLDatabase && pk.getBackingIndex() != null && pk.getBackingIndex().getClustered() != null && !pk.getBackingIndex().getClustered()) { change.setClustered(false); } if (comparisonDatabase instanceof OracleDatabase || (comparisonDatabase instanceof DB2Database && pk.getBackingIndex() != null && !comparisonDatabase.isSystemObject(pk.getBackingIndex()))) { Index backingIndex = pk.getBackingIndex(); if (backingIndex != null && backingIndex.getName() != null) { try { if (!control.getIncludeCatalog() && !control.getIncludeSchema()) { CatalogAndSchema schema = comparisonDatabase.getDefaultSchema().customize(comparisonDatabase); backingIndex .getTable() .setSchema( schema.getCatalogName(), schema .getSchemaName()); // set table schema so it is found in the correct schema } if (referenceDatabase.equals(comparisonDatabase) || !SnapshotGeneratorFactory.getInstance().has(backingIndex, comparisonDatabase)) { Change[] fixes = ChangeGeneratorFactory.getInstance() .fixMissing(backingIndex, control, referenceDatabase, comparisonDatabase); if (fixes != null) { for (Change fix : fixes) { if (fix != null) { returnList.add(fix); } } } } } catch (Exception e) { throw new UnexpectedLiquibaseException(e); } change.setForIndexName(backingIndex.getName()); Schema schema = backingIndex.getSchema(); if (schema != null) { if (control.getIncludeCatalog()) { change.setForIndexCatalogName(schema.getCatalogName()); } if (control.getIncludeSchema()) { change.setForIndexSchemaName(schema.getName()); } } } } control.setAlreadyHandledMissing(pk.getBackingIndex()); returnList.add(change); return returnList.toArray(new Change[returnList.size()]); }
@Override protected void readPrimaryKeys( DatabaseSnapshot snapshot, String schema, DatabaseMetaData databaseMetaData) throws DatabaseException, SQLException { Database database = snapshot.getDatabase(); updateListeners("Reading primary keys for " + database.toString() + " ..."); // we can't add directly to the this.primaryKeys hashSet because adding columns to an exising PK // changes the hashCode and .contains() fails List<PrimaryKey> foundPKs = new ArrayList<PrimaryKey>(); // Setting default schema name. Needed for correct statement generation if (schema == null) schema = database.convertRequestedSchemaToSchema(schema); String query = "select uc.table_name TABLE_NAME,ucc.column_name COLUMN_NAME,ucc.position KEY_SEQ,uc.constraint_name PK_NAME,ui.tablespace_name TABLESPACE from all_constraints uc,all_indexes ui,all_cons_columns ucc where uc.constraint_type = 'P' and uc.index_name = ui.index_name and uc.constraint_name = ucc.constraint_name and uc.owner = '" + schema + "' and ui.table_owner = '" + schema + "' and ucc.owner = '" + schema + "' and uc.table_name = ui.table_name and ui.table_name = ucc.table_name"; Statement statement = null; ResultSet rs = null; try { statement = ((JdbcConnection) database.getConnection()).getUnderlyingConnection().createStatement(); rs = statement.executeQuery(query); while (rs.next()) { String tableName = convertFromDatabaseName(rs.getString("TABLE_NAME")); String tablespace = convertFromDatabaseName(rs.getString("TABLESPACE")); String columnName = convertFromDatabaseName(rs.getString("COLUMN_NAME")); short position = rs.getShort("KEY_SEQ"); boolean foundExistingPK = false; for (PrimaryKey pk : foundPKs) { if (pk.getTable().getName().equals(tableName)) { pk.addColumnName(position - 1, columnName); foundExistingPK = true; } } if (!foundExistingPK && !database.isLiquibaseTable(tableName)) { PrimaryKey primaryKey = new PrimaryKey(); primaryKey.setTablespace(tablespace); Table table = snapshot.getTable(tableName); if (table == null) { continue; // probably a different schema } primaryKey.setTable(table); primaryKey.addColumnName(position - 1, columnName); primaryKey.setName(convertPrimaryKeyName(rs.getString("PK_NAME"))); foundPKs.add(primaryKey); } } } finally { JdbcUtils.closeResultSet(rs); JdbcUtils.closeStatement(statement); } snapshot.getPrimaryKeys().addAll(foundPKs); }
@Override protected void readIndexes( DatabaseSnapshot snapshot, String schema, DatabaseMetaData databaseMetaData) throws DatabaseException, SQLException { Database database = snapshot.getDatabase(); updateListeners("Reading indexes for " + database.toString() + " ..."); String query = "select aic.index_name, 3 AS TYPE, aic.table_name, aic.column_name, aic.column_position AS ORDINAL_POSITION, null AS FILTER_CONDITION, ai.tablespace_name AS TABLESPACE, ai.uniqueness FROM all_ind_columns aic, all_indexes ai WHERE aic.table_owner='" + database.convertRequestedSchemaToSchema(schema) + "' and aic.index_name = ai.index_name ORDER BY INDEX_NAME, ORDINAL_POSITION"; Statement statement = null; ResultSet rs = null; Map<String, Index> indexMap = null; try { statement = ((JdbcConnection) database.getConnection()).getUnderlyingConnection().createStatement(); rs = statement.executeQuery(query); indexMap = new HashMap<String, Index>(); while (rs.next()) { String indexName = convertFromDatabaseName(rs.getString("INDEX_NAME")); String tableName = rs.getString("TABLE_NAME"); String tableSpace = rs.getString("TABLESPACE"); String columnName = convertFromDatabaseName(rs.getString("COLUMN_NAME")); if (columnName == null) { // nothing to index, not sure why these come through sometimes continue; } short type = rs.getShort("TYPE"); boolean nonUnique; String uniqueness = rs.getString("UNIQUENESS"); if ("UNIQUE".equals(uniqueness)) { nonUnique = false; } else { nonUnique = true; } short position = rs.getShort("ORDINAL_POSITION"); String filterCondition = rs.getString("FILTER_CONDITION"); if (type == DatabaseMetaData.tableIndexStatistic) { continue; } Index index; if (indexMap.containsKey(indexName)) { index = indexMap.get(indexName); } else { index = new Index(); Table table = snapshot.getTable(tableName); if (table == null) { continue; // probably different schema } index.setTable(table); index.setTablespace(tableSpace); index.setName(indexName); index.setUnique(!nonUnique); index.setFilterCondition(filterCondition); indexMap.put(indexName, index); } for (int i = index.getColumns().size(); i < position; i++) { index.getColumns().add(null); } index.getColumns().set(position - 1, columnName); } } finally { JdbcUtils.closeResultSet(rs); JdbcUtils.closeStatement(statement); } for (Map.Entry<String, Index> entry : indexMap.entrySet()) { snapshot.getIndexes().add(entry.getValue()); } /* * marks indexes as "associated with" instead of "remove it" * Index should have associations with: * foreignKey, primaryKey or uniqueConstraint * */ for (Index index : snapshot.getIndexes()) { for (PrimaryKey pk : snapshot.getPrimaryKeys()) { if (index.getTable().getName().equalsIgnoreCase(pk.getTable().getName()) && index.getColumnNames().equals(pk.getColumnNames())) { index.addAssociatedWith(Index.MARK_PRIMARY_KEY); } } for (ForeignKey fk : snapshot.getForeignKeys()) { if (index.getTable().getName().equalsIgnoreCase(fk.getForeignKeyTable().getName()) && index.getColumnNames().equals(fk.getForeignKeyColumns())) { index.addAssociatedWith(Index.MARK_FOREIGN_KEY); } } for (UniqueConstraint uc : snapshot.getUniqueConstraints()) { if (index.getTable().getName().equalsIgnoreCase(uc.getTable().getName()) && index.getColumnNames().equals(uc.getColumnNames())) { index.addAssociatedWith(Index.MARK_UNIQUE_CONSTRAINT); } } } }