Obtain the query factory for building DSL based Ickle queries.
972881
public static QueryFactory getQueryFactory(Cache<?, ?> cache) {
      if (cache == null || cache.getAdvancedCache() == null) {
         throw new IllegalArgumentException("cache parameter shall not be null");
      }
      AdvancedCache<?, ?> advancedCache = cache.getAdvancedCache();
      ensureAccessPermissions(advancedCache);
      EmbeddedQueryEngine queryEngine = SecurityActions.getCacheComponentRegistry(advancedCache).getComponent(EmbeddedQueryEngine.class);
      if (queryEngine == null) {
         throw log.queryModuleNotInitialised();
      }
      return new EmbeddedQueryFactory(queryEngine);
   }
266161
def _gql(cls, query_string, *args, **kwds):
    """"""
    from .query import gql  # Import late to avoid circular imports.
    return gql('SELECT * FROM %s %s' % (cls._class_name(), query_string),
               *args, **kwds)
1132455
protected SolrQuery constructQuery(SolrDataQuery query, @Nullable Class<?> domainType) {
		return lookupQueryParser(query).constructSolrQuery(query, domainType);
	}
372243
def getStormQuery(self, text):
        '''
        
        '''
        query = s_syntax.Parser(text).query()
        query.init(self)
        return query
516567
def emit_code_from_single_match_query(match_query):
    """"""
    query_data = deque([u'MATCH '])

    if not match_query.match_traversals:
        raise AssertionError(u'Unexpected falsy value for match_query.match_traversals received: '
                             u'{} {}'.format(match_query.match_traversals, match_query))

    # Represent and add the MATCH traversal steps.
    match_traversal_data = [
        _represent_match_traversal(x)
        for x in match_query.match_traversals
    ]
    query_data.append(match_traversal_data[0])
    for traversal_data in match_traversal_data[1:]:
        query_data.append(u', ')
        query_data.append(traversal_data)

    query_data.appendleft(u' (')            # Prepare to wrap the MATCH in a SELECT.
    query_data.append(u'RETURN $matches)')  # Finish the MATCH query and the wrapping ().

    # Represent and add the LET clauses for any @fold scopes that might be part of the query.
    # Sort for deterministic order of clauses.
    fold_data = sorted([
        _represent_fold(fold_location, fold_ir_blocks)
        for fold_location, fold_ir_blocks in six.iteritems(match_query.folds)
    ])
    if fold_data:
        query_data.append(u' LET ')
        query_data.append(fold_data[0])
        for fold_clause in fold_data[1:]:
            query_data.append(u', ')
            query_data.append(fold_clause)

    # Represent and add the SELECT clauses with the proper output data.
    query_data.appendleft(_construct_output_to_match(match_query.output_block))

    # Represent and add the WHERE clause with the proper filters.
    if match_query.where_block is not None:
        query_data.append(_construct_where_to_match(match_query.where_block))

    return u' '.join(query_data)
818760
private static Query buildQuery(ClassDescriptor cld)
    {
        FieldDescriptor[] pkFields = cld.getPkFields();
        Criteria crit = new Criteria();

        for(int i = 0; i < pkFields.length; i++)
        {
            crit.addEqualTo(pkFields[i].getAttributeName(), null);
        }
        return new QueryByCriteria(cld.getClassOfObject(), crit);
    }
122791
def get_query(self, q, request):
        
        return Project.objects.filter(
            Q(pid__icontains=q)
            | Q(name__icontains=q)
        )
1344855
private OntModel getGraphSparqlQuery(URI graphUri) {

        StringBuilder queryStr = new StringBuilder("CONSTRUCT { ?s ?p ?o } \n")
                .append("WHERE {\n");

        // Add named graph if necessary
        if (graphUri != null) {
            queryStr.append("GRAPH <").append(graphUri.toASCIIString()).append("> ");
        }
        queryStr.append("{ ?s ?p ?o } } \n");

        log.debug("Querying graph store: {}", queryStr.toString());

        Query query = QueryFactory.create(queryStr.toString());
        QueryExecution qe = QueryExecutionFactory.sparqlService(this.getSparqlQueryEndpoint().toASCIIString(), query);
        MonitoredQueryExecution qexec = new MonitoredQueryExecution(qe);
        // Note that we are not using the store specification here to avoid retrieving remote models
//        OntModel resultModel = ModelFactory.createOntologyModel();
        OntModel resultModel = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM_MICRO_RULE_INF);
        try {
            qexec.execConstruct(resultModel);
            return resultModel;
        } finally {
            qexec.close();
        }
    }
