Search in sources :

Example 31 with TypeMismatchException

use of org.apache.geode.cache.query.TypeMismatchException in project geode by apache.

the class CompiledIn method singleBaseCollectionFilterEvaluate.

/**
   * evaluate as a filter, involving a single iterator. Use an index if possible.
   *
   * Invariant: the receiver is dependent on the current iterator.
   */
private SelectResults singleBaseCollectionFilterEvaluate(ExecutionContext context, SelectResults intermediateResults, boolean completeExpansionNeeded, CompiledValue iterOperands, IndexInfo indexInfo, RuntimeIterator[] indpndntItr, boolean isIntersection, boolean conditioningNeeded, boolean evalProj) throws TypeMismatchException, AmbiguousNameException, FunctionDomainException, NameResolutionException, QueryInvocationTargetException {
    ObjectType resultType = indexInfo._index.getResultSetType();
    int indexFieldsSize = -1;
    SelectResults results = null;
    if (resultType instanceof StructType) {
        indexFieldsSize = ((StructTypeImpl) resultType).getFieldNames().length;
    } else {
        indexFieldsSize = 1;
    }
    boolean useLinkedDataStructure = false;
    boolean nullValuesAtStart = true;
    Boolean orderByClause = (Boolean) context.cacheGet(CompiledValue.CAN_APPLY_ORDER_BY_AT_INDEX);
    if (orderByClause != null && orderByClause) {
        List orderByAttrs = (List) context.cacheGet(CompiledValue.ORDERBY_ATTRIB);
        useLinkedDataStructure = orderByAttrs.size() == 1;
        nullValuesAtStart = !((CompiledSortCriterion) orderByAttrs.get(0)).getCriterion();
    }
    List projAttrib = null;
    ObjectType projResultType = null;
    if (!conditioningNeeded) {
        projResultType = evalProj ? (ObjectType) context.cacheGet(RESULT_TYPE) : null;
        if (projResultType != null) {
            resultType = projResultType;
            context.cachePut(RESULT_TYPE, Boolean.TRUE);
            projAttrib = (List) context.cacheGet(PROJ_ATTRIB);
        }
        if (isIntersection) {
            if (resultType instanceof StructType) {
                context.getCache().getLogger().fine("StructType resultType.class=" + resultType.getClass().getName());
                if (useLinkedDataStructure) {
                    results = context.isDistinct() ? new LinkedStructSet((StructTypeImpl) resultType) : new SortedResultsBag<Struct>((StructTypeImpl) resultType, nullValuesAtStart);
                } else {
                    results = QueryUtils.createStructCollection(context, (StructTypeImpl) resultType);
                }
                indexFieldsSize = ((StructTypeImpl) resultType).getFieldNames().length;
            } else {
                context.getCache().getLogger().fine("non-StructType resultType.class=" + resultType.getClass().getName());
                if (useLinkedDataStructure) {
                    results = context.isDistinct() ? new LinkedResultSet(resultType) : new SortedResultsBag(resultType, nullValuesAtStart);
                } else {
                    results = QueryUtils.createResultCollection(context, resultType);
                }
                indexFieldsSize = 1;
            }
        } else {
            if (intermediateResults != null && !completeExpansionNeeded) {
                results = intermediateResults;
            } else {
                if (resultType instanceof StructType) {
                    context.getCache().getLogger().fine("StructType resultType.class=" + resultType.getClass().getName());
                    if (useLinkedDataStructure) {
                        results = context.isDistinct() ? new LinkedStructSet((StructTypeImpl) resultType) : new SortedResultsBag<Struct>((StructTypeImpl) resultType, nullValuesAtStart);
                    } else {
                        results = QueryUtils.createStructCollection(context, (StructTypeImpl) resultType);
                    }
                    indexFieldsSize = ((StructTypeImpl) resultType).getFieldNames().length;
                } else {
                    context.getCache().getLogger().fine("non-StructType resultType.class=" + resultType.getClass().getName());
                    if (useLinkedDataStructure) {
                        results = context.isDistinct() ? new LinkedResultSet(resultType) : new SortedResultsBag(resultType, nullValuesAtStart);
                    } else {
                        results = QueryUtils.createResultCollection(context, resultType);
                    }
                    indexFieldsSize = 1;
                }
            }
        }
    } else {
        if (resultType instanceof StructType) {
            context.getCache().getLogger().fine("StructType resultType.class=" + resultType.getClass().getName());
            if (useLinkedDataStructure) {
                results = context.isDistinct() ? new LinkedStructSet((StructTypeImpl) resultType) : new SortedResultsBag<Struct>((StructTypeImpl) resultType, nullValuesAtStart);
            } else {
                results = QueryUtils.createStructCollection(context, (StructTypeImpl) resultType);
            }
            indexFieldsSize = ((StructTypeImpl) resultType).getFieldNames().length;
        } else {
            context.getCache().getLogger().fine("non-StructType resultType.class=" + resultType.getClass().getName());
            if (useLinkedDataStructure) {
                results = context.isDistinct() ? new LinkedResultSet(resultType) : new SortedResultsBag(resultType, nullValuesAtStart);
            } else {
                results = QueryUtils.createResultCollection(context, resultType);
            }
            indexFieldsSize = 1;
        }
    }
    QueryObserver observer = QueryObserverHolder.getInstance();
    try {
        Object evalColln = evaluateColln(context);
        observer.beforeIndexLookup(indexInfo._index, TOK_EQ, evalColln);
        // unexpected values overwriting expected values
        if (!conditioningNeeded) {
            if (projResultType != null) {
                resultType = projResultType;
                context.cachePut(RESULT_TYPE, Boolean.TRUE);
            }
        }
        // handle each type of collection that we support
        if (evalColln instanceof Map) {
            Iterator itr = ((Map) evalColln).entrySet().iterator();
            while (itr.hasNext()) {
                this.queryIndex(itr.next(), indexInfo, results, iterOperands, indpndntItr, context, projAttrib, conditioningNeeded);
            }
        } else if (evalColln instanceof Collection) {
            Object key = indexInfo.evaluateIndexKey(context);
            // and the evalColln in the [0] position
            if (key instanceof Object[]) {
                Iterator iterator = ((Iterable) ((Object[]) key)[0]).iterator();
                while (iterator.hasNext()) {
                    this.queryIndex(new Object[] { iterator.next(), ((Object[]) key)[1] }, indexInfo, results, iterOperands, indpndntItr, context, projAttrib, conditioningNeeded);
                }
            } else {
                // Removing duplicates from the collection
                HashSet set = new HashSet((Collection) evalColln);
                Iterator itr = set.iterator();
                while (itr.hasNext()) {
                    this.queryIndex(itr.next(), indexInfo, results, iterOperands, indpndntItr, context, projAttrib, conditioningNeeded);
                }
            }
        } else {
            if (!evalColln.getClass().isArray()) {
                throw new TypeMismatchException("Operand of IN cannot be interpreted as a Collection. " + "Is instance of " + evalColln.getClass().getName());
            }
            if (evalColln instanceof Object[]) {
                Object[] arr = (Object[]) evalColln;
                for (int i = 0; i < arr.length; ++i) {
                    this.queryIndex(arr[i], indexInfo, results, iterOperands, indpndntItr, context, projAttrib, conditioningNeeded);
                }
            } else if (evalColln instanceof long[]) {
                long[] a = (long[]) evalColln;
                for (int i = 0; i < a.length; i++) {
                    this.queryIndex(a[i], indexInfo, results, iterOperands, indpndntItr, context, projAttrib, conditioningNeeded);
                }
            } else if (evalColln instanceof double[]) {
                double[] a = (double[]) evalColln;
                for (int i = 0; i < a.length; i++) {
                    this.queryIndex(a[i], indexInfo, results, iterOperands, indpndntItr, context, projAttrib, conditioningNeeded);
                }
            } else if (evalColln instanceof float[]) {
                float[] a = (float[]) evalColln;
                for (int i = 0; i < a.length; i++) {
                    this.queryIndex(a[i], indexInfo, results, iterOperands, indpndntItr, context, projAttrib, conditioningNeeded);
                }
            } else if (evalColln instanceof int[]) {
                int[] a = (int[]) evalColln;
                for (int i = 0; i < a.length; i++) {
                    this.queryIndex(a[i], indexInfo, results, iterOperands, indpndntItr, context, projAttrib, conditioningNeeded);
                }
            } else if (evalColln instanceof short[]) {
                short[] a = (short[]) evalColln;
                for (int i = 0; i < a.length; i++) {
                    this.queryIndex(a[i], indexInfo, results, iterOperands, indpndntItr, context, projAttrib, conditioningNeeded);
                }
            } else if (evalColln instanceof char[]) {
                char[] a = (char[]) evalColln;
                for (int i = 0; i < a.length; i++) {
                    this.queryIndex(a[i], indexInfo, results, iterOperands, indpndntItr, context, projAttrib, conditioningNeeded);
                }
            } else if (evalColln instanceof byte[]) {
                byte[] a = (byte[]) evalColln;
                for (int i = 0; i < a.length; i++) {
                    this.queryIndex(a[i], indexInfo, results, iterOperands, indpndntItr, context, projAttrib, conditioningNeeded);
                }
            } else {
                throw new TypeMismatchException("Operand of IN cannot be interpreted as a Comparable Object. Operand is of type =" + evalColln.getClass());
            }
        }
        if (conditioningNeeded) {
            results = QueryUtils.getConditionedIndexResults(results, indexInfo, context, indexFieldsSize, completeExpansionNeeded, iterOperands, indpndntItr);
        } else {
            if (isIntersection && intermediateResults != null) {
                results = QueryUtils.intersection(intermediateResults, results, context);
            }
        }
        return results;
    } finally {
        observer.afterIndexLookup(results);
    }
}
Also used : StructType(org.apache.geode.cache.query.types.StructType) TypeMismatchException(org.apache.geode.cache.query.TypeMismatchException) ObjectType(org.apache.geode.cache.query.types.ObjectType) SelectResults(org.apache.geode.cache.query.SelectResults) StructTypeImpl(org.apache.geode.cache.query.internal.types.StructTypeImpl) Iterator(java.util.Iterator) ArrayList(java.util.ArrayList) List(java.util.List) HashSet(java.util.HashSet) Collection(java.util.Collection) Map(java.util.Map)

