Search in sources :

Example 6 with RelationType

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

the class DeleteRequest method execute.

/**
 * Method performing the deletion of the record from the datastore.
 * Takes the constructed deletion query and populates with the specific record information.
 * @param op The ObjectProvider for the record to be deleted.
 */
public void execute(ObjectProvider op) {
    if (NucleusLogger.PERSISTENCE.isDebugEnabled()) {
        // Debug information about what we are deleting
        NucleusLogger.PERSISTENCE.debug(Localiser.msg("052210", op.getObjectAsPrintable(), table));
    }
    // Process all related fields first
    // a). Delete any dependent objects
    // b). Null any non-dependent objects with FK at other side
    ClassLoaderResolver clr = op.getExecutionContext().getClassLoaderResolver();
    Set relatedObjectsToDelete = null;
    for (int i = 0; i < callbacks.length; ++i) {
        if (NucleusLogger.PERSISTENCE.isDebugEnabled()) {
            NucleusLogger.PERSISTENCE.debug(Localiser.msg("052212", op.getObjectAsPrintable(), ((JavaTypeMapping) callbacks[i]).getMemberMetaData().getFullFieldName()));
        }
        callbacks[i].preDelete(op);
        // Check for any dependent related 1-1 objects where we hold the FK and where the object hasn't been deleted.
        // This can happen if this DeleteRequest was triggered by delete-orphans and so the related object has to be deleted *after* this object.
        // It's likely we could do this better by using AttachFieldManager and just marking the "orphan" (i.e this object) as deleted
        // (see AttachFieldManager TODO regarding when not copying)
        JavaTypeMapping mapping = (JavaTypeMapping) callbacks[i];
        AbstractMemberMetaData mmd = mapping.getMemberMetaData();
        RelationType relationType = mmd.getRelationType(clr);
        if (mmd.isDependent() && (relationType == RelationType.ONE_TO_ONE_UNI || (relationType == RelationType.ONE_TO_ONE_BI && mmd.getMappedBy() == null))) {
            try {
                op.isLoaded(mmd.getAbsoluteFieldNumber());
                Object relatedPc = op.provideField(mmd.getAbsoluteFieldNumber());
                boolean relatedObjectDeleted = op.getExecutionContext().getApiAdapter().isDeleted(relatedPc);
                if (!relatedObjectDeleted) {
                    if (relatedObjectsToDelete == null) {
                        relatedObjectsToDelete = new HashSet();
                    }
                    relatedObjectsToDelete.add(relatedPc);
                }
            } catch (// Should be XXXObjectNotFoundException but dont want to use JDO class
            Exception e) {
            }
        }
    }
    // and cater for other cases, in particular persistent interfaces
    if (oneToOneNonOwnerFields != null && oneToOneNonOwnerFields.length > 0) {
        for (int i = 0; i < oneToOneNonOwnerFields.length; i++) {
            AbstractMemberMetaData relatedFmd = oneToOneNonOwnerFields[i];
            updateOneToOneBidirectionalOwnerObjectForField(op, relatedFmd);
        }
    }
    // Choose the statement based on whether optimistic or not
    String stmt = null;
    ExecutionContext ec = op.getExecutionContext();
    RDBMSStoreManager storeMgr = table.getStoreManager();
    boolean optimisticChecks = false;
    if (table.getSurrogateColumn(SurrogateColumnType.SOFTDELETE) != null) {
        stmt = softDeleteStmt;
    } else {
        optimisticChecks = (versionMetaData != null && ec.getTransaction().getOptimistic() && versionChecks);
        if (optimisticChecks) {
            stmt = deleteStmtOptimistic;
        } else {
            stmt = deleteStmt;
        }
    }
    // Process the delete of this object
    try {
        ManagedConnection mconn = storeMgr.getConnectionManager().getConnection(ec);
        SQLController sqlControl = storeMgr.getSQLController();
        try {
            // Perform the delete
            boolean batch = true;
            if (optimisticChecks || !ec.getTransaction().isActive()) {
                // Turn OFF batching if doing optimistic checks (since we need the result of the delete)
                // or if using nontransactional writes (since we want it sending to the datastore now)
                batch = false;
            }
            PreparedStatement ps = sqlControl.getStatementForUpdate(mconn, stmt, batch);
            try {
                // provide WHERE clause field(s)
                if (cmd.getIdentityType() == IdentityType.DATASTORE) {
                    StatementMappingIndex mapIdx = mappingStatementIndex.getWhereDatastoreId();
                    for (int i = 0; i < mapIdx.getNumberOfParameterOccurrences(); i++) {
                        table.getSurrogateMapping(SurrogateColumnType.DATASTORE_ID, false).setObject(ec, ps, mapIdx.getParameterPositionsForOccurrence(i), op.getInternalObjectId());
                    }
                } else {
                    StatementClassMapping mappingDefinition = new StatementClassMapping();
                    StatementMappingIndex[] idxs = mappingStatementIndex.getWhereFields();
                    for (int i = 0; i < idxs.length; i++) {
                        if (idxs[i] != null) {
                            mappingDefinition.addMappingForMember(i, idxs[i]);
                        }
                    }
                    op.provideFields(whereFieldNumbers, new ParameterSetter(op, ps, mappingDefinition));
                }
                if (multitenancyStatementMapping != null) {
                    table.getSurrogateMapping(SurrogateColumnType.MULTITENANCY, false).setObject(ec, ps, multitenancyStatementMapping.getParameterPositionsForOccurrence(0), ec.getNucleusContext().getMultiTenancyId(ec, cmd));
                }
                if (optimisticChecks) {
                    // WHERE clause - current version discriminator
                    JavaTypeMapping verMapping = mappingStatementIndex.getWhereVersion().getMapping();
                    Object currentVersion = op.getTransactionalVersion();
                    if (currentVersion == null) {
                        // Somehow the version is not set on this object (not read in ?) so report the bug
                        String msg = Localiser.msg("052202", op.getInternalObjectId(), table);
                        NucleusLogger.PERSISTENCE.error(msg);
                        throw new NucleusException(msg);
                    }
                    StatementMappingIndex mapIdx = mappingStatementIndex.getWhereVersion();
                    for (int i = 0; i < mapIdx.getNumberOfParameterOccurrences(); i++) {
                        verMapping.setObject(ec, ps, mapIdx.getParameterPositionsForOccurrence(i), currentVersion);
                    }
                }
                int[] rcs = sqlControl.executeStatementUpdate(ec, mconn, stmt, ps, !batch);
                if (optimisticChecks && rcs[0] == 0) {
                    // No object deleted so either object disappeared or failed optimistic version checks
                    throw new NucleusOptimisticException(Localiser.msg("052203", op.getObjectAsPrintable(), op.getInternalObjectId(), "" + op.getTransactionalVersion()), op.getObject());
                }
                if (relatedObjectsToDelete != null && !relatedObjectsToDelete.isEmpty()) {
                    // Delete any related objects that need deleting after the delete of this object
                    Iterator iter = relatedObjectsToDelete.iterator();
                    while (iter.hasNext()) {
                        Object relatedObject = iter.next();
                        ec.deleteObjectInternal(relatedObject);
                    }
                }
            } finally {
                sqlControl.closeStatement(mconn, ps);
            }
        } finally {
            mconn.release();
        }
    } catch (SQLException e) {
        String msg = Localiser.msg("052211", op.getObjectAsPrintable(), stmt, e.getMessage());
        NucleusLogger.DATASTORE_PERSIST.warn(msg);
        List exceptions = new ArrayList();
        exceptions.add(e);
        while ((e = e.getNextException()) != null) {
            exceptions.add(e);
        }
        throw new NucleusDataStoreException(msg, (Throwable[]) exceptions.toArray(new Throwable[exceptions.size()]));
    }
}
Also used : HashSet(java.util.HashSet) Set(java.util.Set) JavaTypeMapping(org.datanucleus.store.rdbms.mapping.java.JavaTypeMapping) SQLException(java.sql.SQLException) ArrayList(java.util.ArrayList) StatementMappingIndex(org.datanucleus.store.rdbms.query.StatementMappingIndex) ParameterSetter(org.datanucleus.store.rdbms.fieldmanager.ParameterSetter) SQLController(org.datanucleus.store.rdbms.SQLController) NucleusDataStoreException(org.datanucleus.exceptions.NucleusDataStoreException) RelationType(org.datanucleus.metadata.RelationType) Iterator(java.util.Iterator) ManagedConnection(org.datanucleus.store.connection.ManagedConnection) ArrayList(java.util.ArrayList) List(java.util.List) HashSet(java.util.HashSet) ClassLoaderResolver(org.datanucleus.ClassLoaderResolver) PreparedStatement(java.sql.PreparedStatement) SQLException(java.sql.SQLException) NucleusException(org.datanucleus.exceptions.NucleusException) NucleusDataStoreException(org.datanucleus.exceptions.NucleusDataStoreException) NucleusOptimisticException(org.datanucleus.exceptions.NucleusOptimisticException) RDBMSStoreManager(org.datanucleus.store.rdbms.RDBMSStoreManager) StatementClassMapping(org.datanucleus.store.rdbms.query.StatementClassMapping) ExecutionContext(org.datanucleus.ExecutionContext) NucleusOptimisticException(org.datanucleus.exceptions.NucleusOptimisticException) NucleusException(org.datanucleus.exceptions.NucleusException) AbstractMemberMetaData(org.datanucleus.metadata.AbstractMemberMetaData)

