Search in sources :

Example 1 with NotYetFlushedException

use of org.datanucleus.exceptions.NotYetFlushedException in project datanucleus-rdbms by datanucleus.

the class DatastoreIdMapping method setObject.

/**
 * Mutator for the OID in the datastore
 * @param ec ExecutionContext
 * @param ps The Prepared Statement
 * @param param Param numbers in the PreparedStatement for this object
 * @param value The OID value to use
 */
public void setObject(ExecutionContext ec, PreparedStatement ps, int[] param, Object value) {
    if (value == null) {
        getDatastoreMapping(0).setObject(ps, param[0], null);
    } else {
        ApiAdapter api = ec.getApiAdapter();
        Object id;
        if (api.isPersistable(value)) {
            id = api.getIdForObject(value);
            if (id == null) {
                if (ec.isInserting(value)) {
                    // Object is in the process of being inserted, but has no id yet so provide a null for now
                    // The "NotYetFlushedException" is caught by ParameterSetter and processed as an update being required.
                    getDatastoreMapping(0).setObject(ps, param[0], null);
                    throw new NotYetFlushedException(value);
                }
                // Object is not persist, nor in the process of being made persistent
                ec.persistObjectInternal(value, null, -1, ObjectProvider.PC);
                ec.flushInternal(false);
            }
            id = api.getIdForObject(value);
        } else {
            id = value;
        }
        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());
        }
    }
}
Also used : ApiAdapter(org.datanucleus.api.ApiAdapter) NotYetFlushedException(org.datanucleus.exceptions.NotYetFlushedException) NotYetFlushedException(org.datanucleus.exceptions.NotYetFlushedException)

Example 2 with NotYetFlushedException

use of org.datanucleus.exceptions.NotYetFlushedException in project datanucleus-rdbms by datanucleus.

the class InsertRequest method execute.

/**
 * Method performing the insertion of the record from the datastore.
 * Takes the constructed insert query and populates with the specific record information.
 * @param op The ObjectProvider for the record to be inserted
 */
