Search in sources :

Example 1 with CorrespondentColumnsMapper

use of org.datanucleus.store.rdbms.mapping.CorrespondentColumnsMapper in project datanucleus-rdbms by datanucleus.

the class PersistableMapping method prepareColumnMapping.

/**
 * Method to prepare the PC mapping and add its associated column mappings.
 * @param clr The ClassLoaderResolver
 */
protected void prepareColumnMapping(ClassLoaderResolver clr) {
    if (roleForMember == FieldRole.ROLE_COLLECTION_ELEMENT) {
    // TODO Handle creation of columns in join table for collection of PCs
    } else if (roleForMember == FieldRole.ROLE_ARRAY_ELEMENT) {
    // TODO Handle creation of columns in join table for array of PCs
    } else if (roleForMember == FieldRole.ROLE_MAP_KEY) {
    // TODO Handle creation of columns in join table for map of PCs as keys
    } else if (roleForMember == FieldRole.ROLE_MAP_VALUE) {
    // TODO Handle creation of columns in join table for map of PCs as values
    } else {
        // Either one end of a 1-1 relation, or the N end of a N-1
        AbstractClassMetaData refCmd = storeMgr.getNucleusContext().getMetaDataManager().getMetaDataForClass(mmd.getType(), clr);
        JavaTypeMapping referenceMapping = null;
        if (refCmd == null) {
            // User stupidity
            throw new NucleusUserException("You have a field " + mmd.getFullFieldName() + " that has type " + mmd.getTypeName() + " but this type has no known metadata. Your mapping is incorrect");
        }
        if (refCmd.getInheritanceMetaData() != null && refCmd.getInheritanceMetaData().getStrategy() == InheritanceStrategy.SUBCLASS_TABLE) {
            // Find the actual tables storing the other end (can be multiple subclasses)
            AbstractClassMetaData[] cmds = storeMgr.getClassesManagingTableForClass(refCmd, clr);
            if (cmds != null && cmds.length > 0) {
                if (cmds.length > 1) {
                    // TODO Only log this when it is really necessary. In some situations it is fine
                    NucleusLogger.PERSISTENCE.warn("Field " + mmd.getFullFieldName() + " represents either a 1-1 relation, " + "or a N-1 relation where the other end uses \"subclass-table\" inheritance strategy and more " + "than 1 subclasses with a table. This is not fully supported");
                }
            } else {
                // TODO Throw an exception ?
                return;
            }
            // TODO We need a mapping for each of the possible subclass tables
            referenceMapping = storeMgr.getDatastoreClass(cmds[0].getFullClassName(), clr).getIdMapping();
        } else if (refCmd.getInheritanceMetaData() != null && refCmd.getInheritanceMetaData().getStrategy() == InheritanceStrategy.COMPLETE_TABLE) {
            // Find the other side of the relation
            DatastoreClass refTable = null;
            if (refCmd instanceof ClassMetaData && !((ClassMetaData) refCmd).isAbstract()) {
                refTable = storeMgr.getDatastoreClass(refCmd.getFullClassName(), clr);
            } else {
                Collection<String> refSubclasses = storeMgr.getSubClassesForClass(refCmd.getFullClassName(), true, clr);
                if (refSubclasses != null && !refSubclasses.isEmpty()) {
                    // if only 1 subclass then use that
                    String refSubclassName = refSubclasses.iterator().next();
                    refTable = storeMgr.getDatastoreClass(refSubclassName, clr);
                    if (refSubclasses.size() > 1) {
                        NucleusLogger.DATASTORE_SCHEMA.info("Field " + mmd.getFullFieldName() + " is a 1-1/N-1 relation and the other side had multiple possible classes " + "to which to create a foreign-key. Using first possible (" + refSubclassName + ")");
                    }
                }
            }
            if (refTable != null) {
                referenceMapping = refTable.getIdMapping();
            } else {
                throw new NucleusUserException("Field " + mmd.getFullFieldName() + " represents either a 1-1 relation, " + "or a N-1 relation where the other end uses \"complete-table\" inheritance strategy and either no table was found, or multiple possible tables!");
            }
        } else {
            // Default is to use the ID of the related object
            // TODO Add option to use a natural-id in the other class. Find the mapping using the targetColumnName
            referenceMapping = storeMgr.getDatastoreClass(mmd.getType().getName(), clr).getIdMapping();
        }
        // Generate a mapping from the columns of the referenced object to this mapping's ColumnMetaData
        CorrespondentColumnsMapper correspondentColumnsMapping = new CorrespondentColumnsMapper(mmd, table, referenceMapping, true);
        // Find any related field where this is part of a bidirectional relation
        RelationType relationType = mmd.getRelationType(clr);
        boolean createColumnMappings = true;
        if (relationType == RelationType.MANY_TO_ONE_BI) {
            AbstractMemberMetaData[] relatedMmds = mmd.getRelatedMemberMetaData(clr);
            // TODO Cater for more than 1 related field
            createColumnMappings = (relatedMmds[0].getJoinMetaData() == null);
        } else if (// TODO If join table then don't need this
        relationType == RelationType.ONE_TO_ONE_BI) {
            // Put the FK at the end without "mapped-by"
            createColumnMappings = (mmd.getMappedBy() == null);
        }
        if (mmd.getJoinMetaData() != null && (relationType == RelationType.MANY_TO_ONE_UNI || relationType == RelationType.ONE_TO_ONE_UNI || relationType == RelationType.ONE_TO_ONE_BI)) {
            if (relationType == RelationType.ONE_TO_ONE_UNI || relationType == RelationType.ONE_TO_ONE_BI) {
                throw new NucleusUserException("We do not currently support 1-1 relations via join table : " + mmd.getFullFieldName());
            }
            // create join table
            storeMgr.newJoinTable(table, mmd, clr);
        } else {
            // Loop through the columns in the referenced class and create a column for each
            for (int i = 0; i < referenceMapping.getNumberOfColumnMappings(); i++) {
                ColumnMapping refColumnMapping = referenceMapping.getColumnMapping(i);
                JavaTypeMapping mapping = storeMgr.getMappingManager().getMapping(refColumnMapping.getJavaTypeMapping().getJavaType());
                this.addJavaTypeMapping(mapping);
                // Create physical datastore columns where we require a FK link to the related table.
                if (createColumnMappings) {
                    // Find the Column MetaData that maps to the referenced columncolumn
                    ColumnMetaData colmd = correspondentColumnsMapping.getColumnMetaDataByIdentifier(refColumnMapping.getColumn().getIdentifier());
                    if (colmd == null) {
                        throw new NucleusUserException(Localiser.msg("041038", refColumnMapping.getColumn().getIdentifier(), toString())).setFatal();
                    }
                    // Create a column to equate to the referenced classes column
                    MappingManager mmgr = storeMgr.getMappingManager();
                    Column col = mmgr.createColumn(mmd, table, mapping, colmd, refColumnMapping.getColumn(), clr);
                    // Add its column mapping
                    ColumnMapping colMapping = mmgr.createColumnMapping(mapping, col, refColumnMapping.getJavaTypeMapping().getJavaTypeForColumnMapping(i));
                    this.addColumnMapping(colMapping);
                } else {
                    mapping.setReferenceMapping(referenceMapping);
                }
            }
        }
    }
}
Also used : NucleusUserException(org.datanucleus.exceptions.NucleusUserException) AbstractClassMetaData(org.datanucleus.metadata.AbstractClassMetaData) Column(org.datanucleus.store.rdbms.table.Column) RelationType(org.datanucleus.metadata.RelationType) DatastoreClass(org.datanucleus.store.rdbms.table.DatastoreClass) ColumnMetaData(org.datanucleus.metadata.ColumnMetaData) MappingManager(org.datanucleus.store.rdbms.mapping.MappingManager) AbstractClassMetaData(org.datanucleus.metadata.AbstractClassMetaData) ClassMetaData(org.datanucleus.metadata.ClassMetaData) ColumnMapping(org.datanucleus.store.rdbms.mapping.column.ColumnMapping) CorrespondentColumnsMapper(org.datanucleus.store.rdbms.mapping.CorrespondentColumnsMapper)

