Search in sources :

Example 81 with ObjectProvider

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

the class JoinSetStore method addAll.

/**
 * Adds all elements from a collection to the association container.
 * @param op ObjectProvider for the container.
 * @param elements Collection of elements to add
 * @return Whether it was successful
 */
public boolean addAll(ObjectProvider op, Collection<E> elements, int size) {
    if (elements == null || elements.size() == 0) {
        return false;
    }
    List exceptions = new ArrayList();
    boolean batched = (elements.size() > 1);
    // Validate all elements for writing
    ExecutionContext ec = op.getExecutionContext();
    Iterator<E> iter = elements.iterator();
    while (iter.hasNext()) {
        Object element = iter.next();
        validateElementForWriting(ec, element, null);
        if (relationType == RelationType.ONE_TO_MANY_BI) {
            // TODO This is ManagedRelations - move into RelationshipManager
            // Managed Relations : make sure we have consistency of relation
            ObjectProvider elementOP = op.getExecutionContext().findObjectProvider(element);
            if (elementOP != null) {
                AbstractMemberMetaData[] relatedMmds = ownerMemberMetaData.getRelatedMemberMetaData(clr);
                Object elementOwner = elementOP.provideField(relatedMmds[0].getAbsoluteFieldNumber());
                if (elementOwner == null) {
                    // No owner, so correct it
                    NucleusLogger.PERSISTENCE.info(Localiser.msg("056037", op.getObjectAsPrintable(), ownerMemberMetaData.getFullFieldName(), StringUtils.toJVMIDString(elementOP.getObject())));
                    elementOP.replaceField(relatedMmds[0].getAbsoluteFieldNumber(), op.getObject());
                } else if (elementOwner != op.getObject() && op.getReferencedPC() == null) {
                    // Inconsistent owner, so throw exception
                    throw new NucleusUserException(Localiser.msg("056038", op.getObjectAsPrintable(), ownerMemberMetaData.getFullFieldName(), StringUtils.toJVMIDString(elementOP.getObject()), StringUtils.toJVMIDString(elementOwner)));
                }
            }
        }
    }
    boolean modified = false;
    try {
        ManagedConnection mconn = storeMgr.getConnectionManager().getConnection(ec);
        try {
            SQLController sqlControl = storeMgr.getSQLController();
            try {
                // Process all waiting batched statements before we start our work
                sqlControl.processStatementsForConnection(mconn);
            } catch (SQLException e) {
                throw new MappedDatastoreException("SQLException", e);
            }
            int nextOrderID = orderMapping != null ? getNextIDForOrderColumn(op) : 0;
            // Loop through all elements to be added
            iter = elements.iterator();
            E element = null;
            while (iter.hasNext()) {
                element = iter.next();
                try {
                    // Add the row to the join table
                    boolean toBeInserted = true;
                    if (relationType == RelationType.MANY_TO_MANY_BI) {
                        toBeInserted = !elementAlreadyContainsOwnerInMtoN(op, element);
                    }
                    if (toBeInserted) {
                        int[] rc = doInternalAdd(op, element, mconn, batched, nextOrderID, !batched || (batched && !iter.hasNext()));
                        if (rc != null) {
                            for (int i = 0; i < rc.length; i++) {
                                if (rc[i] > 0) {
                                    // At least one record was inserted
                                    modified = true;
                                }
                            }
                        }
                        nextOrderID++;
                    }
                } catch (MappedDatastoreException mde) {
                    exceptions.add(mde);
                    NucleusLogger.DATASTORE.error("Exception thrown", mde);
                }
            }
        } finally {
            mconn.release();
        }
    } catch (MappedDatastoreException e) {
        exceptions.add(e);
        NucleusLogger.DATASTORE.error("Exception thrown", e);
    }
    if (!exceptions.isEmpty()) {
        // Throw all exceptions received as the cause of a NucleusDataStoreException so the user can see which record(s) didn't persist
        String msg = Localiser.msg("056009", ((Exception) exceptions.get(0)).getMessage());
        NucleusLogger.DATASTORE.error(msg);
        throw new NucleusDataStoreException(msg, (Throwable[]) exceptions.toArray(new Throwable[exceptions.size()]), op.getObject());
    }
    return modified;
}
Also used : MappedDatastoreException(org.datanucleus.store.rdbms.exceptions.MappedDatastoreException) SQLException(java.sql.SQLException) NucleusUserException(org.datanucleus.exceptions.NucleusUserException) ArrayList(java.util.ArrayList) SQLController(org.datanucleus.store.rdbms.SQLController) NucleusDataStoreException(org.datanucleus.exceptions.NucleusDataStoreException) ExecutionContext(org.datanucleus.ExecutionContext) List(java.util.List) ArrayList(java.util.ArrayList) ObjectProvider(org.datanucleus.state.ObjectProvider) ManagedConnection(org.datanucleus.store.connection.ManagedConnection) AbstractMemberMetaData(org.datanucleus.metadata.AbstractMemberMetaData)