592017
def search(self, query, _options={}, products=None):
        '''
        
        '''
        options = _options or {}

        return self.client.post_public_key('/institutions/search', {
            'query': query,
            'products': products,
            'options': options,
        })
142806
private OJBIterator getReportQueryIteratorFromQuery(Query query, ClassDescriptor cld) throws PersistenceBrokerException
    {
        RsIteratorFactory factory = ReportRsIteratorFactoryImpl.getInstance();
        OJBIterator result = getRsIteratorFromQuery(query, cld, factory);

        if (query.usePaging())
        {
            result = new PagingIterator(result, query.getStartAtIndex(), query.getEndAtIndex());
        }

        return result;
    }
595860
def query_factory(obj, sym, factory = false)
      Neo4j::Shared::QueryFactory.create(obj, sym).tap do |factory_instance|
        factory_instance.base_query = factory.blank? ? false : factory.query
      end
    end
1256856
def build_q(fields_dict, params_dict, request=None):
    
    # Building search query
    # queries generated by different search_fields are ANDed
    # if a search field is defined for more than one field, are put together with OR
    and_query = Q()

    for fieldname in fields_dict:
        search_field = fields_dict[fieldname]
        if fieldname in params_dict and params_dict[fieldname] != '' and params_dict[fieldname] != []:
            or_query = None

            if type(search_field) == type(list()):
                field_list = search_field
                search_operator = "__icontains"
                fixed_filters = None
                multiple_values = False
                custom_query_method = None
                value_mapper = None

            else: # dictionary of field definitions
                if search_field.get('ignore', False):
                    continue

                field_list = search_field['fields']
                search_operator = search_field.get('operator', None)
                fixed_filters = search_field.get('fixed_filters', None)
                multiple_values = search_field.get('multiple', False)
                custom_query_method =  search_field.get('custom_query', None)
                value_mapper =  search_field.get('value_mapper', None)

            for model_field in field_list:

                if multiple_values:
                    if hasattr(params_dict, "getlist"):
                        request_field_value = params_dict.getlist(fieldname)
                    elif type(params_dict[fieldname]) == list:
                        request_field_value = params_dict[fieldname]
                    else:
                        request_field_value = [params_dict[fieldname]]
                    if value_mapper:
                        request_field_value = [value_mapper(value) for value in request_field_value]
                else:
                    request_field_value = params_dict[fieldname] if not value_mapper else value_mapper(params_dict[fieldname])

                if not custom_query_method:
                    fieldname_key = model_field + search_operator
                    filter_dict = { fieldname_key : request_field_value}
                    if not or_query:
                        or_query = Q(**filter_dict)
                    else:
                        or_query = or_query | Q(**filter_dict)
                else:
                    #TODO: this is a hack for using request data in custom_query
                    #it would be better to pass ALSO the request to custom_query_method
                    if not request:
                        cf = custom_query_method(model_field, request_field_value, params_dict)
                    else:
                        cf = custom_query_method(model_field, request_field_value, request)

                    if not or_query:
                        or_query = cf
                    else:
                        or_query = or_query | cf

            #fixed_filters
            fixed_filters_q = Q()
            #fixed_filters must return a Q object or None
            if fixed_filters:
                if callable(fixed_filters):
                    fixed_filters_q = fixed_filters(params_dict)
                elif type(fixed_filters) is dict:
                    fixed_filters_q = Q(**fixed_filters)

            and_query = and_query & or_query
            and_query = and_query & fixed_filters_q


    return and_query
