Search in sources :

Example 1 with LockMode

use of org.datanucleus.state.LockMode in project datanucleus-rdbms by datanucleus.

the class FetchRequest method execute.

/* (non-Javadoc)
     * @see org.datanucleus.store.rdbms.request.Request#execute(org.datanucleus.state.ObjectProvider)
     */
public void execute(ObjectProvider op) {
    if (fieldsToFetch != null && NucleusLogger.PERSISTENCE.isDebugEnabled()) {
        // Debug information about what we are retrieving
        NucleusLogger.PERSISTENCE.debug(Localiser.msg("052218", op.getObjectAsPrintable(), fieldsToFetch, table));
    }
    if (((fetchingSurrogateVersion || versionFieldName != null) && numberOfFieldsToFetch == 0) && op.isVersionLoaded()) {
    // Fetching only the version and it is already loaded, so do nothing
    } else if (statementLocked != null) {
        ExecutionContext ec = op.getExecutionContext();
        RDBMSStoreManager storeMgr = table.getStoreManager();
        boolean locked = ec.getSerializeReadForClass(op.getClassMetaData().getFullClassName());
        LockMode lockType = ec.getLockManager().getLockMode(op.getInternalObjectId());
        if (lockType != LockMode.LOCK_NONE) {
            if (lockType == LockMode.LOCK_PESSIMISTIC_READ || lockType == LockMode.LOCK_PESSIMISTIC_WRITE) {
                // Override with pessimistic lock
                locked = true;
            }
        }
        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 = op.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), op.getInternalObjectId());
                        }
                    } else if (cmd.getIdentityType() == IdentityType.APPLICATION) {
                        op.provideFields(cmd.getPKMemberPositions(), new ParameterSetter(op, ps, mappingDef));
                    }
                    JavaTypeMapping multitenancyMapping = table.getSurrogateMapping(SurrogateColumnType.MULTITENANCY, false);
                    if (multitenancyMapping != null) {
                        // Provide the tenant id to the JDBC statement
                        StatementMappingIndex multitenancyIdx = mappingDef.getMappingForMemberPosition(SurrogateColumnType.MULTITENANCY.getFieldNumber());
                        String tenantId = ec.getNucleusContext().getMultiTenancyId(ec, cmd);
                        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()) {
                            if (NucleusLogger.DATASTORE_RETRIEVE.isInfoEnabled()) {
                                NucleusLogger.DATASTORE_RETRIEVE.info(Localiser.msg("050018", op.getInternalObjectId()));
                            }
                            throw new NucleusObjectNotFoundException("No such database row", op.getInternalObjectId());
                        }
                        // Copy the results into the object
                        ResultSetGetter rsGetter = new ResultSetGetter(ec, rs, mappingDef, op.getClassMetaData());
                        rsGetter.setObjectProvider(op);
                        op.replaceFields(memberNumbersToFetch, rsGetter);
                        if (op.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 - now populated in the field in the object from the results
                                datastoreVersion = op.provideField(cmd.getAbsolutePositionOfMember(versionFieldName));
                            }
                            op.setVersion(datastoreVersion);
                        }
                    } finally {
                        rs.close();
                    }
                } finally {
                    sqlControl.closeStatement(mconn, ps);
                }
            } finally {
                mconn.release();
            }
        } catch (SQLException sqle) {
            String msg = Localiser.msg("052219", op.getObjectAsPrintable(), 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
    for (int i = 0; i < callbacks.length; ++i) {
        callbacks[i].postFetch(op);
    }
}
Also used : JavaTypeMapping(org.datanucleus.store.rdbms.mapping.java.JavaTypeMapping) SQLException(java.sql.SQLException) 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) ExecutionContext(org.datanucleus.ExecutionContext) ResultSet(java.sql.ResultSet) ManagedConnection(org.datanucleus.store.connection.ManagedConnection) ArrayList(java.util.ArrayList) List(java.util.List)

Example 2 with LockMode