Example 7 with RelationType

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

the class PersistableMapping method postInsert.

/**
 * Method executed just after the insert of the owning object, allowing any necessary action
 * to this field and the object stored in it.
 * @param op ObjectProvider for the owner
 */
public void postInsert(ObjectProvider op) {
    Object pc = op.provideField(mmd.getAbsoluteFieldNumber());
    TypeManager typeManager = op.getExecutionContext().getTypeManager();
    pc = mmd.isSingleCollection() ? singleCollectionValue(typeManager, pc) : pc;
    if (pc == null) {
        // Has been set to null so nothing to do
        return;
    }
    ClassLoaderResolver clr = op.getExecutionContext().getClassLoaderResolver();
    AbstractMemberMetaData[] relatedMmds = mmd.getRelatedMemberMetaData(clr);
    RelationType relationType = mmd.getRelationType(clr);
    if (relationType == RelationType.ONE_TO_ONE_BI) {
        ObjectProvider otherOP = op.getExecutionContext().findObjectProvider(pc);
        if (otherOP == null) {
            return;
        }
        AbstractMemberMetaData relatedMmd = mmd.getRelatedMemberMetaDataForObject(clr, op.getObject(), pc);
        if (relatedMmd == null) {
            // Fsck knows why
            throw new NucleusUserException("You have a field " + mmd.getFullFieldName() + " that is 1-1 bidir yet cannot find the equivalent field at the other side. Why is that?");
        }
        Object relatedValue = otherOP.provideField(relatedMmd.getAbsoluteFieldNumber());
        relatedValue = relatedMmd.isSingleCollection() ? singleCollectionValue(typeManager, relatedValue) : relatedValue;
        if (relatedValue == null) {
            // Managed Relations : Other side not set so update it in memory
            if (NucleusLogger.PERSISTENCE.isDebugEnabled()) {
                NucleusLogger.PERSISTENCE.debug(Localiser.msg("041018", op.getObjectAsPrintable(), mmd.getFullFieldName(), StringUtils.toJVMIDString(pc), relatedMmd.getFullFieldName()));
            }
            Object replaceValue = op.getObject();
            if (relatedMmd.isSingleCollection()) {
                ElementContainerHandler containerHandler = typeManager.getContainerHandler(relatedMmd.getType());
                replaceValue = containerHandler.newContainer(relatedMmd, op.getObject());
            }
            otherOP.replaceField(relatedMmd.getAbsoluteFieldNumber(), replaceValue);
        } else if (relatedValue != op.getObject()) {
            // Managed Relations : Other side is inconsistent so throw exception
            throw new NucleusUserException(Localiser.msg("041020", op.getObjectAsPrintable(), mmd.getFullFieldName(), StringUtils.toJVMIDString(pc), StringUtils.toJVMIDString(relatedValue)));
        }
    } else if (relationType == RelationType.MANY_TO_ONE_BI && relatedMmds[0].hasCollection()) {
        // TODO Make sure we have this PC in the collection at the other side
        ObjectProvider otherOP = op.getExecutionContext().findObjectProvider(pc);
        if (otherOP != null) {
            // Managed Relations : add to the collection on the other side
            Collection relatedColl = (Collection) otherOP.provideField(relatedMmds[0].getAbsoluteFieldNumber());
            if (relatedColl != null && !(relatedColl instanceof SCOCollection)) {
                // TODO Make sure the collection is a wrapper
                boolean contained = relatedColl.contains(op.getObject());
                if (!contained) {
                    NucleusLogger.PERSISTENCE.info(Localiser.msg("041022", op.getObjectAsPrintable(), mmd.getFullFieldName(), StringUtils.toJVMIDString(pc), relatedMmds[0].getFullFieldName()));
                // TODO Enable this. Currently causes issues with PMImplTest, InheritanceStrategyTest, TCK "inheritance1.conf"
                /*relatedColl.add(op.getObject());*/
                }
            }
        }
    } else if (relationType == RelationType.MANY_TO_ONE_UNI) {
        ObjectProvider otherOP = op.getExecutionContext().findObjectProvider(pc);
        if (otherOP == null) {
            // Related object is not yet persisted so persist it
            Object other = op.getExecutionContext().persistObjectInternal(pc, null, -1, ObjectProvider.PC);
            otherOP = op.getExecutionContext().findObjectProvider(other);
        }
        // Add join table entry
        PersistableRelationStore store = (PersistableRelationStore) storeMgr.getBackingStoreForField(clr, mmd, mmd.getType());
        store.add(op, otherOP);
    }
}
Also used : NucleusUserException(org.datanucleus.exceptions.NucleusUserException) RelationType(org.datanucleus.metadata.RelationType) ClassLoaderResolver(org.datanucleus.ClassLoaderResolver) TypeManager(org.datanucleus.store.types.TypeManager) Collection(java.util.Collection) SCOCollection(org.datanucleus.store.types.SCOCollection) SCOCollection(org.datanucleus.store.types.SCOCollection) ObjectProvider(org.datanucleus.state.ObjectProvider) AbstractMemberMetaData(org.datanucleus.metadata.AbstractMemberMetaData) ElementContainerHandler(org.datanucleus.store.types.ElementContainerHandler) PersistableRelationStore(org.datanucleus.store.types.scostore.PersistableRelationStore)