Example 82 with ObjectProvider

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

the class JoinSetStore method add.

/**
 * Adds one element to the association owner vs elements.
 * @param op ObjectProvider for the container.
 * @param element Element to add
 * @return Whether it was successful
 */
public boolean add(ObjectProvider op, E element, int size) {
    // Check that the object is valid for writing
    ExecutionContext ec = op.getExecutionContext();
    validateElementForWriting(ec, element, null);
    if (relationType == RelationType.ONE_TO_MANY_BI) {
        // TODO This is ManagedRelations - move into RelationshipManager
        // Managed Relations : make sure we have consistency of relation
        ObjectProvider elementOP = ec.findObjectProvider(element);
        if (elementOP != null) {
            AbstractMemberMetaData[] relatedMmds = ownerMemberMetaData.getRelatedMemberMetaData(clr);
            Object elementOwner = elementOP.provideField(relatedMmds[0].getAbsoluteFieldNumber());
            if (elementOwner == null) {
                // No owner, so correct it
                NucleusLogger.PERSISTENCE.info(Localiser.msg("056037", op.getObjectAsPrintable(), ownerMemberMetaData.getFullFieldName(), StringUtils.toJVMIDString(elementOP.getObject())));
                elementOP.replaceField(relatedMmds[0].getAbsoluteFieldNumber(), op.getObject());
            } else if (elementOwner != op.getObject() && op.getReferencedPC() == null) {
                // Inconsistent owner, so throw exception
                throw new NucleusUserException(Localiser.msg("056038", op.getObjectAsPrintable(), ownerMemberMetaData.getFullFieldName(), StringUtils.toJVMIDString(elementOP.getObject()), StringUtils.toJVMIDString(elementOwner)));
            }
        }
    }
    boolean modified = false;
    boolean toBeInserted = true;
    if (relationType == RelationType.MANY_TO_MANY_BI) {
        toBeInserted = !elementAlreadyContainsOwnerInMtoN(op, element);
    }
    if (toBeInserted) {
        try {
            ManagedConnection mconn = storeMgr.getConnectionManager().getConnection(ec);
            try {
                // Add a row to the join table
                int orderID = orderMapping != null ? getNextIDForOrderColumn(op) : -1;
                int[] returnCode = doInternalAdd(op, element, mconn, false, orderID, true);
                if (returnCode[0] > 0) {
                    modified = true;
                }
            } finally {
                mconn.release();
            }
        } catch (MappedDatastoreException e) {
            String msg = Localiser.msg("056009", e.getMessage());
            NucleusLogger.DATASTORE.error(msg, e);
            throw new NucleusDataStoreException(msg, e);
        }
    }
    return modified;
}
Also used : MappedDatastoreException(org.datanucleus.store.rdbms.exceptions.MappedDatastoreException) NucleusUserException(org.datanucleus.exceptions.NucleusUserException) NucleusDataStoreException(org.datanucleus.exceptions.NucleusDataStoreException) ExecutionContext(org.datanucleus.ExecutionContext) ObjectProvider(org.datanucleus.state.ObjectProvider) ManagedConnection(org.datanucleus.store.connection.ManagedConnection) AbstractMemberMetaData(org.datanucleus.metadata.AbstractMemberMetaData)

Example 83 with ObjectProvider

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

