-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsqlt.go
1667 lines (1334 loc) · 33.9 KB
/
sqlt.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 sqlt
import (
"context"
"database/sql"
"encoding"
"encoding/json"
"errors"
"fmt"
"io"
"io/fs"
"reflect"
"runtime"
"slices"
"strings"
"sync"
"text/template"
"text/template/parse"
"time"
"github.com/cespare/xxhash/v2"
"github.com/hashicorp/golang-lru/v2/expirable"
"github.com/jba/templatecheck"
)
type DB interface {
QueryContext(ctx context.Context, sql string, args ...any) (*sql.Rows, error)
QueryRowContext(ctx context.Context, sql string, args ...any) *sql.Row
ExecContext(ctx context.Context, sql string, args ...any) (sql.Result, error)
}
type Option interface {
Configure(config *Config)
}
type Config struct {
Placeholder Placeholder
Templates []Template
Log Log
Cache *Cache
Hasher Hasher
}
func (c Config) Configure(config *Config) {
if c.Placeholder != "" {
config.Placeholder = c.Placeholder
}
if len(c.Templates) > 0 {
config.Templates = append(config.Templates, c.Templates...)
}
if c.Log != nil {
config.Log = c.Log
}
if c.Cache != nil {
config.Cache = c.Cache
}
if c.Hasher != nil {
config.Hasher = c.Hasher
}
}
// Cache controls expression caching.
// Size ≤ 0 means unlimited cache.
// Expiration ≤ 0 prevents expiration.
type Cache struct {
Size int
Expiration time.Duration
}
// Configure applies Config settings.
func (c *Cache) Configure(config *Config) {
config.Cache = c
}
// NoCache disables caching.
func NoCache() *Cache {
return nil
}
// NoExpirationCache enables a non-expiring cache.
func NoExpirationCache(size int) *Cache {
return &Cache{
Size: size,
Expiration: 0,
}
}
// UnlimitedSizeCache enables an unlimited-size cache.
func UnlimitedSizeCache(expiration time.Duration) *Cache {
return &Cache{
Size: 0,
Expiration: expiration,
}
}
// Hasher generates cache keys for parameters.
type Hasher func(param any, writer io.Writer) error
// Configure applies Config settings.
func (h Hasher) Configure(config *Config) {
config.Hasher = h
}
// DefaultHasher encodes parameters as JSON for caching.
func DefaultHasher() Hasher {
return func(param any, writer io.Writer) error {
return json.NewEncoder(writer).Encode(param)
}
}
// Placeholder defines static or positional (`%d`) placeholders.
// Default: `'?'`.
type Placeholder string
// Configure applies Config settings.
func (p Placeholder) Configure(config *Config) {
config.Placeholder = p
}
const (
// Question is the default placeholder.
Question Placeholder = "?"
// Dollar uses positional placeholders ($1, $2).
Dollar Placeholder = "$%d"
// Colon uses positional placeholders (:1, :2).
Colon Placeholder = ":%d"
// AtP uses positional placeholders (@p1, @p2).
AtP Placeholder = "@p%d"
)
// Template modifies a text/template.Template.
type Template func(t *template.Template) (*template.Template, error)
// Configure applies Config settings.
func (to Template) Configure(config *Config) {
config.Templates = append(config.Templates, to)
}
// Name creates a named template.
func Name(name string) Template {
return func(tpl *template.Template) (*template.Template, error) {
return tpl.New(name), nil
}
}
// Parse parses a template string.
func Parse(text string) Template {
return func(tpl *template.Template) (*template.Template, error) {
return tpl.Parse(text)
}
}
// ParseFS loads templates from a filesystem.
func ParseFS(fs fs.FS, patterns ...string) Template {
return func(tpl *template.Template) (*template.Template, error) {
return tpl.ParseFS(fs, patterns...)
}
}
// ParseFiles loads templates from files.
func ParseFiles(filenames ...string) Template {
return func(tpl *template.Template) (*template.Template, error) {
return tpl.ParseFiles(filenames...)
}
}
// ParseGlob loads templates matching a pattern.
func ParseGlob(pattern string) Template {
return func(tpl *template.Template) (*template.Template, error) {
return tpl.ParseGlob(pattern)
}
}
// Funcs adds custom functions to a template.
func Funcs(fm template.FuncMap) Template {
return func(tpl *template.Template) (*template.Template, error) {
return tpl.Funcs(fm), nil
}
}
// MissingKeyInvalid treats missing keys as errors.
func MissingKeyInvalid() Template {
return func(tpl *template.Template) (*template.Template, error) {
return tpl.Option("missingkey=invalid"), nil
}
}
// MissingKeyZero replaces missing keys with zero values.
func MissingKeyZero() Template {
return func(tpl *template.Template) (*template.Template, error) {
return tpl.Option("missingkey=zero"), nil
}
}
// MissingKeyError throws an error on missing keys.
func MissingKeyError() Template {
return func(tpl *template.Template) (*template.Template, error) {
return tpl.Option("missingkey=error"), nil
}
}
// Lookup retrieves a named template.
func Lookup(name string) Template {
return func(tpl *template.Template) (*template.Template, error) {
tpl = tpl.Lookup(name)
if tpl == nil {
return nil, fmt.Errorf("template '%s' not found", name)
}
return tpl, nil
}
}
// Log can be used to apply logging.
type Log func(ctx context.Context, info Info)
// Configure applies Config settings.
func (l Log) Configure(config *Config) {
config.Log = l
}
// Info contains loggable execution details.
type Info struct {
Duration time.Duration
Mode Mode
Template string
Location string
SQL string
Args []any
Err error
Cached bool
Transaction bool
}
// Mode identifies SQL statement types.
type Mode string
const (
// ExecMode for 'Exec' statements.
ExecMode Mode = "Exec"
// QueryRowMode for 'QueryRow' statements.
QueryRowMode Mode = "QueryRow"
// QueryMode for 'Query' statements.
QueryMode Mode = "Query"
// FirstMode for 'First' statements.
FirstMode Mode = "First"
// OneMode for 'One' statements.
OneMode Mode = "One"
// AllMode for 'All' statements.
AllMode Mode = "All"
)
type Expression[Dest any] struct {
SQL string
Args []any
Scanners []Scanner[Dest]
}
func (e Expression[Dest]) DestMapper() ([]any, func(dest *Dest) error, error) {
if len(e.Scanners) == 0 {
scan, err := scan[Dest]("")
if err != nil {
return nil, nil, err
}
e.Scanners = []Scanner[Dest]{scan}
}
var (
values = make([]any, len(e.Scanners))
mappers = make([]func(*Dest) error, len(e.Scanners))
)
for i, s := range e.Scanners {
values[i], mappers[i] = s()
}
return values, func(dest *Dest) error {
for _, m := range mappers {
if m != nil {
if err := m(dest); err != nil {
return err
}
}
}
return nil
}, nil
}
func (e Expression[Dest]) First(ctx context.Context, db DB) (first Dest, err error) {
if len(e.SQL) == 0 {
return first, sql.ErrNoRows
}
row := db.QueryRowContext(ctx, e.SQL, e.Args...)
values, mapper, err := e.DestMapper()
if err != nil {
return first, err
}
if err = row.Scan(values...); err != nil {
return first, err
}
if err = mapper(&first); err != nil {
return first, err
}
return first, nil
}
var ErrTooManyRows = errors.New("too many rows")
func (e Expression[Dest]) One(ctx context.Context, db DB) (one Dest, err error) {
if len(e.SQL) == 0 {
return one, sql.ErrNoRows
}
rows, err := db.QueryContext(ctx, e.SQL, e.Args...)
if err != nil {
return one, err
}
defer func() {
err = errors.Join(err, rows.Close(), rows.Err())
}()
if !rows.Next() {
return one, sql.ErrNoRows
}
values, mapper, err := e.DestMapper()
if err != nil {
return one, err
}
if err = rows.Scan(values...); err != nil {
return one, err
}
if err = mapper(&one); err != nil {
return one, err
}
if rows.Next() {
return one, ErrTooManyRows
}
return one, nil
}
func (e Expression[Dest]) All(ctx context.Context, db DB) (all []Dest, err error) {
if len(e.SQL) == 0 {
return nil, sql.ErrNoRows
}
rows, err := db.QueryContext(ctx, e.SQL, e.Args...)
if err != nil {
return nil, err
}
defer func() {
err = errors.Join(err, rows.Close(), rows.Err())
}()
values, mapper, err := e.DestMapper()
if err != nil {
return nil, err
}
for rows.Next() {
if err = rows.Scan(values...); err != nil {
return nil, err
}
var dest Dest
if err = mapper(&dest); err != nil {
return nil, err
}
all = append(all, dest)
}
return all, nil
}
type Scanner[Dest any] func() (any, func(dest *Dest) error)
type Raw string
type ContextKey string
type ContextStatement[Param any] interface {
ExecContext(ctx context.Context, db DB, param Param) (result context.Context, err error)
}
func Transaction[Param any](txOpts *sql.TxOptions, stmts ...ContextStatement[Param]) *TransactionStatement[Param] {
return &TransactionStatement[Param]{
txOpts: txOpts,
stmts: stmts,
}
}
type TransactionStatement[Param any] struct {
txOpts *sql.TxOptions
stmts []ContextStatement[Param]
}
type TxBeginner interface {
BeginTx(ctx context.Context, opts *sql.TxOptions) (*sql.Tx, error)
}
func (ts *TransactionStatement[Param]) Exec(ctx context.Context, db TxBeginner, param Param) (result context.Context, err error) {
tx, err := db.BeginTx(ctx, ts.txOpts)
if err != nil {
return result, err
}
defer func() {
if err != nil {
err = errors.Join(err, tx.Rollback())
} else {
err = tx.Commit()
}
}()
result = ctx
for _, s := range ts.stmts {
ctx, err = s.ExecContext(result, tx, param)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
continue
}
return result, err
}
if ctx != result {
result = ctx
}
}
return result, nil
}
func Exec[Param any](opts ...Option) *Statement[Param, any, sql.Result] {
return Stmt[Param](getLocation(), ExecMode, func(ctx context.Context, db DB, expr Expression[any]) (sql.Result, error) {
return db.ExecContext(ctx, expr.SQL, expr.Args...)
}, opts...)
}
func QueryRow[Param any](opts ...Option) *Statement[Param, any, *sql.Row] {
return Stmt[Param](getLocation(), QueryRowMode, func(ctx context.Context, db DB, expr Expression[any]) (*sql.Row, error) {
return db.QueryRowContext(ctx, expr.SQL, expr.Args...), nil
}, opts...)
}
func Query[Param any](opts ...Option) *Statement[Param, any, *sql.Rows] {
return Stmt[Param](getLocation(), QueryMode, func(ctx context.Context, db DB, expr Expression[any]) (*sql.Rows, error) {
return db.QueryContext(ctx, expr.SQL, expr.Args...)
}, opts...)
}
func First[Param any, Dest any](opts ...Option) *Statement[Param, Dest, Dest] {
return Stmt[Param](getLocation(), FirstMode, func(ctx context.Context, db DB, expr Expression[Dest]) (Dest, error) {
return expr.First(ctx, db)
}, opts...)
}
func One[Param any, Dest any](opts ...Option) *Statement[Param, Dest, Dest] {
return Stmt[Param](getLocation(), OneMode, func(ctx context.Context, db DB, expr Expression[Dest]) (Dest, error) {
return expr.One(ctx, db)
}, opts...)
}
func All[Param any, Dest any](opts ...Option) *Statement[Param, Dest, []Dest] {
return Stmt[Param](getLocation(), AllMode, func(ctx context.Context, db DB, expr Expression[Dest]) ([]Dest, error) {
return expr.All(ctx, db)
}, opts...)
}
func Stmt[Param any, Dest any, Result any](location string, mode Mode, exec func(ctx context.Context, db DB, expr Expression[Dest]) (Result, error), opts ...Option) *Statement[Param, Dest, Result] {
if location == "" {
location = getLocation()
}
config := &Config{
Placeholder: Question,
Hasher: DefaultHasher(),
}
for _, o := range opts {
o.Configure(config)
}
var (
scannerStore = &scannerStore[Dest]{
store: map[string]Scanner[Dest]{},
}
t = template.New("").Funcs(template.FuncMap{
"Raw": func(sql string) Raw { return Raw(sql) },
"Context": func(key string) any {
return ContextKey(key)
},
"Scan": scannerStore.scan,
"ScanJSON": scannerStore.scanJSON,
"ScanBinary": scannerStore.scanBinary,
"ScanText": scannerStore.scanText,
"ScanDefault": scannerStore.scanDefault,
"ScanSplit": scannerStore.scanSplit,
"ScanBitmask": scannerStore.scanBitmask,
"ScanEnum": scannerStore.scanEnum,
"ScanBool": scannerStore.scanBool,
"ScanTime": scannerStore.scanTime,
})
err error
)
for _, to := range config.Templates {
t, err = to(t)
if err != nil {
panic(fmt.Errorf("parse template at %s: %w", location, err))
}
}
if err = templatecheck.CheckText(t, *new(Param)); err != nil {
panic(fmt.Errorf("check template at %s: %w", location, err))
}
if err = escapeNode[Dest](t, t.Tree.Root); err != nil {
panic(fmt.Errorf("escape template at %s: %w", location, err))
}
t, err = t.Clone()
if err != nil {
panic(err)
}
var (
placeholder = string(config.Placeholder)
positional = strings.Contains(placeholder, "%d")
)
pool := &sync.Pool{
New: func() any {
tc, _ := t.Clone()
r := &runner[Param, Dest]{
ctx: context.Background(),
tpl: tc,
sqlWriter: &sqlWriter{},
}
r.tpl.Funcs(template.FuncMap{
"Context": func(key string) any {
switch value := r.ctx.Value(ContextKey(key)).(type) {
case *any:
return *value
default:
return value
}
},
ident: func(arg any) Raw {
switch a := arg.(type) {
case Raw:
return a
case Scanner[Dest]:
r.scanners = append(r.scanners, a)
return Raw("")
default:
r.args = append(r.args, arg)
if positional {
return Raw(fmt.Sprintf(placeholder, len(r.args)))
}
return Raw(placeholder)
}
},
})
return r
},
}
var cache *expirable.LRU[uint64, Expression[Dest]]
if config.Cache != nil {
cache = expirable.NewLRU[uint64, Expression[Dest]](config.Cache.Size, nil, config.Cache.Expiration)
}
return &Statement[Param, Dest, Result]{
name: t.Name(),
location: location,
mode: mode,
hasher: config.Hasher,
cache: cache,
pool: pool,
log: config.Log,
exec: exec,
}
}
type Statement[Param any, Dest any, Result any] struct {
name string
location string
mode Mode
hasher Hasher
cache *expirable.LRU[uint64, Expression[Dest]]
exec func(ctx context.Context, db DB, expr Expression[Dest]) (Result, error)
pool *sync.Pool
log Log
}
func (s *Statement[Param, Dest, Result]) ExecContext(ctx context.Context, db DB, param Param) (result context.Context, err error) {
res, err := s.Exec(ctx, db, param)
if err != nil {
return result, err
}
switch r := any(res).(type) {
case context.Context:
return r, nil
case *sql.Rows:
data, err := scanRows(r)
if err != nil {
return nil, err
}
return context.WithValue(ctx, ContextKey(s.name), data), nil
case *sql.Row:
var data any
if err = r.Scan(&data); err != nil {
return nil, err
}
return context.WithValue(ctx, ContextKey(s.name), data), nil
}
return context.WithValue(ctx, ContextKey(s.name), res), nil
}
func scanRows(rows *sql.Rows) (result []any, err error) {
defer func() {
err = errors.Join(err, rows.Close())
}()
cols, err := rows.Columns()
if err != nil {
return nil, err
}
if len(cols) == 1 {
var data any
for rows.Next() {
if err = rows.Scan(&data); err != nil {
return nil, err
}
result = append(result, data)
}
return result, nil
}
for rows.Next() {
items := make([]any, len(cols))
for i := range items {
items[i] = new(any)
}
if err := rows.Scan(items...); err != nil {
return nil, err
}
row := make(map[string]any, len(cols))
for i, c := range cols {
vv := items[i].(*any)
row[c] = *vv
}
result = append(result, row)
}
return result, nil
}
// Exec executes and optionally scans rows into the result.
func (s *Statement[Param, Dest, Result]) Exec(ctx context.Context, db DB, param Param) (result Result, err error) {
var (
expr Expression[Dest]
hash uint64
cached bool
)
if s.log != nil {
now := time.Now()
_, inTx := db.(*sql.Tx)
defer func() {
s.log(ctx, Info{
Template: s.name,
Location: s.location,
Duration: time.Since(now),
Mode: s.mode,
SQL: expr.SQL,
Args: expr.Args,
Err: err,
Cached: cached,
Transaction: inTx,
})
}()
}
if s.cache != nil {
hasher := hashPool.Get().(*xxhash.Digest)
defer func() {
hasher.Reset()
hashPool.Put(hasher)
}()
err = s.hasher(param, hasher)
if err != nil {
return result, fmt.Errorf("statement at %s: %w", s.location, err)
}
hash = hasher.Sum64()
expr, cached = s.cache.Get(hash)
if cached {
result, err = s.exec(ctx, db, expr)
if err != nil {
return result, fmt.Errorf("statement at %s: %w", s.location, err)
}
return result, nil
}
}
r := s.pool.Get().(*runner[Param, Dest])
defer func() {
r.reset()
s.pool.Put(r)
}()
r.ctx = ctx
expr, err = r.expr(param)
if err != nil {
return result, fmt.Errorf("statement at %s: %w", s.location, err)
}
if s.cache != nil {
_ = s.cache.Add(hash, expr)
}
result, err = s.exec(ctx, db, expr)
if err != nil {
return result, fmt.Errorf("statement at %s: %w", s.location, err)
}
return result, nil
}
func getDestAccessor[Dest any](field string) (reflect.Type, func(*Dest) reflect.Value, error) {
t, acc, err := getTypeAccessor(reflect.TypeFor[Dest](), field)
if err != nil {
return t, nil, err
}
return t, func(d *Dest) reflect.Value {
return acc(reflect.ValueOf(d).Elem())
}, nil
}
func getTypeAccessor(t reflect.Type, field string) (reflect.Type, func(reflect.Value) reflect.Value, error) {
indices := []int{}
for t.Kind() == reflect.Pointer {
t = t.Elem()
indices = append(indices, -1)
continue
}
if field == "" {
return t, getAccessor(indices), nil
}
parts := strings.Split(field, ".")
for _, part := range parts {
switch t.Kind() {
default:
return t, nil, fmt.Errorf("invalid field access on type %s", t.Name())
case reflect.Struct:
sf, found := t.FieldByName(part)
if !found {
return t, nil, fmt.Errorf("field %s not found in struct %s", field, t.Name())
}
if !sf.IsExported() {
return t, nil, fmt.Errorf("field %s in struct %s is not exported", field, t.Name())
}
indices = append(indices, sf.Index[0])
t = sf.Type
}
for t.Kind() == reflect.Pointer {
t = t.Elem()
indices = append(indices, -1)
continue
}
}
return t, getAccessor(indices), nil
}
func getAccessor(indices []int) func(reflect.Value) reflect.Value {
return func(v reflect.Value) reflect.Value {
for _, idx := range indices {
if idx < 0 {
if v.IsNil() {
v.Set(reflect.New(v.Type().Elem()))
}
v = v.Elem()
continue
}
v = v.Field(idx)
}
return v
}
}
var (
scannerType = reflect.TypeFor[sql.Scanner]()
timeType = reflect.TypeFor[time.Time]()
)
type scannerStore[Dest any] struct {
mu sync.RWMutex
store map[string]Scanner[Dest]
}
func (s *scannerStore[Dest]) get(key string) (Scanner[Dest], bool) {
s.mu.RLock()
scanner, ok := s.store[key]
s.mu.RUnlock()
return scanner, ok
}
func (s *scannerStore[Dest]) set(key string, scanner Scanner[Dest]) {
s.mu.Lock()
s.store[key] = scanner
s.mu.Unlock()
}
func scan[Dest any](field string) (scanner Scanner[Dest], err error) {
typ, acc, err := getDestAccessor[Dest](field)
if err != nil {
return nil, err
}
pointerType := reflect.PointerTo(typ)
if pointerType.Implements(scannerType) {
return func() (any, func(dest *Dest) error) {
var src []byte
return &src, func(dest *Dest) error {
return acc(dest).Addr().Interface().(sql.Scanner).Scan(src)
}
}, nil
}
switch typ.Kind() {
case reflect.String:
return func() (any, func(dest *Dest) error) {
var src string
return &src, func(dest *Dest) error {
acc(dest).SetString(src)
return nil
}
}, nil
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return func() (any, func(dest *Dest) error) {
var src int64
return &src, func(dest *Dest) error {
acc(dest).SetInt(src)
return nil
}
}, nil
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return func() (any, func(dest *Dest) error) {
var src uint64
return &src, func(dest *Dest) error {
acc(dest).SetUint(src)
return nil
}
}, nil
case reflect.Float32, reflect.Float64:
return func() (any, func(dest *Dest) error) {
var src float64
return &src, func(dest *Dest) error {
acc(dest).SetFloat(src)
return nil
}
}, nil
case reflect.Bool:
return func() (any, func(dest *Dest) error) {
var src bool
return &src, func(dest *Dest) error {
acc(dest).SetBool(src)
return nil
}
}, nil
}
if typ != timeType {
return func() (any, func(dest *Dest) error) {
var src time.Time
return &src, func(dest *Dest) error {
acc(dest).Set(reflect.ValueOf(src).Convert(typ))
return nil
}
}, nil
}
return nil, fmt.Errorf("invalid type %s for Scan: want string|int|float|bool|time.Time|sql.Scanner", typ)
}
func (s *scannerStore[Dest]) scan(field string) (scanner Scanner[Dest], err error) {
var (
ok bool
key = "scan:" + field
)
scanner, ok = s.get(key)
if ok {
return scanner, nil
}
defer func() {
if err == nil {
s.set(key, scanner)
}
}()
return scan[Dest](field)
}
var byteSliceType = reflect.TypeFor[[]byte]()
func (s *scannerStore[Dest]) scanJSON(field string) (scanner Scanner[Dest], err error) {
var (
ok bool
key = "scanJSON:" + field
)
scanner, ok = s.get(key)
if ok {
return scanner, nil
}
defer func() {