-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqb_ops.go
451 lines (421 loc) · 11.4 KB
/
qb_ops.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
package qb
import (
"fmt"
"log"
"strings"
"github.com/lib/pq"
)
func NewQbOps() *QbOps {
q := &QbOps{}
q.SetArgs(map[string]interface{}{})
return q
}
func (q *QbOps) SetArgs(value map[string]interface{}) *QbOps {
q.args = value
return q
}
func (q *QbOps) SetField(fnc func() bool, field string, value interface{}) *QbOps {
if q.args == nil {
q.SetArgs(map[string]interface{}{})
}
if !fnc() {
return q
}
q.args[field] = value
return q
}
func (q *QbOps) AppendField(field string, value interface{}) *QbOps {
q.SetField(func() bool {
return true
}, field, value)
return q
}
func (q *QbOps) GetArgs() map[string]interface{} {
return q.args
}
func (q *QbOps) Json() string {
return JsonString(q.args)
}
// Insert inserts one row with param bindings
func (q *QbDB) Insert(data map[string]any) error {
if len(data) == 0 {
return fmt.Errorf("Data is empty")
}
if q.Txn != nil {
return q.Txn.Insert(data)
}
builder := q.Builder
if IsStringEmpty(builder.table) {
return errTableCallBeforeOp
}
columns, values, bindings := prepareBindings(data)
query := `INSERT INTO "` + builder.table + `" (` + strings.Join(columns, `, `) + `) VALUES(` + strings.Join(bindings, `, `) + `)`
setCacheExecuteStmt(query)
_, err := q.Sql().Exec(query, values...)
if err != nil {
return err
}
return nil
}
// InsertIf inserts one row with param bindings
func (q *QbDB) InsertIf(ops *QbOps) error {
return q.Insert(ops.GetArgs())
}
// Insert inserts one row with param bindings
func (q *QbTxn) Insert(data map[string]any) error {
if len(data) == 0 {
return fmt.Errorf("Data is empty")
}
if q.Tx == nil {
return errTransactionModeWithoutTx
}
builder := q.Builder
if IsStringEmpty(builder.table) {
return errTableCallBeforeOp
}
columns, values, bindings := prepareBindings(data)
query := `INSERT INTO "` + builder.table + `" (` + strings.Join(columns, `, `) + `) VALUES(` + strings.Join(bindings, `, `) + `)`
setCacheExecuteStmt(query)
_, err := q.Tx.Exec(query, values...)
if err != nil {
return err
}
return nil
}
// InsertIf inserts one row with param bindings
func (q *QbTxn) InsertIf(ops *QbOps) error {
return q.Insert(ops.GetArgs())
}
// InsertGetId inserts one row with param bindings and returning id
func (q *QbDB) InsertGetId(data map[string]any) (uint64, error) {
if len(data) == 0 {
return 0, fmt.Errorf("Data is empty")
}
if q.Txn != nil {
return q.Txn.InsertGetId(data)
}
builder := q.Builder
if IsStringEmpty(builder.table) {
return 0, errTableCallBeforeOp
}
columns, values, bindings := prepareBindings(data)
query := `INSERT INTO "` + builder.table + `" (` + strings.Join(columns, `, `) + `) VALUES(` + strings.Join(bindings, `, `) + `) RETURNING id`
setCacheExecuteStmt(query)
var id uint64
err := q.Sql().QueryRow(query, values...).Scan(&id)
if err != nil {
return 0, err
}
return id, nil
}
// InsertGetIdIf inserts one row with param bindings and returning id
func (q *QbDB) InsertGetIdIf(ops *QbOps) (uint64, error) {
return q.InsertGetId(ops.GetArgs())
}
// InsertGetId inserts one row with param bindings and returning id
func (q *QbTxn) InsertGetId(data map[string]any) (uint64, error) {
if len(data) == 0 {
return 0, fmt.Errorf("Data is empty")
}
if q.Tx == nil {
return 0, errTransactionModeWithoutTx
}
builder := q.Builder
if IsStringEmpty(builder.table) {
return 0, errTableCallBeforeOp
}
columns, values, bindings := prepareBindings(data)
query := `INSERT INTO "` + builder.table + `" (` + strings.Join(columns, `, `) + `) VALUES(` + strings.Join(bindings, `, `) + `) RETURNING id`
setCacheExecuteStmt(query)
var id uint64
err := q.Tx.QueryRow(query, values...).Scan(&id)
if err != nil {
return 0, err
}
return id, nil
}
// InsertGetIdIf inserts one row with param bindings and returning id
func (q *QbTxn) InsertGetIdIf(ops *QbOps) (uint64, error) {
return q.InsertGetId(ops.GetArgs())
}
// InsertBatch inserts multiple rows based on transaction
func (q *QbDB) InsertBatch(data []map[string]any) error {
if len(data) == 0 {
return fmt.Errorf("Data is empty")
}
builder := q.Builder
if IsStringEmpty(builder.table) {
return errTableCallBeforeOp
}
txn, err := q.Sql().Begin()
if err != nil {
log.Fatal(err)
}
columns, values := prepareInsertBatch(data)
stmt, err := txn.Prepare(pq.CopyIn(builder.table, columns...))
if err != nil {
return err
}
for _, value := range values {
_, err = stmt.Exec(value...)
if err != nil {
return err
}
}
_, err = stmt.Exec()
if err != nil {
return err
}
err = stmt.Close()
if err != nil {
return err
}
err = txn.Commit()
if err != nil {
return err
}
return nil
}
// InsertBatchIf inserts multiple rows based on transaction
func (q *QbDB) InsertBatchIf(ops ...*QbOps) error {
data := []map[string]interface{}{}
for _, v := range ops {
data = append(data, v.GetArgs())
}
return q.InsertBatch(data)
}
// Update builds an UPDATE sql stmt with corresponding where/from clauses if stated
// returning affected rows
func (q *QbDB) Update(data map[string]any) (int64, error) {
if len(data) == 0 {
return 0, fmt.Errorf("Data is empty")
}
if q.Txn != nil {
return q.Txn.Update(data)
}
builder := q.Builder
if IsStringEmpty(builder.table) {
return 0, errTableCallBeforeOp
}
columns, values, bindings := prepareBindings(data)
setVal := ""
l := len(columns)
for k, col := range columns {
setVal += fmt.Sprintf("%s%s%s", col, " = ", bindings[k])
if k < l-1 {
setVal += ", "
}
}
query := `UPDATE "` + q.Builder.table + `" SET ` + setVal
if IsStringNotEmpty(q.Builder.from) {
query += fmt.Sprintf("%s%s", " FROM ", q.Builder.from)
}
q.Builder.startBindingsAt = l + 1
query += q.Builder.buildClauses()
values = append(values, prepareValues(q.Builder.whereBindings)...)
setCacheExecuteStmt(query)
result, err := q.Sql().Exec(query, values...)
if err != nil {
return 0, err
}
return result.RowsAffected()
}
// UpdateIf builds an UPDATE sql stmt with corresponding where/from clauses if stated
// returning affected rows
func (q *QbDB) UpdateIf(ops *QbOps) (int64, error) {
return q.Update(ops.GetArgs())
}
// Update builds an UPDATE sql stmt with corresponding where/from clauses if stated
// returning affected rows
func (q *QbTxn) Update(data map[string]any) (int64, error) {
if len(data) == 0 {
return 0, fmt.Errorf("Data is empty")
}
if q.Tx == nil {
return 0, errTransactionModeWithoutTx
}
builder := q.Builder
if IsStringEmpty(builder.table) {
return 0, errTableCallBeforeOp
}
columns, values, bindings := prepareBindings(data)
setVal := ""
l := len(columns)
for k, col := range columns {
setVal += fmt.Sprintf("%s%s%s", col, " = ", bindings[k])
if k < l-1 {
setVal += ", "
}
}
query := `UPDATE "` + q.Builder.table + `" SET ` + setVal
if IsStringNotEmpty(q.Builder.from) {
query += fmt.Sprintf("%s%s", " FROM ", q.Builder.from)
}
q.Builder.startBindingsAt = l + 1
query += q.Builder.buildClauses()
values = append(values, prepareValues(q.Builder.whereBindings)...)
setCacheExecuteStmt(query)
result, err := q.Tx.Exec(query, values...)
if err != nil {
return 0, err
}
return result.RowsAffected()
}
// UpdateIf builds an UPDATE sql stmt with corresponding where/from clauses if stated
// returning affected rows
func (q *QbTxn) UpdateIf(ops *QbOps) (int64, error) {
return q.Update(ops.GetArgs())
}
// Replace inserts data if conflicting row hasn't been found, else it will update an existing one
func (q *QbDB) Replace(data map[string]any, conflict string) (int64, error) {
if len(data) == 0 {
return 0, fmt.Errorf("Data is empty")
}
if q.Txn != nil {
return q.Txn.Replace(data, conflict)
}
builder := q.Builder
if IsStringEmpty(builder.table) {
return 0, errTableCallBeforeOp
}
columns, values, bindings := prepareBindings(data)
query := `INSERT INTO "` + builder.table + `" (` + strings.Join(columns, `, `) + `) VALUES(` + strings.Join(bindings, `, `) + `) ON CONFLICT(` + conflict + `) DO UPDATE SET `
for i, v := range columns {
// columns[i] = v + " = excluded." + v
columns[i] = fmt.Sprintf("%s%s%s", v, " = excluded.", v)
}
query += strings.Join(columns, ", ")
setCacheExecuteStmt(query)
result, err := q.Sql().Exec(query, values...)
if err != nil {
return 0, err
}
return result.RowsAffected()
}
// Replace inserts data if conflicting row hasn't been found, else it will update an existing one
func (q *QbDB) ReplaceIf(ops *QbOps, conflict string) (int64, error) {
return q.Replace(ops.GetArgs(), conflict)
}
// Replace inserts data if conflicting row hasn't been found, else it will update an existing one
func (q *QbTxn) Replace(data map[string]any, conflict string) (int64, error) {
if len(data) == 0 {
return 0, fmt.Errorf("Data is empty")
}
if q.Tx == nil {
return 0, errTransactionModeWithoutTx
}
builder := q.Builder
if IsStringEmpty(builder.table) {
return 0, errTableCallBeforeOp
}
columns, values, bindings := prepareBindings(data)
query := `INSERT INTO "` + builder.table + `" (` + strings.Join(columns, `, `) + `) VALUES(` + strings.Join(bindings, `, `) + `) ON CONFLICT(` + conflict + `) DO UPDATE SET `
for i, v := range columns {
// columns[i] = v + " = excluded." + v
columns[i] = fmt.Sprintf("%s%s%s", v, " = excluded.", v)
}
query += strings.Join(columns, ", ")
setCacheExecuteStmt(query)
result, err := q.Tx.Exec(query, values...)
if err != nil {
return 0, err
}
return result.RowsAffected()
}
func (q *QbTxn) ReplaceIf(ops *QbOps, conflict string) (int64, error) {
return q.Replace(ops.GetArgs(), conflict)
}
// Delete builds a DELETE stmt with corresponding where clause if stated
// returning affected rows
func (q *QbDB) Delete() (int64, error) {
if q.Txn != nil {
return q.Txn.Delete()
}
builder := q.Builder
if IsStringEmpty(builder.table) {
return 0, errTableCallBeforeOp
}
query := `DELETE FROM "` + q.Builder.table + `"`
query += q.Builder.buildClauses()
setCacheExecuteStmt(query)
result, err := q.Sql().Exec(query, prepareValues(q.Builder.whereBindings)...)
if err != nil {
return 0, err
}
return result.RowsAffected()
}
// Delete builds a DELETE stmt with corresponding where clause if stated
// returning affected rows
func (q *QbTxn) Delete() (int64, error) {
if q.Tx == nil {
return 0, errTransactionModeWithoutTx
}
builder := q.Builder
if IsStringEmpty(builder.table) {
return 0, errTableCallBeforeOp
}
query := `DELETE FROM "` + q.Builder.table + `"`
query += q.Builder.buildClauses()
setCacheExecuteStmt(query)
result, err := q.Tx.Exec(query, prepareValues(q.Builder.whereBindings)...)
if err != nil {
return 0, err
}
return result.RowsAffected()
}
// InTransaction executes fn passed as an argument in transaction mode
// if there are no results returned - txn will be rolled back, otherwise committed and returned
func (q *QbDB) InTransaction(fn func() (any, error)) error {
txn, err := q.Sql().Begin()
if err != nil {
return err
}
// assign transaction and builder to Txn entity
q.Txn = &QbTxn{
Tx: txn,
Builder: q.Builder,
}
defer func() {
// clear Txn object after commit
q.Txn = nil
}()
result, err := fn()
if err != nil {
errTxn := txn.Rollback()
if errTxn != nil {
return errTxn
}
return err
}
isOk := false
switch v := result.(type) {
case int:
if v > 0 {
isOk = true
}
case int64:
if v > 0 {
isOk = true
}
case uint64:
if v > 0 {
isOk = true
}
case []map[string]any:
if len(v) > 0 {
isOk = true
}
case map[string]any:
if len(v) > 0 {
isOk = true
}
}
if !isOk {
return txn.Rollback()
}
err = txn.Commit()
if err != nil {
return err
}
return nil
}