Search in sources :

Example 6 with MappedDatastoreException

use of org.datanucleus.store.rdbms.exceptions.MappedDatastoreException in project datanucleus-rdbms by datanucleus.

the class JoinListStore method internalRemove.

/**
 * Convenience method to remove the specified element from the List.
 * @param element The element
 * @param ownerOP ObjectProvider of the owner
 * @param size Current size of list if known. -1 if not known
 * @return Whether the List was modified
 */
protected boolean internalRemove(ObjectProvider ownerOP, Object element, int size) {
    boolean modified = false;
    if (indexedList) {
        // Indexed List, so retrieve the index of the element and remove the object
        // Get the indices of the elements to remove in reverse order (highest first)
        // This is done because the element could be duplicated in the list.
        Collection elements = new ArrayList();
        elements.add(element);
        int[] indices = getIndicesOf(ownerOP, elements);
        if (indices == null) {
            return false;
        }
        // TODO : Change this to remove all in one go and then shift once
        for (int i = 0; i < indices.length; i++) {
            internalRemoveAt(ownerOP, indices[i], size);
            modified = true;
        }
    } else {
        // Ordered List - just remove the list item since no indexing present
        ExecutionContext ec = ownerOP.getExecutionContext();
        ManagedConnection mconn = storeMgr.getConnectionManager().getConnection(ec);
        try {
            int[] rcs = internalRemove(ownerOP, mconn, false, element, true);
            if (rcs != null) {
                if (rcs[0] > 0) {
                    modified = true;
                }
            }
        } catch (MappedDatastoreException sqe) {
            String msg = Localiser.msg("056012", sqe.getMessage());
            NucleusLogger.DATASTORE.error(msg, sqe.getCause());
            throw new NucleusDataStoreException(msg, sqe, ownerOP.getObject());
        } finally {
            mconn.release();
        }
    }
    return modified;
}
Also used : MappedDatastoreException(org.datanucleus.store.rdbms.exceptions.MappedDatastoreException) NucleusDataStoreException(org.datanucleus.exceptions.NucleusDataStoreException) ExecutionContext(org.datanucleus.ExecutionContext) ArrayList(java.util.ArrayList) Collection(java.util.Collection) ManagedConnection(org.datanucleus.store.connection.ManagedConnection)

Example 7 with MappedDatastoreException

use of org.datanucleus.store.rdbms.exceptions.MappedDatastoreException in project datanucleus-rdbms by datanucleus.

the class JoinListStore method listIterator.

/**
 * Accessor for an iterator through the list elements.
 * @param ownerOP ObjectProvider for the owner
 * @param startIdx The start point in the list (only for indexed lists).
 * @param endIdx End index in the list (only for indexed lists).
 * @return The List Iterator
 */
