// prepare is a helper to prepare a query for future execution
323468
func (c *CockroachDBBackend) prepare(name, query string) error {
	stmt, err := c.client.Prepare(query)
	if err != nil {
		return errwrap.Wrapf(fmt.Sprintf("failed to prepare %q: {{err}}", name), err)
	}
	c.statements[name] = stmt
	return nil
}
1168872
func (conn *OCI8Conn) PrepareContext(ctx context.Context, query string) (driver.Stmt, error) {
	if conn.enableQMPlaceholders {
		query = placeholders(query)
	}

	queryP := cString(query)
	defer C.free(unsafe.Pointer(queryP))

	// statement handle
	stmt, _, err := conn.ociHandleAlloc(C.OCI_HTYPE_STMT, 0)
	if err != nil {
		return nil, fmt.Errorf("allocate statement handle error: %v", err)
	}

	if rv := C.OCIStmtPrepare(
		(*C.OCIStmt)(*stmt),
		conn.errHandle,
		queryP,
		C.ub4(len(query)),
		C.ub4(C.OCI_NTV_SYNTAX),
		C.ub4(C.OCI_DEFAULT),
	); rv != C.OCI_SUCCESS {
		C.OCIHandleFree(*stmt, C.OCI_HTYPE_STMT)
		return nil, conn.getError(rv)
	}

	return &OCI8Stmt{conn: conn, stmt: (*C.OCIStmt)(*stmt)}, nil
}
786862
func (c *CrateDriver) Prepare(query string) (driver.Stmt, error) {
	stmt := &CrateStmt{
		stmt:   query,
		driver: c,
	}

	return stmt, nil
}
56968
func (p Profile) Prepare(s string) (string, error) {
	// Optimistically, assume output will be same length as input
	temp := make([]rune, 0, len(s))

	// Apply maps
	for _, r := range s {
		rs, ok := p.applyMaps(r)
		if ok {
			temp = append(temp, rs...)
		} else {
			temp = append(temp, r)
		}
	}

	// Normalize
	var out string
	if p.Normalize {
		out = norm.NFKC.String(string(temp))
	} else {
		out = string(temp)
	}

	// Check prohibited
	for _, r := range out {
		if p.runeIsProhibited(r) {
			return "", Error{Msg: errProhibited, Rune: r}
		}
	}

	// Check BiDi allowed
	if p.CheckBiDi {
		if err := passesBiDiRules(out); err != nil {
			return "", err
		}
	}

	return out, nil
}
84445
func (change payloadUntrackChange) Prepare(db Database) ([]txn.Op, error) {
	docID := nsPayloads.docID(change.Unit, change.Name)
	payloads, closer := db.GetCollection(payloadsC)
	defer closer()

	op, err := nsPayloads.untrackOp(payloads, docID)
	if errors.Cause(err) == errAlreadyRemoved {
		return nil, ErrChangeComplete
	} else if err != nil {
		return nil, errors.Trace(err)
	}
	return []txn.Op{op}, nil
}
608229
func (c *Option) prepare() (opts *js.Object) {
	if len(c.coms) > 0 {
		c.Set("components", c.coms)
	}
	if len(c.props) > 0 {
		c.Set("props", c.props)
	}
	if len(c.mixins) > 0 {
		c.Set("mixins", c.mixins)
	}
	return c.Object
}
615207
func (s *Restore) PreparedQuery(query *structs.PreparedQuery) error {
	// If this is a template, compile it, otherwise leave the compiled
	// template field nil.
	var ct *prepared_query.CompiledTemplate
	if prepared_query.IsTemplate(query) {
		var err error
		ct, err = prepared_query.Compile(query)
		if err != nil {
			return fmt.Errorf("failed compiling template: %s", err)
		}
	}

	// Insert the wrapped query.
	if err := s.tx.Insert("prepared-queries", &queryWrapper{query, ct}); err != nil {
		return fmt.Errorf("failed restoring prepared query: %s", err)
	}
	if err := indexUpdateMaxTxn(s.tx, query.ModifyIndex, "prepared-queries"); err != nil {
		return fmt.Errorf("failed updating index: %s", err)
	}

	return nil
}
1191588
func (self *StateDB) Prepare(thash, bhash common.Hash, ti int) {
	self.thash = thash
	self.bhash = bhash
	self.txIndex = ti
}
1229180
func (ethash *Ethash) Prepare(chain consensus.ChainReader, header *types.Header) error {
	parent := chain.GetHeader(header.ParentHash, header.Number.Uint64()-1)
	if parent == nil {
		return consensus.ErrUnknownAncestor
	}
	header.Difficulty = ethash.CalcDifficulty(chain, header.Time, parent)
	return nil
}
982811
func (p *PreparedQuery) Apply(args *structs.PreparedQueryRequest, reply *string) (err error) {
	if done, err := p.srv.forward("PreparedQuery.Apply", args, args, reply); done {
		return err
	}
	defer metrics.MeasureSince([]string{"prepared-query", "apply"}, time.Now())

	// Validate the ID. We must create new IDs before applying to the Raft
	// log since it's not deterministic.
	if args.Op == structs.PreparedQueryCreate {
		if args.Query.ID != "" {
			return fmt.Errorf("ID must be empty when creating a new prepared query")
		}

		// We are relying on the fact that UUIDs are random and unlikely
		// to collide since this isn't inside a write transaction.
		state := p.srv.fsm.State()
		for {
			if args.Query.ID, err = uuid.GenerateUUID(); err != nil {
				return fmt.Errorf("UUID generation for prepared query failed: %v", err)
			}
			_, query, err := state.PreparedQueryGet(nil, args.Query.ID)
			if err != nil {
				return fmt.Errorf("Prepared query lookup failed: %v", err)
			}
			if query == nil {
				break
			}
		}
	}
	*reply = args.Query.ID

	// Get the ACL token for the request for the checks below.
	rule, err := p.srv.ResolveToken(args.Token)
	if err != nil {
		return err
	}

	// If prefix ACLs apply to the incoming query, then do an ACL check. We
	// need to make sure they have write access for whatever they are
	// proposing.
	if prefix, ok := args.Query.GetACLPrefix(); ok {
		if rule != nil && !rule.PreparedQueryWrite(prefix) {
			p.srv.logger.Printf("[WARN] consul.prepared_query: Operation on prepared query '%s' denied due to ACLs", args.Query.ID)
			return acl.ErrPermissionDenied
		}
	}

	// This is the second part of the check above. If they are referencing
	// an existing query then make sure it exists and that they have write
	// access to whatever they are changing, if prefix ACLs apply to it.
	if args.Op != structs.PreparedQueryCreate {
		state := p.srv.fsm.State()
		_, query, err := state.PreparedQueryGet(nil, args.Query.ID)
		if err != nil {
			return fmt.Errorf("Prepared Query lookup failed: %v", err)
		}
		if query == nil {
			return fmt.Errorf("Cannot modify non-existent prepared query: '%s'", args.Query.ID)
		}

		if prefix, ok := query.GetACLPrefix(); ok {
			if rule != nil && !rule.PreparedQueryWrite(prefix) {
				p.srv.logger.Printf("[WARN] consul.prepared_query: Operation on prepared query '%s' denied due to ACLs", args.Query.ID)
				return acl.ErrPermissionDenied
			}
		}
	}

	// Parse the query and prep it for the state store.
	switch args.Op {
	case structs.PreparedQueryCreate, structs.PreparedQueryUpdate:
		if err := parseQuery(args.Query, p.srv.config.ACLEnforceVersion8); err != nil {
			return fmt.Errorf("Invalid prepared query: %v", err)
		}

	case structs.PreparedQueryDelete:
		// Nothing else to verify here, just do the delete (we only look
		// at the ID field for this op).

	default:
		return fmt.Errorf("Unknown prepared query operation: %s", args.Op)
	}

	// Commit the query to the state store.
	resp, err := p.srv.raftApply(structs.PreparedQueryRequestType, args)
	if err != nil {
		p.srv.logger.Printf("[ERR] consul.prepared_query: Apply failed %v", err)
		return err
	}
	if respErr, ok := resp.(error); ok {
		return respErr
	}

	return nil
}
342499
func (s3 *S3) prepare(req *request) error {
	var signpath = req.path

	if !req.prepared {
		req.prepared = true
		if req.method == "" {
			req.method = "GET"
		}
		// Copy so they can be mutated without affecting on retries.
		params := make(url.Values)
		headers := make(http.Header)
		for k, v := range req.params {
			params[k] = v
		}
		for k, v := range req.headers {
			headers[k] = v
		}
		req.params = params
		req.headers = headers
		if !strings.HasPrefix(req.path, "/") {
			req.path = "/" + req.path
		}
		signpath = req.path
		if req.bucket != "" {
			req.baseurl = s3.Region.S3BucketEndpoint
			if req.baseurl == "" {
				// Use the path method to address the bucket.
				req.baseurl = s3.Region.S3Endpoint
				req.path = "/" + req.bucket + req.path
			} else {
				// Just in case, prevent injection.
				if strings.IndexAny(req.bucket, "/:@") >= 0 {
					return fmt.Errorf("bad S3 bucket: %q", req.bucket)
				}
				req.baseurl = strings.Replace(req.baseurl, "${bucket}", req.bucket, -1)
			}
			signpath = "/" + req.bucket + signpath
		}
	}

	// Always sign again as it's not clear how far the
	// server has handled a previous attempt.
	u, err := url.Parse(req.baseurl)
	if err != nil {
		return fmt.Errorf("bad S3 endpoint URL %q: %v", req.baseurl, err)
	}
	reqSignpathSpaceFix := (&url.URL{Path: signpath}).String()
	req.headers["Host"] = []string{u.Host}
	req.headers["Date"] = []string{time.Now().In(time.UTC).Format(time.RFC1123)}
	return s3.sign(req.method, reqSignpathSpaceFix, req.params, req.headers)
}
682579
func (tx *Tx) Prepare(name, sql string) (*PreparedStatement, error) {
	return tx.PrepareEx(context.Background(), name, sql, nil)
}
1144518
func (r *Rego) PrepareForPartial(ctx context.Context, opts ...PrepareOption) (PreparedPartialQuery, error) {
	if !r.hasQuery() {
		return PreparedPartialQuery{}, 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 PreparedPartialQuery{}, err
		}
		defer r.store.Abort(ctx, txn)
	}

	err = r.prepare(ctx, txn, partialQueryType, []extraStage{
		{
			after: "CheckSafety",
			stage: r.rewriteEqualsForPartialQueryCompile,
		},
	})

	if err != nil {
		return PreparedPartialQuery{}, err
	}

	return PreparedPartialQuery{preparedQuery{r, pCfg}}, err
}
780450
func (s *Store) PreparedQuerySet(idx uint64, query *structs.PreparedQuery) error {
	tx := s.db.Txn(true)
	defer tx.Abort()

	if err := s.preparedQuerySetTxn(tx, idx, query); err != nil {
		return err
	}

	tx.Commit()
	return nil
}
1142920
func (e *Expr) Prepare(expr string) error {

	//call Golang pareexpr function
	exp, err := parser.ParseExpr(expr)
	if err != nil {
		return err
	}

	//resolve constants to its values
	//to avoid unnecesary conversions
	exp = resolveConstants(exp).(ast.Expr)
	if err != nil {
		return err
	}
	e.expr = exp
	return err
}
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
}
109802
func (rr *RetriableRequest) Prepare() (err error) {
	// preserve the request body; this is to support retry logic as
	// the underlying transport will always close the reqeust body
	if rr.req.Body != nil {
		if rr.rc != nil {
			rr.req.Body = rr.rc
		} else if rr.br != nil {
			_, err = rr.br.Seek(0, io.SeekStart)
			rr.req.Body = ioutil.NopCloser(rr.br)
		}
		if err != nil {
			return err
		}
		if rr.req.GetBody != nil {
			// this will allow us to preserve the body without having to
			// make a copy.  note we need to do this on each iteration
			rr.rc, err = rr.req.GetBody()
			if err != nil {
				return err
			}
		} else if rr.br == nil {
			// fall back to making a copy (only do this once)
			err = rr.prepareFromByteReader()
		}
	}
	return err
}