Search in sources :

Example 6 with ResultsBag

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

the class LikePredicateJUnitTest method equalityForm_2.

/**
   * Tests simple \% or \ _ terminated string which in effect means equality
   * 
   * @throws Exception
   */
private void equalityForm_2(boolean useBindPrms) throws Exception {
    Cache cache = CacheUtils.getCache();
    AttributesFactory attributesFactory = new AttributesFactory();
    RegionAttributes regionAttributes = attributesFactory.create();
    Region region = cache.createRegion("pos", regionAttributes);
    String str = "d_";
    String base = "abc";
    for (int i = 1; i < 6; ++i) {
        Portfolio pf = new Portfolio(i);
        pf.status = base + str;
        region.put(new Integer(i), pf);
    }
    base = "abc";
    str = "d%";
    for (int i = 6; i < 11; ++i) {
        Portfolio pf = new Portfolio(i);
        pf.status = base + str;
        region.put(new Integer(i), pf);
    }
    QueryService qs = cache.getQueryService();
    Query q, q1;
    SelectResults results;
    SelectResults expectedResults;
    String predicate = "";
    if (useBindPrms) {
        predicate = "$1";
    } else {
        predicate = " 'abcd\\_'";
    }
    q = qs.newQuery("SELECT distinct *  FROM /pos ps WHERE ps.status like " + predicate);
    if (useBindPrms) {
        results = (SelectResults) q.execute(new Object[] { "abcd\\_" });
    } else {
        results = (SelectResults) q.execute();
    }
    ResultsBag bag = new ResultsBag(null);
    for (int i = 1; i < 6; ++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);
    predicate = "";
    if (useBindPrms) {
        predicate = "$1";
    } else {
        predicate = " 'abcd\\%'";
    }
    q1 = qs.newQuery("SELECT distinct *  FROM /pos ps WHERE ps.status like " + predicate);
    if (useBindPrms) {
        results = (SelectResults) q1.execute(new Object[] { "abcd\\%" });
    } else {
        results = (SelectResults) q1.execute();
    }
    bag = new ResultsBag(null);
    for (int i = 6; i < 11; ++i) {
        bag.add(region.get(new Integer(i)));
    }
    SelectResults expectedResults1 = new ResultsCollectionWrapper(new ObjectTypeImpl(Object.class), bag.asSet());
    SelectResults[][] rs1 = new SelectResults[][] { { results, expectedResults1 } };
    CacheUtils.compareResultsOfWithAndWithoutIndex(rs1, 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 (useBindPrms) {
        results = (SelectResults) q.execute(new Object[] { "abcd\\_" });
    } else {
        results = (SelectResults) q.execute();
    }
    rs[0][0] = results;
    rs[0][1] = expectedResults;
    CacheUtils.compareResultsOfWithAndWithoutIndex(rs, this);
    if (useBindPrms) {
        results = (SelectResults) q1.execute(new Object[] { "abcd\\%" });
    } else {
        results = (SelectResults) q1.execute();
    }
    rs1[0][0] = results;
    rs1[0][1] = expectedResults1;
    CacheUtils.compareResultsOfWithAndWithoutIndex(rs1, 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 7 with ResultsBag

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

the class LikePredicateJUnitTest method likePercentageTerminated_5.

private void likePercentageTerminated_5(boolean useBindPrm) 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);
    }
    QueryService qs = cache.getQueryService();
    Query q;
    SelectResults results;
    SelectResults expectedResults;
    String predicate = "";
    if (useBindPrm) {
        predicate = "$1";
    } else {
        predicate = " 'a%c%'";
    }
    q = qs.newQuery("SELECT distinct *  FROM /pos ps WHERE ps.status like " + predicate);
    if (useBindPrm) {
        results = (SelectResults) q.execute(new Object[] { "a%bc%" });
    } else {
        results = (SelectResults) q.execute();
    }
    ResultsBag bag = new ResultsBag(null);
    for (int i = 1; i < 6; ++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");
    q = qs.newQuery("SELECT distinct *  FROM /pos ps WHERE ps.status like " + predicate);
    if (useBindPrm) {
        results = (SelectResults) q.execute(new Object[] { "a%bc%" });
    } else {
        results = (SelectResults) q.execute();
    }
    rs = new SelectResults[][] { { results, expectedResults } };
    CacheUtils.compareResultsOfWithAndWithoutIndex(rs, this);
    if (useBindPrm) {
        predicate = "$1";
    } else {
        predicate = "'abc_'";
    }
    q = qs.newQuery("SELECT distinct *  FROM /pos ps WHERE ps.status like " + predicate);
    if (useBindPrm) {
        results = (SelectResults) q.execute(new Object[] { "abc_" });
    } else {
        results = (SelectResults) q.execute();
    }
    rs = new SelectResults[][] { { results, expectedResults } };
    CacheUtils.compareResultsOfWithAndWithoutIndex(rs, this);
    if (useBindPrm) {
        predicate = "$1";
    } else {
        predicate = "'_bc_'";
    }
    q = qs.newQuery("SELECT distinct *  FROM /pos ps WHERE ps.status like " + predicate);
    if (useBindPrm) {
        results = (SelectResults) q.execute(new Object[] { "_bc_" });
    } else {
        results = (SelectResults) q.execute();
    }
    rs = new SelectResults[][] { { results, expectedResults } };
    CacheUtils.compareResultsOfWithAndWithoutIndex(rs, this);
}
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) 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) Region(org.apache.geode.cache.Region) ResultsBag(org.apache.geode.cache.query.internal.ResultsBag) Cache(org.apache.geode.cache.Cache)

