Search in sources :

Example 86 with ManagedConnection

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

the class FKArrayStore method updateElementFk.

/**
 * Update a FK and element position in the element.
 * @param ownerOP ObjectProvider for the owner
 * @param element The element to update
 * @param owner The owner object to set in the FK
 * @param index The index position (or -1 if not known)
 * @return Whether it was performed successfully
 */
private boolean updateElementFk(ObjectProvider ownerOP, E element, Object owner, int index) {
    if (element == null) {
        return false;
    }
    boolean retval;
    String updateFkStmt = getUpdateFkStmt();
    ExecutionContext ec = ownerOP.getExecutionContext();
    try {
        ManagedConnection mconn = storeMgr.getConnectionManager().getConnection(ec);
        SQLController sqlControl = storeMgr.getSQLController();
        try {
            PreparedStatement ps = sqlControl.getStatementForUpdate(mconn, updateFkStmt, false);
            try {
                int jdbcPosition = 1;
                if (elementInfo.length > 1) {
                    DatastoreClass table = storeMgr.getDatastoreClass(element.getClass().getName(), clr);
                    if (table != null) {
                        ps.setString(jdbcPosition++, table.toString());
                    } else {
                        NucleusLogger.PERSISTENCE.info(">> FKArrayStore.updateElementFK : need to set table in statement but dont know table where to store " + element);
                    }
                }
                if (owner == null) {
                    ownerMapping.setObject(ec, ps, MappingHelper.getMappingIndices(jdbcPosition, ownerMapping), null);
                    jdbcPosition += ownerMapping.getNumberOfDatastoreMappings();
                } else {
                    jdbcPosition = BackingStoreHelper.populateOwnerInStatement(ownerOP, ec, ps, jdbcPosition, this);
                }
                jdbcPosition = BackingStoreHelper.populateOrderInStatement(ec, ps, index, jdbcPosition, orderMapping);
                if (relationDiscriminatorMapping != null) {
                    jdbcPosition = BackingStoreHelper.populateRelationDiscriminatorInStatement(ec, ps, jdbcPosition, this);
                }
                jdbcPosition = BackingStoreHelper.populateElementInStatement(ec, ps, element, jdbcPosition, elementMapping);
                sqlControl.executeStatementUpdate(ec, mconn, updateFkStmt, ps, true);
                retval = true;
            } finally {
                sqlControl.closeStatement(mconn, ps);
            }
        } finally {
            mconn.release();
        }
    } catch (SQLException e) {
        throw new NucleusDataStoreException(Localiser.msg("056027", updateFkStmt), e);
    }
    return retval;
}
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) DatastoreClass(org.datanucleus.store.rdbms.table.DatastoreClass) SQLController(org.datanucleus.store.rdbms.SQLController)

Example 87 with ManagedConnection

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

the class FKListStore method clear.

/**
 * Method to clear the List.
 * This is called by the List.clear() method, or when the container object is being deleted
 * and the elements are to be removed (maybe for dependent field), or also when updating a Collection
 * and removing all existing prior to adding all new.
 * @param ownerOP ObjectProvider for the owner
 */
public void clear(ObjectProvider ownerOP) {
    boolean deleteElements = false;
    ExecutionContext ec = ownerOP.getExecutionContext();
    boolean dependent = ownerMemberMetaData.getCollection().isDependentElement();
    if (ownerMemberMetaData.isCascadeRemoveOrphans()) {
        dependent = true;
    }
    if (dependent) {
        // Elements are dependent and can't exist on their own, so delete them all
        NucleusLogger.DATASTORE.debug(Localiser.msg("056034"));
        deleteElements = true;
    } else {
        if (ownerMapping.isNullable() && orderMapping == null) {
            // Field is not dependent, and nullable so we null the FK
            NucleusLogger.DATASTORE.debug(Localiser.msg("056036"));
            deleteElements = false;
        } else if (ownerMapping.isNullable() && orderMapping != null && orderMapping.isNullable()) {
            // Field is not dependent, and nullable so we null the FK
            NucleusLogger.DATASTORE.debug(Localiser.msg("056036"));
            deleteElements = false;
        } else {
            // Field is not dependent, and not nullable so we just delete the elements
            NucleusLogger.DATASTORE.debug(Localiser.msg("056035"));
            deleteElements = true;
        }
    }
    if (deleteElements) {
        // Find elements present in the datastore and delete them one-by-one
        Iterator elementsIter = iterator(ownerOP);
        if (elementsIter != null) {
            while (elementsIter.hasNext()) {
                Object element = elementsIter.next();
                if (ec.getApiAdapter().isPersistable(element) && ec.getApiAdapter().isDeleted(element)) {
                    // Element is waiting to be deleted so flush it (it has the FK)
                    ObjectProvider objSM = ec.findObjectProvider(element);
                    objSM.flush();
                } else {
                    // Element not yet marked for deletion so go through the normal process
                    ec.deleteObjectInternal(element);
                }
            }
        }
    } else {
        boolean ownerSoftDelete = ownerOP.getClassMetaData().hasExtension(MetaData.EXTENSION_CLASS_SOFTDELETE);
        if (!ownerSoftDelete) {
            // Clear without delete
            // TODO If the relation is bidirectional we need to clear the owner in the element
            String clearNullifyStmt = getClearNullifyStmt();
            try {
                ManagedConnection mconn = storeMgr.getConnectionManager().getConnection(ec);
                SQLController sqlControl = storeMgr.getSQLController();
                try {
                    PreparedStatement ps = sqlControl.getStatementForUpdate(mconn, clearNullifyStmt, false);
                    try {
                        int jdbcPosition = 1;
                        jdbcPosition = BackingStoreHelper.populateOwnerInStatement(ownerOP, ec, ps, jdbcPosition, this);
                        if (relationDiscriminatorMapping != null) {
                            BackingStoreHelper.populateRelationDiscriminatorInStatement(ec, ps, jdbcPosition, this);
                        }
                        sqlControl.executeStatementUpdate(ec, mconn, clearNullifyStmt, ps, true);
                    } finally {
                        sqlControl.closeStatement(mconn, ps);
                    }
                } finally {
                    mconn.release();
                }
            } catch (SQLException e) {
                throw new NucleusDataStoreException(Localiser.msg("056013", clearNullifyStmt), e);
            }
        }
    }
}
Also used : NucleusDataStoreException(org.datanucleus.exceptions.NucleusDataStoreException) ExecutionContext(org.datanucleus.ExecutionContext) SQLException(java.sql.SQLException) ListIterator(java.util.ListIterator) Iterator(java.util.Iterator) ObjectProvider(org.datanucleus.state.ObjectProvider) ManagedConnection(org.datanucleus.store.connection.ManagedConnection) PreparedStatement(java.sql.PreparedStatement) SQLController(org.datanucleus.store.rdbms.SQLController)

