Search in sources :

Example 1 with DetachFieldManager

use of org.datanucleus.store.fieldmanager.DetachFieldManager in project datanucleus-core by datanucleus.

the class StateManagerImpl method detachCopy.

/**
 * Method to make detached copy of this instance
 * If the object is detachable then the copy will be migrated to DETACHED state, otherwise will migrate
 * the copy to TRANSIENT. Used by "ExecutionContext.detachObjectCopy()".
 * @param state State for the detachment process
 * @return the detached Persistable instance
 */
public Persistable detachCopy(FetchPlanState state) {
    if (myLC.isDeleted()) {
        throw new NucleusUserException(Localiser.msg("026023", myPC.getClass().getName(), myID));
    }
    if (myEC.getApiAdapter().isDetached(myPC)) {
        throw new NucleusUserException(Localiser.msg("026024", myPC.getClass().getName(), myID));
    }
    if (dirty) {
        myEC.flushInternal(false);
    }
    if (isDetaching()) {
        // Object in the process of detaching (recursive) so return the object which will be the detached object
        return getReferencedPC();
    }
    // Look for an existing detached copy
    DetachState detachState = (DetachState) state;
    DetachState.Entry existingDetached = detachState.getDetachedCopyEntry(myPC);
    Persistable detachedPC;
    if (existingDetached == null) {
        // No existing detached copy - create new one
        detachedPC = myPC.dnNewInstance(this);
        detachState.setDetachedCopyEntry(myPC, detachedPC);
    } else {
        // Found one - if it's sufficient for current FetchPlanState, return it immediately
        detachedPC = (Persistable) existingDetached.getDetachedCopyObject();
        if (existingDetached.checkCurrentState()) {
            return detachedPC;
        }
    // Need to process the detached copy using current FetchPlanState
    }
    myEC.setAttachDetachReferencedObject(this, detachedPC);
    // Check if detachable ... if so then we detach a copy, otherwise we return a transient copy
    boolean detachable = myEC.getApiAdapter().isDetachable(myPC);
    // make sure a detaching PC is not read by another thread while we are detaching
    Object referencedPC = getReferencedPC();
    synchronized (referencedPC) {
        int[] detachFieldNums = getFieldsNumbersToDetach();
        if (detachable) {
            if (NucleusLogger.PERSISTENCE.isDebugEnabled()) {
                int[] fieldsToLoad = null;
                if ((myEC.getFetchPlan().getDetachmentOptions() & FetchPlan.DETACH_LOAD_FIELDS) != 0) {
                    fieldsToLoad = ClassUtils.getFlagsSetTo(loadedFields, myFP.getMemberNumbers(), false);
                }
                NucleusLogger.PERSISTENCE.debug(Localiser.msg("010010", StringUtils.toJVMIDString(myPC), "" + state.getCurrentFetchDepth(), StringUtils.toJVMIDString(detachedPC), StringUtils.intArrayToString(detachFieldNums), StringUtils.intArrayToString(fieldsToLoad)));
            }
            // Call any "pre-detach" listeners
            getCallbackHandler().preDetach(myPC);
        }
        try {
            setDetaching(true);
            // Handle any field loading/unloading before the detach
            if ((myEC.getFetchPlan().getDetachmentOptions() & FetchPlan.DETACH_LOAD_FIELDS) != 0) {
                // Load any unloaded fetch-plan fields
                loadUnloadedFieldsInFetchPlan();
            }
            if (myLC == myEC.getNucleusContext().getApiAdapter().getLifeCycleState(LifeCycleState.HOLLOW) || myLC == myEC.getNucleusContext().getApiAdapter().getLifeCycleState(LifeCycleState.P_NONTRANS)) {
                // Migrate any HOLLOW/P_NONTRANS to P_CLEAN etc
                myLC = myLC.transitionReadField(this, true);
            }
            // Create a SM for our copy object
            ObjectProvider smDetachedPC = new StateManagerImpl(myEC, cmd);
            smDetachedPC.initialiseForDetached(detachedPC, getExternalObjectId(myPC), getVersion(myPC));
            myEC.setAttachDetachReferencedObject(smDetachedPC, myPC);
            // If detached copy already existed, take note of fields previously loaded
            if (existingDetached != null) {
                smDetachedPC.retrieveDetachState(smDetachedPC);
            }
            smDetachedPC.replaceFields(detachFieldNums, new DetachFieldManager(this, cmd.getSCOMutableMemberFlags(), myFP, state, true));
            myEC.setAttachDetachReferencedObject(smDetachedPC, null);
            if (detachable) {
                // Update the object with its detached state - not to be confused with the "state" object above
                detachedPC.dnReplaceFlags();
                ((Detachable) detachedPC).dnReplaceDetachedState();
            } else {
                smDetachedPC.makeTransient(null);
            }
            // Remove its StateManager since now detached or transient
            replaceStateManager(detachedPC, null);
        } catch (Exception e) {
            // What could possibly be wrong here ? Log it and let the user provide a testcase, yeah right
            NucleusLogger.PERSISTENCE.warn("DETACH ERROR : Error thrown while detaching " + StringUtils.toJVMIDString(myPC) + " (id=" + myID + "). Provide a testcase that demonstrates this", e);
        } finally {
            setDetaching(false);
            referencedPC = null;
        }
        if (detachable && !myEC.getApiAdapter().isDetached(detachedPC)) {
            // Sanity check on the objects detached state
            throw new NucleusUserException(Localiser.msg("026025", detachedPC.getClass().getName(), myID));
        }
        if (detachable) {
            // Call any "post-detach" listeners
            getCallbackHandler().postDetach(myPC, detachedPC);
        }
    }
    return detachedPC;
}
Also used : Detachable(org.datanucleus.enhancement.Detachable) Persistable(org.datanucleus.enhancement.Persistable) NucleusUserException(org.datanucleus.exceptions.NucleusUserException) DetachFieldManager(org.datanucleus.store.fieldmanager.DetachFieldManager) DetachState(org.datanucleus.DetachState) NucleusObjectNotFoundException(org.datanucleus.exceptions.NucleusObjectNotFoundException) NucleusException(org.datanucleus.exceptions.NucleusException) EndOfFetchPlanGraphException(org.datanucleus.store.fieldmanager.AbstractFetchDepthFieldManager.EndOfFetchPlanGraphException) NucleusUserException(org.datanucleus.exceptions.NucleusUserException) ClassNotResolvedException(org.datanucleus.exceptions.ClassNotResolvedException) NotYetFlushedException(org.datanucleus.exceptions.NotYetFlushedException)

