-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathselector.go
1319 lines (1271 loc) · 29.4 KB
/
selector.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
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package korm
import (
"context"
"database/sql"
"errors"
"fmt"
"reflect"
"strconv"
"strings"
"time"
"github.com/kamalshkeir/kstrct"
"github.com/kamalshkeir/lg"
)
type Selector[T any] struct {
nested bool
debug bool
ctx context.Context
db *DatabaseEntity
dest *[]T
nocache bool
trace bool
}
type JsonOption struct {
As string
Dialect string
Database string
Params []any
}
func JSON_EXTRACT(dataJson string, opt ...JsonOption) string {
var opts JsonOption
if len(opt) > 0 {
opts = opt[0]
} else {
return JSON_CAST(dataJson, "")
}
if opts.Dialect == "" {
if opts.Database != "" {
// db specified
db, err := GetMemoryDatabase(opts.Database)
if err != nil {
db = &databases[0]
}
if opts.Dialect == "" {
opts.Dialect = db.Dialect
}
} else {
opts.Dialect = databases[0].Dialect
}
}
isData := ""
if strings.HasPrefix(dataJson, "'") {
isData = "'"
} else if strings.HasPrefix(dataJson, "{") {
isData = "{"
}
switch opts.Dialect {
case SQLITE, MYSQL, "sqlite":
st := "JSON_EXTRACT("
if isData == "{" {
st += "'" + dataJson + "'"
} else {
st += dataJson
}
if len(opts.Params) == 0 {
st += "),'$'"
return st
}
st += ","
for i, pp := range opts.Params {
jsonParam := ""
if v, ok := pp.(string); ok {
jsonParam = v
} else {
jsonParam = fmt.Sprint(pp)
}
if i > 0 {
st += ","
}
if strings.HasPrefix(jsonParam, "'") || strings.HasPrefix(jsonParam, "`") {
jsonParam = jsonParam[1 : len(jsonParam)-2]
}
st += "'$"
if strings.Contains(jsonParam, ".") {
sp := strings.Split(jsonParam, ".")
for _, s := range sp {
// check if s is a number
if _, err := strconv.Atoi(s); err == nil {
st += "[" + s + "]"
} else {
st += "." + s
}
}
st += "'"
} else {
st += "." + jsonParam + "'"
}
if i == len(opts.Params)-1 {
st += ")"
}
}
if opts.As != "" {
st += " AS " + opts.As
}
return st
case POSTGRES, "pg":
if len(opts.Params) == 0 {
return dataJson
}
if isData == "'" || isData == "{" {
if isData == "{" {
dataJson = "'" + dataJson + "'::jsonb"
} else {
dataJson = dataJson + "::jsonb"
}
}
if len(opts.Params) == 1 {
ss := ""
if param, ok := opts.Params[0].(string); ok {
for _, s := range strings.Split(param, ".") {
ss += ", '" + s + "'"
}
return "JSONB_EXTRACT_PATH_TEXT(" + dataJson + ss + ")"
} else {
lg.ErrorC("param must be string", "param", param)
return dataJson
}
}
paramsString := ""
// opts.ParamsToExtract "a.2.name", "b.email", "b"
for i, extractParam := range opts.Params {
ep := ""
var ok bool
if ep, ok = extractParam.(string); !ok {
lg.ErrorC("param must be string", "param", extractParam)
return dataJson
}
if i > 0 {
paramsString += ", "
}
paramsString += "JSONB_EXTRACT_PATH_TEXT(" + dataJson
for _, s := range strings.Split(ep, ".") {
paramsString += ", '" + s + "'"
}
paramsString += ")"
}
if len(opts.Params) > 1 {
paramsString = "JSONB_BUILD_ARRAY(" + paramsString + ")"
}
if opts.As != "" {
paramsString += " AS " + opts.As
}
return paramsString
default:
lg.ErrorC("case not handled", "dialect", opts.Dialect)
return ""
}
}
func JSON_REMOVE(dataJson string, opt ...JsonOption) string {
var opts JsonOption
if len(opt) > 0 {
opts = opt[0]
} else {
return JSON_CAST(dataJson, "")
}
if opts.Dialect == "" {
if opts.Database != "" {
// db specified
db, err := GetMemoryDatabase(opts.Database)
if err != nil {
db = &databases[0]
}
if opts.Dialect == "" {
opts.Dialect = db.Dialect
}
} else {
opts.Dialect = databases[0].Dialect
}
}
isData := ""
if strings.HasPrefix(dataJson, "'") {
isData = "'"
} else if strings.HasPrefix(dataJson, "{") {
isData = "{"
}
switch opts.Dialect {
case SQLITE, MYSQL, "sqlite":
st := "JSON_REMOVE("
if isData == "{" {
st += "'" + dataJson + "'"
} else {
st += dataJson
}
if len(opts.Params) == 0 {
st += "),'$'"
return st
}
st += ","
for i, pp := range opts.Params {
if i > 0 {
st += ","
}
var jsonParam string
var ok bool
if jsonParam, ok = pp.(string); !ok {
lg.ErrorC("expected string", "param", pp)
return st
}
if i%2 == 0 {
st += "'$"
if strings.Contains(jsonParam, ".") {
sp := strings.Split(jsonParam, ".")
for _, s := range sp {
// check if s is a number
if _, err := strconv.Atoi(s); err == nil {
st += "[" + s + "]"
} else {
st += "." + s
}
}
st += "'"
} else {
jsonParam = strings.ReplaceAll(jsonParam, "'", "")
st += "." + jsonParam + "'"
}
if i == len(opts.Params)-1 {
st += ")"
}
} else {
st += "'$"
if _, err := strconv.Atoi(jsonParam); err == nil {
st += "[" + jsonParam + "]"
} else {
st += "." + jsonParam + "'"
}
if i == len(opts.Params)-1 {
st += ")"
}
}
}
if opts.As != "" {
st += " AS " + opts.As
}
return st
case POSTGRES, "pg":
// your_column_name #- '{a, 2, name}' #- '{b, email}'
if isData == "'" || isData == "{" {
if isData == "{" {
dataJson = "'" + dataJson + "'::jsonb"
} else {
dataJson = dataJson + "::jsonb"
}
}
st := dataJson
if len(opts.Params) == 0 {
return st
}
for i, pp := range opts.Params {
var jsonParam string
var ok bool
if jsonParam, ok = pp.(string); !ok && i%2 == 0 {
lg.ErrorC("expected string", "param", jsonParam)
return st
}
if i%2 == 0 && strings.Contains(jsonParam, ".") {
sp := strings.Split(jsonParam, ".")
tt := ""
for i, s := range sp {
if i > 0 {
tt += ","
}
tt += s
}
st += " #- '{" + tt + "}'"
} else {
st += " - " + jsonParam
}
}
if opts.As != "" {
st += " AS " + opts.As
}
return st
default:
lg.ErrorC("case not handled", "dialect", opts.Dialect)
return ""
}
}
func JSON_SET(dataJson string, opt ...JsonOption) string {
var opts JsonOption
if len(opt) > 0 {
opts = opt[0]
} else {
return JSON_CAST(dataJson, "data")
}
if len(opts.Params)%2 != 0 {
lg.ErrorC("expected even number of params", "params", opts.Params)
return dataJson
}
if opts.Dialect == "" {
if opts.Database != "" {
// db specified
db, err := GetMemoryDatabase(opts.Database)
if err != nil {
db = &databases[0]
}
if opts.Dialect == "" {
opts.Dialect = db.Dialect
}
} else {
opts.Dialect = databases[0].Dialect
}
}
isData := ""
if strings.HasPrefix(dataJson, "'") {
isData = "'"
} else if strings.HasPrefix(dataJson, "{") {
isData = "{"
}
switch opts.Dialect {
case SQLITE, MYSQL, "sqlite":
st := "JSON_SET("
if isData == "{" {
st += "'" + dataJson + "'"
} else {
st += dataJson
}
if len(opts.Params) == 0 {
st += "),'$'"
return st
}
st += ","
for i, pp := range opts.Params {
if i > 0 {
st += ","
}
var jsonParam string
var ok bool
if i%2 == 0 {
if jsonParam, ok = pp.(string); !ok {
lg.ErrorC("expected string", "param", pp)
return st
}
jsonParam = strings.ReplaceAll(jsonParam, "'", "")
st += "'$"
if strings.Contains(jsonParam, ".") {
sp := strings.Split(jsonParam, ".")
for _, s := range sp {
// check if s is a number
if _, err := strconv.Atoi(s); err == nil {
st += "[" + s + "]"
} else {
st += "." + s
}
}
st += "'"
} else {
st += "." + jsonParam + "'"
}
} else {
if jp, ok := pp.(string); ok {
if !strings.Contains(jp, "'") {
jp = "'" + jp + "'"
}
st += jp
} else {
st += fmt.Sprint(pp)
}
}
if i == len(opts.Params)-1 {
st += ")"
}
}
if opts.As != "" {
st += " AS " + opts.As
}
return st
case POSTGRES, "pg":
if isData == "'" || isData == "{" {
if isData == "{" {
dataJson = "'" + dataJson + "'::jsonb"
} else {
dataJson = dataJson + "::jsonb"
}
}
newws := make([]string, 0, len(opts.Params)/2)
st := "JSONB_SET(" + dataJson
if len(opts.Params) == 0 {
return st + ")"
} else if len(opts.Params) == 2 {
for i, pp := range opts.Params {
var jsonParam string
var ok bool
if i == 0 {
if jsonParam, ok = pp.(string); !ok {
lg.ErrorC("expected string", "param", pp)
return dataJson
}
}
st += ", "
if i%2 == 0 && strings.Contains(jsonParam, ".") {
tt := strings.ReplaceAll(jsonParam, ".", ",")
tt = strings.ReplaceAll(tt, "'", "")
st += " '{" + tt + "}'"
} else {
if v, ok := pp.(string); ok {
if !strings.Contains(v, "'") {
st += " '" + v + "'"
} else {
st += v
}
} else {
st += fmt.Sprint(pp)
}
}
}
st += ", 'true'"
} else {
new := "JSONB_SET(" + dataJson
for i, pp := range opts.Params {
var jsonParam string
var ok bool
if i%2 == 0 {
new = "JSONB_SET(%s"
if jsonParam, ok = pp.(string); !ok {
lg.ErrorC("expected string", "param", pp)
return dataJson
} else {
pp = strings.ReplaceAll(jsonParam, "'", "")
}
}
new += ", "
if i%2 == 0 {
tt := strings.ReplaceAll(jsonParam, ".", ",")
new += " '{" + tt + "}'"
} else {
if v, ok := pp.(string); ok && i%2 == 1 {
if !strings.Contains(v, "'") {
new += " '" + v + "', 'true'"
} else {
new += " " + v + ", 'true'"
}
} else {
new += fmt.Sprint(pp) + ", 'true'"
}
new += ")"
newws = append(newws, new)
}
}
res := newws[0]
for i, v := range newws {
if i == 0 {
continue
}
res = fmt.Sprintf(res, v)
if i == len(newws)-1 {
res = fmt.Sprintf(res, dataJson)
}
}
if opts.As != "" {
res += " AS " + opts.As
}
return res
}
st += ")"
if opts.As != "" {
st += " AS " + opts.As
}
return st
default:
lg.ErrorC("case not handled", "dialect", opts.Dialect)
return ""
}
}
func JSON_ARRAY(values []any, as string, dialect ...string) string {
dbDialect := databases[0].Dialect
if len(dialect) > 0 {
dbDialect = dialect[0]
}
valuesString := make([]string, 0, len(values))
for _, v := range values {
switch vType := v.(type) {
case string:
if strings.Contains(vType, "'") {
valuesString = append(valuesString, vType)
} else {
valuesString = append(valuesString, "'"+vType+"'")
}
case time.Time:
valuesString = append(valuesString, fmt.Sprint(vType.Unix()))
case *time.Time:
valuesString = append(valuesString, fmt.Sprint(vType.Unix()))
default:
valuesString = append(valuesString, fmt.Sprint(v))
}
}
switch dbDialect {
case SQLITE, MYSQL, "sqlite":
st := "JSON_ARRAY(" + strings.Join(valuesString, ", ") + ")"
if as != "" {
st += " AS " + as
}
return st
case POSTGRES, "pg":
st := "JSONB_BUILD_ARRAY(" + strings.Join(valuesString, ", ") + ")"
if as != "" {
st += " AS " + as
}
return st
default:
lg.ErrorC("case not handled", "dialect", dbDialect)
return ""
}
}
func JSON_OBJECT(values []any, as string, dialect ...string) string {
dbDialect := databases[0].Dialect
if len(dialect) > 0 {
dbDialect = dialect[0]
}
valuesString := make([]string, 0, len(values))
for i, v := range values {
var vv string
if i%2 == 0 {
var ok bool
if vv, ok = v.(string); ok {
if !strings.HasPrefix(vv, "'") {
vv = "'" + vv + "'"
}
} else {
lg.ErrorC("expected string", "value", v)
return ""
}
} else {
switch val := v.(type) {
case string:
if !strings.HasPrefix(val, "'") {
vv = "'" + val + "'"
} else {
vv = val
}
case time.Time:
vv = fmt.Sprint(val.Unix())
case *time.Time:
vv = fmt.Sprint(val.Unix())
default:
vv = fmt.Sprint(v)
}
}
valuesString = append(valuesString, vv)
}
switch dbDialect {
case SQLITE, MYSQL, "sqlite":
st := "JSON_OBJECT(" + strings.Join(valuesString, ", ") + ")"
if as != "" {
st += " AS " + as
}
return st
case POSTGRES, "pg":
st := "JSONB_BUILD_OBJECT(" + strings.Join(valuesString, ", ") + ")"
if as != "" {
st += " AS " + as
}
return st
default:
lg.ErrorC("case not handled", "dialect", dbDialect)
return ""
}
}
func JSON_CAST(value string, as string, dialect ...string) string {
value = strings.ReplaceAll(value, "'", "\"")
dbDialect := databases[0].Dialect
if len(dialect) > 0 {
dbDialect = dialect[0]
}
if !strings.HasPrefix(value, "'") {
value = "'" + value + "'"
}
var st string
switch dbDialect {
case SQLITE, "sqlite":
st = "JSON(" + value + ")"
case POSTGRES, "pg":
st = value + "::jsonb"
case MYSQL:
st = "JSON_EXTRACT(" + value + ", '$')"
}
if as != "" {
st += " AS " + as
}
return st
}
func To[T any](dest *[]T, nestedSlice ...bool) *Selector[T] {
s := &Selector[T]{
dest: dest,
db: &databases[0],
}
if len(nestedSlice) > 0 && nestedSlice[0] {
s.nested = true
}
return s
}
func (sl *Selector[T]) Database(dbName string) *Selector[T] {
db, err := GetMemoryDatabase(dbName)
if err == nil {
sl.db = db
} else {
lg.ErrorC("db not found", "dbname", dbName)
}
return sl
}
func (sl *Selector[T]) Ctx(ct context.Context) *Selector[T] {
sl.ctx = ct
return sl
}
func (sl *Selector[T]) Debug() *Selector[T] {
sl.debug = true
return sl
}
func (sl *Selector[T]) NoCache() *Selector[T] {
sl.nocache = true
return sl
}
func (sl *Selector[T]) Trace() *Selector[T] {
if sl == nil {
return nil
}
sl.trace = true
if sl.ctx == nil {
sl.ctx = context.Background()
}
sl.ctx = context.WithValue(sl.ctx, traceEnabledKey, true)
return sl
}
// The input can be a struct, a pointer to a struct, or a pointer to a pointer to a struct.
func ResetStruct(input interface{}) error {
v := reflect.ValueOf(input)
// Handle double pointer
if v.Kind() == reflect.Ptr && v.Elem().Kind() == reflect.Ptr {
if v.IsNil() || v.Elem().IsNil() || v.Elem().Elem().Kind() != reflect.Struct {
return errors.New("input must be a non-nil pointer to a struct or a struct")
}
v = v.Elem().Elem() // Dereference to get to the struct
} else if v.Kind() == reflect.Ptr {
// Handle single pointer
if v.IsNil() || v.Elem().Kind() != reflect.Struct {
return errors.New("input must be a non-nil pointer to a struct or a struct")
}
v = v.Elem()
} else if v.Kind() != reflect.Struct {
// Handle non-pointer struct
return errors.New("input must be a struct or a pointer to a struct")
}
// Iterate through the fields and reset them
for i := 0; i < v.NumField(); i++ {
field := v.Field(i)
if field.CanSet() {
field.Set(reflect.Zero(field.Type()))
}
}
return nil
}
func (sl *Selector[T]) Query(statement string, args ...any) error {
// Ensure we have a context with trace flag if tracing is enabled
if sl.trace && sl.ctx == nil {
sl.ctx = context.WithValue(context.Background(), traceEnabledKey, true)
}
var stt string
if useCache && !sl.nocache {
stt = statement + fmt.Sprint(args...)
if v, ok := cacheQ.Get(stt); ok {
if len(*sl.dest) == 0 {
*sl.dest = v.([]T)
return nil
}
}
}
typ := fmt.Sprintf("%T", *new(T))
ref := reflect.ValueOf(*new(T))
// Expand IN clause arguments before dialect adaptation
statement, args = In(statement, args...)
AdaptPlaceholdersToDialect(&statement, sl.db.Dialect)
adaptTimeToUnixArgs(&args)
var rows *sql.Rows
var err error
if sl.debug {
lg.Info("DEBUG SELECTOR", "statement", statement, "args", fmt.Sprintf("%v", args))
}
if sl.ctx != nil {
rows, err = sl.db.Conn.QueryContext(sl.ctx, statement, args...)
} else {
rows, err = sl.db.Conn.Query(statement, args...)
}
if err != nil {
return err
}
columns, err := rows.Columns()
if err != nil {
return err
}
isMap, isChan, isStrct, isArith, isPtr := false, false, false, false, false
if typ[0] == '*' {
isPtr = true
typ = typ[1:]
}
isNested := sl.nested
if len(*sl.dest) == 1 || len(typ) >= 4 && typ[:4] == "chan" {
isChan = true
if strings.Contains(typ, "map[string]") {
isMap = true
}
}
if typ[:3] == "map" {
isMap = true
} else if isNested || strings.Contains(typ, ".") || ref.Kind() == reflect.Struct || (ref.Kind() == reflect.Chan && ref.Type().Elem().Kind() == reflect.Struct) {
if strings.HasSuffix(typ, "Time") {
isArith = true
} else {
isStrct = true
}
} else {
isArith = true
}
var (
columns_ptr_to_values = make([]any, len(columns))
kv = make([]kstrct.KV, len(columns))
temp = new(T)
lastData []kstrct.KV
)
index := 0
defer rows.Close()
loop:
for rows.Next() {
for i := range kv {
kv[i].Key = columns[i]
columns_ptr_to_values[i] = &kv[i].Value
}
err := rows.Scan(columns_ptr_to_values...)
if err != nil {
return err
}
if sl.db.Dialect == MYSQL {
for i, kvv := range kv {
if v, ok := kvv.Value.([]byte); ok {
kv[i] = kstrct.KV{Key: kvv.Key, Value: string(v)}
}
}
}
switch {
case isStrct && !isChan:
if !isNested {
if isPtr {
t := ref.Type().Elem()
newElem := reflect.New(t).Interface().(T)
err := kstrct.Fill(newElem, kv)
if lg.CheckError(err) {
return err
}
*sl.dest = append(*sl.dest, newElem)
} else {
err := kstrct.Fill(temp, kv)
if lg.CheckError(err) {
return err
}
*sl.dest = append(*sl.dest, *temp)
ResetStruct(temp)
}
continue loop
}
if len(lastData) == 0 {
lastData = make([]kstrct.KV, len(kv))
copy(lastData, kv)
if isPtr {
t := reflect.TypeOf(*new(T)).Elem()
newElem := reflect.New(t).Interface().(T)
*sl.dest = append(*sl.dest, newElem)
temp = &(*sl.dest)[0]
err := kstrct.Fill(*temp, kv, true)
if lg.CheckError(err) {
return err
}
} else {
*sl.dest = append(*sl.dest, *new(T))
temp = &(*sl.dest)[0]
err := kstrct.Fill(temp, kv, true)
if lg.CheckError(err) {
return err
}
}
} else {
for _, kvv := range kv {
if kvv.Key == columns[0] {
foundk := false
for _, ld := range lastData {
if ld.Key == columns[0] && ld.Value == kvv.Value {
foundk = true
break
}
}
if !foundk {
lastData = append(lastData, kvv)
index++
if isPtr {
t := reflect.TypeOf(*new(T)).Elem()
newElem := reflect.New(t).Interface().(T)
*sl.dest = append(*sl.dest, newElem)
temp = &(*sl.dest)[index]
err := kstrct.Fill(*temp, kv, true)
if lg.CheckError(err) {
return err
}
} else {
*sl.dest = append(*sl.dest, *new(T))
temp = &(*sl.dest)[index]
err := kstrct.Fill(temp, kv, true)
if lg.CheckError(err) {
return err
}
}
} else {
lastData = append(lastData, kvv)
if !isPtr {
err := kstrct.Fill(&(*sl.dest)[index], kv, true)
if lg.CheckError(err) {
return err
}
} else {
err := kstrct.Fill((*sl.dest)[index], kv, true)
if lg.CheckError(err) {
return err
}
}
}
break
}
}
}
continue loop
case isMap && !isChan:
if isNested {
return fmt.Errorf("map is not nested struct")
}
m := make(map[string]any, len(kv))
for _, kvv := range kv {
m[kvv.Key] = kvv.Value
}
if isPtr {
if v, ok := any(&m).(T); ok {
*sl.dest = append(*sl.dest, v)
}
} else {
if v, ok := any(m).(T); ok {
*sl.dest = append(*sl.dest, v)
}
}
continue loop
case isArith && !isChan:
if isNested {
return fmt.Errorf("arithmetic types cannot be nested")
}
if len(kv) == 1 {
for _, vKV := range kv {
vv := vKV.Value
if isPtr {
if vok, ok := any(&vv).(T); ok {
*sl.dest = append(*sl.dest, vok)
} else {
elem := reflect.New(ref.Type()).Elem()
err := kstrct.SetReflectFieldValue(elem, vKV.Value)
if err != nil {
return err
}
*sl.dest = append(*sl.dest, elem.Interface().(T))
}
} else {
if vok, ok := any(vv).(T); ok {
*sl.dest = append(*sl.dest, vok)
} else {
elem := reflect.New(ref.Type()).Elem()
err := kstrct.SetReflectFieldValue(elem, vKV.Value)
if err != nil {
return err
}
*sl.dest = append(*sl.dest, elem.Interface().(T))
}
}
}
continue loop
}
case isChan:
switch {
case isStrct:
if isPtr {
return fmt.Errorf("channel of pointers not allowed in case of structs")
}
if !isNested {
err := kstrct.Fill((*sl.dest)[0], kv)
if lg.CheckError(err) {
return err
}
continue loop
} else {
err := kstrct.Fill((*sl.dest)[0], kv, true)
if lg.CheckError(err) {
return err
}
continue loop
}
case isMap:
if isNested {
return fmt.Errorf("map cannot be nested")
}
m := make(map[string]any, len(kv))
for _, vkv := range kv {
m[vkv.Key] = vkv.Value
}
if v, ok := any((*sl.dest)[0]).(chan map[string]any); ok {
v <- m
} else if v, ok := any((*sl.dest)[0]).(chan *map[string]any); ok {
v <- &m
}
continue loop
case isArith:
if isNested {
return fmt.Errorf("type cannot be nested")
}
chanType := reflect.New(ref.Type().Elem()).Elem()
for _, vKv := range kv {
if chanType.Kind() == reflect.Struct || (chanType.Kind() == reflect.Ptr && chanType.Elem().Kind() == reflect.Struct) {
m := make(map[string]any, len(kv))
for _, vkv := range kv {
m[vkv.Key] = vkv.Value
}
err := kstrct.SetReflectFieldValue(chanType, m)
if lg.CheckError(err) {
return err
}
} else {
err := kstrct.SetReflectFieldValue(chanType, vKv.Value)
if lg.CheckError(err) {
return err
}
}
reflect.ValueOf((*sl.dest)[0]).Send(chanType)
}
default:
return fmt.Errorf("channel case not handled")
}
default:
return fmt.Errorf("default triggered, case not handled")
}
}
if useCache && !sl.nocache && !isChan && len(*sl.dest) > 0 {
cacheQ.Set(stt, *sl.dest)
}
return nil
}
func (sl *Selector[T]) Named(statement string, args map[string]any, unsafe ...bool) error {
if sl.trace {