Search in sources :

Example 76 with JavaTypeMapping

use of org.datanucleus.store.rdbms.mapping.java.JavaTypeMapping in project datanucleus-rdbms by datanucleus.

the class ExpressionUtils method getEqualityExpressionForObjectExpressions.

/**
 * Method to generate an equality/inequality expression between two ObjectExpressions.
 * Either or both of the expressions can be ObjectLiterals.
 * @param expr1 First expression
 * @param expr2 Second expression
 * @param equals Whether it is equality (otherwise inequality)
 * @return The expression
 */
public static BooleanExpression getEqualityExpressionForObjectExpressions(ObjectExpression expr1, ObjectExpression expr2, boolean equals) {
    SQLStatement stmt = expr1.stmt;
    RDBMSStoreManager storeMgr = stmt.getRDBMSManager();
    SQLExpressionFactory exprFactory = storeMgr.getSQLExpressionFactory();
    ClassLoaderResolver clr = stmt.getClassLoaderResolver();
    ApiAdapter api = storeMgr.getApiAdapter();
    if (expr1 instanceof ObjectLiteral && expr2 instanceof ObjectLiteral) {
        // ObjectLiterall == ObjectLiteral
        ObjectLiteral lit1 = (ObjectLiteral) expr1;
        ObjectLiteral lit2 = (ObjectLiteral) expr2;
        return new BooleanLiteral(stmt, expr1.mapping, equals ? lit1.getValue().equals(lit2.getValue()) : !lit1.getValue().equals(lit2.getValue()));
    } else if (expr1 instanceof ObjectLiteral || expr2 instanceof ObjectLiteral) {
        // ObjectExpression == ObjectLiteral, ObjectLiteral == ObjectExpression
        BooleanExpression bExpr = null;
        boolean secondIsLiteral = (expr2 instanceof ObjectLiteral);
        Object value = (!secondIsLiteral ? ((ObjectLiteral) expr1).getValue() : ((ObjectLiteral) expr2).getValue());
        if (IdentityUtils.isDatastoreIdentity(value)) {
            // Object is an OID
            Object valueKey = IdentityUtils.getTargetKeyForDatastoreIdentity(value);
            JavaTypeMapping m = storeMgr.getSQLExpressionFactory().getMappingForType(valueKey.getClass(), false);
            SQLExpression oidLit = exprFactory.newLiteral(stmt, m, valueKey);
            if (equals) {
                return (secondIsLiteral ? expr1.subExprs.getExpression(0).eq(oidLit) : expr2.subExprs.getExpression(0).eq(oidLit));
            }
            return (secondIsLiteral ? expr1.subExprs.getExpression(0).ne(oidLit) : expr2.subExprs.getExpression(0).ne(oidLit));
        } else if (IdentityUtils.isSingleFieldIdentity(value)) {
            // Object is SingleFieldIdentity
            Object valueKey = IdentityUtils.getTargetKeyForSingleFieldIdentity(value);
            // This used to use ((SingleFieldId)value).getTargetClass() for some reason, which contradicts the above datastore id method
            JavaTypeMapping m = storeMgr.getSQLExpressionFactory().getMappingForType(valueKey.getClass(), false);
            SQLExpression oidLit = exprFactory.newLiteral(stmt, m, valueKey);
            if (equals) {
                return (secondIsLiteral ? expr1.subExprs.getExpression(0).eq(oidLit) : expr2.subExprs.getExpression(0).eq(oidLit));
            }
            return (secondIsLiteral ? expr1.subExprs.getExpression(0).ne(oidLit) : expr2.subExprs.getExpression(0).ne(oidLit));
        } else {
            AbstractClassMetaData cmd = storeMgr.getNucleusContext().getMetaDataManager().getMetaDataForClass(value.getClass(), clr);
            if (cmd != null) {
                // Value is a persistable object
                if (cmd.getIdentityType() == IdentityType.APPLICATION) {
                    // Application identity
                    if (api.getIdForObject(value) != null) {
                        // Persistent PC object (FCO)
                        // Cater for composite PKs and parts of PK being PC mappings, and recursion
                        ObjectExpression expr = (secondIsLiteral ? expr1 : expr2);
                        JavaTypeMapping[] pkMappingsApp = new JavaTypeMapping[expr.subExprs.size()];
                        Object[] pkFieldValues = new Object[expr.subExprs.size()];
                        int position = 0;
                        ExecutionContext ec = api.getExecutionContext(value);
                        JavaTypeMapping thisMapping = expr.mapping;
                        if (expr.mapping instanceof ReferenceMapping) {
                            // "InterfaceField == value", so pick an implementation mapping that is castable
                            thisMapping = null;
                            ReferenceMapping refMapping = (ReferenceMapping) expr.mapping;
                            JavaTypeMapping[] implMappings = refMapping.getJavaTypeMapping();
                            for (int i = 0; i < implMappings.length; i++) {
                                Class implType = clr.classForName(implMappings[i].getType());
                                if (implType.isAssignableFrom(value.getClass())) {
                                    thisMapping = implMappings[i];
                                    break;
                                }
                            }
                        }
                        if (thisMapping == null) {
                            // Just return a (1=0) since no implementation castable
                            return exprFactory.newLiteral(stmt, expr1.mapping, false).eq(exprFactory.newLiteral(stmt, expr1.mapping, true));
                        }
                        for (int i = 0; i < cmd.getNoOfPrimaryKeyMembers(); i++) {
                            AbstractMemberMetaData mmd = cmd.getMetaDataForManagedMemberAtAbsolutePosition(cmd.getPKMemberPositions()[i]);
                            Object fieldValue = ExpressionUtils.getValueForMemberOfObject(ec, mmd, value);
                            JavaTypeMapping mapping = ((PersistableMapping) thisMapping).getJavaTypeMapping()[i];
                            if (mapping instanceof PersistableMapping) {
                                position = ExpressionUtils.populatePrimaryKeyMappingsValuesForPCMapping(pkMappingsApp, pkFieldValues, position, (PersistableMapping) mapping, cmd, mmd, fieldValue, storeMgr, clr);
                            } else {
                                pkMappingsApp[position] = mapping;
                                pkFieldValues[position] = fieldValue;
                                position++;
                            }
                        }
                        for (int i = 0; i < expr.subExprs.size(); i++) {
                            SQLExpression source = expr.subExprs.getExpression(i);
                            SQLExpression target = exprFactory.newLiteral(stmt, pkMappingsApp[i], pkFieldValues[i]);
                            BooleanExpression subExpr = (secondIsLiteral ? source.eq(target) : target.eq(source));
                            if (bExpr == null) {
                                bExpr = subExpr;
                            } else {
                                bExpr = bExpr.and(subExpr);
                            }
                        }
                    } else {
                        // PC object with no id (embedded, or transient maybe)
                        if (secondIsLiteral) {
                            for (int i = 0; i < expr1.subExprs.size(); i++) {
                                // Query should return nothing (so just do "(1 = 0)")
                                NucleusLogger.QUERY.warn(Localiser.msg("037003", value));
                                bExpr = exprFactory.newLiteral(stmt, expr1.mapping, false).eq(exprFactory.newLiteral(stmt, expr1.mapping, true));
                            // It is arguable that we should compare the id with null (as below)
                            /*bExpr = expr.eq(new NullLiteral(qs));*/
                            }
                        } else {
                            for (int i = 0; i < expr2.subExprs.size(); i++) {
                                // Query should return nothing (so just do "(1 = 0)")
                                NucleusLogger.QUERY.warn(Localiser.msg("037003", value));
                                bExpr = exprFactory.newLiteral(stmt, expr2.mapping, false).eq(exprFactory.newLiteral(stmt, expr2.mapping, true));
                            // It is arguable that we should compare the id with null (as below)
                            /*bExpr = expr.eq(new NullLiteral(qs));*/
                            }
                        }
                    }
                    // TODO Allow for !equals
                    return bExpr;
                } else if (cmd.getIdentityType() == IdentityType.DATASTORE) {
                    // Datastore identity
                    SQLExpression source = (secondIsLiteral ? expr1.subExprs.getExpression(0) : expr2.subExprs.getExpression(0));
                    JavaTypeMapping mapping = (secondIsLiteral ? expr1.mapping : expr2.mapping);
                    Object objectId = api.getIdForObject(value);
                    if (objectId == null) {
                        // PC object with no id (embedded, or transient maybe)
                        // Query should return nothing (so just do "(1 = 0)")
                        NucleusLogger.QUERY.warn(Localiser.msg("037003", value));
                        // TODO Allow for !equals
                        return exprFactory.newLiteral(stmt, mapping, false).eq(exprFactory.newLiteral(stmt, mapping, true));
                    // It is arguable that we should compare the id with null (as below)
                    /*bExpr = expr.eq(new NullLiteral(qs));*/
                    }
                    Object objectIdKey = IdentityUtils.getTargetKeyForDatastoreIdentity(objectId);
                    JavaTypeMapping m = storeMgr.getSQLExpressionFactory().getMappingForType(objectIdKey.getClass(), false);
                    SQLExpression oidExpr = exprFactory.newLiteral(stmt, m, objectIdKey);
                    if (equals) {
                        return source.eq(oidExpr);
                    }
                    return source.ne(oidExpr);
                }
            } else {
                // No metadata, so we either have an application identity, or any object
                String pcClassName = storeMgr.getClassNameForObjectID(value, clr, null);
                if (pcClassName != null) {
                    // Object is an application identity
                    cmd = storeMgr.getNucleusContext().getMetaDataManager().getMetaDataForClass(pcClassName, clr);
                    return (secondIsLiteral ? ExpressionUtils.getAppIdEqualityExpression(value, expr1, storeMgr, clr, cmd, null, null) : ExpressionUtils.getAppIdEqualityExpression(value, expr2, storeMgr, clr, cmd, null, null));
                // TODO Allow for !equals
                }
                // Value not persistable nor an identity, so return nothing "(1 = 0)"
                return exprFactory.newLiteral(stmt, expr1.mapping, false).eq(exprFactory.newLiteral(stmt, expr1.mapping, true));
            // TODO Allow for !equals
            }
        }
    } else {
        // ObjectExpression == ObjectExpression
        BooleanExpression resultExpr = null;
        for (int i = 0; i < expr1.subExprs.size(); i++) {
            SQLExpression sourceExpr = expr1.subExprs.getExpression(i);
            SQLExpression targetExpr = expr2.subExprs.getExpression(i);
            if (resultExpr == null) {
                resultExpr = sourceExpr.eq(targetExpr);
            } else {
                resultExpr = resultExpr.and(sourceExpr.eq(targetExpr));
            }
        }
        if (!equals) {
            resultExpr = new BooleanExpression(Expression.OP_NOT, resultExpr != null ? resultExpr.encloseInParentheses() : null);
        }
        return resultExpr;
    }
    return null;
}
Also used : ApiAdapter(org.datanucleus.api.ApiAdapter) JavaTypeMapping(org.datanucleus.store.rdbms.mapping.java.JavaTypeMapping) ClassLoaderResolver(org.datanucleus.ClassLoaderResolver) SQLStatement(org.datanucleus.store.rdbms.sql.SQLStatement) AbstractClassMetaData(org.datanucleus.metadata.AbstractClassMetaData) RDBMSStoreManager(org.datanucleus.store.rdbms.RDBMSStoreManager) PersistableMapping(org.datanucleus.store.rdbms.mapping.java.PersistableMapping) ExecutionContext(org.datanucleus.ExecutionContext) ReferenceMapping(org.datanucleus.store.rdbms.mapping.java.ReferenceMapping) DatastoreClass(org.datanucleus.store.rdbms.table.DatastoreClass) AbstractMemberMetaData(org.datanucleus.metadata.AbstractMemberMetaData)