1245244
def _build_query(self, table, tree, visitor):
        
        kwargs = {}
        index = None
        if tree.using:
            index_name = kwargs["index"] = tree.using[1]
            index = table.get_index(index_name)
        if tree.where:
            constraints = ConstraintExpression.from_where(tree.where)
            possible_hash = constraints.possible_hash_fields()
            possible_range = constraints.possible_range_fields()
            if index is None:
                # See if we can find an index to query on
                indexes = table.get_matching_indexes(possible_hash, possible_range)
                if not indexes:
                    action = "scan"
                    kwargs["filter"] = constraints.build(visitor)
                    kwargs["expr_values"] = visitor.expression_values
                    kwargs["alias"] = visitor.attribute_names
                elif len(indexes) == 1:
                    index = indexes[0]
                    action = "query"
                    add_query_kwargs(kwargs, visitor, constraints, index)
                else:
                    names = ", ".join([index.name for index in indexes])
                    raise SyntaxError(
                        "No index specified with USING <index>, "
                        "but multiple possibilities for query: "
                        "%s" % names
                    )
            else:
                if index.hash_key in possible_hash:
                    action = "query"
                    add_query_kwargs(kwargs, visitor, constraints, index)
                else:
                    action = "scan"
                    if not index.scannable:
                        raise SyntaxError("Cannot scan local index %r" % index_name)
                    kwargs["filter"] = constraints.build(visitor)
                    kwargs["expr_values"] = visitor.expression_values
                    kwargs["alias"] = visitor.attribute_names
        else:
            action = "scan"
        return [action, kwargs, index]
196636
def get_query(self):
        

        query = super(ExpandableViewMixin, self).get_query()
        expandable_fields = getattr(self, 'expandable_fields', [])

        if expandable_fields:
            requested_expands = parse_requested_expands(self.schema_class.QUERY_KEY, self.request)

            if requested_expands:
                available_expands = self.expandable_fields.keys()

                for name in requested_expands:
                    if name in available_expands:
                        field = self.expandable_fields[name]

                        innerjoin = field.get('join')
                        outerjoin = field.get('outerjoin')

                        if innerjoin:
                            query = query.join(innerjoin)
                        elif outerjoin:
                            query = query.outerjoin(outerjoin)

                        # Apply optional options
                        options = field.get('options')

                        if options:
                            query = query.options(*options)

        return query
1291068
def query(self):
        """"""
        if self._query is None:
            query_string = self.environ.get('QUERY_STRING')
            self._query = QueryDict([
                (k.decode('utf-8'), v.decode('utf-8'))
                for k, v in urlparse.parse_qsl(
                    query_string, keep_blank_values=True)
            ])
        return self._query
1102904
def get_query_result(self, query_object):
        """"""

        # Here, we assume that all the queries will use the same datasource, which is
        # is a valid assumption for current setting. In a long term, we may or maynot
        # support multiple queries from different data source.

        timestamp_format = None
        if self.datasource.type == 'table':
            dttm_col = self.datasource.get_col(query_object.granularity)
            if dttm_col:
                timestamp_format = dttm_col.python_date_format

        # The datasource here can be different backend but the interface is common
        result = self.datasource.query(query_object.to_dict())

        df = result.df
        # Transform the timestamp we received from database to pandas supported
        # datetime format. If no python_date_format is specified, the pattern will
        # be considered as the default ISO date format
        # If the datetime format is unix, the parse will use the corresponding
        # parsing logic
        if df is not None and not df.empty:
            if DTTM_ALIAS in df.columns:
                if timestamp_format in ('epoch_s', 'epoch_ms'):
                    # Column has already been formatted as a timestamp.
                    df[DTTM_ALIAS] = df[DTTM_ALIAS].apply(pd.Timestamp)
                else:
                    df[DTTM_ALIAS] = pd.to_datetime(
                        df[DTTM_ALIAS], utc=False, format=timestamp_format)
                if self.datasource.offset:
                    df[DTTM_ALIAS] += timedelta(hours=self.datasource.offset)
                df[DTTM_ALIAS] += query_object.time_shift

            if self.enforce_numerical_metrics:
                self.df_metrics_to_num(df, query_object)

            df.replace([np.inf, -np.inf], np.nan)
        return {
            'query': result.query,
            'status': result.status,
            'error_message': result.error_message,
            'df': df,
        }
1278852
def get_query_builder(self, *args, **kwargs):
        
        query_builder = self.get_query_builder_class()
        return query_builder(*args, **kwargs)