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);
}
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());
}
}
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);
}
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);
}
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());
}
}
Aggregations