Search in sources :

Example 31 with SQLExpression

use of org.datanucleus.store.rdbms.sql.expression.SQLExpression in project datanucleus-rdbms by datanucleus.

the class FKMapStore method getSQLStatementForGet.

/**
 * Method to return an SQLStatement for retrieving the value for a key.
 * Selects the join table and optionally joins to the value table if it has its own table.
 * @param ownerOP ObjectProvider for the owning object
 * @return The SQLStatement
 */
protected SelectStatement getSQLStatementForGet(ObjectProvider ownerOP) {
    SelectStatement sqlStmt = null;
    ExecutionContext ec = ownerOP.getExecutionContext();
    final ClassLoaderResolver clr = ownerOP.getExecutionContext().getClassLoaderResolver();
    final Class valueCls = clr.classForName(this.valueType);
    if (ownerMemberMetaData.getMap().getMapType() == MapType.MAP_TYPE_KEY_IN_VALUE) {
        getMappingDef = new StatementClassMapping();
        if (valueTable.getDiscriminatorMetaData() != null && valueTable.getDiscriminatorMetaData().getStrategy() != DiscriminatorStrategy.NONE) {
            // Value class has discriminator
            if (ClassUtils.isReferenceType(valueCls)) {
                String[] clsNames = storeMgr.getNucleusContext().getMetaDataManager().getClassesImplementingInterface(valueType, clr);
                Class[] cls = new Class[clsNames.length];
                for (int i = 0; i < clsNames.length; i++) {
                    cls[i] = clr.classForName(clsNames[i]);
                }
                sqlStmt = new DiscriminatorStatementGenerator(storeMgr, clr, cls, true, null, null).getStatement(ec);
            } else {
                sqlStmt = new DiscriminatorStatementGenerator(storeMgr, clr, valueCls, true, null, null).getStatement(ec);
            }
            iterateUsingDiscriminator = true;
        } else {
            // Use union to resolve any subclasses of value
            UnionStatementGenerator stmtGen = new UnionStatementGenerator(storeMgr, clr, valueCls, true, null, null);
            stmtGen.setOption(SelectStatementGenerator.OPTION_SELECT_DN_TYPE);
            getMappingDef.setNucleusTypeColumnName(UnionStatementGenerator.DN_TYPE_COLUMN);
            sqlStmt = stmtGen.getStatement(ec);
        }
        // Select the value field(s)
        SQLStatementHelper.selectFetchPlanOfSourceClassInStatement(sqlStmt, getMappingDef, ec.getFetchPlan(), sqlStmt.getPrimaryTable(), valueCmd, ec.getFetchPlan().getMaxFetchDepth());
    } else {
        // Value is in key table
        sqlStmt = new SelectStatement(storeMgr, mapTable, null, null);
        sqlStmt.setClassLoaderResolver(clr);
        if (valueCmd != null) {
            // Left outer join to value table (so we allow for null values)
            SQLTable valueSqlTbl = sqlStmt.join(JoinType.LEFT_OUTER_JOIN, sqlStmt.getPrimaryTable(), valueMapping, valueTable, null, valueTable.getIdMapping(), null, null, true);
            // Select the value field(s)
            SQLStatementHelper.selectFetchPlanOfSourceClassInStatement(sqlStmt, getMappingDef, ec.getFetchPlan(), valueSqlTbl, valueCmd, ec.getFetchPlan().getMaxFetchDepth());
        } else {
            sqlStmt.select(sqlStmt.getPrimaryTable(), valueMapping, null);
        }
    }
    // Apply condition on owner field to filter by owner
    SQLExpressionFactory exprFactory = storeMgr.getSQLExpressionFactory();
    SQLTable ownerSqlTbl = SQLStatementHelper.getSQLTableForMappingOfTable(sqlStmt, sqlStmt.getPrimaryTable(), ownerMapping);
    SQLExpression ownerExpr = exprFactory.newExpression(sqlStmt, ownerSqlTbl, ownerMapping);
    SQLExpression ownerVal = exprFactory.newLiteralParameter(sqlStmt, ownerMapping, null, "OWNER");
    sqlStmt.whereAnd(ownerExpr.eq(ownerVal), true);
    // Apply condition on key
    if (keyMapping instanceof SerialisedMapping) {
        // if the keyMapping contains a BLOB column (or any other column not supported by the database
        // as primary key), uses like instead of the operator OP_EQ (=)
        // in future do not check if the keyMapping is of ObjectMapping, but use the database
        // adapter to check the data types not supported as primary key
        // if object mapping (BLOB) use like
        SQLExpression keyExpr = exprFactory.newExpression(sqlStmt, sqlStmt.getPrimaryTable(), keyMapping);
        SQLExpression keyVal = exprFactory.newLiteralParameter(sqlStmt, keyMapping, null, "KEY");
        sqlStmt.whereAnd(new org.datanucleus.store.rdbms.sql.expression.BooleanExpression(keyExpr, Expression.OP_LIKE, keyVal), true);
    } else {
        SQLExpression keyExpr = exprFactory.newExpression(sqlStmt, sqlStmt.getPrimaryTable(), keyMapping);
        SQLExpression keyVal = exprFactory.newLiteralParameter(sqlStmt, keyMapping, null, "KEY");
        sqlStmt.whereAnd(keyExpr.eq(keyVal), true);
    }
    // Input parameter(s) - owner, key
    int inputParamNum = 1;
    StatementMappingIndex ownerIdx = new StatementMappingIndex(ownerMapping);
    StatementMappingIndex keyIdx = new StatementMappingIndex(keyMapping);
    if (sqlStmt.getNumberOfUnions() > 0) {
        // Add parameter occurrence for each union of statement
        for (int j = 0; j < sqlStmt.getNumberOfUnions() + 1; j++) {
            int[] ownerPositions = new int[ownerMapping.getNumberOfDatastoreMappings()];
            for (int k = 0; k < ownerPositions.length; k++) {
                ownerPositions[k] = inputParamNum++;
            }
            ownerIdx.addParameterOccurrence(ownerPositions);
            int[] keyPositions = new int[keyMapping.getNumberOfDatastoreMappings()];
            for (int k = 0; k < keyPositions.length; k++) {
                keyPositions[k] = inputParamNum++;
            }
            keyIdx.addParameterOccurrence(keyPositions);
        }
    } else {
        int[] ownerPositions = new int[ownerMapping.getNumberOfDatastoreMappings()];
        for (int k = 0; k < ownerPositions.length; k++) {
            ownerPositions[k] = inputParamNum++;
        }
        ownerIdx.addParameterOccurrence(ownerPositions);
        int[] keyPositions = new int[keyMapping.getNumberOfDatastoreMappings()];
        for (int k = 0; k < keyPositions.length; k++) {
            keyPositions[k] = inputParamNum++;
        }
        keyIdx.addParameterOccurrence(keyPositions);
    }
    getMappingParams = new StatementParameterMapping();
    getMappingParams.addMappingForParameter("owner", ownerIdx);
    getMappingParams.addMappingForParameter("key", keyIdx);
    return sqlStmt;
}
Also used : StatementParameterMapping(org.datanucleus.store.rdbms.query.StatementParameterMapping) SQLExpressionFactory(org.datanucleus.store.rdbms.sql.expression.SQLExpressionFactory) SQLExpression(org.datanucleus.store.rdbms.sql.expression.SQLExpression) ClassLoaderResolver(org.datanucleus.ClassLoaderResolver) StatementMappingIndex(org.datanucleus.store.rdbms.query.StatementMappingIndex) StatementClassMapping(org.datanucleus.store.rdbms.query.StatementClassMapping) UnionStatementGenerator(org.datanucleus.store.rdbms.sql.UnionStatementGenerator) SelectStatement(org.datanucleus.store.rdbms.sql.SelectStatement) ExecutionContext(org.datanucleus.ExecutionContext) DiscriminatorStatementGenerator(org.datanucleus.store.rdbms.sql.DiscriminatorStatementGenerator) SQLTable(org.datanucleus.store.rdbms.sql.SQLTable) SerialisedMapping(org.datanucleus.store.rdbms.mapping.java.SerialisedMapping)

