use of org.datanucleus.store.rdbms.SQLController in project datanucleus-rdbms by datanucleus.
the class FKMapStore 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 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
value = valueMapping.getObject(ec, rs, param, ownerOP, ((JoinTable) mapTable).getOwnerMemberMetaData().getAbsoluteFieldNumber());
} 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;
}
use of org.datanucleus.store.rdbms.SQLController in project datanucleus-rdbms by datanucleus.
the class JoinListStore method internalRemove.
private int[] internalRemove(ObjectProvider op, ManagedConnection conn, boolean batched, Object element, boolean executeNow) throws MappedDatastoreException {
ExecutionContext ec = op.getExecutionContext();
SQLController sqlControl = storeMgr.getSQLController();
String removeStmt = getRemoveStmt(element);
try {
PreparedStatement ps = sqlControl.getStatementForUpdate(conn, removeStmt, batched);
try {
int jdbcPosition = 1;
jdbcPosition = BackingStoreHelper.populateOwnerInStatement(op, ec, ps, jdbcPosition, this);
jdbcPosition = BackingStoreHelper.populateElementForWhereClauseInStatement(ec, ps, element, jdbcPosition, elementMapping);
if (relationDiscriminatorMapping != null) {
jdbcPosition = BackingStoreHelper.populateRelationDiscriminatorInStatement(ec, ps, jdbcPosition, this);
}
// Execute the statement
return sqlControl.executeStatementUpdate(ec, conn, removeStmt, ps, executeNow);
} finally {
sqlControl.closeStatement(conn, ps);
}
} catch (SQLException sqle) {
throw new MappedDatastoreException("SQLException", sqle);
}
}
use of org.datanucleus.store.rdbms.SQLController in project datanucleus-rdbms by datanucleus.
the class JoinListStore method removeAll.
/**
* Remove all elements from a collection from the association owner vs
* elements. Performs the removal in 3 steps. The first gets the indices
* that will be removed (and the highest index present). The second step
* removes these elements from the list. The third step updates the indices
* of the remaining indices to fill the holes created.
* @param op ObjectProvider
* @param elements Collection of elements to remove
* @return Whether the database was updated
*/
public boolean removeAll(ObjectProvider op, Collection elements, int size) {
if (elements == null || elements.size() == 0) {
return false;
}
// Get the current size of the list (and hence maximum index size)
int currentListSize = size(op);
// Get the indices of the elements we are going to remove (highest first)
int[] indices = getIndicesOf(op, elements);
if (indices == null) {
return false;
}
boolean modified = false;
SQLController sqlControl = storeMgr.getSQLController();
ExecutionContext ec = op.getExecutionContext();
// Remove the specified elements from the join table
String removeAllStmt = getRemoveAllStmt(elements);
try {
ManagedConnection mconn = storeMgr.getConnectionManager().getConnection(ec);
try {
PreparedStatement ps = sqlControl.getStatementForUpdate(mconn, removeAllStmt, false);
try {
int jdbcPosition = 1;
Iterator iter = elements.iterator();
while (iter.hasNext()) {
Object element = iter.next();
jdbcPosition = BackingStoreHelper.populateOwnerInStatement(op, ec, ps, jdbcPosition, this);
jdbcPosition = BackingStoreHelper.populateElementForWhereClauseInStatement(ec, ps, element, jdbcPosition, elementMapping);
if (relationDiscriminatorMapping != null) {
jdbcPosition = BackingStoreHelper.populateRelationDiscriminatorInStatement(ec, ps, jdbcPosition, this);
}
}
int[] number = sqlControl.executeStatementUpdate(ec, mconn, removeAllStmt, ps, true);
if (number[0] > 0) {
modified = true;
}
} finally {
sqlControl.closeStatement(mconn, ps);
}
} finally {
mconn.release();
}
} catch (SQLException e) {
NucleusLogger.DATASTORE.error(e);
throw new NucleusDataStoreException(Localiser.msg("056012", removeAllStmt), e);
}
// Shift the remaining indices to remove the holes in ordering
try {
boolean batched = storeMgr.allowsBatching();
ManagedConnection mconn = storeMgr.getConnectionManager().getConnection(ec);
try {
for (int i = 0; i < currentListSize; i++) {
// Find the number of deleted indexes above this index
int shift = 0;
boolean removed = false;
for (int j = 0; j < indices.length; j++) {
if (indices[j] == i) {
removed = true;
break;
}
if (indices[j] < i) {
shift++;
}
}
if (!removed && shift > 0) {
internalShift(op, mconn, batched, i, -1 * shift, (i == currentListSize - 1));
}
}
} finally {
mconn.release();
}
} catch (MappedDatastoreException e) {
NucleusLogger.DATASTORE.error(e);
throw new NucleusDataStoreException(Localiser.msg("056012", removeAllStmt), e);
}
// Dependent field
boolean dependent = getOwnerMemberMetaData().getCollection().isDependentElement();
if (getOwnerMemberMetaData().isCascadeRemoveOrphans()) {
dependent = true;
}
if (dependent) {
// "delete-dependent" : delete elements if the collection is marked as dependent
// TODO What if the collection contains elements that are not in the List ? should not delete them
op.getExecutionContext().deleteObjects(elements.toArray());
}
return modified;
}
use of org.datanucleus.store.rdbms.SQLController 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);
}
}
use of org.datanucleus.store.rdbms.SQLController 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;
}
Aggregations