forked from ido50/sqlz
/
sqlz.go
496 lines (413 loc) · 14.5 KB
/
sqlz.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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
// Package sqlz implements an SQL query builder based on
// github.com/jmoiron/sqlx.
package sqlz
import (
"context"
"database/sql"
"fmt"
"strings"
"github.com/jmoiron/sqlx"
)
// Ext is a union interface which can bind, query, and exec,
// with or without contexts, used by NamedQuery and NamedExec
type Ext interface {
sqlx.Queryer
sqlx.QueryerContext
sqlx.Execer
sqlx.ExecerContext
}
// Queryer is an interface used by Get and Select, with or without context
type Queryer interface {
sqlx.Queryer
sqlx.QueryerContext
}
// DB is a wrapper around sqlx.DB (which is a wrapper around sql.DB)
type DB struct {
*sqlx.DB
ErrHandlers []func(err error)
}
// Tx is a wrapper around sqlx.Tx (which is a wrapper around sql.Tx)
type Tx struct {
*sqlx.Tx
ErrHandlers []func(err error)
}
// SQLStmt is an interface representing a general SQL statement. All
// specific statement types (e.g. SelectStmt, UpdateStmt, etc.)
// implement this interface
type SQLStmt interface {
ToSQL(bool) (string, []interface{})
}
// New creates a new DB instance from an underlying sql.DB object.
// It requires the name of the SQL driver in order to use the correct
// placeholders when generating SQL
func New(db *sql.DB, driverName string, errHandlersFuncs ...func(err error)) *DB {
errHandlers := make([]func(err error), len(errHandlersFuncs), len(errHandlersFuncs))
for i, h := range errHandlersFuncs {
errHandlers[i] = h
}
return &DB{DB: sqlx.NewDb(db, driverName), ErrHandlers: errHandlers}
}
// Newx creates a new DB instance from an underlying sqlx.DB object
func Newx(db *sqlx.DB) *DB {
return &DB{DB: db}
}
// Transactional runs the provided function inside a transaction. The
// function must receive an sqlz Tx object, and return an error. If the
// function returns an error, the transaction is automatically rolled
// back. Otherwise, the transaction is committed.
func (db *DB) Transactional(f func(tx *Tx) error) error {
tx, err := db.Beginx()
if err != nil {
return fmt.Errorf("failed starting transaction: %s", err)
}
err = f(&Tx{Tx: tx, ErrHandlers: db.ErrHandlers})
if err != nil {
tx.Rollback()
return err
}
err = tx.Commit()
if err != nil {
return fmt.Errorf("failed committing transaction: %s", err)
}
return nil
}
// TransactionalContext runs the provided function inside a transaction. The
// function must receive an sqlz Tx object, and return an error. If the
// function returns an error, the transaction is automatically rolled
// back. Otherwise, the transaction is committed.
func (db *DB) TransactionalContext(ctx context.Context, opts *sql.TxOptions, f func(tx *Tx) error) error {
tx, err := db.BeginTxx(ctx, opts)
if err != nil {
return fmt.Errorf("failed starting transaction: %s", err)
}
err = f(&Tx{Tx: tx, ErrHandlers: db.ErrHandlers})
if err != nil {
tx.Rollback()
return err
}
err = tx.Commit()
if err != nil {
return fmt.Errorf("failed committing transaction: %s", err)
}
return nil
}
// WhereCondition is an interface describing conditions
// that can be used inside an SQL WHERE clause. It defines
// the Parse function that generates SQL (with placeholders)
// from the condition(s) and returns a list of data bindings
// for the placeholders (if any)
type WhereCondition interface {
Parse() (asSQL string, bindings []interface{})
}
// SimpleCondition represents the most basic WHERE
// condition, where one left-value (usually a column)
// is compared with a right-value using an operator (e.g.
// "=", "<>", ">=", ...)
type SimpleCondition struct {
Left string
Right interface{}
Operator string
}
// AndOrCondition represents a group of AND or OR
// conditions.
type AndOrCondition struct {
Or bool
Conditions []WhereCondition
}
// PreCondition represents pre-condition operator
type PreCondition struct {
Pre string
Condition WhereCondition
}
// SubqueryCondition is a WHERE condition on the results
// of a sub-query.
type SubqueryCondition struct {
Stmt *SelectStmt
Operator string
}
// SQLCondition represents a condition written directly in
// SQL, allows using complex SQL conditions not yet supported
// by sqlz
type SQLCondition struct {
Condition string
Binds []interface{}
}
// IndirectValue represents a reference to a database name
// (e.g. column, function) that should be used as-is in a
// query rather than replaced with a placeholder.
type IndirectValue struct {
Reference string
Bindings []interface{}
}
// Indirect receives a string and injects it into a query
// as-is rather than with a placeholder. Use this when
// comparing columns, modifying columns based on their (or
// others') existing values, using database functions, etc.
// Never use this with user-supplied input, as this may
// open the door for SQL injections!
func Indirect(value string, bindings ...interface{}) IndirectValue {
return IndirectValue{value, bindings}
}
func (i IndirectValue) ToSQL(_ bool) (string, []interface{}) {
return i.Reference, i.Bindings
}
// And joins multiple where conditions as an AndOrCondition
// (representing AND conditions). You will use this a lot
// less than Or as passing multiple conditions to functions
// like Where or Having are all AND conditions.
func And(conds ...WhereCondition) AndOrCondition {
return AndOrCondition{false, conds}
}
// Or joins multiple where conditions as an AndOrCondition
// (representing OR conditions).
func Or(conds ...WhereCondition) AndOrCondition {
return AndOrCondition{true, conds}
}
// Not represents a pre condition ("NOT" operator)
func Not(cond WhereCondition) PreCondition {
return PreCondition{"NOT", cond}
}
// Eq represents a simple equality condition ("=" operator)
func Eq(col string, value interface{}) SimpleCondition {
return SimpleCondition{col, value, "="}
}
// Ne represents a simple non-equality condition ("<>" operator)
func Ne(col string, value interface{}) SimpleCondition {
return SimpleCondition{col, value, "<>"}
}
// Gt represents a simple greater-than condition (">" operator)
func Gt(col string, value interface{}) SimpleCondition {
return SimpleCondition{col, value, ">"}
}
// Gte represents a simple greater-than-or-equals condition (">=" operator)
func Gte(col string, value interface{}) SimpleCondition {
return SimpleCondition{col, value, ">="}
}
// Lt represents a simple less-than condition ("<" operator)
func Lt(col string, value interface{}) SimpleCondition {
return SimpleCondition{col, value, "<"}
}
// Lte represents a simple less-than-or-equals condition ("<=" operator)
func Lte(col string, value interface{}) SimpleCondition {
return SimpleCondition{col, value, "<="}
}
// Like represents a wildcard equality condition ("LIKE" operator)
func Like(col string, value interface{}) SimpleCondition {
return SimpleCondition{col, value, "LIKE"}
}
// NotLike represents a wildcard non-equality condition ("NOT LIKE" operator)
func NotLike(col string, value interface{}) SimpleCondition {
return SimpleCondition{col, value, "NOT LIKE"}
}
// ILike represents a wildcard equality condition ("ILIKE" operator)
func ILike(col string, value interface{}) SimpleCondition {
return SimpleCondition{col, value, "ILIKE"}
}
// IsNull represents a simple nullity condition ("IS NULL" operator)
func IsNull(col string) SimpleCondition {
return SimpleCondition{col, nil, "IS NULL"}
}
// IsNotNull represents a simple non-nullity condition ("IS NOT NULL" operator)
func IsNotNull(col string) SimpleCondition {
return SimpleCondition{col, nil, "IS NOT NULL"}
}
// Exists creates a sub-query condition checking the sub-query
// returns results ("EXISTS" operator)
func Exists(stmt *SelectStmt) SubqueryCondition {
return SubqueryCondition{stmt, "EXISTS"}
}
// NotExists creates a sub-query condition checking the sub-query
// does not return results ("NOT EXISTS" operator)
func NotExists(stmt *SelectStmt) SubqueryCondition {
return SubqueryCondition{stmt, "NOT EXISTS"}
}
// JSONBOp creates simple conditions with JSONB operators for
// PostgreSQL databases (supported operators are "@>", "<@",
// "?", "?!", "?&", "||", "-" and "#-")
func JSONBOp(op string, left string, value interface{}) SimpleCondition {
switch op {
case "@>", "<@", "?", "?!", "?&", "||", "-", "#-":
return SimpleCondition{left, value, op}
default:
return SimpleCondition{}
}
}
// SQLCond creates an SQL condition, allowing to use complex SQL conditions
// that are not yet supported by sqlz. Question marks must be used for
// placeholders in the condition regardless of the database driver.
func SQLCond(condition string, binds ...interface{}) SQLCondition {
return SQLCondition{condition, binds}
}
// InCondition is a struct representing IN and NOT IN conditions
type InCondition struct {
NotIn bool
Left string
Right []interface{}
}
// In creates an IN condition for matching the value of a column
// against an array of possible values
func In(col string, values ...interface{}) InCondition {
return InCondition{false, col, values}
}
// NotIn creates a NOT IN condition for checking that the value
// of a column is not one of the defined values
func NotIn(col string, values ...interface{}) InCondition {
return InCondition{true, col, values}
}
// ArrayCondition represents an array comparison condition
type ArrayCondition struct {
Left interface{}
Operator string
Type string
Right interface{}
}
// EqAny creates an "= ANY" condition on an array column
func EqAny(arr interface{}, value interface{}) ArrayCondition {
return ArrayCondition{value, "=", "ANY", arr}
}
// NeAny creates an "<> ANY" condition on an array
func NeAny(arr interface{}, value interface{}) ArrayCondition {
return ArrayCondition{value, "<>", "ANY", arr}
}
// LtAny creates an "< ANY" condition on an array
func LtAny(arr interface{}, value interface{}) ArrayCondition {
return ArrayCondition{value, "<", "ANY", arr}
}
// LteAny creates an "<= ANY" condition on an array
func LteAny(arr interface{}, value interface{}) ArrayCondition {
return ArrayCondition{value, "<=", "ANY", arr}
}
// GtAny creates an "> ANY" condition on an array
func GtAny(arr interface{}, value interface{}) ArrayCondition {
return ArrayCondition{value, ">", "ANY", arr}
}
// GteAny creates an ">= ANY" condition on an array
func GteAny(arr interface{}, value interface{}) ArrayCondition {
return ArrayCondition{value, ">=", "ANY", arr}
}
// EqAll creates an "= ALL" condition on an array
func EqAll(arr interface{}, value interface{}) ArrayCondition {
return ArrayCondition{value, "=", "ALL", arr}
}
// NeAll creates an "<> ALL" condition on an array
func NeAll(arr interface{}, value interface{}) ArrayCondition {
return ArrayCondition{value, "<>", "ALL", arr}
}
// LtAll creates an "< ALL" condition on an array
func LtAll(arr interface{}, value interface{}) ArrayCondition {
return ArrayCondition{value, "<", "ALL", arr}
}
// LteAll creates an "<= ALL" condition on an array
func LteAll(arr interface{}, value interface{}) ArrayCondition {
return ArrayCondition{value, "<=", "ALL", arr}
}
// GtAll creates an "> ALL" condition on an array
func GtAll(arr interface{}, value interface{}) ArrayCondition {
return ArrayCondition{value, ">", "ALL", arr}
}
// GteAll creates an ">= ALL" condition on an array
func GteAll(arr interface{}, value interface{}) ArrayCondition {
return ArrayCondition{value, ">=", "ALL", arr}
}
// LikeAny creates an "Like ANY" condition on an array
func LikeAny(arr interface{}, value interface{}) ArrayCondition {
return ArrayCondition{value, "LIKE", "ANY", arr}
}
// Parse implements the WhereCondition interface, generating SQL from
// the condition
func (simple SimpleCondition) Parse() (asSQL string, bindings []interface{}) {
asSQL = simple.Left + " " + simple.Operator
if simple.Right != nil {
placeholder := "?"
if indirect, isIndirect := simple.Right.(IndirectValue); isIndirect {
placeholder = indirect.Reference
bindings = append(bindings, indirect.Bindings...)
} else {
bindings = append(bindings, simple.Right)
}
asSQL += " " + placeholder
}
return asSQL, bindings
}
// Parse implements the WhereCondition interface, generating SQL from
// the condition
func (cond SQLCondition) Parse() (asSQL string, bindings []interface{}) {
return cond.Condition, cond.Binds
}
// Parse implements the WhereCondition interface, generating SQL from
// the condition
func (array ArrayCondition) Parse() (asSQL string, bindings []interface{}) {
var rightAsSQL string
var leftAsSQL string
if indirect, isIndirect := array.Left.(IndirectValue); isIndirect {
leftAsSQL = indirect.Reference
bindings = append(bindings, indirect.Bindings...)
} else {
leftAsSQL = "?"
bindings = append(bindings, array.Left)
}
switch array.Right.(type) {
case string:
rightAsSQL = fmt.Sprintf("%v", array.Right)
default:
rightAsSQL = "?"
bindings = append(bindings, array.Right)
}
asSQL = leftAsSQL + " " + array.Operator + " " + array.Type + "(" + rightAsSQL + ")"
return asSQL, bindings
}
// Parse implements the WhereCondition interface, generating SQL from
// the condition
func (in InCondition) Parse() (asSQL string, bindings []interface{}) {
asSQL = in.Left
if in.NotIn {
asSQL += " NOT"
}
asSQL += " IN ("
var placeholders []string
for _, val := range in.Right {
placeholders = append(placeholders, "?")
bindings = append(bindings, val)
}
asSQL += strings.Join(placeholders, ", ") + ")"
return asSQL, bindings
}
// Parse implements the WhereCondition interface, generating SQL from
// the condition
func (andOr AndOrCondition) Parse() (asSQL string, bindings []interface{}) {
var sqls []string
for _, cond := range andOr.Conditions {
innerSQL, innerBindings := cond.Parse()
sqls = append(sqls, innerSQL)
bindings = append(bindings, innerBindings...)
}
op := " AND "
if andOr.Or {
op = " OR "
}
return "(" + strings.Join(sqls, op) + ")", bindings
}
// Parse implements the WhereCondition interface, generating SQL from
// the condition
func (pre PreCondition) Parse() (asSQL string, bindings []interface{}) {
innerSQL, innerBindings := pre.Condition.Parse()
bindings = append(bindings, innerBindings...)
return pre.Pre +" (" +innerSQL + ")", bindings
}
// Parse implements the WhereCondition interface, generating SQL from
// the condition
func (subCond SubqueryCondition) Parse() (asSQL string, bindings []interface{}) {
asSQL, bindings = subCond.Stmt.ToSQL(false)
return subCond.Operator + " (" + asSQL + ")", bindings
}
func parseConditions(conds []WhereCondition) (asSQL string, bindings []interface{}) {
if len(conds) > 1 {
asSQL, bindings = (AndOrCondition{false, conds}).Parse()
} else if len(conds) == 1 {
asSQL, bindings = conds[0].Parse()
}
if strings.HasPrefix(asSQL, "(") {
asSQL = strings.TrimPrefix(strings.TrimSuffix(asSQL, ")"), "(")
}
return asSQL, bindings
}