// followQuery waits for the query to become ready and sets p's results.
// If the promise is finished somewhere else first, such as if it is canceled,
// followQuery will return.
359909
func (p *asyncRunPromise) followQuery(wg *sync.WaitGroup) {
	defer wg.Done()
	// Always need to call Done after query is finished.
	defer p.q.Done()

	select {
	case <-p.ready:
		// The promise was finished somewhere else, so we don't need to call p.finish.
		// But we do need to cancel the flux. This could be a no-op.
		p.q.Cancel()
	case results, ok := <-p.q.Ready():
		if !ok {
			// Something went wrong with the flux. Set the error in the run result.
			rr := &runResult{err: p.q.Err()}
			p.finish(rr, nil)
			return
		}

		// Exhaust the results so we don't leave unfinished iterators around.
		var wg sync.WaitGroup
		wg.Add(len(results))
		for _, res := range results {
			r := res
			go func() {
				defer wg.Done()
				if err := exhaustResultIterators(r); err != nil {
					p.logger.Info("Error exhausting result iterator", zap.Error(err), zap.String("name", r.Name()))
				}
			}()
		}
		wg.Wait()

		// Otherwise, query was successful.
		// TODO(mr): collect query statistics, once RunResult interface supports them?
		p.finish(new(runResult), nil)
	}
}
133176
func (tl *TestLauncher) ExecuteQuery(q string) (*QueryResults, error) {
	fq, err := tl.QueryController().Query(context.Background(), &query.Request{
		Authorization:  tl.Auth,
		OrganizationID: tl.Auth.OrgID,
		Compiler: lang.FluxCompiler{
			Query: q,
		}})
	if err != nil {
		return nil, err
	}

	results := make([]flux.Result, 0, 1)
	for res := range fq.Results() {
		results = append(results, res)
	}

	if err := fq.Err(); err != nil {
		fq.Done()
		return nil, err
	}

	return &QueryResults{
		Results: results,
		Query:   fq,
	}, nil
}
485197
func (c *Cluster) SearchQuery(q SearchQuery, opts *SearchQueryOptions) (*SearchResults, error) {
	if opts == nil {
		opts = &SearchQueryOptions{}
	}
	ctx := opts.Context
	if ctx == nil {
		ctx = context.Background()
	}

	var span opentracing.Span
	if opts.ParentSpanContext == nil {
		span = opentracing.GlobalTracer().StartSpan("ExecuteSearchQuery",
			opentracing.Tag{Key: "couchbase.service", Value: "fts"})
	} else {
		span = opentracing.GlobalTracer().StartSpan("ExecuteSearchQuery",
			opentracing.Tag{Key: "couchbase.service", Value: "fts"}, opentracing.ChildOf(opts.ParentSpanContext))
	}
	defer span.Finish()

	provider, err := c.getHTTPProvider()
	if err != nil {
		return nil, err
	}

	return c.searchQuery(ctx, span.Context(), q, opts, provider)
}
1276780
func ExecQuery(c context.Context, q *datastore.Query, ldr QueryListLoader) error {
	g := goon.FromContext(c)

	req := ldr.ReqListBase()

	if req.Limit == 0 {
		req.Limit = 10
	}
	if req.Limit != -1 {
		q = q.Limit(req.Limit + 1) // get 1 more, fill blank to cursor when next one is not exists.
	}

	if req.Offset > 0 {
		q = q.Offset(req.Offset)
	}

	if req.Cursor != "" {
		cursor, err := datastore.DecodeCursor(req.Cursor)
		if err != nil {
			return err
		}
		q = q.Start(cursor)
	}

	q = q.KeysOnly()

	log.Debugf(c, "%#v", q)

	t := g.Run(q)

	count := 0
	hasNext := false
	var cursor datastore.Cursor
	for {
		key, err := t.Next(nil)
		if err == datastore.Done {
			break
		}
		if err != nil {
			return err
		}
		count++
		if req.Limit != -1 && req.Limit < count {
			// +1
			hasNext = true
			break
		}
		inst, err := ldr.LoadInstance(c, key)
		if err != nil {
			return err
		}
		err = ldr.Append(inst)
		if err != nil {
			return err
		}
		if req.Limit == count {
			// store cursor at reach to limit.
			cursor, err = t.Cursor()
			if err != nil {
				return err
			}
		}
	}

	err := ldr.PostProcess(c)
	if err != nil {
		return err
	}

	resp := ldr.RespListBase()

	if hasNext {
		resp.Cursor = cursor.String()
	}

	return nil
}
100309
func Follow(c *context.APIContext) {
	target := GetUserByParams(c)
	if c.Written() {
		return
	}
	if err := models.FollowUser(c.User.ID, target.ID); err != nil {
		c.Error(500, "FollowUser", err)
		return
	}
	c.Status(204)
}
245647
func (f QueryHandlerFunc) ServeQuery(ctx context.Context, res QueryResponse, req *QueryRequest) error {
	return f(ctx, res, req)
}
11693
func (r *Request) SetQuery(name, value string) *Request {
	r.Use(query.Set(name, value))
	return r
}
1172161
func (s *QueryService) Query(ctx context.Context, req *query.Request) (flux.ResultIterator, error) {
	return s.QueryF(ctx, req)
}
193989
func (db *DB) AddExpectedQuery(query string, err error) {
	db.AddExpectedExecuteFetch(ExpectedExecuteFetch{
		Query:       query,
		QueryResult: &sqltypes.Result{},
		Error:       err,
	})
}
669159
func QueryAfter(sel interface{}, f func(context.Context, ...*cdp.Node) error, opts ...QueryOption) Action {
	return Query(sel, append(opts, After(f))...)
}
1102577
func (self *Query) extendQuery(mgoQuery *mgo.Query) {

	if self.selector != nil {
		mgoQuery.Select(self.selector)
	}

	if len(self.sort) > 0 {
		mgoQuery.Sort(self.sort...)
	}

	if self.limit != 0 {
		mgoQuery.Limit(self.limit)
	}

	if self.skip != 0 {
		mgoQuery.Skip(self.skip)
	}
}
1024663
func (cc *Client) Query(request Request, options ...RequestOption) (Response, error) {

	options = append(options, addDefaultTimeout(fab.Query))
	options = append(options, addDefaultTargetFilter(cc.context, filter.ChaincodeQuery))

	return callQuery(cc, request, options...)
}
1370122
func (b *Bucket) ExecuteN1qlQuery(q *N1qlQuery, params interface{}) (ViewResults, error) {
	n1qlEp, err := b.getN1qlEp()
	if err != nil {
		return nil, err
	}

	execOpts := make(map[string]interface{})
	for k, v := range q.options {
		execOpts[k] = v
	}
	if params != nil {
		args, isArray := params.([]interface{})
		if isArray {
			execOpts["args"] = args
		} else {
			mapArgs, isMap := params.(map[string]interface{})
			if isMap {
				for key, value := range mapArgs {
					execOpts["$"+key] = value
				}
			} else {
				panic("Invalid params argument passed")
			}
		}
	}

	if q.adHoc {
		return b.executeN1qlQuery(n1qlEp, execOpts)
	}

	// Do Prepared Statement Logic
	var cachedStmt *n1qlCache

	stmtStr := q.options["statement"].(string);

	b.queryCacheLock.RLock()
	cachedStmt = b.queryCache[stmtStr]
	b.queryCacheLock.RUnlock()

	if cachedStmt != nil {
		// Attempt to execute our cached query plan
		delete(execOpts, "statement")
		execOpts["prepared"] = cachedStmt.name
		execOpts["encoded_plan"] = cachedStmt.encodedPlan

		results, err := b.executeN1qlQuery(n1qlEp, execOpts)
		if err == nil {
			return results, nil
		}

		// If we get error 4050, 4070 or 5000, we should attempt
		//   to reprepare the statement immediately before failing.
		n1qlErr, isN1qlErr := err.(*n1qlMultiError)
		if !isN1qlErr {
			return nil, err
		}
		if n1qlErr.Code() != 4050 && n1qlErr.Code() != 4070 && n1qlErr.Code() != 5000 {
			return nil, err
		}
	}

	// Prepare the query
	cachedStmt, err = b.prepareN1qlQuery(n1qlEp, q.options)
	if err != nil {
		return nil, err
	}

	// Save new cached statement
	b.queryCacheLock.Lock()
	b.queryCache[stmtStr] = cachedStmt
	b.queryCacheLock.Unlock()

	// Update with new prepared data
	delete(execOpts, "statement")
	execOpts["prepared"] = cachedStmt.name
	execOpts["encoded_plan"] = cachedStmt.encodedPlan

	return b.executeN1qlQuery(n1qlEp, execOpts)
}
27736
func Follow(r cruntime.Manager, bs bootstrapper.Bootstrapper, runner bootstrapper.CommandRunner) error {
	cs := []string{}
	for _, v := range logCommands(r, bs, 0, true) {
		cs = append(cs, v+" &")
	}
	cs = append(cs, "wait")
	return runner.CombinedOutputTo(strings.Join(cs, " "), os.Stdout)
}
962867
func (s *ResourceQuery) SetQuery(v string) *ResourceQuery {
	s.Query = &v
	return s
}
1217579
func skipQueryPlanCache(options *querypb.ExecuteOptions) bool {
	if options == nil {
		return false
	}
	return options.SkipQueryPlanCache
}
428971
func (s *SearchSource) Query(query Query) *SearchSource {
	s.query = query
	return s
}