Example 32 with TypeMismatchException

use of org.apache.geode.cache.query.TypeMismatchException in project geode by apache.

the class CompiledIn method evaluate.

public Object evaluate(ExecutionContext context) throws FunctionDomainException, TypeMismatchException, NameResolutionException, QueryInvocationTargetException {
    Object evalElm = this.elm.evaluate(context);
    Object evalColln = evaluateColln(context);
    if (evalColln == null || evalColln == QueryService.UNDEFINED) {
        return QueryService.UNDEFINED;
    }
    // handle each type of collection that we support
    if (evalColln instanceof Map) {
        evalColln = ((Map) evalColln).entrySet();
    }
    if (evalColln instanceof Collection) {
        Iterator iterator = ((Iterable) evalColln).iterator();
        while (iterator.hasNext()) {
            Object evalObj = evalElm;
            Object collnObj = iterator.next();
            if (evalElm instanceof PdxString && collnObj instanceof String) {
                evalObj = ((PdxString) evalElm).toString();
            } else if (collnObj instanceof PdxString && evalElm instanceof String) {
                collnObj = ((PdxString) collnObj).toString();
            }
            if (TypeUtils.compare(evalObj, collnObj, OQLLexerTokenTypes.TOK_EQ).equals(Boolean.TRUE)) {
                return Boolean.TRUE;
            }
        }
        return Boolean.FALSE;
    }
    if (!evalColln.getClass().isArray()) {
        throw new TypeMismatchException(LocalizedStrings.CompiledIn_OPERAND_OF_IN_CANNOT_BE_INTERPRETED_AS_A_COLLECTION_IS_INSTANCE_OF_0.toLocalizedString(evalColln.getClass().getName()));
    }
    if (evalColln.getClass().getComponentType().isPrimitive()) {
        if (evalElm == null) {
            throw new TypeMismatchException(LocalizedStrings.CompiledIn_IN_OPERATOR_CHECK_FOR_NULL_IN_PRIMITIVE_ARRAY.toLocalizedString());
        }
    }
    int numElements = Array.getLength(evalColln);
    for (int i = 0; i < numElements; i++) {
        Object o = Array.get(evalColln, i);
        if (TypeUtils.compare(evalElm, o, TOK_EQ).equals(Boolean.TRUE)) {
            return Boolean.TRUE;
        }
    }
    return Boolean.FALSE;
}
Also used : TypeMismatchException(org.apache.geode.cache.query.TypeMismatchException) Iterator(java.util.Iterator) Collection(java.util.Collection) PdxString(org.apache.geode.pdx.internal.PdxString) PdxString(org.apache.geode.pdx.internal.PdxString) Map(java.util.Map)

