Search in sources :

Example 36 with RelationType

use of org.datanucleus.metadata.RelationType in project datanucleus-core by datanucleus.

the class NavigationNullCompilationOptimiser method isPrimaryExpressionRelationNavigation.

protected boolean isPrimaryExpressionRelationNavigation(PrimaryExpression primExpr) {
    List<String> tuples = primExpr.getTuples();
    Iterator<String> tupleIter = tuples.iterator();
    String component = "";
    AbstractClassMetaData cmd = mmgr.getMetaDataForClass(compilation.candidateClass, clr);
    AbstractMemberMetaData mmd = null;
    while (tupleIter.hasNext()) {
        String name = tupleIter.next();
        if (component.length() == 0) {
            if (name.equals(compilation.candidateAlias)) {
            // Starting from this
            } else {
                mmd = cmd.getMetaDataForMember(name);
                RelationType relType = mmd.getRelationType(clr);
                if (RelationType.isRelationSingleValued(relType)) {
                    // Should only join through 1-1/N-1 relations
                    AbstractMemberMetaData[] relMmds = mmd.getRelatedMemberMetaData(clr);
                    cmd = relMmds[0].getAbstractClassMetaData();
                    mmd = relMmds[0];
                // TODO Is this nullable?
                }
            }
            component = name;
        } else {
            if (cmd == null) {
                return false;
            }
            if (mmd != null) {
            }
        }
        component = component + "." + name;
    }
    // TODO Implement this
    return false;
}
Also used : RelationType(org.datanucleus.metadata.RelationType) AbstractMemberMetaData(org.datanucleus.metadata.AbstractMemberMetaData) AbstractClassMetaData(org.datanucleus.metadata.AbstractClassMetaData)

Example 37 with RelationType

use of org.datanucleus.metadata.RelationType in project datanucleus-core by datanucleus.

the class L2CachePopulateFieldManager method processMapContainer.

private void processMapContainer(int fieldNumber, Object mapContainer, AbstractMemberMetaData mmd, MapHandler<Object> containerHandler) {
    try {
        if (!ec.getNucleusContext().getConfiguration().getBooleanProperty(PropertyNames.PROPERTY_CACHE_L2_CACHE_EMBEDDED)) {
            RelationType relType = mmd.getRelationType(ec.getClassLoaderResolver());
            if (relType != RelationType.NONE && (containerHandler.isSerialised(mmd) || containerHandler.isEmbedded(mmd))) {
                // User has requested no caching of embedded/serialised, so ignore this field
                cachedPC.setLoadedField(fieldNumber, false);
                return;
            }
        }
        boolean keyIsPersistent = mmd.getMap().keyIsPersistent();
        boolean keyIsEmbedded = mmd.getMap().isEmbeddedKey();
        boolean keyIsSerialised = mmd.getMap().isSerializedKey();
        boolean valueIsPersistent = mmd.getMap().valueIsPersistent();
        boolean valueIsEmbedded = mmd.getMap().isEmbeddedValue();
        boolean valueIsSerialised = mmd.getMap().isSerializedValue();
        Object newContainer = newContainer(mapContainer, mmd, containerHandler);
        MapContainerAdapter<Object> mapToCacheAdapter = containerHandler.getAdapter(newContainer);
        ApiAdapter api = ec.getApiAdapter();
        for (Entry<Object, Object> entry : containerHandler.getAdapter(mapContainer).entries()) {
            Object mapKey = null;
            if (keyIsPersistent) {
                mapKey = (keyIsEmbedded || keyIsSerialised || mmd.isSerialized()) ? convertPersistableToCachedPC(entry.getKey()) : getCacheableIdForId(api, entry.getKey());
            } else {
                mapKey = SCOUtils.copyValue(entry.getKey());
            }
            Object mapValue = null;
            if (valueIsPersistent) {
                mapValue = (valueIsEmbedded || valueIsSerialised || mmd.isSerialized()) ? convertPersistableToCachedPC(entry.getValue()) : getCacheableIdForId(api, entry.getValue());
            } else {
                mapValue = SCOUtils.copyValue(entry.getValue());
            }
            mapToCacheAdapter.put(mapKey, mapValue);
        }
        // Put Map<X, Y> in CachedPC where X, Y can be OID or CachedPC if they are persistable objects
        cachedPC.setFieldValue(fieldNumber, mapToCacheAdapter.getContainer());
    } catch (Exception e) {
        NucleusLogger.CACHE.warn("Unable to create object of type " + mapContainer.getClass().getName() + " for L2 caching : " + e.getMessage());
        // Contents not loaded so just mark as unloaded
        cachedPC.setLoadedField(fieldNumber, false);
    }
}
Also used : ApiAdapter(org.datanucleus.api.ApiAdapter) RelationType(org.datanucleus.metadata.RelationType)

