Search in sources :

Example 46 with ColumnMetaData

use of org.datanucleus.metadata.ColumnMetaData 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);
                    }
                }
            }
        }
    }
}
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) HashSet(java.util.HashSet) NucleusUserException(org.datanucleus.exceptions.NucleusUserException) IdentifierFactory(org.datanucleus.store.rdbms.identifier.IdentifierFactory) PersistableMapping(org.datanucleus.store.rdbms.mapping.java.PersistableMapping) DatastoreMapping(org.datanucleus.store.rdbms.mapping.datastore.DatastoreMapping) 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 47 with ColumnMetaData

use of org.datanucleus.metadata.ColumnMetaData in project datanucleus-rdbms by datanucleus.

the class CollectionTable method initialize.

/**
 * Method to initialise the table definition.
 * @param clr The ClassLoaderResolver
 */
public void initialize(ClassLoaderResolver clr) {
    super.initialize(clr);
    // Add column(s) for element
    boolean elementPC = (mmd.hasCollection() && mmd.getCollection().elementIsPersistent());
    Class elementClass = clr.classForName(getElementType());
    if (isSerialisedElement() || isEmbeddedElementPC() || (isEmbeddedElement() && !elementPC) || ClassUtils.isReferenceType(elementClass)) {
        // Element = PC(embedded), PC(serialised), Non-PC(serialised), Non-PC(embedded), Reference
        // Join table has : ownerMapping (PK), elementMapping, orderMapping (PK)
        elementMapping = storeMgr.getMappingManager().getMapping(this, mmd, clr, FieldRole.ROLE_COLLECTION_ELEMENT);
        if (NucleusLogger.DATASTORE.isDebugEnabled()) {
            logMapping(mmd.getFullFieldName() + ".[ELEMENT]", elementMapping);
        }
    } else {
        // Element = PC
        // Join table has : ownerMapping (PK), elementMapping, orderMapping (optional)
        ColumnMetaData[] elemColmd = null;
        AbstractMemberMetaData[] relatedMmds = mmd.getRelatedMemberMetaData(clr);
        ElementMetaData elemmd = mmd.getElementMetaData();
        if (elemmd != null && elemmd.getColumnMetaData() != null && elemmd.getColumnMetaData().length > 0) {
            // Column mappings defined at this side (1-N, M-N)
            elemColmd = elemmd.getColumnMetaData();
        } else if (relatedMmds != null && relatedMmds[0].getJoinMetaData() != null && relatedMmds[0].getJoinMetaData().getColumnMetaData() != null && relatedMmds[0].getJoinMetaData().getColumnMetaData().length > 0) {
            // Column mappings defined at other side (M-N) on <join>
            elemColmd = relatedMmds[0].getJoinMetaData().getColumnMetaData();
        }
        elementMapping = ColumnCreator.createColumnsForJoinTables(elementClass, mmd, elemColmd, storeMgr, this, false, false, FieldRole.ROLE_COLLECTION_ELEMENT, clr, null);
        RelationType relationType = mmd.getRelationType(clr);
        if (Boolean.TRUE.equals(mmd.getContainer().allowNulls()) && relationType != RelationType.MANY_TO_MANY_BI) {
            // 1-N : Make all element col(s) nullable so we can store null elements
            for (int i = 0; i < elementMapping.getNumberOfDatastoreMappings(); i++) {
                Column elementCol = elementMapping.getDatastoreMapping(i).getColumn();
                elementCol.setNullable(true);
            }
        }
        if (NucleusLogger.DATASTORE.isDebugEnabled()) {
            logMapping(mmd.getFullFieldName() + ".[ELEMENT]", elementMapping);
        }
    }
    PrimaryKeyMetaData pkmd = (mmd.getJoinMetaData() != null ? mmd.getJoinMetaData().getPrimaryKeyMetaData() : null);
    boolean pkColsSpecified = (pkmd != null ? pkmd.getColumnMetaData() != null : false);
    boolean pkRequired = requiresPrimaryKey();
    // Add order mapping if required
    boolean orderRequired = false;
    if (mmd.getOrderMetaData() != null) {
        if (mmd.getOrderMetaData().isIndexedList()) {
            // Indexed Collection with <order>, so add index mapping
            orderRequired = true;
            RelationType relType = mmd.getRelationType(clr);
            if (relType == RelationType.MANY_TO_MANY_BI) {
                // Don't support M-N using indexed List
                throw new NucleusUserException(Localiser.msg("020002", mmd.getFullFieldName())).setFatal();
            }
        }
    } else if (List.class.isAssignableFrom(mmd.getType())) {
        // Indexed List with no <order>, so has index mapping
        orderRequired = true;
    } else if (pkRequired && !pkColsSpecified) {
        // PK is required so maybe need to add an index to form the PK
        if (isEmbeddedElementPC()) {
            if (mmd.getCollection().getElementClassMetaData(clr).getIdentityType() != IdentityType.APPLICATION) {
                // Embedded PC with datastore id so we need an index to form the PK
                orderRequired = true;
            }
        } else if (isSerialisedElement()) {
            // Serialised element, so need an index to form the PK
            orderRequired = true;
        } else if (elementMapping instanceof ReferenceMapping) {
            // ReferenceMapping, so have order if more than 1 implementation
            ReferenceMapping refMapping = (ReferenceMapping) elementMapping;
            if (refMapping.getJavaTypeMapping().length > 1) {
                orderRequired = true;
            }
        } else if (!(elementMapping instanceof PersistableMapping)) {
            // Non-PC, so depends if the element column can be used as part of a PK
            // TODO This assumes the elementMapping has a single column but what if it is Color with 4 cols?
            Column elementCol = elementMapping.getDatastoreMapping(0).getColumn();
            if (!storeMgr.getDatastoreAdapter().isValidPrimaryKeyType(elementCol.getJdbcType())) {
                // Not possible to use this Non-PC type as part of the PK
                orderRequired = true;
            }
        }
    }
    if (orderRequired) {
        // Order (index) column is required (integer based)
        ColumnMetaData orderColmd = null;
        if (mmd.getOrderMetaData() != null && mmd.getOrderMetaData().getColumnMetaData() != null && mmd.getOrderMetaData().getColumnMetaData().length > 0) {
            // Specified "order" column info
            orderColmd = mmd.getOrderMetaData().getColumnMetaData()[0];
            if (orderColmd.getName() == null) {
                // No column name so use default
                orderColmd = new ColumnMetaData(orderColmd);
                DatastoreIdentifier id = storeMgr.getIdentifierFactory().newIndexFieldIdentifier(mmd);
                orderColmd.setName(id.getName());
            }
        } else {
            // No column name so use default
            DatastoreIdentifier id = storeMgr.getIdentifierFactory().newIndexFieldIdentifier(mmd);
            orderColmd = new ColumnMetaData();
            orderColmd.setName(id.getName());
        }
        // JDO2 spec [18.5] order column is assumed to be "int"
        orderMapping = storeMgr.getMappingManager().getMapping(int.class);
        ColumnCreator.createIndexColumn(orderMapping, storeMgr, clr, this, orderColmd, pkRequired && !pkColsSpecified);
        if (NucleusLogger.DATASTORE.isDebugEnabled()) {
            logMapping(mmd.getFullFieldName() + ".[ORDER]", orderMapping);
        }
    }
    // Define primary key of the join table (if any)
    if (pkRequired) {
        if (pkColsSpecified) {
            // Apply the users PK specification
            applyUserPrimaryKeySpecification(pkmd);
        } else {
            // Define PK
            for (int i = 0; i < ownerMapping.getNumberOfDatastoreMappings(); i++) {
                ownerMapping.getDatastoreMapping(i).getColumn().setPrimaryKey();
            }
            if (orderRequired) {
                // Order column specified so owner+order are the PK
                orderMapping.getDatastoreMapping(0).getColumn().setPrimaryKey();
            } else {
                // No order column specified so owner+element are the PK
                for (int i = 0; i < elementMapping.getNumberOfDatastoreMappings(); i++) {
                    elementMapping.getDatastoreMapping(i).getColumn().setPrimaryKey();
                }
            }
        }
    }
    if (NucleusLogger.DATASTORE_SCHEMA.isDebugEnabled()) {
        NucleusLogger.DATASTORE_SCHEMA.debug(Localiser.msg("057023", this));
    }
    storeMgr.registerTableInitialized(this);
    state = TABLE_STATE_INITIALIZED;
}
Also used : ElementMetaData(org.datanucleus.metadata.ElementMetaData) NucleusUserException(org.datanucleus.exceptions.NucleusUserException) PrimaryKeyMetaData(org.datanucleus.metadata.PrimaryKeyMetaData) PersistableMapping(org.datanucleus.store.rdbms.mapping.java.PersistableMapping) ReferenceMapping(org.datanucleus.store.rdbms.mapping.java.ReferenceMapping) DatastoreIdentifier(org.datanucleus.store.rdbms.identifier.DatastoreIdentifier) RelationType(org.datanucleus.metadata.RelationType) List(java.util.List) ColumnMetaData(org.datanucleus.metadata.ColumnMetaData) AbstractMemberMetaData(org.datanucleus.metadata.AbstractMemberMetaData)

