Search in sources :

Example 1 with DynamicSchemaFieldManager

use of org.datanucleus.store.rdbms.fieldmanager.DynamicSchemaFieldManager in project datanucleus-rdbms by datanucleus.

the class JoinListStore method set.

/**
 * Method to set an object in the List.
 * @param op ObjectProvider for the owner
 * @param index The item index
 * @param element What to set it to.
 * @param allowDependentField Whether to allow dependent field deletes
 * @return The value before setting.
 */
public E set(ObjectProvider op, int index, Object element, boolean allowDependentField) {
    ExecutionContext ec = op.getExecutionContext();
    validateElementForWriting(ec, element, null);
    // Find the original element at this position
    E oldElement = null;
    List fieldVal = (List) op.provideField(ownerMemberMetaData.getAbsoluteFieldNumber());
    if (fieldVal != null && fieldVal instanceof BackedSCO && ((BackedSCO) fieldVal).isLoaded()) {
        // Already loaded in the wrapper
        oldElement = (E) fieldVal.get(index);
    } else {
        oldElement = get(op, index);
    }
    // Check for dynamic schema updates prior to update
    if (storeMgr.getBooleanObjectProperty(RDBMSPropertyNames.PROPERTY_RDBMS_DYNAMIC_SCHEMA_UPDATES).booleanValue()) {
        DynamicSchemaFieldManager dynamicSchemaFM = new DynamicSchemaFieldManager(storeMgr, op);
        Collection coll = new ArrayList();
        coll.add(element);
        dynamicSchemaFM.storeObjectField(getOwnerMemberMetaData().getAbsoluteFieldNumber(), coll);
        if (dynamicSchemaFM.hasPerformedSchemaUpdates()) {
            setStmt = null;
        }
    }
    String theSetStmt = getSetStmt();
    try {
        ManagedConnection mconn = storeMgr.getConnectionManager().getConnection(ec);
        SQLController sqlControl = storeMgr.getSQLController();
        try {
            PreparedStatement ps = sqlControl.getStatementForUpdate(mconn, theSetStmt, false);
            try {
                int jdbcPosition = 1;
                jdbcPosition = BackingStoreHelper.populateElementInStatement(ec, ps, element, jdbcPosition, elementMapping);
                jdbcPosition = BackingStoreHelper.populateOwnerInStatement(op, ec, ps, jdbcPosition, this);
                if (getOwnerMemberMetaData().getOrderMetaData() != null && !getOwnerMemberMetaData().getOrderMetaData().isIndexedList()) {
                    // Ordered list, so can't easily do a set!!!
                    NucleusLogger.PERSISTENCE.warn("Calling List.addElement at a position for an ordered list is a stupid thing to do; the ordering is set my the ordering specification. Use an indexed list to do this correctly");
                } else {
                    jdbcPosition = BackingStoreHelper.populateOrderInStatement(ec, ps, index, jdbcPosition, orderMapping);
                }
                if (relationDiscriminatorMapping != null) {
                    jdbcPosition = BackingStoreHelper.populateRelationDiscriminatorInStatement(ec, ps, jdbcPosition, this);
                }
                sqlControl.executeStatementUpdate(ec, mconn, theSetStmt, ps, true);
            } finally {
                sqlControl.closeStatement(mconn, ps);
            }
        } finally {
            mconn.release();
        }
    } catch (SQLException e) {
        throw new NucleusDataStoreException(Localiser.msg("056015", theSetStmt), e);
    }
    // Dependent field
    CollectionMetaData collmd = ownerMemberMetaData.getCollection();
    boolean dependent = collmd.isDependentElement();
    if (ownerMemberMetaData.isCascadeRemoveOrphans()) {
        dependent = true;
    }
    if (dependent && !collmd.isEmbeddedElement() && allowDependentField) {
        if (oldElement != null && !contains(op, oldElement)) {
            // Delete the element if it is dependent and doesn't have a duplicate entry in the list
            ec.deleteObjectInternal(oldElement);
        }
    }
    return oldElement;
}
Also used : SQLException(java.sql.SQLException) ArrayList(java.util.ArrayList) PreparedStatement(java.sql.PreparedStatement) CollectionMetaData(org.datanucleus.metadata.CollectionMetaData) BackedSCO(org.datanucleus.store.types.wrappers.backed.BackedSCO) SQLController(org.datanucleus.store.rdbms.SQLController) NucleusDataStoreException(org.datanucleus.exceptions.NucleusDataStoreException) ExecutionContext(org.datanucleus.ExecutionContext) DynamicSchemaFieldManager(org.datanucleus.store.rdbms.fieldmanager.DynamicSchemaFieldManager) Collection(java.util.Collection) List(java.util.List) ArrayList(java.util.ArrayList) ManagedConnection(org.datanucleus.store.connection.ManagedConnection)

Example 2 with DynamicSchemaFieldManager

use of org.datanucleus.store.rdbms.fieldmanager.DynamicSchemaFieldManager 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 3 with DynamicSchemaFieldManager

use of org.datanucleus.store.rdbms.fieldmanager.DynamicSchemaFieldManager in project datanucleus-rdbms by datanucleus.

the class JoinSetStore method doInternalAdd.

