Search in sources :

Example 6 with ExecutionContext

use of org.apache.geode.cache.query.internal.ExecutionContext in project geode by apache.

the class PRQueryProcessor method executeSequentially.

private void executeSequentially(Collection<Collection> resultCollector, List buckets) throws QueryException, InterruptedException, ForceReattemptException {
    /*
     * for (Iterator itr = _bucketsToQuery.iterator(); itr.hasNext(); ) { Integer bId =
     * (Integer)itr.next(); doBucketQuery(bId, this._prds, this.query, this.parameters,
     * resultCollector); }
     */
    ExecutionContext context = new QueryExecutionContext(this.parameters, this.pr.getCache(), this.query);
    CompiledSelect cs = this.query.getSimpleSelect();
    int limit = this.query.getLimit(parameters);
    if (cs != null && cs.isOrderBy()) {
        for (Integer bucketID : this._bucketsToQuery) {
            List<Integer> singleBucket = Collections.singletonList(bucketID);
            context.setBucketList(singleBucket);
            executeQueryOnBuckets(resultCollector, context);
        }
        Collection mergedResults = coalesceOrderedResults(resultCollector, context, cs, limit);
        resultCollector.clear();
        resultCollector.add(mergedResults);
    } else {
        context.setBucketList(buckets);
        executeQueryOnBuckets(resultCollector, context);
    }
}
Also used : Integer(java.lang.Integer) ExecutionContext(org.apache.geode.cache.query.internal.ExecutionContext) QueryExecutionContext(org.apache.geode.cache.query.internal.QueryExecutionContext) QueryExecutionContext(org.apache.geode.cache.query.internal.QueryExecutionContext) CompiledSelect(org.apache.geode.cache.query.internal.CompiledSelect) Collection(java.util.Collection)

Example 7 with ExecutionContext

use of org.apache.geode.cache.query.internal.ExecutionContext in project geode by apache.

the class CqServiceImpl method evaluateQuery.

/**
   * Applies the query on the event. This method takes care of the performance related changed done
   * to improve the CQ-query performance. When CQ-query is executed first time, it saves the query
   * related information in the execution context and uses that info in later executions.
   */
private boolean evaluateQuery(CqQueryImpl cQuery, Object[] event) throws Exception {
    ExecutionContext execContext = cQuery.getQueryExecutionContext();
    execContext.reset();
    execContext.setBindArguments(event);
    boolean status = false;
    // ExecutionContext.
    if (execContext.getScopeNum() <= 0) {
        SelectResults results = (SelectResults) ((DefaultQuery) cQuery.getQuery()).executeUsingContext(execContext);
        if (results != null && results.size() > 0) {
            status = true;
        }
    } else {
        // Execute using the saved query info (in ExecutionContext).
        // This avoids building resultSet, index look-up, generating build-plans
        // that are not required for; query execution on single object.
        CompiledSelect cs = ((DefaultQuery) (cQuery.getQuery())).getSelect();
        status = cs.evaluateCq(execContext);
    }
    return status;
}
Also used : ExecutionContext(org.apache.geode.cache.query.internal.ExecutionContext) SelectResults(org.apache.geode.cache.query.SelectResults) DefaultQuery(org.apache.geode.cache.query.internal.DefaultQuery) CompiledSelect(org.apache.geode.cache.query.internal.CompiledSelect)

Example 8 with ExecutionContext

use of org.apache.geode.cache.query.internal.ExecutionContext in project geode by apache.

the class StructSetOrResultsSet method getOrderByComparatorAndLimitForQuery.