Example 32 with SQLExpression

use of org.datanucleus.store.rdbms.sql.expression.SQLExpression in project datanucleus-rdbms by datanucleus.

the class JoinListStore method getIteratorStatement.

/**
 * Method to return the SQLStatement and mapping for an iterator for this backing store.
 * Create a statement of the form
 * <pre>
 * SELECT ELEM_COLS
 * FROM JOIN_TBL
 *   [JOIN ELEM_TBL ON ELEM_TBL.ID = JOIN_TBL.ELEM_ID]
 * [WHERE]
 *   [JOIN_TBL.OWNER_ID = {value}] [AND]
 *   [JOIN_TBL.DISCRIM = {discrimValue}]
 * [ORDER BY {orderClause}]
 * </pre>
 * @param ec ExecutionContext
 * @param fp FetchPlan to use in determing which fields of element to select
 * @param addRestrictionOnOwner Whether to restrict to a particular owner (otherwise functions as bulk fetch for many owners).
 * @param startIdx Start index for the iterator (or -1)
 * @param endIdx End index for the iterator (or -1)
 * @return The SQLStatement and its associated StatementClassMapping
 */
public IteratorStatement getIteratorStatement(ExecutionContext ec, FetchPlan fp, boolean addRestrictionOnOwner, int startIdx, int endIdx) {
    SelectStatement sqlStmt = null;
    StatementClassMapping stmtClassMapping = new StatementClassMapping();
    SQLExpressionFactory exprFactory = storeMgr.getSQLExpressionFactory();
    if (elementsAreEmbedded || elementsAreSerialised) {
        // Element = embedded, serialised (maybe Non-PC)
        // Just select the join table since we're going to return the embedded/serialised columns from it
        sqlStmt = new SelectStatement(storeMgr, containerTable, null, null);
        sqlStmt.setClassLoaderResolver(clr);
        // Select the element column - first select is assumed by ListStoreIterator
        sqlStmt.select(sqlStmt.getPrimaryTable(), elementMapping, null);
    // TODO If embedded element and it includes 1-1/N-1 in FetchPlan then select its fields also
    } else if (elementMapping instanceof ReferenceMapping) {
        // Element = Reference type (interface/Object)
        // Just select the join table since we're going to return the implementation id columns only
        sqlStmt = new SelectStatement(storeMgr, containerTable, null, null);
        sqlStmt.setClassLoaderResolver(clr);
        // Select the reference column(s) - first select is assumed by ListStoreIterator
        sqlStmt.select(sqlStmt.getPrimaryTable(), elementMapping, null);
    } else {
        // Join to the element table(s)
        if (elementInfo != null) {
            for (int i = 0; i < elementInfo.length; i++) {
                // TODO This will only work if all element types have a discriminator
                final int elementNo = i;
                final Class elementCls = clr.classForName(elementInfo[elementNo].getClassName());
                SelectStatement elementStmt = null;
                if (elementInfo[elementNo].getDiscriminatorStrategy() != null && elementInfo[elementNo].getDiscriminatorStrategy() != DiscriminatorStrategy.NONE) {
                    // The element uses a discriminator so just use that in the SELECT
                    String elementType = ownerMemberMetaData.getCollection().getElementType();
                    if (ClassUtils.isReferenceType(clr.classForName(elementType))) {
                        String[] clsNames = storeMgr.getNucleusContext().getMetaDataManager().getClassesImplementingInterface(elementType, clr);
                        Class[] cls = new Class[clsNames.length];
                        for (int j = 0; j < clsNames.length; j++) {
                            cls[j] = clr.classForName(clsNames[j]);
                        }
                        SelectStatementGenerator stmtGen = new DiscriminatorStatementGenerator(storeMgr, clr, cls, true, null, null, containerTable, null, elementMapping);
                        if (allowNulls) {
                            stmtGen.setOption(SelectStatementGenerator.OPTION_ALLOW_NULLS);
                        }
                        elementStmt = stmtGen.getStatement(ec);
                    } else {
                        SelectStatementGenerator stmtGen = new DiscriminatorStatementGenerator(storeMgr, clr, elementCls, true, null, null, containerTable, null, elementMapping);
                        if (allowNulls) {
                            stmtGen.setOption(SelectStatementGenerator.OPTION_ALLOW_NULLS);
                        }
                        elementStmt = stmtGen.getStatement(ec);
                    }
                    iterateUsingDiscriminator = true;
                } else {
                    // No discriminator, but subclasses so use UNIONs
                    SelectStatementGenerator stmtGen = new UnionStatementGenerator(storeMgr, clr, elementCls, true, null, null, containerTable, null, elementMapping);
                    stmtGen.setOption(SelectStatementGenerator.OPTION_SELECT_DN_TYPE);
                    stmtClassMapping.setNucleusTypeColumnName(UnionStatementGenerator.DN_TYPE_COLUMN);
                    elementStmt = stmtGen.getStatement(ec);
                }
                if (sqlStmt == null) {
                    sqlStmt = elementStmt;
                } else {
                    sqlStmt.union(elementStmt);
                }
            }
            if (sqlStmt == null) {
                throw new NucleusException("Error in generation of SQL statement for iterator over (Join) list. Statement is null");
            }
            // Select the required fields
            SQLTable elementSqlTbl = sqlStmt.getTable(elementInfo[0].getDatastoreClass(), sqlStmt.getPrimaryTable().getGroupName());
            SQLStatementHelper.selectFetchPlanOfSourceClassInStatement(sqlStmt, stmtClassMapping, fp, elementSqlTbl, elementCmd, fp.getMaxFetchDepth());
        } else {
            throw new NucleusException("Unable to create SQL statement to retrieve elements of List");
        }
    }
    if (addRestrictionOnOwner) {
        // Apply condition on join-table owner field to filter by owner
        SQLTable ownerSqlTbl = SQLStatementHelper.getSQLTableForMappingOfTable(sqlStmt, sqlStmt.getPrimaryTable(), ownerMapping);
        SQLExpression ownerExpr = exprFactory.newExpression(sqlStmt, ownerSqlTbl, ownerMapping);
        SQLExpression ownerVal = exprFactory.newLiteralParameter(sqlStmt, ownerMapping, null, "OWNER");
        sqlStmt.whereAnd(ownerExpr.eq(ownerVal), true);
    }
    if (relationDiscriminatorMapping != null) {
        // Apply condition on distinguisher field to filter by distinguisher (when present)
        SQLTable distSqlTbl = SQLStatementHelper.getSQLTableForMappingOfTable(sqlStmt, sqlStmt.getPrimaryTable(), relationDiscriminatorMapping);
        SQLExpression distExpr = exprFactory.newExpression(sqlStmt, distSqlTbl, relationDiscriminatorMapping);
        SQLExpression distVal = exprFactory.newLiteral(sqlStmt, relationDiscriminatorMapping, relationDiscriminatorValue);
        sqlStmt.whereAnd(distExpr.eq(distVal), true);
    }
    if (indexedList) {
        // "Indexed List" so allow restriction on returned indexes
        boolean needsOrdering = true;
        if (startIdx == -1 && endIdx == -1) {
            // Just restrict to >= 0 so we don't get any disassociated elements
            SQLExpression indexExpr = exprFactory.newExpression(sqlStmt, sqlStmt.getPrimaryTable(), orderMapping);
            SQLExpression indexVal = exprFactory.newLiteral(sqlStmt, orderMapping, 0);
            sqlStmt.whereAnd(indexExpr.ge(indexVal), true);
        } else if (startIdx >= 0 && endIdx == startIdx) {
            // Particular index required so add restriction
            needsOrdering = false;
            SQLExpression indexExpr = exprFactory.newExpression(sqlStmt, sqlStmt.getPrimaryTable(), orderMapping);
            SQLExpression indexVal = exprFactory.newLiteral(sqlStmt, orderMapping, startIdx);
            sqlStmt.whereAnd(indexExpr.eq(indexVal), true);
        } else {
            // Add restrictions on start/end indices as required
            if (startIdx >= 0) {
                SQLExpression indexExpr = exprFactory.newExpression(sqlStmt, sqlStmt.getPrimaryTable(), orderMapping);
                SQLExpression indexVal = exprFactory.newLiteral(sqlStmt, orderMapping, startIdx);
                sqlStmt.whereAnd(indexExpr.ge(indexVal), true);
            } else {
                // Just restrict to >= 0 so we don't get any disassociated elements
                SQLExpression indexExpr = exprFactory.newExpression(sqlStmt, sqlStmt.getPrimaryTable(), orderMapping);
                SQLExpression indexVal = exprFactory.newLiteral(sqlStmt, orderMapping, 0);
                sqlStmt.whereAnd(indexExpr.ge(indexVal), true);
            }
            if (endIdx >= 0) {
                SQLExpression indexExpr2 = exprFactory.newExpression(sqlStmt, sqlStmt.getPrimaryTable(), orderMapping);
                SQLExpression indexVal2 = exprFactory.newLiteral(sqlStmt, orderMapping, endIdx);
                sqlStmt.whereAnd(indexExpr2.lt(indexVal2), true);
            }
        }
        if (needsOrdering) {
            // Order by the ordering column, when present
            SQLTable orderSqlTbl = SQLStatementHelper.getSQLTableForMappingOfTable(sqlStmt, sqlStmt.getPrimaryTable(), orderMapping);
            SQLExpression[] orderExprs = new SQLExpression[orderMapping.getNumberOfDatastoreMappings()];
            boolean[] descendingOrder = new boolean[orderMapping.getNumberOfDatastoreMappings()];
            orderExprs[0] = exprFactory.newExpression(sqlStmt, orderSqlTbl, orderMapping);
            sqlStmt.setOrdering(orderExprs, descendingOrder);
        }
    } else {
        if (elementInfo != null) {
            // Apply ordering defined by <order-by>
            DatastoreClass elementTbl = elementInfo[0].getDatastoreClass();
            FieldOrder[] orderComponents = ownerMemberMetaData.getOrderMetaData().getFieldOrders();
            SQLExpression[] orderExprs = new SQLExpression[orderComponents.length];
            boolean[] orderDirs = new boolean[orderComponents.length];
            for (int i = 0; i < orderComponents.length; i++) {
                String fieldName = orderComponents[i].getFieldName();
                JavaTypeMapping fieldMapping = elementTbl.getMemberMapping(elementInfo[0].getAbstractClassMetaData().getMetaDataForMember(fieldName));
                orderDirs[i] = !orderComponents[i].isForward();
                SQLTable fieldSqlTbl = SQLStatementHelper.getSQLTableForMappingOfTable(sqlStmt, sqlStmt.getPrimaryTable(), fieldMapping);
                orderExprs[i] = exprFactory.newExpression(sqlStmt, fieldSqlTbl, fieldMapping);
            }
            sqlStmt.setOrdering(orderExprs, orderDirs);
        }
    }
    return new IteratorStatement(this, sqlStmt, stmtClassMapping);
}
Also used : SQLExpressionFactory(org.datanucleus.store.rdbms.sql.expression.SQLExpressionFactory) SQLExpression(org.datanucleus.store.rdbms.sql.expression.SQLExpression) FieldOrder(org.datanucleus.metadata.OrderMetaData.FieldOrder) JavaTypeMapping(org.datanucleus.store.rdbms.mapping.java.JavaTypeMapping) StatementClassMapping(org.datanucleus.store.rdbms.query.StatementClassMapping) UnionStatementGenerator(org.datanucleus.store.rdbms.sql.UnionStatementGenerator) SelectStatementGenerator(org.datanucleus.store.rdbms.sql.SelectStatementGenerator) SelectStatement(org.datanucleus.store.rdbms.sql.SelectStatement) ReferenceMapping(org.datanucleus.store.rdbms.mapping.java.ReferenceMapping) DiscriminatorStatementGenerator(org.datanucleus.store.rdbms.sql.DiscriminatorStatementGenerator) SQLTable(org.datanucleus.store.rdbms.sql.SQLTable) DatastoreClass(org.datanucleus.store.rdbms.table.DatastoreClass) DatastoreClass(org.datanucleus.store.rdbms.table.DatastoreClass) NucleusException(org.datanucleus.exceptions.NucleusException)

