Search in sources :

Example 61 with SQLController

use of org.datanucleus.store.rdbms.SQLController in project datanucleus-rdbms by datanucleus.

the class JoinPersistableRelationStore method remove.

/* (non-Javadoc)
     * @see org.datanucleus.store.scostore.PersistableRelationStore#remove(org.datanucleus.store.ObjectProvider)
     */
public boolean remove(ObjectProvider op) {
    String removeStmt = getRemoveStmt();
    ExecutionContext ec = op.getExecutionContext();
    SQLController sqlControl = storeMgr.getSQLController();
    try {
        ManagedConnection mconn = storeMgr.getConnectionManager().getConnection(ec);
        PreparedStatement ps = sqlControl.getStatementForUpdate(mconn, removeStmt, false);
        try {
            // Update the join table row
            int jdbcPosition = 1;
            populateOwnerInStatement(op, ec, ps, jdbcPosition, joinTable);
            // Execute the statement
            int[] nums = sqlControl.executeStatementUpdate(ec, mconn, removeStmt, ps, true);
            return (nums != null && nums.length == 1 && nums[0] == 1);
        } finally {
            sqlControl.closeStatement(mconn, ps);
            mconn.release();
        }
    } catch (SQLException sqle) {
        throw new NucleusDataStoreException("Exception thrown deleting row from persistable relation join table", sqle);
    }
}
Also used : NucleusDataStoreException(org.datanucleus.exceptions.NucleusDataStoreException) ExecutionContext(org.datanucleus.ExecutionContext) SQLException(java.sql.SQLException) ManagedConnection(org.datanucleus.store.connection.ManagedConnection) PreparedStatement(java.sql.PreparedStatement) SQLController(org.datanucleus.store.rdbms.SQLController)

Example 62 with SQLController

use of org.datanucleus.store.rdbms.SQLController in project datanucleus-rdbms by datanucleus.

the class JoinSetStore method removeAllInternal.

protected boolean removeAllInternal(ObjectProvider op, Collection elements, int size) {
    boolean modified = false;
    String removeAllStmt = getRemoveAllStmt(op, elements);
    try {
        ExecutionContext ec = op.getExecutionContext();
        ManagedConnection mconn = storeMgr.getConnectionManager().getConnection(ec);
        SQLController sqlControl = storeMgr.getSQLController();
        try {
            PreparedStatement ps = sqlControl.getStatementForUpdate(mconn, removeAllStmt, false);
            try {
                int jdbcPosition = 1;
                Iterator iter = elements.iterator();
                while (iter.hasNext()) {
                    Object element = iter.next();
                    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);
                    }
                }
                int[] number = sqlControl.executeStatementUpdate(ec, mconn, removeAllStmt, ps, true);
                if (number[0] > 0) {
                    modified = true;
                }
            } finally {
                sqlControl.closeStatement(mconn, ps);
            }
        } finally {
            mconn.release();
        }
    } catch (SQLException e) {
        NucleusLogger.DATASTORE.error("Exception on removeAll", e);
        throw new NucleusDataStoreException(Localiser.msg("056012", removeAllStmt), e);
    }
    return modified;
}
Also used : NucleusDataStoreException(org.datanucleus.exceptions.NucleusDataStoreException) ExecutionContext(org.datanucleus.ExecutionContext) SQLException(java.sql.SQLException) Iterator(java.util.Iterator) ManagedConnection(org.datanucleus.store.connection.ManagedConnection) PreparedStatement(java.sql.PreparedStatement) SQLController(org.datanucleus.store.rdbms.SQLController)

Example 63 with SQLController

use of org.datanucleus.store.rdbms.SQLController 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 64 with SQLController

use of org.datanucleus.store.rdbms.SQLController 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 65 with SQLController

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

Aggregations

SQLController (org.datanucleus.store.rdbms.SQLController)83 PreparedStatement (java.sql.PreparedStatement)82 SQLException (java.sql.SQLException)72 ExecutionContext (org.datanucleus.ExecutionContext)63 ManagedConnection (org.datanucleus.store.connection.ManagedConnection)63 NucleusDataStoreException (org.datanucleus.exceptions.NucleusDataStoreException)60 ResultSet (java.sql.ResultSet)36 MappedDatastoreException (org.datanucleus.store.rdbms.exceptions.MappedDatastoreException)20 StatementMappingIndex (org.datanucleus.store.rdbms.query.StatementMappingIndex)19 RDBMSStoreManager (org.datanucleus.store.rdbms.RDBMSStoreManager)17 ArrayList (java.util.ArrayList)15 List (java.util.List)13 ObjectProvider (org.datanucleus.state.ObjectProvider)12 StatementClassMapping (org.datanucleus.store.rdbms.query.StatementClassMapping)12 Iterator (java.util.Iterator)11 JavaTypeMapping (org.datanucleus.store.rdbms.mapping.java.JavaTypeMapping)10 PersistentClassROF (org.datanucleus.store.rdbms.query.PersistentClassROF)10 ResultObjectFactory (org.datanucleus.store.rdbms.query.ResultObjectFactory)10 NucleusException (org.datanucleus.exceptions.NucleusException)9 AbstractClassMetaData (org.datanucleus.metadata.AbstractClassMetaData)9