-
-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathtest_adapters.go
3763 lines (3132 loc) · 110 KB
/
test_adapters.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 ksql
import (
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
"io"
"reflect"
"strings"
"testing"
"time"
"github.com/vingarcia/ksql/internal/modifiers"
"github.com/vingarcia/ksql/internal/structs"
tt "github.com/vingarcia/ksql/internal/testtools"
"github.com/vingarcia/ksql/ksqlmodifiers"
"github.com/vingarcia/ksql/nullable"
"github.com/vingarcia/ksql/sqldialect"
)
var usersTable = NewTable("users")
type user struct {
ID uint `ksql:"id"`
Name string `ksql:"name"`
Age int `ksql:"age"`
Address address `ksql:"address,json"`
// This attr has no ksql tag, thus, it should be ignored:
AttrThatShouldBeIgnored string
}
type address struct {
Street string `json:"street"`
Number string `json:"number"`
City string `json:"city"`
State string `json:"state"`
Country string `json:"country"`
}
var postsTable = NewTable("posts")
type post struct {
ID int `ksql:"id"`
UserID uint `ksql:"user_id"`
Title string `ksql:"title"`
}
var userPermissionsTable = NewTable("user_permissions", "user_id", "perm_id")
type userPermission struct {
ID int `ksql:"id"`
UserID int `ksql:"user_id"`
PermID int `ksql:"perm_id"`
Type string `ksql:"type"`
}
// RunTestsForAdapter will run all necessary tests for making sure
// a given adapter is working as expected.
//
// Optionally it is also possible to run each of these tests
// separatedly, which might be useful during the development
// of a new adapter.
func RunTestsForAdapter(
t *testing.T,
adapterName string,
dialect sqldialect.Provider,
connStr string,
newDBAdapter func(t *testing.T) (DBAdapter, io.Closer),
) {
t.Run(adapterName, func(t *testing.T) {
t.Run(dialect.DriverName(), func(t *testing.T) {
QueryTest(t, dialect, connStr, newDBAdapter)
QueryOneTest(t, dialect, connStr, newDBAdapter)
InsertTest(t, dialect, connStr, newDBAdapter)
DeleteTest(t, dialect, connStr, newDBAdapter)
PatchTest(t, dialect, connStr, newDBAdapter)
QueryChunksTest(t, dialect, connStr, newDBAdapter)
TransactionTest(t, dialect, connStr, newDBAdapter)
ModifiersTest(t, dialect, connStr, newDBAdapter)
ScanRowsTest(t, dialect, connStr, newDBAdapter)
})
})
}
// QueryTest runs all tests for making sure the Query function is
// working for a given adapter and dialect.
func QueryTest(
t *testing.T,
dialect sqldialect.Provider,
connStr string,
newDBAdapter func(t *testing.T) (DBAdapter, io.Closer),
) {
ctx := context.Background()
t.Run("Query", func(t *testing.T) {
variations := []struct {
desc string
queryPrefix string
}{
{
desc: "with select *",
queryPrefix: "SELECT * ",
},
{
desc: "building the SELECT part of the query internally",
queryPrefix: "",
},
}
for _, variation := range variations {
t.Run(variation.desc, func(t *testing.T) {
t.Run("using slice of structs", func(t *testing.T) {
db, closer := newDBAdapter(t)
err := createTables(ctx, db, dialect)
if err != nil {
t.Fatal("could not create test table!, reason:", err.Error())
}
defer closer.Close()
t.Run("should return 0 results correctly", func(t *testing.T) {
c := newTestDB(db, dialect)
var users []user
err := c.Query(ctx, &users, variation.queryPrefix+`FROM users WHERE id=1;`)
tt.AssertNoErr(t, err)
tt.AssertEqual(t, len(users), 0)
users = []user{}
err = c.Query(ctx, &users, variation.queryPrefix+`FROM users WHERE id=1;`)
tt.AssertNoErr(t, err)
tt.AssertEqual(t, len(users), 0)
})
t.Run("should return a user correctly", func(t *testing.T) {
_, err := db.ExecContext(ctx, `INSERT INTO users (name, age, address) VALUES ('Bia', 0, '{"country":"BR"}')`)
tt.AssertNoErr(t, err)
c := newTestDB(db, dialect)
var users []user
err = c.Query(ctx, &users, variation.queryPrefix+`FROM users WHERE name=`+c.dialect.Placeholder(0), "Bia")
tt.AssertNoErr(t, err)
tt.AssertEqual(t, len(users), 1)
tt.AssertNotEqual(t, users[0].ID, uint(0))
tt.AssertEqual(t, users[0].Name, "Bia")
tt.AssertEqual(t, users[0].Address.Country, "BR")
})
t.Run("should return multiple users correctly", func(t *testing.T) {
_, err := db.ExecContext(ctx, `INSERT INTO users (name, age, address) VALUES ('João Garcia', 0, '{"country":"US"}')`)
tt.AssertNoErr(t, err)
_, err = db.ExecContext(ctx, `INSERT INTO users (name, age, address) VALUES ('Bia Garcia', 0, '{"country":"BR"}')`)
tt.AssertNoErr(t, err)
c := newTestDB(db, dialect)
var users []user
err = c.Query(ctx, &users, variation.queryPrefix+`FROM users WHERE name like `+c.dialect.Placeholder(0), "% Garcia")
tt.AssertNoErr(t, err)
tt.AssertEqual(t, len(users), 2)
tt.AssertNotEqual(t, users[0].ID, uint(0))
tt.AssertEqual(t, users[0].Name, "João Garcia")
tt.AssertEqual(t, users[0].Address.Country, "US")
tt.AssertNotEqual(t, users[1].ID, uint(0))
tt.AssertEqual(t, users[1].Name, "Bia Garcia")
tt.AssertEqual(t, users[1].Address.Country, "BR")
})
t.Run("should query joined tables correctly", func(t *testing.T) {
// This test only makes sense with no query prefix
if variation.queryPrefix != "" {
return
}
_, err := db.ExecContext(ctx, `INSERT INTO users (name, age, address) VALUES ('João Ribeiro', 0, '{"country":"US"}')`)
tt.AssertNoErr(t, err)
var joao user
getUserByName(db, dialect, &joao, "João Ribeiro")
tt.AssertNoErr(t, err)
_, err = db.ExecContext(ctx, `INSERT INTO users (name, age, address) VALUES ('Bia Ribeiro', 0, '{"country":"BR"}')`)
tt.AssertNoErr(t, err)
var bia user
getUserByName(db, dialect, &bia, "Bia Ribeiro")
_, err = db.ExecContext(ctx, fmt.Sprint(`INSERT INTO posts (user_id, title) VALUES (`, bia.ID, `, 'Bia Post1')`))
tt.AssertNoErr(t, err)
_, err = db.ExecContext(ctx, fmt.Sprint(`INSERT INTO posts (user_id, title) VALUES (`, bia.ID, `, 'Bia Post2')`))
tt.AssertNoErr(t, err)
_, err = db.ExecContext(ctx, fmt.Sprint(`INSERT INTO posts (user_id, title) VALUES (`, joao.ID, `, 'João Post1')`))
tt.AssertNoErr(t, err)
ctx := context.Background()
c := newTestDB(db, dialect)
var rows []struct {
User user `tablename:"u"`
Post post `tablename:"p"`
// This one has no ksql or tablename tag,
// so it should just be ignored to avoid strange
// unexpected errors:
ExtraStructThatShouldBeIgnored user
}
err = c.Query(ctx, &rows, fmt.Sprint(
`FROM users u JOIN posts p ON p.user_id = u.id`,
` WHERE u.name like `, c.dialect.Placeholder(0),
` ORDER BY u.id, p.id`,
), "% Ribeiro")
tt.AssertNoErr(t, err)
tt.AssertEqual(t, len(rows), 3)
tt.AssertEqual(t, rows[0].User.ID, joao.ID)
tt.AssertEqual(t, rows[0].User.Name, "João Ribeiro")
tt.AssertEqual(t, rows[0].Post.Title, "João Post1")
tt.AssertNotEqual(t, rows[0].Post.ID, 0)
tt.AssertEqual(t, rows[1].User.ID, bia.ID)
tt.AssertEqual(t, rows[1].User.Name, "Bia Ribeiro")
tt.AssertEqual(t, rows[1].Post.Title, "Bia Post1")
tt.AssertNotEqual(t, rows[1].Post.ID, 0)
tt.AssertEqual(t, rows[2].User.ID, bia.ID)
tt.AssertEqual(t, rows[2].User.Name, "Bia Ribeiro")
tt.AssertEqual(t, rows[2].Post.Title, "Bia Post2")
tt.AssertNotEqual(t, rows[2].Post.ID, 0)
})
})
t.Run("using slice of pointers to structs", func(t *testing.T) {
db, closer := newDBAdapter(t)
defer closer.Close()
err := createTables(ctx, db, dialect)
if err != nil {
t.Fatal("could not create test table!, reason:", err.Error())
}
t.Run("should return 0 results correctly", func(t *testing.T) {
c := newTestDB(db, dialect)
var users []*user
err := c.Query(ctx, &users, variation.queryPrefix+`FROM users WHERE id=1;`)
tt.AssertNoErr(t, err)
tt.AssertEqual(t, len(users), 0)
users = []*user{}
err = c.Query(ctx, &users, variation.queryPrefix+`FROM users WHERE id=1;`)
tt.AssertNoErr(t, err)
tt.AssertEqual(t, len(users), 0)
})
t.Run("should return a user correctly", func(t *testing.T) {
_, err := db.ExecContext(ctx, `INSERT INTO users (name, age, address) VALUES ('Bia', 0, '{"country":"BR"}')`)
tt.AssertNoErr(t, err)
c := newTestDB(db, dialect)
var users []*user
err = c.Query(ctx, &users, variation.queryPrefix+`FROM users WHERE name=`+c.dialect.Placeholder(0), "Bia")
tt.AssertNoErr(t, err)
tt.AssertEqual(t, len(users), 1)
tt.AssertNotEqual(t, users[0].ID, uint(0))
tt.AssertEqual(t, users[0].Name, "Bia")
tt.AssertEqual(t, users[0].Address.Country, "BR")
})
t.Run("should return multiple users correctly", func(t *testing.T) {
_, err := db.ExecContext(ctx, `INSERT INTO users (name, age, address) VALUES ('João Garcia', 0, '{"country":"US"}')`)
tt.AssertNoErr(t, err)
_, err = db.ExecContext(ctx, `INSERT INTO users (name, age, address) VALUES ('Bia Garcia', 0, '{"country":"BR"}')`)
tt.AssertNoErr(t, err)
c := newTestDB(db, dialect)
var users []*user
err = c.Query(ctx, &users, variation.queryPrefix+`FROM users WHERE name like `+c.dialect.Placeholder(0), "% Garcia")
tt.AssertNoErr(t, err)
tt.AssertEqual(t, len(users), 2)
tt.AssertNotEqual(t, users[0].ID, uint(0))
tt.AssertEqual(t, users[0].Name, "João Garcia")
tt.AssertEqual(t, users[0].Address.Country, "US")
tt.AssertNotEqual(t, users[1].ID, uint(0))
tt.AssertEqual(t, users[1].Name, "Bia Garcia")
tt.AssertEqual(t, users[1].Address.Country, "BR")
})
t.Run("should query joined tables correctly", func(t *testing.T) {
// This test only makes sense with no query prefix
if variation.queryPrefix != "" {
return
}
_, err := db.ExecContext(ctx, `INSERT INTO users (name, age, address) VALUES ('João Ribeiro', 0, '{"country":"US"}')`)
tt.AssertNoErr(t, err)
var joao user
getUserByName(db, dialect, &joao, "João Ribeiro")
_, err = db.ExecContext(ctx, `INSERT INTO users (name, age, address) VALUES ('Bia Ribeiro', 0, '{"country":"BR"}')`)
tt.AssertNoErr(t, err)
var bia user
getUserByName(db, dialect, &bia, "Bia Ribeiro")
_, err = db.ExecContext(ctx, fmt.Sprint(`INSERT INTO posts (user_id, title) VALUES (`, bia.ID, `, 'Bia Post1')`))
tt.AssertNoErr(t, err)
_, err = db.ExecContext(ctx, fmt.Sprint(`INSERT INTO posts (user_id, title) VALUES (`, bia.ID, `, 'Bia Post2')`))
tt.AssertNoErr(t, err)
_, err = db.ExecContext(ctx, fmt.Sprint(`INSERT INTO posts (user_id, title) VALUES (`, joao.ID, `, 'João Post1')`))
tt.AssertNoErr(t, err)
c := newTestDB(db, dialect)
var rows []*struct {
User user `tablename:"u"`
Post post `tablename:"p"`
}
err = c.Query(ctx, &rows, fmt.Sprint(
`FROM users u JOIN posts p ON p.user_id = u.id`,
` WHERE u.name like `, c.dialect.Placeholder(0),
` ORDER BY u.id, p.id`,
), "% Ribeiro")
tt.AssertNoErr(t, err)
tt.AssertEqual(t, len(rows), 3)
tt.AssertEqual(t, rows[0].User.ID, joao.ID)
tt.AssertEqual(t, rows[0].User.Name, "João Ribeiro")
tt.AssertEqual(t, rows[0].Post.Title, "João Post1")
tt.AssertEqual(t, rows[1].User.ID, bia.ID)
tt.AssertEqual(t, rows[1].User.Name, "Bia Ribeiro")
tt.AssertEqual(t, rows[1].Post.Title, "Bia Post1")
tt.AssertEqual(t, rows[2].User.ID, bia.ID)
tt.AssertEqual(t, rows[2].User.Name, "Bia Ribeiro")
tt.AssertEqual(t, rows[2].Post.Title, "Bia Post2")
})
})
})
}
t.Run("testing error cases", func(t *testing.T) {
db, closer := newDBAdapter(t)
defer closer.Close()
err := createTables(ctx, db, dialect)
if err != nil {
t.Fatal("could not create test table!, reason:", err.Error())
}
t.Run("should report error if input is not a pointer to a slice of structs", func(t *testing.T) {
_, err := db.ExecContext(ctx, `INSERT INTO users (name, age) VALUES ('Andréa Sá', 0)`)
tt.AssertNoErr(t, err)
_, err = db.ExecContext(ctx, `INSERT INTO users (name, age) VALUES ('Caio Sá', 0)`)
tt.AssertNoErr(t, err)
c := newTestDB(db, dialect)
err = c.Query(ctx, &user{}, `SELECT * FROM users WHERE name like `+c.dialect.Placeholder(0), "% Sá")
tt.AssertErrContains(t, err, "expected", "to be a slice", "user")
err = c.Query(ctx, []*user{}, `SELECT * FROM users WHERE name like `+c.dialect.Placeholder(0), "% Sá")
tt.AssertErrContains(t, err, "expected", "slice of structs", "user")
var i int
err = c.Query(ctx, &i, `SELECT * FROM users WHERE name like `+c.dialect.Placeholder(0), "% Sá")
tt.AssertErrContains(t, err, "expected", "to be a slice", "int")
err = c.Query(ctx, &[]int{}, `SELECT * FROM users WHERE name like `+c.dialect.Placeholder(0), "% Sá")
tt.AssertErrContains(t, err, "expected", "slice of structs", "[]int")
})
t.Run("should report error if the query is not valid", func(t *testing.T) {
c := newTestDB(db, dialect)
var users []user
err := c.Query(ctx, &users, `SELECT * FROM not a valid query`)
tt.AssertErrContains(t, err, "error running query")
})
t.Run("should report error if the TagInfoCache returns an error", func(t *testing.T) {
c := newTestDB(db, dialect)
// Provoque an error by sending an invalid struct:
var users []struct {
ID int `ksql:"id"`
// Private names cannot have ksql tags:
badPrivateField string `ksql:"name"`
}
err := c.Query(ctx, &users, `SELECT * FROM users`)
tt.AssertErrContains(t, err, "badPrivateField")
})
t.Run("should report error if using nested struct and the query starts with SELECT", func(t *testing.T) {
c := newTestDB(db, dialect)
var rows []struct {
User user `tablename:"users"`
Post post `tablename:"posts"`
}
err := c.Query(ctx, &rows, `SELECT * FROM users u JOIN posts p ON u.id = p.user_id`)
tt.AssertErrContains(t, err, "nested struct", "feature")
})
t.Run("should report error for nested structs with invalid types", func(t *testing.T) {
t.Run("int", func(t *testing.T) {
c := newTestDB(db, dialect)
var rows []struct {
Foo int `tablename:"foo"`
}
err := c.Query(ctx, &rows, fmt.Sprint(
`FROM users u JOIN posts p ON p.user_id = u.id`,
` WHERE u.name like `, c.dialect.Placeholder(0),
` ORDER BY u.id, p.id`,
), "% Ribeiro")
tt.AssertErrContains(t, err, "foo", "int")
})
t.Run("*struct", func(t *testing.T) {
c := newTestDB(db, dialect)
var rows []struct {
Foo *user `tablename:"foo"`
}
err := c.Query(ctx, &rows, fmt.Sprint(
`FROM users u JOIN posts p ON p.user_id = u.id`,
` WHERE u.name like `, c.dialect.Placeholder(0),
` ORDER BY u.id, p.id`,
), "% Ribeiro")
tt.AssertErrContains(t, err, "foo", "*ksql.user")
})
})
t.Run("should report error if nested struct is invalid", func(t *testing.T) {
c := newTestDB(db, dialect)
var rows []struct {
User user `tablename:"users"`
Post struct {
Attr1 int `ksql:"invalid_repeated_name"`
Attr2 int `ksql:"invalid_repeated_name"`
} `tablename:"posts"`
}
err := c.Query(ctx, &rows, `FROM users u JOIN posts p ON u.id = p.user_id`)
tt.AssertErrContains(t, err, "same ksql tag name", "invalid_repeated_name")
})
t.Run("should report error if DBAdapter.Scan() returns an error", func(t *testing.T) {
db := mockDBAdapter{
QueryContextFn: func(ctx context.Context, query string, args ...interface{}) (Rows, error) {
return mockRows{
ColumnsFn: func() ([]string, error) {
return []string{"id", "name", "age", "address"}, nil
},
NextFn: func() bool { return true },
ScanFn: func(values ...interface{}) error {
return fmt.Errorf("fakeScanErr")
},
}, nil
},
}
c := newTestDB(db, dialect)
var users []user
err := c.Query(ctx, &users, `SELECT * FROM users`)
tt.AssertErrContains(t, err, "KSQL", "scan error", "fakeScanErr")
})
t.Run("should report error if DBAdapter.Err() returns an error", func(t *testing.T) {
db := mockDBAdapter{
QueryContextFn: func(ctx context.Context, query string, args ...interface{}) (Rows, error) {
return mockRows{
ColumnsFn: func() ([]string, error) {
return []string{"id", "name", "age", "address"}, nil
},
NextFn: func() bool { return false },
ScanFn: func(values ...interface{}) error {
return nil
},
ErrFn: func() error {
return fmt.Errorf("fakeErrMsg")
},
}, nil
},
}
c := newTestDB(db, dialect)
var users []user
err := c.Query(ctx, &users, `SELECT * FROM users`)
tt.AssertErrContains(t, err, "KSQL", "fakeErrMsg")
})
t.Run("should report error if DBAdapter.Close() returns an error", func(t *testing.T) {
db := mockDBAdapter{
QueryContextFn: func(ctx context.Context, query string, args ...interface{}) (Rows, error) {
return mockRows{
ColumnsFn: func() ([]string, error) {
return []string{"id", "name", "age", "address"}, nil
},
NextFn: func() bool { return false },
ScanFn: func(values ...interface{}) error {
return nil
},
CloseFn: func() error {
return fmt.Errorf("fakeCloseErr")
},
}, nil
},
}
c := newTestDB(db, dialect)
var users []user
err := c.Query(ctx, &users, `SELECT * FROM users`)
tt.AssertErrContains(t, err, "KSQL", "fakeCloseErr")
})
t.Run("should report error context.Canceled if the context is canceled", func(t *testing.T) {
ctx, cancel := context.WithCancel(ctx)
cancel()
c := newTestDB(db, dialect)
var users []user
err := c.Query(ctx, &users, `SELECT * FROM users`)
tt.AssertErrContains(t, err, "context", "canceled")
tt.AssertEqual(t, errors.Is(err, context.Canceled), true)
})
})
})
}
// QueryOneTest runs all tests for making sure the QueryOne function is
// working for a given adapter and dialect.
func QueryOneTest(
t *testing.T,
dialect sqldialect.Provider,
connStr string,
newDBAdapter func(t *testing.T) (DBAdapter, io.Closer),
) {
ctx := context.Background()
t.Run("QueryOne", func(t *testing.T) {
variations := []struct {
desc string
queryPrefix string
}{
{
desc: "with select *",
queryPrefix: "SELECT * ",
},
{
desc: "building the SELECT part of the query internally",
queryPrefix: "",
},
}
for _, variation := range variations {
t.Run(variation.desc, func(t *testing.T) {
db, closer := newDBAdapter(t)
defer closer.Close()
err := createTables(ctx, db, dialect)
if err != nil {
t.Fatal("could not create test table!, reason:", err.Error())
}
t.Run("should return RecordNotFoundErr when there are no results", func(t *testing.T) {
c := newTestDB(db, dialect)
u := user{}
err := c.QueryOne(ctx, &u, variation.queryPrefix+`FROM users WHERE id=1;`)
tt.AssertEqual(t, err, ErrRecordNotFound)
})
t.Run("should return a user correctly", func(t *testing.T) {
_, err := db.ExecContext(ctx, `INSERT INTO users (name, age, address) VALUES ('Bia', 0, '{"country":"BR"}')`)
tt.AssertNoErr(t, err)
c := newTestDB(db, dialect)
u := user{}
err = c.QueryOne(ctx, &u, variation.queryPrefix+`FROM users WHERE name=`+c.dialect.Placeholder(0), "Bia")
tt.AssertNoErr(t, err)
tt.AssertNotEqual(t, u.ID, uint(0))
tt.AssertEqual(t, u.Name, "Bia")
tt.AssertEqual(t, u.Address, address{
Country: "BR",
})
})
t.Run("should return only the first result on multiples matches", func(t *testing.T) {
_, err := db.ExecContext(ctx, `INSERT INTO users (name, age, address) VALUES ('Andréa Sá', 0, '{"country":"US"}')`)
tt.AssertNoErr(t, err)
_, err = db.ExecContext(ctx, `INSERT INTO users (name, age, address) VALUES ('Caio Sá', 0, '{"country":"BR"}')`)
tt.AssertNoErr(t, err)
c := newTestDB(db, dialect)
var u user
err = c.QueryOne(ctx, &u, variation.queryPrefix+`FROM users WHERE name like `+c.dialect.Placeholder(0)+` ORDER BY id ASC`, "% Sá")
tt.AssertNoErr(t, err)
tt.AssertEqual(t, u.Name, "Andréa Sá")
tt.AssertEqual(t, u.Age, 0)
tt.AssertEqual(t, u.Address, address{
Country: "US",
})
})
t.Run("should query joined tables correctly", func(t *testing.T) {
// This test only makes sense with no query prefix
if variation.queryPrefix != "" {
return
}
_, err := db.ExecContext(ctx, `INSERT INTO users (name, age, address) VALUES ('João Ribeiro', 0, '{"country":"US"}')`)
tt.AssertNoErr(t, err)
var joao user
getUserByName(db, dialect, &joao, "João Ribeiro")
_, err = db.ExecContext(ctx, fmt.Sprint(`INSERT INTO posts (user_id, title) VALUES (`, joao.ID, `, 'João Post1')`))
tt.AssertNoErr(t, err)
c := newTestDB(db, dialect)
var row struct {
User user `tablename:"u"`
Post post `tablename:"p"`
}
err = c.QueryOne(ctx, &row, fmt.Sprint(
`FROM users u JOIN posts p ON p.user_id = u.id`,
` WHERE u.name like `, c.dialect.Placeholder(0),
` ORDER BY u.id, p.id`,
), "% Ribeiro")
tt.AssertNoErr(t, err)
tt.AssertEqual(t, row.User.ID, joao.ID)
tt.AssertEqual(t, row.User.Name, "João Ribeiro")
tt.AssertEqual(t, row.Post.Title, "João Post1")
})
t.Run("should handle column tags as case-insensitive as SQL does", func(t *testing.T) {
_, err := db.ExecContext(ctx, `INSERT INTO users (name, age, address) VALUES ('Count Olivia', 0, '{"country":"US"}')`)
tt.AssertNoErr(t, err)
c := newTestDB(db, dialect)
var row struct {
Count int `ksql:"myCount"`
}
err = c.QueryOne(ctx, &row, `SELECT count(*) as myCount FROM users WHERE name='Count Olivia'`)
tt.AssertNoErr(t, err)
tt.AssertEqual(t, row.Count, 1)
})
})
}
t.Run("should report error if input is not a pointer to struct", func(t *testing.T) {
db, closer := newDBAdapter(t)
defer closer.Close()
_, err := db.ExecContext(ctx, `INSERT INTO users (name, age, address) VALUES ('Andréa Sá', 0, '{"country":"US"}')`)
tt.AssertNoErr(t, err)
_, err = db.ExecContext(ctx, `INSERT INTO users (name, age, address) VALUES ('Caio Sá', 0, '{"country":"BR"}')`)
tt.AssertNoErr(t, err)
c := newTestDB(db, dialect)
err = c.QueryOne(ctx, &[]user{}, `SELECT * FROM users WHERE name like `+c.dialect.Placeholder(0), "% Sá")
tt.AssertErrContains(t, err, "pointer to struct")
err = c.QueryOne(ctx, user{}, `SELECT * FROM users WHERE name like `+c.dialect.Placeholder(0), "% Sá")
tt.AssertErrContains(t, err, "pointer to struct")
})
t.Run("should report error if it receives a nil pointer to a struct", func(t *testing.T) {
db, closer := newDBAdapter(t)
defer closer.Close()
c := newTestDB(db, dialect)
var u *user
err := c.QueryOne(ctx, u, `SELECT * FROM users`)
tt.AssertErrContains(t, err, "expected a valid pointer", "received a nil pointer")
})
t.Run("should report error if the query is not valid", func(t *testing.T) {
db, closer := newDBAdapter(t)
defer closer.Close()
c := newTestDB(db, dialect)
var u user
err := c.QueryOne(ctx, &u, `SELECT * FROM not a valid query`)
tt.AssertErrContains(t, err, "error running query")
})
t.Run("should report error if using nested struct and the query starts with SELECT", func(t *testing.T) {
db, closer := newDBAdapter(t)
defer closer.Close()
c := newTestDB(db, dialect)
var row struct {
User user `tablename:"users"`
Post post `tablename:"posts"`
}
err := c.QueryOne(ctx, &row, `SELECT * FROM users u JOIN posts p ON u.id = p.user_id LIMIT 1`)
tt.AssertErrContains(t, err, "nested struct", "feature")
})
t.Run("should report error if a private field has a ksql tag", func(t *testing.T) {
db, closer := newDBAdapter(t)
defer closer.Close()
_, err := db.ExecContext(ctx, `INSERT INTO users (name, age, address) VALUES ('Olivia', 0, '{"country":"US"}')`)
tt.AssertNoErr(t, err)
c := newTestDB(db, dialect)
var row struct {
count int `ksql:"my_count"`
}
err = c.QueryOne(ctx, &row, `SELECT count(*) as my_count FROM users`)
tt.AssertErrContains(t, err, "unexported", "my_count")
})
t.Run("should report error context.Canceled the context has been canceled", func(t *testing.T) {
db, closer := newDBAdapter(t)
defer closer.Close()
ctx, cancel := context.WithCancel(ctx)
cancel()
c := newTestDB(db, dialect)
var u user
err := c.QueryOne(ctx, &u, `SELECT * FROM users LIMIT 1`)
tt.AssertEqual(t, errors.Is(err, context.Canceled), true)
})
})
}
// InsertTest runs all tests for making sure the Insert function is
// working for a given adapter and dialect.
func InsertTest(
t *testing.T,
dialect sqldialect.Provider,
connStr string,
newDBAdapter func(t *testing.T) (DBAdapter, io.Closer),
) {
ctx := context.Background()
t.Run("Insert", func(t *testing.T) {
t.Run("success cases", func(t *testing.T) {
t.Run("single primary key tables", func(t *testing.T) {
db, closer := newDBAdapter(t)
defer closer.Close()
err := createTables(ctx, db, dialect)
if err != nil {
t.Fatal("could not create test table!, reason:", err.Error())
}
t.Run("should insert one user correctly", func(t *testing.T) {
c := newTestDB(db, dialect)
u := user{
Name: "Fernanda",
Address: address{
Country: "Brazil",
},
}
err := c.Insert(ctx, usersTable, &u)
tt.AssertNoErr(t, err)
tt.AssertNotEqual(t, u.ID, 0)
result := user{}
err = getUserByID(c.db, c.dialect, &result, u.ID)
tt.AssertNoErr(t, err)
tt.AssertEqual(t, result.Name, u.Name)
tt.AssertEqual(t, result.Address, u.Address)
})
t.Run("should insert one user correctly with a string ID", func(t *testing.T) {
c := newTestDB(db, dialect)
type strIDUser struct {
Name string `ksql:"name"`
Age int `ksql:"age"`
Address address `ksql:"address,json"`
}
u := strIDUser{
Name: "FernandaIsTheID",
Address: address{
Country: "Brazil",
},
Age: 42,
}
err := c.Insert(ctx, NewTable("users", "name"), &u)
tt.AssertNoErr(t, err)
tt.AssertEqual(t, u.Name, "FernandaIsTheID")
result := user{}
err = getUserByName(db, dialect, &result, "FernandaIsTheID")
tt.AssertNoErr(t, err)
tt.AssertEqual(t, result.Name, u.Name)
tt.AssertEqual(t, result.Address, u.Address)
})
t.Run("should insert one user correctly when the ID is a pointer to string", func(t *testing.T) {
c := newTestDB(db, dialect)
type ptrUser struct {
Name *string `ksql:"name"`
Address address `ksql:"address,json"`
}
name := "FernandaIsTheID"
u := ptrUser{
Name: &name,
Address: address{
Country: "Brazil",
},
}
err := c.Insert(ctx, NewTable("users", "name"), &u)
tt.AssertNoErr(t, err)
tt.AssertEqual(t, u.Name, &name)
result := user{}
err = getUserByName(db, dialect, &result, "FernandaIsTheID")
tt.AssertNoErr(t, err)
tt.AssertEqual(t, &result.Name, u.Name)
tt.AssertEqual(t, result.Address, u.Address)
})
t.Run("should insert one user correctly when the ID is a pointer to int allocating memory when nil", func(t *testing.T) {
c := newTestDB(db, dialect)
type ptrUser struct {
ID *uint `ksql:"id"`
Name string `ksql:"name"`
Address address `ksql:"address,json"`
Age int `ksql:"age"`
}
u := ptrUser{
Name: "Paulo",
Address: address{
Country: "Brazil",
},
}
err := c.Insert(ctx, usersTable, &u)
tt.AssertNoErr(t, err)
tt.AssertNotEqual(t, u.ID, nil)
result := user{}
err = getUserByID(db, dialect, &result, *u.ID)
tt.AssertNoErr(t, err)
tt.AssertEqual(t, result.Name, u.Name)
tt.AssertEqual(t, result.Address, u.Address)
})
t.Run("should insert ignoring the ID with multiple ids", func(t *testing.T) {
if dialect.InsertMethod() != sqldialect.InsertWithLastInsertID {
return
}
// Using columns "id" and "name" as IDs:
table := NewTable("users", "id", "name")
c := newTestDB(db, dialect)
u := user{
Name: "No ID returned",
Age: 3434, // Random number to avoid false positives on this test
Address: address{
Country: "Brazil 3434",
},
}
err = c.Insert(ctx, table, &u)
tt.AssertNoErr(t, err)
tt.AssertEqual(t, u.ID, uint(0))
result := user{}
err = getUserByName(c.db, dialect, &result, "No ID returned")
tt.AssertNoErr(t, err)
tt.AssertEqual(t, result.Age, u.Age)
tt.AssertEqual(t, result.Address, u.Address)
})
t.Run("should work with anonymous structs", func(t *testing.T) {
c := newTestDB(db, dialect)
err = c.Insert(ctx, usersTable, &struct {
ID int `ksql:"id"`
Name string `ksql:"name"`
Address map[string]interface{} `ksql:"address,json"`
}{Name: "fake-name", Address: map[string]interface{}{"city": "bar"}})
tt.AssertNoErr(t, err)
})
t.Run("should work with preset IDs", func(t *testing.T) {
c := newTestDB(db, dialect)
usersByName := NewTable("users", "name")
err = c.Insert(ctx, usersByName, &struct {
Name string `ksql:"name"`
Age int `ksql:"age"`
}{Name: "Preset Name", Age: 5455})
tt.AssertNoErr(t, err)
var inserted user
err := getUserByName(db, dialect, &inserted, "Preset Name")
tt.AssertNoErr(t, err)
tt.AssertEqual(t, inserted.Age, 5455)
})
t.Run("should work and retrieve the ID for structs with no attributes", func(t *testing.T) {
c := newTestDB(db, dialect)
type tsUser struct {
ID uint `ksql:"id"`
Name string `ksql:"name,skipInserts"`
}
u := tsUser{
Name: "Letícia",
}
err := c.Insert(ctx, usersTable, &u)
tt.AssertNoErr(t, err)
tt.AssertNotEqual(t, u.ID, 0)
var untaggedUser struct {
ID uint `ksql:"id"`
Name *string `ksql:"name"`
}
err = c.QueryOne(ctx, &untaggedUser, `FROM users WHERE id = `+c.dialect.Placeholder(0), u.ID)
tt.AssertNoErr(t, err)
tt.AssertEqual(t, untaggedUser.Name, (*string)(nil))
})
t.Run("should work even when ksql.NewTable receives a qualified table name", func(t *testing.T) {
c := newTestDB(db, dialect)
u := user{
Name: "Amanda",
Address: address{
Country: "Brasil",
},
}
var err error
switch dialect.DriverName() {
case "postgres":
// public is the default schema name for postgres:
err = c.Insert(ctx, NewTable("public.users"), &u)
case "sqlserver":
// dbo is the default schema name for sqlserver:
err = c.Insert(ctx, NewTable("dbo.users"), &u)
case "sqlite3":
// main is the default schema name for sqlite:
err = c.Insert(ctx, NewTable("main.users"), &u)
case "mysql":
err = c.Insert(ctx, NewTable("ksql.users"), &u)
}
tt.AssertNoErr(t, err)
tt.AssertNotEqual(t, u.ID, 0)
result := user{}
err = getUserByID(c.db, c.dialect, &result, u.ID)
tt.AssertNoErr(t, err)
tt.AssertEqual(t, result.Name, u.Name)
tt.AssertEqual(t, result.Address, u.Address)
})
})
t.Run("composite key tables", func(t *testing.T) {
db, closer := newDBAdapter(t)
defer closer.Close()
err := createTables(ctx, db, dialect)
if err != nil {
t.Fatal("could not create test table!, reason:", err.Error())
}
t.Run("should insert in composite key tables correctly", func(t *testing.T) {
c := newTestDB(db, dialect)