public void execute(ObjectProvider op) {
    ExecutionContext ec = op.getExecutionContext();
    if (NucleusLogger.PERSISTENCE.isDebugEnabled()) {
        // Debug information about what we are inserting
        NucleusLogger.PERSISTENCE.debug(Localiser.msg("052207", op.getObjectAsPrintable(), table));
    }
    try {
        VersionMetaData vermd = table.getVersionMetaData();
        RDBMSStoreManager storeMgr = table.getStoreManager();
        if (vermd != null && vermd.getFieldName() != null) {
            // Version field - Update the version in the object
            AbstractMemberMetaData verfmd = ((AbstractClassMetaData) vermd.getParent()).getMetaDataForMember(vermd.getFieldName());
            Object currentVersion = op.getVersion();
            if (currentVersion instanceof Number) {
                // Cater for Integer based versions
                currentVersion = Long.valueOf(((Number) currentVersion).longValue());
            }
            Object nextOptimisticVersion = ec.getLockManager().getNextVersion(vermd, currentVersion);
            if (verfmd.getType() == Integer.class || verfmd.getType() == int.class) {
                // Cater for Integer based versions
                nextOptimisticVersion = Integer.valueOf(((Number) nextOptimisticVersion).intValue());
            }
            op.replaceField(verfmd.getAbsoluteFieldNumber(), nextOptimisticVersion);
        }
        // Set the state to "inserting" (may already be at this state if multiple inheritance level INSERT)
        op.changeActivityState(ActivityState.INSERTING);
        SQLController sqlControl = storeMgr.getSQLController();
        ManagedConnection mconn = storeMgr.getConnectionManager().getConnection(ec);
        try {
            PreparedStatement ps = sqlControl.getStatementForUpdate(mconn, insertStmt, batch, hasIdentityColumn && storeMgr.getDatastoreAdapter().supportsOption(DatastoreAdapter.GET_GENERATED_KEYS_STATEMENT));
            try {
                StatementClassMapping mappingDefinition = new StatementClassMapping();
                StatementMappingIndex[] idxs = stmtMappings;
                for (int i = 0; i < idxs.length; i++) {
                    if (idxs[i] != null) {
                        mappingDefinition.addMappingForMember(i, idxs[i]);
                    }
                }
                // Provide the primary key field(s)
                if (table.getIdentityType() == IdentityType.DATASTORE) {
                    if (!table.isObjectIdDatastoreAttributed() || !table.isBaseDatastoreClass()) {
                        int[] paramNumber = { IDPARAMNUMBER };
                        table.getSurrogateMapping(SurrogateColumnType.DATASTORE_ID, false).setObject(ec, ps, paramNumber, op.getInternalObjectId());
                    }
                } else if (table.getIdentityType() == IdentityType.APPLICATION) {
                    op.provideFields(pkFieldNumbers, new ParameterSetter(op, ps, mappingDefinition));
                }
                // This provides "persistence-by-reachability" for these fields
                if (insertFieldNumbers.length > 0) {
                    // TODO Support surrogate current-user, create-timestamp
                    int numberOfFieldsToProvide = 0;
                    for (int i = 0; i < insertFieldNumbers.length; i++) {
                        if (insertFieldNumbers[i] < op.getClassMetaData().getMemberCount()) {
                            AbstractMemberMetaData mmd = op.getClassMetaData().getMetaDataForManagedMemberAtAbsolutePosition(insertFieldNumbers[i]);
                            if (mmd.isCreateTimestamp()) {
                                // Set create timestamp to time for the start of this transaction
                                op.replaceField(insertFieldNumbers[i], new Timestamp(ec.getTransaction().getIsActive() ? ec.getTransaction().getBeginTime() : System.currentTimeMillis()));
                            } else if (mmd.isCreateUser()) {
                                // Set create user to current user
                                op.replaceField(insertFieldNumbers[i], ec.getNucleusContext().getCurrentUser(ec));
                            }
                            numberOfFieldsToProvide++;
                        }
                    }
                    int j = 0;
                    int[] fieldNums = new int[numberOfFieldsToProvide];
                    for (int i = 0; i < insertFieldNumbers.length; i++) {
                        if (insertFieldNumbers[i] < op.getClassMetaData().getMemberCount()) {
                            fieldNums[j++] = insertFieldNumbers[i];
                        }
                    }
                    op.provideFields(fieldNums, new ParameterSetter(op, ps, mappingDefinition));
                }
                JavaTypeMapping versionMapping = table.getSurrogateMapping(SurrogateColumnType.VERSION, false);
                if (versionMapping != null) {
                    // Surrogate version - set the new version for the object
                    Object currentVersion = op.getVersion();
                    Object nextOptimisticVersion = ec.getLockManager().getNextVersion(vermd, currentVersion);
                    for (int k = 0; k < versionStmtMapping.getNumberOfParameterOccurrences(); k++) {
                        versionMapping.setObject(ec, ps, versionStmtMapping.getParameterPositionsForOccurrence(k), nextOptimisticVersion);
                    }
                    op.setTransactionalVersion(nextOptimisticVersion);
                } else if (vermd != null && vermd.getFieldName() != null) {
                    // Version field - set the new version for the object
                    Object currentVersion = op.getVersion();
                    Object nextOptimisticVersion = ec.getLockManager().getNextVersion(vermd, currentVersion);
                    op.setTransactionalVersion(nextOptimisticVersion);
                }
                if (multitenancyStmtMapping != null) {
                    // Multitenancy mapping
                    table.getSurrogateMapping(SurrogateColumnType.MULTITENANCY, false).setObject(ec, ps, multitenancyStmtMapping.getParameterPositionsForOccurrence(0), ec.getNucleusContext().getMultiTenancyId(ec, op.getClassMetaData()));
                }
                if (softDeleteStmtMapping != null) {
                    // Soft-Delete mapping
                    table.getSurrogateMapping(SurrogateColumnType.SOFTDELETE, false).setObject(ec, ps, softDeleteStmtMapping.getParameterPositionsForOccurrence(0), Boolean.FALSE);
                }
                JavaTypeMapping discrimMapping = table.getSurrogateMapping(SurrogateColumnType.DISCRIMINATOR, false);
                if (discrimMapping != null) {
                    // Discriminator mapping
                    Object discVal = op.getClassMetaData().getDiscriminatorValue();
                    for (int k = 0; k < discriminatorStmtMapping.getNumberOfParameterOccurrences(); k++) {
                        discrimMapping.setObject(ec, ps, discriminatorStmtMapping.getParameterPositionsForOccurrence(k), discVal);
                    }
                }
                // External FK columns (optional)
                if (externalFKStmtMappings != null) {
                    for (int i = 0; i < externalFKStmtMappings.length; i++) {
                        Object fkValue = op.getAssociatedValue(externalFKStmtMappings[i].getMapping());
                        if (fkValue != null) {
                            // Need to provide the owner field number so PCMapping can work out if it is inserted yet
                            AbstractMemberMetaData ownerFmd = table.getMetaDataForExternalMapping(externalFKStmtMappings[i].getMapping(), MappingType.EXTERNAL_FK);
                            for (int k = 0; k < externalFKStmtMappings[i].getNumberOfParameterOccurrences(); k++) {
                                externalFKStmtMappings[i].getMapping().setObject(ec, ps, externalFKStmtMappings[i].getParameterPositionsForOccurrence(k), fkValue, null, ownerFmd.getAbsoluteFieldNumber());
                            }
                        } else {
                            // We're inserting a null so don't need the owner field
                            for (int k = 0; k < externalFKStmtMappings[i].getNumberOfParameterOccurrences(); k++) {
                                externalFKStmtMappings[i].getMapping().setObject(ec, ps, externalFKStmtMappings[i].getParameterPositionsForOccurrence(k), null);
                            }
                        }
                    }
                }
                // External FK discriminator columns (optional)
                if (externalFKDiscrimStmtMappings != null) {
                    for (int i = 0; i < externalFKDiscrimStmtMappings.length; i++) {
                        Object discrimValue = op.getAssociatedValue(externalFKDiscrimStmtMappings[i].getMapping());
                        for (int k = 0; k < externalFKDiscrimStmtMappings[i].getNumberOfParameterOccurrences(); k++) {
                            externalFKDiscrimStmtMappings[i].getMapping().setObject(ec, ps, externalFKDiscrimStmtMappings[i].getParameterPositionsForOccurrence(k), discrimValue);
                        }
                    }
                }
                // External order columns (optional)
                if (externalOrderStmtMappings != null) {
                    for (int i = 0; i < externalOrderStmtMappings.length; i++) {
                        Object orderValue = op.getAssociatedValue(externalOrderStmtMappings[i].getMapping());
                        if (orderValue == null) {
                            // No order value so use -1
                            orderValue = Integer.valueOf(-1);
                        }
                        for (int k = 0; k < externalOrderStmtMappings[i].getNumberOfParameterOccurrences(); k++) {
                            externalOrderStmtMappings[i].getMapping().setObject(ec, ps, externalOrderStmtMappings[i].getParameterPositionsForOccurrence(k), orderValue);
                        }
                    }
                }
                sqlControl.executeStatementUpdate(ec, mconn, insertStmt, ps, !batch);
                if (hasIdentityColumn) {
                    // Identity was set in the datastore using auto-increment/identity/serial etc
                    Object newId = getInsertedDatastoreIdentity(ec, sqlControl, op, mconn, ps);
                    if (NucleusLogger.DATASTORE_PERSIST.isDebugEnabled()) {
                        NucleusLogger.DATASTORE_PERSIST.debug(Localiser.msg("052206", op.getObjectAsPrintable(), newId));
                    }
                    op.setPostStoreNewObjectId(newId);
                }
                // Execute any mapping actions on the insert of the fields (e.g Oracle CLOBs/BLOBs)
                for (int i = 0; i < callbacks.length; ++i) {
                    if (NucleusLogger.PERSISTENCE.isDebugEnabled()) {
                        NucleusLogger.PERSISTENCE.debug(Localiser.msg("052222", op.getObjectAsPrintable(), ((JavaTypeMapping) callbacks[i]).getMemberMetaData().getFullFieldName()));
                    }
                    callbacks[i].insertPostProcessing(op);
                }
                // Update the insert status for this table via the StoreManager
                storeMgr.setObjectIsInsertedToLevel(op, table);
                // (if we did it the other way around we would get a NotYetFlushedException thrown above).
                for (int i = 0; i < relationFieldNumbers.length; i++) {
                    Object value = op.provideField(relationFieldNumbers[i]);
                    if (value != null && ec.getApiAdapter().isDetached(value)) {
                        Object valueAttached = ec.persistObjectInternal(value, null, -1, ObjectProvider.PC);
                        op.replaceField(relationFieldNumbers[i], valueAttached);
                    }
                }
                // Perform reachability on all fields that have no datastore column (1-1 bi non-owner, N-1 bi join)
                if (reachableFieldNumbers.length > 0) {
                    int numberOfReachableFields = 0;
                    for (int i = 0; i < reachableFieldNumbers.length; i++) {
                        if (reachableFieldNumbers[i] < op.getClassMetaData().getMemberCount()) {
                            numberOfReachableFields++;
                        }
                    }
                    int[] fieldNums = new int[numberOfReachableFields];
                    int j = 0;
                    for (int i = 0; i < reachableFieldNumbers.length; i++) {
                        if (reachableFieldNumbers[i] < op.getClassMetaData().getMemberCount()) {
                            fieldNums[j++] = reachableFieldNumbers[i];
                        }
                    }
                    mappingDefinition = new StatementClassMapping();
                    idxs = retrievedStmtMappings;
                    for (int i = 0; i < idxs.length; i++) {
                        if (idxs[i] != null) {
                            mappingDefinition.addMappingForMember(i, idxs[i]);
                        }
                    }
                    NucleusLogger.PERSISTENCE.debug("Performing reachability on fields " + StringUtils.intArrayToString(fieldNums));
                    op.provideFields(fieldNums, new ParameterSetter(op, ps, mappingDefinition));
                }
            } finally {
                sqlControl.closeStatement(mconn, ps);
            }
        } finally {
            mconn.release();
        }
    } catch (SQLException e) {
        String msg = Localiser.msg("052208", op.getObjectAsPrintable(), insertStmt, 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()]));
    }
    // (things like inserting any association parent-child).
    for (int i = 0; i < callbacks.length; ++i) {
        try {
            if (NucleusLogger.PERSISTENCE.isDebugEnabled()) {
                NucleusLogger.PERSISTENCE.debug(Localiser.msg("052209", op.getObjectAsPrintable(), ((JavaTypeMapping) callbacks[i]).getMemberMetaData().getFullFieldName()));
            }
            callbacks[i].postInsert(op);
        } catch (NotYetFlushedException e) {
            op.updateFieldAfterInsert(e.getPersistable(), ((JavaTypeMapping) callbacks[i]).getMemberMetaData().getAbsoluteFieldNumber());
        }
    }
}
Also used : VersionMetaData(org.datanucleus.metadata.VersionMetaData) 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) Timestamp(java.sql.Timestamp) AbstractClassMetaData(org.datanucleus.metadata.AbstractClassMetaData) SQLController(org.datanucleus.store.rdbms.SQLController) NucleusDataStoreException(org.datanucleus.exceptions.NucleusDataStoreException) ManagedConnection(org.datanucleus.store.connection.ManagedConnection) ArrayList(java.util.ArrayList) List(java.util.List) PreparedStatement(java.sql.PreparedStatement) NotYetFlushedException(org.datanucleus.exceptions.NotYetFlushedException) RDBMSStoreManager(org.datanucleus.store.rdbms.RDBMSStoreManager) StatementClassMapping(org.datanucleus.store.rdbms.query.StatementClassMapping) ExecutionContext(org.datanucleus.ExecutionContext) AbstractMemberMetaData(org.datanucleus.metadata.AbstractMemberMetaData)

