use of org.datanucleus.store.rdbms.mapping.java.ReferenceMapping in project datanucleus-rdbms by datanucleus.
the class FetchRequest method processMembersOfClass.
/**
* Method to process the supplied members of the class, adding to the SQLStatement as required.
* Can recurse if some of the requested fields are persistent objects in their own right, so we
* take the opportunity to retrieve some of their fields.
* @param sqlStatement Statement being built
* @param mmds Meta-data for the required fields/properties
* @param table The table to look for member mappings
* @param sqlTbl The table in the SQL statement to use for selects
* @param mappingDef Mapping definition for the result
* @param fetchCallbacks Any additional required callbacks are added here
* @param clr ClassLoader resolver
* @return Number of fields being fetched
*/
protected int processMembersOfClass(SelectStatement sqlStatement, AbstractMemberMetaData[] mmds, DatastoreClass table, SQLTable sqlTbl, StatementClassMapping mappingDef, Collection fetchCallbacks, ClassLoaderResolver clr) {
int number = 0;
if (mmds != null) {
for (int i = 0; i < mmds.length; i++) {
// Get the mapping (in this table, or super-table)
AbstractMemberMetaData mmd = mmds[i];
JavaTypeMapping mapping = table.getMemberMapping(mmd);
if (mapping != null) {
if (!mmd.isPrimaryKey() && mapping.includeInFetchStatement()) {
// The depth is the number of levels down to load in this statement.
// 0 is to load just this objects fields (as with JPOX, and DataNucleus up to 1.1.3)
int depth = 0;
AbstractMemberMetaData mmdToUse = mmd;
JavaTypeMapping mappingToUse = mapping;
if (mapping instanceof SingleCollectionMapping) {
// Check the wrapped type
mappingToUse = ((SingleCollectionMapping) mapping).getWrappedMapping();
mmdToUse = ((SingleCollectionMapping) mapping).getWrappedMapping().getMemberMetaData();
}
if (mappingToUse instanceof PersistableMapping) {
// Special case of 1-1/N-1 where we know the other side type so know what to join to, hence can load the related object
depth = 1;
if (Modifier.isAbstract(mmdToUse.getType().getModifiers())) {
String typeName = mmdToUse.getTypeName();
DatastoreClass relTable = table.getStoreManager().getDatastoreClass(typeName, clr);
if (relTable != null && relTable.getSurrogateMapping(SurrogateColumnType.DISCRIMINATOR, false) == null) {
// 1-1 relation to base class with no discriminator and has subclasses
// hence no way of determining the exact type, hence no point in fetching it
String[] subclasses = table.getStoreManager().getMetaDataManager().getSubclassesForClass(typeName, false);
if (subclasses != null && subclasses.length > 0) {
depth = 0;
}
}
}
} else if (mappingToUse instanceof ReferenceMapping) {
ReferenceMapping refMapping = (ReferenceMapping) mappingToUse;
if (refMapping.getMappingStrategy() == ReferenceMapping.PER_IMPLEMENTATION_MAPPING) {
JavaTypeMapping[] subMappings = refMapping.getJavaTypeMapping();
if (subMappings != null && subMappings.length == 1) {
// Support special case of reference mapping with single implementation possible
depth = 1;
}
}
}
// TODO We should use the actual FetchPlan, and the max fetch depth, so then it can pull in all related objects within reach.
// But this will mean we cannot cache the statement, since it is for a specific ExecutionContext
// TODO If this field is a 1-1 and the other side has a discriminator or version then we really ought to fetch it
SQLStatementHelper.selectMemberOfSourceInStatement(sqlStatement, mappingDef, null, sqlTbl, mmd, clr, depth, null);
number++;
}
if (mapping instanceof MappingCallbacks) {
// TODO Need to add that this mapping is for base object or base.field1, etc
fetchCallbacks.add(mapping);
}
}
}
}
JavaTypeMapping versionMapping = table.getSurrogateMapping(SurrogateColumnType.VERSION, true);
if (versionMapping != null) {
// Select version
StatementMappingIndex verMapIdx = new StatementMappingIndex(versionMapping);
SQLTable verSqlTbl = SQLStatementHelper.getSQLTableForMappingOfTable(sqlStatement, sqlTbl, versionMapping);
int[] cols = sqlStatement.select(verSqlTbl, versionMapping, null);
verMapIdx.setColumnPositions(cols);
mappingDef.addMappingForMember(SurrogateColumnType.VERSION.getFieldNumber(), verMapIdx);
}
return number;
}
use of org.datanucleus.store.rdbms.mapping.java.ReferenceMapping 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.mapping.java.ReferenceMapping 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.mapping.java.ReferenceMapping 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;
}
use of org.datanucleus.store.rdbms.mapping.java.ReferenceMapping in project datanucleus-rdbms by datanucleus.
the class ObjectExpression method eq.
/**
* Equals operator. Called when the query contains "obj == value" where "obj" is this object.
* @param expr The expression we compare with (the right-hand-side in the query)
* @return Boolean expression representing the comparison.
*/
public BooleanExpression eq(SQLExpression expr) {
addSubexpressionsToRelatedExpression(expr);
// TODO Implement checks
if (mapping instanceof PersistableIdMapping) {
// Special Case : OID comparison ("id == val")
if (expr instanceof StringLiteral) {
String oidString = (String) ((StringLiteral) expr).getValue();
if (oidString != null) {
AbstractClassMetaData cmd = stmt.getRDBMSManager().getMetaDataManager().getMetaDataForClass(mapping.getType(), stmt.getQueryGenerator().getClassLoaderResolver());
if (cmd.getIdentityType() == IdentityType.DATASTORE) {
try {
Object id = stmt.getRDBMSManager().getNucleusContext().getIdentityManager().getDatastoreId(oidString);
if (id == null) {
// TODO Implement this comparison with the key value
}
} catch (IllegalArgumentException iae) {
NucleusLogger.QUERY.info("Attempted comparison of " + this + " and " + expr + " where the former is a datastore-identity and the latter is of incorrect form (" + oidString + ")");
SQLExpressionFactory exprFactory = stmt.getSQLExpressionFactory();
JavaTypeMapping m = exprFactory.getMappingForType(boolean.class, true);
return exprFactory.newLiteral(stmt, m, false).eq(exprFactory.newLiteral(stmt, m, true));
}
} else if (cmd.getIdentityType() == IdentityType.APPLICATION) {
// TODO Implement comparison with PK field(s)
}
}
}
}
if (mapping instanceof ReferenceMapping && expr.mapping instanceof PersistableMapping) {
return processComparisonOfImplementationWithReference(this, expr, false);
} else if (mapping instanceof PersistableMapping && expr.mapping instanceof ReferenceMapping) {
return processComparisonOfImplementationWithReference(expr, this, false);
}
BooleanExpression bExpr = null;
if (isParameter() || expr.isParameter()) {
if (subExprs != null && subExprs.size() > 1) {
for (int i = 0; i < subExprs.size(); i++) {
BooleanExpression subexpr = subExprs.getExpression(i).eq(((ObjectExpression) expr).subExprs.getExpression(i));
bExpr = (bExpr == null ? subexpr : bExpr.and(subexpr));
}
return bExpr;
}
// Comparison with parameter, so just give boolean compare
return new BooleanExpression(this, Expression.OP_EQ, expr);
} else if (expr instanceof NullLiteral) {
if (subExprs != null) {
for (int i = 0; i < subExprs.size(); i++) {
BooleanExpression subexpr = expr.eq(subExprs.getExpression(i));
bExpr = (bExpr == null ? subexpr : bExpr.and(subexpr));
}
}
return bExpr;
} else if (literalIsValidForSimpleComparison(expr)) {
if (subExprs != null && subExprs.size() > 1) {
// More than 1 value to compare with a simple literal!
return super.eq(expr);
}
// Just do a direct comparison with the basic literals
return new BooleanExpression(this, Expression.OP_EQ, expr);
} else if (expr instanceof ObjectExpression) {
return ExpressionUtils.getEqualityExpressionForObjectExpressions(this, (ObjectExpression) expr, true);
} else {
if (subExprs == null) {
// ObjectExpression for a function call
return new BooleanExpression(this, Expression.OP_EQ, expr);
}
return super.eq(expr);
}
}
Aggregations