forked from longquanzheng/sqlx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sqlx_context_test.go
1344 lines (1208 loc) · 36.5 KB
/
sqlx_context_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
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
// +build go1.8
// The following environment variables, if set, will be used:
//
// * SQLX_SQLITE_DSN
// * SQLX_POSTGRES_DSN
// * SQLX_MYSQL_DSN
//
// Set any of these variables to 'skip' to skip them. Note that for MySQL,
// the string '?parseTime=True' will be appended to the DSN if it's not there
// already.
//
package sqlx
import (
"context"
"database/sql"
"encoding/json"
"fmt"
"log"
"strings"
"testing"
"time"
_ "github.com/go-sql-driver/mysql"
"github.com/jmoiron/sqlx/reflectx"
_ "github.com/lib/pq"
_ "github.com/mattn/go-sqlite3"
)
func MultiExecContext(ctx context.Context, e ExecerContext, query string) {
stmts := strings.Split(query, ";\n")
if len(strings.Trim(stmts[len(stmts)-1], " \n\t\r")) == 0 {
stmts = stmts[:len(stmts)-1]
}
for _, s := range stmts {
_, err := e.ExecContext(ctx, s)
if err != nil {
fmt.Println(err, s)
}
}
}
func RunWithSchemaContext(ctx context.Context, schema Schema, t *testing.T, test func(ctx context.Context, db *DB, t *testing.T)) {
runner := func(ctx context.Context, db *DB, t *testing.T, create, drop string) {
defer func() {
MultiExecContext(ctx, db, drop)
}()
MultiExecContext(ctx, db, create)
test(ctx, db, t)
}
if TestPostgres {
create, drop := schema.Postgres()
runner(ctx, pgdb, t, create, drop)
}
if TestSqlite {
create, drop := schema.Sqlite3()
runner(ctx, sldb, t, create, drop)
}
if TestMysql {
create, drop := schema.MySQL()
runner(ctx, mysqldb, t, create, drop)
}
}
func loadDefaultFixtureContext(ctx context.Context, db *DB, t *testing.T) {
tx := db.MustBeginTx(ctx, nil)
tx.MustExecContext(ctx, tx.Rebind("INSERT INTO person (first_name, last_name, email) VALUES (?, ?, ?)"), "Jason", "Moiron", "[email protected]")
tx.MustExecContext(ctx, tx.Rebind("INSERT INTO person (first_name, last_name, email) VALUES (?, ?, ?)"), "John", "Doe", "[email protected]")
tx.MustExecContext(ctx, tx.Rebind("INSERT INTO place (country, city, telcode) VALUES (?, ?, ?)"), "United States", "New York", "1")
tx.MustExecContext(ctx, tx.Rebind("INSERT INTO place (country, telcode) VALUES (?, ?)"), "Hong Kong", "852")
tx.MustExecContext(ctx, tx.Rebind("INSERT INTO place (country, telcode) VALUES (?, ?)"), "Singapore", "65")
if db.DriverName() == "mysql" {
tx.MustExecContext(ctx, tx.Rebind("INSERT INTO capplace (`COUNTRY`, `TELCODE`) VALUES (?, ?)"), "Sarf Efrica", "27")
} else {
tx.MustExecContext(ctx, tx.Rebind("INSERT INTO capplace (\"COUNTRY\", \"TELCODE\") VALUES (?, ?)"), "Sarf Efrica", "27")
}
tx.MustExecContext(ctx, tx.Rebind("INSERT INTO employees (name, id) VALUES (?, ?)"), "Peter", "4444")
tx.MustExecContext(ctx, tx.Rebind("INSERT INTO employees (name, id, boss_id) VALUES (?, ?, ?)"), "Joe", "1", "4444")
tx.MustExecContext(ctx, tx.Rebind("INSERT INTO employees (name, id, boss_id) VALUES (?, ?, ?)"), "Martin", "2", "4444")
tx.Commit()
}
// Test a new backwards compatible feature, that missing scan destinations
// will silently scan into sql.RawText rather than failing/panicing
func TestMissingNamesContextContext(t *testing.T) {
RunWithSchemaContext(context.Background(), defaultSchema, t, func(ctx context.Context, db *DB, t *testing.T) {
loadDefaultFixtureContext(ctx, db, t)
type PersonPlus struct {
FirstName string `db:"first_name"`
LastName string `db:"last_name"`
Email string
//AddedAt time.Time `db:"added_at"`
}
// test Select first
pps := []PersonPlus{}
// pps lacks added_at destination
err := db.SelectContext(ctx, &pps, "SELECT * FROM person")
if err == nil {
t.Error("Expected missing name from Select to fail, but it did not.")
}
// test Get
pp := PersonPlus{}
err = db.GetContext(ctx, &pp, "SELECT * FROM person LIMIT 1")
if err == nil {
t.Error("Expected missing name Get to fail, but it did not.")
}
// test naked StructScan
pps = []PersonPlus{}
rows, err := db.QueryContext(ctx, "SELECT * FROM person LIMIT 1")
if err != nil {
t.Fatal(err)
}
rows.Next()
err = StructScan(rows, &pps)
if err == nil {
t.Error("Expected missing name in StructScan to fail, but it did not.")
}
rows.Close()
// now try various things with unsafe set.
db = db.Unsafe()
pps = []PersonPlus{}
err = db.SelectContext(ctx, &pps, "SELECT * FROM person")
if err != nil {
t.Error(err)
}
// test Get
pp = PersonPlus{}
err = db.GetContext(ctx, &pp, "SELECT * FROM person LIMIT 1")
if err != nil {
t.Error(err)
}
// test naked StructScan
pps = []PersonPlus{}
rowsx, err := db.QueryxContext(ctx, "SELECT * FROM person LIMIT 1")
if err != nil {
t.Fatal(err)
}
rowsx.Next()
err = StructScan(rowsx, &pps)
if err != nil {
t.Error(err)
}
rowsx.Close()
// test Named stmt
if !isUnsafe(db) {
t.Error("Expected db to be unsafe, but it isn't")
}
nstmt, err := db.PrepareNamedContext(ctx, `SELECT * FROM person WHERE first_name != :name`)
if err != nil {
t.Fatal(err)
}
// its internal stmt should be marked unsafe
if !nstmt.Stmt.unsafe {
t.Error("expected NamedStmt to be unsafe but its underlying stmt did not inherit safety")
}
pps = []PersonPlus{}
err = nstmt.SelectContext(ctx, &pps, map[string]interface{}{"name": "Jason"})
if err != nil {
t.Fatal(err)
}
if len(pps) != 1 {
t.Errorf("Expected 1 person back, got %d", len(pps))
}
// test it with a safe db
db.unsafe = false
if isUnsafe(db) {
t.Error("expected db to be safe but it isn't")
}
nstmt, err = db.PrepareNamedContext(ctx, `SELECT * FROM person WHERE first_name != :name`)
if err != nil {
t.Fatal(err)
}
// it should be safe
if isUnsafe(nstmt) {
t.Error("NamedStmt did not inherit safety")
}
nstmt.Unsafe()
if !isUnsafe(nstmt) {
t.Error("expected newly unsafed NamedStmt to be unsafe")
}
pps = []PersonPlus{}
err = nstmt.SelectContext(ctx, &pps, map[string]interface{}{"name": "Jason"})
if err != nil {
t.Fatal(err)
}
if len(pps) != 1 {
t.Errorf("Expected 1 person back, got %d", len(pps))
}
})
}
func TestEmbeddedStructsContextContext(t *testing.T) {
type Loop1 struct{ Person }
type Loop2 struct{ Loop1 }
type Loop3 struct{ Loop2 }
RunWithSchemaContext(context.Background(), defaultSchema, t, func(ctx context.Context, db *DB, t *testing.T) {
loadDefaultFixtureContext(ctx, db, t)
peopleAndPlaces := []PersonPlace{}
err := db.SelectContext(
ctx,
&peopleAndPlaces,
`SELECT person.*, place.* FROM
person natural join place`)
if err != nil {
t.Fatal(err)
}
for _, pp := range peopleAndPlaces {
if len(pp.Person.FirstName) == 0 {
t.Errorf("Expected non zero lengthed first name.")
}
if len(pp.Place.Country) == 0 {
t.Errorf("Expected non zero lengthed country.")
}
}
// test embedded structs with StructScan
rows, err := db.QueryxContext(
ctx,
`SELECT person.*, place.* FROM
person natural join place`)
if err != nil {
t.Error(err)
}
perp := PersonPlace{}
rows.Next()
err = rows.StructScan(&perp)
if err != nil {
t.Error(err)
}
if len(perp.Person.FirstName) == 0 {
t.Errorf("Expected non zero lengthed first name.")
}
if len(perp.Place.Country) == 0 {
t.Errorf("Expected non zero lengthed country.")
}
rows.Close()
// test the same for embedded pointer structs
peopleAndPlacesPtrs := []PersonPlacePtr{}
err = db.SelectContext(
ctx,
&peopleAndPlacesPtrs,
`SELECT person.*, place.* FROM
person natural join place`)
if err != nil {
t.Fatal(err)
}
for _, pp := range peopleAndPlacesPtrs {
if len(pp.Person.FirstName) == 0 {
t.Errorf("Expected non zero lengthed first name.")
}
if len(pp.Place.Country) == 0 {
t.Errorf("Expected non zero lengthed country.")
}
}
// test "deep nesting"
l3s := []Loop3{}
err = db.SelectContext(ctx, &l3s, `select * from person`)
if err != nil {
t.Fatal(err)
}
for _, l3 := range l3s {
if len(l3.Loop2.Loop1.Person.FirstName) == 0 {
t.Errorf("Expected non zero lengthed first name.")
}
}
// test "embed conflicts"
ec := []EmbedConflict{}
err = db.SelectContext(ctx, &ec, `select * from person`)
// I'm torn between erroring here or having some kind of working behavior
// in order to allow for more flexibility in destination structs
if err != nil {
t.Errorf("Was not expecting an error on embed conflicts.")
}
})
}
func TestJoinQueryContext(t *testing.T) {
type Employee struct {
Name string
ID int64
// BossID is an id into the employee table
BossID sql.NullInt64 `db:"boss_id"`
}
type Boss Employee
RunWithSchemaContext(context.Background(), defaultSchema, t, func(ctx context.Context, db *DB, t *testing.T) {
loadDefaultFixtureContext(ctx, db, t)
var employees []struct {
Employee
Boss `db:"boss"`
}
err := db.SelectContext(ctx,
&employees,
`SELECT employees.*, boss.id "boss.id", boss.name "boss.name" FROM employees
JOIN employees AS boss ON employees.boss_id = boss.id`)
if err != nil {
t.Fatal(err)
}
for _, em := range employees {
if len(em.Employee.Name) == 0 {
t.Errorf("Expected non zero lengthed name.")
}
if em.Employee.BossID.Int64 != em.Boss.ID {
t.Errorf("Expected boss ids to match")
}
}
})
}
func TestJoinQueryNamedPointerStructsContext(t *testing.T) {
type Employee struct {
Name string
ID int64
// BossID is an id into the employee table
BossID sql.NullInt64 `db:"boss_id"`
}
type Boss Employee
RunWithSchemaContext(context.Background(), defaultSchema, t, func(ctx context.Context, db *DB, t *testing.T) {
loadDefaultFixtureContext(ctx, db, t)
var employees []struct {
Emp1 *Employee `db:"emp1"`
Emp2 *Employee `db:"emp2"`
*Boss `db:"boss"`
}
err := db.SelectContext(ctx,
&employees,
`SELECT emp.name "emp1.name", emp.id "emp1.id", emp.boss_id "emp1.boss_id",
emp.name "emp2.name", emp.id "emp2.id", emp.boss_id "emp2.boss_id",
boss.id "boss.id", boss.name "boss.name" FROM employees AS emp
JOIN employees AS boss ON emp.boss_id = boss.id
`)
if err != nil {
t.Fatal(err)
}
for _, em := range employees {
if len(em.Emp1.Name) == 0 || len(em.Emp2.Name) == 0 {
t.Errorf("Expected non zero lengthed name.")
}
if em.Emp1.BossID.Int64 != em.Boss.ID || em.Emp2.BossID.Int64 != em.Boss.ID {
t.Errorf("Expected boss ids to match")
}
}
})
}
func TestSelectSliceMapTimeContext(t *testing.T) {
RunWithSchemaContext(context.Background(), defaultSchema, t, func(ctx context.Context, db *DB, t *testing.T) {
loadDefaultFixtureContext(ctx, db, t)
rows, err := db.QueryxContext(ctx, "SELECT * FROM person")
if err != nil {
t.Fatal(err)
}
for rows.Next() {
_, err := rows.SliceScan()
if err != nil {
t.Error(err)
}
}
rows, err = db.QueryxContext(ctx, "SELECT * FROM person")
if err != nil {
t.Fatal(err)
}
for rows.Next() {
m := map[string]interface{}{}
err := rows.MapScan(m)
if err != nil {
t.Error(err)
}
}
})
}
func TestNilReceiverContext(t *testing.T) {
RunWithSchemaContext(context.Background(), defaultSchema, t, func(ctx context.Context, db *DB, t *testing.T) {
loadDefaultFixtureContext(ctx, db, t)
var p *Person
err := db.GetContext(ctx, p, "SELECT * FROM person LIMIT 1")
if err == nil {
t.Error("Expected error when getting into nil struct ptr.")
}
var pp *[]Person
err = db.SelectContext(ctx, pp, "SELECT * FROM person")
if err == nil {
t.Error("Expected an error when selecting into nil slice ptr.")
}
})
}
func TestNamedQueryContext(t *testing.T) {
var schema = Schema{
create: `
CREATE TABLE place (
id integer PRIMARY KEY,
name text NULL
);
CREATE TABLE person (
first_name text NULL,
last_name text NULL,
email text NULL
);
CREATE TABLE placeperson (
first_name text NULL,
last_name text NULL,
email text NULL,
place_id integer NULL
);
CREATE TABLE jsperson (
"FIRST" text NULL,
last_name text NULL,
"EMAIL" text NULL
);`,
drop: `
drop table person;
drop table jsperson;
drop table place;
drop table placeperson;
`,
}
RunWithSchemaContext(context.Background(), schema, t, func(ctx context.Context, db *DB, t *testing.T) {
type Person struct {
FirstName sql.NullString `db:"first_name"`
LastName sql.NullString `db:"last_name"`
Email sql.NullString
}
p := Person{
FirstName: sql.NullString{String: "ben", Valid: true},
LastName: sql.NullString{String: "doe", Valid: true},
Email: sql.NullString{String: "[email protected]", Valid: true},
}
q1 := `INSERT INTO person (first_name, last_name, email) VALUES (:first_name, :last_name, :email)`
_, err := db.NamedExecContext(ctx, q1, p)
if err != nil {
log.Fatal(err)
}
p2 := &Person{}
rows, err := db.NamedQueryContext(ctx, "SELECT * FROM person WHERE first_name=:first_name", p)
if err != nil {
log.Fatal(err)
}
for rows.Next() {
err = rows.StructScan(p2)
if err != nil {
t.Error(err)
}
if p2.FirstName.String != "ben" {
t.Error("Expected first name of `ben`, got " + p2.FirstName.String)
}
if p2.LastName.String != "doe" {
t.Error("Expected first name of `doe`, got " + p2.LastName.String)
}
}
// these are tests for #73; they verify that named queries work if you've
// changed the db mapper. This code checks both NamedQuery "ad-hoc" style
// queries and NamedStmt queries, which use different code paths internally.
old := *db.Mapper
type JSONPerson struct {
FirstName sql.NullString `json:"FIRST"`
LastName sql.NullString `json:"last_name"`
Email sql.NullString
}
jp := JSONPerson{
FirstName: sql.NullString{String: "ben", Valid: true},
LastName: sql.NullString{String: "smith", Valid: true},
Email: sql.NullString{String: "[email protected]", Valid: true},
}
db.Mapper = reflectx.NewMapperFunc("json", strings.ToUpper)
// prepare queries for case sensitivity to test our ToUpper function.
// postgres and sqlite accept "", but mysql uses ``; since Go's multi-line
// strings are `` we use "" by default and swap out for MySQL
pdb := func(s string, db *DB) string {
if db.DriverName() == "mysql" {
return strings.Replace(s, `"`, "`", -1)
}
return s
}
q1 = `INSERT INTO jsperson ("FIRST", last_name, "EMAIL") VALUES (:FIRST, :last_name, :EMAIL)`
_, err = db.NamedExecContext(ctx, pdb(q1, db), jp)
if err != nil {
t.Fatal(err, db.DriverName())
}
// Checks that a person pulled out of the db matches the one we put in
check := func(t *testing.T, rows *Rows) {
jp = JSONPerson{}
for rows.Next() {
err = rows.StructScan(&jp)
if err != nil {
t.Error(err)
}
if jp.FirstName.String != "ben" {
t.Errorf("Expected first name of `ben`, got `%s` (%s) ", jp.FirstName.String, db.DriverName())
}
if jp.LastName.String != "smith" {
t.Errorf("Expected LastName of `smith`, got `%s` (%s)", jp.LastName.String, db.DriverName())
}
if jp.Email.String != "[email protected]" {
t.Errorf("Expected first name of `doe`, got `%s` (%s)", jp.Email.String, db.DriverName())
}
}
}
ns, err := db.PrepareNamed(pdb(`
SELECT * FROM jsperson
WHERE
"FIRST"=:FIRST AND
last_name=:last_name AND
"EMAIL"=:EMAIL
`, db))
if err != nil {
t.Fatal(err)
}
rows, err = ns.QueryxContext(ctx, jp)
if err != nil {
t.Fatal(err)
}
check(t, rows)
// Check exactly the same thing, but with db.NamedQuery, which does not go
// through the PrepareNamed/NamedStmt path.
rows, err = db.NamedQueryContext(ctx, pdb(`
SELECT * FROM jsperson
WHERE
"FIRST"=:FIRST AND
last_name=:last_name AND
"EMAIL"=:EMAIL
`, db), jp)
if err != nil {
t.Fatal(err)
}
check(t, rows)
db.Mapper = &old
// Test nested structs
type Place struct {
ID int `db:"id"`
Name sql.NullString `db:"name"`
}
type PlacePerson struct {
FirstName sql.NullString `db:"first_name"`
LastName sql.NullString `db:"last_name"`
Email sql.NullString
Place Place `db:"place"`
}
pl := Place{
Name: sql.NullString{String: "myplace", Valid: true},
}
pp := PlacePerson{
FirstName: sql.NullString{String: "ben", Valid: true},
LastName: sql.NullString{String: "doe", Valid: true},
Email: sql.NullString{String: "[email protected]", Valid: true},
}
q2 := `INSERT INTO place (id, name) VALUES (1, :name)`
_, err = db.NamedExecContext(ctx, q2, pl)
if err != nil {
log.Fatal(err)
}
id := 1
pp.Place.ID = id
q3 := `INSERT INTO placeperson (first_name, last_name, email, place_id) VALUES (:first_name, :last_name, :email, :place.id)`
_, err = db.NamedExecContext(ctx, q3, pp)
if err != nil {
log.Fatal(err)
}
pp2 := &PlacePerson{}
rows, err = db.NamedQueryContext(ctx, `
SELECT
first_name,
last_name,
email,
place.id AS "place.id",
place.name AS "place.name"
FROM placeperson
INNER JOIN place ON place.id = placeperson.place_id
WHERE
place.id=:place.id`, pp)
if err != nil {
log.Fatal(err)
}
for rows.Next() {
err = rows.StructScan(pp2)
if err != nil {
t.Error(err)
}
if pp2.FirstName.String != "ben" {
t.Error("Expected first name of `ben`, got " + pp2.FirstName.String)
}
if pp2.LastName.String != "doe" {
t.Error("Expected first name of `doe`, got " + pp2.LastName.String)
}
if pp2.Place.Name.String != "myplace" {
t.Error("Expected place name of `myplace`, got " + pp2.Place.Name.String)
}
if pp2.Place.ID != pp.Place.ID {
t.Errorf("Expected place name of %v, got %v", pp.Place.ID, pp2.Place.ID)
}
}
})
}
func TestNilInsertsContext(t *testing.T) {
var schema = Schema{
create: `
CREATE TABLE tt (
id integer,
value text NULL DEFAULT NULL
);`,
drop: "drop table tt;",
}
RunWithSchemaContext(context.Background(), schema, t, func(ctx context.Context, db *DB, t *testing.T) {
type TT struct {
ID int
Value *string
}
var v, v2 TT
r := db.Rebind
db.MustExecContext(ctx, r(`INSERT INTO tt (id) VALUES (1)`))
db.GetContext(ctx, &v, r(`SELECT * FROM tt`))
if v.ID != 1 {
t.Errorf("Expecting id of 1, got %v", v.ID)
}
if v.Value != nil {
t.Errorf("Expecting NULL to map to nil, got %s", *v.Value)
}
v.ID = 2
// NOTE: this incidentally uncovered a bug which was that named queries with
// pointer destinations would not work if the passed value here was not addressable,
// as reflectx.FieldByIndexes attempts to allocate nil pointer receivers for
// writing. This was fixed by creating & using the reflectx.FieldByIndexesReadOnly
// function. This next line is important as it provides the only coverage for this.
db.NamedExecContext(ctx, `INSERT INTO tt (id, value) VALUES (:id, :value)`, v)
db.GetContext(ctx, &v2, r(`SELECT * FROM tt WHERE id=2`))
if v.ID != v2.ID {
t.Errorf("%v != %v", v.ID, v2.ID)
}
if v2.Value != nil {
t.Errorf("Expecting NULL to map to nil, got %s", *v.Value)
}
})
}
func TestScanErrorContext(t *testing.T) {
var schema = Schema{
create: `
CREATE TABLE kv (
k text,
v integer
);`,
drop: `drop table kv;`,
}
RunWithSchemaContext(context.Background(), schema, t, func(ctx context.Context, db *DB, t *testing.T) {
type WrongTypes struct {
K int
V string
}
_, err := db.Exec(db.Rebind("INSERT INTO kv (k, v) VALUES (?, ?)"), "hi", 1)
if err != nil {
t.Error(err)
}
rows, err := db.QueryxContext(ctx, "SELECT * FROM kv")
if err != nil {
t.Error(err)
}
for rows.Next() {
var wt WrongTypes
err := rows.StructScan(&wt)
if err == nil {
t.Errorf("%s: Scanning wrong types into keys should have errored.", db.DriverName())
}
}
})
}
// FIXME: this function is kinda big but it slows things down to be constantly
// loading and reloading the schema..
func TestUsageContext(t *testing.T) {
RunWithSchemaContext(context.Background(), defaultSchema, t, func(ctx context.Context, db *DB, t *testing.T) {
loadDefaultFixtureContext(ctx, db, t)
slicemembers := []SliceMember{}
err := db.SelectContext(ctx, &slicemembers, "SELECT * FROM place ORDER BY telcode ASC")
if err != nil {
t.Fatal(err)
}
people := []Person{}
err = db.SelectContext(ctx, &people, "SELECT * FROM person ORDER BY first_name ASC")
if err != nil {
t.Fatal(err)
}
jason, john := people[0], people[1]
if jason.FirstName != "Jason" {
t.Errorf("Expecting FirstName of Jason, got %s", jason.FirstName)
}
if jason.LastName != "Moiron" {
t.Errorf("Expecting LastName of Moiron, got %s", jason.LastName)
}
if jason.Email != "[email protected]" {
t.Errorf("Expecting Email of [email protected], got %s", jason.Email)
}
if john.FirstName != "John" || john.LastName != "Doe" || john.Email != "[email protected]" {
t.Errorf("John Doe's person record not what expected: Got %v\n", john)
}
jason = Person{}
err = db.GetContext(ctx, &jason, db.Rebind("SELECT * FROM person WHERE first_name=?"), "Jason")
if err != nil {
t.Fatal(err)
}
if jason.FirstName != "Jason" {
t.Errorf("Expecting to get back Jason, but got %v\n", jason.FirstName)
}
err = db.GetContext(ctx, &jason, db.Rebind("SELECT * FROM person WHERE first_name=?"), "Foobar")
if err == nil {
t.Errorf("Expecting an error, got nil\n")
}
if err != sql.ErrNoRows {
t.Errorf("Expected sql.ErrNoRows, got %v\n", err)
}
// The following tests check statement reuse, which was actually a problem
// due to copying being done when creating Stmt's which was eventually removed
stmt1, err := db.PreparexContext(ctx, db.Rebind("SELECT * FROM person WHERE first_name=?"))
if err != nil {
t.Fatal(err)
}
jason = Person{}
row := stmt1.QueryRowx("DoesNotExist")
row.Scan(&jason)
row = stmt1.QueryRowx("DoesNotExist")
row.Scan(&jason)
err = stmt1.GetContext(ctx, &jason, "DoesNotExist User")
if err == nil {
t.Error("Expected an error")
}
err = stmt1.GetContext(ctx, &jason, "DoesNotExist User 2")
if err == nil {
t.Fatal(err)
}
stmt2, err := db.PreparexContext(ctx, db.Rebind("SELECT * FROM person WHERE first_name=?"))
if err != nil {
t.Fatal(err)
}
jason = Person{}
tx, err := db.Beginx()
if err != nil {
t.Fatal(err)
}
tstmt2 := tx.Stmtx(stmt2)
row2 := tstmt2.QueryRowx("Jason")
err = row2.StructScan(&jason)
if err != nil {
t.Error(err)
}
tx.Commit()
places := []*Place{}
err = db.SelectContext(ctx, &places, "SELECT telcode FROM place ORDER BY telcode ASC")
if err != nil {
t.Fatal(err)
}
usa, singsing, honkers := places[0], places[1], places[2]
if usa.TelCode != 1 || honkers.TelCode != 852 || singsing.TelCode != 65 {
t.Errorf("Expected integer telcodes to work, got %#v", places)
}
placesptr := []PlacePtr{}
err = db.SelectContext(ctx, &placesptr, "SELECT * FROM place ORDER BY telcode ASC")
if err != nil {
t.Error(err)
}
//fmt.Printf("%#v\n%#v\n%#v\n", placesptr[0], placesptr[1], placesptr[2])
// if you have null fields and use SELECT *, you must use sql.Null* in your struct
// this test also verifies that you can use either a []Struct{} or a []*Struct{}
places2 := []Place{}
err = db.SelectContext(ctx, &places2, "SELECT * FROM place ORDER BY telcode ASC")
if err != nil {
t.Fatal(err)
}
usa, singsing, honkers = &places2[0], &places2[1], &places2[2]
// this should return a type error that &p is not a pointer to a struct slice
p := Place{}
err = db.SelectContext(ctx, &p, "SELECT * FROM place ORDER BY telcode ASC")
if err == nil {
t.Errorf("Expected an error, argument to select should be a pointer to a struct slice")
}
// this should be an error
pl := []Place{}
err = db.SelectContext(ctx, pl, "SELECT * FROM place ORDER BY telcode ASC")
if err == nil {
t.Errorf("Expected an error, argument to select should be a pointer to a struct slice, not a slice.")
}
if usa.TelCode != 1 || honkers.TelCode != 852 || singsing.TelCode != 65 {
t.Errorf("Expected integer telcodes to work, got %#v", places)
}
stmt, err := db.PreparexContext(ctx, db.Rebind("SELECT country, telcode FROM place WHERE telcode > ? ORDER BY telcode ASC"))
if err != nil {
t.Error(err)
}
places = []*Place{}
err = stmt.SelectContext(ctx, &places, 10)
if len(places) != 2 {
t.Error("Expected 2 places, got 0.")
}
if err != nil {
t.Fatal(err)
}
singsing, honkers = places[0], places[1]
if singsing.TelCode != 65 || honkers.TelCode != 852 {
t.Errorf("Expected the right telcodes, got %#v", places)
}
rows, err := db.QueryxContext(ctx, "SELECT * FROM place")
if err != nil {
t.Fatal(err)
}
place := Place{}
for rows.Next() {
err = rows.StructScan(&place)
if err != nil {
t.Fatal(err)
}
}
rows, err = db.QueryxContext(ctx, "SELECT * FROM place")
if err != nil {
t.Fatal(err)
}
m := map[string]interface{}{}
for rows.Next() {
err = rows.MapScan(m)
if err != nil {
t.Fatal(err)
}
_, ok := m["country"]
if !ok {
t.Errorf("Expected key `country` in map but could not find it (%#v)\n", m)
}
}
rows, err = db.QueryxContext(ctx, "SELECT * FROM place")
if err != nil {
t.Fatal(err)
}
for rows.Next() {
s, err := rows.SliceScan()
if err != nil {
t.Error(err)
}
if len(s) != 3 {
t.Errorf("Expected 3 columns in result, got %d\n", len(s))
}
}
// test advanced querying
// test that NamedExec works with a map as well as a struct
_, err = db.NamedExecContext(ctx, "INSERT INTO person (first_name, last_name, email) VALUES (:first, :last, :email)", map[string]interface{}{
"first": "Bin",
"last": "Smuth",
"email": "[email protected]",
})
if err != nil {
t.Fatal(err)
}
// ensure that if the named param happens right at the end it still works
// ensure that NamedQuery works with a map[string]interface{}
rows, err = db.NamedQueryContext(ctx, "SELECT * FROM person WHERE first_name=:first", map[string]interface{}{"first": "Bin"})
if err != nil {
t.Fatal(err)
}
ben := &Person{}
for rows.Next() {
err = rows.StructScan(ben)
if err != nil {
t.Fatal(err)
}
if ben.FirstName != "Bin" {
t.Fatal("Expected first name of `Bin`, got " + ben.FirstName)
}
if ben.LastName != "Smuth" {
t.Fatal("Expected first name of `Smuth`, got " + ben.LastName)
}
}
ben.FirstName = "Ben"
ben.LastName = "Smith"
ben.Email = "[email protected]"
// Insert via a named query using the struct
_, err = db.NamedExecContext(ctx, "INSERT INTO person (first_name, last_name, email) VALUES (:first_name, :last_name, :email)", ben)
if err != nil {
t.Fatal(err)
}
rows, err = db.NamedQueryContext(ctx, "SELECT * FROM person WHERE first_name=:first_name", ben)
if err != nil {
t.Fatal(err)
}
for rows.Next() {
err = rows.StructScan(ben)
if err != nil {
t.Fatal(err)
}
if ben.FirstName != "Ben" {
t.Fatal("Expected first name of `Ben`, got " + ben.FirstName)
}
if ben.LastName != "Smith" {
t.Fatal("Expected first name of `Smith`, got " + ben.LastName)
}
}
// ensure that Get does not panic on emppty result set
person := &Person{}
err = db.GetContext(ctx, person, "SELECT * FROM person WHERE first_name=$1", "does-not-exist")
if err == nil {
t.Fatal("Should have got an error for Get on non-existant row.")
}
// lets test prepared statements some more
stmt, err = db.PreparexContext(ctx, db.Rebind("SELECT * FROM person WHERE first_name=?"))
if err != nil {
t.Fatal(err)
}
rows, err = stmt.QueryxContext(ctx, "Ben")
if err != nil {
t.Fatal(err)
}
for rows.Next() {