Example 2 with CorrespondentColumnsMapper

use of org.datanucleus.store.rdbms.mapping.CorrespondentColumnsMapper in project datanucleus-rdbms by datanucleus.

the class PersistableMapping method prepareDatastoreMapping.

/**
 * Method to prepare the PC mapping and add its associated datastore mappings.
 * @param clr The ClassLoaderResolver
 */
protected void prepareDatastoreMapping(ClassLoaderResolver clr) {
    if (roleForMember == FieldRole.ROLE_COLLECTION_ELEMENT) {
    // TODO Handle creation of columns in join table for collection of PCs
    } else if (roleForMember == FieldRole.ROLE_ARRAY_ELEMENT) {
    // TODO Handle creation of columns in join table for array of PCs
    } else if (roleForMember == FieldRole.ROLE_MAP_KEY) {
    // TODO Handle creation of columns in join table for map of PCs as keys
    } else if (roleForMember == FieldRole.ROLE_MAP_VALUE) {
    // TODO Handle creation of columns in join table for map of PCs as values
    } else {
        // Either one end of a 1-1 relation, or the N end of a N-1
        AbstractClassMetaData refCmd = storeMgr.getNucleusContext().getMetaDataManager().getMetaDataForClass(mmd.getType(), clr);
        JavaTypeMapping referenceMapping = null;
        if (refCmd == null) {
            // User stupidity
            throw new NucleusUserException("You have a field " + mmd.getFullFieldName() + " that has type " + mmd.getTypeName() + " but this type has no known metadata. Your mapping is incorrect");
        }
        if (refCmd.getInheritanceMetaData() != null && refCmd.getInheritanceMetaData().getStrategy() == InheritanceStrategy.SUBCLASS_TABLE) {
            // Find the actual tables storing the other end (can be multiple subclasses)
            AbstractClassMetaData[] cmds = storeMgr.getClassesManagingTableForClass(refCmd, clr);
            if (cmds != null && cmds.length > 0) {
                if (cmds.length > 1) {
                    // TODO Only log this when it is really necessary. In some situations it is fine
                    NucleusLogger.PERSISTENCE.warn("Field " + mmd.getFullFieldName() + " represents either a 1-1 relation, " + "or a N-1 relation where the other end uses \"subclass-table\" inheritance strategy and more " + "than 1 subclasses with a table. This is not fully supported");
                }
            } else {
                // TODO Throw an exception ?
                return;
            }
            // TODO We need a mapping for each of the possible subclass tables
            referenceMapping = storeMgr.getDatastoreClass(cmds[0].getFullClassName(), clr).getIdMapping();
        } else if (refCmd.getInheritanceMetaData() != null && refCmd.getInheritanceMetaData().getStrategy() == InheritanceStrategy.COMPLETE_TABLE) {
            // Find the other side of the relation
            DatastoreClass refTable = null;
            if (refCmd instanceof ClassMetaData && !((ClassMetaData) refCmd).isAbstract()) {
                refTable = storeMgr.getDatastoreClass(refCmd.getFullClassName(), clr);
            } else {
                Collection<String> refSubclasses = storeMgr.getSubClassesForClass(refCmd.getFullClassName(), true, clr);
                if (refSubclasses != null && !refSubclasses.isEmpty()) {
                    // if only 1 subclass then use that
                    String refSubclassName = refSubclasses.iterator().next();
                    refTable = storeMgr.getDatastoreClass(refSubclassName, clr);
                    if (refSubclasses.size() > 1) {
                        NucleusLogger.DATASTORE_SCHEMA.info("Field " + mmd.getFullFieldName() + " is a 1-1/N-1 relation and the other side had multiple possible classes " + "to which to create a foreign-key. Using first possible (" + refSubclassName + ")");
                    }
                }
            }
            if (refTable != null) {
                referenceMapping = refTable.getIdMapping();
            } else {
                throw new NucleusUserException("Field " + mmd.getFullFieldName() + " represents either a 1-1 relation, " + "or a N-1 relation where the other end uses \"complete-table\" inheritance strategy and either no table was found, or multiple possible tables!");
            }
        } else {
            // Default is to use the ID of the related object
            // TODO Add option to use a natural-id in the other class. Find the mapping using the targetColumnName
            referenceMapping = storeMgr.getDatastoreClass(mmd.getType().getName(), clr).getIdMapping();
        }
        // Generate a mapping from the columns of the referenced object to this mapping's ColumnMetaData
        CorrespondentColumnsMapper correspondentColumnsMapping = new CorrespondentColumnsMapper(mmd, table, referenceMapping, true);
        // Find any related field where this is part of a bidirectional relation
        RelationType relationType = mmd.getRelationType(clr);
        boolean createDatastoreMappings = true;
        if (relationType == RelationType.MANY_TO_ONE_BI) {
            AbstractMemberMetaData[] relatedMmds = mmd.getRelatedMemberMetaData(clr);
            // TODO Cater for more than 1 related field
            createDatastoreMappings = (relatedMmds[0].getJoinMetaData() == null);
        } else if (// TODO If join table then don't need this
        relationType == RelationType.ONE_TO_ONE_BI) {
            // Put the FK at the end without "mapped-by"
            createDatastoreMappings = (mmd.getMappedBy() == null);
        }
        if (mmd.getJoinMetaData() != null && (relationType == RelationType.MANY_TO_ONE_UNI || relationType == RelationType.ONE_TO_ONE_UNI || relationType == RelationType.ONE_TO_ONE_BI)) {
            if (relationType == RelationType.ONE_TO_ONE_UNI || relationType == RelationType.ONE_TO_ONE_BI) {
                throw new NucleusUserException("We do not currently support 1-1 relations via join table : " + mmd.getFullFieldName());
            }
            // create join table
            storeMgr.newJoinTable(table, mmd, clr);
        } else {
            // Loop through the datastore fields in the referenced class and create a datastore field for each
            for (int i = 0; i < referenceMapping.getNumberOfDatastoreMappings(); i++) {
                DatastoreMapping refDatastoreMapping = referenceMapping.getDatastoreMapping(i);
                JavaTypeMapping mapping = storeMgr.getMappingManager().getMapping(refDatastoreMapping.getJavaTypeMapping().getJavaType());
                this.addJavaTypeMapping(mapping);
                // Create physical datastore columns where we require a FK link to the related table.
                if (createDatastoreMappings) {
                    // Find the Column MetaData that maps to the referenced datastore field
                    ColumnMetaData colmd = correspondentColumnsMapping.getColumnMetaDataByIdentifier(refDatastoreMapping.getColumn().getIdentifier());
                    if (colmd == null) {
                        throw new NucleusUserException(Localiser.msg("041038", refDatastoreMapping.getColumn().getIdentifier(), toString())).setFatal();
                    }
                    // Create a Datastore field to equate to the referenced classes datastore field
                    MappingManager mmgr = storeMgr.getMappingManager();
                    Column col = mmgr.createColumn(mmd, table, mapping, colmd, refDatastoreMapping.getColumn(), clr);
                    // Add its datastore mapping
                    DatastoreMapping datastoreMapping = mmgr.createDatastoreMapping(mapping, col, refDatastoreMapping.getJavaTypeMapping().getJavaTypeForDatastoreMapping(i));
                    this.addDatastoreMapping(datastoreMapping);
                } else {
                    mapping.setReferenceMapping(referenceMapping);
                }
            }
        }
    }
}
Also used : NucleusUserException(org.datanucleus.exceptions.NucleusUserException) AbstractClassMetaData(org.datanucleus.metadata.AbstractClassMetaData) DatastoreMapping(org.datanucleus.store.rdbms.mapping.datastore.DatastoreMapping) Column(org.datanucleus.store.rdbms.table.Column) RelationType(org.datanucleus.metadata.RelationType) DatastoreClass(org.datanucleus.store.rdbms.table.DatastoreClass) ColumnMetaData(org.datanucleus.metadata.ColumnMetaData) MappingManager(org.datanucleus.store.rdbms.mapping.MappingManager) AbstractClassMetaData(org.datanucleus.metadata.AbstractClassMetaData) ClassMetaData(org.datanucleus.metadata.ClassMetaData) CorrespondentColumnsMapper(org.datanucleus.store.rdbms.mapping.CorrespondentColumnsMapper)