Example 88 with ManagedConnection

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

the class FKSetStore method updateElementFk.

/**
 * Utility to update a foreign-key (and distinguisher) in the element in the case of a unidirectional 1-N relationship.
 * @param ownerOP ObjectProvider for the owner
 * @param element The element to update
 * @param owner The owner object to set in the FK
 * @return Whether it was performed successfully
 */
private boolean updateElementFk(ObjectProvider ownerOP, Object element, Object owner) {
    if (element == null) {
        return false;
    }
    validateElementForWriting(ownerOP.getExecutionContext(), element, null);
    boolean retval;
    ExecutionContext ec = ownerOP.getExecutionContext();
    String stmt = getUpdateFkStmt(element);
    try {
        ManagedConnection mconn = storeMgr.getConnectionManager().getConnection(ec);
        SQLController sqlControl = storeMgr.getSQLController();
        try {
            PreparedStatement ps = sqlControl.getStatementForUpdate(mconn, stmt, false);
            try {
                ComponentInfo elemInfo = getComponentInfoForElement(element);
                JavaTypeMapping ownerMapping = elemInfo.getOwnerMapping();
                JavaTypeMapping elemMapping = elemInfo.getDatastoreClass().getIdMapping();
                int jdbcPosition = 1;
                if (owner == null) {
                    ownerMapping.setObject(ec, ps, MappingHelper.getMappingIndices(jdbcPosition, ownerMapping), null, ownerOP, ownerMemberMetaData.getAbsoluteFieldNumber());
                } else {
                    ownerMapping.setObject(ec, ps, MappingHelper.getMappingIndices(jdbcPosition, ownerMapping), ownerOP.getObject(), ownerOP, ownerMemberMetaData.getAbsoluteFieldNumber());
                }
                jdbcPosition += ownerMapping.getNumberOfDatastoreMappings();
                if (relationDiscriminatorMapping != null) {
                    jdbcPosition = BackingStoreHelper.populateRelationDiscriminatorInStatement(ec, ps, jdbcPosition, this);
                }
                jdbcPosition = BackingStoreHelper.populateElementForWhereClauseInStatement(ec, ps, element, jdbcPosition, elemMapping);
                sqlControl.executeStatementUpdate(ec, mconn, stmt, ps, true);
                retval = true;
            } finally {
                sqlControl.closeStatement(mconn, ps);
            }
        } finally {
            mconn.release();
        }
    } catch (SQLException e) {
        throw new NucleusDataStoreException(Localiser.msg("056027", stmt), e);
    }
    return retval;
}
Also used : NucleusDataStoreException(org.datanucleus.exceptions.NucleusDataStoreException) ExecutionContext(org.datanucleus.ExecutionContext) JavaTypeMapping(org.datanucleus.store.rdbms.mapping.java.JavaTypeMapping) SQLException(java.sql.SQLException) ManagedConnection(org.datanucleus.store.connection.ManagedConnection) PreparedStatement(java.sql.PreparedStatement) SQLController(org.datanucleus.store.rdbms.SQLController)

Example 89 with ManagedConnection

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

the class FKSetStore method clear.

/**
 * Method to allow the Set relationship to be cleared out.
 * This is called by the List.clear() method, or when the container object is being deleted
 * and the elements are to be removed (maybe for dependent field), or also when updating a Collection
 * and removing all existing prior to adding all new.
 * @param ownerOP ObjectProvider for the owner.
 */