Example 33 with TypeMismatchException

use of org.apache.geode.cache.query.TypeMismatchException in project geode by apache.

the class CompiledSelect method evaluate.

public SelectResults evaluate(ExecutionContext context) throws FunctionDomainException, TypeMismatchException, NameResolutionException, QueryInvocationTargetException {
    context.newScope((Integer) context.cacheGet(scopeID));
    context.pushExecCache((Integer) context.cacheGet(scopeID));
    context.setDistinct(this.distinct);
    if (this.hasUnmappedOrderByCols && context.getBucketList() != null) {
        throw new QueryInvalidException(LocalizedStrings.DefaultQuery_ORDER_BY_ATTRIBS_NOT_PRESENT_IN_PROJ.toLocalizedString());
    }
    if (hints != null) {
        context.cachePut(QUERY_INDEX_HINTS, hints);
    }
    try {
        // set flag to keep objects serialized for "select *" queries
        if ((DefaultQuery) context.getQuery() != null) {
            ((DefaultQuery) context.getQuery()).keepResultsSerialized(this, context);
        }
        Iterator iter = iterators.iterator();
        while (iter.hasNext()) {
            CompiledIteratorDef iterDef = (CompiledIteratorDef) iter.next();
            RuntimeIterator rIter = iterDef.getRuntimeIterator(context);
            context.bindIterator(rIter);
        // Ideally the function below should always be called after binding has occurred
        // So that the internal ID gets set during binding to the scope. If not so then chances
        // are that internal_id is still null causing index_internal_id to be null.
        // Though in our case it may not be an issue as the compute dependency phase must have
        // already set the index id
        }
        Integer limitValue = evaluateLimitValue(context, this.limit);
        SelectResults result = null;
        boolean evalAsFilters = false;
        if (this.whereClause == null) {
            result = doIterationEvaluate(context, false);
        } else {
            if (!this.whereClause.isDependentOnCurrentScope(context)) {
                // independent
                // where
                // @todo
                // check
                // for
                // dependency
                // on
                // current
                // scope
                // only?
                // clause
                Object b = this.whereClause.evaluate(context);
                if (b == null || b == QueryService.UNDEFINED) {
                    // treat as if all elements are undefined
                    result = prepareEmptyResultSet(context, false);
                // ResultsSet.emptyResultsSet(resultSet, 0);
                // return result;
                } else if (!(b instanceof Boolean)) {
                    throw new TypeMismatchException(LocalizedStrings.CompiledSelect_THE_WHERE_CLAUSE_WAS_TYPE_0_INSTEAD_OF_BOOLEAN.toLocalizedString(b.getClass().getName()));
                } else if ((Boolean) b) {
                    result = doIterationEvaluate(context, false);
                } else {
                    result = prepareEmptyResultSet(context, false);
                // ResultsSet.emptyResultsSet(resultSet, 0);
                // return result;
                }
            } else {
                // Check the numer of independent iterators
                int numInd = context.getAllIndependentIteratorsOfCurrentScope().size();
                // If order by clause is defined, then the first column should be the preferred index
                if (this.orderByAttrs != null && numInd == 1) {
                    CompiledSortCriterion csc = (CompiledSortCriterion) orderByAttrs.get(0);
                    StringBuilder preferredIndexCondn = new StringBuilder();
                    this.evalCanonicalizedExpressionForCSC(csc, context, preferredIndexCondn);
                    context.cachePut(PREF_INDEX_COND, preferredIndexCondn.toString());
                }
                boolean unlock = true;
                Object obj = context.cacheGet(this.whereClause);
                if (obj != null && (obj instanceof IndexInfo[] || obj.equals(CLAUSE_EVALUATED))) {
                    // if indexinfo is cached means the read lock
                    // is not being taken this time, so releasing
                    // the lock is not required
                    unlock = false;
                }
                // see if we should evaluate as filters,
                // and count how many actual index lookups will be performed
                PlanInfo planInfo = this.whereClause.getPlanInfo(context);
                if (context.cacheGet(this.whereClause) == null) {
                    context.cachePut(this.whereClause, CLAUSE_EVALUATED);
                }
                try {
                    evalAsFilters = planInfo.evalAsFilter;
                    // let context know if there is exactly one index lookup
                    context.setOneIndexLookup(planInfo.indexes.size() == 1);
                    if (evalAsFilters) {
                        ((QueryExecutionContext) context).setIndexUsed(true);
                        // Ignore order by attribs for a while
                        boolean canApplyOrderByAtIndex = false;
                        if (limitValue >= 0 && numInd == 1 && ((Filter) this.whereClause).isLimitApplicableAtIndexLevel(context)) {
                            context.cachePut(CAN_APPLY_LIMIT_AT_INDEX, Boolean.TRUE);
                        }
                        StringBuilder temp = null;
                        if (this.orderByAttrs != null) {
                            temp = new StringBuilder();
                            CompiledSortCriterion csc = (CompiledSortCriterion) this.orderByAttrs.get(0);
                            this.evalCanonicalizedExpressionForCSC(csc, context, temp);
                        }
                        boolean needsTopLevelOrdering = true;
                        if (temp != null && numInd == 1 && ((Filter) this.whereClause).isOrderByApplicableAtIndexLevel(context, temp.toString())) {
                            context.cachePut(CAN_APPLY_ORDER_BY_AT_INDEX, Boolean.TRUE);
                            context.cachePut(ORDERBY_ATTRIB, this.orderByAttrs);
                            canApplyOrderByAtIndex = true;
                            if (this.orderByAttrs.size() == 1) {
                                needsTopLevelOrdering = false;
                                // we should use a sorted set
                                if (this.limit != null) {
                                    // Currently check bucket list to determine if it's a pr query
                                    if (context.getBucketList() != null && context.getBucketList().size() > 0) {
                                        needsTopLevelOrdering = true;
                                    }
                                }
                            }
                        } else if (temp != null) {
                            // If order by is present but cannot be applied at index level,
                            // then limit also cannot be applied
                            // at index level
                            context.cachePut(CAN_APPLY_LIMIT_AT_INDEX, Boolean.FALSE);
                        }
                        context.cachePut(RESULT_LIMIT, limitValue);
                        if (numInd == 1 && ((Filter) this.whereClause).isProjectionEvaluationAPossibility(context) && (this.orderByAttrs == null || (canApplyOrderByAtIndex && !needsTopLevelOrdering)) && this.projAttrs != null) {
                            // Possibility of evaluating the resultset as filter itself
                            ObjectType resultType = this.cachedElementTypeForOrderBy != null ? this.cachedElementTypeForOrderBy : this.prepareResultType(context);
                            context.cachePut(RESULT_TYPE, resultType);
                            context.cachePut(PROJ_ATTRIB, this.projAttrs);
                        }
                        result = ((Filter) this.whereClause).filterEvaluate(context, null);
                        if (!(context.cacheGet(RESULT_TYPE) instanceof Boolean)) {
                            QueryObserverHolder.getInstance().beforeApplyingProjectionOnFilterEvaluatedResults(result);
                            result = applyProjectionOnCollection(result, context, !needsTopLevelOrdering);
                        }
                    } else {
                        // otherwise iterate over the single from var to evaluate
                        result = doIterationEvaluate(context, true);
                    }
                } finally {
                    // because we need to select index which can be read-locked.
                    if (unlock) {
                        releaseReadLockOnUsedIndex(planInfo);
                    }
                }
            }
        }
        // if (result == null) { return QueryService.UNDEFINED; }
        assert result != null;
        // drop duplicates if this is DISTINCT
        if (result instanceof SelectResults) {
            SelectResults sr = (SelectResults) result;
            CollectionType colnType = sr.getCollectionType();
            // if (this.distinct && colnType.allowsDuplicates()) {
            if (this.distinct) {
                Collection r;
                // Set s = sr.asSet();
                if (colnType.allowsDuplicates()) {
                    // don't just convert to a ResultsSet (or StructSet), since
                    // the bags can convert themselves to a Set more efficiently
                    r = sr.asSet();
                } else {
                    r = sr;
                }
                result = new ResultsCollectionWrapper(colnType.getElementType(), r, limitValue);
                if (r instanceof Bag.SetView) {
                    ((ResultsCollectionWrapper) result).setModifiable(false);
                }
            } else {
                // SelectResults is of type
                if (limitValue > -1) {
                    ((Bag) sr).applyLimit(limitValue);
                }
            }
            /*
         * We still have to get size of SelectResults in some cases like, if index was used OR query
         * is a distinct query.
         * 
         * If SelectResult size is zero then we need to put Integer for 0 count.
         */
            if (this.count) {
                SelectResults res = (SelectResults) result;
                if ((this.distinct || evalAsFilters || countStartQueryResult == 0)) {
                    // at coordinator node for PR queries.
                    if (context.getBucketList() != null && this.distinct) {
                        return result;
                    }
                    // Take size and empty the results
                    int resultCount = res.size();
                    res.clear();
                    ResultsBag countResult = new ResultsBag(new ObjectTypeImpl(Integer.class), context.getCachePerfStats());
                    countResult.addAndGetOccurence(resultCount);
                    result = countResult;
                } else {
                    ((Bag) res).addAndGetOccurence(countStartQueryResult);
                }
            }
        }
        return result;
    } finally {
        context.popScope();
        context.popExecCache();
    }
}
Also used : TypeMismatchException(org.apache.geode.cache.query.TypeMismatchException) ObjectType(org.apache.geode.cache.query.types.ObjectType) SelectResults(org.apache.geode.cache.query.SelectResults) CollectionType(org.apache.geode.cache.query.types.CollectionType) Iterator(java.util.Iterator) QueryInvalidException(org.apache.geode.cache.query.QueryInvalidException) ObjectTypeImpl(org.apache.geode.cache.query.internal.types.ObjectTypeImpl) Collection(java.util.Collection)

