Search in sources :

Example 56 with SQLController

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

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

Example 58 with SQLController

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

the class JoinArrayStore method iterator.

/**
 * Method to return an iterator to the array.
 * @param ownerOP ObjectProvider for the owner of the array
 */
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 ownerIdx = 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++;
            }
            ownerIdx.addParameterOccurrence(paramPositions);
        }
    } else {
        int[] paramPositions = new int[ownerMapping.getNumberOfDatastoreMappings()];
        for (int k = 0; k < paramPositions.length; k++) {
            paramPositions[k] = inputParamNum++;
        }
        ownerIdx.addParameterOccurrence(paramPositions);
    }
    StatementParameterMapping iteratorMappingParams = new StatementParameterMapping();
    iteratorMappingParams.addMappingForParameter("owner", ownerIdx);
    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 = ownerIdx.getNumberOfParameterOccurrences();
            for (int paramInstance = 0; paramInstance < numParams; paramInstance++) {
                ownerIdx.getMapping().setObject(ec, ps, ownerIdx.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 ArrayStoreIterator(ownerOP, rs, null, this);
                    } else if (elementMapping instanceof ReferenceMapping) {
                        // No ResultObjectFactory needed - handled by SetStoreIterator
                        return new ArrayStoreIterator(ownerOP, rs, null, this);
                    } else {
                        ResultObjectFactory rof = new PersistentClassROF(ec, rs, false, iteratorMappingClass, elementCmd, clr.classForName(elementType));
                        return new ArrayStoreIterator(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 : StatementParameterMapping(org.datanucleus.store.rdbms.query.StatementParameterMapping) 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 59 with SQLController

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

the class JoinMapStore method getNextIDForAdapterColumn.

/**
 * Accessor for the higher id when elements primary key can't be part of
 * the primary key by datastore limitations like BLOB types can't be primary keys.
 * @param op ObjectProvider for container
 * @return The next id
 */
private int getNextIDForAdapterColumn(ObjectProvider op) {
    int nextID;
    try {
        ExecutionContext ec = op.getExecutionContext();
        ManagedConnection mconn = storeMgr.getConnectionManager().getConnection(ec);
        SQLController sqlControl = storeMgr.getSQLController();
        try {
            String stmt = getMaxAdapterColumnIdStmt();
            PreparedStatement ps = sqlControl.getStatementForQuery(mconn, stmt);
            try {
                int jdbcPosition = 1;
                BackingStoreHelper.populateOwnerInStatement(op, ec, ps, jdbcPosition, this);
                ResultSet rs = sqlControl.executeStatementQuery(ec, mconn, stmt, ps);
                try {
                    if (!rs.next()) {
                        nextID = 1;
                    } else {
                        nextID = rs.getInt(1) + 1;
                    }
                    JDBCUtils.logWarnings(rs);
                } finally {
                    rs.close();
                }
            } finally {
                sqlControl.closeStatement(mconn, ps);
            }
        } finally {
            mconn.release();
        }
    } catch (SQLException e) {
        throw new NucleusDataStoreException(Localiser.msg("056020", getMaxAdapterColumnIdStmt()), e);
    }
    return nextID;
}
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 60 with SQLController

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

the class JoinMapStore method internalPut.

/**
 * Method to process a "put" statement (where the key has no value in the join table).
 * @param ownerOP ObjectProvider for the owner
 * @param conn The Connection
 * @param batched Whether we are batching it
 * @param key The key
 * @param value The value
 * @param executeNow Whether to execute the statement now or wait til batching
 * @return The return codes from any executed statement
 * @throws MappedDatastoreException Thrown if an error occurs
 */
protected int[] internalPut(ObjectProvider ownerOP, ManagedConnection conn, boolean batched, Object key, Object value, boolean executeNow) throws MappedDatastoreException {
    ExecutionContext ec = ownerOP.getExecutionContext();
    SQLController sqlControl = storeMgr.getSQLController();
    try {
        PreparedStatement ps = sqlControl.getStatementForUpdate(conn, putStmt, false);
        try {
            int jdbcPosition = 1;
            if (valueMapping != null) {
                jdbcPosition = BackingStoreHelper.populateValueInStatement(ec, ps, value, jdbcPosition, valueMapping);
            } else {
                jdbcPosition = BackingStoreHelper.populateEmbeddedValueFieldsInStatement(ownerOP, value, ps, jdbcPosition, (JoinTable) mapTable, this);
            }
            jdbcPosition = BackingStoreHelper.populateOwnerInStatement(ownerOP, ec, ps, jdbcPosition, this);
            if (adapterMapping != null) {
                // Only set the adapter mapping if we have a new object
                long nextIDAdapter = getNextIDForAdapterColumn(ownerOP);
                adapterMapping.setObject(ec, ps, MappingHelper.getMappingIndices(jdbcPosition, adapterMapping), Long.valueOf(nextIDAdapter));
                jdbcPosition += adapterMapping.getNumberOfDatastoreMappings();
            }
            jdbcPosition = BackingStoreHelper.populateKeyInStatement(ec, ps, key, jdbcPosition, keyMapping);
            // Execute the statement
            return sqlControl.executeStatementUpdate(ec, conn, putStmt, ps, true);
        } finally {
            sqlControl.closeStatement(conn, ps);
        }
    } catch (SQLException e) {
        throw new MappedDatastoreException(getPutStmt(), e);
    }
}
Also used : MappedDatastoreException(org.datanucleus.store.rdbms.exceptions.MappedDatastoreException) ExecutionContext(org.datanucleus.ExecutionContext) SQLException(java.sql.SQLException) PreparedStatement(java.sql.PreparedStatement) SQLController(org.datanucleus.store.rdbms.SQLController) JoinTable(org.datanucleus.store.rdbms.table.JoinTable)

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