Example 77 with JavaTypeMapping

use of org.datanucleus.store.rdbms.mapping.java.JavaTypeMapping 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));
}
Also used : CollectionTable(org.datanucleus.store.rdbms.table.CollectionTable) Table(org.datanucleus.store.rdbms.table.Table) ClassTable(org.datanucleus.store.rdbms.table.ClassTable) SQLTable(org.datanucleus.store.rdbms.sql.SQLTable) SQLExpression(org.datanucleus.store.rdbms.sql.expression.SQLExpression) CollectionTable(org.datanucleus.store.rdbms.table.CollectionTable) JavaTypeMapping(org.datanucleus.store.rdbms.mapping.java.JavaTypeMapping) SQLTable(org.datanucleus.store.rdbms.sql.SQLTable) NumericExpression(org.datanucleus.store.rdbms.sql.expression.NumericExpression) NucleusException(org.datanucleus.exceptions.NucleusException) AbstractMemberMetaData(org.datanucleus.metadata.AbstractMemberMetaData)

Example 78 with JavaTypeMapping

use of org.datanucleus.store.rdbms.mapping.java.JavaTypeMapping 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;
}
Also used : SelectStatement(org.datanucleus.store.rdbms.sql.SelectStatement) CollectionTable(org.datanucleus.store.rdbms.table.CollectionTable) Table(org.datanucleus.store.rdbms.table.Table) SQLTable(org.datanucleus.store.rdbms.sql.SQLTable) SQLExpressionFactory(org.datanucleus.store.rdbms.sql.expression.SQLExpressionFactory) SQLExpression(org.datanucleus.store.rdbms.sql.expression.SQLExpression) JavaTypeMapping(org.datanucleus.store.rdbms.mapping.java.JavaTypeMapping) ClassLoaderResolver(org.datanucleus.ClassLoaderResolver) DatastoreClass(org.datanucleus.store.rdbms.table.DatastoreClass) AbstractMemberMetaData(org.datanucleus.metadata.AbstractMemberMetaData) RDBMSStoreManager(org.datanucleus.store.rdbms.RDBMSStoreManager) SubqueryExpression(org.datanucleus.store.rdbms.sql.expression.SubqueryExpression)

