TupleQuery

@param queryString
@param bindings
@param start
@param pageLength
@param includeInferred
@param baseURI
@return
@throws RepositoryException
@throws MalformedQueryException
@throws UnauthorizedException
@throws QueryInterruptedException
773911
public TupleQueryResult sendTupleQuery(String queryString,SPARQLQueryBindingSet bindings, long start, long pageLength, boolean includeInferred, String baseURI) throws RepositoryException, MalformedQueryException,
			QueryInterruptedException {
		InputStream stream = null;
		try {
			stream = getClient().performSPARQLQuery(queryString, bindings, start, pageLength, this.tx, includeInferred, baseURI);
		} catch (JsonProcessingException e) {
			logger.error(e.getLocalizedMessage());
			throw new MarkLogicSesameException("Issue processing json.");
		}
		TupleQueryResultParser parser = QueryResultIO.createParser(format, getValueFactory());
		MarkLogicBackgroundTupleResult tRes = new MarkLogicBackgroundTupleResult(parser,stream);
		execute(tRes);
		return tRes;
	}
175843
private static QueryBuilder getQueryBldr(final IQueryPart _queryPart)
        throws EFapsException
    {
        final Iterator<String> typeIter = ((AbstractQueryPart) _queryPart).getTypes().iterator();
        String typeStr = typeIter.next();
        final QueryBuilder ret = new QueryBuilder(UUIDUtil.isUUID(typeStr) ? Type.get(UUID.fromString(typeStr))
                        : Type.get(typeStr));
        while (typeIter.hasNext()) {
            typeStr = typeIter.next();
            ret.addType(UUIDUtil.isUUID(typeStr) ? Type.get(UUID.fromString(typeStr)) : Type.get(typeStr));
        }
        for (final AbstractWhere where : ((AbstractQueryPart) _queryPart).getWheres()) {
            if (where instanceof AttributeWhere) {
                final AttributeWhere attrWhere = (AttributeWhere) where;
                switch (where.getComparison()) {
                    case IN:
                    case EQUAL:
                        ret.addWhereAttrEqValue(attrWhere.getAttribute(), attrWhere.getValues().toArray());
                        break;
                    case GREATER:
                        ret.addWhereAttrGreaterValue(attrWhere.getAttribute(), attrWhere.getValues().get(0));
                        break;
                    case LESS:
                        ret.addWhereAttrLessValue(attrWhere.getAttribute(), attrWhere.getValues().get(0));
                        break;
                    case LIKE:
                        ret.addWhereAttrMatchValue(attrWhere.getAttribute(), attrWhere.getValues().get(0));
                        break;
                    case UNEQUAL:
                    case NOTIN:
                        ret.addWhereAttrNotEqValue(attrWhere.getAttribute(), attrWhere.getValues().toArray());
                        break;
                    default:
                        ret.addWhereAttrEqValue("ID", 0);
                        break;
                }
            } else if (where instanceof SelectWhere) {
                final SelectWhere selWhere = (SelectWhere) where;
                switch (where.getComparison()) {
                    case EQUAL:
                        ret.addWhereSelectEqValue(selWhere.getSelect(), selWhere.getValues().toArray());
                        break;
                    case GREATER:
                        ret.addWhereSelectGreaterValue(selWhere.getSelect(), selWhere.getValues().get(0));
                        break;
                    case LESS:
                        ret.addWhereSelectLessValue(selWhere.getSelect(), selWhere.getValues().get(0));
                        break;
                    case LIKE:
                        ret.addWhereSelectMatchValue(selWhere.getSelect(), selWhere.getValues().get(0));
                        break;
                    case UNEQUAL:
                    case IN:
                    case NOTIN:
                    default:
                        ret.addWhereAttrEqValue("ID", 0);
                        break;
                }
            } else if (where instanceof AttrQueryWhere) {
                final AttrQueryWhere attrQueryWhere = (AttrQueryWhere) where;
                switch (where.getComparison()) {
                    case IN:
                        ret.addWhereAttrInQuery(attrQueryWhere.getAttribute(),
                                        getQueryBldr(attrQueryWhere.getQuery()).getAttributeQuery(
                                                        ((AbstractNestedQueryStmtPart) attrQueryWhere.getQuery())
                                                                        .getSelect()));
                        break;
                    case NOTIN:
                        ret.addWhereAttrNotInQuery(attrQueryWhere.getAttribute(),
                                        getQueryBldr(attrQueryWhere.getQuery()).getAttributeQuery(
                                                        ((AbstractNestedQueryStmtPart) attrQueryWhere.getQuery())
                                                                        .getSelect()));
                        break;
                    case EQUAL:
                    case GREATER:
                    case LESS:
                    case LIKE:
                    case UNEQUAL:
                    default:
                        ret.addWhereAttrEqValue("ID", 0);
                        break;
                }
            } else if (where instanceof SelectQueryWhere) {
                final SelectQueryWhere selQueryWhere = (SelectQueryWhere) where;
                switch (where.getComparison()) {
                    case IN:
                        ret.addWhereAttrInQuery(selQueryWhere.getSelect(),
                                        getQueryBldr(selQueryWhere.getQuery()).getAttributeQuery(
                                                        ((AbstractNestedQueryStmtPart) selQueryWhere.getQuery())
                                                                        .getSelect()));
                        break;
                    case NOTIN:
                        ret.addWhereAttrNotInQuery(selQueryWhere.getSelect(),
                                        getQueryBldr(selQueryWhere.getQuery()).getAttributeQuery(
                                                        ((AbstractNestedQueryStmtPart) selQueryWhere.getQuery())
                                                                        .getSelect()));
                        break;
                    case EQUAL:
                    case GREATER:
                    case LESS:
                    case LIKE:
                    case UNEQUAL:
                    default:
                        ret.addWhereAttrEqValue("ID", 0);
                        break;
                }
            }
        }
        if (_queryPart instanceof AbstractQueryStmtPart) {
            ret.setLimit(((AbstractQueryStmtPart) _queryPart).getLimit());
        }
        return ret;
    }