Example 8 with RelationType

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

the class PersistableMapping method setObjectAsValue.

/**
 * Method to set an object reference (FK) in the datastore.
 * @param ec The ExecutionContext
 * @param ps The Prepared Statement
 * @param param The parameter ids in the statement
 * @param value The value to put in the statement at these ids
 * @param ownerOP ObjectProvider for the owner object
 * @param ownerFieldNumber Field number of this PC object in the owner
 * @throws NotYetFlushedException Just put "null" in and throw "NotYetFlushedException", to be caught by ParameterSetter and will signal to the
 *     PC object being inserted that it needs to inform this object when it is inserted.
 */
private void setObjectAsValue(ExecutionContext ec, PreparedStatement ps, int[] param, Object value, ObjectProvider ownerOP, int ownerFieldNumber) {
    Object id;
    ApiAdapter api = ec.getApiAdapter();
    if (!api.isPersistable(value)) {
        throw new NucleusException(Localiser.msg("041016", value.getClass(), value)).setFatal();
    }
    ObjectProvider valueOP = ec.findObjectProvider(value);
    try {
        ClassLoaderResolver clr = ec.getClassLoaderResolver();
        // Check if the field is attributed in the datastore
        boolean hasDatastoreAttributedPrimaryKeyValues = hasDatastoreAttributedPrimaryKeyValues(ec.getMetaDataManager(), storeMgr, clr);
        boolean inserted = false;
        if (ownerFieldNumber >= 0) {
            // Field mapping : is this field of the related object present in the datastore?
            inserted = storeMgr.isObjectInserted(valueOP, ownerFieldNumber);
        } else if (mmd == null) {
            // Identity mapping : is the object inserted far enough to be considered of this mapping type?
            inserted = storeMgr.isObjectInserted(valueOP, type);
        }
        if (valueOP != null) {
            if (ec.getApiAdapter().isDetached(value) && valueOP.getReferencedPC() != null && ownerOP != null && mmd != null) {
                // Still detached but started attaching so replace the field with what will be the attached
                // Note that we have "fmd != null" here hence omitting any M-N relations where this is a join table
                // mapping
                ownerOP.replaceFieldMakeDirty(ownerFieldNumber, valueOP.getReferencedPC());
            }
            if (valueOP.isWaitingToBeFlushedToDatastore()) {
                try {
                    // Related object is not yet flushed to the datastore so flush it so we can set the FK
                    valueOP.flush();
                } catch (NotYetFlushedException nfe) {
                    // Could not flush it, maybe it has a relation to this object! so set as null TODO check nullability
                    if (ownerOP != null) {
                        ownerOP.updateFieldAfterInsert(value, ownerFieldNumber);
                    }
                    setObjectAsNull(ec, ps, param);
                    return;
                }
            }
        } else {
            if (ec.getApiAdapter().isDetached(value)) {
                // Field value is detached and not yet started attaching, so attach
                Object attachedValue = ec.persistObjectInternal(value, null, -1, ObjectProvider.PC);
                if (attachedValue != value && ownerOP != null) {
                    // Replace the field value if using copy-on-attach
                    ownerOP.replaceFieldMakeDirty(ownerFieldNumber, attachedValue);
                    // Work from attached value now that it is attached
                    value = attachedValue;
                }
                valueOP = ec.findObjectProvider(value);
            }
        }
        // 5) the value is the same object as we are inserting anyway and has its identity set
        if (inserted || !ec.isInserting(value) || (!hasDatastoreAttributedPrimaryKeyValues && (this.mmd != null && this.mmd.isPrimaryKey())) || (!hasDatastoreAttributedPrimaryKeyValues && ownerOP == valueOP && api.getIdForObject(value) != null)) {
            // The PC is either already inserted, or inserted down to the level we need, or not inserted at all,
            // or the field is a PK and identity not attributed by the datastore
            // Object either already exists, or is not yet being inserted.
            id = api.getIdForObject(value);
            // Check if the persistable object exists in this datastore
            boolean requiresPersisting = false;
            if (ec.getApiAdapter().isDetached(value) && ownerOP != null) {
                // Detached object so needs attaching
                if (ownerOP.isInserting()) {
                    // we can just return the value now and attach later (in InsertRequest)
                    if (!ec.getBooleanProperty(PropertyNames.PROPERTY_ATTACH_SAME_DATASTORE)) {
                        if (ec.getObjectFromCache(api.getIdForObject(value)) != null) {
                        // Object is in cache so exists for this datastore, so no point checking
                        } else {
                            try {
                                Object obj = ec.findObject(api.getIdForObject(value), true, false, value.getClass().getName());
                                if (obj != null) {
                                    // Make sure this object is not retained in cache etc
                                    ObjectProvider objOP = ec.findObjectProvider(obj);
                                    if (objOP != null) {
                                        ec.evictFromTransaction(objOP);
                                    }
                                    ec.removeObjectFromLevel1Cache(api.getIdForObject(value));
                                }
                            } catch (NucleusObjectNotFoundException onfe) {
                                // Object doesn't yet exist
                                requiresPersisting = true;
                            }
                        }
                    }
                } else {
                    requiresPersisting = true;
                }
            } else if (id == null) {
                // Transient object, so we need to persist it
                requiresPersisting = true;
            } else {
                ExecutionContext pcEC = ec.getApiAdapter().getExecutionContext(value);
                if (pcEC != null && ec != pcEC) {
                    throw new NucleusUserException(Localiser.msg("041015"), id);
                }
            }
            if (requiresPersisting) {
                // This PC object needs persisting (new or detached) to do the "set"
                if (mmd != null && !mmd.isCascadePersist() && !ec.getApiAdapter().isDetached(value)) {
                    // Related PC object not persistent, but cant do cascade-persist so throw exception
                    if (NucleusLogger.PERSISTENCE.isDebugEnabled()) {
                        NucleusLogger.PERSISTENCE.debug(Localiser.msg("007006", mmd.getFullFieldName()));
                    }
                    throw new ReachableObjectNotCascadedException(mmd.getFullFieldName(), value);
                }
                if (NucleusLogger.PERSISTENCE.isDebugEnabled()) {
                    NucleusLogger.PERSISTENCE.debug(Localiser.msg("007007", mmd != null ? mmd.getFullFieldName() : null));
                }
                try {
                    Object pcNew = ec.persistObjectInternal(value, null, -1, ObjectProvider.PC);
                    if (hasDatastoreAttributedPrimaryKeyValues) {
                        ec.flushInternal(false);
                    }
                    id = api.getIdForObject(pcNew);
                    if (ec.getApiAdapter().isDetached(value) && ownerOP != null && mmd != null) {
                        // Update any detached reference to refer to the attached variant
                        ownerOP.replaceFieldMakeDirty(ownerFieldNumber, pcNew);
                        RelationType relationType = mmd.getRelationType(clr);
                        if (relationType == RelationType.MANY_TO_ONE_BI) {
                            // TODO Update the container to refer to the attached object
                            if (NucleusLogger.PERSISTENCE.isInfoEnabled()) {
                                NucleusLogger.PERSISTENCE.info("PCMapping.setObject : object " + ownerOP.getInternalObjectId() + " has field " + ownerFieldNumber + " that is 1-N bidirectional." + " Have just attached the N side so should really update the reference in the 1 side collection" + " to refer to this attached object. Not yet implemented");
                            }
                        } else if (relationType == RelationType.ONE_TO_ONE_BI) {
                            AbstractMemberMetaData[] relatedMmds = mmd.getRelatedMemberMetaData(clr);
                            // TODO Cater for more than 1 related field
                            ObjectProvider relatedOP = ec.findObjectProvider(pcNew);
                            relatedOP.replaceFieldMakeDirty(relatedMmds[0].getAbsoluteFieldNumber(), ownerOP.getObject());
                        }
                    }
                } catch (NotYetFlushedException e) {
                    setObjectAsNull(ec, ps, param);
                    throw new NotYetFlushedException(value);
                }
            }
            if (valueOP != null) {
                valueOP.setStoringPC();
            }
            // If the field doesn't map to any datastore fields (e.g remote FK), omit the set process
            if (getNumberOfDatastoreMappings() > 0) {
                if (IdentityUtils.isDatastoreIdentity(id)) {
                    Object idKey = IdentityUtils.getTargetKeyForDatastoreIdentity(id);
                    try {
                        // Try as a Long
                        getDatastoreMapping(0).setObject(ps, param[0], idKey);
                    } catch (Exception e) {
                        // Must be a String
                        getDatastoreMapping(0).setObject(ps, param[0], idKey.toString());
                    }
                } else {
                    boolean fieldsSet = false;
                    if (IdentityUtils.isSingleFieldIdentity(id) && javaTypeMappings.length > 1) {
                        Object key = IdentityUtils.getTargetKeyForSingleFieldIdentity(id);
                        AbstractClassMetaData keyCmd = ec.getMetaDataManager().getMetaDataForClass(key.getClass(), clr);
                        if (keyCmd != null && keyCmd.getIdentityType() == IdentityType.NONDURABLE) {
                            // Embedded ID - Make sure these are called starting at lowest first, in order
                            // We cannot just call OP.provideFields with all fields since that does last first
                            ObjectProvider keyOP = ec.findObjectProvider(key);
                            int[] fieldNums = keyCmd.getAllMemberPositions();
                            FieldManager fm = new AppIDObjectIdFieldManager(param, ec, ps, javaTypeMappings);
                            for (int i = 0; i < fieldNums.length; i++) {
                                keyOP.provideFields(new int[] { fieldNums[i] }, fm);
                            }
                            fieldsSet = true;
                        }
                    }
                    if (!fieldsSet) {
                        // Copy PK fields from identity to the object
                        FieldManager fm = new AppIDObjectIdFieldManager(param, ec, ps, javaTypeMappings);
                        api.copyKeyFieldsFromIdToObject(value, new AppIdObjectIdFieldConsumer(api, fm), id);
                    }
                }
            }
        } else {
            if (valueOP != null) {
                valueOP.setStoringPC();
            }
            if (getNumberOfDatastoreMappings() > 0) {
                // Object is in the process of being inserted so we cant use its id currently and we need to store
                // a foreign key to it (which we cant yet do). Just put "null" in and throw "NotYetFlushedException",
                // to be caught by ParameterSetter and will signal to the PC object being inserted that it needs
                // to inform this object when it is inserted.
                setObjectAsNull(ec, ps, param);
                throw new NotYetFlushedException(value);
            }
        }
    } finally {
        if (valueOP != null) {
            valueOP.unsetStoringPC();
        }
    }
}
Also used : ApiAdapter(org.datanucleus.api.ApiAdapter) AppIDObjectIdFieldManager(org.datanucleus.store.rdbms.mapping.AppIDObjectIdFieldManager) SingleValueFieldManager(org.datanucleus.store.fieldmanager.SingleValueFieldManager) FieldManager(org.datanucleus.store.fieldmanager.FieldManager) NucleusUserException(org.datanucleus.exceptions.NucleusUserException) ClassLoaderResolver(org.datanucleus.ClassLoaderResolver) NotYetFlushedException(org.datanucleus.exceptions.NotYetFlushedException) NucleusObjectNotFoundException(org.datanucleus.exceptions.NucleusObjectNotFoundException) NucleusObjectNotFoundException(org.datanucleus.exceptions.NucleusObjectNotFoundException) ReachableObjectNotCascadedException(org.datanucleus.exceptions.ReachableObjectNotCascadedException) NucleusException(org.datanucleus.exceptions.NucleusException) NucleusUserException(org.datanucleus.exceptions.NucleusUserException) NotYetFlushedException(org.datanucleus.exceptions.NotYetFlushedException) AbstractClassMetaData(org.datanucleus.metadata.AbstractClassMetaData) ReachableObjectNotCascadedException(org.datanucleus.exceptions.ReachableObjectNotCascadedException) ExecutionContext(org.datanucleus.ExecutionContext) RelationType(org.datanucleus.metadata.RelationType) AppIDObjectIdFieldManager(org.datanucleus.store.rdbms.mapping.AppIDObjectIdFieldManager) ObjectProvider(org.datanucleus.state.ObjectProvider) NucleusException(org.datanucleus.exceptions.NucleusException) AppIdObjectIdFieldConsumer(org.datanucleus.state.AppIdObjectIdFieldConsumer)