Example 33 with SQLExpression

use of org.datanucleus.store.rdbms.sql.expression.SQLExpression in project datanucleus-rdbms by datanucleus.

the class DiscriminatorStatementGenerator method getStatement.

/**
 * Accessor for the SelectStatement.
 * @param ec ExecutionContext
 * @return The SelectStatement for iterating through objects with a discriminator column
 */
public SelectStatement getStatement(ExecutionContext ec) {
    SelectStatement stmt = null;
    SQLTable discrimSqlTbl = null;
    if (joinTable == null) {
        // Select of candidate table
        stmt = new SelectStatement(parentStmt, storeMgr, candidateTable, candidateTableAlias, candidateTableGroupName);
        stmt.setClassLoaderResolver(clr);
        discrimSqlTbl = stmt.getPrimaryTable();
    } else {
        // Select of join table, with join to element table
        stmt = new SelectStatement(parentStmt, storeMgr, joinTable, joinTableAlias, candidateTableGroupName);
        stmt.setClassLoaderResolver(clr);
        JavaTypeMapping candidateIdMapping = candidateTable.getIdMapping();
        if (hasOption(OPTION_ALLOW_NULLS)) {
            // Put element table in same table group since all relates to the elements
            discrimSqlTbl = stmt.join(JoinType.LEFT_OUTER_JOIN, null, joinElementMapping, candidateTable, null, candidateIdMapping, null, stmt.getPrimaryTable().getGroupName(), true);
        } else {
            // Put element table in same table group since all relates to the elements
            discrimSqlTbl = stmt.join(JoinType.INNER_JOIN, null, joinElementMapping, candidateTable, null, candidateIdMapping, null, stmt.getPrimaryTable().getGroupName(), true);
        }
    }
    JavaTypeMapping discMapping = candidateTable.getSurrogateMapping(SurrogateColumnType.DISCRIMINATOR, true);
    if (discMapping != null) {
        // Allow for discriminator being in super-table of the candidate table
        discrimSqlTbl = SQLStatementHelper.getSQLTableForMappingOfTable(stmt, discrimSqlTbl, discMapping);
    }
    DiscriminatorMetaData dismd = discrimSqlTbl.getTable().getDiscriminatorMetaData();
    boolean hasDiscriminator = (discMapping != null && dismd != null && dismd.getStrategy() != DiscriminatorStrategy.NONE);
    // Check if we can omit the discriminator restriction
    boolean restrictDiscriminator = hasOption(OPTION_RESTRICT_DISCRIM);
    if (hasDiscriminator && restrictDiscriminator) {
        // Add the discriminator expression to restrict accepted values
        boolean multipleCandidates = false;
        BooleanExpression discExpr = null;
        if (candidates != null) {
            // Multiple candidates
            if (candidates.length > 1) {
                multipleCandidates = true;
            }
            for (int i = 0; i < candidates.length; i++) {
                if (Modifier.isAbstract(candidates[i].getModifiers())) {
                    // No point selecting this candidate since can't be instantiated
                    continue;
                }
                BooleanExpression discExprCandidate = SQLStatementHelper.getExpressionForDiscriminatorForClass(stmt, candidates[i].getName(), dismd, discMapping, discrimSqlTbl, clr);
                if (discExpr != null) {
                    discExpr = discExpr.ior(discExprCandidate);
                } else {
                    discExpr = discExprCandidate;
                }
                if (includeSubclasses) {
                    Collection<String> subclassNames = storeMgr.getSubClassesForClass(candidateType.getName(), true, clr);
                    Iterator<String> subclassIter = subclassNames.iterator();
                    if (!multipleCandidates) {
                        multipleCandidates = (subclassNames.size() > 0);
                    }
                    while (subclassIter.hasNext()) {
                        String subclassName = subclassIter.next();
                        BooleanExpression discExprSub = SQLStatementHelper.getExpressionForDiscriminatorForClass(stmt, subclassName, dismd, discMapping, discrimSqlTbl, clr);
                        discExpr = discExpr.ior(discExprSub);
                    }
                }
            }
        } else {
            // Single candidate
            if (!Modifier.isAbstract(candidateType.getModifiers())) {
                discExpr = SQLStatementHelper.getExpressionForDiscriminatorForClass(stmt, candidateType.getName(), dismd, discMapping, discrimSqlTbl, clr);
            }
            if (includeSubclasses) {
                Collection<String> subclassNames = storeMgr.getSubClassesForClass(candidateType.getName(), true, clr);
                Iterator<String> subclassIter = subclassNames.iterator();
                multipleCandidates = (subclassNames.size() > 0);
                while (subclassIter.hasNext()) {
                    String subclassName = subclassIter.next();
                    Class subclass = clr.classForName(subclassName);
                    if ((Modifier.isAbstract(subclass.getModifiers()))) {
                        continue;
                    }
                    BooleanExpression discExprCandidate = SQLStatementHelper.getExpressionForDiscriminatorForClass(stmt, subclassName, dismd, discMapping, discrimSqlTbl, clr);
                    if (discExpr == null) {
                        discExpr = discExprCandidate;
                    } else {
                        discExpr = discExpr.ior(discExprCandidate);
                    }
                }
            }
            if (discExpr == null) {
                // No possible candidates, so set expression as "1=0"
                SQLExpressionFactory exprFactory = stmt.getSQLExpressionFactory();
                JavaTypeMapping m = exprFactory.getMappingForType(boolean.class, true);
                discExpr = exprFactory.newLiteral(stmt, m, true).eq(exprFactory.newLiteral(stmt, m, false));
            }
        }
        if (discExpr != null) {
            if (hasOption(OPTION_ALLOW_NULLS)) {
                // Allow for null value of discriminator
                SQLExpression expr = stmt.getSQLExpressionFactory().newExpression(stmt, discrimSqlTbl, discMapping);
                SQLExpression val = new NullLiteral(stmt, null, null, null);
                BooleanExpression nullDiscExpr = expr.eq(val);
                discExpr = discExpr.ior(nullDiscExpr);
                if (!multipleCandidates) {
                    multipleCandidates = true;
                }
            }
            // Apply the discriminator to the query statement
            if (multipleCandidates) {
                discExpr.encloseInParentheses();
            }
            stmt.whereAnd(discExpr, true);
        }
    }
    JavaTypeMapping multitenancyMapping = candidateTable.getSurrogateMapping(SurrogateColumnType.MULTITENANCY, false);
    if (multitenancyMapping != null) {
        // Multi-tenancy restriction
        AbstractClassMetaData cmd = candidateTable.getClassMetaData();
        SQLTable tenantSqlTbl = stmt.getTable(multitenancyMapping.getTable(), discrimSqlTbl.getGroupName());
        SQLExpression tenantExpr = stmt.getSQLExpressionFactory().newExpression(stmt, tenantSqlTbl, multitenancyMapping);
        SQLExpression tenantVal = stmt.getSQLExpressionFactory().newLiteral(stmt, multitenancyMapping, ec.getNucleusContext().getMultiTenancyId(ec, cmd));
        stmt.whereAnd(tenantExpr.eq(tenantVal), true);
    }
    JavaTypeMapping softDeleteMapping = candidateTable.getSurrogateMapping(SurrogateColumnType.SOFTDELETE, false);
    if (softDeleteMapping != null && !hasOption(OPTION_INCLUDE_SOFT_DELETES)) {
        // Soft-delete restriction
        SQLTable softDeleteSqlTbl = stmt.getTable(softDeleteMapping.getTable(), discrimSqlTbl.getGroupName());
        SQLExpression softDeleteExpr = stmt.getSQLExpressionFactory().newExpression(stmt, softDeleteSqlTbl, softDeleteMapping);
        SQLExpression softDeleteVal = stmt.getSQLExpressionFactory().newLiteral(stmt, softDeleteMapping, Boolean.FALSE);
        stmt.whereAnd(softDeleteExpr.eq(softDeleteVal), true);
    }
    return stmt;
}
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) AbstractClassMetaData(org.datanucleus.metadata.AbstractClassMetaData) DiscriminatorMetaData(org.datanucleus.metadata.DiscriminatorMetaData) BooleanExpression(org.datanucleus.store.rdbms.sql.expression.BooleanExpression) NullLiteral(org.datanucleus.store.rdbms.sql.expression.NullLiteral)