478393
public static <T> Query<T> query(Class<T> entityType, String fetchPath, Object queryObject, Pageable pageable) {
        return query(db(), entityType, fetchPath, queryObject, pageable);
    }
324020
@InterfaceAudience.Private
    public List<QueryRow> query(QueryOptions options) throws CouchbaseLiteException {
        if (options == null)
            options = new QueryOptions();
        if (groupOrReduce(options))
            return viewStore.reducedQuery(options);
        else
            return viewStore.regularQuery(options);
    }
442513
private QueryImpl makeQuery(Session session) throws InvalidQueryException, RepositoryException
   {
      StatementContext context = new StatementContext();
      context.statement = new StringBuilder("SELECT * FROM ");
      context.statement.append(JCROrganizationServiceImpl.JOS_USERS_NODETYPE);

      if (query.getUserName() != null)
      {
         addStringStatement(context, UserProperties.JOS_USER_NAME, query.getUserName());
      }

      if (query.getFirstName() != null)
      {
         addStringStatement(context, UserProperties.JOS_FIRST_NAME, query.getFirstName());
      }

      if (query.getLastName() != null)
      {
         addStringStatement(context, UserProperties.JOS_LAST_NAME, query.getLastName());
      }

      if (query.getEmail() != null)
      {
         addStringStatement(context, UserProperties.JOS_EMAIL, query.getEmail());
      }

      if (query.getFromLoginDate() != null)
      {
         addDateStatement(context, UserProperties.JOS_LAST_LOGIN_TIME, ">=", query.getFromLoginDate());
      }

      if (query.getToLoginDate() != null)
      {
         addDateStatement(context, UserProperties.JOS_LAST_LOGIN_TIME, "<=", query.getToLoginDate());
      }

      if (status != UserStatus.ANY)
      {
         context.statement.append(" AND ").append(JCROrganizationServiceImpl.JOS_DISABLED);
         if (status == UserStatus.ENABLED)
            context.statement.append(" IS NULL");
         else
            context.statement.append(" IS NOT NULL");
      }

      return (QueryImpl)session.getWorkspace().getQueryManager().createQuery(context.statement.toString(), Query.SQL);
   }