Example 9 with RelationType

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

the class MultiPersistableMapping method setObject.

/**
 * Sets the specified positions in the PreparedStatement associated with this field, and value.
 * If the number of positions in "pos" is not the same as the number of datastore mappings then it is assumed
 * that we should only set the positions for the real implementation FK; this happens where we have a statement
 * like "... WHERE IMPL1_ID_OID = ? AND IMPL2_ID_OID IS NULL" so we need to filter on the other implementations
 * being null and only want to input parameter(s) for the real implementation of "value".
 * @param ec execution context
 * @param ps a datastore object that executes statements in the database
 * @param pos The position(s) of the PreparedStatement to populate
 * @param value the value stored in this field
 * @param ownerOP the owner ObjectProvider
 * @param ownerFieldNumber the owner absolute field number
 */
public void setObject(ExecutionContext ec, PreparedStatement ps, int[] pos, Object value, ObjectProvider ownerOP, int ownerFieldNumber) {
    boolean setValueFKOnly = false;
    if (pos != null && pos.length < getNumberOfDatastoreMappings()) {
        setValueFKOnly = true;
    }
    // Make sure that this field has a sub-mapping appropriate for the specified value
    int javaTypeMappingNumber = getMappingNumberForValue(ec, value);
    if (value != null && javaTypeMappingNumber == -1) {
        // TODO Change this to a multiple field mapping localised message
        throw new ClassCastException(Localiser.msg("041044", mmd != null ? mmd.getFullFieldName() : "", getType(), value.getClass().getName()));
    }
    if (value != null) {
        ApiAdapter api = ec.getApiAdapter();
        ClassLoaderResolver clr = ec.getClassLoaderResolver();
        // Make sure the value is persisted if it is persistable in its own right
        if (!ec.isInserting(value)) {
            // Object either already exists, or is not yet being inserted.
            Object id = api.getIdForObject(value);
            // Check if the persistable exists in this datastore
            boolean requiresPersisting = false;
            if (ec.getApiAdapter().isDetached(value) && ownerOP != null) {
                // Detached object that needs attaching (or persisting if detached from a different datastore)
                requiresPersisting = true;
            } else if (id == null) {
                // Transient object, so we need to persist it
                requiresPersisting = true;
            } else {
                ExecutionContext valueEC = api.getExecutionContext(value);
                if (valueEC != null && ec != valueEC) {
                    throw new NucleusUserException(Localiser.msg("041015"), id);
                }
            }
            if (requiresPersisting) {
                // The object is either not yet persistent or is detached and so needs attaching
                Object pcNew = ec.persistObjectInternal(value, null, -1, ObjectProvider.PC);
                ec.flushInternal(false);
                id = api.getIdForObject(pcNew);
                if (ec.getApiAdapter().isDetached(value) && ownerOP != null) {
                    // Update any detached reference to refer to the attached variant
                    ownerOP.replaceFieldMakeDirty(ownerFieldNumber, pcNew);
                    if (mmd != null) {
                        RelationType relationType = mmd.getRelationType(clr);
                        if (relationType == RelationType.ONE_TO_ONE_BI) {
                            ObjectProvider relatedSM = ec.findObjectProvider(pcNew);
                            AbstractMemberMetaData[] relatedMmds = mmd.getRelatedMemberMetaData(clr);
                            // TODO Allow for multiple related fields
                            relatedSM.replaceFieldMakeDirty(relatedMmds[0].getAbsoluteFieldNumber(), ownerOP.getObject());
                        } else if (relationType == RelationType.MANY_TO_ONE_BI) {
                            // TODO Update the container element with the attached variant
                            if (NucleusLogger.PERSISTENCE.isDebugEnabled()) {
                                NucleusLogger.PERSISTENCE.debug("PCMapping.setObject : object " + ownerOP.getInternalObjectId() + " has field " + ownerFieldNumber + " that is 1-N bidirectional - should really update the reference in the relation. Not yet supported");
                            }
                        }
                    }
                }
            }
            if (getNumberOfDatastoreMappings() <= 0) {
                // If the field doesn't map to any datastore fields, omit the set process
                return;
            }
        }
    }
    if (pos == null) {
        return;
    }
    ObjectProvider op = (value != null ? ec.findObjectProvider(value) : null);
    try {
        if (op != null) {
            op.setStoringPC();
        }
        int n = 0;
        NotYetFlushedException notYetFlushed = null;
        for (int i = 0; i < javaTypeMappings.length; i++) {
            // Set the PreparedStatement positions for this implementation mapping
            int[] posMapping;
            if (setValueFKOnly) {
                // Only using first "pos" value(s)
                n = 0;
            } else if (n >= pos.length) {
                // store all implementations to the same columns, so we reset the index
                n = 0;
            }
            if (javaTypeMappings[i].getReferenceMapping() != null) {
                posMapping = new int[javaTypeMappings[i].getReferenceMapping().getNumberOfDatastoreMappings()];
            } else {
                posMapping = new int[javaTypeMappings[i].getNumberOfDatastoreMappings()];
            }
            for (int j = 0; j < posMapping.length; j++) {
                posMapping[j] = pos[n++];
            }
            try {
                if (javaTypeMappingNumber == -2 || (value != null && javaTypeMappingNumber == i)) {
                    // This mapping is where the value is to be stored, or using persistent interfaces
                    javaTypeMappings[i].setObject(ec, ps, posMapping, value);
                } else if (!setValueFKOnly) {
                    // Set null for this mapping, since the value is null or is for something else
                    javaTypeMappings[i].setObject(ec, ps, posMapping, null);
                }
            } catch (NotYetFlushedException e) {
                notYetFlushed = e;
            }
        }
        if (notYetFlushed != null) {
            throw notYetFlushed;
        }
    } finally {
        if (op != null) {
            op.unsetStoringPC();
        }
    }
}
Also used : ApiAdapter(org.datanucleus.api.ApiAdapter) NucleusUserException(org.datanucleus.exceptions.NucleusUserException) ClassLoaderResolver(org.datanucleus.ClassLoaderResolver) NotYetFlushedException(org.datanucleus.exceptions.NotYetFlushedException) ExecutionContext(org.datanucleus.ExecutionContext) RelationType(org.datanucleus.metadata.RelationType) ObjectProvider(org.datanucleus.state.ObjectProvider) AbstractMemberMetaData(org.datanucleus.metadata.AbstractMemberMetaData)

