-
Notifications
You must be signed in to change notification settings - Fork 0
/
builder.go
231 lines (188 loc) · 5.2 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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
package qp
import (
"crypto/sha256"
"fmt"
"io"
"reflect"
"slices"
"strings"
"text/template"
"jig.sx/qp/qpjson"
"github.com/Masterminds/sprig/v3"
"github.com/jmoiron/sqlx/reflectx"
)
var defaultDialects = make(dialects).
add("mysql", mysqlQueries).
add("postgres", postgresqlQueries)
var funcs = template.FuncMap{
"pjoin": func(prefix, sep string, s []string) string {
sCopy := make([]string, len(s))
copy(sCopy, s)
for i, v := range s {
sCopy[i] = prefix + v
}
return strings.Join(sCopy, sep)
},
"isjson": func(v any) bool {
_, ok := v.(qpjson.Type)
return ok
},
}
type dialects map[string]*template.Template
func (d dialects) add(driver string, rawtemplate string) dialects {
base, ok := d[driver]
if !ok {
base = template.New(driver).Funcs(sprig.FuncMap()).Funcs(funcs)
d[driver] = base
}
if _, err := base.Parse(rawtemplate); err != nil {
panic("unexpected error: " + err.Error())
}
return d
}
var baseFields = map[string]struct{}{
"id": {},
"created_at": {},
"updated_at": {},
"deleted_at": {},
}
type builder struct {
dialects dialects
fields []string
table string
}
func newBuilder[T any](m *reflectx.Mapper, table string) *builder {
var (
t T
b = &builder{
table: table,
}
)
for _, fi := range m.TypeMap(reflect.TypeOf(t)).Index {
if _, ok := baseFields[fi.Name]; ok || fi.Embedded || strings.Contains(fi.Name, ".") {
continue
}
b.fields = append(b.fields, fi.Name)
}
return b
}
type ctx struct {
Table string
Fields []string
Columns []string
Values []any
}
type query struct {
key [sha256.Size]byte
driver string
name string
columns []string
values []any
}
func (b *builder) query(driver, name string, args ...any) (*query, error) {
columns, values, err := b.split(args...)
if err != nil {
return nil, err
}
h := sha256.New()
_, _ = io.WriteString(h, driver)
_, _ = io.WriteString(h, name)
for _, col := range columns {
_, _ = io.WriteString(h, col)
}
p := h.Sum(nil)
q := (*[sha256.Size]byte)(p[:])
return &query{
driver: driver,
name: name,
key: *q,
columns: columns,
values: values,
}, nil
}
func (b *builder) build(q *query) (string, error) {
t := b.template(q.driver)
if t == nil {
return "", fmt.Errorf("no template for %q driver", q.driver)
}
var buf strings.Builder
if err := t.ExecuteTemplate(&buf, q.name, ctx{
Table: b.table,
Fields: b.fields,
Columns: q.columns,
Values: q.values,
}); err != nil {
return "", err
}
return buf.String(), nil
}
func (b *builder) template(driver string) *template.Template {
if b.dialects != nil {
return b.dialects[driver]
}
return defaultDialects[driver]
}
func (b *builder) split(args ...any) (columns []string, values []any, err error) {
if len(args)%2 != 0 {
return nil, nil, fmt.Errorf("args length is not even")
}
for i := 0; i < len(args); i += 2 {
var column, expr string
switch v := args[i].(type) {
case qpjson.Ref:
column, expr = v.Column(), v.Expr()
case string:
column, expr = v, v
default:
return nil, nil, fmt.Errorf("invalid %[1]d field %[2]q (%[2]T)", i, args[i])
}
if _, ok := baseFields[column]; !ok && !slices.Contains(b.fields, column) {
return nil, nil, fmt.Errorf("invalid %d field %q", i, column)
}
columns = append(columns, expr)
values = append(values, args[i+1])
}
return columns, values, nil
}
const mysqlQueries = `
{{- define "select" -}}
SELECT * FROM {{ .Table }} WHERE deleted_at IS NULL{{ range $i, $col := .Columns }} AND {{ $col }} = ${{ (add $i 1) }}{{ end }} ORDER BY created_at DESC;
{{- end }}
{{- define "insert" -}}
INSERT INTO {{ .Table }} (id, {{ join ", " .Fields }}) VALUES (:id, {{ pjoin ":" ", " .Fields }});
{{- end }}
{{- define "update" -}}
{{- $v := .Values -}}
UPDATE {{ .Table }} SET updated_at = NOW(){{ range $i, $col := (slice .Columns 0 (sub (len .Columns) 1) ) -}}
{{- if isjson (index $v $i) -}}
, {{ $col }} = JSON_MERGE_PATCH({{ $col }}, ${{ add $i 1 }})
{{- else -}}
, {{ $col }} = ${{ add $i 1 -}}
{{- end -}}
{{- end }} WHERE deleted_at IS NULL AND id = ${{ len .Values }};
{{- end }}
{{- define "delete" -}}
UPDATE {{ .Table }} SET deleted_at = NOW() WHERE deleted_at IS NULL AND id = $1;
{{- end }}
`
const postgresqlQueries = `
{{- define "select" -}}
SELECT * FROM {{ .Table }} WHERE deleted_at IS NULL{{ range $i, $col := .Columns }} AND {{ $col }} = ${{ (add $i 1) }}{{ end }} ORDER BY created_at DESC;
{{- end }}
{{- define "insert" -}}
INSERT INTO {{ .Table }} (id, {{ join ", " .Fields }}) VALUES (:id, {{ pjoin ":" ", " .Fields }}) RETURNING created_at, updated_at;
{{- end }}
{{- define "update" -}}
{{- $v := .Values -}}
UPDATE {{ .Table }} SET updated_at = NOW(){{ range $i, $col := (slice .Columns 0 (sub (len .Columns) 1) ) -}}
{{- if isjson (index $v $i) -}}
, {{ $col }} = (CASE WHEN {{ $col }} = 'null'::jsonb THEN '{}'::jsonb ELSE {{ $col }} END) || (CASE WHEN ${{ add $i 1 }} = 'null'::jsonb THEN '{}'::jsonb ELSE ${{ add $i 1 }} END)
{{- else -}}
, {{ $col }} = ${{ add $i 1 -}}
{{- end -}}
{{- end }} WHERE deleted_at IS NULL AND id = ${{ len .Values }} RETURNING updated_at;
{{- end }}
{{- define "delete" -}}
UPDATE {{ .Table }} SET deleted_at = NOW() WHERE deleted_at IS NULL AND id = $1 RETURNING deleted_at;
{{- end }}
`