-
Notifications
You must be signed in to change notification settings - Fork 10
/
builder.go
114 lines (94 loc) · 2.11 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package sqlc
import (
"fmt"
"strconv"
"strings"
)
type (
Builder struct {
filters []filter
order string
offset, limit int
}
filter struct {
expression string
args []interface{}
}
)
func (b *Builder) clone() *Builder {
var cb Builder
cb = *b
return &cb
}
// Where set conditions of where in SELECT
// Where("user = ?","tom")
// Where("a = ? OR b = ?",1,2)
// Where("foo = $1","bar")
func (b *Builder) Where(query string, args ...interface{}) *Builder {
b.filters = append(b.filters, filter{
expression: query,
args: args,
})
return b
}
// In is an equivalent of Where("column IN (?,?,?)", args...).
// In("id", 1, 2, 3)
func (b *Builder) In(column string, args ...interface{}) *Builder {
placeholders := make([]string, len(args))
for i := range args {
placeholders[i] = "?"
}
query := fmt.Sprintf("%s IN (%s)", column, strings.Join(placeholders, ","))
return b.Where(query, args...)
}
// Order sets columns of ORDER BY in SELECT.
// Order("name, age DESC")
func (b *Builder) Order(cols string) *Builder {
b.order = cols
return b
}
// Offset sets the offset in SELECT.
func (b *Builder) Offset(x int) *Builder {
b.offset = x
return b
}
// Limit sets the limit in SELECT.
func (b *Builder) Limit(x int) *Builder {
b.limit = x
return b
}
// Build returns compiled SELECT string and args.
func (b *Builder) Build(query string, args ...interface{}) (string, []interface{}) {
var sb strings.Builder
sb.WriteString(query)
sb.WriteByte('\n')
// append where conditions
for idx, filter := range b.filters {
if idx == 0 {
sb.WriteString("WHERE ")
} else {
sb.WriteString("AND ")
}
sb.WriteByte('(')
sb.WriteString(filter.expression)
sb.WriteByte(')')
sb.WriteByte('\n')
args = append(args, filter.args...)
}
if b.order != "" {
sb.WriteString("ORDER BY ")
sb.WriteString(b.order)
sb.WriteByte('\n')
}
if b.limit > 0 {
sb.WriteString("LIMIT ")
sb.WriteString(strconv.Itoa(b.limit))
sb.WriteByte('\n')
}
if b.offset > 0 {
sb.WriteString("OFFSET ")
sb.WriteString(strconv.Itoa(b.offset))
sb.WriteByte('\n')
}
return sb.String(), args
}