use of org.datanucleus.store.rdbms.table.CollectionTable in project datanucleus-rdbms by datanucleus.
the class QueryToSQLMapper method getSQLTableMappingForPrimaryExpression.
/**
* Method to take in a PrimaryExpression and return the SQLTable mapping info that it signifies.
* If the primary expression implies joining to other objects then adds the joins to the statement.
* Only adds joins if necessary; so if there is a further component after the required join, or if
* the "forceJoin" flag is set.
* @param theStmt SQLStatement to use when looking for tables etc
* @param exprName Name for an expression that this primary is relative to (optional)
* If not specified then the tuples are relative to the candidate.
* If specified then should have an entry in sqlTableByPrimary under this name.
* @param primExpr The primary expression
* @param forceJoin Whether to force a join if a relation member (or null if leaving to this method to decide)
* @return The SQL table mapping information for the specified primary
*/
private SQLTableMapping getSQLTableMappingForPrimaryExpression(SQLStatement theStmt, String exprName, PrimaryExpression primExpr, Boolean forceJoin) {
if (forceJoin == null && primExpr.getParent() != null) {
if (primExpr.getParent().getOperator() == Expression.OP_IS || primExpr.getParent().getOperator() == Expression.OP_ISNOT) {
// "instanceOf" needs to be in the table of the primary expression
forceJoin = Boolean.TRUE;
}
}
SQLTableMapping sqlMapping = null;
List<String> tuples = primExpr.getTuples();
// Find source object
ListIterator<String> iter = tuples.listIterator();
String first = tuples.get(0);
boolean mapKey = false;
boolean mapValue = false;
if (first.endsWith("#KEY")) {
first = first.substring(0, first.length() - 4);
mapKey = true;
} else if (first.endsWith("#VALUE")) {
first = first.substring(0, first.length() - 6);
mapValue = true;
}
String primaryName = null;
if (exprName != null) {
// Primary relative to some object etc
sqlMapping = getSQLTableMappingForAlias(exprName);
primaryName = exprName;
} else {
if (hasSQLTableMappingForAlias(first)) {
// Start from a candidate (e.g JPQL alias)
sqlMapping = getSQLTableMappingForAlias(first);
primaryName = first;
// Skip first tuple
iter.next();
}
if (sqlMapping != null && first.equals(candidateAlias) && candidateCmd.getInheritanceMetaData().getStrategy() == InheritanceStrategy.COMPLETE_TABLE) {
// Special case of using COMPLETE_TABLE for candidate and picked wrong table
// TODO Use OPTION_CASE_INSENSITIVE
SQLTable firstSqlTbl = stmt.getTable(first.toUpperCase());
if (firstSqlTbl != null && firstSqlTbl.getTable() != sqlMapping.table.getTable()) {
// Cached the SQLTableMapping for one of the other inherited classes, so create our own
sqlMapping = new SQLTableMapping(firstSqlTbl, sqlMapping.cmd, firstSqlTbl.getTable().getIdMapping());
}
}
if (sqlMapping == null) {
if (parentMapper != null) {
QueryToSQLMapper theParentMapper = parentMapper;
while (theParentMapper != null) {
if (theParentMapper.hasSQLTableMappingForAlias(first)) {
// Try parent query
sqlMapping = theParentMapper.getSQLTableMappingForAlias(first);
primaryName = first;
// Skip first tuple
iter.next();
// This expression is for the parent statement so any joins need to go on that statement
theStmt = sqlMapping.table.getSQLStatement();
break;
}
theParentMapper = theParentMapper.parentMapper;
}
}
}
if (sqlMapping == null) {
// Field of candidate, so use candidate
sqlMapping = getSQLTableMappingForAlias(candidateAlias);
primaryName = candidateAlias;
}
}
AbstractClassMetaData cmd = sqlMapping.cmd;
JavaTypeMapping mapping = sqlMapping.mapping;
if (sqlMapping.mmd != null && (mapKey || mapValue)) {
// Special case of MAP#KEY or MAP#VALUE, so navigate from the Map "table" to the key or value
SQLTable sqlTbl = sqlMapping.table;
AbstractMemberMetaData mmd = sqlMapping.mmd;
MapMetaData mapmd = mmd.getMap();
// Find the table forming the Map. This may be a join table, or the key or value depending on the type
if (mapKey) {
// Cater for all case possibilities of table name/alias
// TODO Use OPTION_CASE_INSENSITIVE
SQLTable mapSqlTbl = stmt.getTable(first + "_MAP");
if (mapSqlTbl == null) {
mapSqlTbl = stmt.getTable((first + "_MAP").toUpperCase());
if (mapSqlTbl == null) {
mapSqlTbl = stmt.getTable((first + "_MAP").toLowerCase());
}
}
if (mapSqlTbl != null) {
sqlTbl = mapSqlTbl;
}
}
if (mapmd.getMapType() == MapType.MAP_TYPE_JOIN) {
if (sqlTbl.getTable() instanceof MapTable) {
MapTable mapTable = (MapTable) sqlTbl.getTable();
if (mapKey) {
cmd = mapmd.getKeyClassMetaData(clr);
if (!mapmd.isEmbeddedKey() && !mapmd.isSerializedKey()) {
// Join to key table
DatastoreClass keyTable = storeMgr.getDatastoreClass(mapmd.getKeyType(), clr);
sqlTbl = stmt.join(getDefaultJoinTypeForNavigation(), sqlMapping.table, mapTable.getKeyMapping(), keyTable, null, keyTable.getIdMapping(), null, null, true);
mapping = keyTable.getIdMapping();
} else {
mapping = mapTable.getKeyMapping();
}
} else {
cmd = mapmd.getValueClassMetaData(clr);
if (!mapmd.isEmbeddedValue() && !mapmd.isSerializedValue()) {
// Join to value table
DatastoreClass valueTable = storeMgr.getDatastoreClass(mapmd.getValueType(), clr);
sqlTbl = stmt.join(getDefaultJoinTypeForNavigation(), sqlMapping.table, mapTable.getValueMapping(), valueTable, null, valueTable.getIdMapping(), null, null, true);
mapping = valueTable.getIdMapping();
} else {
mapping = mapTable.getValueMapping();
}
}
} else {
// TODO Document exactly which situation this is
if (!mapmd.isEmbeddedValue() && !mapmd.isSerializedValue()) {
mapping = sqlTbl.getTable().getIdMapping();
}
}
} else if (mapmd.getMapType() == MapType.MAP_TYPE_KEY_IN_VALUE) {
if (mapKey) {
AbstractClassMetaData keyCmd = mapmd.getKeyClassMetaData(clr);
String keyMappedBy = mmd.getKeyMetaData().getMappedBy();
mapping = ((DatastoreClass) sqlTbl.getTable()).getMemberMapping(keyMappedBy);
if (keyCmd != null) {
// Join to key table
DatastoreClass keyTable = storeMgr.getDatastoreClass(mapmd.getKeyType(), clr);
sqlTbl = stmt.join(getDefaultJoinTypeForNavigation(), sqlMapping.table, mapping, keyTable, null, keyTable.getIdMapping(), null, null, true);
mapping = keyTable.getIdMapping();
}
} else {
}
} else if (mapmd.getMapType() == MapType.MAP_TYPE_VALUE_IN_KEY) {
// TODO We maybe already have the VALUE TABLE from the original join
if (!mapKey) {
AbstractClassMetaData valCmd = mapmd.getValueClassMetaData(clr);
String valMappedBy = mmd.getValueMetaData().getMappedBy();
mapping = ((DatastoreClass) sqlTbl.getTable()).getMemberMapping(valMappedBy);
if (valCmd != null) {
// Join to value table
DatastoreClass valueTable = storeMgr.getDatastoreClass(mapmd.getValueType(), clr);
sqlTbl = stmt.join(getDefaultJoinTypeForNavigation(), sqlMapping.table, mapping, valueTable, null, valueTable.getIdMapping(), null, null, true);
mapping = valueTable.getIdMapping();
}
}
}
sqlMapping = new SQLTableMapping(sqlTbl, cmd, mapping);
}
while (iter.hasNext()) {
String component = iter.next();
// fully-qualified primary name
primaryName += "." + component;
// Derive SQLTableMapping for this component
SQLTableMapping sqlMappingNew = getSQLTableMappingForAlias(primaryName);
if (sqlMappingNew == null) {
// Table not present for this primary
AbstractMemberMetaData mmd = cmd.getMetaDataForMember(component);
if (mmd == null) {
// Not valid member name
throw new NucleusUserException(Localiser.msg("021062", component, cmd.getFullClassName()));
} else if (mmd.getPersistenceModifier() != FieldPersistenceModifier.PERSISTENT) {
throw new NucleusUserException("Field " + mmd.getFullFieldName() + " is not marked as persistent so cannot be queried");
}
RelationType relationType = mmd.getRelationType(clr);
// Find the table and the mapping for this field in the table
SQLTable sqlTbl = null;
if (mapping instanceof EmbeddedMapping) {
// Embedded into the current table
sqlTbl = sqlMapping.table;
mapping = ((EmbeddedMapping) mapping).getJavaTypeMapping(component);
} else if (mapping instanceof PersistableMapping && cmd.isEmbeddedOnly()) {
// JPA EmbeddedId into current table
sqlTbl = sqlMapping.table;
JavaTypeMapping[] subMappings = ((PersistableMapping) mapping).getJavaTypeMapping();
if (subMappings.length == 1 && subMappings[0] instanceof EmbeddedPCMapping) {
mapping = ((EmbeddedPCMapping) subMappings[0]).getJavaTypeMapping(component);
} else {
// TODO What situation is this?
}
} else {
DatastoreClass table = storeMgr.getDatastoreClass(cmd.getFullClassName(), clr);
if (table == null) {
if (cmd.getInheritanceMetaData().getStrategy() == InheritanceStrategy.COMPLETE_TABLE && candidateCmd.getFullClassName().equals(cmd.getFullClassName())) {
// Special case of a candidate having no table of its own and using COMPLETE_TABLE, so we use the candidate class for this statement (or UNION)
table = storeMgr.getDatastoreClass(stmt.getCandidateClassName(), clr);
}
}
if (table == null) {
AbstractClassMetaData[] subCmds = storeMgr.getClassesManagingTableForClass(cmd, clr);
if (subCmds.length == 1) {
table = storeMgr.getDatastoreClass(subCmds[0].getFullClassName(), clr);
} else {
// all of UNIONs, and this primary expression refers to a mapping in each of subclass tables
throw new NucleusUserException("Unable to find table for primary " + primaryName + " since the class " + cmd.getFullClassName() + " is managed in multiple tables");
}
}
if (table == null) {
throw new NucleusUserException("Unable to find table for primary " + primaryName + ". Table for class=" + cmd.getFullClassName() + " is null : is the field correct? or using some inheritance pattern?");
}
mapping = table.getMemberMapping(mmd);
sqlTbl = SQLStatementHelper.getSQLTableForMappingOfTable(theStmt, sqlMapping.table, mapping);
}
if (relationType == RelationType.NONE) {
sqlMappingNew = new SQLTableMapping(sqlTbl, cmd, mapping);
cmd = sqlMappingNew.cmd;
setSQLTableMappingForAlias(primaryName, sqlMappingNew);
} else if (relationType == RelationType.ONE_TO_ONE_UNI || relationType == RelationType.ONE_TO_ONE_BI) {
if (mmd.getMappedBy() != null) {
// FK in other table so join to that first
AbstractMemberMetaData relMmd = mmd.getRelatedMemberMetaData(clr)[0];
if (relMmd.getAbstractClassMetaData().isEmbeddedOnly()) {
// Member is embedded, so keep same SQL table mapping
sqlMappingNew = sqlMapping;
cmd = relMmd.getAbstractClassMetaData();
} else {
// Member is in own table, so move to that SQL table mapping
DatastoreClass relTable = storeMgr.getDatastoreClass(mmd.getTypeName(), clr);
JavaTypeMapping relMapping = relTable.getMemberMapping(relMmd);
// Join to related table unless we already have the join in place
sqlTbl = theStmt.getTable(relTable, primaryName);
if (sqlTbl == null) {
sqlTbl = SQLStatementHelper.addJoinForOneToOneRelation(theStmt, sqlMapping.table.getTable().getIdMapping(), sqlMapping.table, relMapping, relTable, null, null, primaryName, getDefaultJoinTypeForNavigation());
}
if (iter.hasNext()) {
sqlMappingNew = new SQLTableMapping(sqlTbl, relMmd.getAbstractClassMetaData(), relTable.getIdMapping());
cmd = sqlMappingNew.cmd;
} else {
sqlMappingNew = new SQLTableMapping(sqlTbl, cmd, relTable.getIdMapping());
cmd = sqlMappingNew.cmd;
}
}
} else {
// FK is at this side
if (forceJoin == null) {
if (!iter.hasNext()) {
// Further component provided, so check if we should force a join to the other side
if (primExpr.getParent() != null && primExpr.getParent().getOperator() == Expression.OP_CAST) {
// Cast and not an interface field, so do a join to the table of the persistable object
if (mapping instanceof ReferenceMapping) {
// Don't join with interface field since represents multiple implementations
// and the cast will be a restrict on which implementation to join to
} else {
AbstractClassMetaData relCmd = ec.getMetaDataManager().getMetaDataForClass(mmd.getType(), clr);
if (relCmd != null && !relCmd.isEmbeddedOnly()) {
DatastoreClass relTable = storeMgr.getDatastoreClass(relCmd.getFullClassName(), clr);
if (relTable == null) {
} else {
forceJoin = Boolean.TRUE;
}
} else {
forceJoin = Boolean.TRUE;
}
}
}
} else {
// TODO Add optimisation to omit join if the FK is at this side and only selecting PK of the related object
if (iter.hasNext()) {
// Peek ahead to see if just selecting "id" of the related (i.e candidate.related.id with related FK in candidate table, so don't join)
String next = iter.next();
if (!iter.hasNext()) {
AbstractClassMetaData relCmd = storeMgr.getMetaDataManager().getMetaDataForClass(mmd.getType(), clr);
if (relCmd != null) {
AbstractMemberMetaData mmdOfRelCmd = relCmd.getMetaDataForMember(next);
if (mmdOfRelCmd != null && mmdOfRelCmd.isPrimaryKey() && relCmd.getNoOfPrimaryKeyMembers() == 1 && !storeMgr.getMetaDataManager().isClassPersistable(mmdOfRelCmd.getTypeName())) {
// We have something like "a.b.id" and have the FK to the "B" table in the "A" table, so just refer to A.FK rather than joining and using B.ID
NucleusLogger.QUERY.debug("Found implicit join to member=" + mmdOfRelCmd.getFullFieldName() + " which is PK of the other type but FK is in this table so avoiding the join");
JavaTypeMapping subMapping = ((PersistableMapping) mapping).getJavaTypeMapping()[0];
// Component mappings of a PersistableMapping sometimes don't have table set, so fix it
subMapping.setTable(mapping.getTable());
return new SQLTableMapping(sqlMapping.table, relCmd, subMapping);
}
}
}
iter.previous();
}
}
}
if (iter.hasNext() || Boolean.TRUE.equals(forceJoin)) {
AbstractClassMetaData relCmd = null;
JavaTypeMapping relMapping = null;
DatastoreClass relTable = null;
if (relationType == RelationType.ONE_TO_ONE_BI) {
AbstractMemberMetaData relMmd = mmd.getRelatedMemberMetaData(clr)[0];
relCmd = relMmd.getAbstractClassMetaData();
} else {
String typeName = mmd.isSingleCollection() ? mmd.getCollection().getElementType() : mmd.getTypeName();
relCmd = ec.getMetaDataManager().getMetaDataForClass(typeName, clr);
}
if (relCmd != null && relCmd.isEmbeddedOnly()) {
// Member is embedded so use same table but embedded mapping
sqlMappingNew = new SQLTableMapping(sqlTbl, relCmd, mapping);
cmd = relCmd;
} else {
// Member is in own table, so move to that SQL table mapping
relTable = storeMgr.getDatastoreClass(relCmd.getFullClassName(), clr);
if (relTable == null) {
// No table for the related type (subclass-table), so see if this class has a single subclass with its own table
Collection<String> relSubclassNames = storeMgr.getSubClassesForClass(relCmd.getFullClassName(), false, clr);
if (relSubclassNames != null && relSubclassNames.size() == 1) {
String relSubclassName = relSubclassNames.iterator().next();
relTable = storeMgr.getDatastoreClass(relSubclassName, clr);
// TODO Cater for this having no table and next level yes etc
if (relTable != null) {
relCmd = ec.getMetaDataManager().getMetaDataForClass(relSubclassName, clr);
}
}
if (relTable == null) {
// No table as such, so likely using subclass-table at other side and we don't know where to join to
throw new NucleusUserException("Reference to PrimaryExpression " + primExpr + " yet this needs to join relation " + mmd.getFullFieldName() + " and the other type has no table (subclass-table?). Maybe use a CAST to the appropriate subclass?");
}
}
relMapping = relTable.getIdMapping();
// Join to other table unless we already have the join in place
sqlTbl = theStmt.getTable(relTable, primaryName);
if (sqlTbl == null) {
sqlTbl = SQLStatementHelper.addJoinForOneToOneRelation(theStmt, mapping, sqlMapping.table, relMapping, relTable, null, null, primaryName, getDefaultJoinTypeForNavigation());
}
sqlMappingNew = new SQLTableMapping(sqlTbl, relCmd, relMapping);
cmd = sqlMappingNew.cmd;
setSQLTableMappingForAlias(primaryName, sqlMappingNew);
}
} else {
sqlMappingNew = new SQLTableMapping(sqlTbl, cmd, mapping);
cmd = sqlMappingNew.cmd;
// Don't register the SQLTableMapping for this alias since only using FK
}
}
} else if (relationType == RelationType.MANY_TO_ONE_BI) {
AbstractMemberMetaData relMmd = mmd.getRelatedMemberMetaData(clr)[0];
DatastoreClass relTable = storeMgr.getDatastoreClass(mmd.getTypeName(), clr);
if (mmd.getJoinMetaData() != null || relMmd.getJoinMetaData() != null) {
// Has join table so use that
sqlTbl = theStmt.getTable(relTable, primaryName);
if (sqlTbl == null) {
// Join to the join table
CollectionTable joinTbl = (CollectionTable) storeMgr.getTable(relMmd);
JoinType defJoinType = getDefaultJoinTypeForNavigation();
if (defJoinType == JoinType.INNER_JOIN) {
SQLTable joinSqlTbl = theStmt.join(JoinType.INNER_JOIN, sqlMapping.table, sqlMapping.table.getTable().getIdMapping(), joinTbl, null, joinTbl.getElementMapping(), null, null, true);
sqlTbl = theStmt.join(JoinType.INNER_JOIN, joinSqlTbl, joinTbl.getOwnerMapping(), relTable, null, relTable.getIdMapping(), null, primaryName, true);
} else if (defJoinType == JoinType.LEFT_OUTER_JOIN || defJoinType == null) {
SQLTable joinSqlTbl = theStmt.join(JoinType.LEFT_OUTER_JOIN, sqlMapping.table, sqlMapping.table.getTable().getIdMapping(), joinTbl, null, joinTbl.getElementMapping(), null, null, true);
sqlTbl = theStmt.join(JoinType.LEFT_OUTER_JOIN, joinSqlTbl, joinTbl.getOwnerMapping(), relTable, null, relTable.getIdMapping(), null, primaryName, true);
}
}
sqlMappingNew = new SQLTableMapping(sqlTbl, relMmd.getAbstractClassMetaData(), relTable.getIdMapping());
cmd = sqlMappingNew.cmd;
setSQLTableMappingForAlias(primaryName, sqlMappingNew);
} else {
// FK in this table
sqlTbl = theStmt.getTable(relTable, primaryName);
if (sqlTbl == null) {
if (mmd.getMappedBy() == null) {
// FK at this side so check for optimisations
if (iter.hasNext()) {
// Peek ahead to see if just selecting "id" of the related (i.e candidate.related.id with related FK in candidate table, so don't join)
String next = iter.next();
if (!iter.hasNext()) {
AbstractClassMetaData relCmd = relMmd.getAbstractClassMetaData();
AbstractMemberMetaData mmdOfRelCmd = relCmd.getMetaDataForMember(next);
if (mmdOfRelCmd != null && mmdOfRelCmd.isPrimaryKey() && relCmd.getNoOfPrimaryKeyMembers() == 1 && !storeMgr.getMetaDataManager().isClassPersistable(mmdOfRelCmd.getTypeName())) {
// We have something like "a.b.id" and have the FK to the "B" table in the "A" table, so just refer to A.FK rather than joining and using B.ID
NucleusLogger.QUERY.debug("Found implicit join to member=" + mmdOfRelCmd.getFullFieldName() + " which is PK of the other type but FK is in this table so avoiding the join");
JavaTypeMapping subMapping = ((PersistableMapping) mapping).getJavaTypeMapping()[0];
// Component mappings of a PersistableMapping sometimes don't have table set, so fix it
subMapping.setTable(mapping.getTable());
return new SQLTableMapping(sqlMapping.table, relCmd, subMapping);
}
}
iter.previous();
}
}
Operator op = (primExpr.getParent() != null ? primExpr.getParent().getOperator() : null);
if (!iter.hasNext() && (op == Expression.OP_EQ || op == Expression.OP_GT || op == Expression.OP_LT || op == Expression.OP_GTEQ || op == Expression.OP_LTEQ || op == Expression.OP_NOTEQ)) {
// Just return the FK mapping since in a "a.b == c.d" type expression and not needing to go further than the FK
sqlMappingNew = new SQLTableMapping(sqlMapping.table, relMmd.getAbstractClassMetaData(), mapping);
} else {
// Join to the related table
JoinType defJoinType = getDefaultJoinTypeForNavigation();
if (defJoinType == JoinType.INNER_JOIN) {
sqlTbl = theStmt.join(JoinType.INNER_JOIN, sqlMapping.table, mapping, relTable, null, relTable.getIdMapping(), null, primaryName, true);
} else if (defJoinType == JoinType.LEFT_OUTER_JOIN || defJoinType == null) {
sqlTbl = theStmt.join(JoinType.LEFT_OUTER_JOIN, sqlMapping.table, mapping, relTable, null, relTable.getIdMapping(), null, primaryName, true);
}
sqlMappingNew = new SQLTableMapping(sqlTbl, relMmd.getAbstractClassMetaData(), relTable.getIdMapping());
cmd = sqlMappingNew.cmd;
setSQLTableMappingForAlias(primaryName, sqlMappingNew);
}
} else {
sqlMappingNew = new SQLTableMapping(sqlTbl, relMmd.getAbstractClassMetaData(), relTable.getIdMapping());
cmd = sqlMappingNew.cmd;
setSQLTableMappingForAlias(primaryName, sqlMappingNew);
}
}
} else if (RelationType.isRelationMultiValued(relationType)) {
// Can't reference further than a collection/map so just return its mapping here
sqlMappingNew = new SQLTableMapping(sqlTbl, cmd, mapping);
cmd = sqlMappingNew.cmd;
setSQLTableMappingForAlias(primaryName, sqlMappingNew);
}
} else {
cmd = sqlMappingNew.cmd;
}
sqlMapping = sqlMappingNew;
}
return sqlMapping;
}
use of org.datanucleus.store.rdbms.table.CollectionTable in project datanucleus-rdbms by datanucleus.
the class IndexFunction method getExpression.
/* (non-Javadoc)
* @see org.datanucleus.store.rdbms.sql.method.SQLMethod#getExpression(org.datanucleus.store.rdbms.sql.expression.SQLExpression, java.util.List)
*/
public SQLExpression getExpression(SQLStatement stmt, SQLExpression ignore, List args) {
if (ignore == null) {
if (args == null || args.size() != 2) {
throw new NucleusException("INDEX can only be used with 2 arguments - the element expression, and the collection expression");
}
SQLExpression elemSqlExpr = (SQLExpression) args.get(0);
SQLExpression collSqlExpr = (SQLExpression) args.get(1);
AbstractMemberMetaData mmd = collSqlExpr.getJavaTypeMapping().getMemberMetaData();
if (!mmd.hasCollection()) {
throw new NucleusException("INDEX expression for field " + mmd.getFullFieldName() + " does not represent a collection!");
} else if (!mmd.getOrderMetaData().isIndexedList()) {
throw new NucleusException("INDEX expression for field " + mmd.getFullFieldName() + " does not represent an indexed list!");
}
JavaTypeMapping orderMapping = null;
SQLTable orderTable = null;
Table joinTbl = stmt.getRDBMSManager().getTable(mmd);
if (joinTbl != null) {
// 1-N via join table
CollectionTable collTable = (CollectionTable) joinTbl;
orderTable = stmt.getTableForDatastoreContainer(collTable);
// TODO If the join table is not yet referenced, or referenced multiple times then fix this
orderMapping = collTable.getOrderMapping();
} else {
// 1-N via FK
orderTable = elemSqlExpr.getSQLTable();
orderMapping = ((ClassTable) elemSqlExpr.getSQLTable().getTable()).getExternalMapping(mmd, MappingType.EXTERNAL_INDEX);
}
return new NumericExpression(stmt, orderTable, orderMapping);
}
throw new NucleusException(Localiser.msg("060002", "INDEX", ignore));
}
use of org.datanucleus.store.rdbms.table.CollectionTable in project datanucleus-rdbms by datanucleus.
the class ListGetMethod method getAsSubquery.
/**
* Implementation of Collection.get() using a subquery on the table representing the collection, adding a condition on the index and returning the element.
* @param stmt SQLStatement
* @param listExpr The list expression
* @param idxExpr The index expression
* @return The element expression
*/
protected SQLExpression getAsSubquery(SQLStatement stmt, CollectionExpression listExpr, SQLExpression idxExpr) {
AbstractMemberMetaData mmd = listExpr.getJavaTypeMapping().getMemberMetaData();
RDBMSStoreManager storeMgr = stmt.getRDBMSManager();
ClassLoaderResolver clr = stmt.getQueryGenerator().getClassLoaderResolver();
JavaTypeMapping ownerMapping = null;
JavaTypeMapping indexMapping = null;
JavaTypeMapping elemMapping = null;
Table listTbl = null;
if (mmd != null) {
AbstractMemberMetaData[] relatedMmds = mmd.getRelatedMemberMetaData(clr);
if (mmd.getJoinMetaData() != null || relatedMmds != null && relatedMmds[0].getJoinMetaData() != null) {
// Join table List
listTbl = storeMgr.getTable(mmd);
ownerMapping = ((CollectionTable) listTbl).getOwnerMapping();
indexMapping = ((CollectionTable) listTbl).getOrderMapping();
elemMapping = ((CollectionTable) listTbl).getElementMapping();
} else {
// FK List
DatastoreClass elemTbl = storeMgr.getDatastoreClass(mmd.getCollection().getElementType(), clr);
listTbl = elemTbl;
if (relatedMmds != null) {
ownerMapping = elemTbl.getMemberMapping(relatedMmds[0]);
indexMapping = elemTbl.getExternalMapping(mmd, MappingType.EXTERNAL_INDEX);
elemMapping = elemTbl.getIdMapping();
} else {
ownerMapping = elemTbl.getExternalMapping(mmd, MappingType.EXTERNAL_FK);
indexMapping = elemTbl.getExternalMapping(mmd, MappingType.EXTERNAL_INDEX);
elemMapping = elemTbl.getIdMapping();
}
}
}
SQLExpressionFactory exprFactory = stmt.getSQLExpressionFactory();
SelectStatement subStmt = new SelectStatement(stmt, storeMgr, listTbl, null, null);
subStmt.setClassLoaderResolver(clr);
SQLExpression valExpr = exprFactory.newExpression(subStmt, subStmt.getPrimaryTable(), elemMapping);
subStmt.select(valExpr, null);
// Link to primary statement
SQLExpression elementOwnerExpr = exprFactory.newExpression(subStmt, subStmt.getPrimaryTable(), ownerMapping);
SQLExpression ownerIdExpr = exprFactory.newExpression(stmt, listExpr.getSQLTable(), listExpr.getSQLTable().getTable().getIdMapping());
subStmt.whereAnd(elementOwnerExpr.eq(ownerIdExpr), true);
// Condition on key
SQLExpression keyExpr = exprFactory.newExpression(subStmt, subStmt.getPrimaryTable(), indexMapping);
subStmt.whereAnd(keyExpr.eq(idxExpr), true);
// Create subquery, with mapping being of the element type (since "get" returns an element)
SubqueryExpression subExpr = new SubqueryExpression(stmt, subStmt);
subExpr.setJavaTypeMapping(elemMapping);
return subExpr;
}
use of org.datanucleus.store.rdbms.table.CollectionTable in project datanucleus-rdbms by datanucleus.
the class CollectionContainsMethod method containsAsSubquery.
/**
* Method to return an expression for Collection.contains using a subquery "EXISTS".
* This is for use when there are "!contains" or "OR" operations in the filter.
* Creates the following SQL,
* <ul>
* <li><b>Collection of NonPC using join table</b>
* <pre>
* SELECT 1 FROM JOIN_TBL A0_SUB
* WHERE A0_SUB.JOIN_OWN_ID = A0.ID AND A0_SUB.JOIN_ELEM_ID = {elemExpr}
* </pre>
* </li>
* <li><b>Collection of PC using join table</b>
* <pre>
* SELECT 1 FROM ELEM_TABLE A0_SUB INNER JOIN JOIN_TBL B0 ON ...
* WHERE B0.JOIN_OWN_ID = A0.ID AND A0_SUB.ID = {elemExpr}
* </pre>
* </li>
* <li><b>Collection of PC using FK</b>
* <pre>
* SELECT 1 FROM ELEM_TABLE A0_SUB
* WHERE A0_SUB.OWN_ID = A0.ID AND A0_SUB.ID = {elemExpr}
* </pre>
* </li>
* </ul>
* and returns a BooleanSubqueryExpression ("EXISTS (subquery)")
* @param stmt SQLStatement
* @param collExpr Collection expression
* @param elemExpr Expression for the element
* @return Contains expression
*/
protected SQLExpression containsAsSubquery(SQLStatement stmt, CollectionExpression collExpr, SQLExpression elemExpr) {
boolean elemIsUnbound = (elemExpr instanceof UnboundExpression);
String varName = null;
if (elemIsUnbound) {
varName = ((UnboundExpression) elemExpr).getVariableName();
NucleusLogger.QUERY.debug("collection.contains(" + elemExpr + ") binding unbound variable " + varName + " using SUBQUERY");
}
RDBMSStoreManager storeMgr = stmt.getRDBMSManager();
SQLExpressionFactory exprFactory = stmt.getSQLExpressionFactory();
ClassLoaderResolver clr = stmt.getQueryGenerator().getClassLoaderResolver();
AbstractMemberMetaData mmd = collExpr.getJavaTypeMapping().getMemberMetaData();
AbstractClassMetaData elemCmd = mmd.getCollection().getElementClassMetaData(clr);
CollectionTable joinTbl = (CollectionTable) storeMgr.getTable(mmd);
String elemType = mmd.getCollection().getElementType();
if (elemIsUnbound) {
Class varType = stmt.getQueryGenerator().getTypeOfVariable(varName);
if (varType != null) {
elemType = varType.getName();
elemCmd = storeMgr.getMetaDataManager().getMetaDataForClass(elemType, clr);
}
}
SelectStatement subStmt = null;
if (joinTbl != null) {
// JoinTable Collection
if (elemCmd == null) {
// Collection<Non-PC>
subStmt = new SelectStatement(stmt, storeMgr, joinTbl, null, null);
subStmt.setClassLoaderResolver(clr);
JavaTypeMapping oneMapping = storeMgr.getMappingManager().getMapping(Integer.class);
subStmt.select(exprFactory.newLiteral(subStmt, oneMapping, 1), null);
// Restrict to collection owner
JavaTypeMapping ownerMapping = ((JoinTable) joinTbl).getOwnerMapping();
SQLExpression ownerExpr = exprFactory.newExpression(subStmt, subStmt.getPrimaryTable(), ownerMapping);
SQLExpression ownerIdExpr = exprFactory.newExpression(stmt, collExpr.getSQLTable(), collExpr.getSQLTable().getTable().getIdMapping());
subStmt.whereAnd(ownerExpr.eq(ownerIdExpr), true);
SQLExpression elemIdExpr = exprFactory.newExpression(subStmt, subStmt.getPrimaryTable(), joinTbl.getElementMapping());
if (elemIsUnbound) {
// Bind the variable in the QueryGenerator
stmt.getQueryGenerator().bindVariable(varName, null, elemIdExpr.getSQLTable(), elemIdExpr.getJavaTypeMapping());
} else {
// Add restrict to element
addRestrictionOnElement(subStmt, elemIdExpr, elemExpr);
}
} else {
// Collection<PC>
DatastoreClass elemTbl = storeMgr.getDatastoreClass(elemType, clr);
subStmt = new SelectStatement(stmt, storeMgr, elemTbl, null, null);
subStmt.setClassLoaderResolver(clr);
JavaTypeMapping oneMapping = storeMgr.getMappingManager().getMapping(Integer.class);
subStmt.select(exprFactory.newLiteral(subStmt, oneMapping, 1), null);
// Join to join table
SQLTable joinSqlTbl = subStmt.join(JoinType.INNER_JOIN, subStmt.getPrimaryTable(), elemTbl.getIdMapping(), joinTbl, null, joinTbl.getElementMapping(), null, null, true, null);
// Restrict to collection owner
JavaTypeMapping ownerMapping = ((JoinTable) joinTbl).getOwnerMapping();
SQLExpression ownerExpr = exprFactory.newExpression(subStmt, joinSqlTbl, ownerMapping);
SQLExpression ownerIdExpr = exprFactory.newExpression(stmt, collExpr.getSQLTable(), collExpr.getSQLTable().getTable().getIdMapping());
subStmt.whereAnd(ownerExpr.eq(ownerIdExpr), true);
SQLExpression elemIdExpr = exprFactory.newExpression(subStmt, subStmt.getPrimaryTable(), elemTbl.getIdMapping());
if (elemIsUnbound) {
// Bind the variable in the QueryGenerator
stmt.getQueryGenerator().bindVariable(varName, elemCmd, elemIdExpr.getSQLTable(), elemIdExpr.getJavaTypeMapping());
} else {
// Add restrict to element
addRestrictionOnElement(subStmt, elemIdExpr, elemExpr);
}
}
} else {
// FK Collection
DatastoreClass elemTbl = storeMgr.getDatastoreClass(mmd.getCollection().getElementType(), clr);
subStmt = new SelectStatement(stmt, storeMgr, elemTbl, null, null);
subStmt.setClassLoaderResolver(clr);
JavaTypeMapping oneMapping = storeMgr.getMappingManager().getMapping(Integer.class);
subStmt.select(exprFactory.newLiteral(subStmt, oneMapping, 1), null);
// Restrict to collection owner
JavaTypeMapping ownerMapping = null;
if (mmd.getMappedBy() != null) {
ownerMapping = elemTbl.getMemberMapping(mmd.getRelatedMemberMetaData(clr)[0]);
} else {
ownerMapping = elemTbl.getExternalMapping(mmd, MappingType.EXTERNAL_FK);
}
SQLExpression ownerExpr = exprFactory.newExpression(subStmt, subStmt.getPrimaryTable(), ownerMapping);
SQLExpression ownerIdExpr = exprFactory.newExpression(stmt, collExpr.getSQLTable(), collExpr.getSQLTable().getTable().getIdMapping());
subStmt.whereAnd(ownerExpr.eq(ownerIdExpr), true);
if (elemIsUnbound) {
SQLExpression elemIdExpr = null;
if (!elemType.equals(mmd.getCollection().getElementType())) {
// Variable is defined as a subclass of the declared type so add extra join to variable type
DatastoreClass varTbl = storeMgr.getDatastoreClass(elemType, clr);
SQLTable varSqlTbl = subStmt.join(JoinType.INNER_JOIN, subStmt.getPrimaryTable(), elemTbl.getIdMapping(), null, varTbl, null, varTbl.getIdMapping(), null, null, null, true, null);
elemIdExpr = exprFactory.newExpression(subStmt, varSqlTbl, varTbl.getIdMapping());
} else {
elemIdExpr = exprFactory.newExpression(subStmt, subStmt.getPrimaryTable(), elemTbl.getIdMapping());
}
// Bind the variable in the QueryGenerator
stmt.getQueryGenerator().bindVariable(varName, elemCmd, elemIdExpr.getSQLTable(), elemIdExpr.getJavaTypeMapping());
} else {
// Add restrict to element
SQLExpression elemIdExpr = exprFactory.newExpression(subStmt, subStmt.getPrimaryTable(), elemTbl.getIdMapping());
addRestrictionOnElement(subStmt, elemIdExpr, elemExpr);
}
}
return new BooleanSubqueryExpression(stmt, "EXISTS", subStmt);
}
use of org.datanucleus.store.rdbms.table.CollectionTable in project datanucleus-rdbms by datanucleus.
the class RDBMSStoreManager method getBackingStoreForField.
/**
* Accessor for the backing store for the specified member.
* Note : if we have an embedded object that is embedded into some other type and the object has a member that requires a join table (backing store), this method
* will not cater for the different places that can be embedded.
* @param clr The ClassLoaderResolver
* @param mmd metadata for the member to be persisted by this Store
* @param type instantiated type or prefered type
* @return The backing store
*/
public Store getBackingStoreForField(ClassLoaderResolver clr, AbstractMemberMetaData mmd, Class type) {
if (mmd == null || mmd.isSerialized()) {
return null;
}
Store store = backingStoreByMemberName.get(mmd.getFullFieldName());
if (store != null) {
return store;
}
synchronized (backingStoreByMemberName) {
// Just in case we synced just after someone added since our previous lookup above
store = backingStoreByMemberName.get(mmd.getFullFieldName());
if (store != null) {
return store;
}
Class expectedMappingType = null;
if (mmd.getMap() != null) {
expectedMappingType = MapMapping.class;
} else if (mmd.getArray() != null) {
expectedMappingType = ArrayMapping.class;
} else if (mmd.getCollection() != null) {
expectedMappingType = CollectionMapping.class;
} else {
expectedMappingType = PersistableMapping.class;
}
// Validate the mapping type matches the table
try {
DatastoreClass ownerTable = getDatastoreClass(mmd.getClassName(), clr);
if (ownerTable == null) {
// Class doesn't manage its own table (uses subclass-table, or superclass-table?)
AbstractClassMetaData fieldTypeCmd = getMetaDataManager().getMetaDataForClass(mmd.getClassName(), clr);
AbstractClassMetaData[] tableOwnerCmds = getClassesManagingTableForClass(fieldTypeCmd, clr);
if (tableOwnerCmds != null && tableOwnerCmds.length == 1) {
ownerTable = getDatastoreClass(tableOwnerCmds[0].getFullClassName(), clr);
}
}
if (ownerTable != null) {
JavaTypeMapping m = ownerTable.getMemberMapping(mmd);
if (!expectedMappingType.isAssignableFrom(m.getClass())) {
String requiredType = type != null ? type.getName() : mmd.getTypeName();
NucleusLogger.PERSISTENCE.warn("Member " + mmd.getFullFieldName() + " in table=" + ownerTable + " has mapping=" + m + " but expected mapping type=" + expectedMappingType);
throw new IncompatibleFieldTypeException(mmd.getFullFieldName(), requiredType, m.getType());
}
}
} catch (NoTableManagedException ntme) {
// Embedded, so just pass through
}
if (mmd.getMap() != null) {
Table datastoreTable = getTable(mmd);
if (datastoreTable == null) {
store = new FKMapStore(mmd, this, clr);
} else {
store = new JoinMapStore((MapTable) datastoreTable, clr);
}
} else if (mmd.getArray() != null) {
Table datastoreTable = getTable(mmd);
if (datastoreTable != null) {
store = new JoinArrayStore(mmd, (ArrayTable) datastoreTable, clr);
} else {
store = new FKArrayStore(mmd, this, clr);
}
} else if (mmd.getCollection() != null) {
Table datastoreTable = getTable(mmd);
if (type == null) {
// No type to base it on so create it based on the field declared type
if (datastoreTable == null) {
// We need a "FK" relation
if (Set.class.isAssignableFrom(mmd.getType())) {
store = new FKSetStore(mmd, this, clr);
} else if (List.class.isAssignableFrom(mmd.getType()) || Queue.class.isAssignableFrom(mmd.getType())) {
store = new FKListStore(mmd, this, clr);
} else if (mmd.getOrderMetaData() != null) {
// User has requested ordering
store = new FKListStore(mmd, this, clr);
} else {
store = new FKSetStore(mmd, this, clr);
}
} else {
// We need a "JoinTable" relation.
if (Set.class.isAssignableFrom(mmd.getType())) {
store = new JoinSetStore(mmd, (CollectionTable) datastoreTable, clr);
} else if (List.class.isAssignableFrom(mmd.getType()) || Queue.class.isAssignableFrom(mmd.getType())) {
store = new JoinListStore(mmd, (CollectionTable) datastoreTable, clr);
} else if (mmd.getOrderMetaData() != null) {
// User has requested ordering
store = new JoinListStore(mmd, (CollectionTable) datastoreTable, clr);
} else {
store = new JoinSetStore(mmd, (CollectionTable) datastoreTable, clr);
}
}
} else {
// Instantiated type specified, so use it to pick the associated backing store
if (datastoreTable == null) {
if (SCOUtils.isListBased(type)) {
// List required
store = new FKListStore(mmd, this, clr);
} else {
// Set required
store = new FKSetStore(mmd, this, clr);
}
} else {
if (SCOUtils.isListBased(type)) {
// List required
store = new JoinListStore(mmd, (CollectionTable) datastoreTable, clr);
} else {
// Set required
store = new JoinSetStore(mmd, (CollectionTable) datastoreTable, clr);
}
}
}
} else {
store = new JoinPersistableRelationStore(mmd, (PersistableJoinTable) getTable(mmd), clr);
}
backingStoreByMemberName.put(mmd.getFullFieldName(), store);
return store;
}
}
Aggregations