the class JoinSetStore method iterator.

/**
 * Accessor for an iterator for the set.
 * @param ownerOP ObjectProvider for the set.
 * @return Iterator for the set.
 */
public Iterator<E> iterator(ObjectProvider ownerOP) {
    ExecutionContext ec = ownerOP.getExecutionContext();
    // Generate the statement, and statement mapping/parameter information
    IteratorStatement iterStmt = getIteratorStatement(ec, ec.getFetchPlan(), true);
    SelectStatement sqlStmt = iterStmt.sqlStmt;
    StatementClassMapping iteratorMappingClass = iterStmt.stmtClassMapping;
    // Input parameter(s) - the owner
    int inputParamNum = 1;
    StatementMappingIndex ownerStmtMapIdx = new StatementMappingIndex(ownerMapping);
    if (sqlStmt.getNumberOfUnions() > 0) {
        // Add parameter occurrence for each union of statement
        for (int j = 0; j < sqlStmt.getNumberOfUnions() + 1; j++) {
            int[] paramPositions = new int[ownerMapping.getNumberOfDatastoreMappings()];
            for (int k = 0; k < paramPositions.length; k++) {
                paramPositions[k] = inputParamNum++;
            }
            ownerStmtMapIdx.addParameterOccurrence(paramPositions);
        }
    } else {
        int[] paramPositions = new int[ownerMapping.getNumberOfDatastoreMappings()];
        for (int k = 0; k < paramPositions.length; k++) {
            paramPositions[k] = inputParamNum++;
        }
        ownerStmtMapIdx.addParameterOccurrence(paramPositions);
    }
    if (ec.getTransaction().getSerializeRead() != null && ec.getTransaction().getSerializeRead()) {
        sqlStmt.addExtension(SQLStatement.EXTENSION_LOCK_FOR_UPDATE, true);
    }
    String stmt = sqlStmt.getSQLText().toSQL();
    try {
        ManagedConnection mconn = storeMgr.getConnectionManager().getConnection(ec);
        SQLController sqlControl = storeMgr.getSQLController();
        try {
            // Create the statement
            PreparedStatement ps = sqlControl.getStatementForQuery(mconn, stmt);
            // Set the owner
            ObjectProvider stmtOwnerOP = BackingStoreHelper.getOwnerObjectProviderForBackingStore(ownerOP);
            int numParams = ownerStmtMapIdx.getNumberOfParameterOccurrences();
            for (int paramInstance = 0; paramInstance < numParams; paramInstance++) {
                ownerStmtMapIdx.getMapping().setObject(ec, ps, ownerStmtMapIdx.getParameterPositionsForOccurrence(paramInstance), stmtOwnerOP.getObject());
            }
            try {
                ResultSet rs = sqlControl.executeStatementQuery(ec, mconn, stmt, ps);
                try {
                    if (elementsAreEmbedded || elementsAreSerialised) {
                        // No ResultObjectFactory needed - handled by SetStoreIterator
                        return new CollectionStoreIterator(ownerOP, rs, null, this);
                    } else if (elementMapping instanceof ReferenceMapping) {
                        // No ResultObjectFactory needed - handled by SetStoreIterator
                        return new CollectionStoreIterator(ownerOP, rs, null, this);
                    } else {
                        ResultObjectFactory rof = new PersistentClassROF(ec, rs, false, iteratorMappingClass, elementCmd, clr.classForName(elementType));
                        return new CollectionStoreIterator(ownerOP, rs, rof, this);
                    }
                } finally {
                    rs.close();
                }
            } finally {
                sqlControl.closeStatement(mconn, ps);
            }
        } finally {
            mconn.release();
        }
    } catch (SQLException | MappedDatastoreException e) {
        throw new NucleusDataStoreException(Localiser.msg("056006", stmt), e);
    }
}
Also used : MappedDatastoreException(org.datanucleus.store.rdbms.exceptions.MappedDatastoreException) SQLException(java.sql.SQLException) ResultObjectFactory(org.datanucleus.store.rdbms.query.ResultObjectFactory) PreparedStatement(java.sql.PreparedStatement) StatementMappingIndex(org.datanucleus.store.rdbms.query.StatementMappingIndex) StatementClassMapping(org.datanucleus.store.rdbms.query.StatementClassMapping) SQLController(org.datanucleus.store.rdbms.SQLController) SelectStatement(org.datanucleus.store.rdbms.sql.SelectStatement) NucleusDataStoreException(org.datanucleus.exceptions.NucleusDataStoreException) ExecutionContext(org.datanucleus.ExecutionContext) 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) ObjectProvider(org.datanucleus.state.ObjectProvider)

