-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathintegration_test.go
817 lines (783 loc) · 24.6 KB
/
integration_test.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
package sq
import (
"database/sql"
"fmt"
"net/url"
"strings"
"testing"
"time"
"github.com/bokwoon95/sq/internal/testutil"
_ "github.com/denisenkom/go-mssqldb"
_ "github.com/go-sql-driver/mysql"
"github.com/google/uuid"
_ "github.com/lib/pq"
_ "github.com/mattn/go-sqlite3"
)
type Color int
const (
ColorInvalid Color = iota
ColorRed
ColorGreen
ColorBlue
)
var colorNames = [...]string{
ColorInvalid: "",
ColorRed: "red",
ColorGreen: "green",
ColorBlue: "blue",
}
func (c Color) Enumerate() []string { return colorNames[:] }
type Direction string
const (
DirectionInvalid = Direction("")
DirectionNorth = Direction("north")
DirectionSouth = Direction("south")
DirectionEast = Direction("east")
DirectionWest = Direction("west")
)
func (d Direction) Enumerate() []string {
return []string{
string(DirectionInvalid),
string(DirectionNorth),
string(DirectionSouth),
string(DirectionEast),
string(DirectionWest),
}
}
func TestRow(t *testing.T) {
type TestTable struct {
dialect string
driver string
dsn string
teardown string
setup string
}
tests := []TestTable{{
dialect: DialectSQLite,
driver: "sqlite3",
dsn: "file:/TestRow/sqlite?vfs=memdb&_foreign_keys=true",
teardown: "DROP TABLE IF EXISTS table00;",
setup: "CREATE TABLE table00 (" +
"\n uuid UUID" +
"\n ,data JSON" +
"\n ,color TEXT" +
"\n ,direction TEXT" +
"\n ,weekday TEXT" +
"\n ,text_array JSON" +
"\n ,int_array JSON" +
"\n ,int64_array JSON" +
"\n ,int32_array JSON" +
"\n ,float64_array JSON" +
"\n ,float32_array JSON" +
"\n ,bool_array JSON" +
"\n ,bytes BLOB" +
"\n ,is_active BOOLEAN" +
"\n ,price REAL" +
"\n ,score BIGINT" +
"\n ,name TEXT" +
"\n ,updated_at DATETIME" +
"\n);",
}, {
dialect: DialectPostgres,
driver: "postgres",
dsn: *postgresDSN,
teardown: "DROP TABLE IF EXISTS table00;" +
"\nDROP TYPE IF EXISTS direction;" +
"\nDROP TYPE IF EXISTS color;" +
"\nDROP TYPE IF EXISTS weekday;",
setup: "CREATE TYPE color AS ENUM ('red', 'green', 'blue');" +
"\nCREATE TYPE direction AS ENUM ('north', 'south', 'east', 'west');" +
"\nCREATE TYPE weekday AS ENUM ('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');" +
"\nCREATE TABLE table00 (" +
"\n uuid UUID" +
"\n ,data JSONB" +
"\n ,color color" +
"\n ,direction direction" +
"\n ,weekday weekday" +
"\n ,text_array TEXT[]" +
"\n ,int_array BIGINT[]" +
"\n ,int64_array BIGINT[]" +
"\n ,int32_array INT[]" +
"\n ,float64_array DOUBLE PRECISION[]" +
"\n ,float32_array REAL[]" +
"\n ,bool_array BOOLEAN[]" +
"\n ,is_active BOOLEAN" +
"\n ,bytes BYTEA" +
"\n ,price DOUBLE PRECISION" +
"\n ,score BIGINT" +
"\n ,name TEXT" +
"\n ,updated_at TIMESTAMPTZ" +
"\n);",
}, {
dialect: DialectMySQL,
driver: "mysql",
dsn: *mysqlDSN,
teardown: "DROP TABLE IF EXISTS table00;",
setup: "CREATE TABLE table00 (" +
"\n uuid BINARY(16)" +
"\n ,data JSON" +
"\n ,color VARCHAR(255)" +
"\n ,direction VARCHAR(255)" +
"\n ,weekday VARCHAR(255)" +
"\n ,text_array JSON" +
"\n ,int_array JSON" +
"\n ,int64_array JSON" +
"\n ,int32_array JSON" +
"\n ,float64_array JSON" +
"\n ,float32_array JSON" +
"\n ,bool_array JSON" +
"\n ,is_active BOOLEAN" +
"\n ,bytes LONGBLOB" +
"\n ,price DOUBLE PRECISION" +
"\n ,score BIGINT" +
"\n ,name TEXT" +
"\n ,updated_at DATETIME" +
"\n);",
}, {
dialect: DialectSQLServer,
driver: "sqlserver",
dsn: *sqlserverDSN,
teardown: "DROP TABLE IF EXISTS table00;",
setup: "CREATE TABLE table00 (" +
"\n uuid BINARY(16)" +
"\n ,data NVARCHAR(MAX)" +
"\n ,color NVARCHAR(255)" +
"\n ,direction NVARCHAR(255)" +
"\n ,weekday NVARCHAR(255)" +
"\n ,text_array NVARCHAR(MAX)" +
"\n ,int_array NVARCHAR(MAX)" +
"\n ,int64_array NVARCHAR(MAX)" +
"\n ,int32_array NVARCHAR(MAX)" +
"\n ,float64_array NVARCHAR(MAX)" +
"\n ,float32_array NVARCHAR(MAX)" +
"\n ,bool_array NVARCHAR(MAX)" +
"\n ,is_active BIT" +
"\n ,bytes VARBINARY(MAX)" +
"\n ,price DOUBLE PRECISION" +
"\n ,score BIGINT" +
"\n ,name NVARCHAR(255)" +
"\n ,updated_at DATETIME" +
"\n);",
}}
var TABLE00 = New[struct {
TableStruct `sq:"table00"`
UUID UUIDField
DATA JSONField
COLOR EnumField
DIRECTION EnumField
WEEKDAY EnumField
TEXT_ARRAY ArrayField
INT_ARRAY ArrayField
INT64_ARRAY ArrayField
INT32_ARRAY ArrayField
FLOAT64_ARRAY ArrayField
FLOAT32_ARRAY ArrayField
BOOL_ARRAY ArrayField
BYTES BinaryField
IS_ACTIVE BooleanField
PRICE NumberField
SCORE NumberField
NAME StringField
UPDATED_AT TimeField
}]("")
type Table00 struct {
uuid uuid.UUID
data any
color Color
direction Direction
weekday Weekday
textArray []string
intArray []int
int64Array []int64
int32Array []int32
float64Array []float64
float32Array []float32
boolArray []bool
bytes []byte
isActive bool
price float64
score int64
name string
updatedAt time.Time
}
var table00Values = []Table00{{
uuid: uuid.UUID([16]byte{15: 1}),
data: map[string]any{"lorem ipsum": "dolor sit amet"},
color: ColorRed,
direction: DirectionNorth,
weekday: Monday,
textArray: []string{"one", "two", "three"},
intArray: []int{1, 2, 3},
int64Array: []int64{1, 2, 3},
int32Array: []int32{1, 2, 3},
float64Array: []float64{1, 2, 3},
float32Array: []float32{1, 2, 3},
boolArray: []bool{true, false, false},
bytes: []byte{1, 2, 3},
isActive: true,
price: 123,
score: 123,
name: "one two three",
updatedAt: time.Unix(123, 0).UTC(),
}, {
uuid: uuid.UUID([16]byte{15: 2}),
data: map[string]any{"lorem ipsum": "dolor sit amet"},
color: ColorGreen,
direction: DirectionSouth,
weekday: Tuesday,
textArray: []string{"four", "five", "six"},
intArray: []int{4, 5, 6},
int64Array: []int64{4, 5, 6},
int32Array: []int32{4, 5, 6},
float64Array: []float64{4, 5, 6},
float32Array: []float32{4, 5, 6},
boolArray: []bool{false, true, false},
bytes: []byte{4, 5, 6},
isActive: true,
price: 456,
score: 456,
name: "four five six",
updatedAt: time.Unix(456, 0).UTC(),
}, {
uuid: uuid.UUID([16]byte{15: 3}),
data: map[string]any{"lorem ipsum": "dolor sit amet"},
color: ColorBlue,
direction: DirectionEast,
weekday: Wednesday,
textArray: []string{"seven", "eight", "nine"},
intArray: []int{7, 8, 9},
float64Array: []float64{7, 8, 9},
boolArray: []bool{false, false, true},
bytes: []byte{7, 8, 9},
isActive: true,
price: 789,
score: 789,
name: "seven eight nine",
updatedAt: time.Unix(789, 0).UTC(),
}}
for _, tt := range tests {
tt := tt
t.Run(tt.dialect, func(t *testing.T) {
if tt.dsn == "" {
return
}
t.Parallel()
dsn := preprocessDSN(tt.dialect, tt.dsn)
db, err := sql.Open(tt.driver, dsn)
if err != nil {
t.Fatal(testutil.Callers(), err)
}
_, err = db.Exec(tt.teardown)
if err != nil {
t.Fatal(testutil.Callers(), err)
}
_, err = db.Exec(tt.setup)
if err != nil {
t.Fatal(testutil.Callers(), err)
}
defer func() {
db.Exec(tt.teardown)
}()
// Insert the data.
result, err := Exec(Log(db), InsertInto(TABLE00).
ColumnValues(func(col *Column) {
for _, value := range table00Values {
col.SetUUID(TABLE00.UUID, value.uuid)
col.SetJSON(TABLE00.DATA, value.data)
col.SetEnum(TABLE00.COLOR, value.color)
col.SetEnum(TABLE00.DIRECTION, value.direction)
col.SetEnum(TABLE00.WEEKDAY, value.weekday)
col.SetArray(TABLE00.TEXT_ARRAY, value.textArray)
col.SetArray(TABLE00.INT_ARRAY, value.intArray)
col.SetArray(TABLE00.INT64_ARRAY, value.int64Array)
col.SetArray(TABLE00.INT32_ARRAY, value.int32Array)
col.SetArray(TABLE00.FLOAT64_ARRAY, value.float64Array)
col.SetArray(TABLE00.FLOAT32_ARRAY, value.float32Array)
col.SetArray(TABLE00.BOOL_ARRAY, value.boolArray)
col.SetBytes(TABLE00.BYTES, value.bytes)
col.SetBool(TABLE00.IS_ACTIVE, value.isActive)
col.SetFloat64(TABLE00.PRICE, value.price)
col.SetInt64(TABLE00.SCORE, value.score)
col.SetString(TABLE00.NAME, value.name)
col.SetTime(TABLE00.UPDATED_AT, value.updatedAt)
}
}).
SetDialect(tt.dialect),
)
if err != nil {
t.Fatal(testutil.Callers(), err)
}
if diff := testutil.Diff(result.RowsAffected, int64(len(table00Values))); diff != "" {
t.Error(testutil.Callers(), diff)
}
// Fetch the data.
values, err := FetchAll(VerboseLog(db), From(TABLE00).
OrderBy(TABLE00.UUID).
SetDialect(tt.dialect),
func(row *Row) Table00 {
var value Table00
row.UUIDField(&value.uuid, TABLE00.UUID)
row.JSONField(&value.data, TABLE00.DATA)
row.EnumField(&value.color, TABLE00.COLOR)
row.EnumField(&value.direction, TABLE00.DIRECTION)
row.EnumField(&value.weekday, TABLE00.WEEKDAY)
row.ArrayField(&value.textArray, TABLE00.TEXT_ARRAY)
row.ArrayField(&value.intArray, TABLE00.INT_ARRAY)
row.ArrayField(&value.int64Array, TABLE00.INT64_ARRAY)
row.ArrayField(&value.int32Array, TABLE00.INT32_ARRAY)
row.ArrayField(&value.float64Array, TABLE00.FLOAT64_ARRAY)
row.ArrayField(&value.float32Array, TABLE00.FLOAT32_ARRAY)
row.ArrayField(&value.boolArray, TABLE00.BOOL_ARRAY)
value.bytes = row.BytesField(TABLE00.BYTES)
value.isActive = row.BoolField(TABLE00.IS_ACTIVE)
value.price = row.Float64Field(TABLE00.PRICE)
value.score = row.Int64Field(TABLE00.SCORE)
value.name = row.StringField(TABLE00.NAME)
value.updatedAt = row.TimeField(TABLE00.UPDATED_AT)
// make sure Columns, ColumnTypes and Values are all
// callable inside the rowmapper even for dynamic queries.
fmt.Println(row.Columns())
fmt.Println(row.ColumnTypes())
fmt.Println(row.Values())
return value
},
)
if err != nil {
t.Fatal(testutil.Callers(), err)
}
if diff := testutil.Diff(values, table00Values); diff != "" {
t.Error(testutil.Callers(), diff)
}
exists, err := FetchExists(Log(db), SelectOne().
From(TABLE00).
Where(TABLE00.UUID.EqUUID(table00Values[0].uuid)).
SetDialect(tt.dialect),
)
if err != nil {
t.Fatal(testutil.Callers(), err)
}
if !exists {
t.Errorf(testutil.Callers()+" expected row with uuid = %q to exist, got false", table00Values[0].uuid.String())
}
// SQLServer driver *still* doesn't support NULL UUIDs 🙄, skip
// NULL testing for SQL Server.
// https://github.com/denisenkom/go-mssqldb/issues/196
if tt.dialect == "sqlserver" {
return
}
// Insert NULLs.
_, err = Exec(Log(db), InsertInto(TABLE00).
ColumnValues(func(col *Column) {
col.Set(TABLE00.UUID, nil)
col.Set(TABLE00.DATA, nil)
col.Set(TABLE00.COLOR, nil)
col.Set(TABLE00.DIRECTION, nil)
col.Set(TABLE00.WEEKDAY, nil)
col.Set(TABLE00.TEXT_ARRAY, nil)
col.Set(TABLE00.INT_ARRAY, nil)
col.Set(TABLE00.INT64_ARRAY, nil)
col.Set(TABLE00.INT32_ARRAY, nil)
col.Set(TABLE00.FLOAT64_ARRAY, nil)
col.Set(TABLE00.FLOAT32_ARRAY, nil)
col.Set(TABLE00.BOOL_ARRAY, nil)
col.Set(TABLE00.BYTES, nil)
col.Set(TABLE00.IS_ACTIVE, nil)
col.Set(TABLE00.PRICE, nil)
col.Set(TABLE00.SCORE, nil)
col.Set(TABLE00.NAME, nil)
col.Set(TABLE00.UPDATED_AT, nil)
}).
SetDialect(tt.dialect),
)
if err != nil {
t.Fatal(testutil.Callers(), err)
}
// Fetch NULLs.
_, err = FetchAll(VerboseLog(db), From(TABLE00).
Where(TABLE00.UUID.IsNull()).
OrderBy(TABLE00.UUID).
SetDialect(tt.dialect),
func(row *Row) Table00 {
var value Table00
row.UUIDField(&value.uuid, TABLE00.UUID)
row.JSONField(&value.data, TABLE00.DATA)
row.EnumField(&value.color, TABLE00.COLOR)
row.EnumField(&value.direction, TABLE00.DIRECTION)
row.EnumField(&value.weekday, TABLE00.WEEKDAY)
row.ArrayField(&value.textArray, TABLE00.TEXT_ARRAY)
row.ArrayField(&value.intArray, TABLE00.INT_ARRAY)
row.ArrayField(&value.int64Array, TABLE00.INT64_ARRAY)
row.ArrayField(&value.int32Array, TABLE00.INT32_ARRAY)
row.ArrayField(&value.float64Array, TABLE00.FLOAT64_ARRAY)
row.ArrayField(&value.float32Array, TABLE00.FLOAT32_ARRAY)
row.ArrayField(&value.boolArray, TABLE00.BOOL_ARRAY)
value.bytes = row.BytesField(TABLE00.BYTES)
value.isActive = row.BoolField(TABLE00.IS_ACTIVE)
value.price = row.Float64Field(TABLE00.PRICE)
value.score = row.Int64Field(TABLE00.SCORE)
value.name = row.StringField(TABLE00.NAME)
value.updatedAt = row.TimeField(TABLE00.UPDATED_AT)
return value
},
)
if err != nil {
t.Fatal(testutil.Callers(), err)
}
})
}
}
func TestRowScan(t *testing.T) {
table01Values := [][]any{
{nil, nil, nil, nil, nil, nil},
{123, int64(123), float64(123), "abc", true, time.Unix(123, 0).UTC()},
{456, int64(456), float64(456), "def", true, time.Unix(456, 0).UTC()},
{789, int64(789), float64(789), "ghi", true, time.Unix(789, 0).UTC()},
}
type TestTable struct {
dialect string
driver string
dsn string
teardown string
setup string
}
tests := []TestTable{{
dialect: DialectSQLite,
driver: "sqlite3",
dsn: "file:/TestRowScan/sqlite?vfs=memdb&_foreign_keys=true",
teardown: "DROP TABLE IF EXISTS table01;",
setup: "CREATE TABLE table01 (" +
"\n id INT" +
"\n ,score BIGINT" +
"\n ,price REAL" +
"\n ,name TEXT" +
"\n ,is_active BOOLEAN" +
"\n ,updated_at DATETIME" +
"\n);",
}, {
dialect: DialectPostgres,
driver: "postgres",
dsn: *postgresDSN,
teardown: "DROP TABLE IF EXISTS table01;",
setup: "CREATE TABLE table01 (" +
"\n id INT" +
"\n ,score BIGINT" +
"\n ,price DOUBLE PRECISION" +
"\n ,name TEXT" +
"\n ,is_active BOOLEAN" +
"\n ,updated_at TIMESTAMPTZ" +
"\n);",
}, {
dialect: DialectMySQL,
driver: "mysql",
dsn: *mysqlDSN,
teardown: "DROP TABLE IF EXISTS table01;",
setup: "CREATE TABLE table01 (" +
"\n id INT" +
"\n ,score BIGINT" +
"\n ,price DOUBLE PRECISION" +
"\n ,name VARCHAR(255)" +
"\n ,is_active BOOLEAN" +
"\n ,updated_at DATETIME" +
"\n);",
}, {
dialect: DialectSQLServer,
driver: "sqlserver",
dsn: *sqlserverDSN,
teardown: "DROP TABLE IF EXISTS table01;",
setup: "CREATE TABLE table01 (" +
"\n id INT" +
"\n ,score BIGINT" +
"\n ,price DOUBLE PRECISION" +
"\n ,name NVARCHAR(255)" +
"\n ,is_active BIT" +
"\n ,updated_at DATETIME2" +
"\n);",
}}
for _, tt := range tests {
tt := tt
t.Run(tt.dialect, func(t *testing.T) {
if tt.dsn == "" {
return
}
t.Parallel()
dsn := preprocessDSN(tt.dialect, tt.dsn)
db, err := sql.Open(tt.driver, dsn)
if err != nil {
t.Fatal(testutil.Callers(), err)
}
_, err = db.Exec(tt.teardown)
if err != nil {
t.Fatal(testutil.Callers(), err)
}
_, err = db.Exec(tt.setup)
if err != nil {
t.Fatal(testutil.Callers(), err)
}
defer func() {
db.Exec(tt.teardown)
}()
// Insert values.
result, err := Exec(Log(db), InsertQuery{
Dialect: tt.dialect,
InsertTable: Expr("table01"),
ColumnMapper: func(col *Column) {
for _, value := range table01Values {
col.Set(Expr("id"), value[0])
col.Set(Expr("score"), value[1])
col.Set(Expr("price"), value[2])
col.Set(Expr("name"), value[3])
col.Set(Expr("is_active"), value[4])
col.Set(Expr("updated_at"), value[5])
}
},
})
if err != nil {
t.Fatal(testutil.Callers(), err)
}
if diff := testutil.Diff(result.RowsAffected, int64(len(table01Values))); diff != "" {
t.Error(testutil.Callers(), diff)
}
t.Run("dynamic SQL query", func(t *testing.T) {
gotValues, err := FetchAll(db,
Queryf("SELECT {*} FROM table01 WHERE id IS NOT NULL ORDER BY id").SetDialect(tt.dialect),
func(row *Row) []any {
var id int
var score1 int64
var score2 int32
var price float64
var name string
var isActive bool
var updatedAt time.Time
row.Scan(&id, "id")
row.Scan(&score1, "score")
row.Scan(&score2, "score")
if diff := testutil.Diff(score1, int64(score2)); diff != "" {
panic(fmt.Errorf(testutil.Callers() + diff))
}
row.Scan(&price, "price")
row.Scan(&name, "name")
row.Scan(&isActive, "is_active")
row.Scan(&updatedAt, "updated_at")
return []any{id, score1, price, name, isActive, updatedAt}
},
)
if err != nil {
t.Fatal(testutil.Callers(), err)
}
wantValues := [][]any{
{123, int64(123), float64(123), "abc", true, time.Unix(123, 0).UTC()},
{456, int64(456), float64(456), "def", true, time.Unix(456, 0).UTC()},
{789, int64(789), float64(789), "ghi", true, time.Unix(789, 0).UTC()},
}
if diff := testutil.Diff(gotValues, wantValues); diff != "" {
t.Error(testutil.Callers(), diff)
}
})
t.Run("dynamic SQL query (null values)", func(t *testing.T) {
gotValue, err := FetchOne(db,
Queryf("SELECT {*} FROM table01 WHERE id IS NULL").SetDialect(tt.dialect),
func(row *Row) []any {
var id int
var score1 int64
var score2 int32
var price float64
var name string
var isActive bool
var updatedAt time.Time
row.Scan(&id, "id")
row.Scan(&score1, "score")
row.Scan(&score2, "score")
if diff := testutil.Diff(score1, int64(score2)); diff != "" {
panic(fmt.Errorf(testutil.Callers() + diff))
}
row.Scan(&price, "price")
row.Scan(&name, "name")
row.Scan(&isActive, "is_active")
row.Scan(&updatedAt, "updated_at")
return []any{id, score1, price, name, isActive, updatedAt}
},
)
if err != nil {
t.Fatal(testutil.Callers(), err)
}
wantValue := []any{int(0), int64(0), float64(0), "", false, time.Time{}}
if diff := testutil.Diff(gotValue, wantValue); diff != "" {
t.Error(testutil.Callers(), diff)
}
})
t.Run("dynamic SQL query (null values) (using sql.Null structs)", func(t *testing.T) {
gotValue, err := FetchOne(db,
Queryf("SELECT {*} FROM table01 WHERE id IS NULL").SetDialect(tt.dialect),
func(row *Row) []any {
var id sql.NullInt64
var score1 sql.NullInt64
var score2 sql.NullInt32
var price sql.NullFloat64
var name sql.NullString
var isActive sql.NullBool
var updatedAt sql.NullTime
row.Scan(&id, "id")
row.Scan(&score1, "score")
row.Scan(&score2, "score")
if diff := testutil.Diff(score1.Int64, int64(score2.Int32)); diff != "" {
panic(fmt.Errorf(testutil.Callers() + diff))
}
row.Scan(&price, "price")
row.Scan(&name, "name")
row.Scan(&isActive, "is_active")
row.Scan(&updatedAt, "updated_at")
return []any{int(id.Int64), score1.Int64, price.Float64, name.String, isActive.Bool, updatedAt.Time}
},
)
if err != nil {
t.Fatal(testutil.Callers(), err)
}
wantValue := []any{int(0), int64(0), float64(0), "", false, time.Time{}}
if diff := testutil.Diff(gotValue, wantValue); diff != "" {
t.Error(testutil.Callers(), diff)
}
})
t.Run("static SQL query", func(t *testing.T) {
// Raw SQL query with.
gotValues, err := FetchAll(Log(db),
Queryf("SELECT id, score, price, name, is_active, updated_at FROM table01 WHERE id IS NOT NULL ORDER BY id").SetDialect(tt.dialect),
func(row *Row) []any {
return []any{
row.Int("id"),
row.Int64("score"),
row.Float64("price"),
row.String("name"),
row.Bool("is_active"),
row.Time("updated_at"),
}
},
)
if err != nil {
t.Fatal(testutil.Callers(), err)
}
wantValues := [][]any{
{123, int64(123), float64(123), "abc", true, time.Unix(123, 0).UTC()},
{456, int64(456), float64(456), "def", true, time.Unix(456, 0).UTC()},
{789, int64(789), float64(789), "ghi", true, time.Unix(789, 0).UTC()},
}
if diff := testutil.Diff(gotValues, wantValues); diff != "" {
t.Error(testutil.Callers(), diff)
}
})
t.Run("static SQL query (raw Values)", func(t *testing.T) {
gotValues, err := FetchAll(db,
Queryf("SELECT id, score, price, name, is_active, updated_at FROM table01 WHERE id IS NOT NULL ORDER BY id").SetDialect(tt.dialect),
func(row *Row) []any {
columns := row.Columns()
columnTypes := row.ColumnTypes()
values := row.Values()
if len(columns) != len(columnTypes) || len(columnTypes) != len(values) {
panic(fmt.Errorf(testutil.Callers()+" length of columns/columnTypes/values don't match: %v %v %v", columns, columnTypes, values))
}
return values
},
)
if err != nil {
t.Fatal(testutil.Callers(), err)
}
// We need to tweak wantValues depending on the dialect because
// we are at the mercy of whatever that dialect's database
// driver decides to return.
var wantValues [][]any
switch tt.dialect {
case DialectSQLite, DialectPostgres, DialectSQLServer:
wantValues = [][]any{
{int64(123), int64(123), float64(123), "abc", true, time.Unix(123, 0).UTC()},
{int64(456), int64(456), float64(456), "def", true, time.Unix(456, 0).UTC()},
{int64(789), int64(789), float64(789), "ghi", true, time.Unix(789, 0).UTC()},
}
case DialectMySQL:
wantValues = [][]any{
{[]byte("123"), []byte("123"), []byte("123"), []byte("abc"), []byte("1"), time.Unix(123, 0).UTC()},
{[]byte("456"), []byte("456"), []byte("456"), []byte("def"), []byte("1"), time.Unix(456, 0).UTC()},
{[]byte("789"), []byte("789"), []byte("789"), []byte("ghi"), []byte("1"), time.Unix(789, 0).UTC()},
}
}
if diff := testutil.Diff(gotValues, wantValues); diff != "" {
t.Error(testutil.Callers(), diff)
}
})
t.Run("static SQL query (null values)", func(t *testing.T) {
gotValue, err := FetchOne(db,
Queryf("SELECT id, score, price, name, is_active, updated_at FROM table01 WHERE id IS NULL").SetDialect(tt.dialect),
func(row *Row) []any {
columns := row.Columns()
columnTypes := row.ColumnTypes()
values := row.Values()
if len(columns) != len(columnTypes) || len(columnTypes) != len(values) {
panic(fmt.Errorf(testutil.Callers()+" length of columns/columnTypes/values don't match: %v %v %v", columns, columnTypes, values))
}
return values
},
)
if err != nil {
t.Fatal(testutil.Callers(), err)
}
if diff := testutil.Diff(gotValue, []any{nil, nil, nil, nil, nil, nil}); diff != "" {
t.Error(testutil.Callers(), diff)
}
})
t.Run("static SQL query (null values) (using sql.Null structs)", func(t *testing.T) {
gotValue, err := FetchOne(db,
Queryf("SELECT id, score, price, name, is_active, updated_at FROM table01 WHERE id IS NULL").SetDialect(tt.dialect),
func(row *Row) []any {
return []any{
row.NullInt64("score"),
row.NullFloat64("price"),
row.NullString("name"),
row.NullBool("is_active"),
row.NullTime("updated_at"),
}
},
)
if err != nil {
t.Fatal(testutil.Callers(), err)
}
wantValues := []any{sql.NullInt64{}, sql.NullFloat64{}, sql.NullString{}, sql.NullBool{}, sql.NullTime{}}
if diff := testutil.Diff(gotValue, wantValues); diff != "" {
t.Error(testutil.Callers(), diff)
}
})
})
}
}
func preprocessDSN(dialect string, dsn string) string {
switch dialect {
case DialectPostgres:
before, after, _ := strings.Cut(dsn, "?")
q, err := url.ParseQuery(after)
if err != nil {
return dsn
}
if !q.Has("sslmode") {
q.Set("sslmode", "disable")
}
if !q.Has("binary_parameters") {
q.Set("binary_parameters", "yes")
}
return before + "?" + q.Encode()
case DialectMySQL:
before, after, _ := strings.Cut(strings.TrimPrefix(dsn, "mysql://"), "?")
q, err := url.ParseQuery(after)
if err != nil {
return dsn
}
if !q.Has("allowAllFiles") {
q.Set("allowAllFiles", "true")
}
if !q.Has("multiStatements") {
q.Set("multiStatements", "true")
}
if !q.Has("parseTime") {
q.Set("parseTime", "true")
}
return before + "?" + q.Encode()
default:
return dsn
}
}