/
context.go
77 lines (64 loc) · 1.7 KB
/
context.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
71
72
73
74
75
76
77
package types
import (
"fmt"
"strings"
"github.com/ulule/loukoum/v3/format"
)
// A Context is passed to a root stmt.Statement to generate a query.
type Context interface {
Write(query string)
Bind(value interface{})
}
// RawContext embeds values directly in the query.
type RawContext struct {
buffer strings.Builder
}
// Write appends given subquery in context's buffer.
func (ctx *RawContext) Write(query string) {
_, err := ctx.buffer.WriteString(query)
if err != nil {
panic("loukoum: cannot write on buffer")
}
}
// Bind adds given value in context's values.
func (ctx *RawContext) Bind(value interface{}) {
ctx.Write(format.Value(value))
}
// Query returns the underlaying query.
func (ctx *RawContext) Query() string {
return ctx.buffer.String()
}
// NamedContext uses named query placeholders.
type NamedContext struct {
RawContext
values map[string]interface{}
}
// Bind adds given value in context's values.
func (ctx *NamedContext) Bind(value interface{}) {
if ctx.values == nil {
ctx.values = make(map[string]interface{})
}
idx := len(ctx.values) + 1
name := fmt.Sprintf("arg_%d", idx)
ctx.values[name] = value
ctx.Write(":" + name)
}
// Values returns the named argument values.
func (ctx *NamedContext) Values() map[string]interface{} {
return ctx.values
}
// StdContext uses positional query placeholders.
type StdContext struct {
RawContext
values []interface{}
}
// Bind adds given value in context's values.
func (ctx *StdContext) Bind(value interface{}) {
idx := len(ctx.values) + 1
ctx.values = append(ctx.values, value)
ctx.Write(fmt.Sprintf("$%d", idx))
}
// Values returns the positional argument values.
func (ctx *StdContext) Values() []interface{} {
return ctx.values
}