Example 3 with NotYetFlushedException

use of org.datanucleus.exceptions.NotYetFlushedException 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 4 with NotYetFlushedException

use of org.datanucleus.exceptions.NotYetFlushedException 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 5 with NotYetFlushedException

use of org.datanucleus.exceptions.NotYetFlushedException in project datanucleus-rdbms by datanucleus.

the class JoinSetStore method doInternalAdd.

protected int[] doInternalAdd(ObjectProvider op, E element, ManagedConnection conn, boolean batched, int orderId, boolean executeNow) throws MappedDatastoreException {
    // Check for dynamic schema updates prior to addition
    if (storeMgr.getBooleanObjectProperty(RDBMSPropertyNames.PROPERTY_RDBMS_DYNAMIC_SCHEMA_UPDATES).booleanValue()) {
        DynamicSchemaFieldManager dynamicSchemaFM = new DynamicSchemaFieldManager(storeMgr, op);
        Collection coll = new HashSet();
        coll.add(element);
        dynamicSchemaFM.storeObjectField(ownerMemberMetaData.getAbsoluteFieldNumber(), coll);
        if (dynamicSchemaFM.hasPerformedSchemaUpdates()) {
            invalidateAddStmt();
        }
    }
    String addStmt = getAddStmtForJoinTable();
    boolean notYetFlushedError = false;
    ExecutionContext ec = op.getExecutionContext();
    SQLController sqlControl = storeMgr.getSQLController();
    try {
        PreparedStatement ps = sqlControl.getStatementForUpdate(conn, addStmt, batched);
        try {
            // Insert the join table row
            int jdbcPosition = 1;
            jdbcPosition = BackingStoreHelper.populateOwnerInStatement(op, ec, ps, jdbcPosition, this);
            jdbcPosition = BackingStoreHelper.populateElementInStatement(ec, ps, element, jdbcPosition, elementMapping);
            if (orderMapping != null) {
                jdbcPosition = BackingStoreHelper.populateOrderInStatement(ec, ps, orderId, jdbcPosition, orderMapping);
            }
            if (relationDiscriminatorMapping != null) {
                jdbcPosition = BackingStoreHelper.populateRelationDiscriminatorInStatement(ec, ps, jdbcPosition, this);
            }
            return sqlControl.executeStatementUpdate(ec, conn, addStmt, ps, executeNow);
        } catch (NotYetFlushedException nfe) {
            notYetFlushedError = true;
            throw nfe;
        } finally {
            if (notYetFlushedError) {
                sqlControl.abortStatementForConnection(conn, ps);
            } else {
                sqlControl.closeStatement(conn, ps);
            }
        }
    } catch (SQLException e) {
        throw new MappedDatastoreException(addStmt, e);
    }
}
Also used : MappedDatastoreException(org.datanucleus.store.rdbms.exceptions.MappedDatastoreException) ExecutionContext(org.datanucleus.ExecutionContext) DynamicSchemaFieldManager(org.datanucleus.store.rdbms.fieldmanager.DynamicSchemaFieldManager) SQLException(java.sql.SQLException) Collection(java.util.Collection) PreparedStatement(java.sql.PreparedStatement) NotYetFlushedException(org.datanucleus.exceptions.NotYetFlushedException) HashSet(java.util.HashSet) SQLController(org.datanucleus.store.rdbms.SQLController)