use of org.datanucleus.state.LockMode in project datanucleus-rdbms by datanucleus.

the class LocateBulkRequest method execute.

/**
 * Method performing the location of the records in the datastore.
 * @param ops ObjectProviders to be located
 * @throws NucleusObjectNotFoundException with nested exceptions for each of missing objects (if any)
 */
public void execute(ObjectProvider[] ops) {
    if (ops == null || ops.length == 0) {
        return;
    }
    if (NucleusLogger.PERSISTENCE.isDebugEnabled()) {
        // Debug information about what we are retrieving
        StringBuilder str = new StringBuilder();
        for (int i = 0; i < ops.length; i++) {
            if (i > 0) {
                str.append(", ");
            }
            str.append(ops[i].getInternalObjectId());
        }
        NucleusLogger.PERSISTENCE.debug(Localiser.msg("052223", str.toString(), table));
    }
    ExecutionContext ec = ops[0].getExecutionContext();
    RDBMSStoreManager storeMgr = table.getStoreManager();
    AbstractClassMetaData cmd = ops[0].getClassMetaData();
    boolean locked = ec.getSerializeReadForClass(cmd.getFullClassName());
    LockMode lockType = ec.getLockManager().getLockMode(ops[0].getInternalObjectId());
    if (lockType != LockMode.LOCK_NONE) {
        if (lockType == LockMode.LOCK_PESSIMISTIC_READ || lockType == LockMode.LOCK_PESSIMISTIC_WRITE) {
            // Override with pessimistic lock
            locked = true;
        }
    }
    String statement = getStatement(table, ops, locked);
    try {
        ManagedConnection mconn = storeMgr.getConnectionManager().getConnection(ec);
        SQLController sqlControl = storeMgr.getSQLController();
        try {
            PreparedStatement ps = sqlControl.getStatementForQuery(mconn, statement);
            try {
                // Provide the primary key field(s)
                for (int i = 0; i < ops.length; i++) {
                    if (cmd.getIdentityType() == IdentityType.DATASTORE) {
                        StatementMappingIndex datastoreIdx = mappingDefinitions[i].getMappingForMemberPosition(SurrogateColumnType.DATASTORE_ID.getFieldNumber());
                        for (int j = 0; j < datastoreIdx.getNumberOfParameterOccurrences(); j++) {
                            table.getSurrogateMapping(SurrogateColumnType.DATASTORE_ID, false).setObject(ec, ps, datastoreIdx.getParameterPositionsForOccurrence(j), ops[i].getInternalObjectId());
                        }
                    } else if (cmd.getIdentityType() == IdentityType.APPLICATION) {
                        ops[i].provideFields(cmd.getPKMemberPositions(), new ParameterSetter(ops[i], ps, mappingDefinitions[i]));
                    }
                }
                // Execute the statement
                ResultSet rs = sqlControl.executeStatementQuery(ec, mconn, statement, ps);
                try {
                    ObjectProvider[] missingOps = processResults(rs, ops);
                    if (missingOps != null && missingOps.length > 0) {
                        NucleusObjectNotFoundException[] nfes = new NucleusObjectNotFoundException[missingOps.length];
                        for (int i = 0; i < nfes.length; i++) {
                            nfes[i] = new NucleusObjectNotFoundException("Object not found", missingOps[i].getInternalObjectId());
                        }
                        throw new NucleusObjectNotFoundException("Some objects were not found. Look at nested exceptions for details", nfes);
                    }
                } finally {
                    rs.close();
                }
            } finally {
                sqlControl.closeStatement(mconn, ps);
            }
        } finally {
            mconn.release();
        }
    } catch (SQLException sqle) {
        String msg = Localiser.msg("052220", ops[0].getObjectAsPrintable(), 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()]));
    }
}
Also used : SQLException(java.sql.SQLException) 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) SQLController(org.datanucleus.store.rdbms.SQLController) NucleusDataStoreException(org.datanucleus.exceptions.NucleusDataStoreException) ExecutionContext(org.datanucleus.ExecutionContext) ResultSet(java.sql.ResultSet) ManagedConnection(org.datanucleus.store.connection.ManagedConnection) ObjectProvider(org.datanucleus.state.ObjectProvider) ArrayList(java.util.ArrayList) List(java.util.List)