public void clear(ObjectProvider ownerOP) {
    ExecutionContext ec = ownerOP.getExecutionContext();
    boolean deleteElements = checkRemovalOfElementShouldDelete(ownerOP);
    if (deleteElements) {
        // Find elements present in the datastore and delete them one-by-one
        Iterator elementsIter = iterator(ownerOP);
        if (elementsIter != null) {
            while (elementsIter.hasNext()) {
                Object element = elementsIter.next();
                if (ec.getApiAdapter().isPersistable(element) && ec.getApiAdapter().isDeleted(element)) {
                    // Element is waiting to be deleted so flush it (it has the FK)
                    ec.findObjectProvider(element).flush();
                } else {
                    // Element not yet marked for deletion so go through the normal process
                    ec.deleteObjectInternal(element);
                }
            }
        }
    } else {
        boolean ownerSoftDelete = ownerOP.getClassMetaData().hasExtension(MetaData.EXTENSION_CLASS_SOFTDELETE);
        // Perform any necessary "managed relationships" updates on the element
        // Make sure the field is loaded
        ownerOP.isLoaded(ownerMemberMetaData.getAbsoluteFieldNumber());
        Collection value = (Collection) ownerOP.provideField(ownerMemberMetaData.getAbsoluteFieldNumber());
        Iterator elementsIter = null;
        if (value != null && !value.isEmpty()) {
            elementsIter = value.iterator();
        } else {
            // Maybe deleting the owner with optimistic transactions so the elements are no longer cached
            elementsIter = iterator(ownerOP);
        }
        if (!ownerSoftDelete) {
            if (elementsIter != null) {
                while (elementsIter.hasNext()) {
                    Object element = elementsIter.next();
                    manageRemovalOfElement(ownerOP, element);
                }
            }
        }
        if (!ownerSoftDelete) {
            // TODO This is likely not necessary in the 1-N bidir case since we've just set the owner FK to null above
            for (int i = 0; i < elementInfo.length; i++) {
                String stmt = getClearNullifyStmt(elementInfo[i]);
                try {
                    ManagedConnection mconn = storeMgr.getConnectionManager().getConnection(ec);
                    SQLController sqlControl = storeMgr.getSQLController();
                    try {
                        PreparedStatement ps = sqlControl.getStatementForUpdate(mconn, stmt, false);
                        try {
                            int jdbcPosition = 1;
                            BackingStoreHelper.populateOwnerInStatement(ownerOP, ec, ps, jdbcPosition, this);
                            sqlControl.executeStatementUpdate(ec, mconn, stmt, ps, true);
                        } finally {
                            sqlControl.closeStatement(mconn, ps);
                        }
                    } finally {
                        mconn.release();
                    }
                } catch (SQLException e) {
                    throw new NucleusDataStoreException(Localiser.msg("056013", stmt), e);
                }
            }
        }
    }
}
Also used : NucleusDataStoreException(org.datanucleus.exceptions.NucleusDataStoreException) ExecutionContext(org.datanucleus.ExecutionContext) SQLException(java.sql.SQLException) Iterator(java.util.Iterator) Collection(java.util.Collection) ManagedConnection(org.datanucleus.store.connection.ManagedConnection) PreparedStatement(java.sql.PreparedStatement) SQLController(org.datanucleus.store.rdbms.SQLController)

Example 90 with ManagedConnection

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

the class FKSetStore method iterator.

/**
 * Accessor for an iterator for the set.
 * @param ownerOP ObjectProvider for the owner.
 * @return Iterator for the set.
 */
public Iterator<E> iterator(ObjectProvider ownerOP) {
    ExecutionContext ec = ownerOP.getExecutionContext();
    if (elementInfo == null || elementInfo.length == 0) {
        return null;
    }
    // Generate the statement, and statement mapping/parameter information
    IteratorStatement iterStmt = getIteratorStatement(ec, ec.getFetchPlan(), true);
    SelectStatement sqlStmt = iterStmt.getSelectStatement();
    StatementClassMapping iteratorMappingClass = iterStmt.getStatementClassMapping();
    // 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 < ownerMapping.getNumberOfDatastoreMappings(); k++) {
                paramPositions[k] = inputParamNum++;
            }
            ownerStmtMapIdx.addParameterOccurrence(paramPositions);
        }
    } else {
        int[] paramPositions = new int[ownerMapping.getNumberOfDatastoreMappings()];
        for (int k = 0; k < ownerMapping.getNumberOfDatastoreMappings(); 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 {
                    ResultObjectFactory rof = null;
                    if (elementsAreEmbedded || elementsAreSerialised) {
                        throw new NucleusException("Cannot have FK set with non-persistent objects");
                    }
                    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) PersistentClassROF(org.datanucleus.store.rdbms.query.PersistentClassROF) ResultSet(java.sql.ResultSet) ManagedConnection(org.datanucleus.store.connection.ManagedConnection) ObjectProvider(org.datanucleus.state.ObjectProvider) NucleusException(org.datanucleus.exceptions.NucleusException)

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