-
Notifications
You must be signed in to change notification settings - Fork 5
/
mysql.go
2112 lines (1822 loc) · 63.8 KB
/
mysql.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 mysql
/*
* Copyright 2020-2021 Aldelo, LP
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import (
"database/sql"
"errors"
"fmt"
"github.com/aldelo/common/wrapper/xray"
awsxray "github.com/aws/aws-xray-sdk-go/xray"
"strings"
"time"
util "github.com/aldelo/common"
"github.com/jmoiron/sqlx"
// this package is used by database/sql as we are wrapping the sql access functionality in this utility package
_ "github.com/go-sql-driver/mysql"
)
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// MySql struct Usage Hint
// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
/*
***************************************************************************************************************
First, Create "../model/global.go"
***************************************************************************************************************
package model
import (
"errors"
"time"
data "github.com/aldelo/common/wrapper/mysql"
)
// package level accessible to the mysql server database object
var db *data.MySql
// SetDB allows code outside of package to set the mysql database reference
func SetDB(dbx *data.MySql) {
db = dbx
}
// BeginTran starts db transaction
func BeginTran() {
if db != nil {
db.Begin()
}
}
// CommitTran commits db transaction
func CommitTran() {
if db != nil {
db.Commit()
}
}
// RollbackTran rolls back db transaction
func RollbackTran() {
if db != nil {
db.Rollback()
}
}
*/
/*
***************************************************************************************************************
Second, Prepare DB Object for Use in "../main.go"
***************************************************************************************************************
package main
import (
...
data "github.com/aldelo/common/wrapper/mysql"
"???/model" // ??? is path to model package
...
)
...
func main() {
...
// ========================================
// setup database connection
// ========================================
//
// declare mysql server object
//
s := new(data.MySql)
//
// set mysql dsn fields
//
s.Host = "" // from aws aurora endpoint
s.Port = 0 // custom port number if applicable (0 will ignore this field)
s.Database = "" // database name
s.UserName = "" // database server user name
s.Password = "" // database server user password
//
// open mysql server database connection
//
if err := s.Open(); err != nil {
s.Close()
} else {
// add mysql db object to model global
model.SetDB(&s)
// defer db clean up upon execution ends
defer model.SetDB(nil)
defer s.Close()
}
...
}
*/
/*
***************************************************************************************************************
Third, Using MySql Struct
***************************************************************************************************************
package model
import (
"bytes"
"database/sql" // this import is needed for db struct tags
"errors"
"time"
util "github.com/aldelo/common"
)
// create a struct, and use db struct tags to identify parameter names
// db struct tags can contain ,required ,size=# if string
type Customer struct {
CustomerID int `db:"customerID"`
CompanyName string `db:"companyName"`
}
// when composing sql statements, if statement is long, use bytes.Buffer (or use /QueryBuilder.go)
var b bytes.Buffer
b.WriteString("xyz ")
b.WriteString("123")
v := b.String() // v = xyz 123
// for insert, update, logical delete, physical delete
// use the appropriate functions from db struct, located in model/global.go
// the db struct is global in scope for code files within model package
db.GetStruct(...)
db.GetSliceStruct(...)
// etc
*/
// ================================================================================================================
// STRUCTS
// ================================================================================================================
// MySql struct encapsulates the MySql server database access functionality by wrapping Sqlx package with top level methods
// Charset = utf8, utf8mb4 (< Default)
// Collation = utf8mb4_general_ci (< Default), utf8_general_ci
// ...Timeout = must be decimal number with unit suffix (ms, s, m, h), such as "30s", "0.5m", "1m30s"
type MySql struct {
// MySql server connection properties
UserName string
Password string
Host string
Port int
Database string
Charset string // utf8, utf8mb4
Collation string // utf8mb4_general_ci, utf8_general_ci
ConnectTimeout string // must be decimal number with unit suffix (ms, s, m, h), such as "30s", "0.5m", "1m30s"
ReadTimeout string // must be decimal number with unit suffix (ms, s, m, h), such as "30s", "0.5m", "1m30s"
WriteTimeout string // must be decimal number with unit suffix (ms, s, m, h), such as "30s", "0.5m", "1m30s"
RejectReadOnly bool
// mysql server state object
db *sqlx.DB
tx *sqlx.Tx
lastPing time.Time
_parentSegment *xray.XRayParentSegment
_xrayTxSeg *xray.XSegment
}
// MySqlResult defines sql action query result info
// [ Notes ]
// 1) NewlyInsertedID = ONLY FOR INSERT, ONLY IF AUTO_INCREMENT PRIMARY KEY (Custom PK ID Will Have This Field as 0 Always)
type MySqlResult struct {
RowsAffected int64
NewlyInsertedID int64 // ONLY FOR INSERT, ONLY IF AUTO_INCREMENT PRIMARY KEY (Custom PK ID Will Have This Field as 0 Always)
Err error
}
// ================================================================================================================
// STRUCT FUNCTIONS
// ================================================================================================================
// ----------------------------------------------------------------------------------------------------------------
// utility functions
// ----------------------------------------------------------------------------------------------------------------
// GetDsn serializes MySql server dsn to connection string, for use in database connectivity
func (svr *MySql) GetDsn() (string, error) {
//
// first validate input
//
if len(svr.UserName) == 0 {
return "", errors.New("User Name is Required")
}
if len(svr.Password) == 0 {
return "", errors.New("Password is Required")
}
if len(svr.Host) == 0 {
return "", errors.New("MySQL Host Address is Required")
}
if len(svr.Database) == 0 {
return "", errors.New("MySQL Database Name is Required")
}
//
// now create mysql connection string
// format = [username[:password]@][protocol[(address)]]/dbname[?param1=value1&...¶mN=valueN]
//
str := svr.UserName + ":" + svr.Password
str += "@(" + svr.Host
if svr.Port > 0 {
str += ":" + util.Itoa(svr.Port)
}
str += ")/" + svr.Database
if util.LenTrim(svr.Charset) > 0 {
str += "?charset=" + svr.Charset
} else {
str += "?charset=utf8mb4"
}
if util.LenTrim(svr.Collation) > 0 {
str += "&collation=" + svr.Collation
} else {
str += "&collation=utf8mb4_general_ci"
}
str += "&parseTime=true"
if util.LenTrim(svr.ConnectTimeout) > 0 {
str += "&timeout=" + svr.ConnectTimeout
}
if util.LenTrim(svr.ReadTimeout) > 0 {
str += "&readTimeout=" + svr.ReadTimeout
}
if util.LenTrim(svr.WriteTimeout) > 0 {
str += "&writeTimeout=" + svr.WriteTimeout
}
if svr.RejectReadOnly {
str += "&rejectReadOnly=true"
}
// return to caller
return str, nil
}
// Open will open a database either as normal or with xray tracing,
// Open uses the dsn properties defined in the struct fields
func (svr *MySql) Open(parentSegment ...*xray.XRayParentSegment) error {
if !xray.XRayServiceOn() {
return svr.openNormal()
} else {
if len(parentSegment) > 0 {
svr._parentSegment = parentSegment[0]
}
return svr.openWithXRay()
}
}
// openNormal opens a database by connecting to it, using the dsn properties defined in the struct fields
func (svr *MySql) openNormal() error {
// declare
var str string
var err error
// get connect string
str, err = svr.GetDsn()
if err != nil {
svr.tx = nil
svr.db = nil
return err
}
// validate connection string
if len(str) == 0 {
svr.tx = nil
svr.db = nil
return errors.New("MySQL Server Connect String Generated Cannot Be Empty")
}
// now ready to open mysql database
svr.db, err = sqlx.Open("mysql", str)
if err != nil {
svr.tx = nil
svr.db = nil
return err
}
// test mysql server state object
if err = svr.db.Ping(); err != nil {
svr.tx = nil
svr.db = nil
return err
}
svr.lastPing = time.Now()
// upon open, transaction object already nil
svr.tx = nil
// mysql server state object successfully opened
return nil
}
// openWithXRay opens a database by connecting to it, wrap with XRay tracing, using the dsn properties defined in the struct fields
func (svr *MySql) openWithXRay() (err error) {
trace := xray.NewSegment("MySql-Open-Entry", svr._parentSegment)
defer trace.Close()
defer func() {
_ = trace.Seg.AddMetadata("DB-Host", svr.Host)
_ = trace.Seg.AddMetadata("DB-Database", svr.Database)
_ = trace.Seg.AddMetadata("DB-UserName", svr.UserName)
_ = trace.Seg.AddMetadata("DB-Charset", svr.Charset)
_ = trace.Seg.AddMetadata("DB-Collation", svr.Collation)
_ = trace.Seg.AddMetadata("DB-ConnectTimeout", svr.ConnectTimeout)
_ = trace.Seg.AddMetadata("DB-ReadTimeout", svr.ReadTimeout)
_ = trace.Seg.AddMetadata("DB-WriteTimeout", svr.WriteTimeout)
if err != nil {
_ = trace.Seg.AddError(err)
}
}()
// declare
var str string
trace.Capture("Get-DSN", func() error {
// get connect string
str, err = svr.GetDsn()
if err != nil {
svr.tx = nil
svr.db = nil
return err
} else {
return nil
}
})
if err != nil {
return err
}
// validate connection string
if len(str) == 0 {
svr.tx = nil
svr.db = nil
err = errors.New("MySQL Server Connect String Generated Cannot Be Empty")
return err
}
trace.Capture("Get-SQL-Context", func() error {
// now ready to open mysql database
baseDb, e := awsxray.SQLContext("mysql", str)
if e != nil {
svr.tx = nil
svr.db = nil
err = fmt.Errorf("openWithXRay() Failed During xray.SQLContext(): %s", e.Error())
return err
}
svr.db = sqlx.NewDb(baseDb, "mysql")
return nil
})
if err != nil {
return err
}
// test mysql server state object
subTrace := trace.NewSubSegment("MySql-Open-Ping")
defer subTrace.Close()
defer func() {
if err != nil {
_ = subTrace.Seg.AddError(err)
}
}()
subTrace.Capture("Ping", func() error {
if err = svr.db.PingContext(trace.Ctx); err != nil {
svr.tx = nil
svr.db = nil
return err
}
svr.lastPing = time.Now()
return nil
})
if err != nil {
return err
}
// upon open, transaction object already nil
svr.tx = nil
// mysql server state object successfully opened
return nil
}
// Close will close the database connection and set db to nil
func (svr *MySql) Close() error {
if svr.db != nil {
if err := svr.db.Close(); err != nil {
return err
}
// clean up
svr.tx = nil
svr.db = nil
svr._parentSegment = nil
svr._xrayTxSeg = nil
svr.lastPing = time.Time{}
return nil
}
return nil
}
// Ping tests if current database connection is still active and ready
func (svr *MySql) Ping() (err error) {
if svr.db == nil {
return errors.New("MySQL Server Not Connected")
}
if time.Now().Sub(svr.lastPing) < 90*time.Second {
return nil
}
if !xray.XRayServiceOn() {
if err := svr.db.Ping(); err != nil {
return err
}
} else {
trace := xray.NewSegment("MySql-Ping", svr._parentSegment)
defer trace.Close()
defer func() {
_ = trace.Seg.AddMetadata("Ping-Timestamp-UTC", time.Now().UTC())
if err != nil {
_ = trace.Seg.AddError(err)
}
}()
if err = svr.db.PingContext(trace.Ctx); err != nil {
return err
}
}
// database ok
svr.lastPing = time.Now()
return nil
}
// Begin starts a database transaction, and stores the transaction object until commit or rollback
func (svr *MySql) Begin() error {
// verify if the database connection is good
if err := svr.Ping(); err != nil {
if svr._xrayTxSeg != nil {
_ = svr._xrayTxSeg.Seg.AddError(err)
svr._xrayTxSeg.Close()
svr._xrayTxSeg = nil
}
return err
}
// does transaction already exist
if svr.tx != nil {
return errors.New("Transaction Already Started")
}
if !xray.XRayServiceOn() {
// begin transaction on database
tx, err := svr.db.Beginx()
if err != nil {
return err
}
// transaction begin successful,
// store tx into svr.tx field
svr.tx = tx
} else {
if svr._xrayTxSeg != nil {
svr._xrayTxSeg.Close()
}
svr._xrayTxSeg = xray.NewSegment("MySql-Transaction", svr._parentSegment)
subTrace := svr._xrayTxSeg.NewSubSegment("Begin-Transaction")
defer subTrace.Close()
// begin transaction on database
tx, err := svr.db.BeginTxx(subTrace.Ctx, &sql.TxOptions{
Isolation: 0,
ReadOnly: false,
})
if err != nil {
_ = subTrace.Seg.AddError(err)
_ = svr._xrayTxSeg.Seg.AddError(err)
svr._xrayTxSeg.Close()
svr._xrayTxSeg = nil
return err
}
// transaction begin successful,
// store tx into svr.tx field
svr.tx = tx
}
// return nil as success
return nil
}
// Commit finalizes a database transaction, and commits changes to database
func (svr *MySql) Commit() error {
// verify if the database connection is good
if err := svr.Ping(); err != nil {
if svr._xrayTxSeg != nil {
_ = svr._xrayTxSeg.Seg.AddError(err)
svr._xrayTxSeg.Close()
svr._xrayTxSeg = nil
}
return err
}
// does transaction already exist
if svr.tx == nil {
return errors.New("Transaction Does Not Exist")
}
if !xray.XRayServiceOn() {
// perform tx commit
if err := svr.tx.Commit(); err != nil {
return err
}
// commit successful
svr.tx = nil
svr._xrayTxSeg = nil
} else {
subTrace := svr._xrayTxSeg.NewSubSegment("Commit-Transaction")
defer subTrace.Close()
var outErr error
subTrace.Capture("Commit-Transaction-Do", func() error {
// perform tx commit
if outErr = svr.tx.Commit(); outErr != nil {
_ = subTrace.Seg.AddError(outErr)
return outErr
} else {
return nil
}
})
if outErr != nil {
return outErr
}
// commit successful
svr._xrayTxSeg.Close()
svr.tx = nil
svr._xrayTxSeg = nil
}
return nil
}
// Rollback cancels pending database changes for the current transaction and clears out transaction object
func (svr *MySql) Rollback() error {
// verify if the database connection is good
if err := svr.Ping(); err != nil {
if svr._xrayTxSeg != nil {
_ = svr._xrayTxSeg.Seg.AddError(err)
svr._xrayTxSeg.Close()
svr._xrayTxSeg = nil
}
return err
}
// does transaction already exist
if svr.tx == nil {
return errors.New("Transaction Does Not Exist")
}
if !xray.XRayServiceOn() {
// perform tx rollback
if err := svr.tx.Rollback(); err != nil {
svr.tx = nil
return err
}
// rollback successful
svr.tx = nil
svr._xrayTxSeg = nil
} else {
// perform tx rollback
defer func() {
svr.tx = nil
svr._xrayTxSeg.Close()
svr._xrayTxSeg = nil
}()
subTrace := svr._xrayTxSeg.NewSubSegment("RollBack-Transaction")
defer subTrace.Close()
var outErr error
subTrace.Capture("RollBack-Transaction-Do", func() error {
if outErr = svr.tx.Rollback(); outErr != nil {
_ = subTrace.Seg.AddError(outErr)
_ = svr._xrayTxSeg.Seg.AddError(outErr)
return outErr
} else {
return nil
}
})
if outErr != nil {
return outErr
}
}
return nil
}
func (svr *MySql) newTxSubSegment(name string) *xray.XSegment {
if xray.XRayServiceOn() {
if svr._xrayTxSeg == nil {
svr._xrayTxSeg = xray.NewSegment("MySql-Transaction", svr._parentSegment)
}
return svr._xrayTxSeg.NewSubSegment(name)
} else {
return nil
}
}
// ----------------------------------------------------------------------------------------------------------------
// query and marshal to 'struct slice' or 'struct' helpers
// ----------------------------------------------------------------------------------------------------------------
// GetStructSlice performs query with optional variadic parameters, and unmarshal result rows into target struct slice,
// in essence, each row of data is marshaled into the given struct, and multiple struct form the slice,
// such as: []Customer where each row represent a customer, and multiple customers being part of the slice
// [ Parameters ]
// dest = pointer to the struct slice or address of struct slice, this is the result of rows to be marshaled into struct slice
// query = sql query, optionally having parameters marked as ?, where each represents a parameter position
// args = conditionally required if positioned parameters are specified, must appear in the same order as the positional parameters
// [ Return Values ]
// 1) notFound = indicates no rows found in query (aka sql.ErrNoRows), if error is detected, notFound is always false
// 2) if error != nil, then error is encountered (if error == sql.ErrNoRows, then error is treated as nil, and dest is nil)
// [ Notes ]
// 1) if error == nil, and len(dest struct slice) == 0 then zero struct slice result
func (svr *MySql) GetStructSlice(dest interface{}, query string, args ...interface{}) (notFound bool, retErr error) {
// verify if the database connection is good
if err := svr.Ping(); err != nil {
return false, err
}
// perform select action, and unmarshal result rows into target struct slice
var err error
if svr.tx == nil {
// not in transaction mode
// query using db object
if !xray.XRayServiceOn() {
err = svr.db.Select(dest, query, args...)
} else {
trace := xray.NewSegment("MySql-Select-GetStructSlice", svr._parentSegment)
defer trace.Close()
defer func() {
_ = trace.Seg.AddMetadata("SQL-Query", query)
_ = trace.Seg.AddMetadata("SQL-Param-Values", args)
_ = trace.Seg.AddMetadata("Struct-Slice-Result", dest)
if err != nil {
_ = trace.Seg.AddError(err)
}
}()
err = svr.db.SelectContext(trace.Ctx, dest, query, args...)
}
} else {
// in transaction mode
// query using tx object
if !xray.XRayServiceOn() {
err = svr.tx.Select(dest, query, args...)
} else {
subTrace := svr.newTxSubSegment("Transaction-Select-GetStructSlice")
defer subTrace.Close()
defer func() {
_ = subTrace.Seg.AddMetadata("SQL-Query", query)
_ = subTrace.Seg.AddMetadata("SQL-Param-Values", args)
_ = subTrace.Seg.AddMetadata("Struct-Slice-Result", dest)
if err != nil {
_ = subTrace.Seg.AddError(err)
}
}()
err = svr.tx.SelectContext(subTrace.Ctx, dest, query, args...)
}
}
// if err is sql.ErrNoRows then treat as no error
if err != nil && err == sql.ErrNoRows {
notFound = true
dest = nil
err = nil
} else {
notFound = false
}
// return error
return notFound, err
}
// GetStruct performs query with optional variadic parameters, and unmarshal single result row into single target struct,
// such as: Customer struct where one row of data represent a customer
// [ Parameters ]
// dest = pointer to struct or address of struct, this is the result of row to be marshaled into this struct
// query = sql query, optionally having parameters marked as ?, where each represents a parameter position
// args = conditionally required if positioned parameters are specified, must appear in the same order as the positional parameters
// [ Return Values ]
// 1) notFound = indicates no rows found in query (aka sql.ErrNoRows), if error is detected, notFound is always false
// 2) if error != nil, then error is encountered (if error == sql.ErrNoRows, then error is treated as nil, and dest is nil)
func (svr *MySql) GetStruct(dest interface{}, query string, args ...interface{}) (notFound bool, retErr error) {
// verify if the database connection is good
if err := svr.Ping(); err != nil {
return false, err
}
// perform select action, and unmarshal result row (single row) into target struct (single object)
var err error
if svr.tx == nil {
// not in transaction mode
// query using db object
if !xray.XRayServiceOn() {
err = svr.db.Get(dest, query, args...)
} else {
trace := xray.NewSegment("MySql-Select-GetStruct", svr._parentSegment)
defer trace.Close()
defer func() {
_ = trace.Seg.AddMetadata("SQL-Query", query)
_ = trace.Seg.AddMetadata("SQL-Param-Values", args)
_ = trace.Seg.AddMetadata("Struct-Result", dest)
if err != nil {
_ = trace.Seg.AddError(err)
}
}()
err = svr.db.GetContext(trace.Ctx, dest, query, args...)
}
} else {
// in transaction mode
// query using tx object
if !xray.XRayServiceOn() {
err = svr.tx.Get(dest, query, args...)
} else {
subTrace := svr.newTxSubSegment("Transaction-Select-GetStruct")
defer subTrace.Close()
defer func() {
_ = subTrace.Seg.AddMetadata("SQL-Query", query)
_ = subTrace.Seg.AddMetadata("SQL-Param-Values", args)
_ = subTrace.Seg.AddMetadata("Struct-Result", dest)
if err != nil {
_ = subTrace.Seg.AddError(err)
}
}()
err = svr.tx.GetContext(subTrace.Ctx, dest, query, args...)
}
}
// if err is sql.ErrNoRows then treat as no error
if err != nil && err == sql.ErrNoRows {
notFound = true
dest = nil
err = nil
} else {
notFound = false
}
// return error
return notFound, err
}
// ----------------------------------------------------------------------------------------------------------------
// query and get rows helpers
// ----------------------------------------------------------------------------------------------------------------
// GetRowsByOrdinalParams performs query with optional variadic parameters to get ROWS of result, and returns *sqlx.Rows
// [ Parameters ]
// query = sql query, optionally having parameters marked as ?, where each represents a parameter position
// args = conditionally required if positioned parameters are specified, must appear in the same order as the positional parameters
// [ Return Values ]
// 1) *sqlx.Rows = pointer to sqlx.Rows; or nil if no rows yielded
// 2) if error != nil, then error is encountered (if error == sql.ErrNoRows, then error is treated as nil, and sqlx.Rows is returned as nil)
// [ Ranged Loop & Scan ]
// 1) to loop, use:
// for {
// if !rows.Next() { break }
// rows.Scan(&x, &y, etc)
// }
// 2) to scan, use: r.Scan(&x, &y, ...), where r is the row struct in loop, where &x &y etc are the scanned output value (scan in order of select columns sequence)
// [ Continuous Loop & Scan ]
// 1) Continuous loop until endOfRows = true is yielded from ScanSlice() or ScanStruct()
// 2) ScanSlice(): accepts *sqlx.Rows, scans rows result into target pointer slice (if no error, endOfRows = true is returned)
// 3) ScanStruct(): accepts *sqlx.Rows, scans current single row result into target pointer struct, returns endOfRows as true of false; if endOfRows = true, loop should stop
func (svr *MySql) GetRowsByOrdinalParams(query string, args ...interface{}) (*sqlx.Rows, error) {
// verify if the database connection is good
if err := svr.Ping(); err != nil {
return nil, err
}
// perform select action, and return sqlx rows
var rows *sqlx.Rows
var err error
if svr.tx == nil {
// not in transaction mode
// query using db object
if !xray.XRayServiceOn() {
rows, err = svr.db.Queryx(query, args...)
} else {
trace := xray.NewSegment("MySql-Select-GetRowsByOrdinalParams", svr._parentSegment)
defer trace.Close()
defer func() {
_ = trace.Seg.AddMetadata("SQL-Query", query)
_ = trace.Seg.AddMetadata("SQL-Param-Values", args)
_ = trace.Seg.AddMetadata("Rows-Result", rows)
if err != nil {
_ = trace.Seg.AddError(err)
}
}()
rows, err = svr.db.QueryxContext(trace.Ctx, query, args...)
}
} else {
// in transaction mode
// query using tx object
if !xray.XRayServiceOn() {
rows, err = svr.tx.Queryx(query, args...)
} else {
subTrace := svr.newTxSubSegment("Transaction-Select-GetRowsByOrdinalParams")
defer subTrace.Close()
defer func() {
_ = subTrace.Seg.AddMetadata("SQL-Query", query)
_ = subTrace.Seg.AddMetadata("SQL-Param-Values", args)
_ = subTrace.Seg.AddMetadata("Rows-Result", rows)
if err != nil {
_ = subTrace.Seg.AddError(err)
}
}()
rows, err = svr.tx.QueryxContext(subTrace.Ctx, query, args...)
}
}
// if err is sql.ErrNoRows then treat as no error
if err != nil && err == sql.ErrNoRows {
rows = nil
err = nil
}
// return result
return rows, err
}
// GetRowsByNamedMapParam performs query with named map containing parameters to get ROWS of result, and returns *sqlx.Rows
// [ Syntax ]
// 1) in sql = instead of defining ordinal parameters ?, each parameter in sql does not need to be ordinal, rather define with :xyz (must have : in front of param name), where xyz is name of parameter, such as :customerID
// 2) in go = setup a map variable: var p = make(map[string]interface{})
// 3) in go = to set values into map variable: p["xyz"] = abc
// where xyz is the parameter name matching the sql :xyz (do not include : in go map "xyz")
// where abc is the value of the parameter value, whether string or other data types
// note: in using map, just add additional map elements using the p["xyz"] = abc syntax
// note: if parameter value can be a null, such as nullint, nullstring, use util.ToNullTime(), ToNullInt(), ToNullString(), etc.
// 4) in go = when calling this function passing the map variable, simply pass the map variable p into the args parameter
// [ Parameters ]
// query = sql query, optionally having parameters marked as :xyz for each parameter name, where each represents a named parameter
// args = required, the map variable of the named parameters
// [ Return Values ]
// 1) *sqlx.Rows = pointer to sqlx.Rows; or nil if no rows yielded
// 2) if error != nil, then error is encountered (if error == sql.ErrNoRows, then error is treated as nil, and sqlx.Rows is returned as nil)
// [ Ranged Loop & Scan ]
// 1) to loop, use:
// for {
// if !rows.Next() { break }
// rows.Scan(&x, &y, etc)
// }
// 2) to scan, use: r.Scan(&x, &y, ...), where r is the row struct in loop, where &x &y etc are the scanned output value (scan in order of select columns sequence)
// [ Continuous Loop & Scan ]
// 1) Continuous loop until endOfRows = true is yielded from ScanSlice() or ScanStruct()
// 2) ScanSlice(): accepts *sqlx.Rows, scans rows result into target pointer slice (if no error, endOfRows = true is returned)
// 3) ScanStruct(): accepts *sqlx.Rows, scans current single row result into target pointer struct, returns endOfRows as true of false; if endOfRows = true, loop should stop
func (svr *MySql) GetRowsByNamedMapParam(query string, args map[string]interface{}) (*sqlx.Rows, error) {
// verify if the database connection is good
if err := svr.Ping(); err != nil {
return nil, err
}
// perform select action, and return sqlx rows
var rows *sqlx.Rows
var err error
if svr.tx == nil {
// not in transaction mode
// query using db object
if !xray.XRayServiceOn() {
rows, err = svr.db.NamedQuery(query, args)
} else {
trace := xray.NewSegment("MySql-Select-GetRowsByNamedMapParam", svr._parentSegment)
defer trace.Close()
defer func() {
_ = trace.Seg.AddMetadata("SQL-Query", query)
_ = trace.Seg.AddMetadata("SQL-Param-Values", args)
_ = trace.Seg.AddMetadata("Rows-Result", rows)
if err != nil {
_ = trace.Seg.AddError(err)
}
}()
rows, err = svr.db.NamedQueryContext(trace.Ctx, query, args)
}
} else {
// in transaction mode
// query using tx object
if !xray.XRayServiceOn() {
rows, err = svr.tx.NamedQuery(query, args)
} else {
subTrace := svr.newTxSubSegment("Transaction-Select-GetRowsByNamedMapParam")
defer subTrace.Close()
defer func() {
_ = subTrace.Seg.AddMetadata("SQL-Query", query)
_ = subTrace.Seg.AddMetadata("SQL-Param-Values", args)
_ = subTrace.Seg.AddMetadata("Rows-Result", rows)
if err != nil {
_ = subTrace.Seg.AddError(err)
}
}()
rows, err = sqlx.NamedQueryContext(subTrace.Ctx, svr.tx, query, args)
}
}