Search in sources :

Example 51 with StatementMappingIndex

use of org.datanucleus.store.rdbms.query.StatementMappingIndex in project datanucleus-rdbms by datanucleus.

the class BackingStoreHelper method populateEmbeddedKeyFieldsInStatement.

/**
 * Convenience method to populate the passed PreparedStatement with the field values from
 * the embedded map key starting at the specified jdbc position.
 * @param sm StateManager of the owning container
 * @param key The embedded key
 * @param ps The PreparedStatement
 * @param jdbcPosition JDBC position in the statement to start at
 * @param joinTable The Join table where the values are embedded
 * @param mapStore the map store
 * @return The next JDBC position
 */
public static int populateEmbeddedKeyFieldsInStatement(DNStateManager sm, Object key, PreparedStatement ps, int jdbcPosition, JoinTable joinTable, AbstractMapStore mapStore) {
    AbstractClassMetaData kmd = mapStore.getKeyClassMetaData();
    EmbeddedKeyPCMapping embeddedMapping = (EmbeddedKeyPCMapping) mapStore.getKeyMapping();
    StatementClassMapping mappingDefinition = new StatementClassMapping();
    int[] elementFieldNumbers = new int[embeddedMapping.getNumberOfJavaTypeMappings()];
    for (int i = 0; i < embeddedMapping.getNumberOfJavaTypeMappings(); i++) {
        JavaTypeMapping fieldMapping = embeddedMapping.getJavaTypeMapping(i);
        int absFieldNum = kmd.getAbsolutePositionOfMember(fieldMapping.getMemberMetaData().getName());
        elementFieldNumbers[i] = absFieldNum;
        StatementMappingIndex stmtMapping = new StatementMappingIndex(fieldMapping);
        int[] jdbcParamPositions = new int[fieldMapping.getNumberOfColumnMappings()];
        for (int j = 0; j < fieldMapping.getNumberOfColumnMappings(); j++) {
            jdbcParamPositions[j] = jdbcPosition++;
        }
        stmtMapping.addParameterOccurrence(jdbcParamPositions);
        mappingDefinition.addMappingForMember(absFieldNum, stmtMapping);
    }
    DNStateManager elementSM = mapStore.getStateManagerForEmbeddedPCObject(sm, key, joinTable.getOwnerMemberMetaData(), PersistableObjectType.EMBEDDED_MAP_KEY_PC);
    elementSM.provideFields(elementFieldNumbers, new ParameterSetter(elementSM, ps, mappingDefinition));
    return jdbcPosition;
}
Also used : JavaTypeMapping(org.datanucleus.store.rdbms.mapping.java.JavaTypeMapping) DNStateManager(org.datanucleus.state.DNStateManager) StatementMappingIndex(org.datanucleus.store.rdbms.query.StatementMappingIndex) ParameterSetter(org.datanucleus.store.rdbms.fieldmanager.ParameterSetter) AbstractClassMetaData(org.datanucleus.metadata.AbstractClassMetaData) EmbeddedKeyPCMapping(org.datanucleus.store.rdbms.mapping.java.EmbeddedKeyPCMapping) StatementClassMapping(org.datanucleus.store.rdbms.query.StatementClassMapping)

Example 52 with StatementMappingIndex

use of org.datanucleus.store.rdbms.query.StatementMappingIndex in project datanucleus-rdbms by datanucleus.

the class BackingStoreHelper method populateEmbeddedValueFieldsInStatement.

/**
 * Convenience method to populate the passed PreparedStatement with the field values from
 * the embedded map value starting at the specified jdbc position.
 * @param sm StateManager of the owning container
 * @param value The embedded value
 * @param ps The PreparedStatement
 * @param jdbcPosition JDBC position in the statement to start at
 * @param joinTable The Join table where the values are embedded
 * @param mapStore The map store
 * @return The next JDBC position
 */
public static int populateEmbeddedValueFieldsInStatement(DNStateManager sm, Object value, PreparedStatement ps, int jdbcPosition, JoinTable joinTable, AbstractMapStore mapStore) {
    AbstractClassMetaData vmd = mapStore.getValueClassMetaData();
    EmbeddedValuePCMapping embeddedMapping = (EmbeddedValuePCMapping) mapStore.getValueMapping();
    StatementClassMapping mappingDefinition = new StatementClassMapping();
    int[] elementFieldNumbers = new int[embeddedMapping.getNumberOfJavaTypeMappings()];
    for (int i = 0; i < embeddedMapping.getNumberOfJavaTypeMappings(); i++) {
        JavaTypeMapping fieldMapping = embeddedMapping.getJavaTypeMapping(i);
        int absFieldNum = vmd.getAbsolutePositionOfMember(fieldMapping.getMemberMetaData().getName());
        elementFieldNumbers[i] = absFieldNum;
        StatementMappingIndex stmtMapping = new StatementMappingIndex(fieldMapping);
        int[] jdbcParamPositions = new int[fieldMapping.getNumberOfColumnMappings()];
        for (int j = 0; j < fieldMapping.getNumberOfColumnMappings(); j++) {
            jdbcParamPositions[j] = jdbcPosition++;
        }
        stmtMapping.addParameterOccurrence(jdbcParamPositions);
        mappingDefinition.addMappingForMember(absFieldNum, stmtMapping);
    }
    DNStateManager elementSM = mapStore.getStateManagerForEmbeddedPCObject(sm, value, joinTable.getOwnerMemberMetaData(), PersistableObjectType.EMBEDDED_MAP_VALUE_PC);
    elementSM.provideFields(elementFieldNumbers, new ParameterSetter(elementSM, ps, mappingDefinition));
    return jdbcPosition;
}
Also used : JavaTypeMapping(org.datanucleus.store.rdbms.mapping.java.JavaTypeMapping) EmbeddedValuePCMapping(org.datanucleus.store.rdbms.mapping.java.EmbeddedValuePCMapping) DNStateManager(org.datanucleus.state.DNStateManager) StatementMappingIndex(org.datanucleus.store.rdbms.query.StatementMappingIndex) ParameterSetter(org.datanucleus.store.rdbms.fieldmanager.ParameterSetter) AbstractClassMetaData(org.datanucleus.metadata.AbstractClassMetaData) StatementClassMapping(org.datanucleus.store.rdbms.query.StatementClassMapping)

Example 53 with StatementMappingIndex

use of org.datanucleus.store.rdbms.query.StatementMappingIndex in project datanucleus-rdbms by datanucleus.

the class FKMapStore method getValue.

/**
 * Method to retrieve a value from the Map given the key.
 * @param ownerSM StateManager for the owner of the map.
 * @param key The key to retrieve the value for.
 * @return The value for this key
 * @throws NoSuchElementException if the key was not found
 */
protected V getValue(DNStateManager ownerSM, Object key) throws NoSuchElementException {
    if (!validateKeyForReading(ownerSM, key)) {
        return null;
    }
    ExecutionContext ec = ownerSM.getExecutionContext();
    if (getStmtLocked == null) {
        synchronized (// Make sure this completes in case another thread needs the same info
        this) {
            // Generate the statement, and statement mapping/parameter information
            SQLStatement sqlStmt = getSQLStatementForGet(ownerSM);
            getStmtUnlocked = sqlStmt.getSQLText().toSQL();
            sqlStmt.addExtension(SQLStatement.EXTENSION_LOCK_FOR_UPDATE, true);
            getStmtLocked = sqlStmt.getSQLText().toSQL();
        }
    }
    Boolean serializeRead = ec.getTransaction().getSerializeRead();
    String stmt = (serializeRead != null && serializeRead ? getStmtLocked : getStmtUnlocked);
    Object value = null;
    try {
        ManagedConnection mconn = storeMgr.getConnectionManager().getConnection(ec);
        SQLController sqlControl = storeMgr.getSQLController();
        try {
            // Create the statement and supply owner/key params
            PreparedStatement ps = sqlControl.getStatementForQuery(mconn, stmt);
            StatementMappingIndex ownerIdx = getMappingParams.getMappingForParameter("owner");
            int numParams = ownerIdx.getNumberOfParameterOccurrences();
            for (int paramInstance = 0; paramInstance < numParams; paramInstance++) {
                ownerIdx.getMapping().setObject(ec, ps, ownerIdx.getParameterPositionsForOccurrence(paramInstance), ownerSM.getObject());
            }
            StatementMappingIndex keyIdx = getMappingParams.getMappingForParameter("key");
            numParams = keyIdx.getNumberOfParameterOccurrences();
            for (int paramInstance = 0; paramInstance < numParams; paramInstance++) {
                keyIdx.getMapping().setObject(ec, ps, keyIdx.getParameterPositionsForOccurrence(paramInstance), key);
            }
            try {
                ResultSet rs = sqlControl.executeStatementQuery(ec, mconn, stmt, ps);
                try {
                    boolean found = rs.next();
                    if (!found) {
                        throw new NoSuchElementException();
                    }
                    if (valuesAreEmbedded || valuesAreSerialised) {
                        // Embedded/serialised into table of key
                        int[] param = new int[valueMapping.getNumberOfColumnMappings()];
                        for (int i = 0; i < param.length; ++i) {
                            param[i] = i + 1;
                        }
                        if (valueMapping instanceof SerialisedPCMapping || valueMapping instanceof SerialisedReferenceMapping || valueMapping instanceof EmbeddedKeyPCMapping) {
                            // Value = Serialised
                            String msg = "You appear to have a map (persistable) value serialised/embedded into the key of the map at " + getOwnerMemberMetaData().getFullFieldName() + " Not supported";
                            NucleusLogger.PERSISTENCE.error(msg);
                            throw new NucleusDataStoreException(msg);
                        }
                        // Value = Non-PC
                        value = valueMapping.getObject(ec, rs, param);
                    } else if (valueMapping instanceof ReferenceMapping) {
                        // Value = Reference (Interface/Object)
                        int[] param = new int[valueMapping.getNumberOfColumnMappings()];
                        for (int i = 0; i < param.length; ++i) {
                            param[i] = i + 1;
                        }
                        value = valueMapping.getObject(ec, rs, param);
                    } else {
                        // Value = PC
                        value = new PersistentClassROF(ec, rs, false, ec.getFetchPlan(), getMappingDef, valueCmd, clr.classForName(valueType)).getObject();
                    }
                    JDBCUtils.logWarnings(rs);
                } finally {
                    rs.close();
                }
            } finally {
                sqlControl.closeStatement(mconn, ps);
            }
        } finally {
            mconn.release();
        }
    } catch (SQLException e) {
        throw new NucleusDataStoreException(Localiser.msg("056014", stmt), e);
    }
    return (V) value;
}
Also used : SerialisedReferenceMapping(org.datanucleus.store.rdbms.mapping.java.SerialisedReferenceMapping) SQLException(java.sql.SQLException) PreparedStatement(java.sql.PreparedStatement) StatementMappingIndex(org.datanucleus.store.rdbms.query.StatementMappingIndex) SQLStatement(org.datanucleus.store.rdbms.sql.SQLStatement) SQLController(org.datanucleus.store.rdbms.SQLController) NucleusDataStoreException(org.datanucleus.exceptions.NucleusDataStoreException) ExecutionContext(org.datanucleus.ExecutionContext) SerialisedReferenceMapping(org.datanucleus.store.rdbms.mapping.java.SerialisedReferenceMapping) ReferenceMapping(org.datanucleus.store.rdbms.mapping.java.ReferenceMapping) PersistentClassROF(org.datanucleus.store.rdbms.query.PersistentClassROF) ResultSet(java.sql.ResultSet) ManagedConnection(org.datanucleus.store.connection.ManagedConnection) SerialisedPCMapping(org.datanucleus.store.rdbms.mapping.java.SerialisedPCMapping) NoSuchElementException(java.util.NoSuchElementException) EmbeddedKeyPCMapping(org.datanucleus.store.rdbms.mapping.java.EmbeddedKeyPCMapping)

Example 54 with StatementMappingIndex

use of org.datanucleus.store.rdbms.query.StatementMappingIndex in project datanucleus-rdbms by datanucleus.

the class UpdateRequest method execute.

/**
 * Method performing the update of the record in the datastore.
 * Takes the constructed update query and populates with the specific record information.
 * @param sm StateManager for the record to be updated
 */
public void execute(DNStateManager sm) {
    // Choose the statement based on whether optimistic or not
    String stmt = null;
    ExecutionContext ec = sm.getExecutionContext();
    boolean optimisticChecks = (versionChecks && ec.getTransaction().getOptimistic());
    stmt = optimisticChecks ? updateStmtOptimistic : updateStmt;
    if (stmt != null) {
        // UpdateTimestamp
        int updateTimestampMemberPos = cmd.getUpdateTimestampMemberPosition();
        if (updateTimestampMemberPos >= 0) {
            AbstractMemberMetaData updateTimestampMmd = cmd.getMetaDataForManagedMemberAtAbsolutePosition(updateTimestampMemberPos);
            if (updateTimestampMmd.getType().isAssignableFrom(java.time.Instant.class)) {
                sm.replaceField(updateTimestampMemberPos, ec.getTransaction().getIsActive() ? java.time.Instant.ofEpochMilli(ec.getTransaction().getBeginTime()) : java.time.Instant.now());
            } else {
                sm.replaceField(updateTimestampMemberPos, ec.getTransaction().getIsActive() ? new Timestamp(ec.getTransaction().getBeginTime()) : new Timestamp(System.currentTimeMillis()));
            }
        // TODO Throw exception if invalid member type
        }
        // UpdateUser
        int updateUserMemberPos = cmd.getUpdateUserMemberPosition();
        if (updateUserMemberPos >= 0) {
            sm.replaceField(updateUserMemberPos, ec.getCurrentUser());
        }
        if (NucleusLogger.PERSISTENCE.isDebugEnabled()) {
            // Debug info about fields being updated
            StringBuilder fieldStr = new StringBuilder();
            if (updateFieldNumbers != null) {
                for (int i = 0; i < updateFieldNumbers.length; i++) {
                    if (fieldStr.length() > 0) {
                        fieldStr.append(",");
                    }
                    fieldStr.append(cmd.getMetaDataForManagedMemberAtAbsolutePosition(updateFieldNumbers[i]).getName());
                }
            }
            if (versionMetaData != null && versionMetaData.getMemberName() == null) {
                if (fieldStr.length() > 0) {
                    fieldStr.append(",");
                }
                fieldStr.append("[VERSION]");
            }
            // Debug information about what we are updating
            NucleusLogger.PERSISTENCE.debug(Localiser.msg("052214", IdentityUtils.getPersistableIdentityForId(sm.getInternalObjectId()), fieldStr.toString(), table));
        }
        RDBMSStoreManager storeMgr = table.getStoreManager();
        boolean batch = false;
        // TODO Set the batch flag based on whether we have no other SQL being invoked in here just our UPDATE
        try {
            ManagedConnection mconn = storeMgr.getConnectionManager().getConnection(ec);
            SQLController sqlControl = storeMgr.getSQLController();
            try {
                // Perform the update
                PreparedStatement ps = sqlControl.getStatementForUpdate(mconn, stmt, batch);
                try {
                    Object currentVersion = sm.getTransactionalVersion();
                    Object nextVersion = null;
                    if (// TODO What if strategy is NONE?
                    versionMetaData != null) {
                        // Set the next version in the object
                        if (versionMetaData.getMemberName() != null) {
                            // Version field
                            AbstractMemberMetaData verfmd = cmd.getMetaDataForMember(table.getVersionMetaData().getMemberName());
                            if (currentVersion instanceof Number) {
                                currentVersion = Long.valueOf(((Number) currentVersion).longValue());
                            }
                            nextVersion = ec.getLockManager().getNextVersion(versionMetaData, currentVersion);
                            if (verfmd.getType() == Integer.class || verfmd.getType() == int.class) {
                                // Cater for Integer-based versions
                                nextVersion = Integer.valueOf(((Number) nextVersion).intValue());
                            } else if (verfmd.getType() == Short.class || verfmd.getType() == short.class) {
                                // Cater for Short-based versions
                                nextVersion = Short.valueOf(((Number) nextVersion).shortValue());
                            }
                            sm.replaceField(verfmd.getAbsoluteFieldNumber(), nextVersion);
                        } else {
                            // Surrogate version column
                            nextVersion = ec.getLockManager().getNextVersion(versionMetaData, currentVersion);
                        }
                        sm.setTransactionalVersion(nextVersion);
                    }
                    if (updateUserStmtMapping != null) {
                        table.getSurrogateMapping(SurrogateColumnType.UPDATE_USER, false).setObject(ec, ps, updateUserStmtMapping.getParameterPositionsForOccurrence(0), ec.getCurrentUser());
                    }
                    if (updateTimestampStmtMapping != null) {
                        table.getSurrogateMapping(SurrogateColumnType.UPDATE_TIMESTAMP, false).setObject(ec, ps, updateTimestampStmtMapping.getParameterPositionsForOccurrence(0), new Timestamp(ec.getTransaction().getIsActive() ? ec.getTransaction().getBeginTime() : System.currentTimeMillis()));
                    }
                    // SELECT clause - set the required fields to be updated
                    if (updateFieldNumbers != null) {
                        StatementClassMapping mappingDefinition = new StatementClassMapping();
                        StatementMappingIndex[] idxs = stmtMappingDefinition.getUpdateFields();
                        for (int i = 0; i < idxs.length; i++) {
                            if (idxs[i] != null) {
                                mappingDefinition.addMappingForMember(i, idxs[i]);
                            }
                        }
                        sm.provideFields(updateFieldNumbers, new ParameterSetter(sm, ps, mappingDefinition));
                    }
                    if (versionMetaData != null && versionMetaData.getMemberName() == null) {
                        // SELECT clause - set the surrogate version column to the new version
                        StatementMappingIndex mapIdx = stmtMappingDefinition.getUpdateVersion();
                        for (int i = 0; i < mapIdx.getNumberOfParameterOccurrences(); i++) {
                            table.getSurrogateMapping(SurrogateColumnType.VERSION, false).setObject(ec, ps, mapIdx.getParameterPositionsForOccurrence(i), nextVersion);
                        }
                    }
                    // WHERE clause - primary key fields
                    if (table.getIdentityType() == IdentityType.DATASTORE) {
                        // a). datastore identity
                        StatementMappingIndex mapIdx = stmtMappingDefinition.getWhereDatastoreId();
                        for (int i = 0; i < mapIdx.getNumberOfParameterOccurrences(); i++) {
                            table.getSurrogateMapping(SurrogateColumnType.DATASTORE_ID, false).setObject(ec, ps, mapIdx.getParameterPositionsForOccurrence(i), sm.getInternalObjectId());
                        }
                    } else {
                        // b). application/nondurable identity
                        StatementClassMapping mappingDefinition = new StatementClassMapping();
                        StatementMappingIndex[] idxs = stmtMappingDefinition.getWhereFields();
                        for (int i = 0; i < idxs.length; i++) {
                            if (idxs[i] != null) {
                                mappingDefinition.addMappingForMember(i, idxs[i]);
                            }
                        }
                        FieldManager fm = null;
                        if (cmd.getIdentityType() == IdentityType.NONDURABLE) {
                            fm = new OldValueParameterSetter(sm, ps, mappingDefinition);
                        } else {
                            fm = new ParameterSetter(sm, ps, mappingDefinition);
                        }
                        sm.provideFields(whereFieldNumbers, fm);
                    }
                    if (optimisticChecks) {
                        if (currentVersion == null) {
                            // Somehow the version is not set on this object (not read in ?) so report the bug
                            String msg = Localiser.msg("052201", sm.getInternalObjectId(), table);
                            NucleusLogger.PERSISTENCE.error(msg);
                            throw new NucleusException(msg);
                        }
                        // WHERE clause - current version discriminator
                        StatementMappingIndex mapIdx = stmtMappingDefinition.getWhereVersion();
                        for (int i = 0; i < mapIdx.getNumberOfParameterOccurrences(); i++) {
                            mapIdx.getMapping().setObject(ec, ps, mapIdx.getParameterPositionsForOccurrence(i), currentVersion);
                        }
                    }
                    int[] rcs = sqlControl.executeStatementUpdate(ec, mconn, stmt, ps, !batch);
                    if (rcs[0] == 0 && optimisticChecks) {
                        // TODO Batching : when we use batching here we need to process these somehow
                        throw new NucleusOptimisticException(Localiser.msg("052203", sm.getObjectAsPrintable(), sm.getInternalObjectId(), "" + currentVersion), sm.getObject());
                    }
                    // Execute any post-set mappings
                    if (postSetMappings != null) {
                        for (JavaTypeMapping m : postSetMappings) {
                            if (NucleusLogger.PERSISTENCE.isDebugEnabled()) {
                                NucleusLogger.PERSISTENCE.debug(Localiser.msg("052222", sm.getObjectAsPrintable(), m.getMemberMetaData().getFullFieldName()));
                            }
                            m.performSetPostProcessing(sm);
                        }
                    }
                } finally {
                    sqlControl.closeStatement(mconn, ps);
                }
            } finally {
                mconn.release();
            }
        } catch (SQLException e) {
            String msg = Localiser.msg("052215", IdentityUtils.getPersistableIdentityForId(sm.getInternalObjectId()), stmt, StringUtils.getStringFromStackTrace(e));
            NucleusLogger.DATASTORE_PERSIST.error(msg);
            List<Exception> exceptions = new ArrayList<>();
            exceptions.add(e);
            while ((e = e.getNextException()) != null) {
                exceptions.add(e);
            }
            throw new NucleusDataStoreException(msg, exceptions.toArray(new Throwable[exceptions.size()]));
        }
    }
    // Execute any mapping actions now that we have done the update
    if (mappingCallbacks != null) {
        for (MappingCallbacks m : mappingCallbacks) {
            try {
                if (NucleusLogger.PERSISTENCE.isDebugEnabled()) {
                    NucleusLogger.PERSISTENCE.debug(Localiser.msg("052216", IdentityUtils.getPersistableIdentityForId(sm.getInternalObjectId()), ((JavaTypeMapping) m).getMemberMetaData().getFullFieldName()));
                }
                m.postUpdate(sm);
            } catch (NotYetFlushedException e) {
                sm.updateFieldAfterInsert(e.getPersistable(), ((JavaTypeMapping) m).getMemberMetaData().getAbsoluteFieldNumber());
            }
        }
    }
}
Also used : FieldManager(org.datanucleus.store.fieldmanager.FieldManager) JavaTypeMapping(org.datanucleus.store.rdbms.mapping.java.JavaTypeMapping) SQLException(java.sql.SQLException) MappingCallbacks(org.datanucleus.store.rdbms.mapping.MappingCallbacks) StatementMappingIndex(org.datanucleus.store.rdbms.query.StatementMappingIndex) ParameterSetter(org.datanucleus.store.rdbms.fieldmanager.ParameterSetter) OldValueParameterSetter(org.datanucleus.store.rdbms.fieldmanager.OldValueParameterSetter) Timestamp(java.sql.Timestamp) 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) NucleusOptimisticException(org.datanucleus.exceptions.NucleusOptimisticException) OldValueParameterSetter(org.datanucleus.store.rdbms.fieldmanager.OldValueParameterSetter) NucleusException(org.datanucleus.exceptions.NucleusException) AbstractMemberMetaData(org.datanucleus.metadata.AbstractMemberMetaData)

Example 55 with StatementMappingIndex

use of org.datanucleus.store.rdbms.query.StatementMappingIndex in project datanucleus-rdbms by datanucleus.

the class FetchRequest method execute.

/* (non-Javadoc)
     * @see org.datanucleus.store.rdbms.request.Request#execute(org.datanucleus.state.DNStateManager)
     */
public void execute(DNStateManager sm) {
    if (fieldsToFetch != null && NucleusLogger.PERSISTENCE.isDebugEnabled()) {
        // Debug information about what we are retrieving
        NucleusLogger.PERSISTENCE.debug(Localiser.msg("052218", IdentityUtils.getPersistableIdentityForId(sm.getInternalObjectId()), fieldsToFetch, table));
    }
    if (((fetchingSurrogateVersion || versionFieldName != null) && numberOfFieldsToFetch == 0) && sm.isVersionLoaded()) {
    // Fetching only the version and it is already loaded, so do nothing
    } else if (statementLocked != null) {
        ExecutionContext ec = sm.getExecutionContext();
        RDBMSStoreManager storeMgr = table.getStoreManager();
        // Override with pessimistic lock where specified
        LockMode lockType = ec.getLockManager().getLockMode(sm.getInternalObjectId());
        boolean locked = (lockType == LockMode.LOCK_PESSIMISTIC_READ || lockType == LockMode.LOCK_PESSIMISTIC_WRITE) ? true : ec.getSerializeReadForClass(sm.getClassMetaData().getFullClassName());
        String statement = (locked ? statementLocked : statementUnlocked);
        StatementClassMapping mappingDef = mappingDefinition;
        /*if ((sm.isDeleting() || sm.isDetaching()) && mappingDefinition.hasChildMappingDefinitions())
            {
                // Don't fetch any children since the object is being deleted
                mappingDef = mappingDefinition.cloneStatementMappingWithoutChildren();
            }*/
        try {
            ManagedConnection mconn = storeMgr.getConnectionManager().getConnection(ec);
            SQLController sqlControl = storeMgr.getSQLController();
            try {
                PreparedStatement ps = sqlControl.getStatementForQuery(mconn, statement);
                AbstractClassMetaData cmd = sm.getClassMetaData();
                try {
                    // Provide the primary key field(s) to the JDBC statement
                    if (cmd.getIdentityType() == IdentityType.DATASTORE) {
                        StatementMappingIndex datastoreIdx = mappingDef.getMappingForMemberPosition(SurrogateColumnType.DATASTORE_ID.getFieldNumber());
                        for (int i = 0; i < datastoreIdx.getNumberOfParameterOccurrences(); i++) {
                            table.getSurrogateMapping(SurrogateColumnType.DATASTORE_ID, false).setObject(ec, ps, datastoreIdx.getParameterPositionsForOccurrence(i), sm.getInternalObjectId());
                        }
                    } else if (cmd.getIdentityType() == IdentityType.APPLICATION) {
                        sm.provideFields(cmd.getPKMemberPositions(), new ParameterSetter(sm, ps, mappingDef));
                    }
                    JavaTypeMapping multitenancyMapping = table.getSurrogateMapping(SurrogateColumnType.MULTITENANCY, false);
                    if (multitenancyMapping != null) {
                        String[] tenantReadIds = storeMgr.getNucleusContext().getTenantReadIds(sm.getExecutionContext());
                        if (tenantReadIds != null && tenantReadIds.length > 0) {
                        // Using IN clause so nothing to do since hardcoded
                        } else {
                            // Set MultiTenancy tenant id in statement
                            StatementMappingIndex multitenancyIdx = mappingDef.getMappingForMemberPosition(SurrogateColumnType.MULTITENANCY.getFieldNumber());
                            String tenantId = ec.getTenantId();
                            for (int i = 0; i < multitenancyIdx.getNumberOfParameterOccurrences(); i++) {
                                multitenancyMapping.setObject(ec, ps, multitenancyIdx.getParameterPositionsForOccurrence(i), tenantId);
                            }
                        }
                    }
                    JavaTypeMapping softDeleteMapping = table.getSurrogateMapping(SurrogateColumnType.SOFTDELETE, false);
                    if (softDeleteMapping != null) {
                        // Set SoftDelete parameter in statement
                        StatementMappingIndex softDeleteIdx = mappingDefinition.getMappingForMemberPosition(SurrogateColumnType.SOFTDELETE.getFieldNumber());
                        for (int i = 0; i < softDeleteIdx.getNumberOfParameterOccurrences(); i++) {
                            softDeleteMapping.setObject(ec, ps, softDeleteIdx.getParameterPositionsForOccurrence(i), Boolean.FALSE);
                        }
                    }
                    // Execute the statement
                    ResultSet rs = sqlControl.executeStatementQuery(ec, mconn, statement, ps);
                    try {
                        // Check for failure to find the object
                        if (!rs.next()) {
                            String msg = Localiser.msg("050018", IdentityUtils.getPersistableIdentityForId(sm.getInternalObjectId()));
                            if (NucleusLogger.DATASTORE_RETRIEVE.isInfoEnabled()) {
                                NucleusLogger.DATASTORE_RETRIEVE.info(msg);
                            }
                            throw new NucleusObjectNotFoundException(msg);
                        }
                        // Copy the results into the object
                        ResultSetGetter rsGetter = new ResultSetGetter(ec, rs, mappingDef, sm.getClassMetaData());
                        rsGetter.setStateManager(sm);
                        // Make sure the version is set first
                        if (sm.getTransactionalVersion() == null) {
                            // Object has no version set so update it from this fetch
                            Object datastoreVersion = null;
                            if (fetchingSurrogateVersion) {
                                // Surrogate version column - get from the result set using the version mapping
                                StatementMappingIndex verIdx = mappingDef.getMappingForMemberPosition(SurrogateColumnType.VERSION.getFieldNumber());
                                datastoreVersion = table.getSurrogateMapping(SurrogateColumnType.VERSION, true).getObject(ec, rs, verIdx.getColumnPositions());
                            } else if (versionFieldName != null) {
                                // Version field - populate it in the object and access it from the field
                                int verAbsFieldNum = cmd.getAbsolutePositionOfMember(versionFieldName);
                                sm.replaceFields(new int[] { verAbsFieldNum }, rsGetter);
                                datastoreVersion = sm.provideField(verAbsFieldNum);
                            }
                            sm.setVersion(datastoreVersion);
                        }
                        // Fetch requested fields
                        sm.replaceFields(memberNumbersToFetch, rsGetter);
                        // Store requested fields
                        if (memberNumbersToStore != null) {
                            for (int i = 0; i < memberNumbersToStore.length; i++) {
                                StatementMappingIndex mapIdx = mappingDefinition.getMappingForMemberPosition(memberNumbersToStore[i]);
                                JavaTypeMapping m = mapIdx.getMapping();
                                if (m instanceof PersistableMapping) {
                                    // FK, so create the identity of the related object
                                    AbstractClassMetaData memberCmd = ((PersistableMapping) m).getClassMetaData();
                                    Object memberId = null;
                                    if (memberCmd.getIdentityType() == IdentityType.DATASTORE) {
                                        memberId = MappingHelper.getDatastoreIdentityForResultSetRow(ec, m, rs, mapIdx.getColumnPositions(), memberCmd);
                                    } else if (memberCmd.getIdentityType() == IdentityType.APPLICATION) {
                                        memberId = MappingHelper.getApplicationIdentityForResultSetRow(ec, m, rs, mapIdx.getColumnPositions(), memberCmd);
                                    } else {
                                        break;
                                    }
                                    if (memberId == null) {
                                        // Just set the member and don't bother saving the value
                                        sm.replaceField(memberNumbersToStore[i], null);
                                    } else {
                                        // Store the "id" value in case the member is ever accessed
                                        sm.storeFieldValue(memberNumbersToStore[i], memberId);
                                    }
                                }
                            }
                        }
                    } finally {
                        rs.close();
                    }
                } finally {
                    sqlControl.closeStatement(mconn, ps);
                }
            } finally {
                mconn.release();
            }
        } catch (SQLException sqle) {
            String msg = Localiser.msg("052219", IdentityUtils.getPersistableIdentityForId(sm.getInternalObjectId()), statement, sqle.getMessage());
            NucleusLogger.DATASTORE_RETRIEVE.warn(msg);
            List exceptions = new ArrayList();
            exceptions.add(sqle);
            while ((sqle = sqle.getNextException()) != null) {
                exceptions.add(sqle);
            }
            throw new NucleusDataStoreException(msg, (Throwable[]) exceptions.toArray(new Throwable[exceptions.size()]));
        }
    }
    // Execute any mapping actions now that we have fetched the fields
    if (mappingCallbacks != null) {
        for (MappingCallbacks m : mappingCallbacks) {
            m.postFetch(sm);
        }
    }
}
Also used : JavaTypeMapping(org.datanucleus.store.rdbms.mapping.java.JavaTypeMapping) SQLException(java.sql.SQLException) MappingCallbacks(org.datanucleus.store.rdbms.mapping.MappingCallbacks) ArrayList(java.util.ArrayList) PreparedStatement(java.sql.PreparedStatement) LockMode(org.datanucleus.state.LockMode) StatementMappingIndex(org.datanucleus.store.rdbms.query.StatementMappingIndex) ParameterSetter(org.datanucleus.store.rdbms.fieldmanager.ParameterSetter) NucleusObjectNotFoundException(org.datanucleus.exceptions.NucleusObjectNotFoundException) AbstractClassMetaData(org.datanucleus.metadata.AbstractClassMetaData) RDBMSStoreManager(org.datanucleus.store.rdbms.RDBMSStoreManager) StatementClassMapping(org.datanucleus.store.rdbms.query.StatementClassMapping) SQLController(org.datanucleus.store.rdbms.SQLController) ResultSetGetter(org.datanucleus.store.rdbms.fieldmanager.ResultSetGetter) NucleusDataStoreException(org.datanucleus.exceptions.NucleusDataStoreException) PersistableMapping(org.datanucleus.store.rdbms.mapping.java.PersistableMapping) ExecutionContext(org.datanucleus.ExecutionContext) ResultSet(java.sql.ResultSet) ManagedConnection(org.datanucleus.store.connection.ManagedConnection) ArrayList(java.util.ArrayList) List(java.util.List)