Example 34 with SQLExpression

use of org.datanucleus.store.rdbms.sql.expression.SQLExpression in project datanucleus-rdbms by datanucleus.

the class SelectStatement method generateOrderingStatement.

/**
 * Convenience method to generate the ordering statement to add to the overall query statement.
 * @return The ordering statement
 */
protected SQLText generateOrderingStatement() {
    SQLText orderStmt = null;
    if (orderingExpressions != null && orderingExpressions.length > 0) {
        DatastoreAdapter dba = getDatastoreAdapter();
        if (dba.supportsOption(DatastoreAdapter.ORDERBY_USING_SELECT_COLUMN_INDEX)) {
            // Order using the indexes of the ordering columns in the SELECT
            orderStmt = new SQLText();
            for (int i = 0; i < orderingExpressions.length; ++i) {
                if (i > 0) {
                    orderStmt.append(',');
                }
                orderStmt.append(Integer.toString(orderingColumnIndexes[i]));
                if (orderingDirections[i]) {
                    orderStmt.append(" DESC");
                }
                if (orderNullDirectives != null && orderNullDirectives[i] != null && dba.supportsOption(DatastoreAdapter.ORDERBY_NULLS_DIRECTIVES)) {
                    // Apply "NULLS [FIRST | LAST]" since supported by this datastore
                    orderStmt.append(" " + (orderNullDirectives[i] == NullOrderingType.NULLS_FIRST ? "NULLS FIRST" : "NULLS LAST"));
                }
            }
        } else {
            // TODO Cater for ResultAliasExpression, so we just put the order aliasName
            // Order using column aliases "NUCORDER{i}"
            orderStmt = new SQLText();
            boolean needsSelect = dba.supportsOption(DatastoreAdapter.INCLUDE_ORDERBY_COLS_IN_SELECT);
            if (parent != null) {
                // Don't select ordering columns with subqueries, since we will select just the required column(s)
                needsSelect = false;
            }
            for (int i = 0; i < orderingExpressions.length; ++i) {
                SQLExpression orderExpr = orderingExpressions[i];
                boolean orderDirection = orderingDirections[i];
                NullOrderingType orderNullDirective = (orderNullDirectives != null ? orderNullDirectives[i] : null);
                if (i > 0) {
                    orderStmt.append(',');
                }
                if (needsSelect && !aggregated) {
                    if (orderExpr instanceof ResultAliasExpression) {
                        String orderStr = rdbmsMgr.getIdentifierFactory().getIdentifierInAdapterCase(((ResultAliasExpression) orderExpr).getResultAlias());
                        addOrderComponent(orderStmt, orderStr, orderExpr, orderDirection, orderNullDirective, dba);
                    } else {
                        // Order by the "NUCORDER?" if we need them to be selected and it isn't an aggregate
                        String orderString = "NUCORDER" + i;
                        if (orderExpr.getNumberOfSubExpressions() == 1) {
                            String orderStr = rdbmsMgr.getIdentifierFactory().getIdentifierInAdapterCase(orderString);
                            addOrderComponent(orderStmt, orderStr, orderExpr, orderDirection, orderNullDirective, dba);
                        } else {
                            DatastoreMapping[] mappings = orderExpr.getJavaTypeMapping().getDatastoreMappings();
                            for (int j = 0; j < mappings.length; j++) {
                                String orderStr = rdbmsMgr.getIdentifierFactory().getIdentifierInAdapterCase(orderString + "_" + j);
                                addOrderComponent(orderStmt, orderStr, orderExpr, orderDirection, orderNullDirective, dba);
                                if (j < mappings.length - 1) {
                                    orderStmt.append(',');
                                }
                            }
                        }
                    }
                } else {
                    if (orderExpr instanceof ResultAliasExpression) {
                        String orderStr = rdbmsMgr.getIdentifierFactory().getIdentifierInAdapterCase(((ResultAliasExpression) orderExpr).getResultAlias());
                        addOrderComponent(orderStmt, orderStr, orderExpr, orderDirection, orderNullDirective, dba);
                    } else {
                        // Order by the "THIS.COLUMN" otherwise
                        addOrderComponent(orderStmt, orderExpr.toSQLText().toSQL(), orderExpr, orderDirection, orderNullDirective, dba);
                    }
                }
            }
        }
    }
    return orderStmt;
}
Also used : NullOrderingType(org.datanucleus.query.NullOrderingType) SQLExpression(org.datanucleus.store.rdbms.sql.expression.SQLExpression) ResultAliasExpression(org.datanucleus.store.rdbms.sql.expression.ResultAliasExpression) DatastoreMapping(org.datanucleus.store.rdbms.mapping.datastore.DatastoreMapping) DatastoreAdapter(org.datanucleus.store.rdbms.adapter.DatastoreAdapter)

