-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhey_way.go
More file actions
1303 lines (1124 loc) · 31.5 KB
/
hey_way.go
File metadata and controls
1303 lines (1124 loc) · 31.5 KB
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
// About *Way
package hey
import (
"context"
"database/sql"
"encoding/hex"
"errors"
"fmt"
"maps"
"os"
"reflect"
"sync"
"time"
"github.com/cd365/hey/v7/cst"
)
// hexEncodeToString Convert binary byte array to hexadecimal string.
func hexEncodeToString(values []byte) string {
return hex.EncodeToString(values)
}
// argValueToString Convert a single SQL parameter value into a visual string.
func argValueToString(i any) string {
if i == nil {
return cst.NULL
}
t, v := reflect.TypeOf(i), reflect.ValueOf(i)
k := t.Kind()
for k == reflect.Pointer {
if v.IsNil() {
return cst.NULL
}
t, v = t.Elem(), v.Elem()
k = t.Kind()
}
// any base type to string.
tmp := v.Interface()
switch k {
case reflect.Bool:
return fmt.Sprintf("%t", tmp)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return fmt.Sprintf("%d", tmp)
case reflect.Float32, reflect.Float64:
return fmt.Sprintf("%f", tmp)
case reflect.String:
return fmt.Sprintf("'%s'", tmp)
default:
if bts, ok := tmp.([]byte); ok {
if bts == nil {
return cst.NULL
}
return fmt.Sprintf("'%s'", hexEncodeToString(bts))
}
return fmt.Sprintf("'%v'", tmp)
}
}
// SQLToString Use parameter values to replace placeholders in SQL statements and build a visual SQL script.
// Warning: Binary byte slice will be converted to hexadecimal strings.
func SQLToString(script *SQL) string {
if script == nil {
return cst.Empty
}
counts := len(script.Args)
if counts == 0 {
return script.Prepare
}
index := 0
origin := []byte(script.Prepare)
result := poolGetStringBuilder()
defer poolPutStringBuilder(result)
length := len(origin)
c63 := cst.Placeholder[0]
for i := 0; i < length; i++ {
if origin[i] == c63 && index < counts {
result.WriteString(argValueToString(script.Args[index]))
index++
} else {
result.WriteByte(origin[i])
}
}
return result.String()
}
// transaction Information for transaction.
type transaction struct {
// ctx Context object.
ctx context.Context
// way Original *Way object.
way *Way
// tx Transaction object.
tx *sql.Tx
// track Tracking transaction.
track *MyTrack
// mutex Mutex lock.
mutex sync.Mutex
// script List of SQL statements that have been executed within a transaction.
script []*MyTrack
}
// addScript Add information about the executed SQL statement.
func (s *transaction) addScript(script *MyTrack) *transaction {
s.mutex.Lock()
defer s.mutex.Unlock()
s.script = append(s.script, script)
return s
}
// write Recording transaction logs.
func (s *transaction) write() {
track := s.way.track
if track == nil {
return
}
if s.track.TimeEnd.IsZero() {
s.track.TimeEnd = time.Now()
}
defer track.Track(s.track.Context, s.track)
for _, v := range s.script {
v.Script = SQLToString(NewSQL(v.Prepare, v.Args...))
v.TxId = s.track.TxId
v.TxMsg = s.track.TxMsg
v.TxState = s.track.TxState
track.Track(v.Context, v)
}
}
// Manual For handling different types of databases.
type Manual struct {
// DatabaseType Database type value.
DatabaseType cst.DatabaseType
// Replacer SQL Identifier Replacer.
Replacer Replacer
// Prepare Adjust the SQL statement format to fit the current database format.
Prepare func(prepare string) string
// InsertOneReturningId Insert a record and return the id value of the inserted data.
InsertOneReturningId func(r SQLReturning)
// More custom methods can be added here to achieve the same function using different databases.
}
// InsertOneAndScanInsertId INSERT INTO xxx RETURNING id
func (s *Manual) InsertOneAndScanInsertId() func(r SQLReturning) {
return func(r SQLReturning) {
id := cst.Id
if replace := s.Replacer; replace != nil {
id = replace.Get(id)
}
r.Returning(id)
r.SetExecute(r.QueryRowScan())
}
}
// InsertOneGetLastInsertId INSERT INTO xxx; sql.Result
func (s *Manual) InsertOneGetLastInsertId() func(r SQLReturning) {
return func(r SQLReturning) {
r.SetExecute(r.LastInsertId())
}
}
// prepare63236 Replace '?' in the SQL statement with '$n'.
func prepare63236(prepare string) string {
latest := poolGetStringBuilder()
defer poolPutStringBuilder(latest)
origin := []byte(prepare)
length := len(origin)
c36 := cst.Dollar[0] // $
c63 := cst.Placeholder[0] // ?
num := 0
for i := 0; i < length; i++ {
if origin[i] == c63 {
num++
fmt.Fprintf(latest, "%c%d", c36, num)
} else {
latest.WriteByte(origin[i])
}
}
return latest.String()
}
// manualPostgresql Postgresql manual.
func manualPostgresql() Manual {
manual := Manual{}
manual.DatabaseType = cst.Postgresql
manual.Prepare = prepare63236
manual.InsertOneReturningId = manual.InsertOneAndScanInsertId()
return manual
}
// manualSqlite Sqlite manual.
func manualSqlite() Manual {
manual := Manual{}
manual.DatabaseType = cst.Sqlite
manual.InsertOneReturningId = manual.InsertOneGetLastInsertId()
return manual
}
// manualMysql Mysql manual.
func manualMysql() Manual {
manual := Manual{}
manual.DatabaseType = cst.Mysql
manual.InsertOneReturningId = manual.InsertOneGetLastInsertId()
return manual
}
// Config Configuration structure.
type Config struct {
// Manual For handling different types of databases.
Manual Manual
// TxOptions Start transaction options.
TxOptions *sql.TxOptions
// MapScanner Custom MapScan, cannot be set to nil.
MapScanner MapScanner
// RowsScan For scanning data into structure, cannot be set to nil.
RowsScan func(rows *sql.Rows, result any, tag string) error
// NewSQLLabel Create SQLLabel, cannot be set to nil.
NewSQLLabel func(way *Way) SQLLabel
// NewSQLWith Create SQLWith, cannot be set to nil.
NewSQLWith func(way *Way) SQLWith
// NewSQLSelect Create SQLSelect, cannot be set to nil.
NewSQLSelect func(way *Way) SQLSelect
// NewSQLTable Create SQLAlias, cannot be set to nil.
NewSQLTable func(way *Way, table any) SQLAlias
// NewSQLJoin Create SQLJoin, cannot be set to nil.
NewSQLJoin func(way *Way, query SQLSelect) SQLJoin
// NewSQLJoinOn Create SQLJoinOn, cannot be set to nil.
NewSQLJoinOn func(way *Way) SQLJoinOn
// NewSQLFilter Create Filter, cannot be set to nil.
NewSQLFilter func(way *Way) Filter
// NewSQLGroupBy Create SQLGroupBy, cannot be set to nil.
NewSQLGroupBy func(way *Way) SQLGroupBy
// NewSQLWindow Create SQLWindow, cannot be set to nil.
NewSQLWindow func(way *Way) SQLWindow
// NewSQLOrderBy Create SQLOrderBy, cannot be set to nil.
NewSQLOrderBy func(way *Way) SQLOrderBy
// NewSQLLimit Create SQLLimit, cannot be set to nil.
NewSQLLimit func(way *Way) SQLLimit
// NewSQLInsert Create SQLInsert, cannot be set to nil.
NewSQLInsert func(way *Way) SQLInsert
// NewSQLValues Create SQLValues, cannot be set to nil.
NewSQLValues func(way *Way) SQLValues
// NewSQLReturning Create SQLReturning, cannot be set to nil.
NewSQLReturning func(way *Way, insert Maker) SQLReturning
// NewSQLOnConflict Create SQLOnConflict, cannot be set to nil.
NewSQLOnConflict func(way *Way, insert Maker) SQLOnConflict
// NewSQLOnConflictUpdateSet Create SQLOnConflictUpdateSet, cannot be set to nil.
NewSQLOnConflictUpdateSet func(way *Way) SQLOnConflictUpdateSet
// NewSQLUpdateSet Create SQLUpdateSet, cannot be set to nil.
NewSQLUpdateSet func(way *Way) SQLUpdateSet
// NewSQLCase Create SQLCase, cannot be set to nil.
NewSQLCase func(way *Way) SQLCase
// NewSQLWindowFuncFrame Create SQLWindowFuncFrame, cannot be set to nil.
NewSQLWindowFuncFrame func(frame string) SQLWindowFuncFrame
// NewSQLWindowFuncOver Create SQLWindowFuncOver, cannot be set to nil.
NewSQLWindowFuncOver func(way *Way) SQLWindowFuncOver
// NewMulti Create Multi, cannot be set to nil.
NewMulti func(way *Way) Multi
// NewQuantifier Create Quantifier, cannot be set to nil.
NewQuantifier func(filter Filter) Quantifier
// NewExtractFilter Create ExtractFilter, cannot be set to nil.
NewExtractFilter func(filter Filter) ExtractFilter
// NewTimeFilter Create TimeFilter, cannot be set to nil.
NewTimeFilter func(filter Filter) TimeFilter
// NewTableColumn Create TableColumn, cannot be set to nil.
NewTableColumn func(way *Way, tableName ...string) TableColumn
// ToSQLSelect Construct a query statement, cannot be set to nil.
ToSQLSelect func(s MakeSQL) *SQL
// ToSQLInsert Construct an insert statement, cannot be set to nil.
ToSQLInsert func(s MakeSQL) *SQL
// ToSQLDelete Construct a delete statement, cannot be set to nil.
ToSQLDelete func(s MakeSQL) *SQL
// ToSQLUpdate Construct an update statement, cannot be set to nil.
ToSQLUpdate func(s MakeSQL) *SQL
// ToSQLSelectExists Construct an exists statement, cannot be set to nil.
ToSQLSelectExists func(s MakeSQL) *SQL
// ToSQLSelectCount Construct a count statement, cannot be set to nil.
ToSQLSelectCount func(s MakeSQL) *SQL
// ScanTag Scan data to tag mapping on structure.
ScanTag string
// LabelsSeparator Separator string between multiple labels.
LabelsSeparator string
// TableMethodName Custom method name to get table name.
TableMethodName string
// InsertForbidColumn List of columns ignored when inserting data.
InsertForbidColumn []string
// UpdateForbidColumn List of columns ignored when updating data.
UpdateForbidColumn []string
// MaxLimit Check the maximum allowed LIMIT value; a value less than or equal to 0 will be unlimited.
MaxLimit int64
// MaxOffset Check the maximum allowed OFFSET value; a value less than or equal to 0 will be unlimited.
MaxOffset int64
// DefaultPageSize The default value of limit when querying data with the page parameter for pagination.
DefaultPageSize int64
// DeleteRequireWhere Deletion of data must be filtered using conditions.
DeleteRequireWhere bool
// UpdateRequireWhere Updated data must be filtered using conditions.
UpdateRequireWhere bool
}
func (s *Config) fully(way *Way) bool {
if way.db != nil {
if s.Manual.DatabaseType == cst.Empty {
return false
}
for _, value := range []any{
s.MapScanner,
s.RowsScan,
} {
if value == nil {
return false
}
}
if s.ScanTag == cst.Empty {
return false
}
}
for _, value := range []any{
s.NewSQLLabel,
s.NewSQLWith,
s.NewSQLSelect,
s.NewSQLTable,
s.NewSQLJoin,
s.NewSQLJoinOn,
s.NewSQLFilter,
s.NewSQLGroupBy,
s.NewSQLWindow,
s.NewSQLOrderBy,
s.NewSQLLimit,
s.NewSQLInsert,
s.NewSQLValues,
s.NewSQLReturning,
s.NewSQLOnConflict,
s.NewSQLOnConflictUpdateSet,
s.NewSQLUpdateSet,
s.NewSQLCase,
s.NewSQLWindowFuncFrame,
s.NewSQLWindowFuncOver,
s.NewMulti,
s.NewQuantifier,
s.NewExtractFilter,
s.NewTimeFilter,
s.NewTableColumn,
s.ToSQLSelect,
s.ToSQLInsert,
s.ToSQLDelete,
s.ToSQLUpdate,
s.ToSQLSelectExists,
s.ToSQLSelectCount,
} {
if value == nil {
return false
}
}
return true
}
const (
DefaultTag = "db"
TableMethodName = "Table"
)
// ConfigDefault Default configuration.
// If there is no highly customized configuration, please use it and set the Manual property for the specific database.
func ConfigDefault() *Config {
return &Config{
MapScanner: NewMapScanner(),
RowsScan: RowsScan,
NewSQLLabel: newSQLLabel,
NewSQLWith: newSQLWith,
NewSQLSelect: newSQLSelect,
NewSQLTable: newSQLTable,
NewSQLJoin: newSQLJoin,
NewSQLJoinOn: newSQLJoinOn,
NewSQLFilter: newSQLFilter,
NewSQLGroupBy: newSQLGroupBy,
NewSQLWindow: newSQLWindow,
NewSQLOrderBy: newSQLOrderBy,
NewSQLLimit: newSQLLimit,
NewSQLInsert: newSQLInsert,
NewSQLValues: newSQLValues,
NewSQLReturning: newSQLReturning,
NewSQLOnConflict: newSQLOnConflict,
NewSQLOnConflictUpdateSet: newSQLOnConflictUpdateSet,
NewSQLUpdateSet: newSQLUpdateSet,
NewSQLCase: NewSQLCase,
NewSQLWindowFuncFrame: NewSQLWindowFuncFrame,
NewSQLWindowFuncOver: NewSQLWindowFuncOver,
NewMulti: NewMulti,
NewQuantifier: newQuantifier,
NewExtractFilter: newExtractFilter,
NewTimeFilter: newTimeFilter,
NewTableColumn: NewTableColumn,
ToSQLSelect: toSQLSelect,
ToSQLInsert: toSQLInsert,
ToSQLDelete: toSQLDelete,
ToSQLUpdate: toSQLUpdate,
ToSQLSelectExists: toSQLSelectExists,
ToSQLSelectCount: toSQLSelectCount,
ScanTag: DefaultTag,
LabelsSeparator: cst.Comma,
TableMethodName: TableMethodName,
InsertForbidColumn: []string{cst.Id},
UpdateForbidColumn: []string{cst.Id},
MaxLimit: 10000,
MaxOffset: 100000,
DefaultPageSize: 10,
DeleteRequireWhere: true,
UpdateRequireWhere: true,
}
}
// ConfigDefaultPostgresql Postgresql default configuration.
func ConfigDefaultPostgresql() *Config {
cfg := ConfigDefault()
cfg.Manual = manualPostgresql()
return cfg
}
// ConfigDefaultMysql Mysql default configuration.
func ConfigDefaultMysql() *Config {
cfg := ConfigDefault()
cfg.Manual = manualMysql()
return cfg
}
// ConfigDefaultSqlite Sqlite default configuration.
func ConfigDefaultSqlite() *Config {
cfg := ConfigDefault()
cfg.Manual = manualSqlite()
return cfg
}
type Option func(way *Way)
func WithConfig(cfg *Config) Option {
return func(way *Way) {
if cfg != nil && cfg.fully(way) {
way.cfg = cfg
}
}
}
func WithDatabase(db *sql.DB) Option {
return func(way *Way) {
way.db = db
}
}
func WithTrack(track Track) Option {
return func(way *Way) {
way.track = track
}
}
func WithReader(reader Reader) Option {
return func(way *Way) {
way.reader = reader
}
}
// Reader Separate read and write, when you distinguish between reading and writing, please do not use the same object for both reading and writing.
type Reader interface {
// Read Get an object for read.
Read() *Way
}
type Way struct {
// cfg Configuration information, cannot be set to nil.
cfg *Config
// db Database object.
db *sql.DB
// track Tracing SQL statements.
track Track
// transaction Transaction object.
transaction *transaction
// reader A *Way object used only for reading data.
reader Reader
// isRead Is the current object a read-only object?
isRead bool
}
// NewWay Create a *Way object.
func NewWay(options ...Option) *Way {
way := &Way{}
for _, option := range options {
option(way)
}
if way.cfg == nil {
WithConfig(ConfigDefault())(way)
}
return way
}
func (s *Way) Config() *Config {
return s.cfg
}
func (s *Way) Database() *sql.DB {
return s.db
}
func (s *Way) Track() Track {
return s.track
}
func (s *Way) Reader() Reader {
return s.reader
}
func (s *Way) Read() *Way {
if s.reader == nil {
return s
}
result := s.reader.Read()
result.isRead = true
return result
}
// IsRead is an object for read?
func (s *Way) IsRead() bool {
return s.isRead
}
// Replace get a single identifier mapping value, if it does not exist, return the original value.
func (s *Way) Replace(key string) string {
replace := s.cfg.Manual.Replacer
if replace != nil {
return replace.Get(key)
}
return key
}
// ReplaceAll get multiple identifier mapping values, return the original value if none exists.
func (s *Way) ReplaceAll(keys []string) []string {
replace := s.cfg.Manual.Replacer
if replace != nil {
return replace.GetAll(keys)
}
return keys
}
// begin Open a transaction.
func (s *Way) begin(ctx context.Context, conn *sql.Conn, opts ...*sql.TxOptions) (tx *Way, err error) {
if s.db == nil {
err = ErrDatabaseIsNil
return
}
tmp := *s
tx = &tmp
opt := tx.cfg.TxOptions
length := len(opts)
for i := length - 1; i >= 0; i-- {
if opts[i] != nil {
opt = opts[i]
break
}
}
tx.transaction = &transaction{
ctx: ctx,
way: tx,
}
if conn != nil {
tx.transaction.tx, err = conn.BeginTx(ctx, opt)
} else {
tx.transaction.tx, err = tx.db.BeginTx(ctx, opt)
}
if err != nil {
tx = nil
return
}
start := time.Now()
tracked := trackTransaction(ctx, start)
tracked.TxId = fmt.Sprintf("%d%s%d%s%p", start.UnixNano(), cst.Point, os.Getpid(), cst.Point, tx.transaction)
tracked.TxState = cst.BEGIN
tx.transaction.track = tracked
if s.track != nil {
s.track.Track(ctx, tracked)
}
return
}
// commit commit-transaction.
func (s *Way) commit() (err error) {
if s.transaction == nil {
return ErrTransactionIsNil
}
tx := s.transaction
if tx.track != nil {
tx.track.TxState = cst.COMMIT
}
defer func() {
tx.write()
s.transaction = nil
}()
err = tx.tx.Commit()
if tx.track != nil {
tx.track.Err = err
}
return err
}
// rollback rollback-transaction.
func (s *Way) rollback() (err error) {
if s.transaction == nil {
return ErrTransactionIsNil
}
tx := s.transaction
if tx.track != nil {
tx.track.TxState = cst.ROLLBACK
}
defer func() {
tx.write()
s.transaction = nil
}()
err = tx.tx.Rollback()
if tx.track != nil {
tx.track.Err = err
}
return err
}
// Begin Open a transaction.
func (s *Way) Begin(ctx context.Context, opts ...*sql.TxOptions) (*Way, error) {
return s.begin(ctx, nil, opts...)
}
// BeginConn Open a transaction using *sql.Conn.
func (s *Way) BeginConn(ctx context.Context, conn *sql.Conn, opts ...*sql.TxOptions) (*Way, error) {
return s.begin(ctx, conn, opts...)
}
// Commit Transaction commit.
func (s *Way) Commit() error {
return s.commit()
}
// Rollback Transaction rollback.
func (s *Way) Rollback() error {
return s.rollback()
}
// IsInTransaction is it currently in a transaction?
func (s *Way) IsInTransaction() bool {
return s.transaction != nil
}
// TransactionMessage set the prompt for the current transaction, can only be set once.
func (s *Way) TransactionMessage(message string) *Way {
if s.transaction == nil {
return s
}
if s.transaction.track.TxMsg == cst.Empty {
s.transaction.track.TxMsg = message
}
return s
}
// newTransaction start a new transaction and execute a set of SQL statements atomically.
func (s *Way) newTransaction(ctx context.Context, fx func(tx *Way) error, opts ...*sql.TxOptions) (err error) {
tx := (*Way)(nil)
tx, err = s.begin(ctx, nil, opts...)
if err != nil {
return
}
ok := false
defer func() {
if err == nil && ok {
if e := tx.commit(); e != nil {
err = e
}
} else {
if e := tx.rollback(); e != nil {
if err == nil {
err = e
}
}
}
}()
if err = fx(tx); err != nil {
return
}
ok = true
return
}
// Transaction atomically executes a set of SQL statements. If a transaction has been opened, the opened transaction instance will be used.
func (s *Way) Transaction(ctx context.Context, fx func(tx *Way) error, opts ...*sql.TxOptions) error {
if s.IsInTransaction() {
return fx(s)
}
return s.newTransaction(ctx, fx, opts...)
}
// TransactionNew starts a new transaction and executes a set of SQL statements atomically. Does not care whether the current transaction instance is open.
func (s *Way) TransactionNew(ctx context.Context, fx func(tx *Way) error, opts ...*sql.TxOptions) error {
return s.newTransaction(ctx, fx, opts...)
}
// TransactionRetry starts a new transaction and executes a set of SQL statements atomically. Does not care whether the current transaction instance is open.
func (s *Way) TransactionRetry(ctx context.Context, retries int, fx func(tx *Way) error, opts ...*sql.TxOptions) (err error) {
if retries <= 0 {
err = ErrUnexpectedParameterValue
return
}
for i := 0; i < retries; i++ {
if err = s.newTransaction(ctx, fx, opts...); err == nil {
break
}
}
return
}
// Now get current time, the transaction open status will get the same time.
func (s *Way) Now() time.Time {
if s.IsInTransaction() {
return s.transaction.track.TimeStart
}
return time.Now()
}
// Stmt is a wrapper for *sql.Stmt.
type Stmt struct {
// way Original *Way object.
way *Way
// stmt Prepared statement.
stmt *sql.Stmt
// prepare The raw SQL statement to create *sql.Stmt.
prepare string
}
// Close closes the statement.
func (s *Stmt) Close() (err error) {
if s.stmt != nil {
err = s.stmt.Close()
}
return err
}
// Query executes a prepared query statement with the given arguments and processes the query result set through anonymous functions (query).
func (s *Stmt) Query(ctx context.Context, query func(rows *sql.Rows) error, args ...any) (err error) {
var tracked *MyTrack
if track := s.way.track; track != nil {
tracked = trackSQL(ctx, s.prepare, args)
defer tracked.write(track, s.way)
}
var rows *sql.Rows
rows, err = s.stmt.QueryContext(ctx, args...)
if tracked != nil {
tracked.TimeEnd = time.Now()
tracked.Err = err
}
if err != nil {
return
}
defer func() {
if e := rows.Close(); e != nil && err == nil {
err = e
}
}()
err = query(rows)
if tracked != nil {
tracked.Err = err
}
return
}
// QueryRow executes a prepared query statement with the given arguments and processes the query result set through anonymous functions (query).
func (s *Stmt) QueryRow(ctx context.Context, query func(row *sql.Row) error, args ...any) error {
var tracked *MyTrack
if track := s.way.track; track != nil {
tracked = trackSQL(ctx, s.prepare, args)
defer tracked.write(track, s.way)
}
row := s.stmt.QueryRowContext(ctx, args...)
if tracked != nil {
tracked.TimeEnd = time.Now()
}
err := query(row)
if tracked != nil {
tracked.Err = err
}
return err
}
// Exec executes a prepared statement with the given arguments and
// returns a [sql.Result] summarizing the effect of the statement.
func (s *Stmt) Exec(ctx context.Context, args ...any) (sql.Result, error) {
var tracked *MyTrack
if track := s.way.track; track != nil {
tracked = trackSQL(ctx, s.prepare, args)
defer tracked.write(track, s.way)
}
result, err := s.stmt.ExecContext(ctx, args...)
if tracked != nil {
tracked.TimeEnd = time.Now()
tracked.Err = err
}
return result, err
}
// Execute executes a prepared statement with the given arguments and
// returns number of rows affected.
func (s *Stmt) Execute(ctx context.Context, args ...any) (int64, error) {
result, err := s.Exec(ctx, args...)
if err != nil {
return 0, err
}
return result.RowsAffected()
}
// Scan executes a prepared query statement with the given arguments and
// scan query results into the result receiving parameter.
func (s *Stmt) Scan(ctx context.Context, result any, args ...any) error {
return s.Query(ctx, func(rows *sql.Rows) error {
return s.way.cfg.RowsScan(rows, result, s.way.cfg.ScanTag)
}, args...)
}
// Prepare creates a prepared statement for later queries or executions.
// If a transaction has already started, the transaction object should be used first.
func (s *Way) Prepare(ctx context.Context, query string) (stmt *Stmt, err error) {
if s.db == nil {
return nil, ErrDatabaseIsNil
}
if query == cst.Empty {
return nil, ErrEmptySqlStatement
}
stmt = &Stmt{
way: s,
prepare: query,
}
if prepare := s.cfg.Manual.Prepare; prepare != nil {
query = prepare(query)
}
if s.IsInTransaction() {
stmt.stmt, err = s.transaction.tx.PrepareContext(ctx, query)
} else {
stmt.stmt, err = s.db.PrepareContext(ctx, query)
}
if err != nil {
return nil, err
}
return stmt, nil
}
// RowsScan scan the query result set into the received parameter result.
func (s *Way) RowsScan(result any) func(rows *sql.Rows) error {
return func(rows *sql.Rows) error {
return s.cfg.RowsScan(rows, result, s.cfg.ScanTag)
}
}
// Query executes a query statement.
func (s *Way) Query(ctx context.Context, maker Maker, query func(rows *sql.Rows) error) (err error) {
script := maker.ToSQL()
var stmt *Stmt
stmt, err = s.Prepare(ctx, script.Prepare)
if err != nil {
return
}
defer func() {
if e := stmt.Close(); e != nil && err == nil {
err = e
}
}()
err = stmt.Query(ctx, query, script.Args...)
return
}
// RowScan scan a row of query results.
func (s *Way) RowScan(dest ...any) func(row *sql.Row) error {
return func(row *sql.Row) error {
return row.Scan(dest...)
}
}
// QueryRow executes a statement and return row data, typically, these are INSERT, UPDATE and DELETE.
func (s *Way) QueryRow(ctx context.Context, maker Maker, query func(row *sql.Row) error) (err error) {
script := maker.ToSQL()
var stmt *Stmt
stmt, err = s.Prepare(ctx, script.Prepare)
if err != nil {
return
}
defer func() {
if e := stmt.Close(); e != nil && err == nil {
err = e
}
}()
err = stmt.QueryRow(ctx, query, script.Args...)
return
}
// QueryExists executes a query statement to check if the data exists.
func (s *Way) QueryExists(ctx context.Context, maker Maker) (bool, error) {
// SQL statement format: SELECT EXISTS ( subquery ) AS a
// SELECT EXISTS ( SELECT 1 FROM example_table ) AS a
// SELECT EXISTS ( SELECT 1 FROM example_table WHERE ( id > 0 ) ) AS a
// SELECT EXISTS ( ( SELECT 1 FROM example_table WHERE ( column1 = 'value1' ) ) UNION ALL ( SELECT 1 FROM example_table WHERE ( column2 = 'value2' ) ) ) AS a
// Database drivers typically return a boolean or integer value, where 0 indicates that the data does not exist and 1 indicates that the data exists.
var result any
err := s.Query(ctx, maker, func(rows *sql.Rows) error {
for rows.Next() {
err := rows.Scan(&result)
if err != nil {
return err
}
}
return nil
})
if err != nil {
return false, err
}
switch value := result.(type) {
case bool:
return value, nil
case int:
return value != 0, nil
case int8: