Search in sources :

Example 21 with SQLController

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

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

the class JoinMapStore method removeInternal.

protected void removeInternal(ObjectProvider op, Object key) {
    ExecutionContext ec = op.getExecutionContext();
    try {
        ManagedConnection mconn = storeMgr.getConnectionManager().getConnection(ec);
        SQLController sqlControl = storeMgr.getSQLController();
        try {
            PreparedStatement ps = sqlControl.getStatementForUpdate(mconn, removeStmt, false);
            try {
                int jdbcPosition = 1;
                jdbcPosition = BackingStoreHelper.populateOwnerInStatement(op, ec, ps, jdbcPosition, this);
                BackingStoreHelper.populateKeyInStatement(ec, ps, key, jdbcPosition, keyMapping);
                sqlControl.executeStatementUpdate(ec, mconn, removeStmt, ps, true);
            } finally {
                sqlControl.closeStatement(mconn, ps);
            }
        } finally {
            mconn.release();
        }
    } catch (SQLException e) {
        throw new NucleusDataStoreException(Localiser.msg("056012", removeStmt), e);
    }
}
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 23 with SQLController

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

the class JoinMapStore method getValue.

/**
 * Method to retrieve a value from the Map given the key.
 * @param ownerOP ObjectProvider for the owner of the map.
 * @param key The key to retrieve the value for.
 * @return The value for this key
 * @throws NoSuchElementException if the value for the key was not found
 */
protected V getValue(ObjectProvider ownerOP, Object key) throws NoSuchElementException {
    if (!validateKeyForReading(ownerOP, key)) {
        return null;
    }
    ExecutionContext ec = ownerOP.getExecutionContext();
    if (getStmtLocked == 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 = getSQLStatementForGet(ownerOP);
            getStmtUnlocked = sqlStmt.getSQLText().toSQL();
            sqlStmt.addExtension(SQLStatement.EXTENSION_LOCK_FOR_UPDATE, true);
            getStmtLocked = sqlStmt.getSQLText().toSQL();
        }
    }
    Transaction tx = ec.getTransaction();
    String stmt = (tx.getSerializeRead() != null && tx.getSerializeRead() ? getStmtLocked : getStmtUnlocked);
    Object value = null;
    try {
        ManagedConnection mconn = storeMgr.getConnectionManager().getConnection(ec);
        SQLController sqlControl = storeMgr.getSQLController();
        try {
            // Create the statement and supply owner/key params
            PreparedStatement ps = sqlControl.getStatementForQuery(mconn, stmt);
            StatementMappingIndex ownerIdx = getMappingParams.getMappingForParameter("owner");
            int numParams = ownerIdx.getNumberOfParameterOccurrences();
            for (int paramInstance = 0; paramInstance < numParams; paramInstance++) {
                ownerIdx.getMapping().setObject(ec, ps, ownerIdx.getParameterPositionsForOccurrence(paramInstance), ownerOP.getObject());
            }
            StatementMappingIndex keyIdx = getMappingParams.getMappingForParameter("key");
            numParams = keyIdx.getNumberOfParameterOccurrences();
            for (int paramInstance = 0; paramInstance < numParams; paramInstance++) {
                keyIdx.getMapping().setObject(ec, ps, keyIdx.getParameterPositionsForOccurrence(paramInstance), key);
            }
            try {
                ResultSet rs = sqlControl.executeStatementQuery(ec, mconn, stmt, ps);
                try {
                    boolean found = rs.next();
                    if (!found) {
                        throw new NoSuchElementException();
                    }
                    if (valuesAreEmbedded || valuesAreSerialised) {
                        int[] param = new int[valueMapping.getNumberOfDatastoreMappings()];
                        for (int i = 0; i < param.length; ++i) {
                            param[i] = i + 1;
                        }
                        if (valueMapping instanceof SerialisedPCMapping || valueMapping instanceof SerialisedReferenceMapping || valueMapping instanceof EmbeddedKeyPCMapping) {
                            // Value = Serialised
                            int ownerFieldNumber = ((JoinTable) mapTable).getOwnerMemberMetaData().getAbsoluteFieldNumber();
                            value = valueMapping.getObject(ec, rs, param, ownerOP, ownerFieldNumber);
                        } else {
                            // Value = Non-PC
                            value = valueMapping.getObject(ec, rs, param);
                        }
                    } else if (valueMapping instanceof ReferenceMapping) {
                        // Value = Reference (Interface/Object)
                        int[] param = new int[valueMapping.getNumberOfDatastoreMappings()];
                        for (int i = 0; i < param.length; ++i) {
                            param[i] = i + 1;
                        }
                        value = valueMapping.getObject(ec, rs, param);
                    } else {
                        // Value = PC
                        ResultObjectFactory rof = new PersistentClassROF(ec, rs, false, getMappingDef, valueCmd, clr.classForName(valueType));
                        value = rof.getObject();
                    }
                    JDBCUtils.logWarnings(rs);
                } finally {
                    rs.close();
                }
            } finally {
                sqlControl.closeStatement(mconn, ps);
            }
        } finally {
            mconn.release();
        }
    } catch (SQLException e) {
        throw new NucleusDataStoreException(Localiser.msg("056014", stmt), e);
    }
    return (V) value;
}
Also used : SerialisedReferenceMapping(org.datanucleus.store.rdbms.mapping.java.SerialisedReferenceMapping) 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) SerialisedReferenceMapping(org.datanucleus.store.rdbms.mapping.java.SerialisedReferenceMapping) 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) SerialisedPCMapping(org.datanucleus.store.rdbms.mapping.java.SerialisedPCMapping) NoSuchElementException(java.util.NoSuchElementException) EmbeddedKeyPCMapping(org.datanucleus.store.rdbms.mapping.java.EmbeddedKeyPCMapping)

Example 24 with SQLController

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

Example 25 with SQLController

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

the class JoinPersistableRelationStore method add.

/* (non-Javadoc)
     * @see org.datanucleus.store.scostore.PersistableRelationStore#add(org.datanucleus.store.ObjectProvider, org.datanucleus.store.ObjectProvider)
     */
public boolean add(ObjectProvider op1, ObjectProvider op2) {
    String addStmt = getAddStmt();
    ExecutionContext ec = op1.getExecutionContext();
    SQLController sqlControl = storeMgr.getSQLController();
    try {
        ManagedConnection mconn = storeMgr.getConnectionManager().getConnection(ec);
        PreparedStatement ps = sqlControl.getStatementForUpdate(mconn, addStmt, false);
        try {
            // Insert the join table row
            int jdbcPosition = 1;
            jdbcPosition = populateOwnerInStatement(op1, ec, ps, jdbcPosition, joinTable);
            BackingStoreHelper.populateElementInStatement(ec, ps, op2.getObject(), jdbcPosition, joinTable.getRelatedMapping());
            // Execute the statement
            int[] nums = sqlControl.executeStatementUpdate(ec, mconn, addStmt, 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 inserting row into 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)

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