Aggregations

NotYetFlushedException (org.datanucleus.exceptions.NotYetFlushedException)8 ExecutionContext (org.datanucleus.ExecutionContext)6 PreparedStatement (java.sql.PreparedStatement)4 SQLException (java.sql.SQLException)4 AbstractMemberMetaData (org.datanucleus.metadata.AbstractMemberMetaData)4 SQLController (org.datanucleus.store.rdbms.SQLController)4 ApiAdapter (org.datanucleus.api.ApiAdapter)3 NucleusUserException (org.datanucleus.exceptions.NucleusUserException)3 RelationType (org.datanucleus.metadata.RelationType)3 StatementMappingIndex (org.datanucleus.store.rdbms.query.StatementMappingIndex)3 Timestamp (java.sql.Timestamp)2 ArrayList (java.util.ArrayList)2 List (java.util.List)2 ClassLoaderResolver (org.datanucleus.ClassLoaderResolver)2 NucleusDataStoreException (org.datanucleus.exceptions.NucleusDataStoreException)2 NucleusException (org.datanucleus.exceptions.NucleusException)2 AbstractClassMetaData (org.datanucleus.metadata.AbstractClassMetaData)2 ObjectProvider (org.datanucleus.state.ObjectProvider)2 ManagedConnection (org.datanucleus.store.connection.ManagedConnection)2 FieldManager (org.datanucleus.store.fieldmanager.FieldManager)2