Search in sources :

Example 46 with QueryObserverAdapter

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

the class LikePredicateJUnitTest method likePercentageTerminated_2.

/**
   * Tests a pattern which just contains a single % indicating all match
   * 
   * @throws Exception
   */
private void likePercentageTerminated_2(boolean useBindParam) throws Exception {
    Cache cache = CacheUtils.getCache();
    AttributesFactory attributesFactory = new AttributesFactory();
    RegionAttributes regionAttributes = attributesFactory.create();
    Region region = cache.createRegion("pos", regionAttributes);
    char ch = 'd';
    String base = "abc";
    for (int i = 1; i < 6; ++i) {
        Portfolio pf = new Portfolio(i);
        pf.status = base + ch;
        ch += 1;
        region.put(new Integer(i), pf);
    }
    base = "abd";
    ch = 'd';
    for (int i = 6; i < 11; ++i) {
        Portfolio pf = new Portfolio(i);
        pf.status = base + ch;
        ch += 1;
        region.put(new Integer(i), pf);
    }
    QueryService qs = cache.getQueryService();
    Query q;
    SelectResults results;
    SelectResults expectedResults;
    String predicate = "";
    if (useBindParam) {
        predicate = "$1";
    } else {
        predicate = " '%'";
    }
    q = qs.newQuery("SELECT distinct *  FROM /pos ps WHERE ps.status like " + predicate);
    if (useBindParam) {
        results = (SelectResults) q.execute(new Object[] { "%" });
    } else {
        results = (SelectResults) q.execute();
    }
    ResultsBag bag = new ResultsBag(null);
    for (int i = 1; i < 11; ++i) {
        bag.add(region.get(new Integer(i)));
    }
    expectedResults = new ResultsCollectionWrapper(new ObjectTypeImpl(Object.class), bag.asSet());
    SelectResults[][] rs = new SelectResults[][] { { results, expectedResults } };
    CacheUtils.compareResultsOfWithAndWithoutIndex(rs, this);
    // Create Index
    qs.createIndex("status", IndexType.FUNCTIONAL, "ps.status", "/pos ps");
    QueryObserver old = QueryObserverHolder.setInstance(new QueryObserverAdapter() {

        private boolean indexCalled = false;

        public void afterIndexLookup(Collection results) {
            indexCalled = true;
        }

        public void endQuery() {
            assertTrue(indexCalled);
        }
    });
    if (useBindParam) {
        results = (SelectResults) q.execute(new Object[] { "%" });
    } else {
        results = (SelectResults) q.execute();
    }
    rs[0][0] = results;
    rs[0][1] = expectedResults;
    CacheUtils.compareResultsOfWithAndWithoutIndex(rs, this);
    QueryObserverHolder.setInstance(old);
}
Also used : Query(org.apache.geode.cache.query.Query) RegionAttributes(org.apache.geode.cache.RegionAttributes) Portfolio(org.apache.geode.cache.query.data.Portfolio) ObjectTypeImpl(org.apache.geode.cache.query.internal.types.ObjectTypeImpl) QueryObserver(org.apache.geode.cache.query.internal.QueryObserver) AttributesFactory(org.apache.geode.cache.AttributesFactory) SelectResults(org.apache.geode.cache.query.SelectResults) QueryService(org.apache.geode.cache.query.QueryService) ResultsCollectionWrapper(org.apache.geode.cache.query.internal.ResultsCollectionWrapper) QueryObserverAdapter(org.apache.geode.cache.query.internal.QueryObserverAdapter) Region(org.apache.geode.cache.Region) Collection(java.util.Collection) ResultsBag(org.apache.geode.cache.query.internal.ResultsBag) Cache(org.apache.geode.cache.Cache)

Example 47 with QueryObserverAdapter

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

the class LimitClauseJUnitTest method testLimitDistinctQueryWithTwoCondButOneIndex.

/**
   * Tests the limit functionality for query which has three conditions with AND operator and two
   * conditions can be evaluated using index but not the 3rd one.
   * 
   * This tests the limit application on intermediate results from Index which should not be true in
   * this test.
   * 
   */