56449
protected List<User> executePaginatedQuery(UserQuery query, Integer firstResult, Integer maxResults) {
    if (firstResult == null) {
      firstResult = 0;
    }
    if (maxResults == null) {
      maxResults = Integer.MAX_VALUE;
    }
    return query.listPage(firstResult, maxResults);
  }
68466
@Override
    protected LogicalFilterWrapper appendAttributeToQuery(LogicalFilterWrapper queryBuilder, final String dataAttribute, final List<Object> queryValues) {
        if (queryBuilder == null) {
            queryBuilder = new LogicalFilterWrapper(this.queryType);
        }

        for (final Object queryValue : queryValues) {
            final String queryValueString = queryValue == null ? null : queryValue.toString();

            if (StringUtils.isNotBlank(queryValueString)) {
                final Filter filter;
                if (!queryValueString.contains("*")) {
                    filter = new EqualsFilter(dataAttribute, queryValueString);
                } else {
                    filter = new LikeFilter(dataAttribute, queryValueString);
                }

                queryBuilder.append(filter);
            }
        }

        return queryBuilder;
    }
181768
private <R extends OBDAResultSet, Q extends InputQuery<R>> R executeInThread(Q inputQuery, Evaluator<R, Q> evaluator)
			throws OntopReformulationException, OntopQueryEvaluationException {

		log.debug("Executing SPARQL query: \n{}", inputQuery);

		CountDownLatch monitor = new CountDownLatch(1);
		ExecutableQuery executableQuery = engine.reformulateIntoNativeQuery(inputQuery);

		QueryExecutionThread<R, Q> executionthread = new QueryExecutionThread<>(inputQuery, executableQuery, evaluator,
				monitor);

		this.executionThread = executionthread;
		executionthread.start();
		try {
			monitor.await();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		if (executionthread.errorStatus()) {
			Exception ex = executionthread.getException();
			if (ex instanceof OntopReformulationException) {
				throw (OntopReformulationException) ex;
			}
			else if (ex instanceof OntopQueryEvaluationException) {
				throw (OntopQueryEvaluationException) ex;
			}
			else {
				throw new OntopQueryEvaluationException(ex);
			}
		}

		if (canceled) {
			canceled = false;
			throw new OntopQueryEvaluationException("Query execution was cancelled");
		}
		return executionthread.getResultSet();
	}
37409
@Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
        Cursor result = null;

        if (!controller.hasPreinitialized()) {
            throw new IllegalStateException("Controller has not been initialized.");
        }

        int patternCode = controller.getUriMatcher().match(uri);
        MatcherPattern pattern = controller.findMatcherPattern(patternCode);
        if (pattern == null) {
            throw new IllegalArgumentException("unknown uri : " + uri.toString());
        }

        Parameter parameter = new Parameter(uri, projection, selection, selectionArgs, sortOrder);
        SQLiteDatabase db = this.getHelper().getReadableDatabase();

        result = onQuery(this.getHelper(), db, pattern, parameter);
        if (result != null) {
            this.onQueryCompleted(result, uri, pattern, parameter);
        }
        return result;
    }
