Search in sources :

Example 96 with ManagedConnection

use of org.datanucleus.store.connection.ManagedConnection 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 97 with ManagedConnection

use of org.datanucleus.store.connection.ManagedConnection 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 98 with ManagedConnection

use of org.datanucleus.store.connection.ManagedConnection 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 99 with ManagedConnection

use of org.datanucleus.store.connection.ManagedConnection in project datanucleus-rdbms by datanucleus.

the class JoinSetStore method locate.

private boolean locate(ObjectProvider op, Object element) {
    boolean exists = true;
    String stmt = getLocateStmt(element);
    try {
        ExecutionContext ec = op.getExecutionContext();
        ManagedConnection mconn = storeMgr.getConnectionManager().getConnection(ec);
        SQLController sqlControl = storeMgr.getSQLController();
        try {
            PreparedStatement ps = sqlControl.getStatementForQuery(mconn, stmt);
            try {
                int jdbcPosition = 1;
                jdbcPosition = BackingStoreHelper.populateOwnerInStatement(op, ec, ps, jdbcPosition, this);
                jdbcPosition = BackingStoreHelper.populateElementForWhereClauseInStatement(ec, ps, element, jdbcPosition, elementMapping);
                if (relationDiscriminatorMapping != null) {
                    jdbcPosition = BackingStoreHelper.populateRelationDiscriminatorInStatement(ec, ps, jdbcPosition, this);
                }
                ResultSet rs = sqlControl.executeStatementQuery(ec, mconn, stmt, ps);
                try {
                    if (!rs.next()) {
                        exists = false;
                    }
                } catch (SQLException sqle) {
                    rs.close();
                }
            } finally {
                sqlControl.closeStatement(mconn, ps);
            }
        } finally {
            mconn.release();
        }
    } catch (SQLException e) {
        NucleusLogger.DATASTORE.error(Localiser.msg("RDBMS.SCO.LocateRequestFailed", stmt), e);
        throw new NucleusDataStoreException(Localiser.msg("RDBMS.SCO.LocateRequestFailed", stmt), e);
    }
    return exists;
}
Also used : NucleusDataStoreException(org.datanucleus.exceptions.NucleusDataStoreException) ExecutionContext(org.datanucleus.ExecutionContext) SQLException(java.sql.SQLException) ResultSet(java.sql.ResultSet) ManagedConnection(org.datanucleus.store.connection.ManagedConnection) PreparedStatement(java.sql.PreparedStatement) SQLController(org.datanucleus.store.rdbms.SQLController)

Example 100 with ManagedConnection

use of org.datanucleus.store.connection.ManagedConnection in project datanucleus-rdbms by datanucleus.

the class MapValueCollectionStore method iterator.

/**
 * Accessor for an iterator for the set.
 * @param ownerOP ObjectProvider for the set.
 * @return Iterator for the set.
 */
public Iterator<V> iterator(ObjectProvider ownerOP) {
    ExecutionContext ec = ownerOP.getExecutionContext();
    if (iteratorStmtLocked == 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 = getSQLStatementForIterator(ownerOP);
            iteratorStmtUnlocked = sqlStmt.getSQLText().toSQL();
            sqlStmt.addExtension(SQLStatement.EXTENSION_LOCK_FOR_UPDATE, true);
            iteratorStmtLocked = sqlStmt.getSQLText().toSQL();
        }
    }
    Transaction tx = ec.getTransaction();
    String stmt = (tx.getSerializeRead() != null && tx.getSerializeRead() ? iteratorStmtLocked : iteratorStmtUnlocked);
    try {
        ManagedConnection mconn = storeMgr.getConnectionManager().getConnection(ec);
        SQLController sqlControl = storeMgr.getSQLController();
        try {
            // Create the statement and set the owner
            PreparedStatement ps = sqlControl.getStatementForQuery(mconn, stmt);
            StatementMappingIndex ownerIdx = iteratorMappingParams.getMappingForParameter("owner");
            int numParams = ownerIdx.getNumberOfParameterOccurrences();
            for (int paramInstance = 0; paramInstance < numParams; paramInstance++) {
                ownerIdx.getMapping().setObject(ec, ps, ownerIdx.getParameterPositionsForOccurrence(paramInstance), ownerOP.getObject());
            }
            try {
                ResultSet rs = sqlControl.executeStatementQuery(ec, mconn, stmt, ps);
                try {
                    ResultObjectFactory rof = null;
                    if (elementsAreEmbedded || elementsAreSerialised) {
                        // No ResultObjectFactory needed - handled by SetStoreIterator
                        return new CollectionStoreIterator(ownerOP, rs, null, this);
                    }
                    rof = new PersistentClassROF(ec, rs, false, iteratorMappingDef, elementCmd, clr.classForName(elementType));
                    return new CollectionStoreIterator(ownerOP, rs, rof, this);
                } finally {
                    rs.close();
                }
            } finally {
                sqlControl.closeStatement(mconn, ps);
            }
        } finally {
            mconn.release();
        }
    } catch (SQLException e) {
        throw new NucleusDataStoreException(Localiser.msg("056006", stmt), e);
    } catch (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) SQLStatement(org.datanucleus.store.rdbms.sql.SQLStatement) SQLController(org.datanucleus.store.rdbms.SQLController) NucleusDataStoreException(org.datanucleus.exceptions.NucleusDataStoreException) ExecutionContext(org.datanucleus.ExecutionContext) Transaction(org.datanucleus.Transaction) PersistentClassROF(org.datanucleus.store.rdbms.query.PersistentClassROF) ResultSet(java.sql.ResultSet) ManagedConnection(org.datanucleus.store.connection.ManagedConnection)

Aggregations

ManagedConnection (org.datanucleus.store.connection.ManagedConnection)157 SQLException (java.sql.SQLException)125 RDBMSStoreManager (org.datanucleus.store.rdbms.RDBMSStoreManager)80 Connection (java.sql.Connection)75 NucleusDataStoreException (org.datanucleus.exceptions.NucleusDataStoreException)74 PreparedStatement (java.sql.PreparedStatement)70 ExecutionContext (org.datanucleus.ExecutionContext)64 SQLController (org.datanucleus.store.rdbms.SQLController)63 HashSet (java.util.HashSet)62 DatabaseMetaData (java.sql.DatabaseMetaData)58 PersistenceManager (javax.jdo.PersistenceManager)46 Transaction (javax.jdo.Transaction)46 JDOFatalUserException (javax.jdo.JDOFatalUserException)45 JDOPersistenceManager (org.datanucleus.api.jdo.JDOPersistenceManager)45 ResultSet (java.sql.ResultSet)37 JDOFatalInternalException (javax.jdo.JDOFatalInternalException)24 JDODataStoreException (javax.jdo.JDODataStoreException)21 JDOUserException (javax.jdo.JDOUserException)21 MappedDatastoreException (org.datanucleus.store.rdbms.exceptions.MappedDatastoreException)21 EntityTransaction (javax.persistence.EntityTransaction)19