Search in sources :

Example 1 with CreatorExpression

use of org.datanucleus.query.expression.CreatorExpression in project datanucleus-core by datanucleus.

the class JavaQueryInMemoryEvaluator method execute.

/**
 * Method to perform the evaluation, applying the query restrictions that are required.
 * @param applyFilter Whether to apply any filter constraints on the results
 * @param applyOrdering Whether to apply any order constraints on the results
 * @param applyResult Whether to apply any result/grouping/having on the results
 * @param applyResultClass Whether to apply any resultClass constraint on the results
 * @param applyRange Whether to apply any range constraint on the results
 * @return The results after evaluation.
 */
public Collection execute(boolean applyFilter, boolean applyOrdering, boolean applyResult, boolean applyResultClass, boolean applyRange) {
    if (!applyFilter && !applyOrdering && !applyResult && !applyResultClass && !applyRange) {
        // Nothing to evaluate in-memory
        return candidates;
    }
    Collection executeCandidates = new ArrayList();
    Expression[] result = compilation.getExprResult();
    if (candidates != null) {
        if (applyResult && result != null && result.length > 1) {
            // Have result but not returning rows of candidate type so remove dupd candidates
            Iterator candIter = candidates.iterator();
            while (candIter.hasNext()) {
                Object candidate = candIter.next();
                if (!executeCandidates.contains(candidate)) {
                    executeCandidates.add(candidate);
                }
            }
        } else {
            executeCandidates.addAll(candidates);
        }
    }
    // Really we should aim to have the following order of execution of the different components : FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY
    // TODO Retain variables across the different parts of the query. Currently evaluated in filter then forgotten
    // TODO Where the subquery makes use of the parent query candidate, set the candidates for the subquery using that. This currently just passes the same parent candidates in!
    String[] subqueryAliases = compilation.getSubqueryAliases();
    if (subqueryAliases != null) {
        for (int i = 0; i < subqueryAliases.length; i++) {
            // Evaluate subquery first
            Query subquery = query.getSubqueryForVariable(subqueryAliases[i]).getQuery();
            QueryCompilation subqueryCompilation = compilation.getCompilationForSubquery(subqueryAliases[i]);
            if (subqueryCompilation.getExprFrom() != null) {
                // TODO Evaluate "from"
                NucleusLogger.QUERY.warn("In-memory evaluation of subquery with 'from'=" + StringUtils.objectArrayToString(subqueryCompilation.getExprFrom()) + " but from clause evaluation not currently supported!");
            }
            Collection subqueryResult = evaluateSubquery(subquery, subqueryCompilation, executeCandidates, null);
            if (QueryUtils.queryReturnsSingleRow(subquery)) {
                // Subquery is expected to return single value
                state.put(subqueryAliases[i], subqueryResult.iterator().next());
            } else {
                state.put(subqueryAliases[i], subqueryResult);
            }
        }
    }
    // Evaluate filter
    List resultSet = new ArrayList(executeCandidates);
    Expression filter = compilation.getExprFilter();
    if (applyFilter && filter != null) {
        // Process any filter constraints
        if (NucleusLogger.QUERY.isDebugEnabled()) {
            NucleusLogger.QUERY.debug(Localiser.msg("021012", "filter", language, filter));
        }
        resultSet = handleFilter(resultSet);
    }
    Expression[] ordering = compilation.getExprOrdering();
    if (applyOrdering && ordering != null) {
        // Process any ordering constraints
        if (NucleusLogger.QUERY.isDebugEnabled()) {
            NucleusLogger.QUERY.debug(Localiser.msg("021012", "ordering", language, StringUtils.objectArrayToString(ordering)));
        }
        resultSet = ordering(resultSet);
    }
    if (applyRange && query.getRange() != null) {
        // Process any range constraints
        long fromIncl = query.getRangeFromIncl();
        long toExcl = query.getRangeToExcl();
        if (query.getRangeFromInclParam() != null) {
            fromIncl = ((Number) parameterValues.get(query.getRangeFromInclParam())).longValue();
        }
        if (query.getRangeToExclParam() != null) {
            toExcl = ((Number) parameterValues.get(query.getRangeToExclParam())).longValue();
        }
        if (NucleusLogger.QUERY.isDebugEnabled()) {
            NucleusLogger.QUERY.debug(Localiser.msg("021012", "range", language, "" + fromIncl + "," + toExcl));
        }
        resultSet = handleRange(resultSet, fromIncl, toExcl);
    }
    if (applyResult && result != null) {
        // Process any result/grouping/having constraints
        if (NucleusLogger.QUERY.isDebugEnabled()) {
            NucleusLogger.QUERY.debug(Localiser.msg("021012", "result", language, StringUtils.objectArrayToString(result)));
        }
        // Apply grouping
        List aggregateList = new ArrayList();
        List s = resultSet;
        Expression[] grouping = compilation.getExprGrouping();
        if (grouping != null) {
            s = sortByGrouping(resultSet);
        }
        aggregateList = s;
        // TODO Move this to within sortByGrouping
        if (grouping != null) {
            aggregateList = handleAggregates(s);
        }
        resultSet = handleResult(aggregateList);
        if (query.getResultDistinct()) {
            List tmpList = new ArrayList();
            Iterator iter = resultSet.iterator();
            while (iter.hasNext()) {
                Object obj = iter.next();
                if (// Omit dups
                !tmpList.contains(obj)) {
                    tmpList.add(obj);
                }
            }
            resultSet = tmpList;
        }
    }
    if (applyResultClass && query.getResultClass() != null) {
        // Process any result class constraints
        if (NucleusLogger.QUERY.isDebugEnabled()) {
            NucleusLogger.QUERY.debug(Localiser.msg("021012", "resultClass", language, query.getResultClass().getName()));
        }
        if (result != null && !(result[0] instanceof CreatorExpression)) {
            return this.mapResultClass(resultSet);
        }
    }
    return resultSet;
}
Also used : Query(org.datanucleus.store.query.Query) ArrayList(java.util.ArrayList) CreatorExpression(org.datanucleus.query.expression.CreatorExpression) Expression(org.datanucleus.query.expression.Expression) InvokeExpression(org.datanucleus.query.expression.InvokeExpression) CreatorExpression(org.datanucleus.query.expression.CreatorExpression) Iterator(java.util.Iterator) Collection(java.util.Collection) ArrayList(java.util.ArrayList) List(java.util.List) QueryCompilation(org.datanucleus.query.compiler.QueryCompilation)

