-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathfactory.go
942 lines (779 loc) · 21.1 KB
/
factory.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
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
package buildsqlx
import (
"database/sql"
"errors"
"fmt"
"log"
"reflect"
"strconv"
"strings"
"github.com/fatih/structs"
"github.com/lib/pq"
"golang.org/x/text/cases"
"golang.org/x/text/language"
)
const (
plusSign = "+"
minusSign = "-"
)
var (
// Custom errors
errTableCallBeforeOp = fmt.Errorf("sql: there was no Table() call with table name set")
errTransactionModeWithoutTx = fmt.Errorf("sql: there was no *sql.Tx object set properly")
)
type EachToStructFunc func(rows *sql.Rows) error
// ScanStruct scans query into specific struct
func (r *DB) ScanStruct(src any) error {
if reflect.ValueOf(src).IsNil() {
return fmt.Errorf("cannot decode into nil type %T", src)
}
sqlBuilder := r.Builder
if sqlBuilder.table == "" {
return errTableCallBeforeOp
}
sqlBuilder.limit = 1
query := ""
if len(sqlBuilder.union) > 0 { // got union - need different logic to glue
for _, uBuilder := range sqlBuilder.union {
query += uBuilder + " UNION "
if sqlBuilder.isUnionAll {
query += "ALL "
}
}
query += sqlBuilder.buildSelect()
// clean union (all) after ensuring selects are built
r.Builder.union = []string{}
r.Builder.isUnionAll = false
} else { // std builder
query = sqlBuilder.buildSelect()
}
rows, err := r.Sql().Query(query, prepareValues(r.Builder.whereBindings)...)
if err != nil {
return err
}
columns, _ := rows.Columns()
count := len(columns)
values := make([]any, count)
valuePtrs := make([]any, count)
// resource is the actual value that ptr points to.
resource := reflect.ValueOf(src).Elem()
if err = validateFields(resource, src, columns); err != nil {
return err
}
for rows.Next() {
for i := range columns {
valuePtrs[i] = &values[i]
}
err = rows.Scan(valuePtrs...)
if err != nil {
return err
}
for i, col := range columns {
val := values[i]
setResourceValue(resource, src, cases.Title(language.English).String(col), val)
}
src = resource
}
return nil
}
// EachToStruct scans query into specific struct per row with iterative behaviour
func (r *DB) EachToStruct(fn EachToStructFunc) error {
sqlBuilder := r.Builder
if sqlBuilder.table == "" {
return errTableCallBeforeOp
}
query := ""
if len(sqlBuilder.union) > 0 { // got union - need different logic to glue
for _, uBuilder := range sqlBuilder.union {
query += uBuilder + " UNION "
if sqlBuilder.isUnionAll {
query += "ALL "
}
}
query += sqlBuilder.buildSelect()
// clean union (all) after ensuring selects are built
r.Builder.union = []string{}
r.Builder.isUnionAll = false
} else { // std builder
query = sqlBuilder.buildSelect()
}
rows, err := r.Sql().Query(query, prepareValues(r.Builder.whereBindings)...)
if err != nil {
return err
}
for {
err = fn(rows)
if errors.Is(err, ErrNoMoreRows) {
return nil
}
if err != nil {
return err
}
}
}
// ErrNoMoreRows is returned by Next when there were no more rows
var ErrNoMoreRows = errors.New("sql: no more rows")
// Next will parse the next row into a struct passed as src parameter.
// Returns ErrNoMoreRows if there are no more row to parse
func (r *DB) Next(rows *sql.Rows, src any) error {
if reflect.ValueOf(src).IsNil() {
return fmt.Errorf("cannot decode into nil type %T", src)
}
columns, err := rows.Columns()
if err != nil {
return err
}
count := len(columns)
// resource is the actual value that ptr points to.
resource := reflect.ValueOf(src).Elem()
if err = validateFields(resource, src, columns); err != nil {
return err
}
values := make([]any, count)
valuePtrs := make([]any, count)
if rows.Next() {
for i := range columns {
valuePtrs[i] = &values[i]
}
err = rows.Scan(valuePtrs...)
if err != nil {
return err
}
for i, col := range columns {
val := values[i]
setResourceValue(resource, src, cases.Title(language.English).String(col), val)
}
src = resource
return nil
}
return ErrNoMoreRows
}
func setResourceValue(resource reflect.Value, src any, col string, value any) {
upperCaseFieldName := cases.Upper(language.English).String(col)
if !resource.FieldByName(col).IsValid() && !resource.FieldByName(upperCaseFieldName).IsValid() { // try to get field by db: tag
fields := structs.Fields(src)
for i, f := range fields {
tag := f.Tag("db")
if tag == strings.ToLower(col) {
setValue(resource.Field(i), value)
return
}
}
}
colName := col
if resource.FieldByName(upperCaseFieldName).IsValid() {
colName = upperCaseFieldName
}
setValue(resource.FieldByName(colName), value)
}
func setValue(field reflect.Value, val any) {
if field.Kind() == reflect.Ptr {
newVal := reflect.New(field.Type().Elem())
if val != nil {
newVal.Elem().Set(reflect.ValueOf(val))
}
field.Set(newVal)
return
}
switch v := val.(type) {
case string:
field.SetString(v)
case int:
field.SetInt(int64(v))
case int64:
field.SetInt(v)
case float64:
field.SetFloat(v)
case uint64:
field.SetUint(v)
case nil:
field.SetPointer(nil)
}
if reflect.TypeOf(val).Kind() == reflect.Ptr {
setValue(field, reflect.ValueOf(val).Elem().Interface())
}
}
func validateFields(resource reflect.Value, src any, columns []string) error {
for _, col := range columns {
foundColByTag := false
// standard fields parse
fieldName := cases.Title(language.English).String(col)
// uppercase letters fields parse e.g.: ID, URL etc
upperCaseFieldName := cases.Upper(language.English).String(col)
if !resource.FieldByName(fieldName).IsValid() && !resource.FieldByName(upperCaseFieldName).IsValid() {
fields := structs.Fields(src)
for _, f := range fields {
tag := f.Tag("db")
if tag == col {
foundColByTag = true
break
}
}
if !foundColByTag {
return fmt.Errorf("field '%s' not found in struct", fieldName)
}
}
}
return nil
}
func prepareValues(values []map[string]any) []any {
var vls []any
for _, v := range values {
_, vals, _ := prepareBindings(v)
vls = append(vls, vals...)
}
return vls
}
// buildSelect constructs a query for select statement
func (r *builder) buildSelect() string {
query := `SELECT ` + strings.Join(r.columns, `, `) + ` FROM "` + r.table + `"`
return query + r.buildClauses()
}
// builds query string clauses
func (r *builder) buildClauses() string {
clauses := ""
for _, j := range r.join {
clauses += j
}
// build where clause
if len(r.whereBindings) > 0 {
clauses += composeWhere(r.whereBindings, r.startBindingsAt)
} else { // std without bindings todo: change all to bindings
clauses += r.where
}
if r.groupBy != "" {
clauses += " GROUP BY " + r.groupBy
}
if r.having != "" {
clauses += " HAVING " + r.having
}
clauses += composeOrderBy(r.orderBy, r.orderByRaw)
if r.limit > 0 {
clauses += " LIMIT " + strconv.FormatInt(r.limit, 10)
}
if r.offset > 0 {
clauses += " OFFSET " + strconv.FormatInt(r.offset, 10)
}
if r.lockForUpdate != nil {
clauses += *r.lockForUpdate
}
return clauses
}
// composes WHERE clause string for particular query stmt
func composeWhere(whereBindings []map[string]any, startedAt int) string {
where := " WHERE "
i := startedAt
for _, m := range whereBindings {
for k, v := range m {
// operand >= $i
switch vi := v.(type) {
case []any:
placeholders := make([]string, 0, len(vi))
for range vi {
placeholders = append(placeholders, "$"+strconv.Itoa(i))
i++
}
where += k + " (" + strings.Join(placeholders, ", ") + ")"
default:
if strings.Contains(k, sqlOperatorIs) || strings.Contains(k, sqlOperatorBetween) {
where += k + " " + vi.(string)
break
}
where += k + " $" + strconv.Itoa(i)
i++
}
}
}
return where
}
// composers ORDER BY clause string for particular query stmt
func composeOrderBy(orderBy []map[string]string, orderByRaw *string) string {
if len(orderBy) > 0 {
orderStr := ""
for _, m := range orderBy {
for field, direct := range m {
if orderStr == "" {
orderStr = " ORDER BY " + field + " " + direct
} else {
orderStr += ", " + field + " " + direct
}
}
}
return orderStr
} else if orderByRaw != nil {
return " ORDER BY " + *orderByRaw
}
return ""
}
// Insert inserts one row with param bindings for struct
func (r *DB) Insert(data any) error {
if r.Txn != nil {
return r.Txn.Insert(data)
}
bldr := r.Builder
if bldr.table == "" {
return errTableCallBeforeOp
}
columns, values, bindings := prepareBindingsForStruct(data)
query := `INSERT INTO "` + bldr.table + `" (` + strings.Join(columns, `, `) + `) VALUES(` + strings.Join(bindings, `, `) + `)`
_, err := r.Sql().Exec(query, values...)
if err != nil {
return err
}
return nil
}
// Insert inserts one row with param bindings from struct
// in transaction context
func (r *Txn) Insert(data any) error {
if r.Tx == nil {
return errTransactionModeWithoutTx
}
bldr := r.Builder
if bldr.table == "" {
return errTableCallBeforeOp
}
columns, values, bindings := prepareBindingsForStruct(data)
query := `INSERT INTO "` + bldr.table + `" (` + strings.Join(columns, `, `) + `) VALUES(` + strings.Join(bindings, `, `) + `)`
_, err := r.Tx.Exec(query, values...)
if err != nil {
return err
}
return nil
}
// InsertGetId inserts one row with param bindings and returning id
func (r *DB) InsertGetId(data any) (uint64, error) {
if r.Txn != nil {
return r.Txn.InsertGetId(data)
}
bldr := r.Builder
if bldr.table == "" {
return 0, errTableCallBeforeOp
}
columns, values, bindings := prepareBindingsForStruct(data)
query := `INSERT INTO "` + bldr.table + `" (` + strings.Join(columns, `, `) + `) VALUES(` + strings.Join(bindings, `, `) + `) RETURNING id`
var id uint64
err := r.Sql().QueryRow(query, values...).Scan(&id)
if err != nil {
return 0, err
}
return id, nil
}
// InsertGetId inserts one row with param bindings and returning id
// in transaction context
func (r *Txn) InsertGetId(data any) (uint64, error) {
if r.Tx == nil {
return 0, errTransactionModeWithoutTx
}
bldr := r.Builder
if bldr.table == "" {
return 0, errTableCallBeforeOp
}
columns, values, bindings := prepareBindingsForStruct(data)
query := `INSERT INTO "` + bldr.table + `" (` + strings.Join(columns, `, `) + `) VALUES(` + strings.Join(bindings, `, `) + `) RETURNING id`
var id uint64
err := r.Tx.QueryRow(query, values...).Scan(&id)
if err != nil {
return 0, err
}
return id, nil
}
func prepareValuesForStruct(value reflect.Value) []any {
var values []any
switch value.Kind() {
case reflect.String:
values = append(values, value.String())
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
values = append(values, strconv.FormatInt(value.Int(), 10))
case reflect.Float32, reflect.Float64:
values = append(values, fmt.Sprintf("%g", value.Float()))
case reflect.Ptr:
if value.IsNil() {
values = append(values, nil)
} else {
values = prepareValuesForStruct(value.Elem())
}
}
return values
}
func prepareValue(value any) []any {
var values []any
switch v := value.(type) {
case string:
values = append(values, v)
case int:
values = append(values, strconv.FormatInt(int64(v), 10))
case float64:
values = append(values, fmt.Sprintf("%g", v))
case int64:
values = append(values, strconv.FormatInt(v, 10))
case uint64:
values = append(values, strconv.FormatUint(v, 10))
case []any:
for _, vi := range v {
values = append(values, prepareValue(vi)...)
}
case nil:
values = append(values, nil)
}
return values
}
// prepareBindings prepares slices to split in favor of INSERT sql statement
func prepareBindings(data map[string]any) (columns []string, values []any, bindings []string) {
i := 1
for column, value := range data {
if strings.Contains(column, sqlOperatorIs) || strings.Contains(column, sqlOperatorBetween) {
continue
}
columns = append(columns, column)
pValues := prepareValue(value)
if len(pValues) > 0 {
values = append(values, pValues...)
for range pValues {
bindings = append(bindings, "$"+strconv.FormatInt(int64(i), 10))
i++
}
}
}
return
}
// prepareBindingsForStruct prepares all bindings for SQL-query
func prepareBindingsForStruct(data any) (columns []string, values []any, bindings []string) {
j := 1
resource := reflect.ValueOf(data)
t := reflect.TypeOf(data)
for i := 0; i < t.NumField(); i++ {
value := resource.Field(i)
col := getColumn(t.Field(i))
if strings.Contains(col, sqlOperatorIs) || strings.Contains(col, sqlOperatorBetween) {
continue
}
columns = append(columns, col)
pValues := prepareValuesForStruct(value)
if len(pValues) > 0 {
values = append(values, pValues...)
for range pValues {
bindings = append(bindings, "$"+strconv.FormatInt(int64(j), 10))
j++
}
}
}
return
}
// getColumn gets column name and value
func getColumn(structField reflect.StructField) string {
col := strings.ToLower(structField.Name)
if structField.Tag.Get("db") != "" {
col = structField.Tag.Get("db")
}
return col
}
func getFieldValue(src any, col string) any {
fieldTitleName := cases.Title(language.English).String(col)
fieldUpperName := cases.Upper(language.English).String(col)
resource := reflect.ValueOf(src)
if resource.FieldByName(fieldTitleName).IsValid() {
return resource.FieldByName(fieldTitleName).Interface()
}
if !resource.FieldByName(fieldUpperName).IsValid() {
return resource.FieldByName(fieldUpperName).Interface()
}
resourceType := reflect.TypeOf(src)
for i := 0; i < resourceType.NumField(); i++ {
f := resourceType.Field(i)
if f.Tag.Get("db") == col {
return resource.Field(i).Interface()
}
}
return nil
}
// InsertBatch inserts multiple rows based on transaction
func (r *DB) InsertBatch(data any) error {
bldr := r.Builder
if bldr.table == "" {
return errTableCallBeforeOp
}
txn, err := r.Sql().Begin()
if err != nil {
log.Fatal(err)
}
iSlice := anySlice(data)
columns, values := prepareInsertBatchForStructs(iSlice)
stmt, err := txn.Prepare(pq.CopyIn(bldr.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
}
// prepareInsertBatchForStructs prepares the column names and values for inserting multiple structs into a database table.
//
// It takes in a slice of any structs called data and returns two slices: columns and values.
// The columns slice contains the column names, while the values slice contains the corresponding values for each struct.
func prepareInsertBatchForStructs[T any](data []T) (columns []string, values [][]interface{}) {
values = make([][]interface{}, len(data))
colToIdx := make(map[string]int)
i := 0
for k, v := range data {
values[k] = make([]interface{}, 0)
structValue := reflect.ValueOf(v)
structType := structValue.Type()
for j := 0; j < structValue.NumField(); j++ {
fieldValue := structValue.Field(j)
fieldType := structType.Field(j)
columnName := strings.ToLower(fieldType.Name)
if fieldType.Tag.Get("db") != "" {
columnName = fieldType.Tag.Get("db")
}
columnValue := fieldValue.Interface()
if k == 0 {
columns = append(columns, columnName)
colToIdx[columnName] = i
i++
}
values[k] = append(values[k], columnValue)
}
}
return
}
// anySlice converts a slice of any type to a slice of interface{} type.
//
// It takes a slice as input and returns a new slice where each element is
// converted to the interface{} type. The input slice can be nil or empty,
// in which case the function returns nil.
//
// Parameters:
// - slice: The input slice to be converted.
//
// Return:
// - []interface{}: The converted slice where each element is of type
// interface{}.
func anySlice(slice any) []any {
s := reflect.ValueOf(slice)
if s.Kind() != reflect.Slice {
return nil
}
// Keep the distinction between nil and empty slice input
if s.IsNil() {
return nil
}
ret := make([]any, s.Len())
for i := 0; i < s.Len(); i++ {
ret[i] = s.Index(i).Interface()
}
return ret
}
// Update builds an UPDATE sql stmt with corresponding where/from clauses if stated
// returning affected rows
func (r *DB) Update(data any) (int64, error) {
if r.Txn != nil {
return r.Txn.Update(data)
}
bldr := r.Builder
if bldr.table == "" {
return 0, errTableCallBeforeOp
}
columns, values, bindings := prepareBindingsForStruct(data)
setVal := ""
l := len(columns)
for k, col := range columns {
setVal += col + " = " + bindings[k]
if k < l-1 {
setVal += ", "
}
}
query := `UPDATE "` + r.Builder.table + `" SET ` + setVal
if r.Builder.from != "" {
query += " FROM " + r.Builder.from
}
r.Builder.startBindingsAt = l + 1
query += r.Builder.buildClauses()
values = append(values, prepareValues(r.Builder.whereBindings)...)
res, err := r.Sql().Exec(query, values...)
if err != nil {
return 0, err
}
return res.RowsAffected()
}
// Update builds an UPDATE sql stmt with corresponding where/from clauses if stated
// returning affected rows
func (r *Txn) Update(data any) (int64, error) {
if r.Tx == nil {
return 0, errTransactionModeWithoutTx
}
bldr := r.Builder
if bldr.table == "" {
return 0, errTableCallBeforeOp
}
columns, values, bindings := prepareBindingsForStruct(data)
setVal := ""
l := len(columns)
for k, col := range columns {
setVal += col + " = " + bindings[k]
if k < l-1 {
setVal += ", "
}
}
query := `UPDATE "` + r.Builder.table + `" SET ` + setVal
if r.Builder.from != "" {
query += " FROM " + r.Builder.from
}
r.Builder.startBindingsAt = l + 1
query += r.Builder.buildClauses()
values = append(values, prepareValues(r.Builder.whereBindings)...)
res, err := r.Tx.Exec(query, values...)
if err != nil {
return 0, err
}
return res.RowsAffected()
}
// Delete builds a DELETE stmt with corresponding where clause if stated
// returning affected rows
func (r *DB) Delete() (int64, error) {
if r.Txn != nil {
return r.Txn.Delete()
}
bldr := r.Builder
if bldr.table == "" {
return 0, errTableCallBeforeOp
}
query := `DELETE FROM "` + r.Builder.table + `"`
query += r.Builder.buildClauses()
res, err := r.Sql().Exec(query, prepareValues(r.Builder.whereBindings)...)
if err != nil {
return 0, err
}
return res.RowsAffected()
}
// Delete builds a DELETE stmt with corresponding where clause if stated
// returning affected rows
func (r *Txn) Delete() (int64, error) {
if r.Tx == nil {
return 0, errTransactionModeWithoutTx
}
bldr := r.Builder
if bldr.table == "" {
return 0, errTableCallBeforeOp
}
query := `DELETE FROM "` + r.Builder.table + `"`
query += r.Builder.buildClauses()
res, err := r.Tx.Exec(query, prepareValues(r.Builder.whereBindings)...)
if err != nil {
return 0, err
}
return res.RowsAffected()
}
// Replace inserts data if conflicting row hasn't been found, else it will update an existing one
func (r *DB) Replace(data any, conflict string) (int64, error) {
if r.Txn != nil {
return r.Txn.Replace(data, conflict)
}
bldr := r.Builder
if bldr.table == "" {
return 0, errTableCallBeforeOp
}
columns, values, bindings := prepareBindingsForStruct(data)
query := `INSERT INTO "` + bldr.table + `" (` + strings.Join(columns, `, `) + `) VALUES(` + strings.Join(bindings, `, `) + `) ON CONFLICT(` + conflict + `) DO UPDATE SET `
for i, v := range columns {
columns[i] = v + " = excluded." + v
}
query += strings.Join(columns, ", ")
res, err := r.Sql().Exec(query, values...)
if err != nil {
return 0, err
}
return res.RowsAffected()
}
// Replace inserts data if conflicting row hasn't been found, else it will update an existing one
func (r *Txn) Replace(data any, conflict string) (int64, error) {
if r.Tx == nil {
return 0, errTransactionModeWithoutTx
}
bldr := r.Builder
if bldr.table == "" {
return 0, errTableCallBeforeOp
}
columns, values, bindings := prepareBindingsForStruct(data)
query := `INSERT INTO "` + bldr.table + `" (` + strings.Join(columns, `, `) + `) VALUES(` + strings.Join(bindings, `, `) + `) ON CONFLICT(` + conflict + `) DO UPDATE SET `
for i, v := range columns {
columns[i] = v + " = excluded." + v
}
query += strings.Join(columns, ", ")
res, err := r.Tx.Exec(query, values...)
if err != nil {
return 0, err
}
return res.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 (r *DB) InTransaction(fn func() (any, error)) error {
txn, err := r.Sql().Begin()
if err != nil {
return err
}
// assign transaction + builder to Txn entity
r.Txn = &Txn{
Tx: txn,
Builder: r.Builder,
}
defer func() {
// clear Txn object after commit
r.Txn = nil
}()
res, err := fn()
if err != nil {
errTxn := txn.Rollback()
if errTxn != nil {
return errTxn
}
return err
}
isOk := false
switch v := res.(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
}