Example 3 with LockMode

use of org.datanucleus.state.LockMode in project datanucleus-rdbms by datanucleus.

the class LocateRequest method execute.

/**
 * Method performing the retrieval of the record from the datastore.
 * Takes the constructed retrieval query and populates with the specific record information.
 * @param op ObjectProvider for the record to be retrieved
 */
public void execute(ObjectProvider op) {
    if (statementLocked != null) {
        ExecutionContext ec = op.getExecutionContext();
        RDBMSStoreManager storeMgr = table.getStoreManager();
        boolean locked = ec.getSerializeReadForClass(op.getClassMetaData().getFullClassName());
        LockMode lockType = ec.getLockManager().getLockMode(op.getInternalObjectId());
        if (lockType != LockMode.LOCK_NONE) {
            if (lockType == LockMode.LOCK_PESSIMISTIC_READ || lockType == LockMode.LOCK_PESSIMISTIC_WRITE) {
                // Override with pessimistic lock
                locked = true;
            }
        }
        String statement = (locked ? statementLocked : statementUnlocked);
        try {
            ManagedConnection mconn = storeMgr.getConnectionManager().getConnection(ec);
            SQLController sqlControl = storeMgr.getSQLController();
            try {
                PreparedStatement ps = sqlControl.getStatementForQuery(mconn, statement);
                AbstractClassMetaData cmd = op.getClassMetaData();
                try {
                    // Provide the primary key field(s)
                    if (cmd.getIdentityType() == IdentityType.DATASTORE) {
                        StatementMappingIndex datastoreIdx = mappingDefinition.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), op.getInternalObjectId());
                        }
                    } else if (cmd.getIdentityType() == IdentityType.APPLICATION) {
                        op.provideFields(cmd.getPKMemberPositions(), new ParameterSetter(op, ps, mappingDefinition));
                    }
                    JavaTypeMapping multitenancyMapping = table.getSurrogateMapping(SurrogateColumnType.MULTITENANCY, false);
                    if (multitenancyMapping != null) {
                        // Set MultiTenancy parameter in statement
                        StatementMappingIndex multitenancyIdx = mappingDefinition.getMappingForMemberPosition(SurrogateColumnType.MULTITENANCY.getFieldNumber());
                        String tenantId = ec.getNucleusContext().getMultiTenancyId(ec, cmd);
                        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 {
                        if (!rs.next()) {
                            NucleusLogger.DATASTORE_RETRIEVE.info(Localiser.msg("050018", op.getInternalObjectId()));
                            throw new NucleusObjectNotFoundException("No such database row", op.getInternalObjectId());
                        }
                    } finally {
                        rs.close();
                    }
                } finally {
                    sqlControl.closeStatement(mconn, ps);
                }
            } finally {
                mconn.release();
            }
        } catch (SQLException sqle) {
            String msg = Localiser.msg("052220", op.getObjectAsPrintable(), 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()]));
        }
    }
}
Also used : JavaTypeMapping(org.datanucleus.store.rdbms.mapping.java.JavaTypeMapping) SQLException(java.sql.SQLException) 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) SQLController(org.datanucleus.store.rdbms.SQLController) NucleusDataStoreException(org.datanucleus.exceptions.NucleusDataStoreException) ExecutionContext(org.datanucleus.ExecutionContext) ResultSet(java.sql.ResultSet) ManagedConnection(org.datanucleus.store.connection.ManagedConnection) ArrayList(java.util.ArrayList) List(java.util.List)

Example 4 with LockMode

use of org.datanucleus.state.LockMode in project datanucleus-core by datanucleus.

the class ExecutionContextImpl method preCommit.