Example 8 with ResultsBag

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

the class DSFIDFactory method readResultsBag.

private static ResultsBag readResultsBag(DataInput in) throws IOException, ClassNotFoundException {
    ResultsBag o = new ResultsBag(true);
    InternalDataSerializer.invokeFromData(o, in);
    return o;
}
Also used : ResultsBag(org.apache.geode.cache.query.internal.ResultsBag)

Example 9 with ResultsBag

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

the class RemoteQueryDUnitTest method testBug36434.

/**
   * This the dunit test for the bug no : 36434
   */
@Test
public void testBug36434() throws Exception {
    final String name = this.getName();
    final Host host = Host.getHost(0);
    VM vm0 = host.getVM(0);
    VM vm1 = host.getVM(1);
    final int numberOfEntries = 100;
    // Start server
    vm0.invoke(new CacheSerializableRunnable("Create Bridge Server") {

        public void run2() throws CacheException {
            Properties config = new Properties();
            config.setProperty(LOCATORS, "localhost[" + DistributedTestUtils.getDUnitLocatorPort() + "]");
            getSystem(config);
            AttributesFactory factory = new AttributesFactory();
            factory.setScope(Scope.LOCAL);
            createRegion(name, factory.createRegionAttributes());
            try {
                startBridgeServer(0, false);
            } catch (Exception ex) {
                Assert.fail("While starting CacheServer", ex);
            }
        }
    });
    // Initialize server region
    vm0.invoke(new CacheSerializableRunnable("Create Bridge Server") {

        public void run2() throws CacheException {
            Region region = getRootRegion().getSubregion(name);
            for (int i = 0; i < numberOfEntries; i++) {
                region.put("key-" + i, new TestObject(i, "ibm"));
            }
        }
    });
    final int port = vm0.invoke(() -> RemoteQueryDUnitTest.getCacheServerPort());
    final String host0 = NetworkUtils.getServerHostName(vm0.getHost());
    // Create client region in VM1
    vm1.invoke(new CacheSerializableRunnable("Create region") {

        public void run2() throws CacheException {
            Properties config = new Properties();
            config.setProperty(MCAST_PORT, "0");
            getSystem(config);
            PoolManager.createFactory().addServer(host0, port).setSubscriptionEnabled(true).create("clientPool");
            getCache();
            AttributesFactory factory = new AttributesFactory();
            factory.setScope(Scope.LOCAL);
            factory.setPoolName("clientPool");
            createRegion(name, factory.createRegionAttributes());
        }
    });
    // Execute client queries in VM1
    vm1.invoke(new CacheSerializableRunnable("Execute queries") {

        public void run2() throws CacheException {
            Region region = getRootRegion().getSubregion(name);
            String[] queryStrings = { "id<9", "selection<9", "important<9", "\"select\"<9" };
            for (int i = 0; i < queryStrings.length; ++i) {
                SelectResults results = null;
                try {
                    results = region.query(queryStrings[i]);
                } catch (Exception e) {
                    Assert.fail("Failed executing " + queryStrings[i], e);
                }
                assertEquals(9, results.size());
                String msg = "results expected to be instance of ResultsBag," + " but was found to be is instance of '";
                assertTrue(msg + results.getClass().getName() + "'", results instanceof ResultsBag);
                assertTrue(results.asList().get(0) instanceof TestObject);
            }
        }
    });
    // Close client VM1
    vm1.invoke(new CacheSerializableRunnable("Close client") {

        public void run2() throws CacheException {
            Region region = getRootRegion().getSubregion(name);
            region.close();
            PoolManager.find("clientPool").destroy();
        }
    });
    // Stop server
    vm0.invoke(new SerializableRunnable("Stop CacheServer") {

        public void run() {
            stopBridgeServer(getCache());
        }
    });
}
Also used : CacheException(org.apache.geode.cache.CacheException) SerializableRunnable(org.apache.geode.test.dunit.SerializableRunnable) CacheSerializableRunnable(org.apache.geode.cache30.CacheSerializableRunnable) Host(org.apache.geode.test.dunit.Host) ConfigurationProperties(org.apache.geode.distributed.ConfigurationProperties) Properties(java.util.Properties) IOException(java.io.IOException) CacheException(org.apache.geode.cache.CacheException) QueryInvocationTargetException(org.apache.geode.cache.query.QueryInvocationTargetException) AttributesFactory(org.apache.geode.cache.AttributesFactory) SelectResults(org.apache.geode.cache.query.SelectResults) CacheSerializableRunnable(org.apache.geode.cache30.CacheSerializableRunnable) VM(org.apache.geode.test.dunit.VM) Region(org.apache.geode.cache.Region) ResultsBag(org.apache.geode.cache.query.internal.ResultsBag) FlakyTest(org.apache.geode.test.junit.categories.FlakyTest) Test(org.junit.Test) DistributedTest(org.apache.geode.test.junit.categories.DistributedTest)