Example 35 with SQLExpression

use of org.datanucleus.store.rdbms.sql.expression.SQLExpression in project datanucleus-rdbms by datanucleus.

the class MapContainsKeyMethod 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 expr, List<SQLExpression> args) {
    if (args == null || args.size() == 0 || args.size() > 1) {
        throw new NucleusException(Localiser.msg("060016", "containsKey", "MapExpression", 1));
    }
    MapExpression mapExpr = (MapExpression) expr;
    SQLExpression keyExpr = args.get(0);
    if (keyExpr.isParameter()) {
        // Key is a parameter so make sure its type is set
        AbstractMemberMetaData mmd = mapExpr.getJavaTypeMapping().getMemberMetaData();
        if (mmd != null && mmd.getMap() != null) {
            Class keyCls = stmt.getQueryGenerator().getClassLoaderResolver().classForName(mmd.getMap().getKeyType());
            stmt.getQueryGenerator().bindParameter(keyExpr.getParameterName(), keyCls);
        }
    }
    SQLExpressionFactory exprFactory = stmt.getSQLExpressionFactory();
    ClassLoaderResolver clr = stmt.getQueryGenerator().getClassLoaderResolver();
    if (expr instanceof MapLiteral) {
        // Literal Map
        MapLiteral lit = (MapLiteral) expr;
        Map map = (Map) lit.getValue();
        JavaTypeMapping m = exprFactory.getMappingForType(boolean.class, true);
        if (map == null || map.size() == 0) {
            return exprFactory.newLiteral(stmt, m, true).eq(exprFactory.newLiteral(stmt, m, false));
        }
        boolean useInExpression = false;
        List<SQLExpression> mapKeyExprs = lit.getKeyLiteral().getKeyExpressions();
        if (mapKeyExprs != null && !mapKeyExprs.isEmpty()) {
            // Make sure the the map key(s) are compatible with the keyExpr
            boolean incompatible = true;
            Class elemtype = clr.classForName(keyExpr.getJavaTypeMapping().getType());
            Iterator<SQLExpression> mapKeyExprIter = mapKeyExprs.iterator();
            while (mapKeyExprIter.hasNext()) {
                SQLExpression mapKeyExpr = mapKeyExprIter.next();
                Class mapKeyType = clr.classForName(mapKeyExpr.getJavaTypeMapping().getType());
                if (keyTypeCompatible(elemtype, mapKeyType)) {
                    incompatible = false;
                    break;
                }
            }
            if (incompatible) {
                // The provided element type isn't assignable to any of the input collection elements!
                return exprFactory.newLiteral(stmt, m, true).eq(exprFactory.newLiteral(stmt, m, false));
            }
            // Check if we should compare using an "IN (...)" expression
            SQLExpression mapKeyExpr = mapKeyExprs.get(0);
            if (mapKeyExpr instanceof StringExpression || mapKeyExpr instanceof NumericExpression || mapKeyExpr instanceof TemporalExpression || mapKeyExpr instanceof CharacterExpression || mapKeyExpr instanceof EnumExpression) {
                useInExpression = true;
            }
        }
        if (useInExpression) {
            // Return "key IN (val1, val2, ...)"
            SQLExpression[] exprs = (mapKeyExprs != null ? mapKeyExprs.toArray(new SQLExpression[mapKeyExprs.size()]) : null);
            return new InExpression(keyExpr, exprs);
        }
        // TODO If keyExpr is a parameter and mapExpr is derived from a parameter ?
        MapKeyLiteral mapKeyLiteral = lit.getKeyLiteral();
        BooleanExpression bExpr = null;
        List<SQLExpression> elementExprs = mapKeyLiteral.getKeyExpressions();
        for (int i = 0; i < elementExprs.size(); i++) {
            if (bExpr == null) {
                bExpr = (elementExprs.get(i)).eq(keyExpr);
            } else {
                bExpr = bExpr.ior((elementExprs.get(i)).eq(keyExpr));
            }
        }
        if (bExpr != null) {
            bExpr.encloseInParentheses();
        }
        return bExpr;
    }
    if (stmt.getQueryGenerator().getCompilationComponent() == CompilationComponent.FILTER) {
        boolean useSubquery = getNeedsSubquery(stmt);
        JoinType joinType = JoinType.INNER_JOIN;
        if (keyExpr instanceof UnboundExpression) {
            // See if the user has defined what should be used
            String varName = ((UnboundExpression) keyExpr).getVariableName();
            String extensionName = "datanucleus.query.jdoql." + varName + ".join";
            String extensionValue = (String) stmt.getQueryGenerator().getValueForExtension(extensionName);
            if (extensionValue != null) {
                if (extensionValue.equalsIgnoreCase("SUBQUERY")) {
                    useSubquery = true;
                } else if (extensionValue.equalsIgnoreCase("INNERJOIN")) {
                    useSubquery = false;
                } else if (extensionValue.equalsIgnoreCase("LEFTOUTERJOIN")) {
                    joinType = JoinType.LEFT_OUTER_JOIN;
                }
            }
        }
        // TODO Check if *this* "containsKey" is negated, not any of them (and remove above check)
        if (useSubquery) {
            return containsAsSubquery(stmt, mapExpr, keyExpr);
        }
        return containsAsJoin(stmt, mapExpr, keyExpr, joinType);
    }
    return containsAsSubquery(stmt, mapExpr, keyExpr);
}
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) InExpression(org.datanucleus.store.rdbms.sql.expression.InExpression) UnboundExpression(org.datanucleus.store.rdbms.sql.expression.UnboundExpression) BooleanExpression(org.datanucleus.store.rdbms.sql.expression.BooleanExpression) MapExpression(org.datanucleus.store.rdbms.sql.expression.MapExpression) TemporalExpression(org.datanucleus.store.rdbms.sql.expression.TemporalExpression) ClassLoaderResolver(org.datanucleus.ClassLoaderResolver) NumericExpression(org.datanucleus.store.rdbms.sql.expression.NumericExpression) JoinType(org.datanucleus.store.rdbms.sql.SQLJoin.JoinType) EnumExpression(org.datanucleus.store.rdbms.sql.expression.EnumExpression) CharacterExpression(org.datanucleus.store.rdbms.sql.expression.CharacterExpression) MapLiteral(org.datanucleus.store.rdbms.sql.expression.MapLiteral) StringExpression(org.datanucleus.store.rdbms.sql.expression.StringExpression) DatastoreClass(org.datanucleus.store.rdbms.table.DatastoreClass) NucleusException(org.datanucleus.exceptions.NucleusException) AbstractMemberMetaData(org.datanucleus.metadata.AbstractMemberMetaData) Map(java.util.Map) MapKeyLiteral(org.datanucleus.store.rdbms.sql.expression.MapLiteral.MapKeyLiteral)

