String tableName = table.getName();
// pk name
String primaryKeyName = null; // initially null
// create table's primary key
PrimaryKey pk = factory.createPrimaryKey();
// ***************************
// *** DatabaseNamedObject ***
// ***************************
// set name
// pk.setName (primaryKeyName); // it will be overriden later in this code
// set remarks
// pk.setRemarks (remarks); // N/A
// TODO set extra properties
// table.addExtraProperty (String key, Object value);
// ********************
// *** SchemaObject ***
// ********************
// set catalog
pk.setCatalog(table.getCatalog());
// set schema
pk.setSchema(table.getSchema());
// process all columns included into primary key
while (resultSet.next()) {
// get PK name
if (primaryKeyName == null) {
primaryKeyName = getString(resultSet, "PK_NAME", false);
// set name
pk.setName(primaryKeyName);
}
// column name
String columnName = getString(resultSet, "COLUMN_NAME", false);
// sequence number within primary key
Integer ordinalPosition = getInteger(resultSet, "KEY_SEQ", false);
// trying to find table column with specified name
TableColumn tableColumn = table.findColumnByName(columnName);
String errMessage = null;
// warn if null
if (tableColumn == null) {
errMessage = String.format("[Database %s] Unable to find table column '%5$s' for the table %s (schema %s, catalog %s)",
database.getName(),
tableName,
schemaName,
catalogName,
columnName);
traceLog.debug(errMessage);
}
// if fail is enabled
if (failOnError && (tableColumn == null)) {
throw new DatabaseMetaDataMethodException(errMessage, "populatePrimaryKey");
}
// create PK column
PrimaryKeyColumn pkColumn = factory.createPrimaryKeyColumn();
// check if we found the original table column
if (tableColumn != null) {
// mark original table column as part of PK
tableColumn.setPrimaryKeyColumn(Boolean.TRUE);
// clone properties from original table column to the pkcolumn
PropertyUtils.copyProperties(pkColumn, tableColumn);
} else { // recovery if table column is not found but we still want to create pk column
// set name at least
pkColumn.setName(columnName);
}
// modify ordinal position that correspond to the position in PK
pkColumn.setOrdinalPosition(ordinalPosition);
// add PK column to the primary key
pk.addColumn(pkColumn);
}
// set table primary key
table.setPrimaryKey(pk);