Example 38 with RelationType

use of org.datanucleus.metadata.RelationType in project datanucleus-core by datanucleus.

the class L2CachePopulateFieldManager method processField.

private void processField(int fieldNumber, Object value, AbstractMemberMetaData mmd) {
    RelationType relType = mmd.getRelationType(ec.getClassLoaderResolver());
    if (relType == RelationType.NONE) {
        Object unwrappedValue = value instanceof SCO ? ((SCO) value).getValue() : value;
        cachedPC.setFieldValue(fieldNumber, SCOUtils.copyValue(unwrappedValue));
        return;
    }
    // 1-1, N-1 persistable field
    if (mmd.isSerialized() || MetaDataUtils.isMemberEmbedded(mmd, relType, ec.getClassLoaderResolver(), ec.getMetaDataManager())) {
        if (ec.getNucleusContext().getConfiguration().getBooleanProperty(PropertyNames.PROPERTY_CACHE_L2_CACHE_EMBEDDED)) {
            // Put object in cached as (nested) CachedPC
            cachedPC.setFieldValue(fieldNumber, convertPersistableToCachedPC(value));
        } else {
            // User not caching embedded/serialised
            cachedPC.setLoadedField(fieldNumber, false);
        }
    } else {
        // Put cacheable form of the id in CachedPC
        cachedPC.setFieldValue(fieldNumber, getCacheableIdForId(ec.getApiAdapter(), value));
    }
}
Also used : RelationType(org.datanucleus.metadata.RelationType) SCO(org.datanucleus.store.types.SCO)

Example 39 with RelationType

use of org.datanucleus.metadata.RelationType in project datanucleus-core by datanucleus.

the class L2CachePopulateFieldManager method processElementContainer.

private void processElementContainer(int fieldNumber, Object container, AbstractMemberMetaData mmd, ElementContainerHandler<Object, ElementContainerAdapter<Object>> containerHandler) {
    RelationType relType = mmd.getRelationType(ec.getClassLoaderResolver());
    if (relType == RelationType.NONE) {
        // Container<Non-PC>
        boolean isContainerMutable = ec.getTypeManager().isSecondClassMutableType(mmd.getType().getName());
        String elementType = containerHandler.getElementTypeName(mmd.getContainer());
        boolean isElementMutable = ec.getTypeManager().isSecondClassMutableType(elementType);
        if (isContainerMutable || isElementMutable) {
            ElementContainerAdapter<Object> adapterToCache = containerHandler.getAdapter(newContainer(container, mmd, containerHandler));
            if (isElementMutable) {
                for (Object elementSCO : containerHandler.getAdapter(container)) {
                    adapterToCache.add(SCOUtils.copyValue(elementSCO));
                }
            } else {
                for (Object element : containerHandler.getAdapter(container)) {
                    adapterToCache.add(element);
                }
            }
            cachedPC.setFieldValue(fieldNumber, adapterToCache.getContainer());
        } else {
            // Both container and element are immutable so we can just cache it as it is
            cachedPC.setFieldValue(fieldNumber, container);
        }
    } else {
        // Container<PC>
        ElementContainerAdapter containerAdapter = containerHandler.getAdapter(container);
        if (containerAdapter instanceof SequenceAdapter && mmd.getOrderMetaData() != null && !mmd.getOrderMetaData().isIndexedList()) {
            // Ordered list so don't cache since dependent on datastore-retrieve order
            cachedPC.setLoadedField(fieldNumber, false);
            return;
        }
        try {
            // For arrays[PC] just use an Object array to store the ids because we can use the same type of the original container.
            // Later when restoring the values it will be based on the metadata instead of the actual container type, as opposed to how it's done for non-array containers.
            Object newContainer = mmd.hasArray() ? EMPTY_ARRAY : newContainer(container, mmd, containerHandler);
            ElementContainerAdapter containerToCacheAdapter = containerHandler.getAdapter(newContainer);
            ApiAdapter api = ec.getApiAdapter();
            if ((containerHandler.isSerialised(mmd) || containerHandler.isEmbedded(mmd)) && !ec.getNucleusContext().getConfiguration().getBooleanProperty(PropertyNames.PROPERTY_CACHE_L2_CACHE_EMBEDDED)) {
                // User not caching embedded/serialised
                cachedPC.setLoadedField(fieldNumber, false);
                return;
            }
            for (Object element : containerAdapter) {
                if (containerHandler.isSerialised(mmd) || containerHandler.isEmbedded(mmd)) {
                    // Store embedded/serialised element as nested collection element
                    containerToCacheAdapter.add(convertPersistableToCachedPC(element));
                } else {
                    // Store id of element, since cached in its own right
                    containerToCacheAdapter.add(getCacheableIdForId(api, element));
                }
            }
            cachedPC.setFieldValue(fieldNumber, containerToCacheAdapter.getContainer());
        } catch (Exception e) {
            NucleusLogger.CACHE.warn("Unable to create object of type " + container.getClass().getName() + " for L2 caching : " + e.getMessage());
            // Contents not loaded so just mark as unloaded
            cachedPC.setLoadedField(fieldNumber, false);
        }
    }
}
Also used : ApiAdapter(org.datanucleus.api.ApiAdapter) ElementContainerAdapter(org.datanucleus.store.types.ElementContainerAdapter) RelationType(org.datanucleus.metadata.RelationType) SequenceAdapter(org.datanucleus.store.types.SequenceAdapter)