Example 34 with TypeMismatchException

use of org.apache.geode.cache.query.TypeMismatchException in project geode by apache.

the class CompiledSelect method doNestedIterations.

// returns the number of elements added in the return ResultSet
private int doNestedIterations(int level, SelectResults results, ExecutionContext context, boolean evaluateWhereClause, int numElementsInResult) throws TypeMismatchException, AmbiguousNameException, FunctionDomainException, NameResolutionException, QueryInvocationTargetException, CompiledSelect.NullIteratorException {
    List iterList = context.getCurrentIterators();
    if (level == iterList.size()) {
        boolean addToResults = true;
        if (evaluateWhereClause) {
            Object result = this.whereClause.evaluate(context);
            QueryObserver observer = QueryObserverHolder.getInstance();
            observer.afterIterationEvaluation(result);
            if (result == null) {
                addToResults = false;
            } else if (result instanceof Boolean) {
                addToResults = (Boolean) result;
            } else if (result == QueryService.UNDEFINED) {
                // add UNDEFINED to results only for NOT EQUALS queries
                if (this.whereClause.getType() == COMPARISON) {
                    int operator = ((Filter) this.whereClause).getOperator();
                    if ((operator != TOK_NE && operator != TOK_NE_ALT)) {
                        addToResults = false;
                    }
                } else {
                    addToResults = false;
                }
            } else {
                throw new TypeMismatchException(LocalizedStrings.CompiledSelect_THE_WHERE_CLAUSE_WAS_TYPE_0_INSTEAD_OF_BOOLEAN.toLocalizedString(result.getClass().getName()));
            }
        }
        if (addToResults) {
            int occurence = applyProjectionAndAddToResultSet(context, results, this.orderByAttrs == null);
            // ResultsCollectionWrapper and we will fall short of limit
            if (occurence == 1 || (occurence > 1 && !this.distinct)) {
                // (Unique i.e first time occurence) or subsequent occurence
                // for non distinct query
                ++numElementsInResult;
            }
        }
    } else {
        RuntimeIterator rIter = (RuntimeIterator) iterList.get(level);
        SelectResults sr = rIter.evaluateCollection(context);
        if (sr == null) {
            // continue iteration if a collection evaluates to UNDEFINED
            return 0;
        }
        // we can size directly on the region.
        if (this.whereClause == null && iterators.size() == 1 && isCount() && !isDistinct() && sr instanceof QRegion) {
            QRegion qr = (QRegion) sr;
            countStartQueryResult = qr.getRegion().size();
            return 1;
        }
        // form and send it to the client.
        if ((DefaultQuery) context.getQuery() != null && ((DefaultQuery) context.getQuery()).isKeepSerialized() && sr instanceof QRegion) {
            ((QRegion) sr).setKeepSerialized(true);
        }
        // Iterate through the data set.
        Iterator cIter = sr.iterator();
        while (cIter.hasNext()) {
            // Check if query execution on this thread is canceled.
            QueryMonitor.isQueryExecutionCanceled();
            Object currObj = cIter.next();
            rIter.setCurrent(currObj);
            QueryObserver observer = QueryObserverHolder.getInstance();
            observer.beforeIterationEvaluation(rIter, currObj);
            numElementsInResult = doNestedIterations(level + 1, results, context, evaluateWhereClause, numElementsInResult);
            Integer limitValue = evaluateLimitValue(context, this.limit);
            if (this.orderByAttrs == null && limitValue > -1 && numElementsInResult == limitValue) {
                break;
            }
        }
    }
    return numElementsInResult;
}
Also used : TypeMismatchException(org.apache.geode.cache.query.TypeMismatchException) SelectResults(org.apache.geode.cache.query.SelectResults) Iterator(java.util.Iterator) ArrayList(java.util.ArrayList) List(java.util.List)