Example 48 with ColumnMetaData

use of org.datanucleus.metadata.ColumnMetaData 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;
}
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)

Example 49 with ColumnMetaData

use of org.datanucleus.metadata.ColumnMetaData in project datanucleus-rdbms by datanucleus.

the class TableImpl method getSQLCreateStatements.

/**
 * Accessor for the SQL CREATE statements for this table.
 * @param props Properties for controlling the table creation
 * @return List of statements.
 */
protected List<String> getSQLCreateStatements(Properties props) {
    assertIsInitialized();
    Column[] cols = null;
    // Pass 1 : populate positions defined in metadata as vendor extension "index"
    Iterator<org.datanucleus.store.schema.table.Column> iter = columns.iterator();
    while (iter.hasNext()) {
        Column col = (Column) iter.next();
        ColumnMetaData colmd = col.getColumnMetaData();
        Integer colPos = (colmd != null ? colmd.getPosition() : null);
        if (colPos != null) {
            int index = colPos.intValue();
            if (index < columns.size() && index >= 0) {
                if (cols == null) {
                    cols = new Column[columns.size()];
                }
                if (cols[index] != null) {
                    throw new NucleusUserException("Column index " + index + " has been specified multiple times : " + cols[index] + " and " + col);
                }
                cols[index] = col;
            }
        }
    }
    // Pass 2 : fill in spaces for columns with undefined positions
    if (cols != null) {
        iter = columns.iterator();
        while (iter.hasNext()) {
            Column col = (Column) iter.next();
            ColumnMetaData colmd = col.getColumnMetaData();
            Integer colPos = (colmd != null ? colmd.getPosition() : null);
            if (colPos == null) {
                // No index set for this column, so assign to next free position
                for (int i = 0; i < cols.length; i++) {
                    if (cols[i] == null) {
                        cols[i] = col;
                    }
                }
            }
        }
    } else {
        cols = columns.toArray(new Column[columns.size()]);
    }
    List<String> stmts = new ArrayList<>();
    stmts.add(dba.getCreateTableStatement(this, cols, props, storeMgr.getIdentifierFactory()));
    PrimaryKey pk = getPrimaryKey();
    if (pk.size() > 0) {
        // Some databases define the primary key on the create table
        // statement so we don't have a Statement for the primary key here.
        String pkStmt = dba.getAddPrimaryKeyStatement(pk, storeMgr.getIdentifierFactory());
        if (pkStmt != null) {
            stmts.add(pkStmt);
        }
    }
    return stmts;
}
Also used : NucleusUserException(org.datanucleus.exceptions.NucleusUserException) ArrayList(java.util.ArrayList) PrimaryKey(org.datanucleus.store.rdbms.key.PrimaryKey) ColumnMetaData(org.datanucleus.metadata.ColumnMetaData)