public Wrapper getOrderByComparatorAndLimitForQuery(String orderByQuery, int unorderedResultSize) throws FunctionDomainException, TypeMismatchException, NameResolutionException, QueryInvocationTargetException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
    DefaultQuery q = (DefaultQuery) CacheUtils.getQueryService().newQuery(orderByQuery);
    CompiledSelect cs = q.getSimpleSelect();
    List<CompiledSortCriterion> orderByAttribs = null;
    if (cs.getType() == CompiledValue.GROUP_BY_SELECT) {
        Field originalOrderByMethod = CompiledGroupBySelect.class.getDeclaredField("originalOrderByClause");
        originalOrderByMethod.setAccessible(true);
        orderByAttribs = (List<CompiledSortCriterion>) originalOrderByMethod.get(cs);
    } else {
        orderByAttribs = cs.getOrderByAttrs();
    }
    ObjectType resultType = cs.getElementTypeForOrderByQueries();
    ExecutionContext context = new ExecutionContext(null, CacheUtils.getCache());
    final OrderByComparator obc = new OrderByComparator(orderByAttribs, resultType, context);
    Comparator baseComparator = obc;
    if (resultType.isStructType()) {
        baseComparator = new Comparator<Struct>() {

            @Override
            public int compare(Struct o1, Struct o2) {
                return obc.compare(o1.getFieldValues(), o2.getFieldValues());
            }
        };
    }
    final Comparator secondLevelComparator = baseComparator;
    final Comparator finalComparator = new Comparator() {

        @Override
        public int compare(Object o1, Object o2) {
            final boolean[] orderByColsEqual = new boolean[] { false };
            QueryObserverHolder.setInstance(new QueryObserverAdapter() {

                @Override
                public void orderByColumnsEqual() {
                    orderByColsEqual[0] = true;
                }
            });
            int result = secondLevelComparator.compare(o1, o2);
            if (result != 0 && orderByColsEqual[0]) {
                result = 0;
            }
            return result;
        }
    };
    Field hasUnmappedOrderByColsField = CompiledSelect.class.getDeclaredField("hasUnmappedOrderByCols");
    hasUnmappedOrderByColsField.setAccessible(true);
    boolean skip = ((Boolean) hasUnmappedOrderByColsField.get(cs)).booleanValue();
    ValidationLevel validationLevel = ValidationLevel.ALL;
    int limit;
    if (cs.getType() == CompiledValue.GROUP_BY_SELECT) {
        Field limitCVField = CompiledGroupBySelect.class.getDeclaredField("limit");
        limitCVField.setAccessible(true);
        CompiledValue limitCV = (CompiledValue) limitCVField.get(cs);
        Method evaluateLimitMethod = CompiledSelect.class.getDeclaredMethod("evaluateLimitValue", ExecutionContext.class, CompiledValue.class);
        evaluateLimitMethod.setAccessible(true);
        limit = ((Integer) evaluateLimitMethod.invoke(null, context, limitCV)).intValue();
    } else {
        limit = cs.getLimitValue(null);
    }
    if (limit != -1 && limit < unorderedResultSize) {
        // chances are that results will not match
        if (skip) {
            validationLevel = ValidationLevel.NONE;
        } else {
            validationLevel = ValidationLevel.ORDER_BY_ONLY;
        }
    } else {
        if (skip) {
            validationLevel = ValidationLevel.MATCH_ONLY;
        }
    }
    return new Wrapper(finalComparator, limit, validationLevel);
}
Also used : CompiledSortCriterion(org.apache.geode.cache.query.internal.CompiledSortCriterion) DefaultQuery(org.apache.geode.cache.query.internal.DefaultQuery) CompiledValue(org.apache.geode.cache.query.internal.CompiledValue) Method(java.lang.reflect.Method) Comparator(java.util.Comparator) OrderByComparator(org.apache.geode.cache.query.internal.OrderByComparator) Struct(org.apache.geode.cache.query.Struct) Field(java.lang.reflect.Field) ObjectType(org.apache.geode.cache.query.types.ObjectType) ExecutionContext(org.apache.geode.cache.query.internal.ExecutionContext) QueryObserverAdapter(org.apache.geode.cache.query.internal.QueryObserverAdapter) OrderByComparator(org.apache.geode.cache.query.internal.OrderByComparator) CompiledSelect(org.apache.geode.cache.query.internal.CompiledSelect)

Example 9 with ExecutionContext

use of org.apache.geode.cache.query.internal.ExecutionContext in project geode by apache.

the class LocalRegion method createOQLIndexes.

