-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
expr.go
443 lines (383 loc) · 9.01 KB
/
expr.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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
package pgq
import (
"bytes"
"fmt"
"reflect"
"sort"
"strings"
"time"
)
const (
// PostgreSQL true/false literals.
sqlTrue = "(TRUE)"
sqlFalse = "(FALSE)"
)
type expr struct {
sql string
args []any
}
// Expr builds an expression from a SQL fragment and arguments.
//
// Ex:
//
// Expr("FROM_UNIXTIME(?)", t)
func Expr(sql string, args ...any) SQLizer {
return expr{sql: sql, args: args}
}
func (e expr) SQL() (sql string, args []any, err error) {
simple := true
for _, arg := range e.args {
if _, ok := arg.(SQLizer); ok {
simple = false
}
}
if simple {
return e.sql, e.args, nil
}
buf := &bytes.Buffer{}
ap := e.args
sp := e.sql
var isql string
var iargs []any
for err == nil && len(ap) > 0 && sp != "" {
i := strings.Index(sp, "?")
if i < 0 {
// no more placeholders
break
}
if len(sp) > i+1 && sp[i+1:i+2] == "?" {
// escaped "??"; append it and step past
buf.WriteString(sp[:i+2])
sp = sp[i+2:]
continue
}
if as, ok := ap[0].(SQLizer); ok {
// sqlizer argument; expand it and append the result
isql, iargs, err = as.SQL()
buf.WriteString(sp[:i])
buf.WriteString(isql)
args = append(args, iargs...)
} else {
// normal argument; append it and the placeholder
buf.WriteString(sp[:i+1])
args = append(args, ap[0])
}
// step past the argument and placeholder
ap = ap[1:]
sp = sp[i+1:]
}
// append the remaining sql and arguments
buf.WriteString(sp)
return buf.String(), append(args, ap...), err
}
// ConcatSQL builds a SQL of an expression by concatenating strings and other expressions.
//
// Ex:
//
// name_expr := Expr("CONCAT(?, ' ', ?)", firstName, lastName)
// ConcatSQL("COALESCE(full_name,", name_expr, ")")
func ConcatSQL(ce ...any) (sql string, args []any, err error) {
for _, part := range ce {
switch p := part.(type) {
case string:
sql += p
case SQLizer:
pSQL, pArgs, err := p.SQL()
if err != nil {
return "", nil, err
}
sql += pSQL
args = append(args, pArgs...)
default:
return "", nil, fmt.Errorf("%#v is not a string or SQLizer", part)
}
}
return
}
// Alias allows to define alias for column in SelectBuilder. Useful when column is
// defined as complex expression like IF or CASE
// Ex:
//
// .Column(Alias{Expr: caseStmt, Alias: "case_column"})
type Alias struct {
Expr SQLizer
As string
}
// AliasExprSQL returns a SQL query based on the alias.
func (a Alias) SQL() (sql string, args []any, err error) {
sql, args, err = a.Expr.SQL()
if err == nil {
sql = fmt.Sprintf("(%s) AS %s", sql, a.As)
}
return
}
// Eq is syntactic sugar for use with Where/Having/Set methods.
type Eq map[string]any
func (eq Eq) toSQL(useNotOpr bool) (sql string, args []any, err error) {
if len(eq) == 0 {
// Empty SQL{} evaluates to true.
sql = sqlTrue
return
}
var (
exprs []string
equalOpr = "="
nullOpr = "IS"
inEmptyExpr = sqlFalse
inOpr = "ANY"
)
if useNotOpr {
equalOpr = "<>"
nullOpr = "IS NOT"
inEmptyExpr = sqlTrue
inOpr = "ALL"
}
sortedKeys := getSortedKeys(eq)
for _, key := range sortedKeys {
var expr string
val := eq[key]
switch v := val.(type) {
case Valuer:
if val, err = v.Value(); err != nil {
return
}
}
r := reflect.ValueOf(val)
if r.Kind() == reflect.Ptr {
if r.IsNil() {
val = nil
} else {
val = r.Elem().Interface()
}
}
if val == nil {
expr = fmt.Sprintf("%s %s NULL", key, nullOpr)
} else {
if isListType(val) {
valVal := reflect.ValueOf(val)
if valVal.Len() == 0 {
expr = inEmptyExpr
if args == nil {
args = []any{}
}
} else {
expr = fmt.Sprintf("%s %s %s (?)", key, equalOpr, inOpr)
args = append(args, val)
}
} else {
expr = fmt.Sprintf("%s %s ?", key, equalOpr)
args = append(args, val)
}
}
exprs = append(exprs, expr)
}
sql = strings.Join(exprs, " AND ")
return
}
func (eq Eq) SQL() (sql string, args []any, err error) {
return eq.toSQL(false)
}
// NotEq is syntactic sugar for use with Where/Having/Set methods.
// Ex:
//
// .Where(NotEq{"id": 1}) == "id <> 1"
type NotEq Eq
func (neq NotEq) SQL() (sql string, args []any, err error) {
return Eq(neq).toSQL(true)
}
// Like is syntactic sugar for use with LIKE conditions.
// Ex:
//
// .Where(Like{"name": "%irrel"})
type Like map[string]any
func (lk Like) toSQL(opr string) (sql string, args []any, err error) {
var exprs []string
for key, val := range lk {
expr := ""
switch v := val.(type) {
case Valuer:
if val, err = v.Value(); err != nil {
return
}
}
if val == nil {
err = fmt.Errorf("cannot use null with like operators")
return
} else {
if isListType(val) {
err = fmt.Errorf("cannot use array or slice with like operators")
return
} else {
expr = fmt.Sprintf("%s %s ?", key, opr)
args = append(args, val)
}
}
exprs = append(exprs, expr)
}
sql = strings.Join(exprs, " AND ")
return
}
func (lk Like) SQL() (sql string, args []any, err error) {
return lk.toSQL("LIKE")
}
// NotLike is syntactic sugar for use with LIKE conditions.
// Ex:
//
// .Where(NotLike{"name": "%irrel"})
type NotLike Like
func (nlk NotLike) SQL() (sql string, args []any, err error) {
return Like(nlk).toSQL("NOT LIKE")
}
// ILike is syntactic sugar for use with ILIKE conditions.
// Ex:
//
// .Where(ILike{"name": "sq%"})
type ILike Like
func (ilk ILike) SQL() (sql string, args []any, err error) {
return Like(ilk).toSQL("ILIKE")
}
// NotILike is syntactic sugar for use with ILIKE conditions.
// Ex:
//
// .Where(NotILike{"name": "sq%"})
type NotILike Like
func (nilk NotILike) SQL() (sql string, args []any, err error) {
return Like(nilk).toSQL("NOT ILIKE")
}
// Lt is syntactic sugar for use with Where/Having/Set methods.
// Ex:
//
// .Where(Lt{"id": 1})
type Lt map[string]any
func (lt Lt) toSQL(opposite, orEq bool) (sql string, args []any, err error) {
var (
exprs []string
opr = "<"
)
if opposite {
opr = ">"
}
if orEq {
opr = fmt.Sprintf("%s%s", opr, "=")
}
sortedKeys := getSortedKeys(lt)
for _, key := range sortedKeys {
var expr string
val := lt[key]
switch v := val.(type) {
case Valuer:
if val, err = v.Value(); err != nil {
return
}
}
if val == nil {
err = fmt.Errorf("cannot use null with less than or greater than operators")
return
}
if isListType(val) {
err = fmt.Errorf("cannot use array or slice with less than or greater than operators")
return
}
expr = fmt.Sprintf("%s %s ?", key, opr)
args = append(args, val)
exprs = append(exprs, expr)
}
sql = strings.Join(exprs, " AND ")
return
}
func (lt Lt) SQL() (sql string, args []any, err error) {
return lt.toSQL(false, false)
}
// LtOrEq is syntactic sugar for use with Where/Having/Set methods.
// Ex:
//
// .Where(LtOrEq{"id": 1}) == "id <= 1"
type LtOrEq Lt
func (ltOrEq LtOrEq) SQL() (sql string, args []any, err error) {
return Lt(ltOrEq).toSQL(false, true)
}
// Gt is syntactic sugar for use with Where/Having/Set methods.
// Ex:
//
// .Where(Gt{"id": 1}) == "id > 1"
type Gt Lt
func (gt Gt) SQL() (sql string, args []any, err error) {
return Lt(gt).toSQL(true, false)
}
// GtOrEq is syntactic sugar for use with Where/Having/Set methods.
// Ex:
//
// .Where(GtOrEq{"id": 1}) == "id >= 1"
type GtOrEq Lt
func (gtOrEq GtOrEq) SQL() (sql string, args []any, err error) {
return Lt(gtOrEq).toSQL(true, true)
}
func join(c []SQLizer, sep, defaultExpr string) (sql string, args []any, err error) {
if len(c) == 0 {
return defaultExpr, []any{}, nil
}
var sqlParts []string
for _, sqlizer := range c {
partSQL, partArgs, err := nestedSQL(sqlizer)
if err != nil {
return "", nil, err
}
if partSQL != "" {
sqlParts = append(sqlParts, partSQL)
args = append(args, partArgs...)
}
}
if len(sqlParts) > 0 {
sql = fmt.Sprintf("(%s)", strings.Join(sqlParts, sep))
}
return
}
// And conjunction SQLizers
type And []SQLizer
func (a And) SQL() (string, []any, error) {
return join(a, " AND ", sqlTrue)
}
// Or conjunction SQLizers
type Or []SQLizer
func (o Or) SQL() (string, []any, error) {
return join(o, " OR ", sqlFalse)
}
func getSortedKeys(exp map[string]any) []string {
sortedKeys := make([]string, 0, len(exp))
for k := range exp {
sortedKeys = append(sortedKeys, k)
}
sort.Strings(sortedKeys)
return sortedKeys
}
func isListType(val any) bool {
if isValue(val) {
return false
}
valVal := reflect.ValueOf(val)
return valVal.Kind() == reflect.Array || valVal.Kind() == reflect.Slice
}
// Valuer is the interface providing the Value method.
//
// Types implementing Valuer interface are able to convert
// themselves to a driver Value.
//
// Similar to database/sql/driver.Value, but returns any instead of driver.Value.
type Valuer interface {
// Value returns a driver Value.
// Value must not panic.
Value() (any, error)
}
// isValue reports whether v is a valid Value parameter type.
//
// Similar to database/sql/driver.IsValue, but doesn't accept driver.decimalDecompose.
func isValue(v any) bool {
if v == nil {
return true
}
switch v.(type) {
case []byte, bool, float64, int64, string, time.Time:
return true
}
return false
}