Example 50 with ColumnMetaData

use of org.datanucleus.metadata.ColumnMetaData in project datanucleus-rdbms by datanucleus.

the class AbstractClassTable method addDatastoreId.

/**
 * Utility to create the datastore identity column and mapping.
 * This is used in 2 modes. The first is where we have a (primary) class table
 * and we aren't creating the OID mapping as a FK to another class. The second
 * is where we have a (secondary) class table and we are creating the OID mapping
 * as a FK to the primary class. In the second case the refTable will be specified.
 * @param columnMetaData The column MetaData for the datastore id
 * @param refTable Table used as a reference (if any)
 * @param cmd The MetaData for the class
 */
void addDatastoreId(ColumnMetaData columnMetaData, DatastoreClass refTable, AbstractClassMetaData cmd) {
    // Create the mapping, setting its table
    datastoreIdMapping = new DatastoreIdMapping();
    datastoreIdMapping.setTable(this);
    datastoreIdMapping.initialize(storeMgr, cmd.getFullClassName());
    // Create a ColumnMetaData in the container if none is defined
    ColumnMetaData colmd = null;
    if (columnMetaData == null) {
        colmd = new ColumnMetaData();
    } else {
        colmd = columnMetaData;
    }
    if (colmd.getName() == null) {
        // Provide default column naming if none is defined
        if (refTable != null) {
            colmd.setName(storeMgr.getIdentifierFactory().newColumnIdentifier(refTable.getIdentifier().getName(), this.storeMgr.getNucleusContext().getTypeManager().isDefaultEmbeddedType(DatastoreId.class), FieldRole.ROLE_OWNER, false).getName());
        } else {
            colmd.setName(storeMgr.getIdentifierFactory().newColumnIdentifier(identifier.getName(), this.storeMgr.getNucleusContext().getTypeManager().isDefaultEmbeddedType(DatastoreId.class), FieldRole.ROLE_NONE, false).getName());
        }
    }
    // Add the datastore identity column as the PK
    Column idColumn = addColumn(DatastoreId.class.getName(), storeMgr.getIdentifierFactory().newIdentifier(IdentifierType.COLUMN, colmd.getName()), datastoreIdMapping, colmd);
    idColumn.setPrimaryKey();
    // Set the identity column type based on the IdentityStrategy
    String strategyName = cmd.getIdentityMetaData().getValueStrategy().toString();
    if (cmd.getIdentityMetaData().getValueStrategy().equals(ValueGenerationStrategy.CUSTOM)) {
        strategyName = cmd.getIdentityMetaData().getValueStrategy().getCustomName();
    }
    if (strategyName != null && ValueGenerationStrategy.NATIVE.toString().equals(strategyName)) {
        strategyName = storeMgr.getValueGenerationStrategyForNative(cmd, -1);
    }
    // Check the value generator type being stored
    Class valueGeneratedType = Long.class;
    if (strategyName != null && ValueGenerationStrategy.IDENTITY.toString().equals(strategyName)) {
        valueGeneratedType = dba.getAutoIncrementJavaTypeForType(valueGeneratedType);
        if (valueGeneratedType != Long.class) {
            NucleusLogger.DATASTORE_SCHEMA.debug("Class " + cmd.getFullClassName() + " uses IDENTITY strategy and rather than using BIGINT " + " for the column type, using " + valueGeneratedType.getName() + " since the datastore requires that");
        }
    } else {
        // Get the type that will be generated by the chosen ValueGeneration strategy
        valueGeneratedType = storeMgr.getValueGenerationManager().getTypeForValueGeneratorForMember(strategyName, storeMgr.getValueGenerationManager().getMemberKey(cmd, -1));
    }
    storeMgr.getMappingManager().createDatastoreMapping(datastoreIdMapping, idColumn, valueGeneratedType.getName());
    logMapping("DATASTORE_ID", datastoreIdMapping);
    // Handle any auto-increment requirement
    if (isObjectIdDatastoreAttributed()) {
        if (this instanceof DatastoreClass && ((DatastoreClass) this).isBaseDatastoreClass()) {
            // Only the base class can be autoincremented
            idColumn.setIdentity(true);
        }
    }
    // Check if auto-increment and that it is supported by this RDBMS
    if (idColumn.isIdentity() && !dba.supportsOption(DatastoreAdapter.IDENTITY_COLUMNS)) {
        throw new NucleusException(Localiser.msg("057020", cmd.getFullClassName(), "datastore-identity")).setFatal();
    }
}
Also used : DatastoreIdMapping(org.datanucleus.store.rdbms.mapping.java.DatastoreIdMapping) DatastoreId(org.datanucleus.identity.DatastoreId) ColumnMetaData(org.datanucleus.metadata.ColumnMetaData) NucleusException(org.datanucleus.exceptions.NucleusException)