void createOQLIndexes(InternalRegionArguments internalRegionArgs, boolean recoverFromDisk) {
    if (internalRegionArgs == null || internalRegionArgs.getIndexes() == null || internalRegionArgs.getIndexes().isEmpty()) {
        return;
    }
    if (logger.isDebugEnabled()) {
        logger.debug("LocalRegion.createOQLIndexes on region {}", this.getFullPath());
    }
    long start = getCachePerfStats().startIndexInitialization();
    List oqlIndexes = internalRegionArgs.getIndexes();
    if (this.indexManager == null) {
        this.indexManager = IndexUtils.getIndexManager(this, true);
    }
    DiskRegion dr = this.getDiskRegion();
    boolean isOverflowToDisk = false;
    if (dr != null) {
        isOverflowToDisk = dr.isOverflowEnabled();
        if (recoverFromDisk && !isOverflowToDisk) {
            // Refer bug #44119
            // For disk regions, index creation should wait for async value creation to complete before
            // it starts its iteration
            // In case of disk overflow regions the waitForAsyncRecovery is done in populateOQLIndexes
            // method via getBestIterator()
            dr.waitForAsyncRecovery();
        }
    }
    Set<Index> indexes = new HashSet<Index>();
    Set<Index> prIndexes = new HashSet<>();
    int initLevel = 0;
    try {
        // Release the initialization latch for index creation.
        initLevel = LocalRegion.setThreadInitLevelRequirement(ANY_INIT);
        for (Object o : oqlIndexes) {
            IndexCreationData icd = (IndexCreationData) o;
            try {
                if (icd.getPartitionedIndex() != null) {
                    ExecutionContext externalContext = new ExecutionContext(null, this.cache);
                    if (internalRegionArgs.getPartitionedRegion() != null) {
                        externalContext.setBucketRegion(internalRegionArgs.getPartitionedRegion(), (BucketRegion) this);
                    }
                    if (logger.isDebugEnabled()) {
                        logger.debug("IndexManager Index creation process for {}", icd.getIndexName());
                    }
                    // load entries during initialization only for non overflow regions
                    indexes.add(this.indexManager.createIndex(icd.getIndexName(), icd.getIndexType(), icd.getIndexExpression(), icd.getIndexFromClause(), icd.getIndexImportString(), externalContext, icd.getPartitionedIndex(), !isOverflowToDisk));
                    prIndexes.add(icd.getPartitionedIndex());
                } else {
                    if (logger.isDebugEnabled()) {
                        logger.debug("QueryService Index creation process for {}" + icd.getIndexName());
                    }
                    DefaultQueryService qs = (DefaultQueryService) getGemFireCache().getLocalQueryService();
                    String fromClause = icd.getIndexType() == IndexType.FUNCTIONAL || icd.getIndexType() == IndexType.HASH ? icd.getIndexFromClause() : this.getFullPath();
                    // load entries during initialization only for non overflow regions
                    indexes.add(qs.createIndex(icd.getIndexName(), icd.getIndexType(), icd.getIndexExpression(), fromClause, icd.getIndexImportString(), !isOverflowToDisk));
                }
            } catch (Exception ex) {
                logger.info("Failed to create index {} on region {} with exception: {}", icd.getIndexName(), this.getFullPath(), ex);
                // exception.
                if (internalRegionArgs.getDeclarativeIndexCreation()) {
                    throw new InternalGemFireError(LocalizedStrings.GemFireCache_INDEX_CREATION_EXCEPTION_1.toLocalizedString(icd.getIndexName(), this.getFullPath()), ex);
                }
            }
        }
    } finally {
        // Reset the initialization lock.
        LocalRegion.setThreadInitLevelRequirement(initLevel);
    }
    // Load data into OQL indexes in case of disk recovery and disk overflow
    if (isOverflowToDisk) {
        if (recoverFromDisk) {
            populateOQLIndexes(indexes);
        } else {
            // Empty indexes are created for overflow regions but not populated at this stage
            // since this is not recovery.
            // Setting the populate flag to true so that the indexes can apply updates.
            this.indexManager.setPopulateFlagForIndexes(indexes);
        }
        // due to bug #52096, the pr index populate flags were not being set
        // we should revisit and clean up the index creation code paths
        this.indexManager.setPopulateFlagForIndexes(prIndexes);
    }
    getCachePerfStats().endIndexInitialization(start);
}
Also used : Index(org.apache.geode.cache.query.Index) Endpoint(org.apache.geode.cache.client.internal.Endpoint) TimeoutException(org.apache.geode.cache.TimeoutException) NameResolutionException(org.apache.geode.cache.query.NameResolutionException) RegionDestroyedException(org.apache.geode.cache.RegionDestroyedException) EntryNotFoundException(org.apache.geode.cache.EntryNotFoundException) InternalGemFireException(org.apache.geode.InternalGemFireException) ConflictingPersistentDataException(org.apache.geode.cache.persistence.ConflictingPersistentDataException) CacheRuntimeException(org.apache.geode.cache.CacheRuntimeException) QueryInvocationTargetException(org.apache.geode.cache.query.QueryInvocationTargetException) EntryDestroyedException(org.apache.geode.cache.EntryDestroyedException) IOException(java.io.IOException) CacheException(org.apache.geode.cache.CacheException) ExecutionException(java.util.concurrent.ExecutionException) TypeMismatchException(org.apache.geode.cache.query.TypeMismatchException) FunctionDomainException(org.apache.geode.cache.query.FunctionDomainException) EntryExistsException(org.apache.geode.cache.EntryExistsException) PartitionedRegionStorageException(org.apache.geode.cache.PartitionedRegionStorageException) StatisticsDisabledException(org.apache.geode.cache.StatisticsDisabledException) CacheLoaderException(org.apache.geode.cache.CacheLoaderException) FailedSynchronizationException(org.apache.geode.cache.FailedSynchronizationException) NoSuchElementException(java.util.NoSuchElementException) QueryException(org.apache.geode.cache.query.QueryException) RedundancyAlreadyMetException(org.apache.geode.internal.cache.partitioned.RedundancyAlreadyMetException) QueryInvalidException(org.apache.geode.cache.query.QueryInvalidException) LowMemoryException(org.apache.geode.cache.LowMemoryException) ServerOperationException(org.apache.geode.cache.client.ServerOperationException) SystemException(javax.transaction.SystemException) SubscriptionNotEnabledException(org.apache.geode.cache.client.SubscriptionNotEnabledException) RegionExistsException(org.apache.geode.cache.RegionExistsException) RegionReinitializedException(org.apache.geode.cache.RegionReinitializedException) CancelException(org.apache.geode.CancelException) DiskAccessException(org.apache.geode.cache.DiskAccessException) CacheWriterException(org.apache.geode.cache.CacheWriterException) IndexMaintenanceException(org.apache.geode.cache.query.IndexMaintenanceException) TransactionException(org.apache.geode.cache.TransactionException) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) CacheClosedException(org.apache.geode.cache.CacheClosedException) RollbackException(javax.transaction.RollbackException) ConcurrentCacheModificationException(org.apache.geode.internal.cache.versions.ConcurrentCacheModificationException) MultiIndexCreationException(org.apache.geode.cache.query.MultiIndexCreationException) DeltaSerializationException(org.apache.geode.DeltaSerializationException) IndexCreationData(org.apache.geode.cache.query.internal.index.IndexCreationData) ExecutionContext(org.apache.geode.cache.query.internal.ExecutionContext) VersionedObjectList(org.apache.geode.internal.cache.tier.sockets.VersionedObjectList) ArrayList(java.util.ArrayList) List(java.util.List) StoredObject(org.apache.geode.internal.offheap.StoredObject) DefaultQueryService(org.apache.geode.cache.query.internal.DefaultQueryService) HashSet(java.util.HashSet) InternalGemFireError(org.apache.geode.InternalGemFireError)