Example 2 with DetachFieldManager

use of org.datanucleus.store.fieldmanager.DetachFieldManager in project datanucleus-core by datanucleus.

the class StateManagerImpl method detach.

/**
 * Method to detach this object.
 * If the object is detachable then it will be migrated to DETACHED state, otherwise will migrate to TRANSIENT. Used by "DetachAllOnCommit"/"DetachAllOnRollback"
 * @param state State for the detachment process
 */
public void detach(FetchPlanState state) {
    if (myEC == null) {
        return;
    }
    ApiAdapter api = myEC.getApiAdapter();
    if (myLC.isDeleted() || api.isDetached(myPC) || isDetaching()) {
        // Already deleted, detached or being detached
        return;
    }
    // Check if detachable ... if so then we detach a copy, otherwise we return a transient copy
    boolean detachable = api.isDetachable(myPC);
    if (detachable) {
        if (NucleusLogger.PERSISTENCE.isDebugEnabled()) {
            NucleusLogger.PERSISTENCE.debug(Localiser.msg("010009", StringUtils.toJVMIDString(myPC), "" + state.getCurrentFetchDepth()));
        }
        // Call any "pre-detach" listeners
        getCallbackHandler().preDetach(myPC);
    }
    try {
        setDetaching(true);
        String detachedState = myEC.getNucleusContext().getConfiguration().getStringProperty(PropertyNames.PROPERTY_DETACH_DETACHED_STATE);
        if (detachedState.equalsIgnoreCase("all")) {
            loadUnloadedFields();
        } else if (detachedState.equalsIgnoreCase("loaded")) {
        // Do nothing since just using currently loaded fields
        } else {
            // Using fetch-groups, so honour detachmentOptions for loading/unloading
            if ((myEC.getFetchPlan().getDetachmentOptions() & FetchPlan.DETACH_LOAD_FIELDS) != 0) {
                // Load any unloaded fetch-plan fields
                loadUnloadedFieldsInFetchPlan();
            }
            if ((myEC.getFetchPlan().getDetachmentOptions() & FetchPlan.DETACH_UNLOAD_FIELDS) != 0) {
                // Unload any loaded fetch-plan fields that aren't in the current fetch plan
                unloadNonFetchPlanFields();
                // Remove the values from the detached object - not required by the spec
                int[] unloadedFields = ClassUtils.getFlagsSetTo(loadedFields, cmd.getAllMemberPositions(), false);
                if (unloadedFields != null && unloadedFields.length > 0) {
                    Persistable dummyPC = myPC.dnNewInstance(this);
                    myPC.dnCopyFields(dummyPC, unloadedFields);
                    replaceStateManager(dummyPC, null);
                }
            }
        }
        // Detach all (loaded) fields in the FetchPlan
        FieldManager detachFieldManager = new DetachFieldManager(this, cmd.getSCOMutableMemberFlags(), myFP, state, false);
        for (int i = 0; i < loadedFields.length; i++) {
            if (loadedFields[i]) {
                try {
                    // Just fetch the field since we are usually called in postCommit() so dont want to update it
                    detachFieldManager.fetchObjectField(i);
                } catch (EndOfFetchPlanGraphException eofpge) {
                    Object value = provideField(i);
                    if (api.isPersistable(value)) {
                        // PC field beyond end of graph
                        ObjectProvider valueOP = myEC.findObjectProvider(value);
                        if (!api.isDetached(value) && !(valueOP != null && valueOP.isDetaching())) {
                            // Field value is not detached or being detached so unload it
                            String fieldName = cmd.getMetaDataForManagedMemberAtAbsolutePosition(i).getName();
                            if (NucleusLogger.PERSISTENCE.isDebugEnabled()) {
                                NucleusLogger.PERSISTENCE.debug(Localiser.msg("026032", StringUtils.toJVMIDString(myPC), IdentityUtils.getPersistableIdentityForId(myID), fieldName));
                            }
                            unloadField(fieldName);
                        }
                    }
                // TODO What if we have collection/map that includes some objects that are not detached?
                // Currently we just leave as persistent etc but should we????
                // The problem is that with 1-N bidir fields we could unload the field incorrectly
                }
            }
        }
        if (detachable) {
            // Migrate the lifecycle state to DETACHED_CLEAN
            myLC = myLC.transitionDetach(this);
            // Update the object with its detached state
            myPC.dnReplaceFlags();
            ((Detachable) myPC).dnReplaceDetachedState();
            // Call any "post-detach" listeners
            // there is no copy, so give the same object
            getCallbackHandler().postDetach(myPC, myPC);
            Persistable toCheckPC = myPC;
            Object toCheckID = myID;
            disconnect();
            if (!toCheckPC.dnIsDetached()) {
                // Sanity check on the objects detached state
                throw new NucleusUserException(Localiser.msg("026025", toCheckPC.getClass().getName(), toCheckID));
            }
        } else {
            // Warn the user since they selected detachAllOnCommit
            NucleusLogger.PERSISTENCE.warn(Localiser.msg("026031", myPC.getClass().getName(), IdentityUtils.getPersistableIdentityForId(myID)));
            // Make the object transient
            makeTransient(null);
        }
    } finally {
        setDetaching(false);
    }
}
Also used : Detachable(org.datanucleus.enhancement.Detachable) ApiAdapter(org.datanucleus.api.ApiAdapter) Persistable(org.datanucleus.enhancement.Persistable) LoadFieldManager(org.datanucleus.store.fieldmanager.LoadFieldManager) MakeTransientFieldManager(org.datanucleus.store.fieldmanager.MakeTransientFieldManager) AttachFieldManager(org.datanucleus.store.fieldmanager.AttachFieldManager) UnsetOwnerFieldManager(org.datanucleus.store.fieldmanager.UnsetOwnerFieldManager) DetachFieldManager(org.datanucleus.store.fieldmanager.DetachFieldManager) PersistFieldManager(org.datanucleus.store.fieldmanager.PersistFieldManager) SingleValueFieldManager(org.datanucleus.store.fieldmanager.SingleValueFieldManager) DeleteFieldManager(org.datanucleus.store.fieldmanager.DeleteFieldManager) L2CachePopulateFieldManager(org.datanucleus.cache.L2CachePopulateFieldManager) FieldManager(org.datanucleus.store.fieldmanager.FieldManager) SingleTypeFieldManager(org.datanucleus.store.fieldmanager.SingleTypeFieldManager) L2CacheRetrieveFieldManager(org.datanucleus.cache.L2CacheRetrieveFieldManager) DetachFieldManager(org.datanucleus.store.fieldmanager.DetachFieldManager) NucleusUserException(org.datanucleus.exceptions.NucleusUserException) EndOfFetchPlanGraphException(org.datanucleus.store.fieldmanager.AbstractFetchDepthFieldManager.EndOfFetchPlanGraphException)