/**
 * Method to perform any pre-commit checks.
 */
public void preCommit() {
    if (cache != null && !cache.isEmpty()) {
        // Check for objects that are managed but not dirty, yet require a version update
        Collection<ObjectProvider> cachedOPs = new HashSet<>(cache.values());
        for (ObjectProvider cachedOP : cachedOPs) {
            LockMode lockMode = getLockManager().getLockMode(cachedOP);
            if (cachedOP != null && cachedOP.isFlushedToDatastore() && cachedOP.getClassMetaData().isVersioned() && (lockMode == LockMode.LOCK_OPTIMISTIC_WRITE || lockMode == LockMode.LOCK_PESSIMISTIC_WRITE)) {
                // Not dirty, but locking requires a version update, so force it
                VersionMetaData vermd = cachedOP.getClassMetaData().getVersionMetaDataForClass();
                if (vermd != null) {
                    if (vermd.getFieldName() != null) {
                        cachedOP.makeDirty((Persistable) cachedOP.getObject(), vermd.getFieldName());
                        dirtyOPs.add(cachedOP);
                    } else {
                        // TODO Cater for surrogate version
                        NucleusLogger.PERSISTENCE.warn("We do not support forced version update with surrogate version columns : " + cachedOP);
                    }
                }
            } else if (cachedOP == null) {
                NucleusLogger.CACHE.error(">> EC.preCommit L1Cache op IS NULL!");
            }
        }
    }
    // Make sure all is flushed before we start
    flush();
    if (pbrAtCommitHandler != null) {
        // Persistence-by-reachability at commit
        try {
            pbrAtCommitHandler.execute();
        } catch (Throwable t) {
            NucleusLogger.PERSISTENCE.error(t);
            if (t instanceof NucleusException) {
                throw (NucleusException) t;
            }
            throw new NucleusException("Unexpected error during precommit", t);
        }
    }
    if (l2CacheEnabled) {
        // L2 caching of enlisted objects
        performLevel2CacheUpdateAtCommit();
    }
    if (properties.getFrequentProperties().getDetachAllOnCommit()) {
        // "detach-on-commit"
        performDetachAllOnTxnEndPreparation();
    }
}
Also used : VersionMetaData(org.datanucleus.metadata.VersionMetaData) ObjectProvider(org.datanucleus.state.ObjectProvider) LockMode(org.datanucleus.state.LockMode) NucleusException(org.datanucleus.exceptions.NucleusException) HashSet(java.util.HashSet)

Aggregations

LockMode (org.datanucleus.state.LockMode)4 PreparedStatement (java.sql.PreparedStatement)3 ResultSet (java.sql.ResultSet)3 SQLException (java.sql.SQLException)3 ArrayList (java.util.ArrayList)3 List (java.util.List)3 ExecutionContext (org.datanucleus.ExecutionContext)3 NucleusDataStoreException (org.datanucleus.exceptions.NucleusDataStoreException)3 NucleusObjectNotFoundException (org.datanucleus.exceptions.NucleusObjectNotFoundException)3 AbstractClassMetaData (org.datanucleus.metadata.AbstractClassMetaData)3 ManagedConnection (org.datanucleus.store.connection.ManagedConnection)3 RDBMSStoreManager (org.datanucleus.store.rdbms.RDBMSStoreManager)3 SQLController (org.datanucleus.store.rdbms.SQLController)3 ParameterSetter (org.datanucleus.store.rdbms.fieldmanager.ParameterSetter)3 StatementMappingIndex (org.datanucleus.store.rdbms.query.StatementMappingIndex)3 ObjectProvider (org.datanucleus.state.ObjectProvider)2 JavaTypeMapping (org.datanucleus.store.rdbms.mapping.java.JavaTypeMapping)2 HashSet (java.util.HashSet)1 NucleusException (org.datanucleus.exceptions.NucleusException)1 VersionMetaData (org.datanucleus.metadata.VersionMetaData)1