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