@Test
public void testLimitDistinctQueryWithTwoCondButOneIndex() {
    try {
        Query query;
        SelectResults result;
        Region region = CacheUtils.createRegion("portfolios1", Portfolio.class);
        for (int i = 1; i < 100; i++) {
            Portfolio p = new Portfolio(i);
            if (i < 50)
                p.status = "active";
            region.put(Integer.toString(i), p);
        }
        // Create Index on ID
        Index index = qs.createIndex("idIndex", "ID", "/portfolios1");
        assertNotNull(index);
        String queryString = "select DISTINCT * from /portfolios1 where status ='inactive' AND (ID > 0 AND ID < 100) limit 10";
        query = qs.newQuery(queryString);
        result = (SelectResults) query.execute();
        assertTrue(result instanceof SelectResults);
        assertEquals(10, result.size());
        SelectResults wrapper = (SelectResults) result;
        assertEquals(10, wrapper.asSet().size());
    } catch (Exception e) {
        CacheUtils.getLogger().error(e);
        fail(e.toString());
    } finally {
        QueryObserverHolder.setInstance(new QueryObserverAdapter());
    }
}
Also used : SelectResults(org.apache.geode.cache.query.SelectResults) Query(org.apache.geode.cache.query.Query) QueryObserverAdapter(org.apache.geode.cache.query.internal.QueryObserverAdapter) Portfolio(org.apache.geode.cache.query.data.Portfolio) LocalRegion(org.apache.geode.internal.cache.LocalRegion) Region(org.apache.geode.cache.Region) Index(org.apache.geode.cache.query.Index) Test(org.junit.Test) IntegrationTest(org.apache.geode.test.junit.categories.IntegrationTest)

Example 48 with QueryObserverAdapter

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

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

the class MultiIndexCreationJUnitTest method testBasicMultiIndexCreation.

@Test
public void testBasicMultiIndexCreation() throws Exception {
    Region r = CacheUtils.getRegion(regionName);
    for (int i = 0; i < 10; i++) {
        r.put("" + i, new Portfolio(i));
    }
    QueryService qs = CacheUtils.getQueryService();
    qs.defineIndex("statusIndex", "status", r.getFullPath());
    qs.defineIndex("IDIndex", "ID", r.getFullPath());
    List<Index> indexes = qs.createDefinedIndexes();
    assertEquals("Only 2 indexes should have been created. ", 2, indexes.size());
    Index ind = qs.getIndex(r, "statusIndex");
    assertEquals(2, ind.getStatistics().getNumberOfKeys());
    assertEquals(10, ind.getStatistics().getNumberOfValues());
    ind = qs.getIndex(r, "IDIndex");
    assertEquals(10, ind.getStatistics().getNumberOfKeys());
    assertEquals(10, ind.getStatistics().getNumberOfValues());
    QueryObserver old = QueryObserverHolder.setInstance(new QueryObserverAdapter() {

        private boolean indexCalled = false;

        public void afterIndexLookup(Collection results) {
            indexCalled = true;
        }

        public void endQuery() {
            assertTrue(indexCalled);
        }
    });
    String[] queries = { "select * from " + r.getFullPath() + " where status = 'active'", "select * from " + r.getFullPath() + " where ID > 4" };
    for (int i = 0; i < queries.length; i++) {
        SelectResults sr = (SelectResults) qs.newQuery(queries[i]).execute();
        assertEquals(5, sr.size());
    }
    QueryObserverHolder.setInstance(old);
}
Also used : Portfolio(org.apache.geode.cache.query.data.Portfolio) Index(org.apache.geode.cache.query.Index) CompactRangeIndex(org.apache.geode.cache.query.internal.index.CompactRangeIndex) HashIndex(org.apache.geode.cache.query.internal.index.HashIndex) PrimaryKeyIndex(org.apache.geode.cache.query.internal.index.PrimaryKeyIndex) QueryObserver(org.apache.geode.cache.query.internal.QueryObserver) SelectResults(org.apache.geode.cache.query.SelectResults) QueryService(org.apache.geode.cache.query.QueryService) QueryObserverAdapter(org.apache.geode.cache.query.internal.QueryObserverAdapter) Region(org.apache.geode.cache.Region) Collection(java.util.Collection) Test(org.junit.Test) IntegrationTest(org.apache.geode.test.junit.categories.IntegrationTest)