192061
protected void initializeQueryHandler() throws RepositoryException, RepositoryConfigurationException
   {
      // initialize query handler
      String className = config.getType();
      if (className == null)
      {
         throw new RepositoryConfigurationException("Content hanler       configuration fail");
      }

      try
      {
         Class<?> qHandlerClass = ClassLoading.forName(className, this);
         try
         {
            // We first try a constructor with the workspace id
            Constructor<?> constuctor =
               qHandlerClass.getConstructor(String.class, QueryHandlerEntry.class, ConfigurationManager.class);
            handler = (QueryHandler)constuctor.newInstance(wsContainerId, config, cfm);
         }
         catch (NoSuchMethodException e)
         {
            // No constructor with the workspace id can be found so we use the default constructor
            Constructor<?> constuctor =
               qHandlerClass.getConstructor(QueryHandlerEntry.class, ConfigurationManager.class);
            handler = (QueryHandler)constuctor.newInstance(config, cfm);
         }
         QueryHandler parentHandler = (this.parentSearchManager != null) ? parentSearchManager.getHandler() : null;
         QueryHandlerContext context = createQueryHandlerContext(parentHandler);
         handler.setContext(context);

         if (parentSearchManager != null)
         {
            changesFilter = initializeChangesFilter();
            parentSearchManager.setChangesFilter(changesFilter);
         }
      }
      catch (SecurityException e)
      {
         throw new RepositoryException(e.getMessage(), e);
      }
      catch (IllegalArgumentException e)
      {
         throw new RepositoryException(e.getMessage(), e);
      }
      catch (ClassNotFoundException e)
      {
         throw new RepositoryException(e.getMessage(), e);
      }
      catch (NoSuchMethodException e)
      {
         throw new RepositoryException(e.getMessage(), e);
      }
      catch (InstantiationException e)
      {
         throw new RepositoryException(e.getMessage(), e);
      }
      catch (IllegalAccessException e)
      {
         throw new RepositoryException(e.getMessage(), e);
      }
      catch (InvocationTargetException e)
      {
         throw new RepositoryException(e.getMessage(), e);
      }
   }
176655
private void addQueryParams(final Request request) {
        if (bindingType != null) {
            for (UserBinding.BindingType prop : bindingType) {
                request.addQueryParam("BindingType", prop.toString());
            }
        }

        if (getPageSize() != null) {
            request.addQueryParam("PageSize", Integer.toString(getPageSize()));
        }
    }
211219
@Override
    public MarkLogicBooleanQuery prepareBooleanQuery(String queryString) throws RepositoryException, MalformedQueryException {
        return prepareBooleanQuery(QueryLanguage.SPARQL, queryString, null);
    }
298826
private InputQuery parseQueryString(String queryString) throws OntopOWLException {
		try {
			return inputQueryFactory.createSPARQLQuery(queryString);
		} catch (OntopInvalidInputQueryException | OntopUnsupportedInputQueryException e) {
			throw new OntopOWLException(e);
		}
	}
630190
@Override
	public ClosableIterator<Tuple> executeBackendQuery(BackendQuery<T> query, QueryParameters queryParameters, TupleContext tupleContext) {
		return queryableGridDialect.executeBackendQuery( query, queryParameters, tupleContext );
	}