Example 35 with TypeMismatchException

use of org.apache.geode.cache.query.TypeMismatchException in project geode by apache.

the class QueryAccessController method runAdhocQuery.

/**
   * Run an adhoc Query specified in a query string
   * 
   * @param oql OQL query string to be executed
   * @return query result as a JSON document
   */
@RequestMapping(method = RequestMethod.GET, value = "/adhoc", produces = { MediaType.APPLICATION_JSON_UTF8_VALUE })
@ApiOperation(value = "run an adhoc query", notes = "Run an unnamed (unidentified), ad-hoc query passed as a URL parameter", response = void.class)
@ApiResponses({ @ApiResponse(code = 200, message = "OK."), @ApiResponse(code = 401, message = "Invalid Username or Password."), @ApiResponse(code = 403, message = "Insufficient privileges for operation."), @ApiResponse(code = 500, message = "GemFire throws an error or exception") })
@ResponseBody
@ResponseStatus(HttpStatus.OK)
@PreAuthorize("@securityService.authorize('DATA', 'READ')")
public ResponseEntity<String> runAdhocQuery(@RequestParam("q") String oql) {
    logger.debug("Running an adhoc Query ({})...", oql);
    oql = decode(oql);
    final Query query = getQueryService().newQuery(oql);
    // and handle the Exceptions appropriately (500 Server Error)!
    try {
        Object queryResult = query.execute();
        return processQueryResponse(query, null, queryResult);
    } catch (FunctionDomainException fde) {
        throw new GemfireRestException("A function was applied to a parameter that is improper for that function!", fde);
    } catch (TypeMismatchException tme) {
        throw new GemfireRestException("Bind parameter is not of the expected type!", tme);
    } catch (NameResolutionException nre) {
        throw new GemfireRestException("Name in the query cannot be resolved!", nre);
    } catch (IllegalArgumentException iae) {
        throw new GemfireRestException(" The number of bound parameters does not match the number of placeholders!", iae);
    } catch (IllegalStateException ise) {
        throw new GemfireRestException("Query is not permitted on this type of region!", ise);
    } catch (QueryExecutionTimeoutException qete) {
        throw new GemfireRestException("Query execution time is exceeded max query execution time (gemfire.Cache.MAX_QUERY_EXECUTION_TIME) configured! ", qete);
    } catch (QueryInvocationTargetException qite) {
        throw new GemfireRestException("Data referenced in from clause is not available for querying!", qite);
    } catch (QueryExecutionLowMemoryException qelme) {
        throw new GemfireRestException("Query execution gets canceled due to low memory conditions and the resource manager critical heap percentage has been set!", qelme);
    } catch (Exception e) {
        throw new GemfireRestException("Server has encountered while executing Adhoc query!", e);
    }
}
Also used : GemfireRestException(org.apache.geode.rest.internal.web.exception.GemfireRestException) Query(org.apache.geode.cache.query.Query) DefaultQuery(org.apache.geode.cache.query.internal.DefaultQuery) FunctionDomainException(org.apache.geode.cache.query.FunctionDomainException) QueryExecutionLowMemoryException(org.apache.geode.cache.query.QueryExecutionLowMemoryException) TypeMismatchException(org.apache.geode.cache.query.TypeMismatchException) QueryExecutionTimeoutException(org.apache.geode.cache.query.QueryExecutionTimeoutException) QueryInvocationTargetException(org.apache.geode.cache.query.QueryInvocationTargetException) NameResolutionException(org.apache.geode.cache.query.NameResolutionException) FunctionDomainException(org.apache.geode.cache.query.FunctionDomainException) NameResolutionException(org.apache.geode.cache.query.NameResolutionException) QueryExecutionTimeoutException(org.apache.geode.cache.query.QueryExecutionTimeoutException) ResourceNotFoundException(org.apache.geode.rest.internal.web.exception.ResourceNotFoundException) QueryInvalidException(org.apache.geode.cache.query.QueryInvalidException) QueryExecutionLowMemoryException(org.apache.geode.cache.query.QueryExecutionLowMemoryException) GemfireRestException(org.apache.geode.rest.internal.web.exception.GemfireRestException) TypeMismatchException(org.apache.geode.cache.query.TypeMismatchException) QueryInvocationTargetException(org.apache.geode.cache.query.QueryInvocationTargetException) ResponseStatus(org.springframework.web.bind.annotation.ResponseStatus) ApiOperation(io.swagger.annotations.ApiOperation) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) ApiResponses(io.swagger.annotations.ApiResponses) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Aggregations

TypeMismatchException (org.apache.geode.cache.query.TypeMismatchException)36 NameResolutionException (org.apache.geode.cache.query.NameResolutionException)17 FunctionDomainException (org.apache.geode.cache.query.FunctionDomainException)16 QueryInvocationTargetException (org.apache.geode.cache.query.QueryInvocationTargetException)16 SelectResults (org.apache.geode.cache.query.SelectResults)15 Query (org.apache.geode.cache.query.Query)12 Iterator (java.util.Iterator)11 ArrayList (java.util.ArrayList)9 QueryService (org.apache.geode.cache.query.QueryService)9 DefaultQuery (org.apache.geode.cache.query.internal.DefaultQuery)9 Collection (java.util.Collection)7 List (java.util.List)6 QueryException (org.apache.geode.cache.query.QueryException)6 CacheSerializableRunnable (org.apache.geode.cache30.CacheSerializableRunnable)6 Host (org.apache.geode.test.dunit.Host)6 VM (org.apache.geode.test.dunit.VM)6 Map (java.util.Map)5 QueryExecutionTimeoutException (org.apache.geode.cache.query.QueryExecutionTimeoutException)5 ObjectType (org.apache.geode.cache.query.types.ObjectType)5 HashSet (java.util.HashSet)4