Example 50 with QueryObserverAdapter

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

the class LimitClauseJUnitTest method testLimitNonDistinctQueryWithTwoCondButOneIndex.

@Test
public void testLimitNonDistinctQueryWithTwoCondButOneIndex() {
    try {
        Query query;
        SelectResults result;
        Region region = CacheUtils.createRegion("portfolios1", Portfolio.class);
        for (int i = 1; i < 100; i++) {
            Portfolio p = new Portfolio(i);
            if (i < 50)
                p.status = "active";
            region.put(Integer.toString(i), p);
        }
        MyQueryObserverAdapter observer = new MyQueryObserverAdapter();
        QueryObserver old = QueryObserverHolder.setInstance(observer);
        // Create Index on ID
        Index index = qs.createIndex("idIndex", "ID", "/portfolios1");
        assertNotNull(index);
        String[] queryString = new String[] { "select * from /portfolios1 where status ='inactive' AND (ID > 0 AND ID < 100) limit 10", "select * from /portfolios1 where (status > 'inactiva' AND status < 'xyz') AND (ID > 0 AND ID < 100) limit 10", "select * from /portfolios1 where (status > 'inactiva' AND status < 'xyz') AND (ID > 0 AND ID < 100) AND (\"type\"='type1' OR \"type\"='type2') limit 10" };
        for (String qstr : queryString) {
            query = qs.newQuery(qstr);
            result = (SelectResults) query.execute();
            assertEquals(10, result.size());
            assertFalse(observer.limitAppliedAtIndex);
        }
    } catch (Exception e) {
        CacheUtils.getLogger().error(e);
        fail(e.toString());
    } finally {
        QueryObserverHolder.setInstance(new QueryObserverAdapter());
    }
}
Also used : QueryObserver(org.apache.geode.cache.query.internal.QueryObserver) SelectResults(org.apache.geode.cache.query.SelectResults) Query(org.apache.geode.cache.query.Query) QueryObserverAdapter(org.apache.geode.cache.query.internal.QueryObserverAdapter) Portfolio(org.apache.geode.cache.query.data.Portfolio) LocalRegion(org.apache.geode.internal.cache.LocalRegion) Region(org.apache.geode.cache.Region) Index(org.apache.geode.cache.query.Index) Test(org.junit.Test) IntegrationTest(org.apache.geode.test.junit.categories.IntegrationTest)

Aggregations

QueryObserverAdapter (org.apache.geode.cache.query.internal.QueryObserverAdapter)63 SelectResults (org.apache.geode.cache.query.SelectResults)59 Test (org.junit.Test)55 Query (org.apache.geode.cache.query.Query)54 IntegrationTest (org.apache.geode.test.junit.categories.IntegrationTest)51 Portfolio (org.apache.geode.cache.query.data.Portfolio)49 Region (org.apache.geode.cache.Region)48 QueryObserver (org.apache.geode.cache.query.internal.QueryObserver)38 Index (org.apache.geode.cache.query.Index)36 QueryService (org.apache.geode.cache.query.QueryService)35 ObjectTypeImpl (org.apache.geode.cache.query.internal.types.ObjectTypeImpl)23 Collection (java.util.Collection)18 ObjectType (org.apache.geode.cache.query.types.ObjectType)18 LocalRegion (org.apache.geode.internal.cache.LocalRegion)14 AttributesFactory (org.apache.geode.cache.AttributesFactory)12 Cache (org.apache.geode.cache.Cache)11 List (java.util.List)10 ArrayList (java.util.ArrayList)9 RegionAttributes (org.apache.geode.cache.RegionAttributes)9 StructTypeImpl (org.apache.geode.cache.query.internal.types.StructTypeImpl)7