Example 10 with RelationType

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

the class ClassTable method getExpectedIndices.

/**
 * Accessor for the indices for this table. This includes both the
 * user-defined indices (via MetaData), and the ones required by foreign
 * keys (required by relationships).
 * @param clr The ClassLoaderResolver
 * @return The indices
 */
protected Set<Index> getExpectedIndices(ClassLoaderResolver clr) {
    // Auto mode allows us to decide which indices are needed as well as using what is in the users MetaData
    boolean autoMode = false;
    if (storeMgr.getStringProperty(RDBMSPropertyNames.PROPERTY_RDBMS_CONSTRAINT_CREATE_MODE).equals("DataNucleus")) {
        autoMode = true;
    }
    Set<Index> indices = new HashSet();
    // Add on any user-required indices for the fields/properties
    Set memberNumbersSet = memberMappingsMap.keySet();
    Iterator iter = memberNumbersSet.iterator();
    while (iter.hasNext()) {
        AbstractMemberMetaData fmd = (AbstractMemberMetaData) iter.next();
        JavaTypeMapping fieldMapping = memberMappingsMap.get(fmd);
        if (fieldMapping instanceof EmbeddedPCMapping) {
            // Add indexes for fields of this embedded PC object
            EmbeddedPCMapping embMapping = (EmbeddedPCMapping) fieldMapping;
            for (int i = 0; i < embMapping.getNumberOfJavaTypeMappings(); i++) {
                JavaTypeMapping embFieldMapping = embMapping.getJavaTypeMapping(i);
                IndexMetaData imd = embFieldMapping.getMemberMetaData().getIndexMetaData();
                if (imd != null) {
                    Index index = TableUtils.getIndexForField(this, imd, embFieldMapping);
                    if (index != null) {
                        indices.add(index);
                    }
                }
            }
        } else if (fieldMapping instanceof SerialisedMapping) {
        // Don't index these
        } else {
            // Add any required index for this field
            IndexMetaData imd = fmd.getIndexMetaData();
            if (imd != null) {
                // Index defined so add it
                Index index = TableUtils.getIndexForField(this, imd, fieldMapping);
                if (index != null) {
                    indices.add(index);
                }
            } else if (autoMode) {
                if (fmd.getIndexed() == null) {
                    // Indexing not set, so add where we think it is appropriate
                    if (// Ignore PKs since they will be indexed anyway
                    !fmd.isPrimaryKey()) {
                        // TODO Some RDBMS create index automatically for all FK cols so we don't need to really
                        RelationType relationType = fmd.getRelationType(clr);
                        if (relationType == RelationType.ONE_TO_ONE_UNI) {
                            // 1-1 with FK at this side so index the FK
                            if (fieldMapping instanceof ReferenceMapping) {
                                ReferenceMapping refMapping = (ReferenceMapping) fieldMapping;
                                if (refMapping.getMappingStrategy() == ReferenceMapping.PER_IMPLEMENTATION_MAPPING) {
                                    // Cols per implementation : index each of implementations
                                    if (refMapping.getJavaTypeMapping() != null) {
                                        int colNum = 0;
                                        JavaTypeMapping[] implMappings = refMapping.getJavaTypeMapping();
                                        for (int i = 0; i < implMappings.length; i++) {
                                            int numColsInImpl = implMappings[i].getNumberOfDatastoreMappings();
                                            Index index = new Index(this, false, null);
                                            for (int j = 0; j < numColsInImpl; j++) {
                                                index.setColumn(j, fieldMapping.getDatastoreMapping(colNum++).getColumn());
                                            }
                                            indices.add(index);
                                        }
                                    }
                                }
                            } else {
                                Index index = new Index(this, false, null);
                                for (int i = 0; i < fieldMapping.getNumberOfDatastoreMappings(); i++) {
                                    index.setColumn(i, fieldMapping.getDatastoreMapping(i).getColumn());
                                }
                                indices.add(index);
                            }
                        } else if (relationType == RelationType.ONE_TO_ONE_BI && fmd.getMappedBy() == null) {
                            // 1-1 with FK at this side so index the FK
                            Index index = new Index(this, false, null);
                            for (int i = 0; i < fieldMapping.getNumberOfDatastoreMappings(); i++) {
                                index.setColumn(i, fieldMapping.getDatastoreMapping(i).getColumn());
                            }
                            indices.add(index);
                        } else if (relationType == RelationType.MANY_TO_ONE_BI) {
                            // N-1 with FK at this side so index the FK
                            AbstractMemberMetaData relMmd = fmd.getRelatedMemberMetaData(clr)[0];
                            if (relMmd.getJoinMetaData() == null && fmd.getJoinMetaData() == null) {
                                if (fieldMapping.getNumberOfDatastoreMappings() > 0) {
                                    Index index = new Index(this, false, null);
                                    for (int i = 0; i < fieldMapping.getNumberOfDatastoreMappings(); i++) {
                                        index.setColumn(i, fieldMapping.getDatastoreMapping(i).getColumn());
                                    }
                                    indices.add(index);
                                } else {
                                    // TODO How do we get this?
                                    NucleusLogger.DATASTORE_SCHEMA.warn("Table " + this + " manages member " + fmd.getFullFieldName() + " which is a N-1 but there is no column for this mapping so not adding index!");
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    // Check if any version column needs indexing
    if (versionMapping != null) {
        IndexMetaData idxmd = getVersionMetaData().getIndexMetaData();
        if (idxmd != null) {
            Index index = new Index(this, idxmd.isUnique(), idxmd.getExtensions());
            if (idxmd.getName() != null) {
                index.setName(idxmd.getName());
            }
            int countVersionFields = versionMapping.getNumberOfDatastoreMappings();
            for (int i = 0; i < countVersionFields; i++) {
                index.addColumn(versionMapping.getDatastoreMapping(i).getColumn());
            }
            indices.add(index);
        }
    }
    // Check if any discriminator column needs indexing
    if (discriminatorMapping != null) {
        DiscriminatorMetaData dismd = getDiscriminatorMetaData();
        IndexMetaData idxmd = dismd.getIndexMetaData();
        if (idxmd != null) {
            Index index = new Index(this, idxmd.isUnique(), idxmd.getExtensions());
            if (idxmd.getName() != null) {
                index.setName(idxmd.getName());
            }
            int countDiscrimFields = discriminatorMapping.getNumberOfDatastoreMappings();
            for (int i = 0; i < countDiscrimFields; i++) {
                index.addColumn(discriminatorMapping.getDatastoreMapping(i).getColumn());
            }
            indices.add(index);
        }
    }
    // Add on any order fields (for lists, arrays, collections) that need indexing
    Set orderMappingsEntries = getExternalOrderMappings().entrySet();
    Iterator orderMappingsEntriesIter = orderMappingsEntries.iterator();
    while (orderMappingsEntriesIter.hasNext()) {
        Map.Entry entry = (Map.Entry) orderMappingsEntriesIter.next();
        AbstractMemberMetaData fmd = (AbstractMemberMetaData) entry.getKey();
        JavaTypeMapping mapping = (JavaTypeMapping) entry.getValue();
        OrderMetaData omd = fmd.getOrderMetaData();
        if (omd != null && omd.getIndexMetaData() != null) {
            Index index = getIndexForIndexMetaDataAndMapping(omd.getIndexMetaData(), mapping);
            if (index != null) {
                indices.add(index);
            }
        }
    }
    // Add on any user-required indices for the class(es) as a whole (subelement of <class>)
    Iterator<AbstractClassMetaData> cmdIter = managedClassMetaData.iterator();
    while (cmdIter.hasNext()) {
        AbstractClassMetaData thisCmd = cmdIter.next();
        List<IndexMetaData> classIndices = thisCmd.getIndexMetaData();
        if (classIndices != null) {
            for (IndexMetaData idxmd : classIndices) {
                Index index = getIndexForIndexMetaData(idxmd);
                if (index != null) {
                    indices.add(index);
                }
            }
        }
    }
    if (cmd.getIdentityType() == IdentityType.APPLICATION) {
        // Make sure there is no reuse of PK fields that cause a duplicate index for the PK. Remove it if required
        PrimaryKey pk = getPrimaryKey();
        Iterator<Index> indicesIter = indices.iterator();
        while (indicesIter.hasNext()) {
            Index idx = indicesIter.next();
            if (idx.getColumnList().equals(pk.getColumnList())) {
                NucleusLogger.DATASTORE_SCHEMA.debug("Index " + idx + " is for the same columns as the PrimaryKey so being removed from expected set of indices. PK is always indexed");
                indicesIter.remove();
            }
        }
    }
    return indices;
}
Also used : Set(java.util.Set) HashSet(java.util.HashSet) JavaTypeMapping(org.datanucleus.store.rdbms.mapping.java.JavaTypeMapping) PrimaryKey(org.datanucleus.store.rdbms.key.PrimaryKey) Index(org.datanucleus.store.rdbms.key.Index) AbstractClassMetaData(org.datanucleus.metadata.AbstractClassMetaData) OrderMetaData(org.datanucleus.metadata.OrderMetaData) ReferenceMapping(org.datanucleus.store.rdbms.mapping.java.ReferenceMapping) RelationType(org.datanucleus.metadata.RelationType) Iterator(java.util.Iterator) HashSet(java.util.HashSet) EmbeddedPCMapping(org.datanucleus.store.rdbms.mapping.java.EmbeddedPCMapping) IndexMetaData(org.datanucleus.metadata.IndexMetaData) DiscriminatorMetaData(org.datanucleus.metadata.DiscriminatorMetaData) SerialisedMapping(org.datanucleus.store.rdbms.mapping.java.SerialisedMapping) AbstractMemberMetaData(org.datanucleus.metadata.AbstractMemberMetaData) Map(java.util.Map) HashMap(java.util.HashMap)

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