Example 79 with JavaTypeMapping

use of org.datanucleus.store.rdbms.mapping.java.JavaTypeMapping 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);
}
Also used : SQLExpressionFactory(org.datanucleus.store.rdbms.sql.expression.SQLExpressionFactory) SQLExpression(org.datanucleus.store.rdbms.sql.expression.SQLExpression) JavaTypeMapping(org.datanucleus.store.rdbms.mapping.java.JavaTypeMapping) ClassLoaderResolver(org.datanucleus.ClassLoaderResolver) UnboundExpression(org.datanucleus.store.rdbms.sql.expression.UnboundExpression) AbstractClassMetaData(org.datanucleus.metadata.AbstractClassMetaData) RDBMSStoreManager(org.datanucleus.store.rdbms.RDBMSStoreManager) SelectStatement(org.datanucleus.store.rdbms.sql.SelectStatement) CollectionTable(org.datanucleus.store.rdbms.table.CollectionTable) BooleanSubqueryExpression(org.datanucleus.store.rdbms.sql.expression.BooleanSubqueryExpression) SQLTable(org.datanucleus.store.rdbms.sql.SQLTable) DatastoreClass(org.datanucleus.store.rdbms.table.DatastoreClass) DatastoreClass(org.datanucleus.store.rdbms.table.DatastoreClass) AbstractMemberMetaData(org.datanucleus.metadata.AbstractMemberMetaData) JoinTable(org.datanucleus.store.rdbms.table.JoinTable)

