1 // Copyright 2011 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
27 freedFrom := make(map[dbConn]string)
29 getFreedFrom := func(c dbConn) string {
34 setFreedFrom := func(c dbConn, s string) {
39 putConnHook = func(db *DB, c *driverConn) {
41 for i, v := range db.freeConn {
48 // print before panic, as panic may get lost due to conflicting panic
49 // (all goroutines asleep) elsewhere, since we might not unlock
50 // the mutex in freeConn here.
51 println("double free of conn. conflicts are:\nA) " + getFreedFrom(dbConn{db, c}) + "\n\nand\nB) " + stack())
52 panic("double free of conn.")
54 setFreedFrom(dbConn{db, c}, stack())
58 const fakeDBName = "foo"
60 var chrisBirthday = time.Unix(123456789, 0)
62 func newTestDB(t testing.TB, name string) *DB {
63 return newTestDBConnector(t, &fakeConnector{name: fakeDBName}, name)
66 func newTestDBConnector(t testing.TB, fc *fakeConnector, name string) *DB {
69 if _, err := db.Exec("WIPE"); err != nil {
70 t.Fatalf("exec wipe: %v", err)
73 exec(t, db, "CREATE|people|name=string,age=int32,photo=blob,dead=bool,bdate=datetime")
74 exec(t, db, "INSERT|people|name=Alice,age=?,photo=APHOTO", 1)
75 exec(t, db, "INSERT|people|name=Bob,age=?,photo=BPHOTO", 2)
76 exec(t, db, "INSERT|people|name=Chris,age=?,photo=CPHOTO,bdate=?", 3, chrisBirthday)
78 if name == "magicquery" {
79 // Magic table name and column, known by fakedb_test.go.
80 exec(t, db, "CREATE|magicquery|op=string,millis=int32")
81 exec(t, db, "INSERT|magicquery|op=sleep,millis=10")
86 func TestOpenDB(t *testing.T) {
87 db := OpenDB(dsnConnector{dsn: fakeDBName, driver: fdriver})
88 if db.Driver() != fdriver {
89 t.Fatalf("OpenDB should return the driver of the Connector")
93 func TestDriverPanic(t *testing.T) {
94 // Test that if driver panics, database/sql does not deadlock.
95 db, err := Open("test", fakeDBName)
97 t.Fatalf("Open: %v", err)
99 expectPanic := func(name string, f func()) {
103 t.Fatalf("%s did not panic", name)
109 expectPanic("Exec Exec", func() { db.Exec("PANIC|Exec|WIPE") })
110 exec(t, db, "WIPE") // check not deadlocked
111 expectPanic("Exec NumInput", func() { db.Exec("PANIC|NumInput|WIPE") })
112 exec(t, db, "WIPE") // check not deadlocked
113 expectPanic("Exec Close", func() { db.Exec("PANIC|Close|WIPE") })
114 exec(t, db, "WIPE") // check not deadlocked
115 exec(t, db, "PANIC|Query|WIPE") // should run successfully: Exec does not call Query
116 exec(t, db, "WIPE") // check not deadlocked
118 exec(t, db, "CREATE|people|name=string,age=int32,photo=blob,dead=bool,bdate=datetime")
120 expectPanic("Query Query", func() { db.Query("PANIC|Query|SELECT|people|age,name|") })
121 expectPanic("Query NumInput", func() { db.Query("PANIC|NumInput|SELECT|people|age,name|") })
122 expectPanic("Query Close", func() {
123 rows, err := db.Query("PANIC|Close|SELECT|people|age,name|")
129 db.Query("PANIC|Exec|SELECT|people|age,name|") // should run successfully: Query does not call Exec
130 exec(t, db, "WIPE") // check not deadlocked
133 func exec(t testing.TB, db *DB, query string, args ...interface{}) {
135 _, err := db.Exec(query, args...)
137 t.Fatalf("Exec of %q: %v", query, err)
141 func closeDB(t testing.TB, db *DB) {
142 if e := recover(); e != nil {
143 fmt.Printf("Panic: %v\n", e)
146 defer setHookpostCloseConn(nil)
147 setHookpostCloseConn(func(_ *fakeConn, err error) {
149 t.Errorf("Error closing fakeConn: %v", err)
153 for i, dc := range db.freeConn {
154 if n := len(dc.openStmt); n > 0 {
155 // Just a sanity check. This is legal in
156 // general, but if we make the tests clean up
157 // their statements first, then we can safely
158 // verify this is always zero here, and any
159 // other value is a leak.
160 t.Errorf("while closing db, freeConn %d/%d had %d open stmts; want 0", i, len(db.freeConn), n)
167 t.Fatalf("error closing DB: %v", err)
171 if !waitCondition(5*time.Second, 5*time.Millisecond, func() bool {
172 numOpen = db.numOpenConns()
175 t.Fatalf("%d connections still open after closing DB", numOpen)
179 // numPrepares assumes that db has exactly 1 idle conn and returns
180 // its count of calls to Prepare
181 func numPrepares(t *testing.T, db *DB) int {
182 if n := len(db.freeConn); n != 1 {
183 t.Fatalf("free conns = %d; want 1", n)
185 return db.freeConn[0].ci.(*fakeConn).numPrepare
188 func (db *DB) numDeps() int {
194 // Dependencies are closed via a goroutine, so this polls waiting for
195 // numDeps to fall to want, waiting up to d.
196 func (db *DB) numDepsPollUntil(want int, d time.Duration) int {
197 deadline := time.Now().Add(d)
200 if n <= want || time.Now().After(deadline) {
203 time.Sleep(50 * time.Millisecond)
207 func (db *DB) numFreeConns() int {
210 return len(db.freeConn)
213 func (db *DB) numOpenConns() int {
219 // clearAllConns closes all connections in db.
220 func (db *DB) clearAllConns(t *testing.T) {
221 db.SetMaxIdleConns(0)
223 if g, w := db.numFreeConns(), 0; g != w {
224 t.Errorf("free conns = %d; want %d", g, w)
227 if n := db.numDepsPollUntil(0, time.Second); n > 0 {
228 t.Errorf("number of dependencies = %d; expected 0", n)
233 func (db *DB) dumpDeps(t *testing.T) {
234 for fc := range db.dep {
235 db.dumpDep(t, 0, fc, map[finalCloser]bool{})
239 func (db *DB) dumpDep(t *testing.T, depth int, dep finalCloser, seen map[finalCloser]bool) {
241 indent := strings.Repeat(" ", depth)
244 t.Logf("%s%T (%p) waiting for -> %T (%p)", indent, dep, dep, k, k)
245 if fc, ok := k.(finalCloser); ok {
247 db.dumpDep(t, depth+1, fc, seen)
253 func TestQuery(t *testing.T) {
254 db := newTestDB(t, "people")
256 prepares0 := numPrepares(t, db)
257 rows, err := db.Query("SELECT|people|age,name|")
259 t.Fatalf("Query: %v", err)
268 err = rows.Scan(&r.age, &r.name)
270 t.Fatalf("Scan: %v", err)
276 t.Fatalf("Err: %v", err)
279 {age: 1, name: "Alice"},
280 {age: 2, name: "Bob"},
281 {age: 3, name: "Chris"},
283 if !reflect.DeepEqual(got, want) {
284 t.Errorf("mismatch.\n got: %#v\nwant: %#v", got, want)
287 // And verify that the final rows.Next() call, which hit EOF,
288 // also closed the rows connection.
289 if n := db.numFreeConns(); n != 1 {
290 t.Fatalf("free conns after query hitting EOF = %d; want 1", n)
292 if prepares := numPrepares(t, db) - prepares0; prepares != 1 {
293 t.Errorf("executed %d Prepare statements; want 1", prepares)
297 // TestQueryContext tests canceling the context while scanning the rows.
298 func TestQueryContext(t *testing.T) {
299 db := newTestDB(t, "people")
301 prepares0 := numPrepares(t, db)
303 ctx, cancel := context.WithCancel(context.Background())
306 rows, err := db.QueryContext(ctx, "SELECT|people|age,name|")
308 t.Fatalf("Query: %v", err)
319 waitForRowsClose(t, rows, 5*time.Second)
322 err = rows.Scan(&r.age, &r.name)
327 t.Fatalf("Scan: %v", err)
329 if index == 2 && err != context.Canceled {
330 t.Fatalf("Scan: %v; want context.Canceled", err)
337 if err := ctx.Err(); err != context.Canceled {
338 t.Fatalf("context err = %v; want context.Canceled", err)
341 t.Fatalf("context err = nil; want context.Canceled")
344 {age: 1, name: "Alice"},
345 {age: 2, name: "Bob"},
347 if !reflect.DeepEqual(got, want) {
348 t.Errorf("mismatch.\n got: %#v\nwant: %#v", got, want)
351 // And verify that the final rows.Next() call, which hit EOF,
352 // also closed the rows connection.
353 waitForRowsClose(t, rows, 5*time.Second)
354 waitForFree(t, db, 5*time.Second, 1)
355 if prepares := numPrepares(t, db) - prepares0; prepares != 1 {
356 t.Errorf("executed %d Prepare statements; want 1", prepares)
360 func waitCondition(waitFor, checkEvery time.Duration, fn func() bool) bool {
361 deadline := time.Now().Add(waitFor)
362 for time.Now().Before(deadline) {
366 time.Sleep(checkEvery)
371 // waitForFree checks db.numFreeConns until either it equals want or
372 // the maxWait time elapses.
373 func waitForFree(t *testing.T, db *DB, maxWait time.Duration, want int) {
375 if !waitCondition(maxWait, 5*time.Millisecond, func() bool {
376 numFree = db.numFreeConns()
377 return numFree == want
379 t.Fatalf("free conns after hitting EOF = %d; want %d", numFree, want)
383 func waitForRowsClose(t *testing.T, rows *Rows, maxWait time.Duration) {
384 if !waitCondition(maxWait, 5*time.Millisecond, func() bool {
386 defer rows.closemu.RUnlock()
389 t.Fatal("failed to close rows")
393 // TestQueryContextWait ensures that rows and all internal statements are closed when
394 // a query context is closed during execution.
395 func TestQueryContextWait(t *testing.T) {
396 db := newTestDB(t, "people")
398 prepares0 := numPrepares(t, db)
400 // TODO(kardianos): convert this from using a timeout to using an explicit
401 // cancel when the query signals that it is "executing" the query.
402 ctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond)
405 // This will trigger the *fakeConn.Prepare method which will take time
406 // performing the query. The ctxDriverPrepare func will check the context
407 // after this and close the rows and return an error.
408 _, err := db.QueryContext(ctx, "WAIT|1s|SELECT|people|age,name|")
409 if err != context.DeadlineExceeded {
410 t.Fatalf("expected QueryContext to error with context deadline exceeded but returned %v", err)
413 // Verify closed rows connection after error condition.
414 waitForFree(t, db, 5*time.Second, 1)
415 if prepares := numPrepares(t, db) - prepares0; prepares != 1 {
416 // TODO(kardianos): if the context timeouts before the db.QueryContext
417 // executes this check may fail. After adjusting how the context
418 // is canceled above revert this back to a Fatal error.
419 t.Logf("executed %d Prepare statements; want 1", prepares)
423 // TestTxContextWait tests the transaction behavior when the tx context is canceled
424 // during execution of the query.
425 func TestTxContextWait(t *testing.T) {
426 db := newTestDB(t, "people")
429 ctx, cancel := context.WithTimeout(context.Background(), 15*time.Millisecond)
432 tx, err := db.BeginTx(ctx, nil)
434 // Guard against the context being canceled before BeginTx completes.
435 if err == context.DeadlineExceeded {
436 t.Skip("tx context canceled prior to first use")
441 // This will trigger the *fakeConn.Prepare method which will take time
442 // performing the query. The ctxDriverPrepare func will check the context
443 // after this and close the rows and return an error.
444 _, err = tx.QueryContext(ctx, "WAIT|1s|SELECT|people|age,name|")
445 if err != context.DeadlineExceeded {
446 t.Fatalf("expected QueryContext to error with context deadline exceeded but returned %v", err)
449 waitForFree(t, db, 5*time.Second, 0)
452 // TestUnsupportedOptions checks that the database fails when a driver that
453 // doesn't implement ConnBeginTx is used with non-default options and an
454 // un-cancellable context.
455 func TestUnsupportedOptions(t *testing.T) {
456 db := newTestDB(t, "people")
458 _, err := db.BeginTx(context.Background(), &TxOptions{
459 Isolation: LevelSerializable, ReadOnly: true,
462 t.Fatal("expected error when using unsupported options, got nil")
466 func TestMultiResultSetQuery(t *testing.T) {
467 db := newTestDB(t, "people")
469 prepares0 := numPrepares(t, db)
470 rows, err := db.Query("SELECT|people|age,name|;SELECT|people|name|")
472 t.Fatalf("Query: %v", err)
484 err = rows.Scan(&r.age, &r.name)
486 t.Fatalf("Scan: %v", err)
488 got1 = append(got1, r)
492 t.Fatalf("Err: %v", err)
495 {age: 1, name: "Alice"},
496 {age: 2, name: "Bob"},
497 {age: 3, name: "Chris"},
499 if !reflect.DeepEqual(got1, want1) {
500 t.Errorf("mismatch.\n got1: %#v\nwant: %#v", got1, want1)
503 if !rows.NextResultSet() {
504 t.Errorf("expected another result set")
510 err = rows.Scan(&r.name)
512 t.Fatalf("Scan: %v", err)
514 got2 = append(got2, r)
518 t.Fatalf("Err: %v", err)
525 if !reflect.DeepEqual(got2, want2) {
526 t.Errorf("mismatch.\n got: %#v\nwant: %#v", got2, want2)
528 if rows.NextResultSet() {
529 t.Errorf("expected no more result sets")
532 // And verify that the final rows.Next() call, which hit EOF,
533 // also closed the rows connection.
534 waitForFree(t, db, 5*time.Second, 1)
535 if prepares := numPrepares(t, db) - prepares0; prepares != 1 {
536 t.Errorf("executed %d Prepare statements; want 1", prepares)
540 func TestQueryNamedArg(t *testing.T) {
541 db := newTestDB(t, "people")
543 prepares0 := numPrepares(t, db)
544 rows, err := db.Query(
545 // Ensure the name and age parameters only match on placeholder name, not position.
546 "SELECT|people|age,name|name=?name,age=?age",
548 Named("name", "Bob"),
551 t.Fatalf("Query: %v", err)
560 err = rows.Scan(&r.age, &r.name)
562 t.Fatalf("Scan: %v", err)
568 t.Fatalf("Err: %v", err)
571 {age: 2, name: "Bob"},
573 if !reflect.DeepEqual(got, want) {
574 t.Errorf("mismatch.\n got: %#v\nwant: %#v", got, want)
577 // And verify that the final rows.Next() call, which hit EOF,
578 // also closed the rows connection.
579 if n := db.numFreeConns(); n != 1 {
580 t.Fatalf("free conns after query hitting EOF = %d; want 1", n)
582 if prepares := numPrepares(t, db) - prepares0; prepares != 1 {
583 t.Errorf("executed %d Prepare statements; want 1", prepares)
587 func TestPoolExhaustOnCancel(t *testing.T) {
593 var saturate, saturateDone sync.WaitGroup
595 saturateDone.Add(max)
597 donePing := make(chan bool)
600 // waiter will be called for all queries, including
601 // initial setup queries. The state is only assigned when
602 // no queries are made.
604 // Only allow the first batch of queries to finish once the
605 // second batch of Ping queries have finished.
606 waiter := func(ctx context.Context) {
609 // Nothing. Initial database setup.
619 db := newTestDBConnector(t, &fakeConnector{waiter: waiter}, "people")
622 db.SetMaxOpenConns(max)
624 // First saturate the connection pool.
625 // Then start new requests for a connection that is cancelled after it is requested.
628 for i := 0; i < max; i++ {
630 rows, err := db.Query("SELECT|people|name,photo|")
632 t.Fatalf("Query: %v", err)
642 // Now cancel the request while it is waiting.
643 ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
646 for i := 0; i < max; i++ {
647 ctxReq, cancelReq := context.WithCancel(ctx)
649 time.Sleep(100 * time.Millisecond)
652 err := db.PingContext(ctxReq)
653 if err != context.Canceled {
654 t.Fatalf("PingContext (Exhaust): %v", err)
660 // Now try to open a normal connection.
661 err := db.PingContext(ctx)
663 t.Fatalf("PingContext (Normal): %v", err)
667 func TestRowsColumns(t *testing.T) {
668 db := newTestDB(t, "people")
670 rows, err := db.Query("SELECT|people|age,name|")
672 t.Fatalf("Query: %v", err)
674 cols, err := rows.Columns()
676 t.Fatalf("Columns: %v", err)
678 want := []string{"age", "name"}
679 if !reflect.DeepEqual(cols, want) {
680 t.Errorf("got %#v; want %#v", cols, want)
682 if err := rows.Close(); err != nil {
683 t.Errorf("error closing rows: %s", err)
687 func TestRowsColumnTypes(t *testing.T) {
688 db := newTestDB(t, "people")
690 rows, err := db.Query("SELECT|people|age,name|")
692 t.Fatalf("Query: %v", err)
694 tt, err := rows.ColumnTypes()
696 t.Fatalf("ColumnTypes: %v", err)
699 types := make([]reflect.Type, len(tt))
700 for i, tp := range tt {
703 t.Errorf("scantype is null for column %q", tp.Name())
708 values := make([]interface{}, len(tt))
709 for i := range values {
710 values[i] = reflect.New(types[i]).Interface()
714 err = rows.Scan(values...)
716 t.Fatalf("failed to scan values in %v", err)
719 if age := *values[0].(*int32); age != 2 {
720 t.Errorf("Expected 2, got %v", age)
722 if name := *values[1].(*string); name != "Bob" {
723 t.Errorf("Expected Bob, got %v", name)
729 t.Errorf("expected 3 rows, got %d", ct)
732 if err := rows.Close(); err != nil {
733 t.Errorf("error closing rows: %s", err)
737 func TestQueryRow(t *testing.T) {
738 db := newTestDB(t, "people")
742 var birthday time.Time
744 err := db.QueryRow("SELECT|people|age,name|age=?", 3).Scan(&age)
745 if err == nil || !strings.Contains(err.Error(), "expected 2 destination arguments") {
746 t.Errorf("expected error from wrong number of arguments; actually got: %v", err)
749 err = db.QueryRow("SELECT|people|bdate|age=?", 3).Scan(&birthday)
750 if err != nil || !birthday.Equal(chrisBirthday) {
751 t.Errorf("chris birthday = %v, err = %v; want %v", birthday, err, chrisBirthday)
754 err = db.QueryRow("SELECT|people|age,name|age=?", 2).Scan(&age, &name)
756 t.Fatalf("age QueryRow+Scan: %v", err)
759 t.Errorf("expected name Bob, got %q", name)
762 t.Errorf("expected age 2, got %d", age)
765 err = db.QueryRow("SELECT|people|age,name|name=?", "Alice").Scan(&age, &name)
767 t.Fatalf("name QueryRow+Scan: %v", err)
770 t.Errorf("expected name Alice, got %q", name)
773 t.Errorf("expected age 1, got %d", age)
777 err = db.QueryRow("SELECT|people|photo|name=?", "Alice").Scan(&photo)
779 t.Fatalf("photo QueryRow+Scan: %v", err)
781 want := []byte("APHOTO")
782 if !reflect.DeepEqual(photo, want) {
783 t.Errorf("photo = %q; want %q", photo, want)
787 func TestTxRollbackCommitErr(t *testing.T) {
788 db := newTestDB(t, "people")
791 tx, err := db.Begin()
797 t.Errorf("expected nil error from Rollback; got %v", err)
800 if err != ErrTxDone {
801 t.Errorf("expected %q from Commit; got %q", ErrTxDone, err)
810 t.Errorf("expected nil error from Commit; got %v", err)
813 if err != ErrTxDone {
814 t.Errorf("expected %q from Rollback; got %q", ErrTxDone, err)
818 func TestStatementErrorAfterClose(t *testing.T) {
819 db := newTestDB(t, "people")
821 stmt, err := db.Prepare("SELECT|people|age|name=?")
823 t.Fatalf("Prepare: %v", err)
827 t.Fatalf("Close: %v", err)
830 err = stmt.QueryRow("foo").Scan(&name)
832 t.Errorf("expected error from QueryRow.Scan after Stmt.Close")
836 func TestStatementQueryRow(t *testing.T) {
837 db := newTestDB(t, "people")
839 stmt, err := db.Prepare("SELECT|people|age|name=?")
841 t.Fatalf("Prepare: %v", err)
845 for n, tt := range []struct {
853 if err := stmt.QueryRow(tt.name).Scan(&age); err != nil {
854 t.Errorf("%d: on %q, QueryRow/Scan: %v", n, tt.name, err)
855 } else if age != tt.want {
856 t.Errorf("%d: age=%d, want %d", n, age, tt.want)
861 type stubDriverStmt struct {
865 func (s stubDriverStmt) Close() error {
869 func (s stubDriverStmt) NumInput() int {
873 func (s stubDriverStmt) Exec(args []driver.Value) (driver.Result, error) {
877 func (s stubDriverStmt) Query(args []driver.Value) (driver.Rows, error) {
881 // golang.org/issue/12798
882 func TestStatementClose(t *testing.T) {
883 want := errors.New("STMT ERROR")
889 {&Stmt{stickyErr: want}, "stickyErr not propagated"},
890 {&Stmt{cg: &Tx{}, cgds: &driverStmt{Locker: &sync.Mutex{}, si: stubDriverStmt{want}}}, "driverStmt.Close() error not propagated"},
892 for _, test := range tests {
893 if err := test.stmt.Close(); err != want {
894 t.Errorf("%s. Got stmt.Close() = %v, want = %v", test.msg, err, want)
899 // golang.org/issue/3734
900 func TestStatementQueryRowConcurrent(t *testing.T) {
901 db := newTestDB(t, "people")
903 stmt, err := db.Prepare("SELECT|people|age|name=?")
905 t.Fatalf("Prepare: %v", err)
910 ch := make(chan error, n)
911 for i := 0; i < n; i++ {
914 err := stmt.QueryRow("Alice").Scan(&age)
915 if err == nil && age != 1 {
916 err = fmt.Errorf("unexpected age %d", age)
921 for i := 0; i < n; i++ {
922 if err := <-ch; err != nil {
928 // just a test of fakedb itself
929 func TestBogusPreboundParameters(t *testing.T) {
930 db := newTestDB(t, "foo")
932 exec(t, db, "CREATE|t1|name=string,age=int32,dead=bool")
933 _, err := db.Prepare("INSERT|t1|name=?,age=bogusconversion")
935 t.Fatalf("expected error")
937 if err.Error() != `fakedb: invalid conversion to int32 from "bogusconversion"` {
938 t.Errorf("unexpected error: %v", err)
942 func TestExec(t *testing.T) {
943 db := newTestDB(t, "foo")
945 exec(t, db, "CREATE|t1|name=string,age=int32,dead=bool")
946 stmt, err := db.Prepare("INSERT|t1|name=?,age=?")
948 t.Errorf("Stmt, err = %v, %v", stmt, err)
952 type execTest struct {
956 execTests := []execTest{
958 {[]interface{}{"Brad", 31}, ""},
959 {[]interface{}{"Brad", int64(31)}, ""},
960 {[]interface{}{"Bob", "32"}, ""},
961 {[]interface{}{7, 9}, ""},
963 // Invalid conversions:
964 {[]interface{}{"Brad", int64(0xFFFFFFFF)}, "sql: converting argument $2 type: sql/driver: value 4294967295 overflows int32"},
965 {[]interface{}{"Brad", "strconv fail"}, `sql: converting argument $2 type: sql/driver: value "strconv fail" can't be converted to int32`},
967 // Wrong number of args:
968 {[]interface{}{}, "sql: expected 2 arguments, got 0"},
969 {[]interface{}{1, 2, 3}, "sql: expected 2 arguments, got 3"},
971 for n, et := range execTests {
972 _, err := stmt.Exec(et.args...)
977 if errStr != et.wantErr {
978 t.Errorf("stmt.Execute #%d: for %v, got error %q, want error %q",
979 n, et.args, errStr, et.wantErr)
984 func TestTxPrepare(t *testing.T) {
985 db := newTestDB(t, "")
987 exec(t, db, "CREATE|t1|name=string,age=int32,dead=bool")
988 tx, err := db.Begin()
990 t.Fatalf("Begin = %v", err)
992 stmt, err := tx.Prepare("INSERT|t1|name=?,age=?")
994 t.Fatalf("Stmt, err = %v, %v", stmt, err)
997 _, err = stmt.Exec("Bobby", 7)
999 t.Fatalf("Exec = %v", err)
1003 t.Fatalf("Commit = %v", err)
1005 // Commit() should have closed the statement
1007 t.Fatal("Stmt not closed after Commit")
1011 func TestTxStmt(t *testing.T) {
1012 db := newTestDB(t, "")
1013 defer closeDB(t, db)
1014 exec(t, db, "CREATE|t1|name=string,age=int32,dead=bool")
1015 stmt, err := db.Prepare("INSERT|t1|name=?,age=?")
1017 t.Fatalf("Stmt, err = %v, %v", stmt, err)
1020 tx, err := db.Begin()
1022 t.Fatalf("Begin = %v", err)
1024 txs := tx.Stmt(stmt)
1026 _, err = txs.Exec("Bobby", 7)
1028 t.Fatalf("Exec = %v", err)
1032 t.Fatalf("Commit = %v", err)
1034 // Commit() should have closed the statement
1036 t.Fatal("Stmt not closed after Commit")
1040 func TestTxStmtPreparedOnce(t *testing.T) {
1041 db := newTestDB(t, "")
1042 defer closeDB(t, db)
1043 exec(t, db, "CREATE|t1|name=string,age=int32")
1045 prepares0 := numPrepares(t, db)
1047 // db.Prepare increments numPrepares.
1048 stmt, err := db.Prepare("INSERT|t1|name=?,age=?")
1050 t.Fatalf("Stmt, err = %v, %v", stmt, err)
1054 tx, err := db.Begin()
1056 t.Fatalf("Begin = %v", err)
1059 txs1 := tx.Stmt(stmt)
1060 txs2 := tx.Stmt(stmt)
1062 _, err = txs1.Exec("Go", 7)
1064 t.Fatalf("Exec = %v", err)
1068 _, err = txs2.Exec("Gopher", 8)
1070 t.Fatalf("Exec = %v", err)
1076 t.Fatalf("Commit = %v", err)
1079 if prepares := numPrepares(t, db) - prepares0; prepares != 1 {
1080 t.Errorf("executed %d Prepare statements; want 1", prepares)
1084 func TestTxStmtClosedRePrepares(t *testing.T) {
1085 db := newTestDB(t, "")
1086 defer closeDB(t, db)
1087 exec(t, db, "CREATE|t1|name=string,age=int32")
1089 prepares0 := numPrepares(t, db)
1091 // db.Prepare increments numPrepares.
1092 stmt, err := db.Prepare("INSERT|t1|name=?,age=?")
1094 t.Fatalf("Stmt, err = %v, %v", stmt, err)
1096 tx, err := db.Begin()
1098 t.Fatalf("Begin = %v", err)
1102 t.Fatalf("stmt.Close() = %v", err)
1104 // tx.Stmt increments numPrepares because stmt is closed.
1105 txs := tx.Stmt(stmt)
1106 if txs.stickyErr != nil {
1107 t.Fatal(txs.stickyErr)
1109 if txs.parentStmt != nil {
1110 t.Fatal("expected nil parentStmt")
1112 _, err = txs.Exec(`Eric`, 82)
1114 t.Fatalf("txs.Exec = %v", err)
1119 t.Fatalf("txs.Close = %v", err)
1124 if prepares := numPrepares(t, db) - prepares0; prepares != 2 {
1125 t.Errorf("executed %d Prepare statements; want 2", prepares)
1129 func TestParentStmtOutlivesTxStmt(t *testing.T) {
1130 db := newTestDB(t, "")
1131 defer closeDB(t, db)
1132 exec(t, db, "CREATE|t1|name=string,age=int32")
1134 // Make sure everything happens on the same connection.
1135 db.SetMaxOpenConns(1)
1137 prepares0 := numPrepares(t, db)
1139 // db.Prepare increments numPrepares.
1140 stmt, err := db.Prepare("INSERT|t1|name=?,age=?")
1142 t.Fatalf("Stmt, err = %v, %v", stmt, err)
1145 tx, err := db.Begin()
1147 t.Fatalf("Begin = %v", err)
1149 txs := tx.Stmt(stmt)
1150 if len(stmt.css) != 1 {
1151 t.Fatalf("len(stmt.css) = %v; want 1", len(stmt.css))
1155 t.Fatalf("txs.Close() = %v", err)
1159 t.Fatalf("tx.Rollback() = %v", err)
1161 // txs must not be valid.
1162 _, err = txs.Exec("Suzan", 30)
1164 t.Fatalf("txs.Exec(), expected err")
1166 // Stmt must still be valid.
1167 _, err = stmt.Exec("Janina", 25)
1169 t.Fatalf("stmt.Exec() = %v", err)
1172 if prepares := numPrepares(t, db) - prepares0; prepares != 1 {
1173 t.Errorf("executed %d Prepare statements; want 1", prepares)
1177 // Test that tx.Stmt called with a statement already
1178 // associated with tx as argument re-prepares the same
1180 func TestTxStmtFromTxStmtRePrepares(t *testing.T) {
1181 db := newTestDB(t, "")
1182 defer closeDB(t, db)
1183 exec(t, db, "CREATE|t1|name=string,age=int32")
1184 prepares0 := numPrepares(t, db)
1185 // db.Prepare increments numPrepares.
1186 stmt, err := db.Prepare("INSERT|t1|name=?,age=?")
1188 t.Fatalf("Stmt, err = %v, %v", stmt, err)
1192 tx, err := db.Begin()
1194 t.Fatalf("Begin = %v", err)
1196 txs1 := tx.Stmt(stmt)
1198 // tx.Stmt(txs1) increments numPrepares because txs1 already
1199 // belongs to a transaction (albeit the same transaction).
1200 txs2 := tx.Stmt(txs1)
1201 if txs2.stickyErr != nil {
1202 t.Fatal(txs2.stickyErr)
1204 if txs2.parentStmt != nil {
1205 t.Fatal("expected nil parentStmt")
1207 _, err = txs2.Exec(`Eric`, 82)
1214 t.Fatalf("txs1.Close = %v", err)
1218 t.Fatalf("txs1.Close = %v", err)
1222 t.Fatalf("tx.Rollback = %v", err)
1225 if prepares := numPrepares(t, db) - prepares0; prepares != 2 {
1226 t.Errorf("executed %d Prepare statements; want 2", prepares)
1230 // Issue: https://golang.org/issue/2784
1231 // This test didn't fail before because we got lucky with the fakedb driver.
1232 // It was failing, and now not, in github.com/bradfitz/go-sql-test
1233 func TestTxQuery(t *testing.T) {
1234 db := newTestDB(t, "")
1235 defer closeDB(t, db)
1236 exec(t, db, "CREATE|t1|name=string,age=int32,dead=bool")
1237 exec(t, db, "INSERT|t1|name=Alice")
1239 tx, err := db.Begin()
1245 r, err := tx.Query("SELECT|t1|name|")
1255 t.Fatal("expected one row")
1265 func TestTxQueryInvalid(t *testing.T) {
1266 db := newTestDB(t, "")
1267 defer closeDB(t, db)
1269 tx, err := db.Begin()
1275 _, err = tx.Query("SELECT|t1|name|")
1277 t.Fatal("Error expected")
1281 // Tests fix for issue 4433, that retries in Begin happen when
1282 // conn.Begin() returns ErrBadConn
1283 func TestTxErrBadConn(t *testing.T) {
1284 db, err := Open("test", fakeDBName+";badConn")
1286 t.Fatalf("Open: %v", err)
1288 if _, err := db.Exec("WIPE"); err != nil {
1289 t.Fatalf("exec wipe: %v", err)
1291 defer closeDB(t, db)
1292 exec(t, db, "CREATE|t1|name=string,age=int32,dead=bool")
1293 stmt, err := db.Prepare("INSERT|t1|name=?,age=?")
1295 t.Fatalf("Stmt, err = %v, %v", stmt, err)
1298 tx, err := db.Begin()
1300 t.Fatalf("Begin = %v", err)
1302 txs := tx.Stmt(stmt)
1304 _, err = txs.Exec("Bobby", 7)
1306 t.Fatalf("Exec = %v", err)
1310 t.Fatalf("Commit = %v", err)
1314 func TestConnQuery(t *testing.T) {
1315 db := newTestDB(t, "people")
1316 defer closeDB(t, db)
1318 ctx, cancel := context.WithCancel(context.Background())
1320 conn, err := db.Conn(ctx)
1324 conn.dc.ci.(*fakeConn).skipDirtySession = true
1328 err = conn.QueryRowContext(ctx, "SELECT|people|name|age=?", 3).Scan(&name)
1332 if name != "Chris" {
1333 t.Fatalf("unexpected result, got %q want Chris", name)
1336 err = conn.PingContext(ctx)
1342 func TestConnRaw(t *testing.T) {
1343 db := newTestDB(t, "people")
1344 defer closeDB(t, db)
1346 ctx, cancel := context.WithCancel(context.Background())
1348 conn, err := db.Conn(ctx)
1352 conn.dc.ci.(*fakeConn).skipDirtySession = true
1356 err = conn.Raw(func(dc interface{}) error {
1358 if _, ok := dc.(*fakeConn); !ok {
1359 return fmt.Errorf("got %T want *fakeConn", dc)
1367 t.Fatal("Raw func not called")
1374 t.Fatal("expected panic")
1377 closed := conn.dc == nil
1378 conn.closemu.Unlock()
1380 t.Fatal("expected connection to be closed after panic")
1383 err = conn.Raw(func(dc interface{}) error {
1384 panic("Conn.Raw panic should return an error")
1386 t.Fatal("expected panic from Raw func")
1390 func TestCursorFake(t *testing.T) {
1391 db := newTestDB(t, "people")
1392 defer closeDB(t, db)
1394 ctx, cancel := context.WithTimeout(context.Background(), time.Second*30)
1397 exec(t, db, "CREATE|peoplecursor|list=table")
1398 exec(t, db, "INSERT|peoplecursor|list=people!name!age")
1400 rows, err := db.QueryContext(ctx, `SELECT|peoplecursor|list|`)
1409 var cursor = &Rows{}
1410 err = rows.Scan(cursor)
1414 defer cursor.Close()
1416 const expectedRows = 3
1417 var currentRow int64
1423 err = cursor.Scan(&s, &n)
1427 if n != currentRow {
1428 t.Errorf("expected number(Age)=%d, got %d", currentRow, n)
1431 if currentRow != expectedRows {
1432 t.Errorf("expected %d rows, got %d rows", expectedRows, currentRow)
1436 func TestInvalidNilValues(t *testing.T) {
1443 expectedError string
1448 expectedError: `sql: Scan error on column index 0, name "bdate": unsupported Scan, storing driver.Value type <nil> into type *time.Time`,
1453 expectedError: `sql: Scan error on column index 0, name "bdate": converting NULL to int is unsupported`,
1457 for _, tt := range tests {
1458 t.Run(tt.name, func(t *testing.T) {
1459 db := newTestDB(t, "people")
1460 defer closeDB(t, db)
1462 ctx, cancel := context.WithCancel(context.Background())
1464 conn, err := db.Conn(ctx)
1468 conn.dc.ci.(*fakeConn).skipDirtySession = true
1471 err = conn.QueryRowContext(ctx, "SELECT|people|bdate|age=?", 1).Scan(tt.input)
1473 t.Fatal("expected error when querying nil column, but succeeded")
1475 if err.Error() != tt.expectedError {
1476 t.Fatalf("Expected error: %s\nReceived: %s", tt.expectedError, err.Error())
1479 err = conn.PingContext(ctx)
1487 func TestConnTx(t *testing.T) {
1488 db := newTestDB(t, "people")
1489 defer closeDB(t, db)
1491 ctx, cancel := context.WithCancel(context.Background())
1493 conn, err := db.Conn(ctx)
1497 conn.dc.ci.(*fakeConn).skipDirtySession = true
1500 tx, err := conn.BeginTx(ctx, nil)
1504 insertName, insertAge := "Nancy", 33
1505 _, err = tx.ExecContext(ctx, "INSERT|people|name=?,age=?,photo=APHOTO", insertName, insertAge)
1514 var selectName string
1515 err = conn.QueryRowContext(ctx, "SELECT|people|name|age=?", insertAge).Scan(&selectName)
1519 if selectName != insertName {
1520 t.Fatalf("got %q want %q", selectName, insertName)
1524 // Tests fix for issue 2542, that we release a lock when querying on
1525 // a closed connection.
1526 func TestIssue2542Deadlock(t *testing.T) {
1527 db := newTestDB(t, "people")
1529 for i := 0; i < 2; i++ {
1530 _, err := db.Query("SELECT|people|age,name|")
1532 t.Fatalf("expected error")
1537 // From golang.org/issue/3865
1538 func TestCloseStmtBeforeRows(t *testing.T) {
1539 db := newTestDB(t, "people")
1540 defer closeDB(t, db)
1542 s, err := db.Prepare("SELECT|people|name|")
1561 // Tests fix for issue 2788, that we bind nil to a []byte if the
1562 // value in the column is sql null
1563 func TestNullByteSlice(t *testing.T) {
1564 db := newTestDB(t, "")
1565 defer closeDB(t, db)
1566 exec(t, db, "CREATE|t|id=int32,name=nullstring")
1567 exec(t, db, "INSERT|t|id=10,name=?", nil)
1571 err := db.QueryRow("SELECT|t|name|id=?", 10).Scan(&name)
1576 t.Fatalf("name []byte should be nil for null column value, got: %#v", name)
1579 exec(t, db, "INSERT|t|id=11,name=?", "bob")
1580 err = db.QueryRow("SELECT|t|name|id=?", 11).Scan(&name)
1584 if string(name) != "bob" {
1585 t.Fatalf("name []byte should be bob, got: %q", string(name))
1589 func TestPointerParamsAndScans(t *testing.T) {
1590 db := newTestDB(t, "")
1591 defer closeDB(t, db)
1592 exec(t, db, "CREATE|t|id=int32,name=nullstring")
1598 exec(t, db, "INSERT|t|id=10,name=?", name)
1600 exec(t, db, "INSERT|t|id=20,name=?", name)
1602 err := db.QueryRow("SELECT|t|name|id=?", 10).Scan(&name)
1604 t.Fatalf("querying id 10: %v", err)
1607 t.Errorf("id 10's name = nil; want bob")
1608 } else if *name != "bob" {
1609 t.Errorf("id 10's name = %q; want bob", *name)
1612 err = db.QueryRow("SELECT|t|name|id=?", 20).Scan(&name)
1614 t.Fatalf("querying id 20: %v", err)
1617 t.Errorf("id 20 = %q; want nil", *name)
1621 func TestQueryRowClosingStmt(t *testing.T) {
1622 db := newTestDB(t, "people")
1623 defer closeDB(t, db)
1626 err := db.QueryRow("SELECT|people|age,name|age=?", 3).Scan(&age, &name)
1630 if len(db.freeConn) != 1 {
1631 t.Fatalf("expected 1 free conn")
1633 fakeConn := db.freeConn[0].ci.(*fakeConn)
1634 if made, closed := fakeConn.stmtsMade, fakeConn.stmtsClosed; made != closed {
1635 t.Errorf("statement close mismatch: made %d, closed %d", made, closed)
1639 var atomicRowsCloseHook atomic.Value // of func(*Rows, *error)
1642 rowsCloseHook = func() func(*Rows, *error) {
1643 fn, _ := atomicRowsCloseHook.Load().(func(*Rows, *error))
1648 func setRowsCloseHook(fn func(*Rows, *error)) {
1650 // Can't change an atomic.Value back to nil, so set it to this
1651 // no-op func instead.
1652 fn = func(*Rows, *error) {}
1654 atomicRowsCloseHook.Store(fn)
1658 func TestIssue6651(t *testing.T) {
1659 db := newTestDB(t, "people")
1660 defer closeDB(t, db)
1664 want := "error in rows.Next"
1665 rowsCursorNextHook = func(dest []driver.Value) error {
1666 return fmt.Errorf(want)
1668 defer func() { rowsCursorNextHook = nil }()
1670 err := db.QueryRow("SELECT|people|name|").Scan(&v)
1671 if err == nil || err.Error() != want {
1672 t.Errorf("error = %q; want %q", err, want)
1674 rowsCursorNextHook = nil
1676 want = "error in rows.Close"
1677 setRowsCloseHook(func(rows *Rows, err *error) {
1678 *err = fmt.Errorf(want)
1680 defer setRowsCloseHook(nil)
1681 err = db.QueryRow("SELECT|people|name|").Scan(&v)
1682 if err == nil || err.Error() != want {
1683 t.Errorf("error = %q; want %q", err, want)
1687 type nullTestRow struct {
1688 nullParam interface{}
1689 notNullParam interface{}
1690 scanNullVal interface{}
1693 type nullTestSpec struct {
1699 func TestNullStringParam(t *testing.T) {
1700 spec := nullTestSpec{"nullstring", "string", [6]nullTestRow{
1701 {NullString{"aqua", true}, "", NullString{"aqua", true}},
1702 {NullString{"brown", false}, "", NullString{"", false}},
1703 {"chartreuse", "", NullString{"chartreuse", true}},
1704 {NullString{"darkred", true}, "", NullString{"darkred", true}},
1705 {NullString{"eel", false}, "", NullString{"", false}},
1706 {"foo", NullString{"black", false}, nil},
1708 nullTestRun(t, spec)
1711 func TestNullInt64Param(t *testing.T) {
1712 spec := nullTestSpec{"nullint64", "int64", [6]nullTestRow{
1713 {NullInt64{31, true}, 1, NullInt64{31, true}},
1714 {NullInt64{-22, false}, 1, NullInt64{0, false}},
1715 {22, 1, NullInt64{22, true}},
1716 {NullInt64{33, true}, 1, NullInt64{33, true}},
1717 {NullInt64{222, false}, 1, NullInt64{0, false}},
1718 {0, NullInt64{31, false}, nil},
1720 nullTestRun(t, spec)
1723 func TestNullInt32Param(t *testing.T) {
1724 spec := nullTestSpec{"nullint32", "int32", [6]nullTestRow{
1725 {NullInt32{31, true}, 1, NullInt32{31, true}},
1726 {NullInt32{-22, false}, 1, NullInt32{0, false}},
1727 {22, 1, NullInt32{22, true}},
1728 {NullInt32{33, true}, 1, NullInt32{33, true}},
1729 {NullInt32{222, false}, 1, NullInt32{0, false}},
1730 {0, NullInt32{31, false}, nil},
1732 nullTestRun(t, spec)
1735 func TestNullFloat64Param(t *testing.T) {
1736 spec := nullTestSpec{"nullfloat64", "float64", [6]nullTestRow{
1737 {NullFloat64{31.2, true}, 1, NullFloat64{31.2, true}},
1738 {NullFloat64{13.1, false}, 1, NullFloat64{0, false}},
1739 {-22.9, 1, NullFloat64{-22.9, true}},
1740 {NullFloat64{33.81, true}, 1, NullFloat64{33.81, true}},
1741 {NullFloat64{222, false}, 1, NullFloat64{0, false}},
1742 {10, NullFloat64{31.2, false}, nil},
1744 nullTestRun(t, spec)
1747 func TestNullBoolParam(t *testing.T) {
1748 spec := nullTestSpec{"nullbool", "bool", [6]nullTestRow{
1749 {NullBool{false, true}, true, NullBool{false, true}},
1750 {NullBool{true, false}, false, NullBool{false, false}},
1751 {true, true, NullBool{true, true}},
1752 {NullBool{true, true}, false, NullBool{true, true}},
1753 {NullBool{true, false}, true, NullBool{false, false}},
1754 {true, NullBool{true, false}, nil},
1756 nullTestRun(t, spec)
1759 func TestNullTimeParam(t *testing.T) {
1761 t1 := time.Date(2000, 1, 1, 8, 9, 10, 11, time.UTC)
1762 t2 := time.Date(2010, 1, 1, 8, 9, 10, 11, time.UTC)
1763 spec := nullTestSpec{"nulldatetime", "datetime", [6]nullTestRow{
1764 {NullTime{t1, true}, t2, NullTime{t1, true}},
1765 {NullTime{t1, false}, t2, NullTime{t0, false}},
1766 {t1, t2, NullTime{t1, true}},
1767 {NullTime{t1, true}, t2, NullTime{t1, true}},
1768 {NullTime{t1, false}, t2, NullTime{t0, false}},
1769 {t2, NullTime{t1, false}, nil},
1771 nullTestRun(t, spec)
1774 func nullTestRun(t *testing.T, spec nullTestSpec) {
1775 db := newTestDB(t, "")
1776 defer closeDB(t, db)
1777 exec(t, db, fmt.Sprintf("CREATE|t|id=int32,name=string,nullf=%s,notnullf=%s", spec.nullType, spec.notNullType))
1779 // Inserts with db.Exec:
1780 exec(t, db, "INSERT|t|id=?,name=?,nullf=?,notnullf=?", 1, "alice", spec.rows[0].nullParam, spec.rows[0].notNullParam)
1781 exec(t, db, "INSERT|t|id=?,name=?,nullf=?,notnullf=?", 2, "bob", spec.rows[1].nullParam, spec.rows[1].notNullParam)
1783 // Inserts with a prepared statement:
1784 stmt, err := db.Prepare("INSERT|t|id=?,name=?,nullf=?,notnullf=?")
1786 t.Fatalf("prepare: %v", err)
1789 if _, err := stmt.Exec(3, "chris", spec.rows[2].nullParam, spec.rows[2].notNullParam); err != nil {
1790 t.Errorf("exec insert chris: %v", err)
1792 if _, err := stmt.Exec(4, "dave", spec.rows[3].nullParam, spec.rows[3].notNullParam); err != nil {
1793 t.Errorf("exec insert dave: %v", err)
1795 if _, err := stmt.Exec(5, "eleanor", spec.rows[4].nullParam, spec.rows[4].notNullParam); err != nil {
1796 t.Errorf("exec insert eleanor: %v", err)
1799 // Can't put null val into non-null col
1800 if _, err := stmt.Exec(6, "bob", spec.rows[5].nullParam, spec.rows[5].notNullParam); err == nil {
1801 t.Errorf("expected error inserting nil val with prepared statement Exec")
1804 _, err = db.Exec("INSERT|t|id=?,name=?,nullf=?", 999, nil, nil)
1806 // TODO: this test fails, but it's just because
1807 // fakeConn implements the optional Execer interface,
1808 // so arguably this is the correct behavior. But
1809 // maybe I should flesh out the fakeConn.Exec
1810 // implementation so this properly fails.
1811 // t.Errorf("expected error inserting nil name with Exec")
1814 paramtype := reflect.TypeOf(spec.rows[0].nullParam)
1815 bindVal := reflect.New(paramtype).Interface()
1817 for i := 0; i < 5; i++ {
1819 if err := db.QueryRow("SELECT|t|nullf|id=?", id).Scan(bindVal); err != nil {
1820 t.Errorf("id=%d Scan: %v", id, err)
1822 bindValDeref := reflect.ValueOf(bindVal).Elem().Interface()
1823 if !reflect.DeepEqual(bindValDeref, spec.rows[i].scanNullVal) {
1824 t.Errorf("id=%d got %#v, want %#v", id, bindValDeref, spec.rows[i].scanNullVal)
1829 // golang.org/issue/4859
1830 func TestQueryRowNilScanDest(t *testing.T) {
1831 db := newTestDB(t, "people")
1832 defer closeDB(t, db)
1833 var name *string // nil pointer
1834 err := db.QueryRow("SELECT|people|name|").Scan(name)
1835 want := `sql: Scan error on column index 0, name "name": destination pointer is nil`
1836 if err == nil || err.Error() != want {
1837 t.Errorf("error = %q; want %q", err.Error(), want)
1841 func TestIssue4902(t *testing.T) {
1842 db := newTestDB(t, "people")
1843 defer closeDB(t, db)
1845 driver := db.Driver().(*fakeDriver)
1846 opens0 := driver.openCount
1850 for i := 0; i < 10; i++ {
1851 stmt, err = db.Prepare("SELECT|people|name|")
1861 opens := driver.openCount - opens0
1863 t.Errorf("opens = %d; want <= 1", opens)
1864 t.Logf("db = %#v", db)
1865 t.Logf("driver = %#v", driver)
1866 t.Logf("stmt = %#v", stmt)
1871 // This used to deadlock.
1872 func TestSimultaneousQueries(t *testing.T) {
1873 db := newTestDB(t, "people")
1874 defer closeDB(t, db)
1876 tx, err := db.Begin()
1882 r1, err := tx.Query("SELECT|people|name|")
1888 r2, err := tx.Query("SELECT|people|name|")
1895 func TestMaxIdleConns(t *testing.T) {
1896 db := newTestDB(t, "people")
1897 defer closeDB(t, db)
1899 tx, err := db.Begin()
1904 if got := len(db.freeConn); got != 1 {
1905 t.Errorf("freeConns = %d; want 1", got)
1908 db.SetMaxIdleConns(0)
1910 if got := len(db.freeConn); got != 0 {
1911 t.Errorf("freeConns after set to zero = %d; want 0", got)
1914 tx, err = db.Begin()
1919 if got := len(db.freeConn); got != 0 {
1920 t.Errorf("freeConns = %d; want 0", got)
1924 func TestMaxOpenConns(t *testing.T) {
1925 if testing.Short() {
1926 t.Skip("skipping in short mode")
1928 defer setHookpostCloseConn(nil)
1929 setHookpostCloseConn(func(_ *fakeConn, err error) {
1931 t.Errorf("Error closing fakeConn: %v", err)
1935 db := newTestDB(t, "magicquery")
1936 defer closeDB(t, db)
1938 driver := db.Driver().(*fakeDriver)
1940 // Force the number of open connections to 0 so we can get an accurate
1941 // count for the test
1945 opens0 := driver.openCount
1946 closes0 := driver.closeCount
1949 db.SetMaxIdleConns(10)
1950 db.SetMaxOpenConns(10)
1952 stmt, err := db.Prepare("SELECT|magicquery|op|op=?,millis=?")
1957 // Start 50 parallel slow queries.
1963 var wg sync.WaitGroup
1964 for batch := 0; batch < nbatch; batch++ {
1965 for i := 0; i < nquery; i++ {
1970 if err := stmt.QueryRow("sleep", sleepMillis).Scan(&op); err != nil && err != ErrNoRows {
1975 // Sleep for twice the expected length of time for the
1976 // batch of 50 queries above to finish before starting
1978 time.Sleep(2 * sleepMillis * time.Millisecond)
1982 if g, w := db.numFreeConns(), 10; g != w {
1983 t.Errorf("free conns = %d; want %d", g, w)
1986 if n := db.numDepsPollUntil(20, time.Second); n > 20 {
1987 t.Errorf("number of dependencies = %d; expected <= 20", n)
1992 opens := driver.openCount - opens0
1993 closes := driver.closeCount - closes0
1997 t.Logf("open calls = %d", opens)
1998 t.Logf("close calls = %d", closes)
1999 t.Errorf("db connections opened = %d; want <= 10", opens)
2003 if err := stmt.Close(); err != nil {
2007 if g, w := db.numFreeConns(), 10; g != w {
2008 t.Errorf("free conns = %d; want %d", g, w)
2011 if n := db.numDepsPollUntil(10, time.Second); n > 10 {
2012 t.Errorf("number of dependencies = %d; expected <= 10", n)
2016 db.SetMaxOpenConns(5)
2018 if g, w := db.numFreeConns(), 5; g != w {
2019 t.Errorf("free conns = %d; want %d", g, w)
2022 if n := db.numDepsPollUntil(5, time.Second); n > 5 {
2023 t.Errorf("number of dependencies = %d; expected 0", n)
2027 db.SetMaxOpenConns(0)
2029 if g, w := db.numFreeConns(), 5; g != w {
2030 t.Errorf("free conns = %d; want %d", g, w)
2033 if n := db.numDepsPollUntil(5, time.Second); n > 5 {
2034 t.Errorf("number of dependencies = %d; expected 0", n)
2041 // Issue 9453: tests that SetMaxOpenConns can be lowered at runtime
2042 // and affects the subsequent release of connections.
2043 func TestMaxOpenConnsOnBusy(t *testing.T) {
2044 defer setHookpostCloseConn(nil)
2045 setHookpostCloseConn(func(_ *fakeConn, err error) {
2047 t.Errorf("Error closing fakeConn: %v", err)
2051 db := newTestDB(t, "magicquery")
2052 defer closeDB(t, db)
2054 db.SetMaxOpenConns(3)
2056 ctx := context.Background()
2058 conn0, err := db.conn(ctx, cachedOrNewConn)
2060 t.Fatalf("db open conn fail: %v", err)
2063 conn1, err := db.conn(ctx, cachedOrNewConn)
2065 t.Fatalf("db open conn fail: %v", err)
2068 conn2, err := db.conn(ctx, cachedOrNewConn)
2070 t.Fatalf("db open conn fail: %v", err)
2073 if g, w := db.numOpen, 3; g != w {
2074 t.Errorf("free conns = %d; want %d", g, w)
2077 db.SetMaxOpenConns(2)
2078 if g, w := db.numOpen, 3; g != w {
2079 t.Errorf("free conns = %d; want %d", g, w)
2082 conn0.releaseConn(nil)
2083 conn1.releaseConn(nil)
2084 if g, w := db.numOpen, 2; g != w {
2085 t.Errorf("free conns = %d; want %d", g, w)
2088 conn2.releaseConn(nil)
2089 if g, w := db.numOpen, 2; g != w {
2090 t.Errorf("free conns = %d; want %d", g, w)
2094 // Issue 10886: tests that all connection attempts return when more than
2095 // DB.maxOpen connections are in flight and the first DB.maxOpen fail.
2096 func TestPendingConnsAfterErr(t *testing.T) {
2099 tryOpen = maxOpen*2 + 2
2102 // No queries will be run.
2103 db, err := Open("test", fakeDBName)
2105 t.Fatalf("Open: %v", err)
2107 defer closeDB(t, db)
2109 for k, v := range db.lastPut {
2110 t.Logf("%p: %v", k, v)
2114 db.SetMaxOpenConns(maxOpen)
2115 db.SetMaxIdleConns(0)
2117 errOffline := errors.New("db offline")
2119 defer func() { setHookOpenErr(nil) }()
2121 errs := make(chan error, tryOpen)
2123 var opening sync.WaitGroup
2124 opening.Add(tryOpen)
2126 setHookOpenErr(func() error {
2127 // Wait for all connections to enqueue.
2132 for i := 0; i < tryOpen; i++ {
2134 opening.Done() // signal one connection is in flight
2135 _, err := db.Exec("will never run")
2140 opening.Wait() // wait for all workers to begin running
2142 const timeout = 5 * time.Second
2143 to := time.NewTimer(timeout)
2146 // check that all connections fail without deadlock
2147 for i := 0; i < tryOpen; i++ {
2150 if got, want := err, errOffline; got != want {
2151 t.Errorf("unexpected err: got %v, want %v", got, want)
2154 t.Fatalf("orphaned connection request(s), still waiting after %v", timeout)
2158 // Wait a reasonable time for the database to close all connections.
2159 tick := time.NewTicker(3 * time.Millisecond)
2165 if db.numOpen == 0 {
2171 // Closing the database will check for numOpen and fail the test.
2177 func TestSingleOpenConn(t *testing.T) {
2178 db := newTestDB(t, "people")
2179 defer closeDB(t, db)
2181 db.SetMaxOpenConns(1)
2183 rows, err := db.Query("SELECT|people|name|")
2187 if err = rows.Close(); err != nil {
2190 // shouldn't deadlock
2191 rows, err = db.Query("SELECT|people|name|")
2195 if err = rows.Close(); err != nil {
2200 func TestStats(t *testing.T) {
2201 db := newTestDB(t, "people")
2203 if got := stats.OpenConnections; got != 1 {
2204 t.Errorf("stats.OpenConnections = %d; want 1", got)
2207 tx, err := db.Begin()
2215 if got := stats.OpenConnections; got != 0 {
2216 t.Errorf("stats.OpenConnections = %d; want 0", got)
2220 func TestConnMaxLifetime(t *testing.T) {
2221 t0 := time.Unix(1000000, 0)
2222 offset := time.Duration(0)
2224 nowFunc = func() time.Time { return t0.Add(offset) }
2225 defer func() { nowFunc = time.Now }()
2227 db := newTestDB(t, "magicquery")
2228 defer closeDB(t, db)
2230 driver := db.Driver().(*fakeDriver)
2232 // Force the number of open connections to 0 so we can get an accurate
2233 // count for the test
2237 opens0 := driver.openCount
2238 closes0 := driver.closeCount
2241 db.SetMaxIdleConns(10)
2242 db.SetMaxOpenConns(10)
2244 tx, err := db.Begin()
2249 offset = time.Second
2250 tx2, err := db.Begin()
2259 opens := driver.openCount - opens0
2260 closes := driver.closeCount - closes0
2264 t.Errorf("opens = %d; want 2", opens)
2267 t.Errorf("closes = %d; want 0", closes)
2269 if g, w := db.numFreeConns(), 2; g != w {
2270 t.Errorf("free conns = %d; want %d", g, w)
2273 // Expire first conn
2274 offset = 11 * time.Second
2275 db.SetConnMaxLifetime(10 * time.Second)
2280 tx, err = db.Begin()
2284 tx2, err = db.Begin()
2292 opens = driver.openCount - opens0
2293 closes = driver.closeCount - closes0
2297 t.Errorf("opens = %d; want 3", opens)
2300 t.Errorf("closes = %d; want 1", closes)
2304 // golang.org/issue/5323
2305 func TestStmtCloseDeps(t *testing.T) {
2306 if testing.Short() {
2307 t.Skip("skipping in short mode")
2309 defer setHookpostCloseConn(nil)
2310 setHookpostCloseConn(func(_ *fakeConn, err error) {
2312 t.Errorf("Error closing fakeConn: %v", err)
2316 db := newTestDB(t, "magicquery")
2317 defer closeDB(t, db)
2319 driver := db.Driver().(*fakeDriver)
2322 opens0 := driver.openCount
2323 closes0 := driver.closeCount
2325 openDelta0 := opens0 - closes0
2327 stmt, err := db.Prepare("SELECT|magicquery|op|op=?,millis=?")
2332 // Start 50 parallel slow queries.
2338 var wg sync.WaitGroup
2339 for batch := 0; batch < nbatch; batch++ {
2340 for i := 0; i < nquery; i++ {
2345 if err := stmt.QueryRow("sleep", sleepMillis).Scan(&op); err != nil && err != ErrNoRows {
2350 // Sleep for twice the expected length of time for the
2351 // batch of 50 queries above to finish before starting
2353 time.Sleep(2 * sleepMillis * time.Millisecond)
2357 if g, w := db.numFreeConns(), 2; g != w {
2358 t.Errorf("free conns = %d; want %d", g, w)
2361 if n := db.numDepsPollUntil(4, time.Second); n > 4 {
2362 t.Errorf("number of dependencies = %d; expected <= 4", n)
2367 opens := driver.openCount - opens0
2368 closes := driver.closeCount - closes0
2369 openDelta := (driver.openCount - driver.closeCount) - openDelta0
2373 t.Logf("open calls = %d", opens)
2374 t.Logf("close calls = %d", closes)
2375 t.Logf("open delta = %d", openDelta)
2376 t.Errorf("db connections opened = %d; want <= 2", openDelta)
2380 if !waitCondition(5*time.Second, 5*time.Millisecond, func() bool {
2381 return len(stmt.css) <= nquery
2383 t.Errorf("len(stmt.css) = %d; want <= %d", len(stmt.css), nquery)
2386 if err := stmt.Close(); err != nil {
2390 if g, w := db.numFreeConns(), 2; g != w {
2391 t.Errorf("free conns = %d; want %d", g, w)
2394 if n := db.numDepsPollUntil(2, time.Second); n > 2 {
2395 t.Errorf("number of dependencies = %d; expected <= 2", n)
2402 // golang.org/issue/5046
2403 func TestCloseConnBeforeStmts(t *testing.T) {
2404 db := newTestDB(t, "people")
2405 defer closeDB(t, db)
2407 defer setHookpostCloseConn(nil)
2408 setHookpostCloseConn(func(_ *fakeConn, err error) {
2410 t.Errorf("Error closing fakeConn: %v; from %s", err, stack())
2412 t.Errorf("DB = %#v", db)
2416 stmt, err := db.Prepare("SELECT|people|name|")
2421 if len(db.freeConn) != 1 {
2422 t.Fatalf("expected 1 freeConn; got %d", len(db.freeConn))
2424 dc := db.freeConn[0]
2426 t.Errorf("conn shouldn't be closed")
2429 if n := len(dc.openStmt); n != 1 {
2430 t.Errorf("driverConn num openStmt = %d; want 1", n)
2434 t.Errorf("db Close = %v", err)
2437 t.Errorf("after db.Close, driverConn should be closed")
2439 if n := len(dc.openStmt); n != 0 {
2440 t.Errorf("driverConn num openStmt = %d; want 0", n)
2445 t.Errorf("Stmt close = %v", err)
2449 t.Errorf("conn should be closed")
2452 t.Errorf("after Stmt Close, driverConn's Conn interface should be nil")
2456 // golang.org/issue/5283: don't release the Rows' connection in Close
2457 // before calling Stmt.Close.
2458 func TestRowsCloseOrder(t *testing.T) {
2459 db := newTestDB(t, "people")
2460 defer closeDB(t, db)
2462 db.SetMaxIdleConns(0)
2463 setStrictFakeConnClose(t)
2464 defer setStrictFakeConnClose(nil)
2466 rows, err := db.Query("SELECT|people|age,name|")
2476 func TestRowsImplicitClose(t *testing.T) {
2477 db := newTestDB(t, "people")
2478 defer closeDB(t, db)
2480 rows, err := db.Query("SELECT|people|age,name|")
2485 want, fail := 2, errors.New("fail")
2486 r := rows.rowsi.(*rowsCursor)
2487 r.errPos, r.err = want, fail
2494 t.Errorf("got %d rows, want %d", got, want)
2496 if err := rows.Err(); err != fail {
2497 t.Errorf("got error %v, want %v", err, fail)
2500 t.Errorf("r.closed is false, want true")
2504 func TestStmtCloseOrder(t *testing.T) {
2505 db := newTestDB(t, "people")
2506 defer closeDB(t, db)
2508 db.SetMaxIdleConns(0)
2509 setStrictFakeConnClose(t)
2510 defer setStrictFakeConnClose(nil)
2512 _, err := db.Query("SELECT|non_existent|name|")
2514 t.Fatal("Querying non-existent table should fail")
2518 // Test cases where there's more than maxBadConnRetries bad connections in the
2519 // pool (issue 8834)
2520 func TestManyErrBadConn(t *testing.T) {
2521 manyErrBadConnSetup := func(first ...func(db *DB)) *DB {
2522 db := newTestDB(t, "people")
2524 for _, f := range first {
2528 nconn := maxBadConnRetries + 1
2529 db.SetMaxIdleConns(nconn)
2530 db.SetMaxOpenConns(nconn)
2531 // open enough connections
2533 for i := 0; i < nconn; i++ {
2534 rows, err := db.Query("SELECT|people|age,name|")
2543 defer db.mu.Unlock()
2544 if db.numOpen != nconn {
2545 t.Fatalf("unexpected numOpen %d (was expecting %d)", db.numOpen, nconn)
2546 } else if len(db.freeConn) != nconn {
2547 t.Fatalf("unexpected len(db.freeConn) %d (was expecting %d)", len(db.freeConn), nconn)
2549 for _, conn := range db.freeConn {
2551 conn.ci.(*fakeConn).stickyBad = true
2558 db := manyErrBadConnSetup()
2559 defer closeDB(t, db)
2560 rows, err := db.Query("SELECT|people|age,name|")
2564 if err = rows.Close(); err != nil {
2569 db = manyErrBadConnSetup()
2570 defer closeDB(t, db)
2571 _, err = db.Exec("INSERT|people|name=Julia,age=19")
2577 db = manyErrBadConnSetup()
2578 defer closeDB(t, db)
2579 tx, err := db.Begin()
2583 if err = tx.Rollback(); err != nil {
2588 db = manyErrBadConnSetup()
2589 defer closeDB(t, db)
2590 stmt, err := db.Prepare("SELECT|people|age,name|")
2594 if err = stmt.Close(); err != nil {
2599 db = manyErrBadConnSetup(func(db *DB) {
2600 stmt, err = db.Prepare("INSERT|people|name=Julia,age=19")
2605 defer closeDB(t, db)
2606 _, err = stmt.Exec()
2610 if err = stmt.Close(); err != nil {
2615 db = manyErrBadConnSetup(func(db *DB) {
2616 stmt, err = db.Prepare("SELECT|people|age,name|")
2621 defer closeDB(t, db)
2622 rows, err = stmt.Query()
2626 if err = rows.Close(); err != nil {
2629 if err = stmt.Close(); err != nil {
2634 db = manyErrBadConnSetup()
2635 defer closeDB(t, db)
2636 ctx, cancel := context.WithCancel(context.Background())
2638 conn, err := db.Conn(ctx)
2642 conn.dc.ci.(*fakeConn).skipDirtySession = true
2649 db = manyErrBadConnSetup()
2650 defer closeDB(t, db)
2651 err = db.PingContext(ctx)
2657 // TestIssue20575 ensures the Rows from query does not block
2658 // closing a transaction. Ensure Rows is closed while closing a trasaction.
2659 func TestIssue20575(t *testing.T) {
2660 db := newTestDB(t, "people")
2661 defer closeDB(t, db)
2663 tx, err := db.Begin()
2667 ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
2669 _, err = tx.QueryContext(ctx, "SELECT|people|age,name|")
2673 // Do not close Rows from QueryContext.
2681 t.Fatal("timeout: failed to rollback query without closing rows:", ctx.Err())
2685 // TestIssue20622 tests closing the transaction before rows is closed, requires
2686 // the race detector to fail.
2687 func TestIssue20622(t *testing.T) {
2688 db := newTestDB(t, "people")
2689 defer closeDB(t, db)
2691 ctx, cancel := context.WithCancel(context.Background())
2694 tx, err := db.BeginTx(ctx, nil)
2699 rows, err := tx.Query("SELECT|people|age,name|")
2709 if err := rows.Scan(&age, &name); err != nil {
2710 t.Fatal("scan failed", err)
2716 time.Sleep(100 * time.Millisecond)
2722 // golang.org/issue/5718
2723 func TestErrBadConnReconnect(t *testing.T) {
2724 db := newTestDB(t, "foo")
2725 defer closeDB(t, db)
2726 exec(t, db, "CREATE|t1|name=string,age=int32,dead=bool")
2728 simulateBadConn := func(name string, hook *func() bool, op func() error) {
2729 broken, retried := false, false
2730 numOpen := db.numOpen
2732 // simulate a broken connection on the first try
2733 *hook = func() bool {
2742 if err := op(); err != nil {
2743 t.Errorf(name+": %v", err)
2747 if !broken || !retried {
2748 t.Error(name + ": Failed to simulate broken connection")
2752 if numOpen != db.numOpen {
2753 t.Errorf(name+": leaked %d connection(s)!", db.numOpen-numOpen)
2754 numOpen = db.numOpen
2759 dbExec := func() error {
2760 _, err := db.Exec("INSERT|t1|name=?,age=?,dead=?", "Gordon", 3, true)
2763 simulateBadConn("db.Exec prepare", &hookPrepareBadConn, dbExec)
2764 simulateBadConn("db.Exec exec", &hookExecBadConn, dbExec)
2767 dbQuery := func() error {
2768 rows, err := db.Query("SELECT|t1|age,name|")
2774 simulateBadConn("db.Query prepare", &hookPrepareBadConn, dbQuery)
2775 simulateBadConn("db.Query query", &hookQueryBadConn, dbQuery)
2778 simulateBadConn("db.Prepare", &hookPrepareBadConn, func() error {
2779 stmt, err := db.Prepare("INSERT|t1|name=?,age=?,dead=?")
2787 // Provide a way to force a re-prepare of a statement on next execution
2788 forcePrepare := func(stmt *Stmt) {
2793 stmt1, err := db.Prepare("INSERT|t1|name=?,age=?,dead=?")
2795 t.Fatalf("prepare: %v", err)
2798 // make sure we must prepare the stmt first
2801 stmtExec := func() error {
2802 _, err := stmt1.Exec("Gopher", 3, false)
2805 simulateBadConn("stmt.Exec prepare", &hookPrepareBadConn, stmtExec)
2806 simulateBadConn("stmt.Exec exec", &hookExecBadConn, stmtExec)
2809 stmt2, err := db.Prepare("SELECT|t1|age,name|")
2811 t.Fatalf("prepare: %v", err)
2814 // make sure we must prepare the stmt first
2817 stmtQuery := func() error {
2818 rows, err := stmt2.Query()
2824 simulateBadConn("stmt.Query prepare", &hookPrepareBadConn, stmtQuery)
2825 simulateBadConn("stmt.Query exec", &hookQueryBadConn, stmtQuery)
2828 // golang.org/issue/11264
2829 func TestTxEndBadConn(t *testing.T) {
2830 db := newTestDB(t, "foo")
2831 defer closeDB(t, db)
2832 db.SetMaxIdleConns(0)
2833 exec(t, db, "CREATE|t1|name=string,age=int32,dead=bool")
2834 db.SetMaxIdleConns(1)
2836 simulateBadConn := func(name string, hook *func() bool, op func() error) {
2838 numOpen := db.numOpen
2840 *hook = func() bool {
2847 if err := op(); err != driver.ErrBadConn {
2848 t.Errorf(name+": %v", err)
2853 t.Error(name + ": Failed to simulate broken connection")
2857 if numOpen != db.numOpen {
2858 t.Errorf(name+": leaked %d connection(s)!", db.numOpen-numOpen)
2863 dbExec := func(endTx func(tx *Tx) error) func() error {
2864 return func() error {
2865 tx, err := db.Begin()
2869 _, err = tx.Exec("INSERT|t1|name=?,age=?,dead=?", "Gordon", 3, true)
2876 simulateBadConn("db.Tx.Exec commit", &hookCommitBadConn, dbExec((*Tx).Commit))
2877 simulateBadConn("db.Tx.Exec rollback", &hookRollbackBadConn, dbExec((*Tx).Rollback))
2880 dbQuery := func(endTx func(tx *Tx) error) func() error {
2881 return func() error {
2882 tx, err := db.Begin()
2886 rows, err := tx.Query("SELECT|t1|age,name|")
2895 simulateBadConn("db.Tx.Query commit", &hookCommitBadConn, dbQuery((*Tx).Commit))
2896 simulateBadConn("db.Tx.Query rollback", &hookRollbackBadConn, dbQuery((*Tx).Rollback))
2899 type concurrentTest interface {
2900 init(t testing.TB, db *DB)
2901 finish(t testing.TB)
2902 test(t testing.TB) error
2905 type concurrentDBQueryTest struct {
2909 func (c *concurrentDBQueryTest) init(t testing.TB, db *DB) {
2913 func (c *concurrentDBQueryTest) finish(t testing.TB) {
2917 func (c *concurrentDBQueryTest) test(t testing.TB) error {
2918 rows, err := c.db.Query("SELECT|people|name|")
2931 type concurrentDBExecTest struct {
2935 func (c *concurrentDBExecTest) init(t testing.TB, db *DB) {
2939 func (c *concurrentDBExecTest) finish(t testing.TB) {
2943 func (c *concurrentDBExecTest) test(t testing.TB) error {
2944 _, err := c.db.Exec("NOSERT|people|name=Chris,age=?,photo=CPHOTO,bdate=?", 3, chrisBirthday)
2952 type concurrentStmtQueryTest struct {
2957 func (c *concurrentStmtQueryTest) init(t testing.TB, db *DB) {
2960 c.stmt, err = db.Prepare("SELECT|people|name|")
2966 func (c *concurrentStmtQueryTest) finish(t testing.TB) {
2974 func (c *concurrentStmtQueryTest) test(t testing.TB) error {
2975 rows, err := c.stmt.Query()
2977 t.Errorf("error on query: %v", err)
2989 type concurrentStmtExecTest struct {
2994 func (c *concurrentStmtExecTest) init(t testing.TB, db *DB) {
2997 c.stmt, err = db.Prepare("NOSERT|people|name=Chris,age=?,photo=CPHOTO,bdate=?")
3003 func (c *concurrentStmtExecTest) finish(t testing.TB) {
3011 func (c *concurrentStmtExecTest) test(t testing.TB) error {
3012 _, err := c.stmt.Exec(3, chrisBirthday)
3014 t.Errorf("error on exec: %v", err)
3020 type concurrentTxQueryTest struct {
3025 func (c *concurrentTxQueryTest) init(t testing.TB, db *DB) {
3028 c.tx, err = c.db.Begin()
3034 func (c *concurrentTxQueryTest) finish(t testing.TB) {
3042 func (c *concurrentTxQueryTest) test(t testing.TB) error {
3043 rows, err := c.db.Query("SELECT|people|name|")
3056 type concurrentTxExecTest struct {
3061 func (c *concurrentTxExecTest) init(t testing.TB, db *DB) {
3064 c.tx, err = c.db.Begin()
3070 func (c *concurrentTxExecTest) finish(t testing.TB) {
3078 func (c *concurrentTxExecTest) test(t testing.TB) error {
3079 _, err := c.tx.Exec("NOSERT|people|name=Chris,age=?,photo=CPHOTO,bdate=?", 3, chrisBirthday)
3087 type concurrentTxStmtQueryTest struct {
3093 func (c *concurrentTxStmtQueryTest) init(t testing.TB, db *DB) {
3096 c.tx, err = c.db.Begin()
3100 c.stmt, err = c.tx.Prepare("SELECT|people|name|")
3106 func (c *concurrentTxStmtQueryTest) finish(t testing.TB) {
3118 func (c *concurrentTxStmtQueryTest) test(t testing.TB) error {
3119 rows, err := c.stmt.Query()
3121 t.Errorf("error on query: %v", err)
3133 type concurrentTxStmtExecTest struct {
3139 func (c *concurrentTxStmtExecTest) init(t testing.TB, db *DB) {
3142 c.tx, err = c.db.Begin()
3146 c.stmt, err = c.tx.Prepare("NOSERT|people|name=Chris,age=?,photo=CPHOTO,bdate=?")
3152 func (c *concurrentTxStmtExecTest) finish(t testing.TB) {
3164 func (c *concurrentTxStmtExecTest) test(t testing.TB) error {
3165 _, err := c.stmt.Exec(3, chrisBirthday)
3167 t.Errorf("error on exec: %v", err)
3173 type concurrentRandomTest struct {
3174 tests []concurrentTest
3177 func (c *concurrentRandomTest) init(t testing.TB, db *DB) {
3178 c.tests = []concurrentTest{
3179 new(concurrentDBQueryTest),
3180 new(concurrentDBExecTest),
3181 new(concurrentStmtQueryTest),
3182 new(concurrentStmtExecTest),
3183 new(concurrentTxQueryTest),
3184 new(concurrentTxExecTest),
3185 new(concurrentTxStmtQueryTest),
3186 new(concurrentTxStmtExecTest),
3188 for _, ct := range c.tests {
3193 func (c *concurrentRandomTest) finish(t testing.TB) {
3194 for _, ct := range c.tests {
3199 func (c *concurrentRandomTest) test(t testing.TB) error {
3200 ct := c.tests[rand.Intn(len(c.tests))]
3204 func doConcurrentTest(t testing.TB, ct concurrentTest) {
3205 maxProcs, numReqs := 1, 500
3206 if testing.Short() {
3207 maxProcs, numReqs = 4, 50
3209 defer runtime.GOMAXPROCS(runtime.GOMAXPROCS(maxProcs))
3211 db := newTestDB(t, "people")
3212 defer closeDB(t, db)
3217 var wg sync.WaitGroup
3220 reqs := make(chan bool)
3223 for i := 0; i < maxProcs*2; i++ {
3236 for i := 0; i < numReqs; i++ {
3243 func TestIssue6081(t *testing.T) {
3244 db := newTestDB(t, "people")
3245 defer closeDB(t, db)
3247 drv := db.Driver().(*fakeDriver)
3249 opens0 := drv.openCount
3250 closes0 := drv.closeCount
3253 stmt, err := db.Prepare("SELECT|people|name|")
3257 setRowsCloseHook(func(rows *Rows, err *error) {
3258 *err = driver.ErrBadConn
3260 defer setRowsCloseHook(nil)
3261 for i := 0; i < 10; i++ {
3262 rows, err := stmt.Query()
3268 if n := len(stmt.css); n > 1 {
3269 t.Errorf("len(css slice) = %d; want <= 1", n)
3272 if n := len(stmt.css); n != 0 {
3273 t.Errorf("len(css slice) after Close = %d; want 0", n)
3277 opens := drv.openCount - opens0
3278 closes := drv.closeCount - closes0
3281 t.Errorf("opens = %d; want >= 9", opens)
3284 t.Errorf("closes = %d; want >= 9", closes)
3288 // TestIssue18429 attempts to stress rolling back the transaction from a
3289 // context cancel while simultaneously calling Tx.Rollback. Rolling back from a
3290 // context happens concurrently so tx.rollback and tx.Commit must guard against
3293 // In the test, a context is canceled while the query is in process so
3294 // the internal rollback will run concurrently with the explicitly called
3297 // The addition of calling rows.Next also tests
3299 func TestIssue18429(t *testing.T) {
3300 db := newTestDB(t, "people")
3301 defer closeDB(t, db)
3303 ctx := context.Background()
3304 sem := make(chan bool, 20)
3305 var wg sync.WaitGroup
3307 const milliWait = 30
3309 for i := 0; i < 100; i++ {
3317 qwait := (time.Duration(rand.Intn(milliWait)) * time.Millisecond).String()
3319 ctx, cancel := context.WithTimeout(ctx, time.Duration(rand.Intn(milliWait))*time.Millisecond)
3322 tx, err := db.BeginTx(ctx, nil)
3326 // This is expected to give a cancel error most, but not all the time.
3327 // Test failure will happen with a panic or other race condition being
3329 rows, _ := tx.QueryContext(ctx, "WAIT|"+qwait+"|SELECT|people|name|")
3332 // Call Next to test Issue 21117 and check for races.
3334 // Scan the buffer so it is read and checked for races.
3339 // This call will race with the context cancel rollback to complete
3340 // if the rollback itself isn't guarded.
3347 // TestIssue20160 attempts to test a short context life on a stmt Query.
3348 func TestIssue20160(t *testing.T) {
3349 db := newTestDB(t, "people")
3350 defer closeDB(t, db)
3352 ctx := context.Background()
3353 sem := make(chan bool, 20)
3354 var wg sync.WaitGroup
3356 const milliWait = 30
3358 stmt, err := db.PrepareContext(ctx, "SELECT|people|name|")
3364 for i := 0; i < 100; i++ {
3372 ctx, cancel := context.WithTimeout(ctx, time.Duration(rand.Intn(milliWait))*time.Millisecond)
3375 // This is expected to give a cancel error most, but not all the time.
3376 // Test failure will happen with a panic or other race condition being
3378 rows, _ := stmt.QueryContext(ctx)
3387 // TestIssue18719 closes the context right before use. The sql.driverConn
3388 // will nil out the ci on close in a lock, but if another process uses it right after
3389 // it will panic with on the nil ref.
3391 // See https://golang.org/cl/35550 .
3392 func TestIssue18719(t *testing.T) {
3393 db := newTestDB(t, "people")
3394 defer closeDB(t, db)
3396 ctx, cancel := context.WithCancel(context.Background())
3399 tx, err := db.BeginTx(ctx, nil)
3404 hookTxGrabConn = func() {
3407 // Wait for the context to cancel and tx to rollback.
3408 for tx.isDone() == false {
3409 time.Sleep(3 * time.Millisecond)
3412 defer func() { hookTxGrabConn = nil }()
3414 // This call will grab the connection and cancel the context
3415 // after it has done so. Code after must deal with the canceled state.
3416 _, err = tx.QueryContext(ctx, "SELECT|people|name|")
3418 t.Fatalf("expected error %v but got %v", nil, err)
3421 // Rows may be ignored because it will be closed when the context is canceled.
3423 // Do not explicitly rollback. The rollback will happen from the
3424 // canceled context.
3429 func TestIssue20647(t *testing.T) {
3430 db := newTestDB(t, "people")
3431 defer closeDB(t, db)
3433 ctx, cancel := context.WithCancel(context.Background())
3436 conn, err := db.Conn(ctx)
3440 conn.dc.ci.(*fakeConn).skipDirtySession = true
3443 stmt, err := conn.PrepareContext(ctx, "SELECT|people|name|")
3449 rows1, err := stmt.QueryContext(ctx)
3451 t.Fatal("rows1", err)
3455 rows2, err := stmt.QueryContext(ctx)
3457 t.Fatal("rows2", err)
3461 if rows1.dc != rows2.dc {
3462 t.Fatal("stmt prepared on Conn does not use same connection")
3466 func TestConcurrency(t *testing.T) {
3471 {"Query", new(concurrentDBQueryTest)},
3472 {"Exec", new(concurrentDBExecTest)},
3473 {"StmtQuery", new(concurrentStmtQueryTest)},
3474 {"StmtExec", new(concurrentStmtExecTest)},
3475 {"TxQuery", new(concurrentTxQueryTest)},
3476 {"TxExec", new(concurrentTxExecTest)},
3477 {"TxStmtQuery", new(concurrentTxStmtQueryTest)},
3478 {"TxStmtExec", new(concurrentTxStmtExecTest)},
3479 {"Random", new(concurrentRandomTest)},
3481 for _, item := range list {
3482 t.Run(item.name, func(t *testing.T) {
3483 doConcurrentTest(t, item.ct)
3488 func TestConnectionLeak(t *testing.T) {
3489 db := newTestDB(t, "people")
3490 defer closeDB(t, db)
3491 // Start by opening defaultMaxIdleConns
3492 rows := make([]*Rows, defaultMaxIdleConns)
3493 // We need to SetMaxOpenConns > MaxIdleConns, so the DB can open
3494 // a new connection and we can fill the idle queue with the released
3496 db.SetMaxOpenConns(len(rows) + 1)
3497 for ii := range rows {
3498 r, err := db.Query("SELECT|people|name|")
3503 if err := r.Err(); err != nil {
3508 // Now we have defaultMaxIdleConns busy connections. Open
3509 // a new one, but wait until the busy connections are released
3510 // before returning control to DB.
3511 drv := db.Driver().(*fakeDriver)
3512 drv.waitCh = make(chan struct{}, 1)
3513 drv.waitingCh = make(chan struct{}, 1)
3514 var wg sync.WaitGroup
3517 r, err := db.Query("SELECT|people|name|")
3525 // Wait until the goroutine we've just created has started waiting.
3527 // Now close the busy connections. This provides a connection for
3528 // the blocked goroutine and then fills up the idle queue.
3529 for _, v := range rows {
3532 // At this point we give the new connection to DB. This connection is
3533 // now useless, since the idle queue is full and there are no pending
3534 // requests. DB should deal with this situation without leaking the
3536 drv.waitCh <- struct{}{}
3540 func TestStatsMaxIdleClosedZero(t *testing.T) {
3541 db := newTestDB(t, "people")
3542 defer closeDB(t, db)
3544 db.SetMaxOpenConns(1)
3545 db.SetMaxIdleConns(1)
3546 db.SetConnMaxLifetime(0)
3548 preMaxIdleClosed := db.Stats().MaxIdleClosed
3550 for i := 0; i < 10; i++ {
3551 rows, err := db.Query("SELECT|people|name|")
3559 maxIdleClosed := st.MaxIdleClosed - preMaxIdleClosed
3560 t.Logf("MaxIdleClosed: %d", maxIdleClosed)
3561 if maxIdleClosed != 0 {
3562 t.Fatal("expected 0 max idle closed conns, got: ", maxIdleClosed)
3566 func TestStatsMaxIdleClosedTen(t *testing.T) {
3567 db := newTestDB(t, "people")
3568 defer closeDB(t, db)
3570 db.SetMaxOpenConns(1)
3571 db.SetMaxIdleConns(0)
3572 db.SetConnMaxLifetime(0)
3574 preMaxIdleClosed := db.Stats().MaxIdleClosed
3576 for i := 0; i < 10; i++ {
3577 rows, err := db.Query("SELECT|people|name|")
3585 maxIdleClosed := st.MaxIdleClosed - preMaxIdleClosed
3586 t.Logf("MaxIdleClosed: %d", maxIdleClosed)
3587 if maxIdleClosed != 10 {
3588 t.Fatal("expected 0 max idle closed conns, got: ", maxIdleClosed)
3592 type nvcDriver struct {
3594 skipNamedValueCheck bool
3597 func (d *nvcDriver) Open(dsn string) (driver.Conn, error) {
3598 c, err := d.fakeDriver.Open(dsn)
3600 fc.db.allowAny = true
3601 return &nvcConn{fc, d.skipNamedValueCheck}, err
3604 type nvcConn struct {
3606 skipNamedValueCheck bool
3609 type decimalInt struct {
3613 type doNotInclude struct{}
3615 var _ driver.NamedValueChecker = &nvcConn{}
3617 func (c *nvcConn) CheckNamedValue(nv *driver.NamedValue) error {
3618 if c.skipNamedValueCheck {
3619 return driver.ErrSkip
3621 switch v := nv.Value.(type) {
3623 return driver.ErrSkip
3625 switch ov := v.Dest.(type) {
3627 return errors.New("unknown NameValueCheck OUTPUT type")
3630 nv.Value = "OUT:*string"
3633 case decimalInt, []int64:
3636 return driver.ErrRemoveArgument
3640 func TestNamedValueChecker(t *testing.T) {
3641 Register("NamedValueCheck", &nvcDriver{})
3642 db, err := Open("NamedValueCheck", "")
3648 ctx, cancel := context.WithCancel(context.Background())
3651 _, err = db.ExecContext(ctx, "WIPE")
3653 t.Fatal("exec wipe", err)
3656 _, err = db.ExecContext(ctx, "CREATE|keys|dec1=any,str1=string,out1=string,array1=any")
3658 t.Fatal("exec create", err)
3662 _, err = db.ExecContext(ctx, "INSERT|keys|dec1=?A,str1=?,out1=?O1,array1=?", Named("A", decimalInt{123}), "hello", Named("O1", Out{Dest: &o1}), []int64{42, 128, 707}, doNotInclude{})
3664 t.Fatal("exec insert", err)
3671 err = db.QueryRowContext(ctx, "SELECT|keys|dec1,str1,array1|").Scan(&dec1, &str1, &arr1)
3673 t.Fatal("select", err)
3676 list := []struct{ got, want interface{} }{
3677 {o1, "from-server"},
3678 {dec1, decimalInt{123}},
3680 {arr1, []int64{42, 128, 707}},
3683 for index, item := range list {
3684 if !reflect.DeepEqual(item.got, item.want) {
3685 t.Errorf("got %#v wanted %#v for index %d", item.got, item.want, index)
3690 func TestNamedValueCheckerSkip(t *testing.T) {
3691 Register("NamedValueCheckSkip", &nvcDriver{skipNamedValueCheck: true})
3692 db, err := Open("NamedValueCheckSkip", "")
3698 ctx, cancel := context.WithCancel(context.Background())
3701 _, err = db.ExecContext(ctx, "WIPE")
3703 t.Fatal("exec wipe", err)
3706 _, err = db.ExecContext(ctx, "CREATE|keys|dec1=any")
3708 t.Fatal("exec create", err)
3711 _, err = db.ExecContext(ctx, "INSERT|keys|dec1=?A", Named("A", decimalInt{123}))
3713 t.Fatalf("expected error with bad argument, got %v", err)
3717 func TestOpenConnector(t *testing.T) {
3718 Register("testctx", &fakeDriverCtx{})
3719 db, err := Open("testctx", "people")
3725 if _, is := db.connector.(*fakeConnector); !is {
3726 t.Fatal("not using *fakeConnector")
3730 type ctxOnlyDriver struct {
3734 func (d *ctxOnlyDriver) Open(dsn string) (driver.Conn, error) {
3735 conn, err := d.fakeDriver.Open(dsn)
3739 return &ctxOnlyConn{fc: conn.(*fakeConn)}, nil
3743 _ driver.Conn = &ctxOnlyConn{}
3744 _ driver.QueryerContext = &ctxOnlyConn{}
3745 _ driver.ExecerContext = &ctxOnlyConn{}
3748 type ctxOnlyConn struct {
3755 func (c *ctxOnlyConn) Begin() (driver.Tx, error) {
3759 func (c *ctxOnlyConn) Close() error {
3763 // Prepare is still part of the Conn interface, so while it isn't used
3764 // must be defined for compatibility.
3765 func (c *ctxOnlyConn) Prepare(q string) (driver.Stmt, error) {
3769 func (c *ctxOnlyConn) PrepareContext(ctx context.Context, q string) (driver.Stmt, error) {
3770 return c.fc.PrepareContext(ctx, q)
3773 func (c *ctxOnlyConn) QueryContext(ctx context.Context, q string, args []driver.NamedValue) (driver.Rows, error) {
3774 c.queryCtxCalled = true
3775 return c.fc.QueryContext(ctx, q, args)
3778 func (c *ctxOnlyConn) ExecContext(ctx context.Context, q string, args []driver.NamedValue) (driver.Result, error) {
3779 c.execCtxCalled = true
3780 return c.fc.ExecContext(ctx, q, args)
3783 // TestQueryExecContextOnly ensures drivers only need to implement QueryContext
3784 // and ExecContext methods.
3785 func TestQueryExecContextOnly(t *testing.T) {
3786 // Ensure connection does not implment non-context interfaces.
3787 var connType driver.Conn = &ctxOnlyConn{}
3788 if _, ok := connType.(driver.Execer); ok {
3789 t.Fatalf("%T must not implement driver.Execer", connType)
3791 if _, ok := connType.(driver.Queryer); ok {
3792 t.Fatalf("%T must not implement driver.Queryer", connType)
3795 Register("ContextOnly", &ctxOnlyDriver{})
3796 db, err := Open("ContextOnly", "")
3802 ctx, cancel := context.WithCancel(context.Background())
3805 conn, err := db.Conn(ctx)
3807 t.Fatal("db.Conn", err)
3810 coc := conn.dc.ci.(*ctxOnlyConn)
3811 coc.fc.skipDirtySession = true
3813 _, err = conn.ExecContext(ctx, "WIPE")
3815 t.Fatal("exec wipe", err)
3818 _, err = conn.ExecContext(ctx, "CREATE|keys|v1=string")
3820 t.Fatal("exec create", err)
3822 expectedValue := "value1"
3823 _, err = conn.ExecContext(ctx, "INSERT|keys|v1=?", expectedValue)
3825 t.Fatal("exec insert", err)
3827 rows, err := conn.QueryContext(ctx, "SELECT|keys|v1|")
3829 t.Fatal("query select", err)
3833 err = rows.Scan(&v1)
3835 t.Fatal("rows scan", err)
3840 if v1 != expectedValue {
3841 t.Fatalf("expected %q, got %q", expectedValue, v1)
3844 if !coc.execCtxCalled {
3845 t.Error("ExecContext not called")
3847 if !coc.queryCtxCalled {
3848 t.Error("QueryContext not called")
3852 // badConn implements a bad driver.Conn, for TestBadDriver.
3853 // The Exec method panics.
3854 type badConn struct{}
3856 func (bc badConn) Prepare(query string) (driver.Stmt, error) {
3857 return nil, errors.New("badConn Prepare")
3860 func (bc badConn) Close() error {
3864 func (bc badConn) Begin() (driver.Tx, error) {
3865 return nil, errors.New("badConn Begin")
3868 func (bc badConn) Exec(query string, args []driver.Value) (driver.Result, error) {
3869 panic("badConn.Exec")
3872 // badDriver is a driver.Driver that uses badConn.
3873 type badDriver struct{}
3875 func (bd badDriver) Open(name string) (driver.Conn, error) {
3876 return badConn{}, nil
3880 func TestBadDriver(t *testing.T) {
3881 Register("bad", badDriver{})
3882 db, err := Open("bad", "ignored")
3887 if r := recover(); r == nil {
3888 t.Error("expected panic")
3890 if want := "badConn.Exec"; r.(string) != want {
3891 t.Errorf("panic was %v, expected %v", r, want)
3899 type pingDriver struct {
3903 type pingConn struct {
3908 var pingError = errors.New("Ping failed")
3910 func (pc pingConn) Ping(ctx context.Context) error {
3911 if pc.driver.fails {
3917 var _ driver.Pinger = pingConn{}
3919 func (pd *pingDriver) Open(name string) (driver.Conn, error) {
3920 return pingConn{driver: pd}, nil
3923 func TestPing(t *testing.T) {
3924 driver := &pingDriver{}
3925 Register("ping", driver)
3927 db, err := Open("ping", "ignored")
3932 if err := db.Ping(); err != nil {
3933 t.Errorf("err was %#v, expected nil", err)
3938 if err := db.Ping(); err != pingError {
3939 t.Errorf("err was %#v, expected pingError", err)
3944 func TestTypedString(t *testing.T) {
3945 db := newTestDB(t, "people")
3946 defer closeDB(t, db)
3951 err := db.QueryRow("SELECT|people|name|name=?", "Alice").Scan(&scanned)
3955 expected := Str("Alice")
3956 if scanned != expected {
3957 t.Errorf("expected %+v, got %+v", expected, scanned)
3961 func BenchmarkConcurrentDBExec(b *testing.B) {
3963 ct := new(concurrentDBExecTest)
3964 for i := 0; i < b.N; i++ {
3965 doConcurrentTest(b, ct)
3969 func BenchmarkConcurrentStmtQuery(b *testing.B) {
3971 ct := new(concurrentStmtQueryTest)
3972 for i := 0; i < b.N; i++ {
3973 doConcurrentTest(b, ct)
3977 func BenchmarkConcurrentStmtExec(b *testing.B) {
3979 ct := new(concurrentStmtExecTest)
3980 for i := 0; i < b.N; i++ {
3981 doConcurrentTest(b, ct)
3985 func BenchmarkConcurrentTxQuery(b *testing.B) {
3987 ct := new(concurrentTxQueryTest)
3988 for i := 0; i < b.N; i++ {
3989 doConcurrentTest(b, ct)
3993 func BenchmarkConcurrentTxExec(b *testing.B) {
3995 ct := new(concurrentTxExecTest)
3996 for i := 0; i < b.N; i++ {
3997 doConcurrentTest(b, ct)
4001 func BenchmarkConcurrentTxStmtQuery(b *testing.B) {
4003 ct := new(concurrentTxStmtQueryTest)
4004 for i := 0; i < b.N; i++ {
4005 doConcurrentTest(b, ct)
4009 func BenchmarkConcurrentTxStmtExec(b *testing.B) {
4011 ct := new(concurrentTxStmtExecTest)
4012 for i := 0; i < b.N; i++ {
4013 doConcurrentTest(b, ct)
4017 func BenchmarkConcurrentRandom(b *testing.B) {
4019 ct := new(concurrentRandomTest)
4020 for i := 0; i < b.N; i++ {
4021 doConcurrentTest(b, ct)
4025 func BenchmarkManyConcurrentQueries(b *testing.B) {
4027 // To see lock contention in Go 1.4, 16~ cores and 128~ goroutines are required.
4028 const parallelism = 16
4030 db := newTestDB(b, "magicquery")
4031 defer closeDB(b, db)
4032 db.SetMaxIdleConns(runtime.GOMAXPROCS(0) * parallelism)
4034 stmt, err := db.Prepare("SELECT|magicquery|op|op=?,millis=?")
4040 b.SetParallelism(parallelism)
4041 b.RunParallel(func(pb *testing.PB) {
4043 rows, err := stmt.Query("sleep", 1)