Aggregations

SQLExpression (org.datanucleus.store.rdbms.sql.expression.SQLExpression)199 SQLExpressionFactory (org.datanucleus.store.rdbms.sql.expression.SQLExpressionFactory)98 JavaTypeMapping (org.datanucleus.store.rdbms.mapping.java.JavaTypeMapping)95 ArrayList (java.util.ArrayList)75 NumericExpression (org.datanucleus.store.rdbms.sql.expression.NumericExpression)74 NucleusException (org.datanucleus.exceptions.NucleusException)63 RDBMSStoreManager (org.datanucleus.store.rdbms.RDBMSStoreManager)56 DatastoreClass (org.datanucleus.store.rdbms.table.DatastoreClass)47 NucleusUserException (org.datanucleus.exceptions.NucleusUserException)44 StringExpression (org.datanucleus.store.rdbms.sql.expression.StringExpression)41 BooleanExpression (org.datanucleus.store.rdbms.sql.expression.BooleanExpression)40 SelectStatement (org.datanucleus.store.rdbms.sql.SelectStatement)35 ClassLoaderResolver (org.datanucleus.ClassLoaderResolver)34 AbstractMemberMetaData (org.datanucleus.metadata.AbstractMemberMetaData)34 SQLTable (org.datanucleus.store.rdbms.sql.SQLTable)34 UnboundExpression (org.datanucleus.store.rdbms.sql.expression.UnboundExpression)31 SQLLiteral (org.datanucleus.store.rdbms.sql.expression.SQLLiteral)29 NullLiteral (org.datanucleus.store.rdbms.sql.expression.NullLiteral)28 ParameterLiteral (org.datanucleus.store.rdbms.sql.expression.ParameterLiteral)28 AbstractClassMetaData (org.datanucleus.metadata.AbstractClassMetaData)25