database/sql: add option to use named parameter in query arguments

Modify the new Context methods to take a name-value driver struct.
This will require more modifications to drivers to use, but will
reduce the overall number of structures that need to be maintained
over time.

Fixes #12381

Change-Id: I30747533ce418a1be5991a0c8767a26e8451adbd
Reviewed-on: https://go-review.googlesource.com/30166
Reviewed-by: Brad Fitzpatrick <bradfitz@golang.org>
Run-TryBot: Brad Fitzpatrick <bradfitz@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
This commit is contained in:
Daniel Theophanes 2016-10-03 09:49:25 -07:00 committed by Brad Fitzpatrick
parent 99df54f196
commit 707a83341b
6 changed files with 202 additions and 39 deletions

View file

@ -67,6 +67,27 @@ func Drivers() []string {
return list
}
// NamedParam may be passed into query parameter arguments to associate
// a named placeholder with a value.
type NamedParam struct {
// Name of the parameter placeholder. If empty the ordinal position in the
// argument list will be used.
Name string
// Value of the parameter. It may be assigned the same value types as
// the query arguments.
Value interface{}
}
// Param provides a more concise way to create NamedParam values.
func Param(name string, value interface{}) NamedParam {
// This method exists because the go1compat promise
// doesn't guarantee that structs don't grow more fields,
// so unkeyed struct literals are a vet error. Thus, we don't
// want to encourage sql.NamedParam{name, value}.
return NamedParam{Name: name, Value: value}
}
// RawBytes is a byte slice that holds a reference to memory owned by
// the database itself. After a Scan into a RawBytes, the slice is only
// valid until the next call to Next, Scan, or Close.
@ -1064,7 +1085,7 @@ func (db *DB) exec(ctx context.Context, query string, args []interface{}, strate
}()
if execer, ok := dc.ci.(driver.Execer); ok {
var dargs []driver.Value
var dargs []driver.NamedValue
dargs, err = driverArgs(nil, args)
if err != nil {
return nil, err