Search in sources :

Example 41 with DefaultQuery

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

the class IndexHintJUnitTest method testSingleIndexHint.

// tests the grammar for a hint with a single index name
@Test
public void testSingleIndexHint() throws Exception {
    createRegion();
    QueryService qs = CacheUtils.getQueryService();
    DefaultQuery query = (DefaultQuery) qs.newQuery("<hint 'FirstIndex'> select * from /Portfolios p where p.ID > 10");
    QueryExecutionContext qec = new QueryExecutionContext(new Object[1], CacheUtils.getCache(), query);
    query.executeUsingContext(qec);
    assertTrue(qec.isHinted("FirstIndex"));
    assertEquals(-1, qec.getHintSize("FirstIndex"));
}
Also used : DefaultQuery(org.apache.geode.cache.query.internal.DefaultQuery) QueryExecutionContext(org.apache.geode.cache.query.internal.QueryExecutionContext) Test(org.junit.Test) IntegrationTest(org.apache.geode.test.junit.categories.IntegrationTest)

Example 42 with DefaultQuery

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

the class Query method cmdExecute.

@Override
public void cmdExecute(Message clientMessage, ServerConnection serverConnection, long start) throws IOException, InterruptedException {
    // Based on MessageType.DESTROY
    // Added by gregp 10/18/05
    serverConnection.setAsTrue(REQUIRES_RESPONSE);
    serverConnection.setAsTrue(REQUIRES_CHUNKED_RESPONSE);
    // Retrieve the data from the message parts
    String queryString = clientMessage.getPart(0).getString();
    if (clientMessage.getNumberOfParts() == 3) {
        int timeout = clientMessage.getPart(2).getInt();
        serverConnection.setRequestSpecificTimeout(timeout);
    }
    if (logger.isDebugEnabled()) {
        logger.debug("{}: Received query request from {} queryString: {}", serverConnection.getName(), serverConnection.getSocketString(), queryString);
    }
    try {
        // Create query
        QueryService queryService = serverConnection.getCachedRegionHelper().getCache().getLocalQueryService();
        org.apache.geode.cache.query.Query query = queryService.newQuery(queryString);
        Set regionNames = ((DefaultQuery) query).getRegionsInQuery(null);
        // Authorization check
        QueryOperationContext queryContext = null;
        AuthorizeRequest authzRequest = serverConnection.getAuthzRequest();
        if (authzRequest != null) {
            queryContext = authzRequest.queryAuthorize(queryString, regionNames);
            String newQueryString = queryContext.getQuery();
            if (queryString != null && !queryString.equals(newQueryString)) {
                query = queryService.newQuery(newQueryString);
                queryString = newQueryString;
                regionNames = queryContext.getRegionNames();
                if (regionNames == null) {
                    regionNames = ((DefaultQuery) query).getRegionsInQuery(null);
                }
            }
        }
        processQuery(clientMessage, query, queryString, regionNames, start, null, queryContext, serverConnection, true);
    } catch (QueryInvalidException e) {
        throw new QueryInvalidException(e.getMessage() + queryString);
    } catch (QueryExecutionLowMemoryException e) {
        writeQueryResponseException(clientMessage, e, serverConnection);
    }
}
Also used : Set(java.util.Set) DefaultQuery(org.apache.geode.cache.query.internal.DefaultQuery) AuthorizeRequest(org.apache.geode.internal.security.AuthorizeRequest) QueryExecutionLowMemoryException(org.apache.geode.cache.query.QueryExecutionLowMemoryException) QueryInvalidException(org.apache.geode.cache.query.QueryInvalidException) QueryOperationContext(org.apache.geode.cache.operations.QueryOperationContext) QueryService(org.apache.geode.cache.query.QueryService)

Example 43 with DefaultQuery

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

the class QueryDataFunction method selectWithType.

