-
Notifications
You must be signed in to change notification settings - Fork 45
/
named.go
67 lines (52 loc) · 1.26 KB
/
named.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package bob
import (
"context"
"database/sql/driver"
"fmt"
"io"
)
type RawNamedArgError struct {
Name string
}
func (e RawNamedArgError) Error() string {
return fmt.Sprintf("raw named arg %q used without rebinding", e.Name)
}
// named args should ONLY be used to prepare statements
type namedArg string
// Value implements the driver.Valuer interface.
// it always returns an error because named args should only be used to prepare statements
func (n namedArg) Value() (driver.Value, error) {
return nil, RawNamedArgError{string(n)}
}
// Named args should ONLY be used to prepare statements
func Named(names ...string) Expression {
return named{names: names}
}
// NamedGroup is like Named, but wraps in parentheses
func NamedGroup(names ...string) Expression {
return named{names: names}
}
type named struct {
names []string
grouped bool
}
func (a named) WriteSQL(ctx context.Context, w io.Writer, d Dialect, start int) ([]any, error) {
if len(a.names) == 0 {
return nil, nil
}
args := make([]any, len(a.names))
if a.grouped {
w.Write([]byte(openPar))
}
for k, name := range a.names {
if k > 0 {
w.Write([]byte(commaSpace))
}
d.WriteArg(w, start+k)
args[k] = namedArg(name)
}
if a.grouped {
w.Write([]byte(closePar))
}
return args, nil
}