forked from DATA-DOG/go-txdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
db_test.go
810 lines (703 loc) · 20.7 KB
/
db_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
package txdb_test
import (
"context"
"database/sql"
"errors"
"fmt"
"os"
"reflect"
"sort"
"strings"
"sync"
"testing"
"time"
"github.com/DATA-DOG/go-txdb"
_ "github.com/go-sql-driver/mysql"
_ "github.com/lib/pq"
)
var txDrivers = testDrivers{
{name: "mysql_txdb", driver: "mysql", dsnEnvKey: "MYSQL_DSN", options: "multiStatements=true"},
{name: "psql_txdb", driver: "postgres", dsnEnvKey: "PSQL_DSN", options: "sslmode=disable"},
}
type testDriver struct {
// name is the name we use internally for the connection.
name string
// driver is the name registered by the driver when imported.
driver string
// dsnEnvKey is the name of an environment variable to fetch the DSN from.
// The DSN is expected to include the name of the database, and any
// necessary credentials.
dsnEnvKey string
// options are optional parameters appended to the DSN before connecting.
options string
// registered is set to true once the driver is registered, to prevent
// duplicate registration.
registered bool
}
type testDrivers []*testDriver
var registerMu sync.Mutex
// dsn returns the base dsn (without DB name) and the full dsn (with dbname)
// for the test driver, or calls t.Skip if it is unset or disabled.
func (d *testDriver) dsn(t *testing.T) (base string, full string) {
t.Helper()
base = os.Getenv(d.dsnEnvKey)
if base == "" {
t.Skipf("%s not set, skipping tests for %s", d.dsnEnvKey, d.driver)
}
if strings.ToLower(base) == "auto" {
base = d.startTestContainer(t)
}
full = strings.TrimSuffix(base, "/") + "/" + testDB
if d.options == "" {
return base, full
}
return base + "?" + d.options, full + "?" + d.options
}
func (d *testDriver) startTestContainer(t *testing.T) string {
switch d.driver {
case "postgres":
return startPostgres(t)
case "mysql":
return startMySQL(t)
default:
panic("cannot start testcontainer for driver " + d.driver)
}
}
func (d *testDriver) register(t *testing.T) {
t.Helper()
registerMu.Lock()
defer registerMu.Unlock()
if !d.registered {
base, full := d.dsn(t)
d.registered = true
createDB(t, d.driver, base)
bootstrap(t, d.driver, full)
txdb.Register(d.name, d.driver, full)
}
}
// Run registers the driver, if not already registered, then calls f with the
// driver name.
func (d *testDriver) Run(t *testing.T, f func(t *testing.T, driver *testDriver)) {
t.Helper()
t.Run(d.name, func(t *testing.T) {
d.register(t)
f(t, d)
})
}
// Run iterates over the configured drivers, and calls [testDriver.Run] on each.
func (d testDrivers) Run(t *testing.T, f func(t *testing.T, driver *testDriver)) {
t.Helper()
for _, driver := range d {
driver.Run(t, f)
}
}
// driver returns the subset of d whose driver match one of the provided names.
// Useful for tests that require specific database driver capabilities.
func (d testDrivers) drivers(names ...string) testDrivers {
result := make(testDrivers, 0, len(d))
for _, driver := range d {
for _, name := range names {
if driver.driver == name {
result = append(result, driver)
}
}
}
return result
}
func TestShouldWorkWithOpenDB(t *testing.T) {
t.Parallel()
for _, d := range txDrivers {
d.Run(t, func(t *testing.T, driver *testDriver) {
_, dsn := driver.dsn(t)
db := sql.OpenDB(txdb.New(d.driver, dsn))
defer db.Close()
_, err := db.Exec("SELECT 1")
if err != nil {
t.Fatal(err)
}
})
}
}
func TestShouldRunWithNestedTransaction(t *testing.T) {
t.Parallel()
txDrivers.Run(t, func(t *testing.T, driver *testDriver) {
var count int
db, err := sql.Open(driver.name, "five")
if err != nil {
t.Fatalf("failed to open a connection: %s", err)
}
func(db *sql.DB) {
defer db.Close()
_, err = db.Exec(`INSERT INTO users (username, email) VALUES('txdb', '[email protected]')`)
if err != nil {
t.Fatalf("failed to insert a user: %s", err)
}
err = db.QueryRow("SELECT COUNT(id) FROM users").Scan(&count)
if err != nil {
t.Fatalf("failed to count users: %s", err)
}
if count != 4 {
t.Fatalf("expected 4 users to be in database, but got %d", count)
}
tx, err := db.Begin()
if err != nil {
t.Fatalf("failed to begin transaction: %s", err)
}
{
_, err = tx.Exec(`INSERT INTO users (username, email) VALUES('txdb', '[email protected]')`)
if err != nil {
t.Fatalf("failed to insert an user: %s", err)
}
err = tx.QueryRow("SELECT COUNT(id) FROM users").Scan(&count)
if err != nil {
t.Fatalf("failed to count users: %s", err)
}
if count != 5 {
t.Fatalf("expected 5 users to be in database, but got %d", count)
}
if err := tx.Rollback(); err != nil {
t.Fatalf("failed to rollback transaction: %s", err)
}
}
err = db.QueryRow("SELECT COUNT(id) FROM users").Scan(&count)
if err != nil {
t.Fatalf("failed to count users: %s", err)
}
if count != 4 {
t.Fatalf("expected 4 users to be in database, but got %d", count)
}
tx, err = db.Begin()
if err != nil {
t.Fatalf("failed to begin transaction: %s", err)
}
{
_, err = tx.Exec(`INSERT INTO users (username, email) VALUES('txdb', '[email protected]')`)
if err != nil {
t.Fatalf("failed to insert an user: %s", err)
}
err = tx.QueryRow("SELECT COUNT(id) FROM users").Scan(&count)
if err != nil {
t.Fatalf("failed to count users: %s", err)
}
if count != 5 {
t.Fatalf("expected 5 users to be in database, but got %d", count)
}
if err := tx.Commit(); err != nil {
t.Fatalf("failed to commit transaction: %s", err)
}
}
err = db.QueryRow("SELECT COUNT(id) FROM users").Scan(&count)
if err != nil {
t.Fatalf("failed to count users: %s", err)
}
if count != 5 {
t.Fatalf("expected 5 users to be in database, but got %d", count)
}
}(db)
db, err = sql.Open(driver.name, "six")
if err != nil {
t.Fatalf("failed to reopen a mysql connection: %s", err)
}
func(db *sql.DB) {
defer db.Close()
err = db.QueryRow("SELECT COUNT(id) FROM users").Scan(&count)
if err != nil {
t.Fatalf("failed to count users: %s", err)
}
if count != 3 {
t.Fatalf("expected 3 users to be in database, but got %d", count)
}
}(db)
})
}
func TestShouldRunWithinTransaction(t *testing.T) {
t.Parallel()
txDrivers.Run(t, func(t *testing.T, driver *testDriver) {
var count int
db, err := sql.Open(driver.name, "one")
if err != nil {
t.Fatalf("failed to open a connection: %s", err)
}
func(db *sql.DB) {
defer db.Close()
_, err = db.Exec(`INSERT INTO users (username, email) VALUES('txdb', '[email protected]')`)
if err != nil {
t.Fatalf("failed to insert an user: %s", err)
}
err = db.QueryRow("SELECT COUNT(id) FROM users").Scan(&count)
if err != nil {
t.Fatalf("failed to count users: %s", err)
}
if count != 4 {
t.Fatalf("expected 4 users to be in database, but got %d", count)
}
}(db)
db, err = sql.Open(driver.name, "two")
if err != nil {
t.Fatalf("failed to reopen a mysql connection: %s", err)
}
func(db *sql.DB) {
defer db.Close()
err = db.QueryRow("SELECT COUNT(id) FROM users").Scan(&count)
if err != nil {
t.Fatalf("failed to count users: %s", err)
}
if count != 3 {
t.Fatalf("expected 3 users to be in database, but got %d", count)
}
}(db)
})
}
func TestShouldNotHoldConnectionForRows(t *testing.T) {
t.Parallel()
txDrivers.Run(t, func(t *testing.T, driver *testDriver) {
db, err := sql.Open(driver.name, "three")
if err != nil {
t.Fatalf("failed to open a connection: %s", err)
}
defer db.Close()
rows, err := db.Query("SELECT username FROM users")
if err != nil {
t.Fatalf("failed to query users: %s", err)
}
defer rows.Close()
_, err = db.Exec(`INSERT INTO users(username, email) VALUES('txdb', '[email protected]')`)
if err != nil {
t.Fatalf("failed to insert an user: %s", err)
}
})
}
func TestShouldPerformParallelActions(t *testing.T) {
t.Parallel()
txDrivers.Run(t, func(t *testing.T, driver *testDriver) {
db, err := sql.Open(driver.name, "four")
if err != nil {
t.Fatalf("failed to open a connection: %s", err)
}
defer db.Close()
wg := &sync.WaitGroup{}
for i := 0; i < 4; i++ {
wg.Add(1)
go func(d *sql.DB, idx int) {
defer wg.Done()
rows, err := d.Query("SELECT username FROM users")
if err != nil {
t.Errorf("failed to query users: %s", err)
}
defer rows.Close()
insertSQL := "INSERT INTO users(username, email) VALUES(?, ?)"
if strings.Index(driver.name, "psql_") == 0 {
insertSQL = "INSERT INTO users(username, email) VALUES($1, $2)"
}
username := fmt.Sprintf("parallel%d", idx)
email := fmt.Sprintf("parallel%[email protected]", idx)
_, err = d.Exec(insertSQL, username, email)
if err != nil {
t.Errorf("failed to insert an user: %s", err)
}
}(db, i)
}
wg.Wait()
var count int
err = db.QueryRow("SELECT COUNT(id) FROM users").Scan(&count)
if err != nil {
t.Fatalf("failed to count users: %s", err)
}
if count != 7 {
t.Fatalf("expected 7 users to be in database, but got %d", count)
}
})
}
func TestShouldFailInvalidPrepareStatement(t *testing.T) {
t.Parallel()
txDrivers.Run(t, func(t *testing.T, driver *testDriver) {
db, err := sql.Open(driver.name, "fail_prepare")
if err != nil {
t.Fatalf("failed to open a connection: %s", err)
}
defer db.Close()
if _, err = db.Prepare("THIS SHOULD FAIL..."); err == nil {
t.Fatal("expected an error, since prepare should validate sql query, but got none")
}
})
}
func TestShouldHandlePrepare(t *testing.T) {
t.Parallel()
txDrivers.Run(t, func(t *testing.T, driver *testDriver) {
db, err := sql.Open(driver.name, "prepare")
if err != nil {
t.Fatalf("failed to open a connection: %s", err)
}
defer db.Close()
selectSQL := "SELECT email FROM users WHERE username = ?"
if strings.Index(driver.name, "psql_") == 0 {
selectSQL = "SELECT email FROM users WHERE username = $1"
}
stmt1, err := db.Prepare(selectSQL)
if err != nil {
t.Fatalf("could not prepare - %s", err)
}
insertSQL := "INSERT INTO users (username, email) VALUES(?, ?)"
if strings.Index(driver.name, "psql_") == 0 {
insertSQL = "INSERT INTO users (username, email) VALUES($1, $2)"
}
stmt2, err := db.Prepare(insertSQL)
if err != nil {
t.Fatalf("could not prepare - %s", err)
}
var email string
if err = stmt1.QueryRow("jane").Scan(&email); err != nil {
t.Fatalf("could not scan email - %s", err)
}
_, err = stmt2.Exec("mark", "[email protected]")
if err != nil {
t.Fatalf("should have inserted user - %s", err)
}
})
}
func TestShouldCloseRootDB(t *testing.T) {
txDrivers.Run(t, func(t *testing.T, driver *testDriver) {
db1, err := sql.Open(driver.name, "first")
if err != nil {
t.Fatalf("failed to open a connection: %s", err)
}
defer db1.Close()
stmt, err := db1.Prepare("SELECT * FROM users")
if err != nil {
t.Fatalf("could not prepare - %s", err)
}
defer stmt.Close()
drv1 := db1.Driver().(*txdb.TxDriver)
if drv1.DB() == nil {
t.Fatalf("expected database, drv1.db: %v", drv1.DB())
}
db2, err := sql.Open(driver.name, "second")
if err != nil {
t.Fatalf("failed to open a connection: %s", err)
}
defer db2.Close()
stmt, err = db2.Prepare("SELECT * FROM users")
if err != nil {
t.Fatalf("could not prepare - %s", err)
}
defer stmt.Close()
// Both drivers share the same database.
drv2 := db2.Driver().(*txdb.TxDriver)
if drv2.DB() != drv1.DB() {
t.Fatalf("drv1.db=%v != drv2.db=%v", drv1.DB(), drv2.DB())
}
// Database should remain open while a connection is open.
if err := db1.Close(); err != nil {
t.Fatalf("could not close database - %s", err)
}
if drv1.DB() == nil {
t.Fatal("expected database, not nil")
}
if drv2.DB() == nil {
t.Fatal("expected database ,not nil")
}
// Database should close after last connection is closed.
if err := db2.Close(); err != nil {
t.Fatalf("could not close database - %s", err)
}
if drv1.DB() != nil {
t.Fatalf("expected closed database, not %v", drv1.DB())
}
if drv2.DB() != nil {
t.Fatalf("expected closed database, not %v", drv2.DB())
}
})
}
func TestShouldReopenAfterClose(t *testing.T) {
txDrivers.Run(t, func(t *testing.T, driver *testDriver) {
db, err := sql.Open(driver.name, "first")
if err != nil {
t.Fatalf("failed to open a connection: %s", err)
}
defer db.Close()
stmt, err := db.Prepare("SELECT * FROM users")
if err != nil {
t.Fatalf("could not prepare - %s", err)
}
defer stmt.Close()
if err := db.Close(); err != nil {
t.Fatalf("could not close database - %s", err)
}
if err := db.Ping(); err.Error() != "sql: database is closed" {
t.Fatalf("expected closed database - %s", err)
}
db, err = sql.Open(driver.name, "second")
if err != nil {
t.Fatalf("failed to open a connection: %s", err)
}
defer db.Close()
if err := db.Ping(); err != nil {
t.Fatalf("failed to ping: %s", err)
}
})
}
type canceledContext struct{}
func (canceledContext) Deadline() (deadline time.Time, ok bool) { return time.Time{}, true }
func (canceledContext) Done() <-chan struct{} {
done := make(chan struct{})
close(done)
return done
}
func (canceledContext) Err() error { return errors.New("canceled") }
func (canceledContext) Value(key interface{}) interface{} { return nil }
func TestShouldDiscardConnectionWhenClosedBecauseOfError(t *testing.T) {
txDrivers.Run(t, func(t *testing.T, driver *testDriver) {
{
db, err := sql.Open(driver.name, "first")
if err != nil {
t.Fatalf("failed to open a connection: %s", err)
}
defer db.Close()
tx, err := db.Begin()
defer func() {
err = tx.Rollback()
if err != nil {
t.Fatalf("rollback err: %s", err)
}
}()
if err != nil {
t.Fatalf("failed to begin transaction err: %s", err)
}
// TODO: we somehow need to poison the DB connection here so that Rollback fails
_, err = tx.PrepareContext(canceledContext{}, "SELECT * FROM users")
if err == nil {
t.Fatal("should have returned error for prepare")
}
}
fmt.Println("Opening db...")
{
db, err := sql.Open(driver.name, "second")
if err != nil {
t.Fatalf("failed to open a connection: %s", err)
}
defer db.Close()
if err := db.Ping(); err != nil {
t.Fatalf("failed to ping: %s", err)
}
}
})
}
func TestPostgresRowsScanTypeTables(t *testing.T) {
txDrivers.drivers("postgres").Run(t, func(t *testing.T, driver *testDriver) {
db, err := sql.Open(driver.name, "scantype")
if err != nil {
t.Fatalf("psql: failed to open a postgres connection: %s", err)
}
defer db.Close()
rows, err := db.Query("SELECT 1")
if err != nil {
t.Fatalf("psql: unable to execute trivial query: %v", err)
}
colTypes, err := rows.ColumnTypes()
if err != nil {
t.Fatalf("psql: unable to retrieve column types: %v", err)
}
int32Type := reflect.TypeOf(int32(0))
if colTypes[0].ScanType() != int32Type {
t.Fatalf("psql: column scan type is %s, but should be %s", colTypes[0].ScanType().String(), int32Type.String())
}
})
}
func TestMysqlShouldBeAbleToLockTables(t *testing.T) {
txDrivers.drivers("mysql").Run(t, func(t *testing.T, driver *testDriver) {
db, err := sql.Open(driver.name, "locks")
if err != nil {
t.Fatalf("mysql: failed to open a mysql connection: %s", err)
}
defer db.Close()
_, err = db.Exec("LOCK TABLE users READ")
if err != nil {
t.Fatalf("mysql: should be able to lock table, but got err: %v", err)
}
var count int
err = db.QueryRow("SELECT COUNT(*) FROM users").Scan(&count)
if err != nil {
t.Fatalf("mysql: unexpected read error: %v", err)
}
if count != 3 {
t.Fatalf("mysql: was expecting 3 users in db")
}
_, err = db.Exec("UNLOCK TABLES")
if err != nil {
t.Fatalf("mysql: should be able to unlock table, but got err: %v", err)
}
})
}
func TestShouldGetMultiRowSet(t *testing.T) {
t.Parallel()
txDrivers.Run(t, func(t *testing.T, driver *testDriver) {
db, err := sql.Open(driver.name, "multiRows")
if err != nil {
t.Fatalf("failed to open a connection: %s", err)
}
defer db.Close()
rows, err := db.QueryContext(context.Background(), "SELECT username FROM users; SELECT COUNT(*) FROM users;")
if err != nil {
t.Fatalf("failed to query users: %s", err)
}
defer rows.Close()
var users []string
for rows.Next() {
var name string
if err := rows.Scan(&name); err != nil {
t.Fatalf("unexpected row scan err: %v", err)
}
users = append(users, name)
}
if !rows.NextResultSet() {
t.Fatal("expected next result set")
}
if !rows.Next() {
t.Fatal("expected next result set - row")
}
var count int
if err := rows.Scan(&count); err != nil {
t.Fatalf("unexpected row scan err: %v", err)
}
if count != len(users) {
t.Fatal("unexpected number of users")
}
})
}
func TestShouldBeAbleToPingWithContext(t *testing.T) {
txDrivers.Run(t, func(t *testing.T, driver *testDriver) {
db, err := sql.Open(driver.name, "ping")
if err != nil {
t.Fatalf("failed to open a connection: %s", err)
}
defer db.Close()
if err := db.PingContext(context.Background()); err != nil {
t.Fatalf("%v", err)
}
})
}
func TestShouldHandleStmtsWithoutContextPollution(t *testing.T) {
t.Parallel()
txDrivers.Run(t, func(t *testing.T, driver *testDriver) {
db, err := sql.Open(driver.name, "contextpollution")
if err != nil {
t.Fatalf("failed to open a connection: %s", err)
}
defer db.Close()
insertSQL := "INSERT INTO users (username, email) VALUES(?, ?)"
if strings.Index(driver.name, "psql_") == 0 {
insertSQL = "INSERT INTO users (username, email) VALUES($1, $2)"
}
ctx1, cancel1 := context.WithCancel(context.Background())
defer cancel1()
_, err = db.ExecContext(ctx1, insertSQL, "first", "[email protected]")
if err != nil {
t.Fatalf("unexpected error inserting user 1: %s", err)
}
cancel1()
ctx2, cancel2 := context.WithCancel(context.Background())
defer cancel2()
_, err = db.ExecContext(ctx2, insertSQL, "second", "[email protected]")
if err != nil {
t.Fatalf("unexpected error inserting user 2: %s", err)
}
cancel2()
const selectQuery = `
select username
from users
where username = 'first' OR username = 'second'`
rows, err := db.QueryContext(context.Background(), selectQuery)
if err != nil {
t.Fatalf("unexpected error querying users: %s", err)
}
defer rows.Close()
assertRows := func(t *testing.T, rows *sql.Rows) {
t.Helper()
var users []string
for rows.Next() {
var user string
err := rows.Scan(&user)
if err != nil {
t.Errorf("unexpected scan failure: %s", err)
continue
}
users = append(users, user)
}
sort.Strings(users)
wanted := []string{"first", "second"}
if len(users) != 2 {
t.Fatalf("invalid users received; want=%v\tgot=%v", wanted, users)
}
for i, want := range wanted {
if got := users[i]; want != got {
t.Errorf("invalid user; want=%s\tgot=%s", want, got)
}
}
}
assertRows(t, rows)
ctx3, cancel3 := context.WithCancel(context.Background())
defer cancel3()
stmt, err := db.PrepareContext(ctx3, selectQuery)
if err != nil {
t.Fatalf("unexpected error preparing stmt: %s", err)
}
rows, err = stmt.QueryContext(context.TODO())
if err != nil {
t.Fatalf("unexpected error in stmt querying users: %s", err)
}
defer rows.Close()
assertRows(t, rows)
})
}
// https://github.com/DATA-DOG/go-txdb/issues/49
func TestIssue49(t *testing.T) {
t.Parallel()
txDrivers.Run(t, func(t *testing.T, driver *testDriver) {
db, err := sql.Open(driver.name, "rollback")
if err != nil {
t.Fatalf("failed to open a connection: %s", err)
}
defer db.Close()
// do a query prior to starting a nested transaction to
// reproduce the error
var count int
err = db.QueryRow("SELECT COUNT(id) FROM users").Scan(&count)
if err != nil {
t.Fatalf("prepared statement count err %v", err)
}
if count != 3 {
t.Logf("Count not 3: %d", count)
t.FailNow()
}
// start a nested transaction
tx, err := db.Begin()
if err != nil {
t.Fatalf("failed to start transaction: %s", err)
}
// need a prepared statement to reproduce the error
insertSQL := "INSERT INTO users (username, email) VALUES(?, ?)"
if strings.Index(driver.name, "psql_") == 0 {
insertSQL = "INSERT INTO users (username, email) VALUES($1, $2)"
}
stmt, err := tx.Prepare(insertSQL)
if err != nil {
t.Fatalf("failed to prepare named statement: %s", err)
}
// try to insert already existing username/email
_, err = stmt.Exec("gopher", "[email protected]")
if err == nil {
t.Fatal("double insert?")
}
// The insert failed, so we need to close the prepared statement
err = stmt.Close()
if err != nil {
t.Fatalf("error closing prepared statement: %s", err)
}
// rollback the transaction now that it has failed
err = tx.Rollback()
if err != nil {
t.Logf("failed rollback of failed transaction: %s", err)
t.FailNow()
}
})
}