Aggregations

StatementMappingIndex (org.datanucleus.store.rdbms.query.StatementMappingIndex)66 ExecutionContext (org.datanucleus.ExecutionContext)49 StatementClassMapping (org.datanucleus.store.rdbms.query.StatementClassMapping)44 PreparedStatement (java.sql.PreparedStatement)37 SQLException (java.sql.SQLException)37 NucleusDataStoreException (org.datanucleus.exceptions.NucleusDataStoreException)37 ManagedConnection (org.datanucleus.store.connection.ManagedConnection)37 SQLController (org.datanucleus.store.rdbms.SQLController)37 JavaTypeMapping (org.datanucleus.store.rdbms.mapping.java.JavaTypeMapping)36 ResultSet (java.sql.ResultSet)32 SelectStatement (org.datanucleus.store.rdbms.sql.SelectStatement)28 AbstractMemberMetaData (org.datanucleus.metadata.AbstractMemberMetaData)21 ParameterSetter (org.datanucleus.store.rdbms.fieldmanager.ParameterSetter)21 PersistentClassROF (org.datanucleus.store.rdbms.query.PersistentClassROF)20 RDBMSStoreManager (org.datanucleus.store.rdbms.RDBMSStoreManager)19 ResultObjectFactory (org.datanucleus.store.rdbms.query.ResultObjectFactory)19 AbstractClassMetaData (org.datanucleus.metadata.AbstractClassMetaData)18 DatastoreClass (org.datanucleus.store.rdbms.table.DatastoreClass)18 ClassLoaderResolver (org.datanucleus.ClassLoaderResolver)15 DNStateManager (org.datanucleus.state.DNStateManager)15