Example 40 with RelationType

use of org.datanucleus.metadata.RelationType in project datanucleus-core by datanucleus.

the class AttachFieldManager method storeObjectField.

/**
 * Method to store an object field into the attached instance.
 * @param fieldNumber Number of the field to store
 * @param value the value in the detached instance
 */
public void storeObjectField(int fieldNumber, Object value) {
    // Note : when doing updates always do replaceField first and makeDirty after since the replaceField
    // can cause flush() to be called meaning that an update with null would be made before the new value
    // makes it into the field
    AbstractClassMetaData cmd = attachedOP.getClassMetaData();
    AbstractMemberMetaData mmd = cmd.getMetaDataForManagedMemberAtAbsolutePosition(fieldNumber);
    ExecutionContext ec = attachedOP.getExecutionContext();
    RelationType relationType = mmd.getRelationType(ec.getClassLoaderResolver());
    // boolean processWhenExisting = true;
    if (mmd.hasExtension("attach")) {
        if (mmd.getValueForExtension("attach").equalsIgnoreCase("never")) {
            // Member is tagged to not attach, so put a null
            attachedOP.replaceFieldMakeDirty(fieldNumber, null);
            return;
        }
    // TODO Support attach only when not present in the datastore (only for PCs)
    // else if (mmd.getValueForExtension("attach").equalsIgnoreCase("when-non-existing"))
    // {
    // processWhenExisting = false;
    // }
    }
    // Use ContainerHandlers to support non-JDK Collections and single element collections
    ApiAdapter api = ec.getApiAdapter();
    if (value == null) {
        Object oldValue = null;
        if (mmd.isDependent() && persistent) {
            // Get any old value of this field so we can do cascade-delete if being nulled
            try {
                attachedOP.loadFieldFromDatastore(fieldNumber);
            } catch (Exception e) {
            // Error loading the field so didn't exist before attaching anyway
            }
            oldValue = attachedOP.provideField(fieldNumber);
        }
        attachedOP.replaceField(fieldNumber, null);
        if (dirtyFields[fieldNumber] || !persistent) {
            attachedOP.makeDirty(fieldNumber);
        }
        if (mmd.isDependent() && !mmd.isEmbedded() && oldValue != null && api.isPersistable(oldValue)) {
            // Check for a field storing a PC where it is being nulled and the other object is dependent
            // Flush the nulling of the field
            attachedOP.flush();
            NucleusLogger.PERSISTENCE.debug(Localiser.msg("026026", oldValue, mmd.getFullFieldName()));
            ec.deleteObjectInternal(oldValue);
        }
    } else if (secondClassMutableFields[fieldNumber]) {
        if (mmd.isSerialized() && !RelationType.isRelationMultiValued(relationType)) {
            // SCO Field is serialised, and no persistable elements so just update the column with this new value
            attachedOP.replaceFieldMakeDirty(fieldNumber, value);
            attachedOP.makeDirty(fieldNumber);
        } else {
            // Make sure that the value is a SCO wrapper
            Object oldValue = null;
            if (persistent && !attachedOP.isFieldLoaded(fieldNumber)) {
                attachedOP.loadField(fieldNumber);
            }
            oldValue = attachedOP.provideField(fieldNumber);
            boolean changed = dirtyFields[fieldNumber];
            if (!changed) {
                // Check if the new value is different (not detected if detached field was not a wrapper and mutable)
                if (oldValue == null) {
                    changed = true;
                } else {
                    if (mmd.hasCollection() && relationType != RelationType.NONE) {
                        boolean collsEqual = SCOUtils.collectionsAreEqual(api, (Collection) oldValue, (Collection) value);
                        changed = !collsEqual;
                    } else // TODO Do like the above for relational Maps
                    {
                        changed = !(oldValue.equals(value));
                    }
                }
            }
            SCO sco;
            if (oldValue == null || !(oldValue instanceof SCO)) {
                // Detached object didn't use wrapped field
                if (NucleusLogger.PERSISTENCE.isDebugEnabled()) {
                    NucleusLogger.PERSISTENCE.debug(Localiser.msg("026029", StringUtils.toJVMIDString(attachedOP.getObject()), attachedOP.getInternalObjectId(), mmd.getName()));
                }
                sco = ec.getTypeManager().createSCOInstance(attachedOP, mmd, value != null ? value.getClass() : null, null, false);
                if (sco instanceof SCOContainer) {
                    // Load any containers to avoid update issues
                    ((SCOContainer) sco).load();
                }
                attachedOP.replaceFieldMakeDirty(fieldNumber, sco);
            } else {
                // The field is already a SCO wrapper, so just copy the new values to it
                sco = (SCO) oldValue;
            }
            if (cascadeAttach) {
                // Only trigger the cascade when required
                if (copy) {
                    // Attach copy of the SCO
                    sco.attachCopy(value);
                } else {
                    // Should be changed to do things like in attachCopy above.
                    if (sco instanceof Collection) {
                        // Attach all PC elements of the collection
                        SCOUtils.attachForCollection(attachedOP, ((Collection) value).toArray(), SCOUtils.collectionHasElementsWithoutIdentity(mmd));
                    } else if (sco instanceof Map) {
                        // Attach all PC keys/values of the map
                        SCOUtils.attachForMap(attachedOP, ((Map) value).entrySet(), SCOUtils.mapHasKeysWithoutIdentity(mmd), SCOUtils.mapHasValuesWithoutIdentity(mmd));
                    } else {
                        // Initialise the SCO with the new value
                        sco.initialise(value);
                    }
                }
            }
            if (changed || !persistent) {
                attachedOP.makeDirty(fieldNumber);
            }
        }
    } else if (mmd.getType().isArray() && RelationType.isRelationMultiValued(relationType)) {
        // Array of persistable objects
        if (mmd.isSerialized() || mmd.isEmbedded()) {
            // Field is serialised/embedded so just update the column with this new value TODO Make sure they have ObjectProviders
            attachedOP.replaceField(fieldNumber, value);
            if (dirtyFields[fieldNumber] || !persistent) {
                attachedOP.makeDirty(fieldNumber);
            }
        } else {
            Object oldValue = attachedOP.provideField(fieldNumber);
            if (oldValue == null && !attachedOP.getLoadedFields()[fieldNumber] && persistent) {
                // Retrieve old value for field
                attachedOP.loadField(fieldNumber);
                oldValue = attachedOP.provideField(fieldNumber);
            }
            if (cascadeAttach) {
                // Only trigger the cascade when required
                Object arr = Array.newInstance(mmd.getType().getComponentType(), Array.getLength(value));
                for (int i = 0; i < Array.getLength(value); i++) {
                    Object elem = Array.get(value, i);
                    // TODO Compare with old value and handle delete dependent etc
                    if (copy) {
                        Object elemAttached = ec.attachObjectCopy(attachedOP, elem, false);
                        Array.set(arr, i, elemAttached);
                    } else {
                        ec.attachObject(attachedOP, elem, false);
                        Array.set(arr, i, elem);
                    }
                }
                attachedOP.replaceFieldMakeDirty(fieldNumber, arr);
            }
            if (dirtyFields[fieldNumber] || !persistent) {
                attachedOP.makeDirty(fieldNumber);
            }
        }
    } else if (RelationType.isRelationSingleValued(relationType)) {
        // 1-1/N-1
        ObjectProvider valueSM = ec.findObjectProvider(value);
        if (valueSM != null && valueSM.getReferencedPC() != null && !api.isPersistent(value)) {
            // Value has ObjectProvider and has referenced object so is being attached, so refer to attached PC
            if (dirtyFields[fieldNumber]) {
                attachedOP.replaceFieldMakeDirty(fieldNumber, valueSM.getReferencedPC());
            } else {
                attachedOP.replaceField(fieldNumber, valueSM.getReferencedPC());
            }
        }
        if (cascadeAttach) {
            // Determine if field is persisted into the owning object (embedded/serialised)
            boolean sco = mmd.getEmbeddedMetaData() != null || mmd.isSerialized() || mmd.isEmbedded();
            if (copy) {
                // Attach copy of the PC
                value = ec.attachObjectCopy(attachedOP, value, sco);
                if (sco || dirtyFields[fieldNumber]) {
                    // Either embedded/serialised or marked as changed, so make it dirty
                    attachedOP.replaceFieldMakeDirty(fieldNumber, value);
                } else {
                    attachedOP.replaceField(fieldNumber, value);
                }
            } else {
                // Attach PC in-situ
                ec.attachObject(attachedOP, value, sco);
            }
            // Make sure the field is marked as dirty
            if (dirtyFields[fieldNumber] || !persistent) {
                attachedOP.makeDirty(fieldNumber);
            } else if (sco && value != null && api.isDirty(value)) {
                attachedOP.makeDirty(fieldNumber);
            }
        } else if (dirtyFields[fieldNumber] || !persistent) {
            attachedOP.makeDirty(fieldNumber);
        }
    } else {
        attachedOP.replaceField(fieldNumber, value);
        if (dirtyFields[fieldNumber] || !persistent) {
            attachedOP.makeDirty(fieldNumber);
        }
    }
}
Also used : ApiAdapter(org.datanucleus.api.ApiAdapter) AbstractClassMetaData(org.datanucleus.metadata.AbstractClassMetaData) SCOContainer(org.datanucleus.store.types.SCOContainer) ExecutionContext(org.datanucleus.ExecutionContext) RelationType(org.datanucleus.metadata.RelationType) Collection(java.util.Collection) ObjectProvider(org.datanucleus.state.ObjectProvider) AbstractMemberMetaData(org.datanucleus.metadata.AbstractMemberMetaData) Map(java.util.Map) SCO(org.datanucleus.store.types.SCO)