Example 10 with ExecutionContext

use of org.apache.geode.cache.query.internal.ExecutionContext in project geode by apache.

the class PRQueryProcessor method executeWithThreadPool.

private void executeWithThreadPool(Collection<Collection> resultCollector) throws QueryException, InterruptedException, ForceReattemptException {
    if (Thread.interrupted())
        throw new InterruptedException();
    java.util.List callableTasks = buildCallableTaskList(resultCollector);
    ExecutorService execService = PRQueryExecutor.getExecutorService();
    boolean reattemptNeeded = false;
    ForceReattemptException fre = null;
    if (callableTasks != null && !callableTasks.isEmpty()) {
        List futures = null;
        try {
            futures = execService.invokeAll(callableTasks, 300, TimeUnit.SECONDS);
        } catch (RejectedExecutionException rejectedExecutionEx) {
            throw rejectedExecutionEx;
        }
        if (futures != null) {
            Iterator itr = futures.iterator();
            while (itr.hasNext() && !execService.isShutdown() && !execService.isTerminated()) {
                // this._prds.partitionedRegion.checkReadiness();
                Future fut = (Future) itr.next();
                QueryTask.BucketQueryResult bqr = null;
                try {
                    bqr = (QueryTask.BucketQueryResult) fut.get(BUCKET_QUERY_TIMEOUT, TimeUnit.SECONDS);
                    // if (retry.booleanValue()) {
                    // reattemptNeeded = true;
                    // fre = (ForceReattemptException)bqr.getException();
                    // } else {
                    // handles an exception if there was one,
                    bqr.handleAndThrowException();
                    // }
                    if (bqr.retry) {
                        reattemptNeeded = true;
                    }
                } catch (TimeoutException e) {
                    throw new InternalGemFireException(LocalizedStrings.PRQueryProcessor_TIMED_OUT_WHILE_EXECUTING_QUERY_TIME_EXCEEDED_0.toLocalizedString(BUCKET_QUERY_TIMEOUT), e);
                } catch (ExecutionException ee) {
                    Throwable cause = ee.getCause();
                    if (cause instanceof QueryException) {
                        throw (QueryException) cause;
                    } else {
                        throw new InternalGemFireException(LocalizedStrings.PRQueryProcessor_GOT_UNEXPECTED_EXCEPTION_WHILE_EXECUTING_QUERY_ON_PARTITIONED_REGION_BUCKET.toLocalizedString(), cause);
                    }
                }
            }
            CompiledSelect cs = this.query.getSimpleSelect();
            if (cs != null && (cs.isOrderBy() || cs.isGroupBy())) {
                ExecutionContext context = new QueryExecutionContext(this.parameters, pr.getCache());
                int limit = this.query.getLimit(parameters);
                Collection mergedResults = coalesceOrderedResults(resultCollector, context, cs, limit);
                resultCollector.clear();
                resultCollector.add(mergedResults);
            }
        }
    }
    if (execService == null || execService.isShutdown() || execService.isTerminated()) {
        this._prds.partitionedRegion.checkReadiness();
    }
    if (reattemptNeeded) {
        throw fre;
    }
}
Also used : InternalGemFireException(org.apache.geode.InternalGemFireException) QueryExecutionContext(org.apache.geode.cache.query.internal.QueryExecutionContext) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) List(java.util.List) QueryException(org.apache.geode.cache.query.QueryException) ExecutionContext(org.apache.geode.cache.query.internal.ExecutionContext) QueryExecutionContext(org.apache.geode.cache.query.internal.QueryExecutionContext) ExecutorService(java.util.concurrent.ExecutorService) Iterator(java.util.Iterator) CompiledSelect(org.apache.geode.cache.query.internal.CompiledSelect) Future(java.util.concurrent.Future) Collection(java.util.Collection) ArrayList(java.util.ArrayList) List(java.util.List) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) ExecutionException(java.util.concurrent.ExecutionException) TimeoutException(java.util.concurrent.TimeoutException)

Aggregations

ExecutionContext (org.apache.geode.cache.query.internal.ExecutionContext)11 DefaultQuery (org.apache.geode.cache.query.internal.DefaultQuery)6 QueryExecutionContext (org.apache.geode.cache.query.internal.QueryExecutionContext)6 HashSet (java.util.HashSet)5 Set (java.util.Set)4 CompiledSelect (org.apache.geode.cache.query.internal.CompiledSelect)4 IntegrationTest (org.apache.geode.test.junit.categories.IntegrationTest)4 Test (org.junit.Test)4 QueryService (org.apache.geode.cache.query.QueryService)3 ArrayList (java.util.ArrayList)2 Collection (java.util.Collection)2 List (java.util.List)2 ExecutionException (java.util.concurrent.ExecutionException)2 RejectedExecutionException (java.util.concurrent.RejectedExecutionException)2 InternalGemFireException (org.apache.geode.InternalGemFireException)2 QueryException (org.apache.geode.cache.query.QueryException)2 IOException (java.io.IOException)1 Integer (java.lang.Integer)1 Field (java.lang.reflect.Field)1 Method (java.lang.reflect.Method)1