Search in sources :

Example 1 with OldValueParameterSetter

use of org.datanucleus.store.rdbms.fieldmanager.OldValueParameterSetter 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 op The ObjectProvider for the record to be updated
 */
public void execute(ObjectProvider op) {
    // Choose the statement based on whether optimistic or not
    String stmt = null;
    ExecutionContext ec = op.getExecutionContext();
    boolean optimisticChecks = (versionMetaData != null && ec.getTransaction().getOptimistic() && versionChecks);
    stmt = optimisticChecks ? updateStmtOptimistic : updateStmt;
    if (stmt != null) {
        // TODO Support surrogate update user/timestamp
        AbstractMemberMetaData[] mmds = cmd.getManagedMembers();
        for (int i = 0; i < mmds.length; i++) {
            if (// TODO Make this accessible from cmd
            mmds[i].isUpdateTimestamp()) {
                op.replaceField(mmds[i].getAbsoluteFieldNumber(), new Timestamp(ec.getTransaction().getIsActive() ? ec.getTransaction().getBeginTime() : System.currentTimeMillis()));
            } else if (// TODO Make this accessible from cmd
            mmds[i].isUpdateUser()) {
                op.replaceField(mmds[i].getAbsoluteFieldNumber(), ec.getNucleusContext().getCurrentUser(ec));
            }
        }
        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.getFieldName() == null) {
                if (fieldStr.length() > 0) {
                    fieldStr.append(",");
                }
                fieldStr.append("[VERSION]");
            }
            // Debug information about what we are updating
            NucleusLogger.PERSISTENCE.debug(Localiser.msg("052214", op.getObjectAsPrintable(), 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 = op.getTransactionalVersion();
                    Object nextVersion = null;
                    if (// TODO What if strategy is NONE?
                    versionMetaData != null) {
                        // Set the next version in the object
                        if (versionMetaData.getFieldName() != null) {
                            // Version field
                            AbstractMemberMetaData verfmd = cmd.getMetaDataForMember(table.getVersionMetaData().getFieldName());
                            if (currentVersion instanceof Number) {
                                // Cater for Integer-based versions
                                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());
                            }
                            op.replaceField(verfmd.getAbsoluteFieldNumber(), nextVersion);
                        } else {
                            // Surrogate version column
                            nextVersion = ec.getLockManager().getNextVersion(versionMetaData, currentVersion);
                        }
                        op.setTransactionalVersion(nextVersion);
                    }
                    // 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]);
                            }
                        }
                        op.provideFields(updateFieldNumbers, new ParameterSetter(op, ps, mappingDefinition));
                    }
                    if (versionMetaData != null && versionMetaData.getFieldName() == 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), op.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(op, ps, mappingDefinition);
                        } else {
                            fm = new ParameterSetter(op, ps, mappingDefinition);
                        }
                        op.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", op.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", op.getObjectAsPrintable(), op.getInternalObjectId(), "" + currentVersion), op.getObject());
                    }
                } finally {
                    sqlControl.closeStatement(mconn, ps);
                }
            } finally {
                mconn.release();
            }
        } catch (SQLException e) {
            String msg = Localiser.msg("052215", op.getObjectAsPrintable(), stmt, StringUtils.getStringFromStackTrace(e));
            NucleusLogger.DATASTORE_PERSIST.error(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()]));
        }
    }
    // Execute any mapping actions now that we have done the update
    for (int i = 0; i < callbacks.length; ++i) {
        try {
            if (NucleusLogger.PERSISTENCE.isDebugEnabled()) {
                NucleusLogger.PERSISTENCE.debug(Localiser.msg("052216", op.getObjectAsPrintable(), ((JavaTypeMapping) callbacks[i]).getMemberMetaData().getFullFieldName()));
            }
            callbacks[i].postUpdate(op);
        } catch (NotYetFlushedException e) {
            op.updateFieldAfterInsert(e.getPersistable(), ((JavaTypeMapping) callbacks[i]).getMemberMetaData().getAbsoluteFieldNumber());
        }
    }
}
Also used : FieldManager(org.datanucleus.store.fieldmanager.FieldManager) SQLException(java.sql.SQLException) ArrayList(java.util.ArrayList) 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 2 with OldValueParameterSetter

use of org.datanucleus.store.rdbms.fieldmanager.OldValueParameterSetter 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)

Aggregations

PreparedStatement (java.sql.PreparedStatement)2 SQLException (java.sql.SQLException)2 Timestamp (java.sql.Timestamp)2 ArrayList (java.util.ArrayList)2 List (java.util.List)2 ExecutionContext (org.datanucleus.ExecutionContext)2 NotYetFlushedException (org.datanucleus.exceptions.NotYetFlushedException)2 NucleusDataStoreException (org.datanucleus.exceptions.NucleusDataStoreException)2 NucleusException (org.datanucleus.exceptions.NucleusException)2 NucleusOptimisticException (org.datanucleus.exceptions.NucleusOptimisticException)2 AbstractMemberMetaData (org.datanucleus.metadata.AbstractMemberMetaData)2 ManagedConnection (org.datanucleus.store.connection.ManagedConnection)2 FieldManager (org.datanucleus.store.fieldmanager.FieldManager)2 RDBMSStoreManager (org.datanucleus.store.rdbms.RDBMSStoreManager)2 SQLController (org.datanucleus.store.rdbms.SQLController)2 OldValueParameterSetter (org.datanucleus.store.rdbms.fieldmanager.OldValueParameterSetter)2 ParameterSetter (org.datanucleus.store.rdbms.fieldmanager.ParameterSetter)2 StatementClassMapping (org.datanucleus.store.rdbms.query.StatementClassMapping)2 StatementMappingIndex (org.datanucleus.store.rdbms.query.StatementMappingIndex)2 MappingCallbacks (org.datanucleus.store.rdbms.mapping.MappingCallbacks)1