private QueryDataFunctionResult selectWithType(final FunctionContext context, String queryString, final boolean showMember, final String regionName, final int limit, final int queryResultSetLimit, final int queryCollectionsDepth) throws Exception {
    InternalCache cache = getCache();
    Function localQueryFunc = new LocalQueryFunction("LocalQueryFunction", regionName, showMember).setOptimizeForWrite(true);
    queryString = applyLimitClause(queryString, limit, queryResultSetLimit);
    try {
        TypedJson result = new TypedJson(queryCollectionsDepth);
        Region region = cache.getRegion(regionName);
        if (region == null) {
            throw new Exception(ManagementStrings.QUERY__MSG__REGIONS_NOT_FOUND_ON_MEMBER.toLocalizedString(regionName, cache.getDistributedSystem().getDistributedMember().getId()));
        }
        Object results = null;
        boolean noDataFound = true;
        if (region.getAttributes().getDataPolicy() == DataPolicy.NORMAL) {
            QueryService queryService = cache.getQueryService();
            Query query = queryService.newQuery(queryString);
            results = query.execute();
        } else {
            ResultCollector rcollector;
            PartitionedRegion parRegion = PartitionedRegionHelper.getPartitionedRegion(regionName, cache);
            if (parRegion != null && showMember) {
                if (parRegion.isDataStore()) {
                    Set<BucketRegion> localPrimaryBucketRegions = parRegion.getDataStore().getAllLocalPrimaryBucketRegions();
                    Set<Integer> localPrimaryBucketSet = new HashSet<>();
                    for (BucketRegion bRegion : localPrimaryBucketRegions) {
                        localPrimaryBucketSet.add(bRegion.getId());
                    }
                    LocalDataSet lds = new LocalDataSet(parRegion, localPrimaryBucketSet);
                    DefaultQuery query = (DefaultQuery) cache.getQueryService().newQuery(queryString);
                    results = (SelectResults) lds.executeQuery(query, null, localPrimaryBucketSet);
                }
            } else {
                rcollector = FunctionService.onRegion(cache.getRegion(regionName)).setArguments(queryString).execute(localQueryFunc);
                results = rcollector.getResult();
            }
        }
        if (results != null && results instanceof SelectResults) {
            SelectResults selectResults = (SelectResults) results;
            for (Object object : selectResults) {
                result.add(RESULT_KEY, object);
                noDataFound = false;
            }
        } else if (results != null && results instanceof ArrayList) {
            ArrayList listResults = (ArrayList) results;
            ArrayList actualResult = (ArrayList) listResults.get(0);
            for (Object object : actualResult) {
                result.add(RESULT_KEY, object);
                noDataFound = false;
            }
        }
        if (!noDataFound && showMember) {
            result.add(MEMBER_KEY, cache.getDistributedSystem().getDistributedMember().getId());
        }
        if (noDataFound) {
            return new QueryDataFunctionResult(QUERY_EXEC_SUCCESS, BeanUtilFuncs.compress(new JsonisedErrorMessage(NO_DATA_FOUND).toString()));
        }
        return new QueryDataFunctionResult(QUERY_EXEC_SUCCESS, BeanUtilFuncs.compress(result.toString()));
    } catch (Exception e) {
        logger.warn(e.getMessage(), e);
        throw e;
    }
}
Also used : DefaultQuery(org.apache.geode.cache.query.internal.DefaultQuery) Query(org.apache.geode.cache.query.Query) DefaultQuery(org.apache.geode.cache.query.internal.DefaultQuery) TypedJson(org.apache.geode.management.internal.cli.json.TypedJson) ArrayList(java.util.ArrayList) InternalCache(org.apache.geode.internal.cache.InternalCache) GfJsonException(org.apache.geode.management.internal.cli.json.GfJsonException) FunctionException(org.apache.geode.cache.execute.FunctionException) QueryInvalidException(org.apache.geode.cache.query.QueryInvalidException) Function(org.apache.geode.cache.execute.Function) SelectResults(org.apache.geode.cache.query.SelectResults) BucketRegion(org.apache.geode.internal.cache.BucketRegion) QueryService(org.apache.geode.cache.query.QueryService) LocalDataSet(org.apache.geode.internal.cache.LocalDataSet) PartitionedRegion(org.apache.geode.internal.cache.PartitionedRegion) BucketRegion(org.apache.geode.internal.cache.BucketRegion) Region(org.apache.geode.cache.Region) PartitionedRegion(org.apache.geode.internal.cache.PartitionedRegion) GfJsonObject(org.apache.geode.management.internal.cli.json.GfJsonObject) ResultCollector(org.apache.geode.cache.execute.ResultCollector) HashSet(java.util.HashSet)