524423
function queryDef(flags, id, bindings) {
    var bindingDefs = [];
    for (var propName in bindings) {
        var bindingType = bindings[propName];
        bindingDefs.push({ propName: propName, bindingType: bindingType });
    }
    return {
        // will bet set by the view definition
        nodeIndex: -1,
        parent: null,
        renderParent: null,
        bindingIndex: -1,
        outputIndex: -1,
        // regular values
        // TODO(vicb): check
        checkIndex: -1, flags: flags,
        childFlags: 0,
        directChildFlags: 0,
        childMatchedQueries: 0,
        ngContentIndex: -1,
        matchedQueries: {},
        matchedQueryIds: 0,
        references: {},
        childCount: 0,
        bindings: [],
        bindingFlags: 0,
        outputs: [],
        element: null,
        provider: null,
        text: null,
        query: { id: id, filterId: filterQueryId(id), bindings: bindingDefs },
        ngContent: null
    };
}
122209
@Override
    public List<QueryRow> regularQuery(final QueryOptions options) throws CouchbaseLiteException {

        final Predicate<QueryRow> postFilter = options.getPostFilter();

        int tmpLimit = QueryOptions.QUERY_OPTIONS_DEFAULT_LIMIT;
        int tmpSkip = 0;
        if (postFilter != null) {
            // #574: Custom post-filter means skip/limit apply to the filtered rows, not to the
            // underlying query, so handle them specially:
            tmpLimit = options.getLimit();
            tmpSkip = options.getSkip();
            if (tmpLimit == 0)
                return new ArrayList<QueryRow>(); // empty result set
            options.setLimit(QueryOptions.QUERY_OPTIONS_DEFAULT_LIMIT);
            options.setSkip(0);
        }

        final CountDown skip = new CountDown(tmpSkip);
        final CountDown limit = new CountDown(tmpLimit);

        final List<QueryRow> rows = new ArrayList<QueryRow>();

        Status status = runQuery(options, new QueryRowBlock() {
            @Override
            public Status onRow(byte[] keyData, byte[] valueData, String docID, Cursor cursor) {
                JsonDocument keyDoc = new JsonDocument(keyData);
                JsonDocument valueDoc = new JsonDocument(valueData);
                long sequence = Long.parseLong(cursor.getString(3));
                RevisionInternal docRevision = null;
                if (options.isIncludeDocs()) {
                    Object valueObject = valueDoc.jsonObject();
                    String linkedID = null;
                    if (valueObject instanceof Map)
                        linkedID = (String) ((Map) valueObject).get("_id");
                    if (linkedID != null) {
                        // Linked document: http://wiki.apache.org/couchdb/Introduction_to_CouchDB_views#Linked_documents
                        String linkedRev = (String) ((Map) valueObject).get("_rev");
                        Status linkedStatus = new Status();
                        docRevision = store.getDocument(linkedID, linkedRev, true, linkedStatus);
                        sequence = docRevision.getSequence();
                    } else {
                        String revID = cursor.getString(4);
                        byte[] json = cursor.getBlob(5);
                        Map<String, Object> properties = store.documentPropertiesFromJSON(
                                json,
                                docID,
                                revID,
                                false,
                                sequence);
                        docRevision = SQLiteStore.revision(
                                docID,    // docID
                                revID,    // revID
                                false,    // deleted
                                sequence, // sequence
                                properties// properties
                        );
                    }
                }
                QueryRow row = new QueryRow(docID, sequence,
                        keyDoc.jsonObject(), valueDoc.jsonObject(),
                        docRevision);
                if (postFilter != null) {
                    if (!postFilter.apply(row)) {
                        return new Status(Status.OK);
                    }
                    if (skip.getCount() > 0) {
                        skip.countDown();
                        return new Status(Status.OK);
                    }

                }
                rows.add(row);

                if (limit.countDown() == 0)
                    return new Status(0); /// stops the iteration
                return new Status(Status.OK);
            }
        });

        // If given keys, sort the output into that order, and add entries for missing keys:
        if (options.getKeys() != null && options.getKeys().size() > 0) {
            // Group rows by key:
            Map<Object, List<QueryRow>> rowsByKey = new HashMap<Object, List<QueryRow>>();
            for (QueryRow row : rows) {
                List<QueryRow> rs = rowsByKey.get(row.getKey());
                if (rs == null) {
                    rs = new ArrayList<QueryRow>();
                    rowsByKey.put(row.getKey(), rs);
                }
                rs.add(row);
            }

            // Now concatenate them in the order the keys are given in options:
            final List<QueryRow> sortedRows = new ArrayList<QueryRow>();
            for (Object key : options.getKeys()) {
                JsonDocument jsonDoc = null;
                try {
                    byte[] keyBytes = Manager.getObjectMapper().writeValueAsBytes(key);
                    jsonDoc = new JsonDocument(keyBytes);
                } catch (JsonProcessingException e) {
                    throw new CouchbaseLiteException(Status.INTERNAL_SERVER_ERROR);
                }
                List<QueryRow> rs = rowsByKey.get(jsonDoc.jsonObject());
                if (rs != null)
                    sortedRows.addAll(rs);
            }

            return sortedRows;
        }

        return rows;
    }
410848
@Override
    public MarkLogicTupleQuery prepareTupleQuery(QueryLanguage queryLanguage, String queryString) throws RepositoryException, MalformedQueryException {
        return prepareTupleQuery(queryLanguage, queryString, null);
    }