Aggregations

ColumnMetaData (org.datanucleus.metadata.ColumnMetaData)85 AbstractMemberMetaData (org.datanucleus.metadata.AbstractMemberMetaData)28 NucleusUserException (org.datanucleus.exceptions.NucleusUserException)16 ClassMetaData (org.datanucleus.metadata.ClassMetaData)14 AbstractClassMetaData (org.datanucleus.metadata.AbstractClassMetaData)13 ElementMetaData (org.datanucleus.metadata.ElementMetaData)13 DatastoreIdentifier (org.datanucleus.store.rdbms.identifier.DatastoreIdentifier)11 ClassLoaderResolver (org.datanucleus.ClassLoaderResolver)10 JoinMetaData (org.datanucleus.metadata.JoinMetaData)9 MetaDataManager (org.datanucleus.metadata.MetaDataManager)9 MappingManager (org.datanucleus.store.rdbms.mapping.MappingManager)8 Column (org.datanucleus.store.rdbms.table.Column)8 NucleusContext (org.datanucleus.NucleusContext)7 PersistenceNucleusContextImpl (org.datanucleus.PersistenceNucleusContextImpl)7 JPAMetaDataManager (org.datanucleus.api.jpa.metadata.JPAMetaDataManager)7 PrimaryKeyMetaData (org.datanucleus.metadata.PrimaryKeyMetaData)7 IdentifierFactory (org.datanucleus.store.rdbms.identifier.IdentifierFactory)7 JavaTypeMapping (org.datanucleus.store.rdbms.mapping.java.JavaTypeMapping)7 DiscriminatorMetaData (org.datanucleus.metadata.DiscriminatorMetaData)6 PersistenceUnitMetaData (org.datanucleus.metadata.PersistenceUnitMetaData)6