protected ListIterator<E> listIterator(ObjectProvider ownerOP, int startIdx, int endIdx) {
    ExecutionContext ec = ownerOP.getExecutionContext();
    Transaction tx = ec.getTransaction();
    // Generate the statement. Note that this is not cached since depends on the current FetchPlan and other things
    IteratorStatement iterStmt = getIteratorStatement(ownerOP.getExecutionContext(), ec.getFetchPlan(), true, startIdx, endIdx);
    SelectStatement sqlStmt = iterStmt.getSelectStatement();
    StatementClassMapping resultMapping = iterStmt.getStatementClassMapping();
    // 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);
    }
    if (tx.getSerializeRead() != null && tx.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 ListStoreIterator(ownerOP, rs, null, this);
                    } else if (elementMapping instanceof ReferenceMapping) {
                        // No ResultObjectFactory needed - handled by SetStoreIterator
                        return new ListStoreIterator(ownerOP, rs, null, this);
                    } else {
                        ResultObjectFactory rof = new PersistentClassROF(ec, rs, false, resultMapping, elementCmd, clr.classForName(elementType));
                        return new ListStoreIterator(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) Transaction(org.datanucleus.Transaction) PersistentClassROF(org.datanucleus.store.rdbms.query.PersistentClassROF) ResultSet(java.sql.ResultSet) ManagedConnection(org.datanucleus.store.connection.ManagedConnection) ObjectProvider(org.datanucleus.state.ObjectProvider)

Example 8 with MappedDatastoreException

use of org.datanucleus.store.rdbms.exceptions.MappedDatastoreException in project datanucleus-rdbms by datanucleus.

the class JoinListStore method internalAdd.

/**
 * Internal method to add element(s) to the List.
 * Performs the add in 2 steps.
 * <ol>
 * <li>Shift all existing elements into their new positions so we can insert.</li>
 * <li>Insert all new elements directly at their desired positions</li>
 * </ol>
 * Both steps can be batched (separately).
 * @param op The ObjectProvider
 * @param start The start location (if required)
 * @param atEnd Whether to add the element at the end
 * @param c The collection of objects to add.
 * @param size Current size of list if known. -1 if not known
 * @return Whether it was successful
 */
protected boolean internalAdd(ObjectProvider op, int start, boolean atEnd, Collection<E> c, int size) {
    if (c == null || c.size() == 0) {
        return true;
    }
    if (relationType == RelationType.MANY_TO_MANY_BI && ownerMemberMetaData.getMappedBy() != null) {
        // M-N non-owner : don't add from this side to avoid duplicates
        return true;
    }
    // Calculate the amount we need to shift any existing elements by
    // This is used where inserting between existing elements and have to shift down all elements after the start point
    int shift = c.size();
    // check all elements are valid for persisting and exist (persistence-by-reachability)
    ExecutionContext ec = op.getExecutionContext();
    Iterator iter = c.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
            ObjectProvider elementOP = ec.findObjectProvider(element);
            if (elementOP != null) {
                AbstractMemberMetaData[] relatedMmds = ownerMemberMetaData.getRelatedMemberMetaData(clr);
                // TODO Cater for more than 1 related field
                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)));
                }
            }
        }
    }
    // Check what we have persistent already
    int currentListSize = 0;
    if (size < 0) {
        // Get the current size from the datastore
        currentListSize = size(op);
    } else {
        currentListSize = size;
    }
    // Check for dynamic schema updates prior to addition
    if (storeMgr.getBooleanObjectProperty(RDBMSPropertyNames.PROPERTY_RDBMS_DYNAMIC_SCHEMA_UPDATES).booleanValue()) {
        DynamicSchemaFieldManager dynamicSchemaFM = new DynamicSchemaFieldManager(storeMgr, op);
        dynamicSchemaFM.storeObjectField(getOwnerMemberMetaData().getAbsoluteFieldNumber(), c);
        if (dynamicSchemaFM.hasPerformedSchemaUpdates()) {
            invalidateAddStmt();
        }
    }
    String addStmt = getAddStmtForJoinTable();
    try {
        ManagedConnection mconn = storeMgr.getConnectionManager().getConnection(ec);
        SQLController sqlControl = storeMgr.getSQLController();
        try {
            // Shift any existing elements so that we can insert the new element(s) at their position
            if (!atEnd && start != currentListSize) {
                boolean batched = currentListSize - start > 0;
                for (int i = currentListSize - 1; i >= start; i--) {
                    // Shift the index for this row by "shift"
                    internalShift(op, mconn, batched, i, shift, (i == start));
                }
            } else {
                start = currentListSize;
            }
            // Insert the elements at their required location
            int jdbcPosition = 1;
            boolean batched = (c.size() > 1);
            Iterator elemIter = c.iterator();
            while (elemIter.hasNext()) {
                Object element = elemIter.next();
                PreparedStatement ps = sqlControl.getStatementForUpdate(mconn, addStmt, batched);
                try {
                    jdbcPosition = 1;
                    jdbcPosition = BackingStoreHelper.populateOwnerInStatement(op, ec, ps, jdbcPosition, this);
                    jdbcPosition = BackingStoreHelper.populateElementInStatement(ec, ps, element, jdbcPosition, elementMapping);
                    if (orderMapping != null) {
                        jdbcPosition = BackingStoreHelper.populateOrderInStatement(ec, ps, start, jdbcPosition, orderMapping);
                    }
                    if (relationDiscriminatorMapping != null) {
                        jdbcPosition = BackingStoreHelper.populateRelationDiscriminatorInStatement(ec, ps, jdbcPosition, this);
                    }
                    start++;
                    // Execute the statement
                    sqlControl.executeStatementUpdate(ec, mconn, addStmt, ps, !iter.hasNext());
                } finally {
                    sqlControl.closeStatement(mconn, ps);
                }
            }
        } finally {
            mconn.release();
        }
    } catch (SQLException | MappedDatastoreException e) {
        throw new NucleusDataStoreException(Localiser.msg("056009", addStmt), e);
    }
    return true;
}
Also used : MappedDatastoreException(org.datanucleus.store.rdbms.exceptions.MappedDatastoreException) SQLException(java.sql.SQLException) NucleusUserException(org.datanucleus.exceptions.NucleusUserException) PreparedStatement(java.sql.PreparedStatement) SQLController(org.datanucleus.store.rdbms.SQLController) NucleusDataStoreException(org.datanucleus.exceptions.NucleusDataStoreException) ExecutionContext(org.datanucleus.ExecutionContext) DynamicSchemaFieldManager(org.datanucleus.store.rdbms.fieldmanager.DynamicSchemaFieldManager) ListIterator(java.util.ListIterator) Iterator(java.util.Iterator) ObjectProvider(org.datanucleus.state.ObjectProvider) ManagedConnection(org.datanucleus.store.connection.ManagedConnection) AbstractMemberMetaData(org.datanucleus.metadata.AbstractMemberMetaData)

Example 9 with MappedDatastoreException

use of org.datanucleus.store.rdbms.exceptions.MappedDatastoreException in project datanucleus-rdbms by datanucleus.

the class JoinMapStore method putAll.

/**
 * Method to put all elements from a Map into our Map.
 * @param op ObjectProvider for the Map
 * @param m The Map to add
 */