Example 44 with DefaultQuery

use of org.apache.geode.cache.query.internal.DefaultQuery 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 45 with DefaultQuery

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

the class OrderByTestImplementation method testOrderByWithColumnAlias_Bug52041_1.

@Test
public void testOrderByWithColumnAlias_Bug52041_1() throws Exception {
    Region region = createRegion("portfolio", Portfolio.class);
    for (int i = 1; i < 200; ++i) {
        Portfolio pf = new Portfolio(i);
        pf.shortID = (short) ((short) i / 5);
        pf.status = "active";
        region.put("" + i, pf);
    }
    String queryStr = "select distinct p.status, p.shortID as short_id  from /portfolio p where p.ID >= 0 " + "order by short_id asc";
    QueryService qs = CacheUtils.getQueryService();
    Query query = qs.newQuery(queryStr);
    SelectResults<Struct> results = (SelectResults<Struct>) query.execute();
    Iterator<Struct> iter = results.asList().iterator();
    int counter = 0;
    while (iter.hasNext()) {
        Struct str = iter.next();
        assertEquals(counter, ((Short) str.get("short_id")).intValue());
        ++counter;
    }
    assertEquals(39, counter - 1);
    CompiledSelect cs = ((DefaultQuery) query).getSimpleSelect();
    List<CompiledSortCriterion> orderbyAtts = cs.getOrderByAttrs();
    assertEquals(orderbyAtts.get(0).getColumnIndex(), 1);
}
Also used : CompiledSortCriterion(org.apache.geode.cache.query.internal.CompiledSortCriterion) DefaultQuery(org.apache.geode.cache.query.internal.DefaultQuery) Query(org.apache.geode.cache.query.Query) DefaultQuery(org.apache.geode.cache.query.internal.DefaultQuery) Portfolio(org.apache.geode.cache.query.data.Portfolio) Struct(org.apache.geode.cache.query.Struct) SelectResults(org.apache.geode.cache.query.SelectResults) QueryService(org.apache.geode.cache.query.QueryService) CompiledSelect(org.apache.geode.cache.query.internal.CompiledSelect) Region(org.apache.geode.cache.Region) Test(org.junit.Test)

Aggregations

DefaultQuery (org.apache.geode.cache.query.internal.DefaultQuery)66 Test (org.junit.Test)49 QueryService (org.apache.geode.cache.query.QueryService)40 SelectResults (org.apache.geode.cache.query.SelectResults)38 Query (org.apache.geode.cache.query.Query)37 Region (org.apache.geode.cache.Region)33 CompiledSelect (org.apache.geode.cache.query.internal.CompiledSelect)32 Struct (org.apache.geode.cache.query.Struct)27 Iterator (java.util.Iterator)26 HashSet (java.util.HashSet)23 ObjectType (org.apache.geode.cache.query.types.ObjectType)23 StructType (org.apache.geode.cache.query.types.StructType)22 Portfolio (org.apache.geode.cache.query.data.Portfolio)18 PortfolioPdx (org.apache.geode.cache.query.data.PortfolioPdx)13 Set (java.util.Set)11 PartitionedRegion (org.apache.geode.internal.cache.PartitionedRegion)11 IntegrationTest (org.apache.geode.test.junit.categories.IntegrationTest)11 CacheSerializableRunnable (org.apache.geode.cache30.CacheSerializableRunnable)10 DistributedTest (org.apache.geode.test.junit.categories.DistributedTest)10 QueryInvocationTargetException (org.apache.geode.cache.query.QueryInvocationTargetException)9