// RewriteAsPrepareable rewite the insert as a ? substituteable query
//     INSERT INTO user (name) VALUES ("wonder-woman") ->
//        INSERT INTO user (name) VALUES (?)
359666
func (m *SqlInsert) RewriteAsPrepareable(maxRows int, mark byte) string {
	buf := bytes.Buffer{}
	buf.WriteString(fmt.Sprintf("INSERT INTO %s (", m.Table))

	for i, col := range m.Columns {
		if i > 0 {
			buf.WriteString(", ")
		}
		buf.WriteString(col.String())
	}
	buf.WriteString(") VALUES")
	for i, row := range m.Rows {
		if maxRows > 0 && i >= maxRows {
			break
		}
		if i > 0 {
			buf.WriteString("\n\t,")
		}
		buf.WriteString(" (")
		for vi := range row {
			if vi > 0 {
				buf.WriteString(" ,")
			}
			buf.WriteByte(mark)
		}
		buf.WriteByte(')')
	}
	return buf.String()
}
250138
func (d *dbBase) PrepareInsert(q dbQuerier, mi *modelInfo) (stmtQuerier, string, error) {
	Q := d.ins.TableQuote()

	dbcols := make([]string, 0, len(mi.fields.dbcols))
	marks := make([]string, 0, len(mi.fields.dbcols))
	for _, fi := range mi.fields.fieldsDB {
		if fi.auto == false {
			dbcols = append(dbcols, fi.column)
			marks = append(marks, "?")
		}
	}
	qmarks := strings.Join(marks, ", ")
	sep := fmt.Sprintf("%s, %s", Q, Q)
	columns := strings.Join(dbcols, sep)

	query := fmt.Sprintf("INSERT INTO %s%s%s (%s%s%s) VALUES (%s)", Q, mi.table, Q, Q, columns, Q, qmarks)

	d.ins.ReplaceMarks(&query)

	d.ins.HasReturningID(mi, &query)

	stmt, err := q.Prepare(query)
	return stmt, query, err
}
334980
func (rw *HeaderRewriter) Rewrite(req *http.Request) {
	if !rw.TrustForwardHeader {
		utils.RemoveHeaders(req.Header, XHeaders...)
	}

	if clientIP, _, err := net.SplitHostPort(req.RemoteAddr); err == nil {
		clientIP = ipv6fix(clientIP)
		// If not websocket, done in http.ReverseProxy
		if IsWebsocketRequest(req) {
			if prior, ok := req.Header[XForwardedFor]; ok {
				req.Header.Set(XForwardedFor, strings.Join(prior, ", ")+", "+clientIP)
			} else {
				req.Header.Set(XForwardedFor, clientIP)
			}
		}

		if req.Header.Get(XRealIp) == "" {
			req.Header.Set(XRealIp, clientIP)
		}
	}

	xfProto := req.Header.Get(XForwardedProto)
	if xfProto == "" {
		if req.TLS != nil {
			req.Header.Set(XForwardedProto, "https")
		} else {
			req.Header.Set(XForwardedProto, "http")
		}
	}

	if IsWebsocketRequest(req) {
		if req.Header.Get(XForwardedProto) == "https" {
			req.Header.Set(XForwardedProto, "wss")
		} else {
			req.Header.Set(XForwardedProto, "ws")
		}
	}

	if xfPort := req.Header.Get(XForwardedPort); xfPort == "" {
		req.Header.Set(XForwardedPort, forwardedPort(req))
	}

	if xfHost := req.Header.Get(XForwardedHost); xfHost == "" && req.Host != "" {
		req.Header.Set(XForwardedHost, req.Host)
	}

	if rw.Hostname != "" {
		req.Header.Set(XForwardedServer, rw.Hostname)
	}
}
600679
func (m *PlannerDefault) WalkPreparedStatement(p *PreparedStatement) error {
	u.Debugf("WalkPreparedStatement %+v", p.Stmt)
	return ErrNotImplemented
}
1045342
func (s *PerUserKeyring) PreparePrev(m MetaContext, newSeed PerUserKeySeed,
	newGeneration keybase1.PerUserKeyGeneration) (PerUserKeyPrev, error) {
	s.Lock()
	defer s.Unlock()

	if newSeed.IsBlank() {
		return "", errors.New("attempt to prev with blank per-user-key")
	}

	currentGen := s.currentGenerationLocked()
	if currentGen == 0 {
		return "", errors.New("attempt to prepare per-user-key prev with no keys")
	}
	if currentGen != newGeneration-1 {
		return "", fmt.Errorf("incompatible prev generations %v != %v-1", currentGen, newGeneration)
	}

	symmetricKey, err := newSeed.derivePrevKey()
	if err != nil {
		return "", err
	}

	contents := s.generations[currentGen].seed

	return newPerUserKeyPrev(contents, symmetricKey)
}
1185293
func (a *aggregationEliminateChecker) rewriteExpr(ctx sessionctx.Context, aggFunc *aggregation.AggFuncDesc) expression.Expression {
	switch aggFunc.Name {
	case ast.AggFuncCount:
		if aggFunc.Mode == aggregation.FinalMode {
			return a.wrapCastFunction(ctx, aggFunc.Args[0], aggFunc.RetTp)
		}
		return a.rewriteCount(ctx, aggFunc.Args, aggFunc.RetTp)
	case ast.AggFuncSum, ast.AggFuncAvg, ast.AggFuncFirstRow, ast.AggFuncMax, ast.AggFuncMin, ast.AggFuncGroupConcat:
		return a.wrapCastFunction(ctx, aggFunc.Args[0], aggFunc.RetTp)
	case ast.AggFuncBitAnd, ast.AggFuncBitOr, ast.AggFuncBitXor:
		return a.rewriteBitFunc(ctx, aggFunc.Name, aggFunc.Args[0], aggFunc.RetTp)
	default:
		panic("Unsupported function")
	}
}
998904
func (r *userMemoryRepository) InsertOrUpdate(user datamodels.User) (datamodels.User, error) {
	id := user.ID

	if id == 0 { // Create new action
		var lastID int64
		// find the biggest ID in order to not have duplications
		// in productions apps you can use a third-party
		// library to generate a UUID as string.
		r.mu.RLock()
		for _, item := range r.source {
			if item.ID > lastID {
				lastID = item.ID
			}
		}
		r.mu.RUnlock()

		id = lastID + 1
		user.ID = id

		// map-specific thing
		r.mu.Lock()
		r.source[id] = user
		r.mu.Unlock()

		return user, nil
	}

	// Update action based on the user.ID,
	// here we will allow updating the poster and genre if not empty.
	// Alternatively we could do pure replace instead:
	// r.source[id] = user
	// and comment the code below;
	current, exists := r.Select(func(m datamodels.User) bool {
		return m.ID == id
	})

	if !exists { // ID is not a real one, return an error.
		return datamodels.User{}, errors.New("failed to update a nonexistent user")
	}

	// or comment these and r.source[id] = user for pure replace
	if user.Username != "" {
		current.Username = user.Username
	}

	if user.Firstname != "" {
		current.Firstname = user.Firstname
	}

	// map-specific thing
	r.mu.Lock()
	r.source[id] = current
	r.mu.Unlock()

	return user, nil
}
989683
func (s *HTTPServer) preparedQueryExplain(id string, resp http.ResponseWriter, req *http.Request) (interface{}, error) {
	args := structs.PreparedQueryExecuteRequest{
		QueryIDOrName: id,
		Agent: structs.QuerySource{
			Node:       s.agent.config.NodeName,
			Datacenter: s.agent.config.Datacenter,
			Segment:    s.agent.config.SegmentName,
		},
	}
	s.parseSource(req, &args.Source)
	if done := s.parse(resp, req, &args.Datacenter, &args.QueryOptions); done {
		return nil, nil
	}
	if err := parseLimit(req, &args.Limit); err != nil {
		return nil, fmt.Errorf("Bad limit: %s", err)
	}

	var reply structs.PreparedQueryExplainResponse
	defer setMeta(resp, &reply.QueryMeta)
RETRY_ONCE:
	if err := s.agent.RPC("PreparedQuery.Explain", &args, &reply); err != nil {
		// We have to check the string since the RPC sheds
		// the specific error type.
		if err.Error() == consul.ErrQueryNotFound.Error() {
			resp.WriteHeader(http.StatusNotFound)
			fmt.Fprint(resp, err.Error())
			return nil, nil
		}
		return nil, err
	}
	if args.QueryOptions.AllowStale && args.MaxStaleDuration > 0 && args.MaxStaleDuration < reply.LastContact {
		args.AllowStale = false
		args.MaxStaleDuration = 0
		goto RETRY_ONCE
	}
	reply.ConsistencyLevel = args.QueryOptions.ConsistencyLevel()
	return reply, nil
}
350239
func (rule *substringNameRule) Rewrite(ctx context.Context, state request.Request) Result {
	if strings.Contains(state.Name(), rule.Substring) {
		state.Req.Question[0].Name = strings.Replace(state.Name(), rule.Substring, rule.Replacement, -1)
		return RewriteDone
	}
	return RewriteIgnored
}
242379
func (r ComplexRule) Rewrite(fs http.FileSystem, req *http.Request) (re Result) {
	replacer := newReplacer(req)

	// validate regexp if present
	if r.Regexp != nil {
		matches := regexpMatches(r.Regexp, r.Base, req.URL.Path)
		switch len(matches) {
		case 0:
			// no match
			return
		default:
			// set regexp match variables {1}, {2} ...

			// url escaped values of ? and #.
			q, f := url.QueryEscape("?"), url.QueryEscape("#")

			for i := 1; i < len(matches); i++ {
				// Special case of unescaped # and ? by stdlib regexp.
				// Reverse the unescape.
				if strings.ContainsAny(matches[i], "?#") {
					matches[i] = strings.NewReplacer("?", q, "#", f).Replace(matches[i])
				}

				replacer.Set(fmt.Sprint(i), matches[i])
			}
		}
	}

	// attempt rewrite
	return To(fs, req, r.To, replacer)
}
725589
func (self *qbsWrapped) AllowWrite(pb PBundle) bool {
	allow, ok := self.post.(AllowWriter)
	if !ok {
		return true
	}
	return allow.AllowWrite(pb)
}
8389
func (rule *edns0SubnetRule) Rewrite(w dns.ResponseWriter, r *dns.Msg) Result {
	result := RewriteIgnored
	o := setupEdns0Opt(r)
	found := false
	for _, s := range o.Option {
		switch e := s.(type) {
		case *dns.EDNS0_SUBNET:
			if rule.action == Replace || rule.action == Set {
				if rule.fillEcsData(w, r, e) == nil {
					result = RewriteDone
				}
			}
			found = true
			break
		}
	}

	// add option if not found
	if !found && (rule.action == Append || rule.action == Set) {
		o.SetDo()
		opt := dns.EDNS0_SUBNET{Code: dns.EDNS0SUBNET}
		if rule.fillEcsData(w, r, &opt) == nil {
			o.Option = append(o.Option, &opt)
			result = RewriteDone
		}
	}

	return result
}
788333
func (rule MergeFromRangeRule) Rewrite(node plan.Node) (plan.Node, bool, error) {
	from := node.Predecessors()[0]
	fromSpec := from.ProcedureSpec().(*PhysicalFromProcedureSpec)
	rangeSpec := node.ProcedureSpec().(*universe.RangeProcedureSpec)
	fromRange := fromSpec.Copy().(*PhysicalFromProcedureSpec)

	// Set new bounds to `range` bounds initially
	fromRange.Bounds = rangeSpec.Bounds

	var (
		now   = rangeSpec.Bounds.Now
		start = rangeSpec.Bounds.Start
		stop  = rangeSpec.Bounds.Stop
	)

	bounds := &plan.Bounds{
		Start: values.ConvertTime(start.Time(now)),
		Stop:  values.ConvertTime(stop.Time(now)),
	}

	// Intersect bounds if `from` already bounded
	if fromSpec.BoundsSet {
		now = fromSpec.Bounds.Now
		start = fromSpec.Bounds.Start
		stop = fromSpec.Bounds.Stop

		fromBounds := &plan.Bounds{
			Start: values.ConvertTime(start.Time(now)),
			Stop:  values.ConvertTime(stop.Time(now)),
		}

		bounds = bounds.Intersect(fromBounds)
		fromRange.Bounds = flux.Bounds{
			Start: flux.Time{Absolute: bounds.Start.Time()},
			Stop:  flux.Time{Absolute: bounds.Stop.Time()},
		}
	}

	fromRange.BoundsSet = true

	// Finally merge nodes into single operation
	merged, err := plan.MergeToPhysicalNode(node, from, fromRange)
	if err != nil {
		return nil, false, err
	}

	return merged, true, nil
}
745704
func InsertBlockPrevNext(db *sql.DB, blockDbID uint64,
	hash, prev, next string) error {
	rows, err := db.Query(internal.InsertBlockPrevNext, blockDbID, prev, hash, next)
	if err == nil {
		return rows.Close()
	}
	return err
}
1262468
func (s *SelectStatement) RewriteDistinct() {
	WalkFunc(s.Fields, func(n Node) {
		switch n := n.(type) {
		case *Field:
			if expr, ok := n.Expr.(*Distinct); ok {
				n.Expr = expr.NewCall()
				s.IsRawQuery = false
			}
		case *Call:
			for i, arg := range n.Args {
				if arg, ok := arg.(*Distinct); ok {
					n.Args[i] = arg.NewCall()
				}
			}
		}
	})
}
47676
func Rewrite(in, out string) RewritePair {
	return RewritePair{
		Expr:        regexp.MustCompile(in),
		Replacement: out,
	}
}
1237582
func (q *query) CommitPrepared(ctx context.Context, request *querypb.CommitPreparedRequest) (response *querypb.CommitPreparedResponse, err error) {
	defer q.server.HandlePanic(&err)
	ctx = callerid.NewContext(callinfo.GRPCCallInfo(ctx),
		request.EffectiveCallerId,
		request.ImmediateCallerId,
	)
	if err := q.server.CommitPrepared(ctx, request.Target, request.Dtid); err != nil {
		return nil, vterrors.ToGRPC(err)
	}

	return &querypb.CommitPreparedResponse{}, nil
}