Aggregations

RelationType (org.datanucleus.metadata.RelationType)41 AbstractMemberMetaData (org.datanucleus.metadata.AbstractMemberMetaData)33 AbstractClassMetaData (org.datanucleus.metadata.AbstractClassMetaData)14 ClassLoaderResolver (org.datanucleus.ClassLoaderResolver)10 NucleusUserException (org.datanucleus.exceptions.NucleusUserException)10 JavaTypeMapping (org.datanucleus.store.rdbms.mapping.java.JavaTypeMapping)10 ArrayList (java.util.ArrayList)9 ExecutionContext (org.datanucleus.ExecutionContext)7 ApiAdapter (org.datanucleus.api.ApiAdapter)7 DatastoreClass (org.datanucleus.store.rdbms.table.DatastoreClass)7 ObjectProvider (org.datanucleus.state.ObjectProvider)6 Collection (java.util.Collection)5 Iterator (java.util.Iterator)5 List (java.util.List)5 NucleusException (org.datanucleus.exceptions.NucleusException)5 HashMap (java.util.HashMap)4 HashSet (java.util.HashSet)4 Map (java.util.Map)4 ColumnMetaData (org.datanucleus.metadata.ColumnMetaData)4 EmbeddedPCMapping (org.datanucleus.store.rdbms.mapping.java.EmbeddedPCMapping)4