// Create the ForeignKey base details
ForeignKey fk = new ForeignKey(fkmd.isDeferred());
fk.setForMetaData(fkmd);
// Find the target of the foreign-key
AbstractClassMetaData acmd = cmd;
if (fkmd.getTable() == null)
{
// Can't create a FK if we don't know where it goes to
NucleusLogger.DATASTORE_SCHEMA.warn(LOCALISER.msg("058105", acmd.getFullClassName()));
return null;
}
DatastoreIdentifier tableId = storeMgr.getIdentifierFactory().newDatastoreContainerIdentifier(fkmd.getTable());
ClassTable refTable = (ClassTable)storeMgr.getDatastoreClass(tableId);
if (refTable == null)
{
// TODO Go to the datastore and query for this table to get the columns of the PK
NucleusLogger.DATASTORE_SCHEMA.warn(LOCALISER.msg("058106", acmd.getFullClassName(),
fkmd.getTable()));
return null;
}
PrimaryKey pk = refTable.getPrimaryKey();
List targetCols = pk.getColumns();
// Generate the columns for the source of the foreign-key
List sourceCols = new ArrayList();
ColumnMetaData[] colmds = fkmd.getColumnMetaData();
AbstractMemberMetaData[] fmds = fkmd.getMemberMetaData();
if (colmds != null && colmds.length > 0)
{
// FK specified via <column>
for (int i=0;i<colmds.length;i++)
{
// Find the column and add to the source columns for the FK
DatastoreIdentifier colId = storeMgr.getIdentifierFactory().newDatastoreFieldIdentifier(colmds[i].getName());
Column sourceCol = columnsByName.get(colId);
if (sourceCol == null)
{
NucleusLogger.DATASTORE_SCHEMA.warn(LOCALISER.msg("058107",
acmd.getFullClassName(), fkmd.getTable(), colmds[i].getName(), toString()));
return null;
}
sourceCols.add(sourceCol);
}
}
else if (fmds != null && fmds.length > 0)
{
// FK specified via <field>
for (int i=0;i<fmds.length;i++)
{
// Find the metadata for the actual field with the same name as this "foreign-key" field
// and add all columns to the source columns for the FK
AbstractMemberMetaData realFmd = getMetaDataForMember(fmds[i].getName());
JavaTypeMapping fieldMapping = memberMappingsMap.get(realFmd);
int countDatastoreFields = fieldMapping.getNumberOfDatastoreMappings();
for (int j=0; j<countDatastoreFields; j++)
{
// Add each column of this field to the FK definition
sourceCols.add(fieldMapping.getDatastoreMapping(j).getDatastoreField());
}
}
}
if (sourceCols.size() != targetCols.size())
{
// Different number of cols in this table and target table
NucleusLogger.DATASTORE_SCHEMA.warn(LOCALISER.msg("058108",
acmd.getFullClassName(), fkmd.getTable(), "" + sourceCols.size(), "" + targetCols.size()));
}
// Add all column mappings to the ForeignKey
if (sourceCols.size() > 0)
{