protected int[] doInternalAdd(ObjectProvider op, E element, ManagedConnection conn, boolean batched, int orderId, boolean executeNow) throws MappedDatastoreException {
    // Check for dynamic schema updates prior to addition
    if (storeMgr.getBooleanObjectProperty(RDBMSPropertyNames.PROPERTY_RDBMS_DYNAMIC_SCHEMA_UPDATES).booleanValue()) {
        DynamicSchemaFieldManager dynamicSchemaFM = new DynamicSchemaFieldManager(storeMgr, op);
        Collection coll = new HashSet();
        coll.add(element);
        dynamicSchemaFM.storeObjectField(ownerMemberMetaData.getAbsoluteFieldNumber(), coll);
        if (dynamicSchemaFM.hasPerformedSchemaUpdates()) {
            invalidateAddStmt();
        }
    }
    String addStmt = getAddStmtForJoinTable();
    boolean notYetFlushedError = false;
    ExecutionContext ec = op.getExecutionContext();
    SQLController sqlControl = storeMgr.getSQLController();
    try {
        PreparedStatement ps = sqlControl.getStatementForUpdate(conn, addStmt, batched);
        try {
            // Insert the join table row
            int 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, orderId, jdbcPosition, orderMapping);
            }
            if (relationDiscriminatorMapping != null) {
                jdbcPosition = BackingStoreHelper.populateRelationDiscriminatorInStatement(ec, ps, jdbcPosition, this);
            }
            return sqlControl.executeStatementUpdate(ec, conn, addStmt, ps, executeNow);
        } catch (NotYetFlushedException nfe) {
            notYetFlushedError = true;
            throw nfe;
        } finally {
            if (notYetFlushedError) {
                sqlControl.abortStatementForConnection(conn, ps);
            } else {
                sqlControl.closeStatement(conn, ps);
            }
        }
    } catch (SQLException e) {
        throw new MappedDatastoreException(addStmt, e);
    }
}
Also used : MappedDatastoreException(org.datanucleus.store.rdbms.exceptions.MappedDatastoreException) ExecutionContext(org.datanucleus.ExecutionContext) DynamicSchemaFieldManager(org.datanucleus.store.rdbms.fieldmanager.DynamicSchemaFieldManager) SQLException(java.sql.SQLException) Collection(java.util.Collection) PreparedStatement(java.sql.PreparedStatement) NotYetFlushedException(org.datanucleus.exceptions.NotYetFlushedException) HashSet(java.util.HashSet) SQLController(org.datanucleus.store.rdbms.SQLController)

Example 4 with DynamicSchemaFieldManager

use of org.datanucleus.store.rdbms.fieldmanager.DynamicSchemaFieldManager in project datanucleus-rdbms by datanucleus.

the class RDBMSPersistenceHandler method checkForSchemaUpdatesForFieldsOfObject.

/**
 * Check if we need to update the schema before performing an insert/update.
 * This is typically of use where the user has an interface field and some new implementation
 * is trying to be persisted to that field, so we need to update the schema.
 * @param sm ObjectProvider for the object
 * @param fieldNumbers The fields to check for required schema updates
 */
private void checkForSchemaUpdatesForFieldsOfObject(ObjectProvider sm, int[] fieldNumbers) {
    if (storeMgr.getBooleanObjectProperty(RDBMSPropertyNames.PROPERTY_RDBMS_DYNAMIC_SCHEMA_UPDATES).booleanValue()) {
        DynamicSchemaFieldManager dynamicSchemaFM = new DynamicSchemaFieldManager((RDBMSStoreManager) storeMgr, sm);
        sm.provideFields(fieldNumbers, dynamicSchemaFM);
        if (dynamicSchemaFM.hasPerformedSchemaUpdates()) {
            requestsByID.clear();
        }
    }
}
Also used : DynamicSchemaFieldManager(org.datanucleus.store.rdbms.fieldmanager.DynamicSchemaFieldManager)

Aggregations

DynamicSchemaFieldManager (org.datanucleus.store.rdbms.fieldmanager.DynamicSchemaFieldManager)4 PreparedStatement (java.sql.PreparedStatement)3 SQLException (java.sql.SQLException)3 ExecutionContext (org.datanucleus.ExecutionContext)3 SQLController (org.datanucleus.store.rdbms.SQLController)3 Collection (java.util.Collection)2 NucleusDataStoreException (org.datanucleus.exceptions.NucleusDataStoreException)2 ManagedConnection (org.datanucleus.store.connection.ManagedConnection)2 MappedDatastoreException (org.datanucleus.store.rdbms.exceptions.MappedDatastoreException)2 ArrayList (java.util.ArrayList)1 HashSet (java.util.HashSet)1 Iterator (java.util.Iterator)1 List (java.util.List)1 ListIterator (java.util.ListIterator)1 NotYetFlushedException (org.datanucleus.exceptions.NotYetFlushedException)1 NucleusUserException (org.datanucleus.exceptions.NucleusUserException)1 AbstractMemberMetaData (org.datanucleus.metadata.AbstractMemberMetaData)1 CollectionMetaData (org.datanucleus.metadata.CollectionMetaData)1 ObjectProvider (org.datanucleus.state.ObjectProvider)1 BackedSCO (org.datanucleus.store.types.wrappers.backed.BackedSCO)1