-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuilder.go
70 lines (62 loc) · 1.52 KB
/
builder.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
68
69
70
package queries
import (
"fmt"
"strings"
)
type Builder struct {
query strings.Builder
args []any
counter int
placeholder rune
}
func (b *Builder) Appendf(format string, args ...any) {
a := make([]any, len(args))
for i, arg := range args {
a[i] = argument{value: arg, builder: b}
}
fmt.Fprintf(&b.query, format, a...)
}
func (b *Builder) Query() string {
query := b.query.String()
if strings.Contains(query, "%!") {
// fmt silently recovers panics and writes them to the output.
// We want panics to be loud, so we find and rethrow them.
// See also https://github.com/golang/go/issues/28150.
panic(fmt.Sprintf("queries: bad query: %s", query))
}
if b.placeholder == -1 {
panic("queries: different placeholders used")
}
return query
}
func (b *Builder) Args() []any { return b.args }
type argument struct {
value any
builder *Builder
}
// Format implements the [fmt.Formatter] interface.
func (a argument) Format(s fmt.State, verb rune) {
switch verb {
case '?', '$', '@':
a.builder.args = append(a.builder.args, a.value)
if a.builder.placeholder == 0 {
a.builder.placeholder = verb
}
if a.builder.placeholder != verb {
a.builder.placeholder = -1
}
}
switch verb {
case '?': // MySQL, SQLite
fmt.Fprint(s, "?")
case '$': // PostgreSQL
a.builder.counter++
fmt.Fprintf(s, "$%d", a.builder.counter)
case '@': // MSSQL
a.builder.counter++
fmt.Fprintf(s, "@p%d", a.builder.counter)
default:
format := fmt.FormatString(s, verb)
fmt.Fprintf(s, format, a.value)
}
}