Example 80 with JavaTypeMapping

use of org.datanucleus.store.rdbms.mapping.java.JavaTypeMapping in project datanucleus-rdbms by datanucleus.

the class SQLExpressionFactory method getMappingForType.

/**
 * Accessor for a mapping to use in a query expression.
 * @param cls The class that the mapping should represent.
 * @param useCached Whether to use any cached mapping (if available)
 * @return The mapping
 */
public JavaTypeMapping getMappingForType(Class cls, boolean useCached) {
    JavaTypeMapping mapping = null;
    if (useCached) {
        mapping = mappingByClass.get(cls);
        if (mapping != null) {
            return mapping;
        }
    }
    mapping = storeMgr.getMappingManager().getMappingWithDatastoreMapping(cls, false, false, clr);
    mappingByClass.put(cls, mapping);
    return mapping;
}
Also used : JavaTypeMapping(org.datanucleus.store.rdbms.mapping.java.JavaTypeMapping)

Aggregations

JavaTypeMapping (org.datanucleus.store.rdbms.mapping.java.JavaTypeMapping)230 SQLExpression (org.datanucleus.store.rdbms.sql.expression.SQLExpression)96 AbstractMemberMetaData (org.datanucleus.metadata.AbstractMemberMetaData)82 RDBMSStoreManager (org.datanucleus.store.rdbms.RDBMSStoreManager)82 SQLExpressionFactory (org.datanucleus.store.rdbms.sql.expression.SQLExpressionFactory)81 DatastoreClass (org.datanucleus.store.rdbms.table.DatastoreClass)76 AbstractClassMetaData (org.datanucleus.metadata.AbstractClassMetaData)69 ArrayList (java.util.ArrayList)66 NucleusException (org.datanucleus.exceptions.NucleusException)57 ClassLoaderResolver (org.datanucleus.ClassLoaderResolver)50 NucleusUserException (org.datanucleus.exceptions.NucleusUserException)47 NumericExpression (org.datanucleus.store.rdbms.sql.expression.NumericExpression)43 SQLTable (org.datanucleus.store.rdbms.sql.SQLTable)37 PersistableMapping (org.datanucleus.store.rdbms.mapping.java.PersistableMapping)30 SelectStatement (org.datanucleus.store.rdbms.sql.SelectStatement)30 StringExpression (org.datanucleus.store.rdbms.sql.expression.StringExpression)27 List (java.util.List)25 ReferenceMapping (org.datanucleus.store.rdbms.mapping.java.ReferenceMapping)22 StatementMappingIndex (org.datanucleus.store.rdbms.query.StatementMappingIndex)21 StringLiteral (org.datanucleus.store.rdbms.sql.expression.StringLiteral)21