Example 2 with CreatorExpression

use of org.datanucleus.query.expression.CreatorExpression in project datanucleus-core by datanucleus.

the class JavaQueryInMemoryEvaluator method handleResult.

/**
 * Checks if there are aggregates and handles it.
 * @param resultSet The resultSet containing all elements
 * @return A list with aggregated elements
 */
private List handleResult(List resultSet) {
    List result = new ArrayList();
    final Expression[] grouping = compilation.getExprGrouping();
    if (grouping != null) {
        Comparator c = new Comparator() {

            public int compare(Object arg0, Object arg1) {
                for (int i = 0; i < grouping.length; i++) {
                    state.put(candidateAlias, arg0);
                    Object a = grouping[i].evaluate(evaluator);
                    state.put(candidateAlias, arg1);
                    Object b = grouping[i].evaluate(evaluator);
                    // Put any null values at the end
                    if (a == null && b == null) {
                        return 0;
                    } else if (a == null) {
                        return -1;
                    } else if (b == null) {
                        return 1;
                    } else {
                        int result = ((Comparable) a).compareTo(b);
                        if (result != 0) {
                            return result;
                        }
                    }
                }
                return 0;
            }
        };
        List groups = new ArrayList();
        List group = new ArrayList();
        if (!resultSet.isEmpty()) {
            groups.add(group);
        }
        for (int i = 0; i < resultSet.size(); i++) {
            if (i > 0) {
                if (c.compare(resultSet.get(i - 1), resultSet.get(i)) != 0) {
                    group = new ArrayList();
                    groups.add(group);
                }
            }
            group.add(resultSet.get(i));
        }
        // Apply the result to the generated groups
        for (int i = 0; i < groups.size(); i++) {
            group = (List) groups.get(i);
            result.add(result(group));
        }
    } else {
        boolean aggregates = false;
        Expression[] resultExprs = compilation.getExprResult();
        if (resultExprs.length > 0 && resultExprs[0] instanceof CreatorExpression) {
            Expression[] resExpr = ((CreatorExpression) resultExprs[0]).getArguments().toArray(new Expression[((CreatorExpression) resultExprs[0]).getArguments().size()]);
            for (int i = 0; i < resExpr.length; i++) {
                if (resExpr[i] instanceof InvokeExpression) {
                    String method = ((InvokeExpression) resExpr[i]).getOperation().toLowerCase();
                    if (method.equals("count") || method.equals("sum") || method.equals("avg") || method.equals("min") || method.equals("max")) {
                        aggregates = true;
                    }
                }
            }
        } else {
            for (int i = 0; i < resultExprs.length; i++) {
                if (resultExprs[i] instanceof InvokeExpression) {
                    String method = ((InvokeExpression) resultExprs[i]).getOperation().toLowerCase();
                    if (method.equals("count") || method.equals("sum") || method.equals("avg") || method.equals("min") || method.equals("max")) {
                        aggregates = true;
                    }
                }
            }
        }
        if (aggregates) {
            result.add(result(resultSet));
        } else {
            for (int i = 0; i < resultSet.size(); i++) {
                result.add(result(resultSet.get(i)));
            }
        }
    }
    if (!result.isEmpty() && ((Object[]) result.get(0)).length == 1) {
        List r = result;
        result = new ArrayList();
        for (int i = 0; i < r.size(); i++) {
            result.add(((Object[]) r.get(i))[0]);
        }
    }
    return result;
}
Also used : InvokeExpression(org.datanucleus.query.expression.InvokeExpression) Expression(org.datanucleus.query.expression.Expression) InvokeExpression(org.datanucleus.query.expression.InvokeExpression) CreatorExpression(org.datanucleus.query.expression.CreatorExpression) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) CreatorExpression(org.datanucleus.query.expression.CreatorExpression) Comparator(java.util.Comparator)

Aggregations

ArrayList (java.util.ArrayList)2 List (java.util.List)2 CreatorExpression (org.datanucleus.query.expression.CreatorExpression)2 Expression (org.datanucleus.query.expression.Expression)2 InvokeExpression (org.datanucleus.query.expression.InvokeExpression)2 Collection (java.util.Collection)1 Comparator (java.util.Comparator)1 Iterator (java.util.Iterator)1 QueryCompilation (org.datanucleus.query.compiler.QueryCompilation)1 Query (org.datanucleus.store.query.Query)1