Example 10 with ResultsBag

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

the class PartitionedRegion method doExecuteQuery.

/**
   * If ForceReattemptException is thrown then the caller must loop and call us again.
   * 
   * @throws ForceReattemptException if one of the buckets moved out from under us
   */
private Object doExecuteQuery(DefaultQuery query, Object[] parameters, Set buckets) throws FunctionDomainException, TypeMismatchException, NameResolutionException, QueryInvocationTargetException, ForceReattemptException {
    if (logger.isDebugEnabled()) {
        logger.debug("Executing query :{}", query);
    }
    HashSet<Integer> allBuckets = new HashSet<Integer>();
    if (buckets == null) {
        // remote buckets
        final Iterator remoteIter = getRegionAdvisor().getBucketSet().iterator();
        try {
            while (remoteIter.hasNext()) {
                allBuckets.add((Integer) remoteIter.next());
            }
        } catch (NoSuchElementException ignore) {
        }
    } else {
        // local buckets
        Iterator localIter = null;
        if (this.dataStore != null) {
            localIter = buckets.iterator();
        } else {
            localIter = Collections.emptySet().iterator();
        }
        try {
            while (localIter.hasNext()) {
                allBuckets.add((Integer) localIter.next());
            }
        } catch (NoSuchElementException ignore) {
        }
    }
    if (allBuckets.size() == 0) {
        if (logger.isDebugEnabled()) {
            logger.debug("No bucket storage allocated. PR has no data yet.");
        }
        ResultsSet resSet = new ResultsSet();
        resSet.setElementType(new ObjectTypeImpl(this.getValueConstraint() == null ? Object.class : this.getValueConstraint()));
        return resSet;
    }
    CompiledSelect selectExpr = query.getSimpleSelect();
    if (selectExpr == null) {
        throw new IllegalArgumentException(LocalizedStrings.PartitionedRegion_QUERY_MUST_BE_A_SELECT_EXPRESSION_ONLY.toLocalizedString());
    }
    // this can return a BAG even if it's a DISTINCT select expression,
    // since the expectation is that the duplicates will be removed at the end
    SelectResults results = selectExpr.getEmptyResultSet(parameters, getCache(), query);
    PartitionedRegionQueryEvaluator prqe = new PartitionedRegionQueryEvaluator(this.getSystem(), this, query, parameters, results, allBuckets);
    for (; ; ) {
        this.getCancelCriterion().checkCancelInProgress(null);
        boolean interrupted = Thread.interrupted();
        try {
            results = prqe.queryBuckets(null);
            break;
        } catch (InterruptedException ignore) {
            interrupted = true;
        } catch (FunctionDomainException e) {
            throw e;
        } catch (TypeMismatchException e) {
            throw e;
        } catch (NameResolutionException e) {
            throw e;
        } catch (QueryInvocationTargetException e) {
            throw e;
        } catch (QueryException qe) {
            throw new QueryInvocationTargetException(LocalizedStrings.PartitionedRegion_UNEXPECTED_QUERY_EXCEPTION_OCCURRED_DURING_QUERY_EXECUTION_0.toLocalizedString(qe.getMessage()), qe);
        } finally {
            if (interrupted) {
                Thread.currentThread().interrupt();
            }
        }
    }
    // for
    // Drop Duplicates if this is a DISTINCT query
    boolean allowsDuplicates = results.getCollectionType().allowsDuplicates();
    // be exactly matching the limit
    if (selectExpr.isDistinct()) {
        // don't just convert to a ResultsSet (or StructSet), since
        // the bags can convert themselves to a Set more efficiently
        ObjectType elementType = results.getCollectionType().getElementType();
        if (selectExpr.getOrderByAttrs() != null) {
        // Set limit also, its not applied while building the final result set as order by is
        // involved.
        } else if (allowsDuplicates) {
            results = new ResultsCollectionWrapper(elementType, results.asSet());
        }
        if (selectExpr.isCount() && (results.isEmpty() || selectExpr.isDistinct())) {
            // Constructor with elementType not visible.
            SelectResults resultCount = new ResultsBag(getCachePerfStats());
            resultCount.setElementType(new ObjectTypeImpl(Integer.class));
            ((Bag) resultCount).addAndGetOccurence(results.size());
            return resultCount;
        }
    }
    return results;
}
Also used : ResultsSet(org.apache.geode.cache.query.internal.ResultsSet) TypeMismatchException(org.apache.geode.cache.query.TypeMismatchException) ObjectTypeImpl(org.apache.geode.cache.query.internal.types.ObjectTypeImpl) QueryInvocationTargetException(org.apache.geode.cache.query.QueryInvocationTargetException) Bag(org.apache.geode.cache.query.internal.Bag) ResultsBag(org.apache.geode.cache.query.internal.ResultsBag) NameResolutionException(org.apache.geode.cache.query.NameResolutionException) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ObjectType(org.apache.geode.cache.query.types.ObjectType) QueryException(org.apache.geode.cache.query.QueryException) SelectResults(org.apache.geode.cache.query.SelectResults) FunctionDomainException(org.apache.geode.cache.query.FunctionDomainException) ResultsCollectionWrapper(org.apache.geode.cache.query.internal.ResultsCollectionWrapper) PREntriesIterator(org.apache.geode.internal.cache.partitioned.PREntriesIterator) Iterator(java.util.Iterator) CompiledSelect(org.apache.geode.cache.query.internal.CompiledSelect) ResultsBag(org.apache.geode.cache.query.internal.ResultsBag) NoSuchElementException(java.util.NoSuchElementException) HashSet(java.util.HashSet)

