github.com/cockroachdb/cockroach@v20.2.0-alpha.1+incompatible/pkg/sql/execute.go (about)

     1  // Copyright 2017 The Cockroach Authors.
     2  //
     3  // Use of this software is governed by the Business Source License
     4  // included in the file licenses/BSL.txt.
     5  //
     6  // As of the Change Date specified in that file, in accordance with
     7  // the Business Source License, use of this software will be governed
     8  // by the Apache License, Version 2.0, included in the file
     9  // licenses/APL.txt.
    10  
    11  package sql
    12  
    13  import (
    14  	"context"
    15  
    16  	"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgcode"
    17  	"github.com/cockroachdb/cockroach/pkg/sql/pgwire/pgerror"
    18  	"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
    19  	"github.com/cockroachdb/cockroach/pkg/sql/sessiondata"
    20  	"github.com/cockroachdb/cockroach/pkg/sql/sqlbase"
    21  	"github.com/cockroachdb/errors"
    22  )
    23  
    24  // fillInPlaceholder helps with the EXECUTE foo(args) SQL statement: it takes in
    25  // a prepared statement returning
    26  // the referenced prepared statement and correctly updated placeholder info.
    27  // See https://www.postgresql.org/docs/current/static/sql-execute.html for details.
    28  func fillInPlaceholders(
    29  	ctx context.Context,
    30  	ps *PreparedStatement,
    31  	name string,
    32  	params tree.Exprs,
    33  	searchPath sessiondata.SearchPath,
    34  ) (*tree.PlaceholderInfo, error) {
    35  	if len(ps.Types) != len(params) {
    36  		return nil, pgerror.Newf(pgcode.Syntax,
    37  			"wrong number of parameters for prepared statement %q: expected %d, got %d",
    38  			name, len(ps.Types), len(params))
    39  	}
    40  
    41  	qArgs := make(tree.QueryArguments, len(params))
    42  	var semaCtx tree.SemaContext
    43  	for i, e := range params {
    44  		idx := tree.PlaceholderIdx(i)
    45  
    46  		typ, ok := ps.ValueType(idx)
    47  		if !ok {
    48  			return nil, errors.AssertionFailedf("no type for placeholder %s", idx)
    49  		}
    50  		typedExpr, err := sqlbase.SanitizeVarFreeExpr(
    51  			ctx, e, typ, "EXECUTE parameter", /* context */
    52  			&semaCtx, true /* allowImpure */)
    53  		if err != nil {
    54  			return nil, pgerror.WithCandidateCode(err, pgcode.WrongObjectType)
    55  		}
    56  
    57  		qArgs[idx] = typedExpr
    58  	}
    59  	return &tree.PlaceholderInfo{
    60  		Values: qArgs,
    61  		PlaceholderTypesInfo: tree.PlaceholderTypesInfo{
    62  			TypeHints: ps.TypeHints,
    63  			Types:     ps.Types,
    64  		},
    65  	}, nil
    66  }