Aggregations

Detachable (org.datanucleus.enhancement.Detachable)2 Persistable (org.datanucleus.enhancement.Persistable)2 NucleusUserException (org.datanucleus.exceptions.NucleusUserException)2 EndOfFetchPlanGraphException (org.datanucleus.store.fieldmanager.AbstractFetchDepthFieldManager.EndOfFetchPlanGraphException)2 DetachFieldManager (org.datanucleus.store.fieldmanager.DetachFieldManager)2 DetachState (org.datanucleus.DetachState)1 ApiAdapter (org.datanucleus.api.ApiAdapter)1 L2CachePopulateFieldManager (org.datanucleus.cache.L2CachePopulateFieldManager)1 L2CacheRetrieveFieldManager (org.datanucleus.cache.L2CacheRetrieveFieldManager)1 ClassNotResolvedException (org.datanucleus.exceptions.ClassNotResolvedException)1 NotYetFlushedException (org.datanucleus.exceptions.NotYetFlushedException)1 NucleusException (org.datanucleus.exceptions.NucleusException)1 NucleusObjectNotFoundException (org.datanucleus.exceptions.NucleusObjectNotFoundException)1 AttachFieldManager (org.datanucleus.store.fieldmanager.AttachFieldManager)1 DeleteFieldManager (org.datanucleus.store.fieldmanager.DeleteFieldManager)1 FieldManager (org.datanucleus.store.fieldmanager.FieldManager)1 LoadFieldManager (org.datanucleus.store.fieldmanager.LoadFieldManager)1 MakeTransientFieldManager (org.datanucleus.store.fieldmanager.MakeTransientFieldManager)1 PersistFieldManager (org.datanucleus.store.fieldmanager.PersistFieldManager)1 SingleTypeFieldManager (org.datanucleus.store.fieldmanager.SingleTypeFieldManager)1