Aggregations

ResultsBag (org.apache.geode.cache.query.internal.ResultsBag)12 SelectResults (org.apache.geode.cache.query.SelectResults)10 AttributesFactory (org.apache.geode.cache.AttributesFactory)9 Region (org.apache.geode.cache.Region)9 Cache (org.apache.geode.cache.Cache)8 RegionAttributes (org.apache.geode.cache.RegionAttributes)8 Query (org.apache.geode.cache.query.Query)8 QueryService (org.apache.geode.cache.query.QueryService)8 Portfolio (org.apache.geode.cache.query.data.Portfolio)8 ResultsCollectionWrapper (org.apache.geode.cache.query.internal.ResultsCollectionWrapper)8 ObjectTypeImpl (org.apache.geode.cache.query.internal.types.ObjectTypeImpl)8 Collection (java.util.Collection)6 QueryObserver (org.apache.geode.cache.query.internal.QueryObserver)6 QueryObserverAdapter (org.apache.geode.cache.query.internal.QueryObserverAdapter)6 QueryInvocationTargetException (org.apache.geode.cache.query.QueryInvocationTargetException)2 IOException (java.io.IOException)1 HashSet (java.util.HashSet)1 Iterator (java.util.Iterator)1 NoSuchElementException (java.util.NoSuchElementException)1 Properties (java.util.Properties)1