Example 84 with ObjectProvider

use of org.datanucleus.state.ObjectProvider 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 op ObjectProvider 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(ObjectProvider op, 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.getNumberOfDatastoreMappings()];
        for (int j = 0; j < fieldMapping.getNumberOfDatastoreMappings(); j++) {
            jdbcParamPositions[j] = jdbcPosition++;
        }
        stmtMapping.addParameterOccurrence(jdbcParamPositions);
        mappingDefinition.addMappingForMember(absFieldNum, stmtMapping);
    }
    ObjectProvider elementOP = mapStore.getObjectProviderForEmbeddedPCObject(op, key, joinTable.getOwnerMemberMetaData(), ObjectProvider.EMBEDDED_MAP_KEY_PC);
    elementOP.provideFields(elementFieldNumbers, new ParameterSetter(elementOP, ps, mappingDefinition));
    return jdbcPosition;
}
Also used : JavaTypeMapping(org.datanucleus.store.rdbms.mapping.java.JavaTypeMapping) ObjectProvider(org.datanucleus.state.ObjectProvider) 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 85 with ObjectProvider

use of org.datanucleus.state.ObjectProvider 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 op ObjectProvider 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(ObjectProvider op, 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.getNumberOfDatastoreMappings()];
        for (int j = 0; j < fieldMapping.getNumberOfDatastoreMappings(); j++) {
            jdbcParamPositions[j] = jdbcPosition++;
        }
        stmtMapping.addParameterOccurrence(jdbcParamPositions);
        mappingDefinition.addMappingForMember(absFieldNum, stmtMapping);
    }
    ObjectProvider elementOP = mapStore.getObjectProviderForEmbeddedPCObject(op, value, joinTable.getOwnerMemberMetaData(), ObjectProvider.EMBEDDED_MAP_VALUE_PC);
    elementOP.provideFields(elementFieldNumbers, new ParameterSetter(elementOP, ps, mappingDefinition));
    return jdbcPosition;
}
Also used : JavaTypeMapping(org.datanucleus.store.rdbms.mapping.java.JavaTypeMapping) ObjectProvider(org.datanucleus.state.ObjectProvider) EmbeddedValuePCMapping(org.datanucleus.store.rdbms.mapping.java.EmbeddedValuePCMapping) 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)

Aggregations

ObjectProvider (org.datanucleus.state.ObjectProvider)160 ExecutionContext (org.datanucleus.ExecutionContext)85 Iterator (java.util.Iterator)43 NucleusUserException (org.datanucleus.exceptions.NucleusUserException)34 AbstractMemberMetaData (org.datanucleus.metadata.AbstractMemberMetaData)25 Map (java.util.Map)22 NucleusDataStoreException (org.datanucleus.exceptions.NucleusDataStoreException)22 AbstractClassMetaData (org.datanucleus.metadata.AbstractClassMetaData)21 SQLException (java.sql.SQLException)17 Collection (java.util.Collection)16 ApiAdapter (org.datanucleus.api.ApiAdapter)16 NucleusObjectNotFoundException (org.datanucleus.exceptions.NucleusObjectNotFoundException)16 SCOCollectionIterator (org.datanucleus.store.types.SCOCollectionIterator)16 ArrayList (java.util.ArrayList)14 HashSet (java.util.HashSet)14 StatementMappingIndex (org.datanucleus.store.rdbms.query.StatementMappingIndex)14 NucleusException (org.datanucleus.exceptions.NucleusException)13 ManagedConnection (org.datanucleus.store.connection.ManagedConnection)13 ListIterator (java.util.ListIterator)12 SQLController (org.datanucleus.store.rdbms.SQLController)12