Example 3 with CorrespondentColumnsMapper

use of org.datanucleus.store.rdbms.mapping.CorrespondentColumnsMapper 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.getColumnMapping(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.getNumberOfColumnMappings();
                            for (int i = 0; i < countIdFields; i++) {
                                ColumnMapping refColumnMapping = ownerIdMapping.getColumnMapping(i);
                                JavaTypeMapping mapping = storeMgr.getMappingManager().getMapping(refColumnMapping.getJavaTypeMapping().getJavaType());
                                ColumnMetaData colmd = correspondentColumnsMapping.getColumnMetaDataByIdentifier(refColumnMapping.getColumn().getIdentifier());
                                if (colmd == null) {
                                    throw new NucleusUserException(Localiser.msg("057035", refColumnMapping.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, refColumnMapping.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);
                                refColumnMapping.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.addColumnMapping(getStoreManager().getMappingManager().createColumnMapping(mapping, refColumn, refColumnMapping.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.getNumberOfColumnMappings(); j++) {
                                    if (existingFkMapping.getColumnMapping(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);
                    }
                }
            }
        }
    }
}
Also used : Set(java.util.Set) HashSet(java.util.HashSet) DuplicateColumnException(org.datanucleus.store.rdbms.exceptions.DuplicateColumnException) JavaTypeMapping(org.datanucleus.store.rdbms.mapping.java.JavaTypeMapping) MacroString(org.datanucleus.util.MacroString) AbstractClassMetaData(org.datanucleus.metadata.AbstractClassMetaData) ColumnMetaDataContainer(org.datanucleus.metadata.ColumnMetaDataContainer) Iterator(java.util.Iterator) ColumnMetaData(org.datanucleus.metadata.ColumnMetaData) ColumnMapping(org.datanucleus.store.rdbms.mapping.column.ColumnMapping) HashSet(java.util.HashSet) NucleusUserException(org.datanucleus.exceptions.NucleusUserException) IdentifierFactory(org.datanucleus.store.rdbms.identifier.IdentifierFactory) PersistableMapping(org.datanucleus.store.rdbms.mapping.java.PersistableMapping) DatastoreIdentifier(org.datanucleus.store.rdbms.identifier.DatastoreIdentifier) Collection(java.util.Collection) NucleusException(org.datanucleus.exceptions.NucleusException) AbstractMemberMetaData(org.datanucleus.metadata.AbstractMemberMetaData) Map(java.util.Map) HashMap(java.util.HashMap) CorrespondentColumnsMapper(org.datanucleus.store.rdbms.mapping.CorrespondentColumnsMapper)

Example 4 with CorrespondentColumnsMapper

use of org.datanucleus.store.rdbms.mapping.CorrespondentColumnsMapper 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("056076", 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.getNumberOfColumnMappings(); i++) {
                JavaTypeMapping refDatastoreMapping = storeMgr.getMappingManager().getMapping(m.getColumnMapping(i).getJavaTypeMapping().getJavaType());
                ColumnMetaData colmd = correspondentColumnsMapping.getColumnMetaDataByIdentifier(m.getColumnMapping(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.getColumnMapping(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.getColumnMapping(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.getColumnMapping(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.getColumnMapping(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.getColumnMapping(i).getColumn().copyConfigurationTo(column);
                    if (isPrimaryKey) {
                        column.setPrimaryKey();
                    }
                    if (isNullable) {
                        column.setNullable(true);
                    }
                    storeMgr.getMappingManager().createColumnMapping(refDatastoreMapping, column, m.getColumnMapping(i).getJavaTypeMapping().getJavaTypeForColumnMapping(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().createColumnMapping(mapping, column, mapping.getJavaTypeForColumnMapping(0));
        if (isNullable) {
            column.setNullable(true);
        }
    }
    return mapping;
}
Also used : DuplicateColumnException(org.datanucleus.store.rdbms.exceptions.DuplicateColumnException) JavaTypeMapping(org.datanucleus.store.rdbms.mapping.java.JavaTypeMapping) NucleusUserException(org.datanucleus.exceptions.NucleusUserException) IdentifierFactory(org.datanucleus.store.rdbms.identifier.IdentifierFactory) AbstractClassMetaData(org.datanucleus.metadata.AbstractClassMetaData) PersistableMapping(org.datanucleus.store.rdbms.mapping.java.PersistableMapping) ReferenceMapping(org.datanucleus.store.rdbms.mapping.java.ReferenceMapping) ColumnMetaDataContainer(org.datanucleus.metadata.ColumnMetaDataContainer) DatastoreIdentifier(org.datanucleus.store.rdbms.identifier.DatastoreIdentifier) ColumnMetaData(org.datanucleus.metadata.ColumnMetaData) NoTableManagedException(org.datanucleus.store.rdbms.exceptions.NoTableManagedException) AbstractMemberMetaData(org.datanucleus.metadata.AbstractMemberMetaData) CorrespondentColumnsMapper(org.datanucleus.store.rdbms.mapping.CorrespondentColumnsMapper)

Aggregations

NucleusUserException (org.datanucleus.exceptions.NucleusUserException)4 AbstractClassMetaData (org.datanucleus.metadata.AbstractClassMetaData)4 ColumnMetaData (org.datanucleus.metadata.ColumnMetaData)4 CorrespondentColumnsMapper (org.datanucleus.store.rdbms.mapping.CorrespondentColumnsMapper)4 AbstractMemberMetaData (org.datanucleus.metadata.AbstractMemberMetaData)2 ClassMetaData (org.datanucleus.metadata.ClassMetaData)2 ColumnMetaDataContainer (org.datanucleus.metadata.ColumnMetaDataContainer)2 RelationType (org.datanucleus.metadata.RelationType)2 DuplicateColumnException (org.datanucleus.store.rdbms.exceptions.DuplicateColumnException)2 DatastoreIdentifier (org.datanucleus.store.rdbms.identifier.DatastoreIdentifier)2 IdentifierFactory (org.datanucleus.store.rdbms.identifier.IdentifierFactory)2 MappingManager (org.datanucleus.store.rdbms.mapping.MappingManager)2 ColumnMapping (org.datanucleus.store.rdbms.mapping.column.ColumnMapping)2 JavaTypeMapping (org.datanucleus.store.rdbms.mapping.java.JavaTypeMapping)2 PersistableMapping (org.datanucleus.store.rdbms.mapping.java.PersistableMapping)2 Column (org.datanucleus.store.rdbms.table.Column)2 DatastoreClass (org.datanucleus.store.rdbms.table.DatastoreClass)2 Collection (java.util.Collection)1 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1