public void putAll(ObjectProvider op, Map<? extends K, ? extends V> m) {
    if (m == null || m.size() == 0) {
        return;
    }
    Set<Map.Entry> puts = new HashSet<>();
    Set<Map.Entry> updates = new HashSet<>();
    Iterator i = m.entrySet().iterator();
    while (i.hasNext()) {
        Map.Entry e = (Map.Entry) i.next();
        Object key = e.getKey();
        Object value = e.getValue();
        // Make sure the related objects are persisted (persistence-by-reachability)
        validateKeyForWriting(op, key);
        validateValueForWriting(op, value);
        // Check if this is a new entry, or an update
        try {
            Object oldValue = getValue(op, key);
            if (oldValue != value) {
                updates.add(e);
            }
        } catch (NoSuchElementException nsee) {
            puts.add(e);
        }
    }
    boolean batched = allowsBatching();
    // Put any new entries
    if (puts.size() > 0) {
        try {
            ExecutionContext ec = op.getExecutionContext();
            ManagedConnection mconn = storeMgr.getConnectionManager().getConnection(ec);
            try {
                // Loop through all entries
                Iterator<Map.Entry> iter = puts.iterator();
                while (iter.hasNext()) {
                    // Add the row to the join table
                    Map.Entry entry = iter.next();
                    internalPut(op, mconn, batched, entry.getKey(), entry.getValue(), (!iter.hasNext()));
                }
            } finally {
                mconn.release();
            }
        } catch (MappedDatastoreException e) {
            throw new NucleusDataStoreException(Localiser.msg("056016", e.getMessage()), e);
        }
    }
    // Update any changed entries
    if (updates.size() > 0) {
        try {
            ExecutionContext ec = op.getExecutionContext();
            ManagedConnection mconn = storeMgr.getConnectionManager().getConnection(ec);
            try {
                // Loop through all entries
                Iterator<Map.Entry> iter = updates.iterator();
                while (iter.hasNext()) {
                    // Update the row in the join table
                    Map.Entry entry = iter.next();
                    internalUpdate(op, mconn, batched, entry.getKey(), entry.getValue(), !iter.hasNext());
                }
            } finally {
                mconn.release();
            }
        } catch (MappedDatastoreException mde) {
            throw new NucleusDataStoreException(Localiser.msg("056016", mde.getMessage()), mde);
        }
    }
}
Also used : MappedDatastoreException(org.datanucleus.store.rdbms.exceptions.MappedDatastoreException) NucleusDataStoreException(org.datanucleus.exceptions.NucleusDataStoreException) ExecutionContext(org.datanucleus.ExecutionContext) Iterator(java.util.Iterator) ManagedConnection(org.datanucleus.store.connection.ManagedConnection) Map(java.util.Map) NoSuchElementException(java.util.NoSuchElementException) HashSet(java.util.HashSet)

Example 10 with MappedDatastoreException

use of org.datanucleus.store.rdbms.exceptions.MappedDatastoreException in project datanucleus-rdbms by datanucleus.

the class JoinMapStore method internalUpdate.

/**
 * Method to process an "update" statement (where the key already has a 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 new value
 * @param executeNow Whether to execute the statement now or wait til any batch
 * @throws MappedDatastoreException Thrown if an error occurs
 */
protected void internalUpdate(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, updateStmt, 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);
            jdbcPosition = BackingStoreHelper.populateKeyInStatement(ec, ps, key, jdbcPosition, keyMapping);
            if (batched) {
                ps.addBatch();
            } else {
                sqlControl.executeStatementUpdate(ec, conn, updateStmt, ps, true);
            }
        } finally {
            sqlControl.closeStatement(conn, ps);
        }
    } catch (SQLException e) {
        throw new MappedDatastoreException(getUpdateStmt(), 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

ExecutionContext (org.datanucleus.ExecutionContext)27 MappedDatastoreException (org.datanucleus.store.rdbms.exceptions.MappedDatastoreException)27 NucleusDataStoreException (org.datanucleus.exceptions.NucleusDataStoreException)21 ManagedConnection (org.datanucleus.store.connection.ManagedConnection)21 SQLException (java.sql.SQLException)20 SQLController (org.datanucleus.store.rdbms.SQLController)20 PreparedStatement (java.sql.PreparedStatement)19 ResultSet (java.sql.ResultSet)9 ObjectProvider (org.datanucleus.state.ObjectProvider)9 StatementMappingIndex (org.datanucleus.store.rdbms.query.StatementMappingIndex)9 PersistentClassROF (org.datanucleus.store.rdbms.query.PersistentClassROF)8 ResultObjectFactory (org.datanucleus.store.rdbms.query.ResultObjectFactory)8 StatementClassMapping (org.datanucleus.store.rdbms.query.StatementClassMapping)6 SelectStatement (org.datanucleus.store.rdbms.sql.SelectStatement)6 Iterator (java.util.Iterator)5 Transaction (org.datanucleus.Transaction)5 ArrayList (java.util.ArrayList)4 List (java.util.List)3 ListIterator (java.util.ListIterator)3 NucleusException (org.datanucleus.exceptions.NucleusException)3