use of org.datanucleus.store.rdbms.identifier.IdentifierFactory in project tests by datanucleus.
the class IdentifierFactoryTest method testDataNucleus2.
/**
* Tests for DNIdentifierFactory
*/
public void testDataNucleus2() {
RDBMSStoreManager srm = (RDBMSStoreManager) storeMgr;
IdentifierFactory idFactory = srm.getIdentifierFactory();
ClassLoaderResolver clr = new ClassLoaderResolverImpl();
// Table identifiers
// a). generated name shorter than max length
DatastoreIdentifier id = idFactory.newIdentifier(IdentifierType.TABLE, "MyClass");
assertTrue("newIdentifier(TABLE, String) has generated an incorrect name : " + id.getName(), "MYCLASS".equalsIgnoreCase(id.getName()));
// b). specified name shorter than max length
id = idFactory.newTableIdentifier("MY_TABLE_NAME");
assertTrue("newDatastoreContainerIdentifier(String) has returned an incorrect name when should have used the supplied name " + id.getName(), "MY_TABLE_NAME".equalsIgnoreCase(id.getName()));
// c). name specified via ClassMetaData
AbstractClassMetaData managerCMD = storeMgr.getNucleusContext().getMetaDataManager().getMetaDataForClass("org.jpox.samples.models.company.Manager", clr);
id = idFactory.newTableIdentifier(managerCMD);
assertTrue("newDatastoreContainerIdentifier(clr, ClassMetaData) has returned an incorrect generated name " + id.getName(), "MANAGER".equalsIgnoreCase(id.getName()));
// d). name specified via ClassMetaData
AbstractMemberMetaData fmd = managerCMD.getMetaDataForMember("subordinates");
id = idFactory.newTableIdentifier(fmd);
assertTrue("newDatastoreContainerIdentifier(clr, AbstractMemberMetaData) has returned an incorrect generated name " + id.getName(), "MANAGER_SUBORDINATES".equalsIgnoreCase(id.getName()));
// Column identifiers
// a). generated name shorter than max length
id = idFactory.newIdentifier(IdentifierType.COLUMN, "myField");
assertTrue("newIdentifier(COLUMN, String) has generated an incorrect name : " + id.getName(), "MYFIELD".equalsIgnoreCase(id.getName()));
// b). specified name shorter than max length
id = idFactory.newColumnIdentifier("MYCOLUMNNAME");
assertTrue("newColumnIdentifier(String) has returned an incorrect name when should have used the supplied name " + id.getName(), "MYCOLUMNNAME".equalsIgnoreCase(id.getName()));
// c). Discriminator column identifier
id = idFactory.newDiscriminatorFieldIdentifier();
assertTrue("newDiscriminatorFieldIdentifier() has returned an incorrect name : " + id.getName(), "DISCRIMINATOR".equalsIgnoreCase(id.getName()));
// d). Version column identifier
id = idFactory.newVersionFieldIdentifier();
assertTrue("newVersionFieldIdentifier() has returned an incorrect name : " + id.getName(), "VERSION".equalsIgnoreCase(id.getName()));
// e). Index (ordering) column identifier
id = idFactory.newIndexFieldIdentifier(fmd);
assertTrue("newIndexFieldIdentifier() has returned an incorrect name : " + id.getName(), "IDX".equalsIgnoreCase(id.getName()));
// f). Adapter Index column identifier
id = idFactory.newAdapterIndexFieldIdentifier();
assertTrue("newAdapterIndexFieldIdentifier() has returned an incorrect name : " + id.getName(), "IDX".equalsIgnoreCase(id.getName()));
AbstractMemberMetaData[] relatedMmds = fmd.getRelatedMemberMetaData(clr);
// g). join table owner column identifier (1-N bi JoinTable)
DatastoreIdentifier destId = idFactory.newColumnIdentifier("MANAGER_ID");
id = idFactory.newJoinTableFieldIdentifier(fmd, relatedMmds != null ? relatedMmds[0] : null, destId, false, FieldRole.ROLE_OWNER);
assertTrue("newJoinTableFieldIdentifier(OWNER) has returned an incorrect generated name " + id.getName(), "MANAGER_ID_OID".equalsIgnoreCase(id.getName()));
// h). join table element column identifier (1-N bi JoinTable)
destId = idFactory.newColumnIdentifier("EMPLOYEE_ID");
id = idFactory.newJoinTableFieldIdentifier(fmd, relatedMmds != null ? relatedMmds[0] : null, destId, false, FieldRole.ROLE_COLLECTION_ELEMENT);
assertTrue("newJoinTableFieldIdentifier(ELEMENT) has returned an incorrect generated name " + id.getName(), "EMPLOYEE_ID_EID".equalsIgnoreCase(id.getName()));
// i). FK owner column identifier (1-N bi FK)
AbstractMemberMetaData deptsFMD = managerCMD.getMetaDataForMember("departments");
AbstractMemberMetaData[] deptsRelatedMmds = deptsFMD.getRelatedMemberMetaData(clr);
destId = idFactory.newColumnIdentifier("MANAGER_ID");
id = idFactory.newForeignKeyFieldIdentifier(deptsFMD, deptsRelatedMmds != null ? deptsRelatedMmds[0] : null, destId, false, FieldRole.ROLE_OWNER);
assertTrue("newForeignKeyFieldIdentifier(OWNER) has returned an incorrect generated name " + id.getName(), "MANAGER_MANAGER_ID_OID".equalsIgnoreCase(id.getName()));
// Primary key identifiers
// Index identifiers
// Foreign key identifiers
// Candidate key identifiers
// Sequence identifiers
}
use of org.datanucleus.store.rdbms.identifier.IdentifierFactory in project datanucleus-rdbms by datanucleus.
the class ClassTable method manageUnmappedColumns.
/**
* Adds on management of the columns in the defined MetaData that are "unmapped" (have no field associated).
* @param theCmd ClassMetaData for the class to be managed
* @param clr The ClassLoaderResolver
*/
private void manageUnmappedColumns(AbstractClassMetaData theCmd, ClassLoaderResolver clr) {
List cols = theCmd.getUnmappedColumns();
if (cols != null && cols.size() > 0) {
Iterator colsIter = cols.iterator();
while (colsIter.hasNext()) {
ColumnMetaData colmd = (ColumnMetaData) colsIter.next();
// Create a column with the specified name and jdbc-type
if (colmd.getJdbcType() == JdbcType.VARCHAR && colmd.getLength() == null) {
colmd.setLength(storeMgr.getIntProperty(RDBMSPropertyNames.PROPERTY_RDBMS_STRING_DEFAULT_LENGTH));
}
IdentifierFactory idFactory = getStoreManager().getIdentifierFactory();
DatastoreIdentifier colIdentifier = idFactory.newIdentifier(IdentifierType.COLUMN, colmd.getName());
Column col = addColumn(null, colIdentifier, null, colmd);
SQLTypeInfo sqlTypeInfo = storeMgr.getSQLTypeInfoForJDBCType(dba.getJDBCTypeForName(colmd.getJdbcTypeName()));
col.setTypeInfo(sqlTypeInfo);
if (unmappedColumns == null) {
unmappedColumns = new HashSet();
}
if (NucleusLogger.DATASTORE_SCHEMA.isDebugEnabled()) {
NucleusLogger.DATASTORE_SCHEMA.debug(Localiser.msg("057011", col.toString(), colmd.getJdbcType()));
}
unmappedColumns.add(col);
}
}
}
use of org.datanucleus.store.rdbms.identifier.IdentifierFactory in project datanucleus-rdbms by datanucleus.
the class ClassTable method addOrderColumn.
/**
* Adds an ordering column to the element table (this) in FK list relationships.
* Used to store the position of the element in the List.
* If the <order> provides a mapped-by, this will return the existing column mapping.
* @param mmd The MetaData of the field/property with the list for the column to map to
* @return The Mapping for the order column
*/
private JavaTypeMapping addOrderColumn(AbstractMemberMetaData mmd, ClassLoaderResolver clr) {
Class indexType = Integer.class;
JavaTypeMapping orderIndexMapping = new OrderIndexMapping();
orderIndexMapping.initialize(storeMgr, indexType.getName());
orderIndexMapping.setMemberMetaData(mmd);
orderIndexMapping.setTable(this);
IdentifierFactory idFactory = storeMgr.getIdentifierFactory();
DatastoreIdentifier indexColumnName = null;
ColumnMetaData colmd = null;
// Allow for any user definition in OrderMetaData
OrderMetaData omd = mmd.getOrderMetaData();
if (omd != null) {
colmd = (omd.getColumnMetaData() != null && omd.getColumnMetaData().length > 0 ? omd.getColumnMetaData()[0] : null);
if (omd.getMappedBy() != null) {
// User has defined ordering using the column(s) of an existing field.
// Not adding anything so just set table back to "initialised"
state = TABLE_STATE_INITIALIZED;
JavaTypeMapping orderMapping = getMemberMapping(omd.getMappedBy());
if (!(orderMapping instanceof IntegerMapping) && !(orderMapping instanceof LongMapping)) {
throw new NucleusUserException(Localiser.msg("057022", mmd.getFullFieldName(), omd.getMappedBy()));
}
return orderMapping;
}
String colName = null;
if (omd.getColumnMetaData() != null && omd.getColumnMetaData().length > 0 && omd.getColumnMetaData()[0].getName() != null) {
// User-defined name so create an identifier using it
colName = omd.getColumnMetaData()[0].getName();
indexColumnName = idFactory.newColumnIdentifier(colName);
}
}
if (indexColumnName == null) {
// No name defined so generate one
indexColumnName = idFactory.newForeignKeyFieldIdentifier(mmd, null, null, storeMgr.getNucleusContext().getTypeManager().isDefaultEmbeddedType(indexType), FieldRole.ROLE_INDEX);
}
Column column = addColumn(indexType.getName(), indexColumnName, orderIndexMapping, colmd);
if (colmd == null || (colmd.getAllowsNull() == null) || (colmd.getAllowsNull() != null && colmd.isAllowsNull())) {
// User either wants it nullable, or havent specified anything, so make it nullable
column.setNullable(true);
}
storeMgr.getMappingManager().createDatastoreMapping(orderIndexMapping, column, indexType.getName());
return orderIndexMapping;
}
use of org.datanucleus.store.rdbms.identifier.IdentifierFactory in project datanucleus-rdbms by datanucleus.
the class ClassTable method runCallBacks.
/**
* Execute the callbacks for the classes that this table maps to.
* @param clr ClassLoader resolver
*/
private void runCallBacks(ClassLoaderResolver clr) {
// Run callbacks for all classes managed by this table
Iterator<AbstractClassMetaData> cmdIter = managedClassMetaData.iterator();
while (cmdIter.hasNext()) {
AbstractClassMetaData managedCmd = cmdIter.next();
if (managingClassCurrent != null && managingClassCurrent.equals(managedCmd.getFullClassName())) {
// We can't run callbacks for this class since it is still being initialised. Mark callbacks to run after it completes
runCallbacksAfterManageClass = true;
break;
}
Collection processedCallbacks = callbacksAppliedForManagedClass.get(managedCmd.getFullClassName());
Collection c = (Collection) storeMgr.getSchemaCallbacks().get(managedCmd.getFullClassName());
if (c != null) {
if (processedCallbacks == null) {
processedCallbacks = new HashSet();
callbacksAppliedForManagedClass.put(managedCmd.getFullClassName(), processedCallbacks);
}
for (Iterator it = c.iterator(); it.hasNext(); ) {
AbstractMemberMetaData callbackMmd = (AbstractMemberMetaData) it.next();
if (processedCallbacks.contains(callbackMmd)) {
continue;
}
processedCallbacks.add(callbackMmd);
if (callbackMmd.getJoinMetaData() == null) {
// 1-N FK relationship
AbstractMemberMetaData ownerFmd = callbackMmd;
if (ownerFmd.getMappedBy() != null) {
// Bidirectional (element has a PC mapping to the owner)
// Check that the "mapped-by" field in the other class actually exists
AbstractMemberMetaData fmd = null;
if (ownerFmd.getMappedBy().indexOf('.') > 0) {
// TODO Can we just use getRelatedMemberMetaData always?
AbstractMemberMetaData[] relMmds = ownerFmd.getRelatedMemberMetaData(clr);
fmd = (relMmds != null && relMmds.length > 0) ? relMmds[0] : null;
} else {
fmd = managedCmd.getMetaDataForMember(ownerFmd.getMappedBy());
}
if (fmd == null) {
throw new NucleusUserException(Localiser.msg("057036", ownerFmd.getMappedBy(), managedCmd.getFullClassName(), ownerFmd.getFullFieldName()));
}
if (ownerFmd.getMap() != null && storeMgr.getBooleanProperty(RDBMSPropertyNames.PROPERTY_RDBMS_UNIQUE_CONSTRAINTS_MAP_INVERSE)) {
initializeFKMapUniqueConstraints(ownerFmd);
}
boolean duplicate = false;
JavaTypeMapping fkDiscrimMapping = null;
JavaTypeMapping orderMapping = null;
if (ownerFmd.hasExtension(MetaData.EXTENSION_MEMBER_RELATION_DISCRIM_COLUMN)) {
// Collection has a relation discriminator so we need to share the FK. Check for the required discriminator
String colName = ownerFmd.getValueForExtension(MetaData.EXTENSION_MEMBER_RELATION_DISCRIM_COLUMN);
if (colName == null) {
// No column defined so use a fallback name
colName = "RELATION_DISCRIM";
}
Set fkDiscrimEntries = getExternalFkDiscriminatorMappings().entrySet();
Iterator discrimMappingIter = fkDiscrimEntries.iterator();
while (discrimMappingIter.hasNext()) {
Map.Entry entry = (Map.Entry) discrimMappingIter.next();
JavaTypeMapping discrimMapping = (JavaTypeMapping) entry.getValue();
String discrimColName = (discrimMapping.getDatastoreMapping(0).getColumn().getColumnMetaData()).getName();
if (discrimColName.equalsIgnoreCase(colName)) {
duplicate = true;
fkDiscrimMapping = discrimMapping;
orderMapping = getExternalOrderMappings().get(entry.getKey());
break;
}
}
if (!duplicate) {
// Create the relation discriminator column since we dont have this discriminator
ColumnMetaData colmd = new ColumnMetaData();
colmd.setName(colName);
// Allow for elements not in any discriminated collection
colmd.setAllowsNull(Boolean.TRUE);
// Only support String discriminators currently
fkDiscrimMapping = storeMgr.getMappingManager().getMapping(String.class);
fkDiscrimMapping.setTable(this);
ColumnCreator.createIndexColumn(fkDiscrimMapping, storeMgr, clr, this, colmd, false);
}
if (fkDiscrimMapping != null) {
getExternalFkDiscriminatorMappings().put(ownerFmd, fkDiscrimMapping);
}
}
// Add the order mapping as necessary
addOrderMapping(ownerFmd, orderMapping, clr);
} else {
// Unidirectional (element knows nothing about the owner)
String ownerClassName = ownerFmd.getAbstractClassMetaData().getFullClassName();
JavaTypeMapping fkMapping = new PersistableMapping();
fkMapping.setTable(this);
fkMapping.initialize(storeMgr, ownerClassName);
JavaTypeMapping fkDiscrimMapping = null;
JavaTypeMapping orderMapping = null;
boolean duplicate = false;
try {
// Get the owner id mapping of the "1" end
DatastoreClass ownerTbl = storeMgr.getDatastoreClass(ownerClassName, clr);
if (ownerTbl == null) {
// Class doesn't have its own table (subclass-table) so find where it persists
AbstractClassMetaData[] ownerParentCmds = storeMgr.getClassesManagingTableForClass(ownerFmd.getAbstractClassMetaData(), clr);
if (ownerParentCmds.length > 1) {
throw new NucleusUserException("Relation (" + ownerFmd.getFullFieldName() + ") with multiple related tables (using subclass-table). Not supported");
}
ownerClassName = ownerParentCmds[0].getFullClassName();
ownerTbl = storeMgr.getDatastoreClass(ownerClassName, clr);
if (ownerTbl == null) {
throw new NucleusException("Failed to get owner table at other end of relation for field=" + ownerFmd.getFullFieldName());
}
}
JavaTypeMapping ownerIdMapping = ownerTbl.getIdMapping();
ColumnMetaDataContainer colmdContainer = null;
if (ownerFmd.hasCollection() || ownerFmd.hasArray()) {
// 1-N Collection/array
colmdContainer = ownerFmd.getElementMetaData();
} else if (ownerFmd.hasMap() && ownerFmd.getKeyMetaData() != null && ownerFmd.getKeyMetaData().getMappedBy() != null) {
// 1-N Map with key stored in the value
colmdContainer = ownerFmd.getValueMetaData();
} else if (ownerFmd.hasMap() && ownerFmd.getValueMetaData() != null && ownerFmd.getValueMetaData().getMappedBy() != null) {
// 1-N Map with value stored in the key
colmdContainer = ownerFmd.getKeyMetaData();
}
CorrespondentColumnsMapper correspondentColumnsMapping = new CorrespondentColumnsMapper(colmdContainer, this, ownerIdMapping, true);
int countIdFields = ownerIdMapping.getNumberOfDatastoreMappings();
for (int i = 0; i < countIdFields; i++) {
DatastoreMapping refDatastoreMapping = ownerIdMapping.getDatastoreMapping(i);
JavaTypeMapping mapping = storeMgr.getMappingManager().getMapping(refDatastoreMapping.getJavaTypeMapping().getJavaType());
ColumnMetaData colmd = correspondentColumnsMapping.getColumnMetaDataByIdentifier(refDatastoreMapping.getColumn().getIdentifier());
if (colmd == null) {
throw new NucleusUserException(Localiser.msg("057035", refDatastoreMapping.getColumn().getIdentifier(), toString())).setFatal();
}
DatastoreIdentifier identifier = null;
IdentifierFactory idFactory = storeMgr.getIdentifierFactory();
if (colmd.getName() == null || colmd.getName().length() < 1) {
// No user provided name so generate one
identifier = idFactory.newForeignKeyFieldIdentifier(ownerFmd, null, refDatastoreMapping.getColumn().getIdentifier(), storeMgr.getNucleusContext().getTypeManager().isDefaultEmbeddedType(mapping.getJavaType()), FieldRole.ROLE_OWNER);
} else {
// User-defined name
identifier = idFactory.newColumnIdentifier(colmd.getName());
}
Column refColumn = addColumn(mapping.getJavaType().getName(), identifier, mapping, colmd);
refDatastoreMapping.getColumn().copyConfigurationTo(refColumn);
if ((colmd.getAllowsNull() == null) || (colmd.getAllowsNull() != null && colmd.isAllowsNull())) {
// User either wants it nullable, or haven't specified anything, so make it nullable
refColumn.setNullable(true);
}
fkMapping.addDatastoreMapping(getStoreManager().getMappingManager().createDatastoreMapping(mapping, refColumn, refDatastoreMapping.getJavaTypeMapping().getJavaType().getName()));
((PersistableMapping) fkMapping).addJavaTypeMapping(mapping);
}
} catch (DuplicateColumnException dce) {
// If the user hasnt specified "relation-discriminator-column" here we dont allow the sharing of columns
if (!ownerFmd.hasExtension(MetaData.EXTENSION_MEMBER_RELATION_DISCRIM_COLUMN)) {
throw dce;
}
// Find the FK using this column and use it instead of creating a new one since we're sharing
Iterator fkIter = getExternalFkMappings().entrySet().iterator();
fkMapping = null;
while (fkIter.hasNext()) {
Map.Entry entry = (Map.Entry) fkIter.next();
JavaTypeMapping existingFkMapping = (JavaTypeMapping) entry.getValue();
for (int j = 0; j < existingFkMapping.getNumberOfDatastoreMappings(); j++) {
if (existingFkMapping.getDatastoreMapping(j).getColumn().getIdentifier().toString().equals(dce.getConflictingColumn().getIdentifier().toString())) {
// The FK is shared (and so if it is a List we also share the index)
fkMapping = existingFkMapping;
fkDiscrimMapping = externalFkDiscriminatorMappings.get(entry.getKey());
orderMapping = getExternalOrderMappings().get(entry.getKey());
break;
}
}
}
if (fkMapping == null) {
// Should never happen since we know there is a col duplicating ours
throw dce;
}
duplicate = true;
}
if (!duplicate && ownerFmd.hasExtension(MetaData.EXTENSION_MEMBER_RELATION_DISCRIM_COLUMN)) {
// Create the relation discriminator column
String colName = ownerFmd.getValueForExtension(MetaData.EXTENSION_MEMBER_RELATION_DISCRIM_COLUMN);
if (colName == null) {
// No column defined so use a fallback name
colName = "RELATION_DISCRIM";
}
ColumnMetaData colmd = new ColumnMetaData();
colmd.setName(colName);
// Allow for elements not in any discriminated collection
colmd.setAllowsNull(Boolean.TRUE);
// Only support String discriminators currently
fkDiscrimMapping = storeMgr.getMappingManager().getMapping(String.class);
fkDiscrimMapping.setTable(this);
ColumnCreator.createIndexColumn(fkDiscrimMapping, storeMgr, clr, this, colmd, false);
}
// Save the external FK
getExternalFkMappings().put(ownerFmd, fkMapping);
if (fkDiscrimMapping != null) {
getExternalFkDiscriminatorMappings().put(ownerFmd, fkDiscrimMapping);
}
// Add the order mapping as necessary
addOrderMapping(ownerFmd, orderMapping, clr);
}
}
}
}
}
}
use of org.datanucleus.store.rdbms.identifier.IdentifierFactory in project datanucleus-rdbms by datanucleus.
the class ColumnCreator method createColumnsForField.
/**
* Method to create the column(s) for a field in either a join table or for a reference field.
* @param javaType The java type of the field being stored
* @param mapping The JavaTypeMapping (if existing, otherwise created and returned by this method)
* @param table The table to insert the columns into (join table, or primary table (if ref field))
* @param storeMgr Manager for the store
* @param mmd MetaData for the field (or null if a collection field)
* @param isPrimaryKey Whether to create the columns as part of the PK
* @param isNullable Whether the columns should be nullable
* @param serialised Whether the field is serialised
* @param embedded Whether the field is embedded
* @param fieldRole The role of the field (when part of a join table)
* @param columnMetaData MetaData for the column(s)
* @param clr ClassLoader resolver
* @param isReferenceField Whether this field is part of a reference field
* @param ownerTable Table of the owner of this member (optional, for when the member is embedded)
* @return The JavaTypeMapping for the table
*/
public static JavaTypeMapping createColumnsForField(Class javaType, JavaTypeMapping mapping, Table table, RDBMSStoreManager storeMgr, AbstractMemberMetaData mmd, boolean isPrimaryKey, boolean isNullable, boolean serialised, boolean embedded, FieldRole fieldRole, ColumnMetaData[] columnMetaData, ClassLoaderResolver clr, boolean isReferenceField, Table ownerTable) {
IdentifierFactory idFactory = storeMgr.getIdentifierFactory();
if (mapping instanceof ReferenceMapping || mapping instanceof PersistableMapping) {
// PC/interface/Object mapping
JavaTypeMapping container = mapping;
if (mapping instanceof ReferenceMapping) {
// Interface/Object has child mappings for each implementation
container = storeMgr.getMappingManager().getMapping(javaType, serialised, embedded, mmd != null ? mmd.getFullFieldName() : null);
((ReferenceMapping) mapping).addJavaTypeMapping(container);
}
// Get the table that we want our column to be a FK to. This could be the owner table, element table, key table, value table etc
DatastoreClass destinationTable = null;
try {
destinationTable = storeMgr.getDatastoreClass(javaType.getName(), clr);
} catch (NoTableManagedException ntme) {
if (ownerTable != null && ownerTable instanceof DatastoreClass) {
destinationTable = (DatastoreClass) ownerTable;
} else {
throw ntme;
}
}
if (destinationTable == null) {
// Maybe the owner hasn't got its own table (e.g "subclass-table" or "complete-table"+abstract)
// Alternate is when we have an embedded type which itself has an embedded collection - not catered for at all currently
AbstractClassMetaData ownerCmd = storeMgr.getMetaDataManager().getMetaDataForClass(javaType, clr);
if (ownerCmd.getBaseAbstractClassMetaData().getInheritanceMetaData().getStrategy() == InheritanceStrategy.COMPLETE_TABLE) {
// COMPLETE-TABLE but abstract root, so find one of the subclasses with a table and use that for now
Collection<String> ownerSubclassNames = storeMgr.getSubClassesForClass(javaType.getName(), true, clr);
if (ownerSubclassNames != null && ownerSubclassNames.size() > 0) {
for (String ownerSubclassName : ownerSubclassNames) {
ownerCmd = storeMgr.getMetaDataManager().getMetaDataForClass(ownerSubclassName, clr);
try {
destinationTable = storeMgr.getDatastoreClass(ownerSubclassName, clr);
} catch (NoTableManagedException ntme) {
}
if (destinationTable != null) {
break;
}
}
}
} else {
AbstractClassMetaData[] ownerCmds = storeMgr.getClassesManagingTableForClass(ownerCmd, clr);
if (ownerCmds == null || ownerCmds.length == 0) {
throw new NucleusUserException(Localiser.msg("057023", javaType.getName())).setFatal();
}
// Use the first one since they should all have the same id column(s)
destinationTable = storeMgr.getDatastoreClass(ownerCmds[0].getFullClassName(), clr);
}
}
if (destinationTable != null) {
// Foreign-Key to the destination table ID mapping
JavaTypeMapping m = destinationTable.getIdMapping();
// For each column in the destination mapping, add a column here
ColumnMetaDataContainer columnContainer = null;
if (columnMetaData != null && columnMetaData.length > 0) {
columnContainer = (ColumnMetaDataContainer) columnMetaData[0].getParent();
}
CorrespondentColumnsMapper correspondentColumnsMapping = new CorrespondentColumnsMapper(columnContainer, table, columnMetaData, m, true);
for (int i = 0; i < m.getNumberOfDatastoreMappings(); i++) {
JavaTypeMapping refDatastoreMapping = storeMgr.getMappingManager().getMapping(m.getDatastoreMapping(i).getJavaTypeMapping().getJavaType());
ColumnMetaData colmd = correspondentColumnsMapping.getColumnMetaDataByIdentifier(m.getDatastoreMapping(i).getColumn().getIdentifier());
try {
DatastoreIdentifier identifier = null;
if (fieldRole == FieldRole.ROLE_MAP_KEY && columnContainer == null) {
// Map KEY field and no metadata defined
if (isReferenceField) {
// Create reference identifier
identifier = idFactory.newReferenceFieldIdentifier(mmd, storeMgr.getNucleusContext().getMetaDataManager().getMetaDataForClass(javaType, clr), m.getDatastoreMapping(i).getColumn().getIdentifier(), storeMgr.getNucleusContext().getTypeManager().isDefaultEmbeddedType(javaType), fieldRole);
} else {
// Create join table identifier
AbstractMemberMetaData[] relatedMmds = mmd.getRelatedMemberMetaData(clr);
// TODO If the mmd is an "embedded" type this can create invalid identifiers
// TODO Cater for more than 1 related field
identifier = idFactory.newJoinTableFieldIdentifier(mmd, relatedMmds != null ? relatedMmds[0] : null, m.getDatastoreMapping(i).getColumn().getIdentifier(), storeMgr.getNucleusContext().getTypeManager().isDefaultEmbeddedType(javaType), fieldRole);
}
} else {
if (colmd.getName() == null) {
// User hasn't provided a name, so we use default naming
if (isReferenceField) {
// Create reference identifier
identifier = idFactory.newReferenceFieldIdentifier(mmd, storeMgr.getNucleusContext().getMetaDataManager().getMetaDataForClass(javaType, clr), m.getDatastoreMapping(i).getColumn().getIdentifier(), storeMgr.getNucleusContext().getTypeManager().isDefaultEmbeddedType(javaType), fieldRole);
} else {
// Create join table identifier
AbstractMemberMetaData[] relatedMmds = mmd.getRelatedMemberMetaData(clr);
// TODO If the mmd is an "embedded" type this can create invalid identifiers
// TODO Cater for more than 1 related field
identifier = idFactory.newJoinTableFieldIdentifier(mmd, relatedMmds != null ? relatedMmds[0] : null, m.getDatastoreMapping(i).getColumn().getIdentifier(), storeMgr.getNucleusContext().getTypeManager().isDefaultEmbeddedType(javaType), fieldRole);
}
} else {
// User defined name, so we use that.
identifier = idFactory.newColumnIdentifier(colmd.getName());
}
}
// Only add the column if not currently present
Column column = table.addColumn(javaType.getName(), identifier, refDatastoreMapping, colmd);
m.getDatastoreMapping(i).getColumn().copyConfigurationTo(column);
if (isPrimaryKey) {
column.setPrimaryKey();
}
if (isNullable) {
column.setNullable(true);
}
storeMgr.getMappingManager().createDatastoreMapping(refDatastoreMapping, column, m.getDatastoreMapping(i).getJavaTypeMapping().getJavaTypeForDatastoreMapping(i));
} catch (DuplicateColumnException ex) {
throw new NucleusUserException("Cannot create column for field " + mmd.getFullFieldName() + " column metadata " + colmd, ex);
}
try {
((PersistableMapping) container).addJavaTypeMapping(refDatastoreMapping);
} catch (ClassCastException e) {
throw new NucleusUserException("Failed to create column for field " + mmd.getFullFieldName() + ". Cannot cast mapping to PersistableMapping.", e);
}
}
}
} else {
// Non-PC mapping
// Add column for the field
Column column = null;
ColumnMetaData colmd = null;
if (columnMetaData != null && columnMetaData.length > 0) {
colmd = columnMetaData[0];
}
DatastoreIdentifier identifier = null;
if (colmd != null && colmd.getName() != null) {
// User specified name
identifier = idFactory.newColumnIdentifier(colmd.getName());
} else {
// No user-supplied name so generate one
identifier = idFactory.newJoinTableFieldIdentifier(mmd, null, null, storeMgr.getNucleusContext().getTypeManager().isDefaultEmbeddedType(javaType), fieldRole);
}
column = table.addColumn(javaType.getName(), identifier, mapping, colmd);
storeMgr.getMappingManager().createDatastoreMapping(mapping, column, mapping.getJavaTypeForDatastoreMapping(0));
if (isNullable) {
column.setNullable(true);
}
}
return mapping;
}
Aggregations