use of org.datanucleus.state.DNStateManager in project datanucleus-rdbms by datanucleus.
the class FlushReferential method execute.
/* (non-Javadoc)
* @see org.datanucleus.FlushOrdered#execute(org.datanucleus.ExecutionContext, java.util.Collection, java.util.Collection, org.datanucleus.flush.OperationQueue)
*/
@Override
public List<NucleusOptimisticException> execute(ExecutionContext ec, Collection<DNStateManager> primarySMs, Collection<DNStateManager> secondarySMs, OperationQueue smQueue) {
List<NucleusOptimisticException> flushExcps = null;
// Phase 1 : Find all objects that have no relations or external FKs and process first
Set<DNStateManager> unrelatedSMs = null;
if (primarySMs != null) {
Iterator<DNStateManager> opIter = primarySMs.iterator();
while (opIter.hasNext()) {
DNStateManager sm = opIter.next();
if (!sm.isEmbedded() && isClassSuitableForBatching(ec, sm.getClassMetaData())) {
if (unrelatedSMs == null) {
unrelatedSMs = new HashSet<>();
}
unrelatedSMs.add(sm);
opIter.remove();
}
}
}
if (secondarySMs != null) {
Iterator<DNStateManager> smIter = secondarySMs.iterator();
while (smIter.hasNext()) {
DNStateManager sm = smIter.next();
if (!sm.isEmbedded() && isClassSuitableForBatching(ec, sm.getClassMetaData())) {
if (unrelatedSMs == null) {
unrelatedSMs = new HashSet<>();
}
unrelatedSMs.add(sm);
smIter.remove();
}
}
}
if (unrelatedSMs != null) {
// Process DELETEs, then INSERTs, then UPDATEs
FlushNonReferential groupedFlush = new FlushNonReferential();
flushExcps = groupedFlush.flushDeleteInsertUpdateGrouped(unrelatedSMs, ec);
}
// Phase 2 : Fallback to FlushOrdered handling for remaining objects
List<NucleusOptimisticException> excps = super.execute(ec, primarySMs, secondarySMs, smQueue);
// Return any exceptions
if (excps != null) {
if (flushExcps == null) {
flushExcps = excps;
} else {
flushExcps.addAll(excps);
}
}
return flushExcps;
}
use of org.datanucleus.state.DNStateManager in project datanucleus-rdbms by datanucleus.
the class FKListStore method listIterator.
/**
* Accessor for an iterator through the list elements.
* @param ownerSM StateManager for the owner.
* @param startIdx The start index in the list (only for indexed lists)
* @param endIdx The end index in the list (only for indexed lists)
* @return The List Iterator
*/
@Override
protected ListIterator<E> listIterator(DNStateManager ownerSM, int startIdx, int endIdx) {
ExecutionContext ec = ownerSM.getExecutionContext();
if (elementInfo == null || elementInfo.length == 0) {
return null;
}
// Generate the statement. Note that this is not cached since depends on the current FetchPlan and other things
ElementIteratorStatement iterStmt = getIteratorStatement(ownerSM.getExecutionContext(), ec.getFetchPlan(), true, startIdx, endIdx);
SelectStatement sqlStmt = iterStmt.getSelectStatement();
StatementClassMapping resultMapping = iterStmt.getElementClassMapping();
// 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.getNumberOfColumnMappings()];
for (int k = 0; k < ownerMapping.getNumberOfColumnMappings(); k++) {
paramPositions[k] = inputParamNum++;
}
ownerIdx.addParameterOccurrence(paramPositions);
}
} else {
int[] paramPositions = new int[ownerMapping.getNumberOfColumnMappings()];
for (int k = 0; k < ownerMapping.getNumberOfColumnMappings(); k++) {
paramPositions[k] = inputParamNum++;
}
ownerIdx.addParameterOccurrence(paramPositions);
}
Boolean serializeRead = ec.getTransaction().getSerializeRead();
if (serializeRead != null && serializeRead) {
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
DNStateManager stmtOwnerSM = BackingStoreHelper.getOwnerStateManagerForBackingStore(ownerSM);
int numParams = ownerIdx.getNumberOfParameterOccurrences();
for (int paramInstance = 0; paramInstance < numParams; paramInstance++) {
ownerIdx.getMapping().setObject(ec, ps, ownerIdx.getParameterPositionsForOccurrence(paramInstance), stmtOwnerSM.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, ec.getFetchPlan(), resultMapping, elementCmd, clr.classForName(elementType));
return new ListStoreIterator(ownerSM, rs, rof, this);
} finally {
rs.close();
}
} finally {
sqlControl.closeStatement(mconn, ps);
}
} finally {
mconn.release();
}
} catch (SQLException e) {
throw new NucleusDataStoreException(Localiser.msg("056006", stmt), e);
}
}
use of org.datanucleus.state.DNStateManager 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 ownerSM StateManager for the owner
*/
@Override
public void clear(DNStateManager ownerSM) {
boolean deleteElements = false;
boolean dependent = (ownerMemberMetaData.getCollection().isDependentElement() || ownerMemberMetaData.isCascadeRemoveOrphans());
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;
}
}
ExecutionContext ec = ownerSM.getExecutionContext();
if (deleteElements) {
// Find elements present in the datastore and delete them one-by-one
Iterator elementsIter = iterator(ownerSM);
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)
DNStateManager objSM = ec.findStateManager(element);
objSM.flush();
} else {
// Element not yet marked for deletion so go through the normal process
ec.deleteObjectInternal(element);
}
}
}
} else {
boolean ownerSoftDelete = ownerSM.getClassMetaData().isSoftDelete();
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(ownerSM, 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);
}
}
}
}
use of org.datanucleus.state.DNStateManager in project datanucleus-rdbms by datanucleus.
the class FKSetStore method iterator.
@Override
public Iterator<E> iterator(DNStateManager ownerSM) {
if (elementInfo == null || elementInfo.length == 0) {
return null;
}
ExecutionContext ec = ownerSM.getExecutionContext();
// Generate the statement, and statement mapping/parameter information
ElementIteratorStatement iterStmt = getIteratorStatement(ec, ec.getFetchPlan(), true);
SelectStatement sqlStmt = iterStmt.getSelectStatement();
StatementClassMapping iteratorMappingClass = iterStmt.getElementClassMapping();
// 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.getNumberOfColumnMappings()];
for (int k = 0; k < paramPositions.length; k++) {
paramPositions[k] = inputParamNum++;
}
ownerStmtMapIdx.addParameterOccurrence(paramPositions);
}
} else {
int[] paramPositions = new int[ownerMapping.getNumberOfColumnMappings()];
for (int k = 0; k < paramPositions.length; 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
DNStateManager stmtOwnerSM = BackingStoreHelper.getOwnerStateManagerForBackingStore(ownerSM);
int numParams = ownerStmtMapIdx.getNumberOfParameterOccurrences();
for (int paramInstance = 0; paramInstance < numParams; paramInstance++) {
ownerStmtMapIdx.getMapping().setObject(ec, ps, ownerStmtMapIdx.getParameterPositionsForOccurrence(paramInstance), stmtOwnerSM.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, ec.getFetchPlan(), iteratorMappingClass, elementCmd, clr.classForName(elementType));
return new CollectionStoreIterator(ownerSM, rs, rof, this);
} finally {
rs.close();
}
} finally {
sqlControl.closeStatement(mconn, ps);
}
} finally {
mconn.release();
}
} catch (SQLException e) {
throw new NucleusDataStoreException(Localiser.msg("056006", stmt), e);
}
}
use of org.datanucleus.state.DNStateManager in project datanucleus-rdbms by datanucleus.
the class JoinSetStore method addAll.
@Override
public boolean addAll(DNStateManager sm, Collection<E> elements, int size) {
if (elements == null || elements.size() == 0) {
return false;
}
List exceptions = new ArrayList();
boolean batched = (elements.size() > 1);
// Validate all elements for writing
ExecutionContext ec = sm.getExecutionContext();
Iterator<E> iter = elements.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
// Managed Relations : make sure we have consistency of relation
DNStateManager elementSM = sm.getExecutionContext().findStateManager(element);
if (elementSM != null) {
AbstractMemberMetaData[] relatedMmds = ownerMemberMetaData.getRelatedMemberMetaData(clr);
Object elementOwner = elementSM.provideField(relatedMmds[0].getAbsoluteFieldNumber());
if (elementOwner == null) {
// No owner, so correct it
NucleusLogger.PERSISTENCE.info(Localiser.msg("056037", sm.getObjectAsPrintable(), ownerMemberMetaData.getFullFieldName(), StringUtils.toJVMIDString(elementSM.getObject())));
elementSM.replaceField(relatedMmds[0].getAbsoluteFieldNumber(), sm.getObject());
} else if (elementOwner != sm.getObject() && sm.getReferencedPC() == null) {
// Inconsistent owner, so throw exception
throw new NucleusUserException(Localiser.msg("056038", sm.getObjectAsPrintable(), ownerMemberMetaData.getFullFieldName(), StringUtils.toJVMIDString(elementSM.getObject()), StringUtils.toJVMIDString(elementOwner)));
}
}
}
}
boolean modified = false;
ManagedConnection mconn = storeMgr.getConnectionManager().getConnection(ec);
try {
SQLController sqlControl = storeMgr.getSQLController();
try {
// Process all waiting batched statements before we start our work
sqlControl.processStatementsForConnection(mconn);
} catch (SQLException e) {
throw new NucleusDataStoreException("SQLException", e);
}
int nextOrderID = orderMapping != null ? getNextIDForOrderColumn(sm) : 0;
// Loop through all elements to be added
iter = elements.iterator();
E element = null;
while (iter.hasNext()) {
element = iter.next();
// Add the row to the join table
boolean toBeInserted = true;
if (relationType == RelationType.MANY_TO_MANY_BI) {
toBeInserted = !elementAlreadyContainsOwnerInMtoN(sm, element);
}
if (toBeInserted) {
int[] rc = doInternalAdd(sm, element, mconn, batched, nextOrderID, !batched || (batched && !iter.hasNext()));
if (rc != null) {
for (int i = 0; i < rc.length; i++) {
if (rc[i] > 0) {
// At least one record was inserted
modified = true;
}
}
}
nextOrderID++;
}
}
} finally {
mconn.release();
}
if (!exceptions.isEmpty()) {
// Throw all exceptions received as the cause of a NucleusDataStoreException so the user can see which record(s) didn't persist
String msg = Localiser.msg("056009", ((Exception) exceptions.get(0)).getMessage());
NucleusLogger.DATASTORE.error(msg);
throw new NucleusDataStoreException(msg, (Throwable[]) exceptions.toArray(new Throwable[exceptions.size()]), sm.getObject());
}
return modified;
}
Aggregations