// Return the prepared statement for a given SQL query
167436
func (db *DB) statement(sql string) (*sql.Stmt, error) {
	if db.connection == nil {
		return nil, fmt.Errorf("Not connected to database")
	}

	sql = db.connection.Rebind(sql)
	if _, ok := db.cache[sql]; !ok {
		stmt, err := db.connection.Prepare(sql)
		if err != nil {
			return nil, err
		}
		db.cache[sql] = stmt
	}

	if q, ok := db.cache[sql]; ok {
		return q, nil
	}

	return nil, fmt.Errorf("Weird bug: query '%s' is still not properly prepared", sql)
}
1043844
func (session *Session) Query(sqlStr string, paramStr ...interface{}) (resultsSlice []map[string][]byte, err error) {
	defer session.resetStatement()
	if session.IsAutoClose {
		defer session.Close()
	}

	return session.query(sqlStr, paramStr...)
}
728273
func preparedQueriesTableSchema() *memdb.TableSchema {
	return &memdb.TableSchema{
		Name: "prepared-queries",
		Indexes: map[string]*memdb.IndexSchema{
			"id": &memdb.IndexSchema{
				Name:         "id",
				AllowMissing: false,
				Unique:       true,
				Indexer: &memdb.UUIDFieldIndex{
					Field: "ID",
				},
			},
			"name": &memdb.IndexSchema{
				Name:         "name",
				AllowMissing: true,
				Unique:       true,
				Indexer: &memdb.StringFieldIndex{
					Field:     "Name",
					Lowercase: true,
				},
			},
			"template": &memdb.IndexSchema{
				Name:         "template",
				AllowMissing: true,
				Unique:       true,
				Indexer:      &PreparedQueryIndex{},
			},
			"session": &memdb.IndexSchema{
				Name:         "session",
				AllowMissing: true,
				Unique:       false,
				Indexer: &memdb.UUIDFieldIndex{
					Field: "Session",
				},
			},
		},
	}
}
1197043
func (p *PreparedQuery) Get(args *structs.PreparedQuerySpecificRequest,
	reply *structs.IndexedPreparedQueries) error {
	if done, err := p.srv.forward("PreparedQuery.Get", args, args, reply); done {
		return err
	}

	return p.srv.blockingQuery(
		&args.QueryOptions,
		&reply.QueryMeta,
		func(ws memdb.WatchSet, state *state.Store) error {
			index, query, err := state.PreparedQueryGet(ws, args.QueryID)
			if err != nil {
				return err
			}
			if query == nil {
				return ErrQueryNotFound
			}

			// If no prefix ACL applies to this query, then they are
			// always allowed to see it if they have the ID. We still
			// have to filter the remaining object for tokens.
			reply.Index = index
			reply.Queries = structs.PreparedQueries{query}
			if _, ok := query.GetACLPrefix(); !ok {
				return p.srv.filterACL(args.Token, &reply.Queries[0])
			}

			// Otherwise, attempt to filter it the usual way.
			if err := p.srv.filterACL(args.Token, reply); err != nil {
				return err
			}

			// Since this is a GET of a specific query, if ACLs have
			// prevented us from returning something that exists,
			// then alert the user with a permission denied error.
			if len(reply.Queries) == 0 {
				p.srv.logger.Printf("[WARN] consul.prepared_query: Request to get prepared query '%s' denied due to ACLs", args.QueryID)
				return acl.ErrPermissionDenied
			}

			return nil
		})
}
1290982
func (se *splitQuerySQLExecuter) SQLExecute(
	sql string, bindVariables map[string]*querypb.BindVariable,
) (*sqltypes.Result, error) {
	// We need to parse the query since we're dealing with bind-vars.
	// TODO(erez): Add an SQLExecute() to SQLExecuterInterface that gets a parsed query so that
	// we don't have to parse the query again here.
	ast, err := sqlparser.Parse(sql)
	if err != nil {
		return nil, vterrors.Wrap(err, "splitQuerySQLExecuter: parsing sql failed with")
	}
	parsedQuery := sqlparser.NewParsedQuery(ast)

	// We clone "bindVariables" since fullFetch() changes it.
	return se.queryExecutor.dbConnFetch(
		se.conn,
		parsedQuery,
		sqltypes.CopyBindVariables(bindVariables),
		"",   /* buildStreamComment */
		true, /* wantfields */
	)
}
1148800
func (db *DB) Query(query string, args ...interface{}) (*Rows, error) {
	var rows *Rows
	var err error
	for i := 0; i < maxBadConnRetries; i++ {
		rows, err = db.query(query, args)
		if err != driver.ErrBadConn {
			break
		}
	}
	return rows, err
}
520835
func (m *MySQLLock) prepare(name, query string) error {
	stmt, err := m.in.Prepare(query)
	if err != nil {
		return errwrap.Wrapf(fmt.Sprintf("failed to prepare %q: {{err}}", name), err)
	}
	m.statements[name] = stmt
	return nil
}
809109
func ExecuteTxQuery(ctx context.Context, tx *sql.Tx, params map[string]string, query string) error {

	parsedQuery := parseQuery(params, query)

	stmt, err := tx.PrepareContext(ctx, parsedQuery)
	if err != nil {
		return err
	}
	defer stmt.Close()

	return execute(ctx, stmt)
}
1160444
func (s *HTTPServer) PreparedQuerySpecific(resp http.ResponseWriter, req *http.Request) (interface{}, error) {
	if req.Method == "OPTIONS" {
		return s.preparedQuerySpecificOptions(resp, req), nil
	}

	path := req.URL.Path
	id := strings.TrimPrefix(path, "/v1/query/")

	switch {
	case strings.HasSuffix(path, "/execute"):
		if req.Method != "GET" {
			return nil, MethodNotAllowedError{req.Method, []string{"GET"}}
		}
		id = strings.TrimSuffix(id, "/execute")
		return s.preparedQueryExecute(id, resp, req)

	case strings.HasSuffix(path, "/explain"):
		if req.Method != "GET" {
			return nil, MethodNotAllowedError{req.Method, []string{"GET"}}
		}
		id = strings.TrimSuffix(id, "/explain")
		return s.preparedQueryExplain(id, resp, req)

	default:
		switch req.Method {
		case "GET":
			return s.preparedQueryGet(id, resp, req)

		case "PUT":
			return s.preparedQueryUpdate(id, resp, req)

		case "DELETE":
			return s.preparedQueryDelete(id, resp, req)

		default:
			return nil, MethodNotAllowedError{req.Method, []string{"GET", "PUT", "DELETE"}}
		}
	}
}
126473
func (kv *KeyValue) sql(sqlStmt string) string {
	// string manipulation is done only once
	kv.queriesInitOnce.Do(func() {
		kv.queries = make(map[string]string, 8) // we have 8 queries in this file
		kv.replacer = strings.NewReplacer("/*TPRE*/", kv.TablePrefix)
	})
	kv.queriesMu.RLock()
	sqlQuery, ok := kv.queries[sqlStmt]
	kv.queriesMu.RUnlock()
	if ok {
		return sqlQuery
	}
	kv.queriesMu.Lock()
	// check again, now holding the lock
	if sqlQuery, ok = kv.queries[sqlStmt]; ok {
		kv.queriesMu.Unlock()
		return sqlQuery
	}
	sqlQuery = sqlStmt
	if f := kv.PlaceHolderFunc; f != nil {
		sqlQuery = f(sqlQuery)
	}
	sqlQuery = kv.replacer.Replace(sqlQuery)
	kv.queries[sqlStmt] = sqlQuery
	kv.queriesMu.Unlock()
	return sqlQuery
}
888864
func (s *session) ExecutePreparedStmt(ctx context.Context, stmtID uint32, args ...interface{}) (sqlexec.RecordSet, error) {
	err := checkArgs(args...)
	if err != nil {
		return nil, err
	}

	s.PrepareTxnCtx(ctx)
	st, err := executor.CompileExecutePreparedStmt(s, stmtID, args...)
	if err != nil {
		return nil, err
	}
	logQuery(st.OriginText(), s.sessionVars)
	r, err := runStmt(ctx, s, st)
	return r, err
}
234335
func (d *database) Query(ctx context.Context, query string, bindVars map[string]interface{}) (Cursor, error) {
	req, err := d.conn.NewRequest("POST", path.Join(d.relPath(), "_api/cursor"))
	if err != nil {
		return nil, WithStack(err)
	}
	input := queryRequest{
		Query:    query,
		BindVars: bindVars,
	}
	input.applyContextSettings(ctx)
	if _, err := req.SetBody(input); err != nil {
		return nil, WithStack(err)
	}
	cs := applyContextSettings(ctx, req)
	resp, err := d.conn.Do(ctx, req)
	if err != nil {
		return nil, WithStack(err)
	}
	if err := resp.CheckStatus(201); err != nil {
		return nil, WithStack(err)
	}
	var data cursorData
	if err := resp.ParseBody("", &data); err != nil {
		return nil, WithStack(err)
	}
	col, err := newCursor(data, resp.Endpoint(), d, cs.AllowDirtyReads)
	if err != nil {
		return nil, WithStack(err)
	}
	return col, nil
}
384287
func (db DBWrapper) Query(sqlText string, args ...interface{}) (qr QueryResult) {
	rows, err := db.DB.Query(sqlText, args...)
	defer func() {
		if rows != nil {
			rows.Close()
		}
	}()

	if err != nil {
		db.logError(err, sqlText, args)
		qr.Error = err
		return
	}

	qr.Cols, err = rows.Columns()
	if err != nil {
		db.logError(err, sqlText, args)
		qr.Error = err
		return
	}
	qr.Rows = make([]Row, 0, 10) // Default len 10
	for rows.Next() {
		row := make([]interface{}, len(qr.Cols))
		for i, _ := range row {
			row[i] = new([]byte)
		}

		rows.Scan(row...)
		qr.Rows = append(qr.Rows, row)
	}
	return
}
1074068
func SanitizeSQL(sql string, args ...interface{}) (string, error) {
	query, err := NewQuery(sql)
	if err != nil {
		return "", err
	}
	return query.Sanitize(args...)
}
308586
func RedactSQLQuery(sql string) (string, error) {
	bv := map[string]*querypb.BindVariable{}
	sqlStripped, comments := SplitMarginComments(sql)

	stmt, err := Parse(sqlStripped)
	if err != nil {
		return "", err
	}

	prefix := "redacted"
	Normalize(stmt, bv, prefix)

	return comments.Leading + String(stmt) + comments.Trailing, nil
}
863451
func (m *qlbConn) Prepare(query string) (driver.Stmt, error) {
	return nil, expr.ErrNotImplemented
}
1210024
func (r *Rego) PrepareForEval(ctx context.Context, opts ...PrepareOption) (PreparedEvalQuery, error) {
	if !r.hasQuery() {
		return PreparedEvalQuery{}, fmt.Errorf("cannot evaluate empty query")
	}

	pCfg := &PrepareConfig{}
	for _, o := range opts {
		o(pCfg)
	}

	txn := r.txn

	var err error
	if txn == nil {
		txn, err = r.store.NewTransaction(ctx)
		if err != nil {
			return PreparedEvalQuery{}, err
		}
		defer r.store.Abort(ctx, txn)
	}

	// If the caller wanted to do partial evaluation as part of preparation
	// do it now and use the new Rego object.
	if pCfg.doPartialEval {
		err := r.prepare(ctx, txn, partialResultQueryType, []extraStage{
			{
				after: "ResolveRefs",
				stage: r.rewriteQueryForPartialEval,
			},
		})
		if err != nil {
			return PreparedEvalQuery{}, err
		}

		ectx := &EvalContext{
			parsedInput:      r.parsedInput,
			metrics:          r.metrics,
			txn:              txn,
			partialNamespace: r.partialNamespace,
			tracers:          r.tracers,
			compiledQuery:    r.compiledQueries[partialResultQueryType],
		}

		pr, err := r.partialResult(ctx, ectx, ast.Wildcard)
		if err != nil {
			return PreparedEvalQuery{}, err
		}
		// Prepare the new query
		return pr.Rego().PrepareForEval(ctx)
	}

	err = r.prepare(ctx, txn, evalQueryType, []extraStage{
		{
			after: "ResolveRefs",
			stage: r.rewriteQueryToCaptureValue,
		},
	})
	if err != nil {
		return PreparedEvalQuery{}, err
	}

	return PreparedEvalQuery{preparedQuery{r, pCfg}}, err
}