Source file src/database/sql/sql_test.go

     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.
     4  
     5  package sql
     6  
     7  import (
     8  	"bytes"
     9  	"context"
    10  	"database/sql/driver"
    11  	"errors"
    12  	"fmt"
    13  	"internal/race"
    14  	"internal/testenv"
    15  	"math/rand"
    16  	"reflect"
    17  	"runtime"
    18  	"slices"
    19  	"strings"
    20  	"sync"
    21  	"sync/atomic"
    22  	"testing"
    23  	"testing/synctest"
    24  	"time"
    25  	"uuid"
    26  )
    27  
    28  type requireFeature string
    29  
    30  // testDatabase executes f in a synctest bubble.
    31  //
    32  // It executes several subtests, each with a database driver supporting
    33  // a different set of optional interfaces (QueryerContext, etc.).
    34  //
    35  // Limit a test to drivers implementing a certain feature by passing
    36  // a requireFeature option. For example:
    37  //
    38  //	// testFunc only executes with drivers which implement Validator.
    39  //	testDatabase(t, testFunc, requireFeature("Validator"))
    40  func testDatabase(t *testing.T, f func(t *testing.T, db *DB), opts ...any) {
    41  	var require []string
    42  	for _, o := range opts {
    43  		switch o := o.(type) {
    44  		case requireFeature:
    45  			require = append(require, string(o))
    46  		default:
    47  			t.Fatalf("unrecognized option %T", o)
    48  		}
    49  	}
    50  Test:
    51  	for _, test := range []struct {
    52  		name      string
    53  		connector driver.Connector
    54  		features  []string
    55  	}{
    56  		{
    57  			// Basic driver supporting none of the optional driver interfaces.
    58  			name:      "basic",
    59  			connector: &basicConnector{name: fakeDBName},
    60  		},
    61  		{
    62  			// Default test driver. Supports some but not all features.
    63  			// This is the "default" because this is the only driver we used
    64  			// before adding testDatabase.
    65  			name:      "default",
    66  			connector: &fakeConnector{name: fakeDBName},
    67  			features: []string{
    68  				"ConnBeginTx",
    69  				"NamedValue",
    70  				"Validator",
    71  			},
    72  		},
    73  		{
    74  			name:      "scancols",
    75  			connector: &rowsColumnScannerConnector{name: fakeDBName},
    76  			features: []string{
    77  				"ConnBeginTx",
    78  				"NamedValue",
    79  				"Validator",
    80  				"ScanColumn",
    81  			},
    82  		},
    83  	} {
    84  		for _, req := range require {
    85  			if !slices.Contains(test.features, req) {
    86  				continue Test
    87  			}
    88  		}
    89  		t.Run(test.name, func(t *testing.T) {
    90  			synctest.Test(t, func(t *testing.T) {
    91  				db := OpenDB(test.connector)
    92  				if _, err := db.Exec("WIPE"); err != nil {
    93  					t.Fatalf("exec wipe: %v", err)
    94  				}
    95  				t.Cleanup(func() {
    96  					closeDB(t, db)
    97  				})
    98  				f(t, db)
    99  			})
   100  		})
   101  	}
   102  }
   103  
   104  func init() {
   105  	type dbConn struct {
   106  		db *DB
   107  		c  *driverConn
   108  	}
   109  	freedFrom := make(map[dbConn]string)
   110  	var mu sync.Mutex
   111  	getFreedFrom := func(c dbConn) string {
   112  		mu.Lock()
   113  		defer mu.Unlock()
   114  		return freedFrom[c]
   115  	}
   116  	setFreedFrom := func(c dbConn, s string) {
   117  		mu.Lock()
   118  		defer mu.Unlock()
   119  		freedFrom[c] = s
   120  	}
   121  	putConnHook = func(db *DB, c *driverConn) {
   122  		if slices.Contains(db.freeConn, c) {
   123  			// print before panic, as panic may get lost due to conflicting panic
   124  			// (all goroutines asleep) elsewhere, since we might not unlock
   125  			// the mutex in freeConn here.
   126  			println("double free of conn. conflicts are:\nA) " + getFreedFrom(dbConn{db, c}) + "\n\nand\nB) " + stack())
   127  			panic("double free of conn.")
   128  		}
   129  		setFreedFrom(dbConn{db, c}, stack())
   130  	}
   131  }
   132  
   133  const fakeDBName = "foo"
   134  
   135  var chrisBirthday = time.Unix(123456789, 0)
   136  
   137  func newTestDB(t testing.TB, name string) *DB {
   138  	return newTestDBConnector(t, &fakeConnector{name: fakeDBName}, name)
   139  }
   140  
   141  func newTestDBConnector(t testing.TB, fc *fakeConnector, name string) *DB {
   142  	fc.name = fakeDBName
   143  	db := OpenDB(fc)
   144  	if _, err := db.Exec("WIPE"); err != nil {
   145  		t.Fatalf("exec wipe: %v", err)
   146  	}
   147  	t.Cleanup(func() {
   148  		closeDB(t, db)
   149  	})
   150  	if name != "" {
   151  		populate(t, db, name)
   152  	}
   153  	return db
   154  }
   155  
   156  func populate(t testing.TB, db *DB, name string) {
   157  	t.Helper()
   158  	switch name {
   159  	case "people":
   160  		exec(t, db, "CREATE|people|name=string,age=int32,photo=blob,dead=bool,bdate=datetime")
   161  		exec(t, db, "INSERT|people|name=Alice,age=?,photo=APHOTO", 1)
   162  		exec(t, db, "INSERT|people|name=Bob,age=?,photo=BPHOTO", 2)
   163  		exec(t, db, "INSERT|people|name=Chris,age=?,photo=CPHOTO,bdate=?", 3, chrisBirthday)
   164  	case "magicquery":
   165  		// Magic table name and column, known by fakedb_test.go.
   166  		exec(t, db, "CREATE|magicquery|op=string,millis=int32")
   167  		exec(t, db, "INSERT|magicquery|op=sleep,millis=10")
   168  	case "tx_status":
   169  		// Magic table name and column, known by fakedb_test.go.
   170  		exec(t, db, "CREATE|tx_status|tx_status=string")
   171  		exec(t, db, "INSERT|tx_status|tx_status=invalid")
   172  	default:
   173  		t.Fatalf("unknown database name %q", name)
   174  	}
   175  }
   176  
   177  // basicConn implements only the bare minimum of the driver.Conn interface.
   178  type basicConn struct {
   179  	driver.Conn
   180  }
   181  
   182  func (c *basicConn) getFakeConn() *fakeConn {
   183  	return c.Conn.(*fakeConn)
   184  }
   185  
   186  func (c *basicConn) Prepare(query string) (driver.Stmt, error) {
   187  	stmt, err := c.Conn.(*fakeConn).PrepareContext(context.Background(), query)
   188  	if err != nil {
   189  		return nil, err
   190  	}
   191  	return &basicStmt{fc: c.Conn.(*fakeConn), Stmt: stmt}, nil
   192  }
   193  
   194  func (c *basicConn) Begin() (driver.Tx, error) {
   195  	return c.Conn.(*fakeConn).Begin()
   196  }
   197  
   198  func (c *basicConn) Close() error {
   199  	return c.Conn.(*fakeConn).Close()
   200  }
   201  
   202  type basicStmt struct {
   203  	fc *fakeConn
   204  	driver.Stmt
   205  }
   206  
   207  func (s *basicStmt) valuesToNamedValues(args []driver.Value) ([]driver.NamedValue, error) {
   208  	nv := make([]driver.NamedValue, len(args))
   209  	for i, arg := range args {
   210  		val, err := s.Stmt.(*fakeStmt).ColumnConverter(i).ConvertValue(arg)
   211  		if err != nil {
   212  			return nil, fmt.Errorf("sql: converting argument $%v type: %w", i+1, err)
   213  		}
   214  		nv[i] = driver.NamedValue{
   215  			Ordinal: i + 1,
   216  			Value:   val,
   217  		}
   218  	}
   219  	return nv, nil
   220  }
   221  
   222  func (s *basicStmt) Exec(args []driver.Value) (driver.Result, error) {
   223  	nvs, err := s.valuesToNamedValues(args)
   224  	if err != nil {
   225  		return nil, err
   226  	}
   227  	return s.Stmt.(*fakeStmt).ExecContext(context.Background(), nvs)
   228  }
   229  
   230  func (s *basicStmt) Query(args []driver.Value) (driver.Rows, error) {
   231  	nvs, err := s.valuesToNamedValues(args)
   232  	if err != nil {
   233  		return nil, err
   234  	}
   235  	return s.Stmt.(*fakeStmt).QueryContext(context.Background(), nvs)
   236  }
   237  
   238  type basicConnector struct {
   239  	fakeConnector
   240  }
   241  
   242  func (c *basicConnector) Connect(ctx context.Context) (driver.Conn, error) {
   243  	conn, err := c.fakeConnector.Connect(ctx)
   244  	if err != nil {
   245  		return nil, err
   246  	}
   247  	fc := getFakeConn(conn)
   248  	fc.skipDirtySession = true // Conn won't implement ResetSession
   249  	return &basicConn{fc}, nil
   250  }
   251  
   252  func TestOpenDB(t *testing.T) {
   253  	synctest.Test(t, testOpenDB)
   254  }
   255  func testOpenDB(t *testing.T) {
   256  	db := OpenDB(dsnConnector{dsn: fakeDBName, driver: fdriver})
   257  	defer db.Close()
   258  	if db.Driver() != fdriver {
   259  		t.Fatalf("OpenDB should return the driver of the Connector")
   260  	}
   261  }
   262  
   263  func TestDriverPanic(t *testing.T) {
   264  	synctest.Test(t, testDriverPanic)
   265  }
   266  func testDriverPanic(t *testing.T) {
   267  	db, err := Open("test", fakeDBName)
   268  	if err != nil {
   269  		t.Fatalf("Open: %v", err)
   270  	}
   271  	defer db.Close()
   272  	// Test that if driver panics, database/sql does not deadlock.
   273  	expectPanic := func(name string, f func()) {
   274  		defer func() {
   275  			err := recover()
   276  			if err == nil {
   277  				t.Fatalf("%s did not panic", name)
   278  			}
   279  		}()
   280  		f()
   281  	}
   282  
   283  	expectPanic("Exec Exec", func() { db.Exec("PANIC|Exec|WIPE") })
   284  	exec(t, db, "WIPE") // check not deadlocked
   285  	expectPanic("Exec NumInput", func() { db.Exec("PANIC|NumInput|WIPE") })
   286  	exec(t, db, "WIPE") // check not deadlocked
   287  	expectPanic("Exec Close", func() { db.Exec("PANIC|Close|WIPE") })
   288  	exec(t, db, "WIPE")             // check not deadlocked
   289  	exec(t, db, "PANIC|Query|WIPE") // should run successfully: Exec does not call Query
   290  	exec(t, db, "WIPE")             // check not deadlocked
   291  
   292  	exec(t, db, "CREATE|people|name=string,age=int32,photo=blob,dead=bool,bdate=datetime")
   293  
   294  	expectPanic("Query Query", func() { db.Query("PANIC|Query|SELECT|people|age,name|") })
   295  	expectPanic("Query NumInput", func() { db.Query("PANIC|NumInput|SELECT|people|age,name|") })
   296  	expectPanic("Query Close", func() {
   297  		rows, err := db.Query("PANIC|Close|SELECT|people|age,name|")
   298  		if err != nil {
   299  			t.Fatal(err)
   300  		}
   301  		rows.Close()
   302  	})
   303  	db.Query("PANIC|Exec|SELECT|people|age,name|") // should run successfully: Query does not call Exec
   304  	exec(t, db, "WIPE")                            // check not deadlocked
   305  }
   306  
   307  func exec(t testing.TB, db *DB, query string, args ...any) {
   308  	t.Helper()
   309  	_, err := db.Exec(query, args...)
   310  	if err != nil {
   311  		t.Fatalf("Exec of %q: %v", query, err)
   312  	}
   313  }
   314  
   315  func closeDB(t testing.TB, db *DB) {
   316  	t.Helper()
   317  
   318  	if e := recover(); e != nil {
   319  		fmt.Printf("Panic: %v\n", e)
   320  		panic(e)
   321  	}
   322  	defer setHookpostCloseConn(nil)
   323  	setHookpostCloseConn(func(_ *fakeConn, err error) {
   324  		if err != nil {
   325  			t.Errorf("Error closing fakeConn: %v", err)
   326  		}
   327  	})
   328  	db.mu.Lock()
   329  	for i, dc := range db.freeConn {
   330  		if n := len(dc.openStmt); n > 0 {
   331  			// Just a sanity check. This is legal in
   332  			// general, but if we make the tests clean up
   333  			// their statements first, then we can safely
   334  			// verify this is always zero here, and any
   335  			// other value is a leak.
   336  			t.Errorf("while closing db, freeConn %d/%d had %d open stmts; want 0", i, len(db.freeConn), n)
   337  		}
   338  	}
   339  	db.mu.Unlock()
   340  
   341  	err := db.Close()
   342  	if err != nil {
   343  		t.Fatalf("error closing DB: %v", err)
   344  	}
   345  
   346  	// Connections close asynchronously; wait for them to finish doing so.
   347  	numOpenConns := func() int {
   348  		db.mu.Lock()
   349  		defer db.mu.Unlock()
   350  		return db.numOpen
   351  	}
   352  	if _, ok := t.(*testing.B); ok {
   353  		// We don't use synctest in benchmarks, so just poll.
   354  		deadline := time.Now().Add(5 * time.Second)
   355  		for numOpenConns() > 0 && time.Now().Before(deadline) {
   356  			time.Sleep(1 * time.Millisecond)
   357  		}
   358  	} else {
   359  		synctest.Wait()
   360  	}
   361  	if numOpen := numOpenConns(); numOpen != 0 {
   362  		t.Fatalf("%d connections still open after closing DB", numOpen)
   363  	}
   364  }
   365  
   366  // numPrepares assumes that db has exactly 1 idle conn and returns
   367  // its count of calls to Prepare
   368  func numPrepares(t *testing.T, db *DB) int {
   369  	if n := len(db.freeConn); n != 1 {
   370  		t.Fatalf("free conns = %d; want 1", n)
   371  	}
   372  	return getFakeConn(db.freeConn[0].ci).numPrepare
   373  }
   374  
   375  func (db *DB) numDeps() int {
   376  	synctest.Wait()
   377  	db.mu.Lock()
   378  	defer db.mu.Unlock()
   379  	return len(db.dep)
   380  }
   381  
   382  func (db *DB) numFreeConns() int {
   383  	synctest.Wait()
   384  	db.mu.Lock()
   385  	defer db.mu.Unlock()
   386  	return len(db.freeConn)
   387  }
   388  
   389  // clearAllConns closes all connections in db.
   390  func (db *DB) clearAllConns(t *testing.T) {
   391  	db.SetMaxIdleConns(0)
   392  
   393  	if g, w := db.numFreeConns(), 0; g != w {
   394  		t.Errorf("free conns = %d; want %d", g, w)
   395  	}
   396  
   397  	if n := db.numDeps(); n > 0 {
   398  		t.Errorf("number of dependencies = %d; expected 0", n)
   399  		db.dumpDeps(t)
   400  	}
   401  }
   402  
   403  func (db *DB) dumpDeps(t *testing.T) {
   404  	for fc := range db.dep {
   405  		db.dumpDep(t, 0, fc, map[finalCloser]bool{})
   406  	}
   407  }
   408  
   409  func (db *DB) dumpDep(t *testing.T, depth int, dep finalCloser, seen map[finalCloser]bool) {
   410  	seen[dep] = true
   411  	indent := strings.Repeat("  ", depth)
   412  	ds := db.dep[dep]
   413  	for k := range ds {
   414  		t.Logf("%s%T (%p) waiting for -> %T (%p)", indent, dep, dep, k, k)
   415  		if fc, ok := k.(finalCloser); ok {
   416  			if !seen[fc] {
   417  				db.dumpDep(t, depth+1, fc, seen)
   418  			}
   419  		}
   420  	}
   421  }
   422  
   423  func TestQuery(t *testing.T) {
   424  	testDatabase(t, testQuery)
   425  }
   426  func testQuery(t *testing.T, db *DB) {
   427  	populate(t, db, "people")
   428  	prepares0 := numPrepares(t, db)
   429  	rows, err := db.Query("SELECT|people|age,name|")
   430  	if err != nil {
   431  		t.Fatalf("Query: %v", err)
   432  	}
   433  	defer rows.Close()
   434  	type row struct {
   435  		age  int
   436  		name string
   437  	}
   438  	got := []row{}
   439  	for rows.Next() {
   440  		var r row
   441  		err = rows.Scan(&r.age, &r.name)
   442  		if err != nil {
   443  			t.Fatalf("Scan: %v", err)
   444  		}
   445  		got = append(got, r)
   446  	}
   447  	err = rows.Err()
   448  	if err != nil {
   449  		t.Fatalf("Err: %v", err)
   450  	}
   451  	want := []row{
   452  		{age: 1, name: "Alice"},
   453  		{age: 2, name: "Bob"},
   454  		{age: 3, name: "Chris"},
   455  	}
   456  	if !slices.Equal(got, want) {
   457  		t.Errorf("mismatch.\n got: %#v\nwant: %#v", got, want)
   458  	}
   459  
   460  	// And verify that the final rows.Next() call, which hit EOF,
   461  	// also closed the rows connection.
   462  	if n := db.numFreeConns(); n != 1 {
   463  		t.Fatalf("free conns after query hitting EOF = %d; want 1", n)
   464  	}
   465  	if prepares := numPrepares(t, db) - prepares0; prepares != 1 {
   466  		t.Errorf("executed %d Prepare statements; want 1", prepares)
   467  	}
   468  }
   469  
   470  // TestQueryContext tests canceling the context while scanning the rows.
   471  func TestQueryContext(t *testing.T) {
   472  	testDatabase(t, testQueryContext)
   473  }
   474  func testQueryContext(t *testing.T, db *DB) {
   475  	populate(t, db, "people")
   476  	prepares0 := numPrepares(t, db)
   477  
   478  	ctx, cancel := context.WithCancel(context.Background())
   479  	defer cancel()
   480  
   481  	rows, err := db.QueryContext(ctx, "SELECT|people|age,name|")
   482  	if err != nil {
   483  		t.Fatalf("Query: %v", err)
   484  	}
   485  	type row struct {
   486  		age  int
   487  		name string
   488  	}
   489  	got := []row{}
   490  	index := 0
   491  	for rows.Next() {
   492  		if index == 2 {
   493  			cancel()
   494  			waitForRowsClose(t, rows)
   495  		}
   496  		var r row
   497  		err = rows.Scan(&r.age, &r.name)
   498  		if err != nil {
   499  			if index == 2 {
   500  				break
   501  			}
   502  			t.Fatalf("Scan: %v", err)
   503  		}
   504  		if index == 2 && err != context.Canceled {
   505  			t.Fatalf("Scan: %v; want context.Canceled", err)
   506  		}
   507  		got = append(got, r)
   508  		index++
   509  	}
   510  	select {
   511  	case <-ctx.Done():
   512  		if err := ctx.Err(); err != context.Canceled {
   513  			t.Fatalf("context err = %v; want context.Canceled", err)
   514  		}
   515  	default:
   516  		t.Fatalf("context err = nil; want context.Canceled")
   517  	}
   518  	want := []row{
   519  		{age: 1, name: "Alice"},
   520  		{age: 2, name: "Bob"},
   521  	}
   522  	if !slices.Equal(got, want) {
   523  		t.Errorf("mismatch.\n got: %#v\nwant: %#v", got, want)
   524  	}
   525  
   526  	// And verify that the final rows.Next() call, which hit EOF,
   527  	// also closed the rows connection.
   528  	waitForRowsClose(t, rows)
   529  	waitForFree(t, db, 1)
   530  	if prepares := numPrepares(t, db) - prepares0; prepares != 1 {
   531  		t.Errorf("executed %d Prepare statements; want 1", prepares)
   532  	}
   533  }
   534  
   535  // waitForFree checks db.numFreeConns until either it equals want or
   536  // the maxWait time elapses.
   537  func waitForFree(t *testing.T, db *DB, want int) {
   538  	synctest.Wait()
   539  	numFree := db.numFreeConns()
   540  	if numFree != want {
   541  		t.Fatalf("free conns after hitting EOF = %d; want %d", numFree, want)
   542  	}
   543  }
   544  
   545  func waitForRowsClose(t *testing.T, rows *Rows) {
   546  	synctest.Wait()
   547  	rows.closemu.RLock()
   548  	defer rows.closemu.RUnlock()
   549  	if !rows.closed {
   550  		t.Fatal("failed to close rows")
   551  	}
   552  }
   553  
   554  // TestQueryContextWait ensures that rows and all internal statements are closed when
   555  // a query context is closed during execution.
   556  func TestQueryContextWait(t *testing.T) {
   557  	testDatabase(t, testQueryContextWait)
   558  }
   559  func testQueryContextWait(t *testing.T, db *DB) {
   560  	populate(t, db, "people")
   561  	prepares0 := numPrepares(t, db)
   562  
   563  	ctx, cancel := context.WithCancel(context.Background())
   564  	defer cancel()
   565  
   566  	// This will trigger the *fakeConn.Prepare method which will take time
   567  	// performing the query. The ctxDriverPrepare func will check the context
   568  	// after this and close the rows and return an error.
   569  	c, err := db.Conn(ctx)
   570  	if err != nil {
   571  		t.Fatal(err)
   572  	}
   573  
   574  	getFakeConn(c.dc.ci).waiter = func(c context.Context) {
   575  		cancel()
   576  		<-ctx.Done()
   577  	}
   578  	_, err = c.QueryContext(ctx, "SELECT|people|age,name|")
   579  	c.Close()
   580  	if err != context.Canceled {
   581  		t.Fatalf("expected QueryContext to error with context deadline exceeded but returned %v", err)
   582  	}
   583  
   584  	// Verify closed rows connection after error condition.
   585  	waitForFree(t, db, 1)
   586  	if prepares := numPrepares(t, db) - prepares0; prepares != 1 {
   587  		t.Fatalf("executed %d Prepare statements; want 1", prepares)
   588  	}
   589  }
   590  
   591  // TestTxContextWait tests the transaction behavior when the tx context is canceled
   592  // during execution of the query.
   593  func TestTxContextWait(t *testing.T) {
   594  	testDatabase(t, func(t *testing.T, db *DB) {
   595  		testContextWait(t, false, db)
   596  	})
   597  }
   598  
   599  // TestTxContextWaitNoDiscard is the same as TestTxContextWait, but should not discard
   600  // the final connection.
   601  func TestTxContextWaitNoDiscard(t *testing.T) {
   602  	testDatabase(t, func(t *testing.T, db *DB) {
   603  		testContextWait(t, true, db)
   604  	})
   605  }
   606  
   607  func testContextWait(t *testing.T, keepConnOnRollback bool, db *DB) {
   608  	populate(t, db, "people")
   609  
   610  	ctx, cancel := context.WithCancel(context.Background())
   611  
   612  	tx, err := db.BeginTx(ctx, nil)
   613  	if err != nil {
   614  		t.Fatal(err)
   615  	}
   616  	tx.keepConnOnRollback = keepConnOnRollback
   617  
   618  	getFakeConn(tx.dc.ci).waiter = func(c context.Context) {
   619  		cancel()
   620  		<-ctx.Done()
   621  	}
   622  	// This will trigger the *fakeConn.Prepare method which will take time
   623  	// performing the query. The ctxDriverPrepare func will check the context
   624  	// after this and close the rows and return an error.
   625  	_, err = tx.QueryContext(ctx, "SELECT|people|age,name|")
   626  	if err != context.Canceled {
   627  		t.Fatalf("expected QueryContext to error with context canceled but returned %v", err)
   628  	}
   629  
   630  	if keepConnOnRollback {
   631  		waitForFree(t, db, 1)
   632  	} else {
   633  		waitForFree(t, db, 0)
   634  	}
   635  }
   636  
   637  // TestUnsupportedOptions checks that the database fails when a driver that
   638  // doesn't implement ConnBeginTx is used with non-default options and an
   639  // un-cancellable context.
   640  func TestUnsupportedOptions(t *testing.T) {
   641  	testDatabase(t, testUnsupportedOptions)
   642  }
   643  func testUnsupportedOptions(t *testing.T, db *DB) {
   644  	populate(t, db, "people")
   645  	_, err := db.BeginTx(context.Background(), &TxOptions{
   646  		Isolation: LevelSerializable, ReadOnly: true,
   647  	})
   648  	if err == nil {
   649  		t.Fatal("expected error when using unsupported options, got nil")
   650  	}
   651  }
   652  
   653  func TestMultiResultSetQuery(t *testing.T) {
   654  	testDatabase(t, testMultiResultSetQuery)
   655  }
   656  func testMultiResultSetQuery(t *testing.T, db *DB) {
   657  	populate(t, db, "people")
   658  	prepares0 := numPrepares(t, db)
   659  	rows, err := db.Query("SELECT|people|age,name|;SELECT|people|name|")
   660  	if err != nil {
   661  		t.Fatalf("Query: %v", err)
   662  	}
   663  	type row1 struct {
   664  		age  int
   665  		name string
   666  	}
   667  	type row2 struct {
   668  		name string
   669  	}
   670  	got1 := []row1{}
   671  	for rows.Next() {
   672  		var r row1
   673  		err = rows.Scan(&r.age, &r.name)
   674  		if err != nil {
   675  			t.Fatalf("Scan: %v", err)
   676  		}
   677  		got1 = append(got1, r)
   678  	}
   679  	err = rows.Err()
   680  	if err != nil {
   681  		t.Fatalf("Err: %v", err)
   682  	}
   683  	want1 := []row1{
   684  		{age: 1, name: "Alice"},
   685  		{age: 2, name: "Bob"},
   686  		{age: 3, name: "Chris"},
   687  	}
   688  	if !slices.Equal(got1, want1) {
   689  		t.Errorf("mismatch.\n got1: %#v\nwant: %#v", got1, want1)
   690  	}
   691  
   692  	if !rows.NextResultSet() {
   693  		t.Errorf("expected another result set")
   694  	}
   695  
   696  	got2 := []row2{}
   697  	for rows.Next() {
   698  		var r row2
   699  		err = rows.Scan(&r.name)
   700  		if err != nil {
   701  			t.Fatalf("Scan: %v", err)
   702  		}
   703  		got2 = append(got2, r)
   704  	}
   705  	err = rows.Err()
   706  	if err != nil {
   707  		t.Fatalf("Err: %v", err)
   708  	}
   709  	want2 := []row2{
   710  		{name: "Alice"},
   711  		{name: "Bob"},
   712  		{name: "Chris"},
   713  	}
   714  	if !slices.Equal(got2, want2) {
   715  		t.Errorf("mismatch.\n got: %#v\nwant: %#v", got2, want2)
   716  	}
   717  	if rows.NextResultSet() {
   718  		t.Errorf("expected no more result sets")
   719  	}
   720  
   721  	// And verify that the final rows.Next() call, which hit EOF,
   722  	// also closed the rows connection.
   723  	waitForFree(t, db, 1)
   724  	if prepares := numPrepares(t, db) - prepares0; prepares != 1 {
   725  		t.Errorf("executed %d Prepare statements; want 1", prepares)
   726  	}
   727  }
   728  
   729  func TestQueryNamedArg(t *testing.T) {
   730  	testDatabase(t, testQueryNamedArg, requireFeature("NamedValue"))
   731  }
   732  func testQueryNamedArg(t *testing.T, db *DB) {
   733  	populate(t, db, "people")
   734  	prepares0 := numPrepares(t, db)
   735  	rows, err := db.Query(
   736  		// Ensure the name and age parameters only match on placeholder name, not position.
   737  		"SELECT|people|age,name|name=?name,age=?age",
   738  		Named("age", 2),
   739  		Named("name", "Bob"),
   740  	)
   741  	if err != nil {
   742  		t.Fatalf("Query: %v", err)
   743  	}
   744  	type row struct {
   745  		age  int
   746  		name string
   747  	}
   748  	got := []row{}
   749  	for rows.Next() {
   750  		var r row
   751  		err = rows.Scan(&r.age, &r.name)
   752  		if err != nil {
   753  			t.Fatalf("Scan: %v", err)
   754  		}
   755  		got = append(got, r)
   756  	}
   757  	err = rows.Err()
   758  	if err != nil {
   759  		t.Fatalf("Err: %v", err)
   760  	}
   761  	want := []row{
   762  		{age: 2, name: "Bob"},
   763  	}
   764  	if !slices.Equal(got, want) {
   765  		t.Errorf("mismatch.\n got: %#v\nwant: %#v", got, want)
   766  	}
   767  
   768  	// And verify that the final rows.Next() call, which hit EOF,
   769  	// also closed the rows connection.
   770  	if n := db.numFreeConns(); n != 1 {
   771  		t.Fatalf("free conns after query hitting EOF = %d; want 1", n)
   772  	}
   773  	if prepares := numPrepares(t, db) - prepares0; prepares != 1 {
   774  		t.Errorf("executed %d Prepare statements; want 1", prepares)
   775  	}
   776  }
   777  
   778  func TestPoolExhaustOnCancel(t *testing.T) {
   779  	synctest.Test(t, testPoolExhaustOnCancel)
   780  }
   781  func testPoolExhaustOnCancel(t *testing.T) {
   782  	max := 3
   783  	var saturate, saturateDone sync.WaitGroup
   784  	saturate.Add(max)
   785  	saturateDone.Add(max)
   786  
   787  	donePing := make(chan bool)
   788  	state := 0
   789  
   790  	// waiter will be called for all queries, including
   791  	// initial setup queries. The state is only assigned when
   792  	// no queries are made.
   793  	//
   794  	// Only allow the first batch of queries to finish once the
   795  	// second batch of Ping queries have finished.
   796  	waiter := func(ctx context.Context) {
   797  		switch state {
   798  		case 0:
   799  			// Nothing. Initial database setup.
   800  		case 1:
   801  			saturate.Done()
   802  			select {
   803  			case <-ctx.Done():
   804  			case <-donePing:
   805  			}
   806  		case 2:
   807  		}
   808  	}
   809  	db := newTestDBConnector(t, &fakeConnector{waiter: waiter}, "people")
   810  
   811  	db.SetMaxOpenConns(max)
   812  
   813  	// First saturate the connection pool.
   814  	// Then start new requests for a connection that is canceled after it is requested.
   815  
   816  	state = 1
   817  	for i := 0; i < max; i++ {
   818  		go func() {
   819  			rows, err := db.Query("SELECT|people|name,photo|")
   820  			if err != nil {
   821  				t.Errorf("Query: %v", err)
   822  				return
   823  			}
   824  			rows.Close()
   825  			saturateDone.Done()
   826  		}()
   827  	}
   828  
   829  	saturate.Wait()
   830  	if t.Failed() {
   831  		t.FailNow()
   832  	}
   833  	state = 2
   834  
   835  	// Now cancel the request while it is waiting.
   836  	ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
   837  	defer cancel()
   838  
   839  	for i := 0; i < max; i++ {
   840  		ctxReq, cancelReq := context.WithCancel(ctx)
   841  		go func() {
   842  			time.Sleep(100 * time.Millisecond)
   843  			cancelReq()
   844  		}()
   845  		err := db.PingContext(ctxReq)
   846  		if err != context.Canceled {
   847  			t.Fatalf("PingContext (Exhaust): %v", err)
   848  		}
   849  	}
   850  	close(donePing)
   851  	saturateDone.Wait()
   852  
   853  	// Now try to open a normal connection.
   854  	err := db.PingContext(ctx)
   855  	if err != nil {
   856  		t.Fatalf("PingContext (Normal): %v", err)
   857  	}
   858  }
   859  
   860  func TestRowsColumns(t *testing.T) {
   861  	testDatabase(t, testRowsColumns)
   862  }
   863  func testRowsColumns(t *testing.T, db *DB) {
   864  	populate(t, db, "people")
   865  	rows, err := db.Query("SELECT|people|age,name|")
   866  	if err != nil {
   867  		t.Fatalf("Query: %v", err)
   868  	}
   869  	cols, err := rows.Columns()
   870  	if err != nil {
   871  		t.Fatalf("Columns: %v", err)
   872  	}
   873  	want := []string{"age", "name"}
   874  	if !slices.Equal(cols, want) {
   875  		t.Errorf("got %#v; want %#v", cols, want)
   876  	}
   877  	if err := rows.Close(); err != nil {
   878  		t.Errorf("error closing rows: %s", err)
   879  	}
   880  }
   881  
   882  func TestRowsColumnTypes(t *testing.T) {
   883  	testDatabase(t, testRowsColumnTypes)
   884  }
   885  func testRowsColumnTypes(t *testing.T, db *DB) {
   886  	populate(t, db, "people")
   887  	rows, err := db.Query("SELECT|people|age,name|")
   888  	if err != nil {
   889  		t.Fatalf("Query: %v", err)
   890  	}
   891  	tt, err := rows.ColumnTypes()
   892  	if err != nil {
   893  		t.Fatalf("ColumnTypes: %v", err)
   894  	}
   895  
   896  	types := make([]reflect.Type, len(tt))
   897  	for i, tp := range tt {
   898  		st := tp.ScanType()
   899  		if st == nil {
   900  			t.Errorf("scantype is null for column %q", tp.Name())
   901  			continue
   902  		}
   903  		types[i] = st
   904  	}
   905  	values := make([]any, len(tt))
   906  	for i := range values {
   907  		values[i] = reflect.New(types[i]).Interface()
   908  	}
   909  	ct := 0
   910  	for rows.Next() {
   911  		err = rows.Scan(values...)
   912  		if err != nil {
   913  			t.Fatalf("failed to scan values in %v", err)
   914  		}
   915  		if ct == 1 {
   916  			if age := *values[0].(*int32); age != 2 {
   917  				t.Errorf("Expected 2, got %v", age)
   918  			}
   919  			if name := *values[1].(*string); name != "Bob" {
   920  				t.Errorf("Expected Bob, got %v", name)
   921  			}
   922  		}
   923  		ct++
   924  	}
   925  	if ct != 3 {
   926  		t.Errorf("expected 3 rows, got %d", ct)
   927  	}
   928  
   929  	if err := rows.Close(); err != nil {
   930  		t.Errorf("error closing rows: %s", err)
   931  	}
   932  }
   933  
   934  func TestQueryRow(t *testing.T) {
   935  	testDatabase(t, testQueryRow)
   936  }
   937  func testQueryRow(t *testing.T, db *DB) {
   938  	populate(t, db, "people")
   939  	var name string
   940  	var age int
   941  	var birthday time.Time
   942  
   943  	err := db.QueryRow("SELECT|people|age,name|age=?", 3).Scan(&age)
   944  	if err == nil || !strings.Contains(err.Error(), "expected 2 destination arguments") {
   945  		t.Errorf("expected error from wrong number of arguments; actually got: %v", err)
   946  	}
   947  
   948  	err = db.QueryRow("SELECT|people|bdate|age=?", 3).Scan(&birthday)
   949  	if err != nil || !birthday.Equal(chrisBirthday) {
   950  		t.Errorf("chris birthday = %v, err = %v; want %v", birthday, err, chrisBirthday)
   951  	}
   952  
   953  	err = db.QueryRow("SELECT|people|age,name|age=?", 2).Scan(&age, &name)
   954  	if err != nil {
   955  		t.Fatalf("age QueryRow+Scan: %v", err)
   956  	}
   957  	if name != "Bob" {
   958  		t.Errorf("expected name Bob, got %q", name)
   959  	}
   960  	if age != 2 {
   961  		t.Errorf("expected age 2, got %d", age)
   962  	}
   963  
   964  	err = db.QueryRow("SELECT|people|age,name|name=?", "Alice").Scan(&age, &name)
   965  	if err != nil {
   966  		t.Fatalf("name QueryRow+Scan: %v", err)
   967  	}
   968  	if name != "Alice" {
   969  		t.Errorf("expected name Alice, got %q", name)
   970  	}
   971  	if age != 1 {
   972  		t.Errorf("expected age 1, got %d", age)
   973  	}
   974  
   975  	var photo []byte
   976  	err = db.QueryRow("SELECT|people|photo|name=?", "Alice").Scan(&photo)
   977  	if err != nil {
   978  		t.Fatalf("photo QueryRow+Scan: %v", err)
   979  	}
   980  	want := []byte("APHOTO")
   981  	if !slices.Equal(photo, want) {
   982  		t.Errorf("photo = %q; want %q", photo, want)
   983  	}
   984  }
   985  
   986  func TestRowErr(t *testing.T) {
   987  	testDatabase(t, testRowErr)
   988  }
   989  func testRowErr(t *testing.T, db *DB) {
   990  	populate(t, db, "people")
   991  
   992  	row := db.QueryRowContext(context.Background(), "SELECT|people|bdate|age=?", 3)
   993  	if err := row.Err(); err != nil {
   994  		t.Errorf("Unexpected err = %v; want %v", err, nil)
   995  	}
   996  	row.Scan()
   997  
   998  	ctx, cancel := context.WithCancel(context.Background())
   999  	cancel()
  1000  
  1001  	err := db.QueryRowContext(ctx, "SELECT|people|bdate|age=?", 3).Err()
  1002  	exp := "context canceled"
  1003  	if err == nil || !strings.Contains(err.Error(), exp) {
  1004  		t.Errorf("Expected err = %v; got %v", exp, err)
  1005  	}
  1006  }
  1007  
  1008  func TestTxRollbackCommitErr(t *testing.T) {
  1009  	testDatabase(t, testTxRollbackCommitErr)
  1010  }
  1011  func testTxRollbackCommitErr(t *testing.T, db *DB) {
  1012  	populate(t, db, "people")
  1013  
  1014  	tx, err := db.Begin()
  1015  	if err != nil {
  1016  		t.Fatal(err)
  1017  	}
  1018  	err = tx.Rollback()
  1019  	if err != nil {
  1020  		t.Errorf("expected nil error from Rollback; got %v", err)
  1021  	}
  1022  	err = tx.Commit()
  1023  	if err != ErrTxDone {
  1024  		t.Errorf("expected %q from Commit; got %q", ErrTxDone, err)
  1025  	}
  1026  
  1027  	tx, err = db.Begin()
  1028  	if err != nil {
  1029  		t.Fatal(err)
  1030  	}
  1031  	err = tx.Commit()
  1032  	if err != nil {
  1033  		t.Errorf("expected nil error from Commit; got %v", err)
  1034  	}
  1035  	err = tx.Rollback()
  1036  	if err != ErrTxDone {
  1037  		t.Errorf("expected %q from Rollback; got %q", ErrTxDone, err)
  1038  	}
  1039  }
  1040  
  1041  func TestStatementErrorAfterClose(t *testing.T) {
  1042  	testDatabase(t, testStatementErrorAfterClose)
  1043  }
  1044  func testStatementErrorAfterClose(t *testing.T, db *DB) {
  1045  	populate(t, db, "people")
  1046  	stmt, err := db.Prepare("SELECT|people|age|name=?")
  1047  	if err != nil {
  1048  		t.Fatalf("Prepare: %v", err)
  1049  	}
  1050  	err = stmt.Close()
  1051  	if err != nil {
  1052  		t.Fatalf("Close: %v", err)
  1053  	}
  1054  	var name string
  1055  	err = stmt.QueryRow("foo").Scan(&name)
  1056  	if err == nil {
  1057  		t.Errorf("expected error from QueryRow.Scan after Stmt.Close")
  1058  	}
  1059  }
  1060  
  1061  func TestStatementQueryRow(t *testing.T) {
  1062  	testDatabase(t, testStatementQueryRow)
  1063  }
  1064  func testStatementQueryRow(t *testing.T, db *DB) {
  1065  	populate(t, db, "people")
  1066  	stmt, err := db.Prepare("SELECT|people|age|name=?")
  1067  	if err != nil {
  1068  		t.Fatalf("Prepare: %v", err)
  1069  	}
  1070  	defer stmt.Close()
  1071  	var age int
  1072  	for n, tt := range []struct {
  1073  		name string
  1074  		want int
  1075  	}{
  1076  		{"Alice", 1},
  1077  		{"Bob", 2},
  1078  		{"Chris", 3},
  1079  	} {
  1080  		if err := stmt.QueryRow(tt.name).Scan(&age); err != nil {
  1081  			t.Errorf("%d: on %q, QueryRow/Scan: %v", n, tt.name, err)
  1082  		} else if age != tt.want {
  1083  			t.Errorf("%d: age=%d, want %d", n, age, tt.want)
  1084  		}
  1085  	}
  1086  }
  1087  
  1088  type stubDriverStmt struct {
  1089  	err error
  1090  }
  1091  
  1092  func (s stubDriverStmt) Close() error {
  1093  	return s.err
  1094  }
  1095  
  1096  func (s stubDriverStmt) NumInput() int {
  1097  	return -1
  1098  }
  1099  
  1100  func (s stubDriverStmt) Exec(args []driver.Value) (driver.Result, error) {
  1101  	return nil, nil
  1102  }
  1103  
  1104  func (s stubDriverStmt) Query(args []driver.Value) (driver.Rows, error) {
  1105  	return nil, nil
  1106  }
  1107  
  1108  // golang.org/issue/12798
  1109  func TestStatementClose(t *testing.T) {
  1110  	synctest.Test(t, testStatementClose)
  1111  }
  1112  func testStatementClose(t *testing.T) {
  1113  	want := errors.New("STMT ERROR")
  1114  
  1115  	tests := []struct {
  1116  		stmt *Stmt
  1117  		msg  string
  1118  	}{
  1119  		{&Stmt{stickyErr: want}, "stickyErr not propagated"},
  1120  		{&Stmt{cg: &Tx{}, cgds: &driverStmt{Locker: &sync.Mutex{}, si: stubDriverStmt{want}}}, "driverStmt.Close() error not propagated"},
  1121  	}
  1122  	for _, test := range tests {
  1123  		if err := test.stmt.Close(); err != want {
  1124  			t.Errorf("%s. Got stmt.Close() = %v, want = %v", test.msg, err, want)
  1125  		}
  1126  	}
  1127  }
  1128  
  1129  // golang.org/issue/3734
  1130  func TestStatementQueryRowConcurrent(t *testing.T) {
  1131  	testDatabase(t, testStatementQueryRowConcurrent)
  1132  }
  1133  func testStatementQueryRowConcurrent(t *testing.T, db *DB) {
  1134  	populate(t, db, "people")
  1135  	stmt, err := db.Prepare("SELECT|people|age|name=?")
  1136  	if err != nil {
  1137  		t.Fatalf("Prepare: %v", err)
  1138  	}
  1139  	defer stmt.Close()
  1140  
  1141  	const n = 10
  1142  	ch := make(chan error, n)
  1143  	for i := 0; i < n; i++ {
  1144  		go func() {
  1145  			var age int
  1146  			err := stmt.QueryRow("Alice").Scan(&age)
  1147  			if err == nil && age != 1 {
  1148  				err = fmt.Errorf("unexpected age %d", age)
  1149  			}
  1150  			ch <- err
  1151  		}()
  1152  	}
  1153  	for i := 0; i < n; i++ {
  1154  		if err := <-ch; err != nil {
  1155  			t.Error(err)
  1156  		}
  1157  	}
  1158  }
  1159  
  1160  // just a test of fakedb itself
  1161  func TestBogusPreboundParameters(t *testing.T) {
  1162  	testDatabase(t, testBogusPreboundParameters)
  1163  }
  1164  func testBogusPreboundParameters(t *testing.T, db *DB) {
  1165  	exec(t, db, "CREATE|t1|name=string,age=int32,dead=bool")
  1166  	_, err := db.Prepare("INSERT|t1|name=?,age=bogusconversion")
  1167  	if err == nil {
  1168  		t.Fatalf("expected error")
  1169  	}
  1170  	if err.Error() != `fakedb: invalid conversion to int32 from "bogusconversion"` {
  1171  		t.Errorf("unexpected error: %v", err)
  1172  	}
  1173  }
  1174  
  1175  func TestExec(t *testing.T) {
  1176  	testDatabase(t, testExec)
  1177  }
  1178  func testExec(t *testing.T, db *DB) {
  1179  	exec(t, db, "CREATE|t1|name=string,age=int32,dead=bool")
  1180  	stmt, err := db.Prepare("INSERT|t1|name=?,age=?")
  1181  	if err != nil {
  1182  		t.Errorf("Stmt, err = %v, %v", stmt, err)
  1183  	}
  1184  	defer stmt.Close()
  1185  
  1186  	type execTest struct {
  1187  		args    []any
  1188  		wantErr string
  1189  	}
  1190  	execTests := []execTest{
  1191  		// Okay:
  1192  		{[]any{"Brad", 31}, ""},
  1193  		{[]any{"Brad", int64(31)}, ""},
  1194  		{[]any{"Bob", "32"}, ""},
  1195  		{[]any{7, 9}, ""},
  1196  
  1197  		// Invalid conversions:
  1198  		{[]any{"Brad", int64(0xFFFFFFFF)}, "sql: converting argument $2 type: sql/driver: value 4294967295 overflows int32"},
  1199  		{[]any{"Brad", "strconv fail"}, `sql: converting argument $2 type: sql/driver: value "strconv fail" can't be converted to int32`},
  1200  
  1201  		// Wrong number of args:
  1202  		{[]any{}, "sql: expected 2 arguments, got 0"},
  1203  		{[]any{1, 2, 3}, "sql: expected 2 arguments, got 3"},
  1204  	}
  1205  	for n, et := range execTests {
  1206  		_, err := stmt.Exec(et.args...)
  1207  		errStr := ""
  1208  		if err != nil {
  1209  			errStr = err.Error()
  1210  		}
  1211  		if errStr != et.wantErr {
  1212  			t.Errorf("stmt.Execute #%d: for %v, got error %q, want error %q",
  1213  				n, et.args, errStr, et.wantErr)
  1214  		}
  1215  	}
  1216  }
  1217  
  1218  func TestTxPrepare(t *testing.T) {
  1219  	testDatabase(t, testTxPrepare)
  1220  }
  1221  func testTxPrepare(t *testing.T, db *DB) {
  1222  	exec(t, db, "CREATE|t1|name=string,age=int32,dead=bool")
  1223  	tx, err := db.Begin()
  1224  	if err != nil {
  1225  		t.Fatalf("Begin = %v", err)
  1226  	}
  1227  	stmt, err := tx.Prepare("INSERT|t1|name=?,age=?")
  1228  	if err != nil {
  1229  		t.Fatalf("Stmt, err = %v, %v", stmt, err)
  1230  	}
  1231  	defer stmt.Close()
  1232  	_, err = stmt.Exec("Bobby", 7)
  1233  	if err != nil {
  1234  		t.Fatalf("Exec = %v", err)
  1235  	}
  1236  	err = tx.Commit()
  1237  	if err != nil {
  1238  		t.Fatalf("Commit = %v", err)
  1239  	}
  1240  	// Commit() should have closed the statement
  1241  	if !stmt.closed {
  1242  		t.Fatal("Stmt not closed after Commit")
  1243  	}
  1244  }
  1245  
  1246  func TestTxStmt(t *testing.T) {
  1247  	testDatabase(t, testTxStmt)
  1248  }
  1249  func testTxStmt(t *testing.T, db *DB) {
  1250  	exec(t, db, "CREATE|t1|name=string,age=int32,dead=bool")
  1251  	stmt, err := db.Prepare("INSERT|t1|name=?,age=?")
  1252  	if err != nil {
  1253  		t.Fatalf("Stmt, err = %v, %v", stmt, err)
  1254  	}
  1255  	defer stmt.Close()
  1256  	tx, err := db.Begin()
  1257  	if err != nil {
  1258  		t.Fatalf("Begin = %v", err)
  1259  	}
  1260  	txs := tx.Stmt(stmt)
  1261  	defer txs.Close()
  1262  	_, err = txs.Exec("Bobby", 7)
  1263  	if err != nil {
  1264  		t.Fatalf("Exec = %v", err)
  1265  	}
  1266  	err = tx.Commit()
  1267  	if err != nil {
  1268  		t.Fatalf("Commit = %v", err)
  1269  	}
  1270  	// Commit() should have closed the statement
  1271  	if !txs.closed {
  1272  		t.Fatal("Stmt not closed after Commit")
  1273  	}
  1274  }
  1275  
  1276  func TestTxStmtPreparedOnce(t *testing.T) {
  1277  	testDatabase(t, testTxStmtPreparedOnce)
  1278  }
  1279  func testTxStmtPreparedOnce(t *testing.T, db *DB) {
  1280  	exec(t, db, "CREATE|t1|name=string,age=int32")
  1281  
  1282  	prepares0 := numPrepares(t, db)
  1283  
  1284  	// db.Prepare increments numPrepares.
  1285  	stmt, err := db.Prepare("INSERT|t1|name=?,age=?")
  1286  	if err != nil {
  1287  		t.Fatalf("Stmt, err = %v, %v", stmt, err)
  1288  	}
  1289  	defer stmt.Close()
  1290  
  1291  	tx, err := db.Begin()
  1292  	if err != nil {
  1293  		t.Fatalf("Begin = %v", err)
  1294  	}
  1295  
  1296  	txs1 := tx.Stmt(stmt)
  1297  	txs2 := tx.Stmt(stmt)
  1298  
  1299  	_, err = txs1.Exec("Go", 7)
  1300  	if err != nil {
  1301  		t.Fatalf("Exec = %v", err)
  1302  	}
  1303  	txs1.Close()
  1304  
  1305  	_, err = txs2.Exec("Gopher", 8)
  1306  	if err != nil {
  1307  		t.Fatalf("Exec = %v", err)
  1308  	}
  1309  	txs2.Close()
  1310  
  1311  	err = tx.Commit()
  1312  	if err != nil {
  1313  		t.Fatalf("Commit = %v", err)
  1314  	}
  1315  
  1316  	if prepares := numPrepares(t, db) - prepares0; prepares != 1 {
  1317  		t.Errorf("executed %d Prepare statements; want 1", prepares)
  1318  	}
  1319  }
  1320  
  1321  func TestTxStmtClosedRePrepares(t *testing.T) {
  1322  	testDatabase(t, testTxStmtClosedRePrepares)
  1323  }
  1324  func testTxStmtClosedRePrepares(t *testing.T, db *DB) {
  1325  	exec(t, db, "CREATE|t1|name=string,age=int32")
  1326  
  1327  	prepares0 := numPrepares(t, db)
  1328  
  1329  	// db.Prepare increments numPrepares.
  1330  	stmt, err := db.Prepare("INSERT|t1|name=?,age=?")
  1331  	if err != nil {
  1332  		t.Fatalf("Stmt, err = %v, %v", stmt, err)
  1333  	}
  1334  	tx, err := db.Begin()
  1335  	if err != nil {
  1336  		t.Fatalf("Begin = %v", err)
  1337  	}
  1338  	err = stmt.Close()
  1339  	if err != nil {
  1340  		t.Fatalf("stmt.Close() = %v", err)
  1341  	}
  1342  	// tx.Stmt increments numPrepares because stmt is closed.
  1343  	txs := tx.Stmt(stmt)
  1344  	if txs.stickyErr != nil {
  1345  		t.Fatal(txs.stickyErr)
  1346  	}
  1347  	if txs.parentStmt != nil {
  1348  		t.Fatal("expected nil parentStmt")
  1349  	}
  1350  	_, err = txs.Exec(`Eric`, 82)
  1351  	if err != nil {
  1352  		t.Fatalf("txs.Exec = %v", err)
  1353  	}
  1354  
  1355  	err = txs.Close()
  1356  	if err != nil {
  1357  		t.Fatalf("txs.Close = %v", err)
  1358  	}
  1359  
  1360  	tx.Rollback()
  1361  
  1362  	if prepares := numPrepares(t, db) - prepares0; prepares != 2 {
  1363  		t.Errorf("executed %d Prepare statements; want 2", prepares)
  1364  	}
  1365  }
  1366  
  1367  func TestParentStmtOutlivesTxStmt(t *testing.T) {
  1368  	testDatabase(t, testParentStmtOutlivesTxStmt)
  1369  }
  1370  func testParentStmtOutlivesTxStmt(t *testing.T, db *DB) {
  1371  	exec(t, db, "CREATE|t1|name=string,age=int32")
  1372  
  1373  	// Make sure everything happens on the same connection.
  1374  	db.SetMaxOpenConns(1)
  1375  
  1376  	prepares0 := numPrepares(t, db)
  1377  
  1378  	// db.Prepare increments numPrepares.
  1379  	stmt, err := db.Prepare("INSERT|t1|name=?,age=?")
  1380  	if err != nil {
  1381  		t.Fatalf("Stmt, err = %v, %v", stmt, err)
  1382  	}
  1383  	defer stmt.Close()
  1384  	tx, err := db.Begin()
  1385  	if err != nil {
  1386  		t.Fatalf("Begin = %v", err)
  1387  	}
  1388  	txs := tx.Stmt(stmt)
  1389  	if len(stmt.css) != 1 {
  1390  		t.Fatalf("len(stmt.css) = %v; want 1", len(stmt.css))
  1391  	}
  1392  	err = txs.Close()
  1393  	if err != nil {
  1394  		t.Fatalf("txs.Close() = %v", err)
  1395  	}
  1396  	err = tx.Rollback()
  1397  	if err != nil {
  1398  		t.Fatalf("tx.Rollback() = %v", err)
  1399  	}
  1400  	// txs must not be valid.
  1401  	_, err = txs.Exec("Suzan", 30)
  1402  	if err == nil {
  1403  		t.Fatalf("txs.Exec(), expected err")
  1404  	}
  1405  	// Stmt must still be valid.
  1406  	_, err = stmt.Exec("Janina", 25)
  1407  	if err != nil {
  1408  		t.Fatalf("stmt.Exec() = %v", err)
  1409  	}
  1410  
  1411  	if prepares := numPrepares(t, db) - prepares0; prepares != 1 {
  1412  		t.Errorf("executed %d Prepare statements; want 1", prepares)
  1413  	}
  1414  }
  1415  
  1416  // Test that tx.Stmt called with a statement already
  1417  // associated with tx as argument re-prepares the same
  1418  // statement again.
  1419  func TestTxStmtFromTxStmtRePrepares(t *testing.T) {
  1420  	testDatabase(t, testTxStmtFromTxStmtRePrepares)
  1421  }
  1422  func testTxStmtFromTxStmtRePrepares(t *testing.T, db *DB) {
  1423  	exec(t, db, "CREATE|t1|name=string,age=int32")
  1424  	prepares0 := numPrepares(t, db)
  1425  	// db.Prepare increments numPrepares.
  1426  	stmt, err := db.Prepare("INSERT|t1|name=?,age=?")
  1427  	if err != nil {
  1428  		t.Fatalf("Stmt, err = %v, %v", stmt, err)
  1429  	}
  1430  	defer stmt.Close()
  1431  
  1432  	tx, err := db.Begin()
  1433  	if err != nil {
  1434  		t.Fatalf("Begin = %v", err)
  1435  	}
  1436  	txs1 := tx.Stmt(stmt)
  1437  
  1438  	// tx.Stmt(txs1) increments numPrepares because txs1 already
  1439  	// belongs to a transaction (albeit the same transaction).
  1440  	txs2 := tx.Stmt(txs1)
  1441  	if txs2.stickyErr != nil {
  1442  		t.Fatal(txs2.stickyErr)
  1443  	}
  1444  	if txs2.parentStmt != nil {
  1445  		t.Fatal("expected nil parentStmt")
  1446  	}
  1447  	_, err = txs2.Exec(`Eric`, 82)
  1448  	if err != nil {
  1449  		t.Fatal(err)
  1450  	}
  1451  
  1452  	err = txs1.Close()
  1453  	if err != nil {
  1454  		t.Fatalf("txs1.Close = %v", err)
  1455  	}
  1456  	err = txs2.Close()
  1457  	if err != nil {
  1458  		t.Fatalf("txs1.Close = %v", err)
  1459  	}
  1460  	err = tx.Rollback()
  1461  	if err != nil {
  1462  		t.Fatalf("tx.Rollback = %v", err)
  1463  	}
  1464  
  1465  	if prepares := numPrepares(t, db) - prepares0; prepares != 2 {
  1466  		t.Errorf("executed %d Prepare statements; want 2", prepares)
  1467  	}
  1468  }
  1469  
  1470  // Issue: https://golang.org/issue/2784
  1471  // This test didn't fail before because we got lucky with the fakedb driver.
  1472  // It was failing, and now not, in github.com/bradfitz/go-sql-test
  1473  func TestTxQuery(t *testing.T) {
  1474  	testDatabase(t, testTxQuery)
  1475  }
  1476  func testTxQuery(t *testing.T, db *DB) {
  1477  	exec(t, db, "CREATE|t1|name=string,age=int32,dead=bool")
  1478  	exec(t, db, "INSERT|t1|name=Alice")
  1479  
  1480  	tx, err := db.Begin()
  1481  	if err != nil {
  1482  		t.Fatal(err)
  1483  	}
  1484  	defer tx.Rollback()
  1485  
  1486  	r, err := tx.Query("SELECT|t1|name|")
  1487  	if err != nil {
  1488  		t.Fatal(err)
  1489  	}
  1490  	defer r.Close()
  1491  
  1492  	if !r.Next() {
  1493  		if r.Err() != nil {
  1494  			t.Fatal(r.Err())
  1495  		}
  1496  		t.Fatal("expected one row")
  1497  	}
  1498  
  1499  	var x string
  1500  	err = r.Scan(&x)
  1501  	if err != nil {
  1502  		t.Fatal(err)
  1503  	}
  1504  }
  1505  
  1506  func TestTxQueryInvalid(t *testing.T) {
  1507  	testDatabase(t, testTxQueryInvalid)
  1508  }
  1509  func testTxQueryInvalid(t *testing.T, db *DB) {
  1510  	defer closeDB(t, db)
  1511  
  1512  	tx, err := db.Begin()
  1513  	if err != nil {
  1514  		t.Fatal(err)
  1515  	}
  1516  	defer tx.Rollback()
  1517  
  1518  	_, err = tx.Query("SELECT|t1|name|")
  1519  	if err == nil {
  1520  		t.Fatal("Error expected")
  1521  	}
  1522  }
  1523  
  1524  // Tests fix for issue 4433, that retries in Begin happen when
  1525  // conn.Begin() returns ErrBadConn
  1526  func TestTxErrBadConn(t *testing.T) {
  1527  	synctest.Test(t, testTxErrBadConn)
  1528  }
  1529  func testTxErrBadConn(t *testing.T) {
  1530  	db, err := Open("test", fakeDBName+";badConn")
  1531  	if err != nil {
  1532  		t.Fatalf("Open: %v", err)
  1533  	}
  1534  	if _, err := db.Exec("WIPE"); err != nil {
  1535  		t.Fatalf("exec wipe: %v", err)
  1536  	}
  1537  	defer closeDB(t, db)
  1538  	exec(t, db, "CREATE|t1|name=string,age=int32,dead=bool")
  1539  	stmt, err := db.Prepare("INSERT|t1|name=?,age=?")
  1540  	if err != nil {
  1541  		t.Fatalf("Stmt, err = %v, %v", stmt, err)
  1542  	}
  1543  	defer stmt.Close()
  1544  	tx, err := db.Begin()
  1545  	if err != nil {
  1546  		t.Fatalf("Begin = %v", err)
  1547  	}
  1548  	txs := tx.Stmt(stmt)
  1549  	defer txs.Close()
  1550  	_, err = txs.Exec("Bobby", 7)
  1551  	if err != nil {
  1552  		t.Fatalf("Exec = %v", err)
  1553  	}
  1554  	err = tx.Commit()
  1555  	if err != nil {
  1556  		t.Fatalf("Commit = %v", err)
  1557  	}
  1558  }
  1559  
  1560  func TestConnQuery(t *testing.T) {
  1561  	testDatabase(t, testConnQuery)
  1562  }
  1563  func testConnQuery(t *testing.T, db *DB) {
  1564  	populate(t, db, "people")
  1565  
  1566  	ctx := t.Context()
  1567  	conn, err := db.Conn(ctx)
  1568  	if err != nil {
  1569  		t.Fatal(err)
  1570  	}
  1571  	getFakeConn(conn.dc.ci).skipDirtySession = true
  1572  	defer conn.Close()
  1573  
  1574  	var name string
  1575  	err = conn.QueryRowContext(ctx, "SELECT|people|name|age=?", 3).Scan(&name)
  1576  	if err != nil {
  1577  		t.Fatal(err)
  1578  	}
  1579  	if name != "Chris" {
  1580  		t.Fatalf("unexpected result, got %q want Chris", name)
  1581  	}
  1582  
  1583  	err = conn.PingContext(ctx)
  1584  	if err != nil {
  1585  		t.Fatal(err)
  1586  	}
  1587  }
  1588  
  1589  func TestConnRaw(t *testing.T) {
  1590  	testDatabase(t, testConnRaw)
  1591  }
  1592  func testConnRaw(t *testing.T, db *DB) {
  1593  	populate(t, db, "people")
  1594  
  1595  	ctx := t.Context()
  1596  	conn, err := db.Conn(ctx)
  1597  	if err != nil {
  1598  		t.Fatal(err)
  1599  	}
  1600  	getFakeConn(conn.dc.ci).skipDirtySession = true
  1601  	defer conn.Close()
  1602  
  1603  	sawFunc := false
  1604  	err = conn.Raw(func(dc any) error {
  1605  		sawFunc = true
  1606  		_ = getFakeConn(dc.(driver.Conn))
  1607  		return nil
  1608  	})
  1609  	if err != nil {
  1610  		t.Fatal(err)
  1611  	}
  1612  	if !sawFunc {
  1613  		t.Fatal("Raw func not called")
  1614  	}
  1615  
  1616  	func() {
  1617  		defer func() {
  1618  			x := recover()
  1619  			if x == nil {
  1620  				t.Fatal("expected panic")
  1621  			}
  1622  			conn.mu.Lock()
  1623  			closed := conn.closed && conn.numRefs == 0
  1624  			conn.mu.Unlock()
  1625  			if !closed {
  1626  				t.Fatal("expected connection to be closed after panic")
  1627  			}
  1628  		}()
  1629  		err = conn.Raw(func(dc any) error {
  1630  			panic("Conn.Raw panic should return an error")
  1631  		})
  1632  		t.Fatal("expected panic from Raw func")
  1633  	}()
  1634  }
  1635  
  1636  // TestConnCloseConcurrentOperation races Conn.Close with an operation on
  1637  // the Conn. The operation must either run normally or fail with ErrConnDone.
  1638  func TestConnCloseConcurrentOperation(t *testing.T) {
  1639  	testDatabase(t, testConnCloseConcurrentOperation)
  1640  }
  1641  func testConnCloseConcurrentOperation(t *testing.T, db *DB) {
  1642  	ctx := t.Context()
  1643  	for range 1000 {
  1644  		conn, err := db.Conn(ctx)
  1645  		if err != nil {
  1646  			t.Fatal(err)
  1647  		}
  1648  		closeErr := make(chan error)
  1649  		go func() {
  1650  			closeErr <- conn.Close()
  1651  		}()
  1652  		runtime.Gosched() // let Close overlap with Raw
  1653  		err = conn.Raw(func(any) error { return nil })
  1654  		if err != nil && err != ErrConnDone {
  1655  			t.Fatalf("Raw = %v, want nil or ErrConnDone", err)
  1656  		}
  1657  		if err := <-closeErr; err != nil {
  1658  			t.Fatalf("Close = %v", err)
  1659  		}
  1660  	}
  1661  }
  1662  
  1663  // TestConnCloseWaitsForOperations verifies that Conn.Close waits for running
  1664  // operations, and that operations started after Close fail without waiting.
  1665  func TestConnCloseWaitsForOperations(t *testing.T) {
  1666  	testDatabase(t, testConnCloseWaitsForOperations)
  1667  }
  1668  func testConnCloseWaitsForOperations(t *testing.T, db *DB) {
  1669  	ctx := t.Context()
  1670  	conn, err := db.Conn(ctx)
  1671  	if err != nil {
  1672  		t.Fatal(err)
  1673  	}
  1674  
  1675  	unblock := make(chan struct{})
  1676  	rawErr := make(chan error)
  1677  	go func() {
  1678  		rawErr <- conn.Raw(func(any) error {
  1679  			<-unblock
  1680  			return nil
  1681  		})
  1682  	}()
  1683  	synctest.Wait()
  1684  
  1685  	closeErr := make(chan error)
  1686  	go func() {
  1687  		closeErr <- conn.Close()
  1688  	}()
  1689  	synctest.Wait()
  1690  	select {
  1691  	case err := <-closeErr:
  1692  		t.Fatalf("Close = %v before running Raw returned", err)
  1693  	default:
  1694  	}
  1695  
  1696  	if err := conn.PingContext(ctx); err != ErrConnDone {
  1697  		t.Errorf("PingContext during Close = %v, want ErrConnDone", err)
  1698  	}
  1699  	if err := conn.Raw(func(any) error { return nil }); err != ErrConnDone {
  1700  		t.Errorf("Raw during Close = %v, want ErrConnDone", err)
  1701  	}
  1702  
  1703  	close(unblock)
  1704  	if err := <-rawErr; err != nil {
  1705  		t.Errorf("Raw = %v", err)
  1706  	}
  1707  	if err := <-closeErr; err != nil {
  1708  		t.Errorf("Close = %v", err)
  1709  	}
  1710  	if st := db.Stats(); st.InUse != 0 || st.Idle != 1 {
  1711  		t.Errorf("after Close: %d in use, %d idle; want 0, 1", st.InUse, st.Idle)
  1712  	}
  1713  }
  1714  
  1715  // TestConnOperationDuringRelease verifies that operations on a closed Conn
  1716  // fail without waiting for the connection to be returned to the pool,
  1717  // which may call into the driver.
  1718  func TestConnOperationDuringRelease(t *testing.T) {
  1719  	testDatabase(t, testConnOperationDuringRelease)
  1720  }
  1721  func testConnOperationDuringRelease(t *testing.T, db *DB) {
  1722  	ctx := t.Context()
  1723  	conn, err := db.Conn(ctx)
  1724  	if err != nil {
  1725  		t.Fatal(err)
  1726  	}
  1727  
  1728  	inPut := make(chan struct{})
  1729  	unblock := make(chan struct{})
  1730  	origHook := putConnHook
  1731  	defer func() { putConnHook = origHook }()
  1732  	putConnHook = func(db *DB, dc *driverConn) {
  1733  		origHook(db, dc)
  1734  		close(inPut)
  1735  		<-unblock
  1736  	}
  1737  
  1738  	closeErr := make(chan error)
  1739  	go func() {
  1740  		closeErr <- conn.Close()
  1741  	}()
  1742  	<-inPut
  1743  
  1744  	pingErr := make(chan error, 1)
  1745  	go func() {
  1746  		pingErr <- conn.PingContext(ctx)
  1747  	}()
  1748  	synctest.Wait()
  1749  	select {
  1750  	case err := <-pingErr:
  1751  		if err != ErrConnDone {
  1752  			t.Errorf("PingContext = %v, want ErrConnDone", err)
  1753  		}
  1754  	default:
  1755  		t.Errorf("PingContext blocked while Close returned the connection to the pool")
  1756  	}
  1757  
  1758  	close(unblock)
  1759  	if err := <-closeErr; err != nil {
  1760  		t.Errorf("Close = %v", err)
  1761  	}
  1762  }
  1763  
  1764  // TestConnBadConnDuringClose verifies that a connection reported bad by an
  1765  // operation running concurrently with Conn.Close is discarded rather than
  1766  // returned to the pool.
  1767  func TestConnBadConnDuringClose(t *testing.T) {
  1768  	testDatabase(t, testConnBadConnDuringClose)
  1769  }
  1770  func testConnBadConnDuringClose(t *testing.T, db *DB) {
  1771  	conn, err := db.Conn(t.Context())
  1772  	if err != nil {
  1773  		t.Fatal(err)
  1774  	}
  1775  
  1776  	unblock := make(chan struct{})
  1777  	rawErr := make(chan error)
  1778  	go func() {
  1779  		rawErr <- conn.Raw(func(any) error {
  1780  			<-unblock
  1781  			return driver.ErrBadConn
  1782  		})
  1783  	}()
  1784  	synctest.Wait()
  1785  
  1786  	closeErr := make(chan error)
  1787  	go func() {
  1788  		closeErr <- conn.Close()
  1789  	}()
  1790  	synctest.Wait() // Close is waiting for Raw.
  1791  
  1792  	close(unblock)
  1793  	if err := <-rawErr; !errors.Is(err, driver.ErrBadConn) {
  1794  		t.Errorf("Raw = %v, want driver.ErrBadConn", err)
  1795  	}
  1796  	if err := <-closeErr; err != nil {
  1797  		t.Errorf("Close = %v", err)
  1798  	}
  1799  	if st := db.Stats(); st.OpenConnections != 0 || st.Idle != 0 {
  1800  		t.Errorf("after bad connection: %d open, %d idle; want 0, 0", st.OpenConnections, st.Idle)
  1801  	}
  1802  }
  1803  
  1804  // TestConnBadConnWithOpenRows verifies that an operation reporting
  1805  // driver.ErrBadConn while Rows from the same Conn are open does not
  1806  // deadlock, and that the connection is discarded once the Rows are closed.
  1807  func TestConnBadConnWithOpenRows(t *testing.T) {
  1808  	testDatabase(t, testConnBadConnWithOpenRows)
  1809  }
  1810  func testConnBadConnWithOpenRows(t *testing.T, db *DB) {
  1811  	populate(t, db, "people")
  1812  	ctx := t.Context()
  1813  	conn, err := db.Conn(ctx)
  1814  	if err != nil {
  1815  		t.Fatal(err)
  1816  	}
  1817  	rows, err := conn.QueryContext(ctx, "SELECT|people|name|")
  1818  	if err != nil {
  1819  		t.Fatal(err)
  1820  	}
  1821  
  1822  	hookExecBadConn = func() bool { return true }
  1823  	_, err = conn.ExecContext(ctx, "INSERT|people|name=Dan,age=?", 4)
  1824  	hookExecBadConn = nil
  1825  	if !errors.Is(err, driver.ErrBadConn) {
  1826  		t.Errorf("ExecContext = %v, want driver.ErrBadConn", err)
  1827  	}
  1828  	if err := conn.PingContext(ctx); err != ErrConnDone {
  1829  		t.Errorf("PingContext after bad connection = %v, want ErrConnDone", err)
  1830  	}
  1831  
  1832  	// The open Rows keep using the connection until they are closed.
  1833  	n := 0
  1834  	for rows.Next() {
  1835  		n++
  1836  	}
  1837  	if err := rows.Close(); err != nil {
  1838  		t.Errorf("rows.Close = %v", err)
  1839  	}
  1840  	if n != 3 {
  1841  		t.Errorf("read %d rows, want 3", n)
  1842  	}
  1843  	if err := conn.Close(); err != ErrConnDone {
  1844  		t.Errorf("Close = %v, want ErrConnDone", err)
  1845  	}
  1846  	if st := db.Stats(); st.OpenConnections != 0 {
  1847  		t.Errorf("after bad connection: %d open, want 0", st.OpenConnections)
  1848  	}
  1849  }
  1850  
  1851  func TestCursorFake(t *testing.T) {
  1852  	testDatabase(t, testCursorFake)
  1853  }
  1854  func testCursorFake(t *testing.T, db *DB) {
  1855  	populate(t, db, "people")
  1856  
  1857  	ctx, cancel := context.WithTimeout(context.Background(), time.Second*30)
  1858  	defer cancel()
  1859  
  1860  	exec(t, db, "CREATE|peoplecursor|list=table")
  1861  	exec(t, db, "INSERT|peoplecursor|list=people!name!age")
  1862  
  1863  	rows, err := db.QueryContext(ctx, `SELECT|peoplecursor|list|`)
  1864  	if err != nil {
  1865  		t.Fatal(err)
  1866  	}
  1867  	defer rows.Close()
  1868  
  1869  	if !rows.Next() {
  1870  		t.Fatal("no rows")
  1871  	}
  1872  	var cursor = &Rows{}
  1873  	err = rows.Scan(cursor)
  1874  	if err != nil {
  1875  		t.Fatal(err)
  1876  	}
  1877  	defer cursor.Close()
  1878  
  1879  	const expectedRows = 3
  1880  	var currentRow int64
  1881  
  1882  	var n int64
  1883  	var s string
  1884  	for cursor.Next() {
  1885  		currentRow++
  1886  		err = cursor.Scan(&s, &n)
  1887  		if err != nil {
  1888  			t.Fatal(err)
  1889  		}
  1890  		if n != currentRow {
  1891  			t.Errorf("expected number(Age)=%d, got %d", currentRow, n)
  1892  		}
  1893  	}
  1894  	if currentRow != expectedRows {
  1895  		t.Errorf("expected %d rows, got %d rows", expectedRows, currentRow)
  1896  	}
  1897  }
  1898  
  1899  func TestCursorDoubleRowsPointer(t *testing.T) {
  1900  	testDatabase(t, testCursorDoubleRowsPointer)
  1901  }
  1902  func testCursorDoubleRowsPointer(t *testing.T, db *DB) {
  1903  	exec(t, db, "CREATE|table1|col=string")
  1904  	exec(t, db, "INSERT|table1|col=value")
  1905  	exec(t, db, "CREATE|cursor|list=table")
  1906  	exec(t, db, "INSERT|cursor|list=table1!col")
  1907  
  1908  	rows, err := db.QueryContext(t.Context(), `SELECT|cursor|list|`)
  1909  	if err != nil {
  1910  		t.Fatal(err)
  1911  	}
  1912  	defer rows.Close()
  1913  
  1914  	if !rows.Next() {
  1915  		t.Fatal("no rows")
  1916  	}
  1917  	var cursor *Rows
  1918  	if err := rows.Scan(&cursor); err != nil {
  1919  		t.Fatal(err)
  1920  	}
  1921  	defer cursor.Close()
  1922  
  1923  	if !cursor.Next() {
  1924  		t.Fatal("no child rows")
  1925  	}
  1926  	var col string
  1927  	if err := cursor.Scan(&col); err != nil {
  1928  		t.Fatal(err)
  1929  	}
  1930  	if got, want := col, "value"; got != want {
  1931  		t.Errorf("read col=%q, want %q", got, want)
  1932  	}
  1933  }
  1934  
  1935  func TestCursorNull(t *testing.T) {
  1936  	testDatabase(t, testCursorNull)
  1937  }
  1938  func testCursorNull(t *testing.T, db *DB) {
  1939  	exec(t, db, "CREATE|cursor|list=nulltable")
  1940  	exec(t, db, "INSERT|cursor|list=?", nil)
  1941  
  1942  	rows, err := db.QueryContext(t.Context(), `SELECT|cursor|list|`)
  1943  	if err != nil {
  1944  		t.Fatal(err)
  1945  	}
  1946  	defer rows.Close()
  1947  
  1948  	if !rows.Next() {
  1949  		t.Fatal("no rows")
  1950  	}
  1951  
  1952  	var cursor *Rows
  1953  	if err := rows.Scan(&cursor); err != nil {
  1954  		t.Fatal(err)
  1955  	}
  1956  	if cursor != nil {
  1957  		t.Errorf("Scan returned cursor, expected nil")
  1958  	}
  1959  }
  1960  
  1961  // TestCursorCancel exercises calling Rows.Close at various places,
  1962  // including canceling a cursor (child Rows).
  1963  func TestCursorCancel(t *testing.T) {
  1964  	for _, test := range []struct {
  1965  		name     string
  1966  		cancelOn string
  1967  		want     []string
  1968  	}{{
  1969  		// don't cancel
  1970  		name: "no cancel",
  1971  		want: []string{
  1972  			"table1",
  1973  			"1.1",
  1974  			"1.2",
  1975  			"table2",
  1976  			"2.1",
  1977  			"2.2",
  1978  		},
  1979  	}, {
  1980  		name:     "outer cancel",
  1981  		cancelOn: "table2",
  1982  		want: []string{
  1983  			"table1",
  1984  			"1.1",
  1985  			"1.2",
  1986  			"table2",
  1987  		},
  1988  	}, {
  1989  		name:     "inner cancel",
  1990  		cancelOn: "1.1",
  1991  		want: []string{
  1992  			"table1",
  1993  			"1.1",
  1994  			"table2",
  1995  			"2.1",
  1996  			"2.2",
  1997  		},
  1998  	}} {
  1999  		t.Run(test.name, func(t *testing.T) {
  2000  			testDatabase(t, func(t *testing.T, db *DB) {
  2001  				testCursorCancel(t, db, test.cancelOn, test.want)
  2002  			})
  2003  		})
  2004  	}
  2005  }
  2006  func testCursorCancel(t *testing.T, db *DB, cancelOn string, want []string) {
  2007  	exec(t, db, "CREATE|table1|col=string")
  2008  	exec(t, db, "INSERT|table1|col=1.1")
  2009  	exec(t, db, "INSERT|table1|col=1.2")
  2010  	exec(t, db, "CREATE|table2|col=string")
  2011  	exec(t, db, "INSERT|table2|col=2.1")
  2012  	exec(t, db, "INSERT|table2|col=2.2")
  2013  
  2014  	exec(t, db, "CREATE|cursor|name=string,list=table")
  2015  	exec(t, db, "INSERT|cursor|name=table1,list=table1!col")
  2016  	exec(t, db, "INSERT|cursor|name=table2,list=table2!col")
  2017  
  2018  	ctx, cancel := context.WithTimeout(context.Background(), time.Second*30)
  2019  	defer cancel()
  2020  
  2021  	rows, err := db.QueryContext(ctx, `SELECT|cursor|name,list|`)
  2022  	if err != nil {
  2023  		t.Fatal(err)
  2024  	}
  2025  	defer rows.Close()
  2026  
  2027  	var got []string
  2028  	for rows.Next() {
  2029  		var name string
  2030  		cursor := &Rows{}
  2031  		if err := rows.Scan(&name, cursor); err != nil {
  2032  			t.Fatal(err)
  2033  		}
  2034  		got = append(got, name)
  2035  		if name == cancelOn {
  2036  			rows.Close()
  2037  		}
  2038  		for cursor.Next() {
  2039  			var col string
  2040  			if err := cursor.Scan(&col); err != nil {
  2041  				t.Fatal(err)
  2042  			}
  2043  			got = append(got, col)
  2044  			if col == cancelOn {
  2045  				cursor.Close()
  2046  			}
  2047  		}
  2048  	}
  2049  
  2050  	if !slices.Equal(got, want) {
  2051  		t.Errorf("cancel after reading %q:\ngot:  %v\nwant: %v", cancelOn, got, want)
  2052  	}
  2053  }
  2054  
  2055  func TestInvalidNilValues(t *testing.T) {
  2056  	var date1 time.Time
  2057  	var date2 int
  2058  
  2059  	tests := []struct {
  2060  		name          string
  2061  		input         any
  2062  		expectedError string
  2063  	}{
  2064  		{
  2065  			name:          "time.Time",
  2066  			input:         &date1,
  2067  			expectedError: `sql: Scan error on column index 0, name "bdate": unsupported Scan, storing driver.Value type <nil> into type *time.Time`,
  2068  		},
  2069  		{
  2070  			name:          "int",
  2071  			input:         &date2,
  2072  			expectedError: `sql: Scan error on column index 0, name "bdate": converting NULL to int is unsupported`,
  2073  		},
  2074  	}
  2075  
  2076  	for _, tt := range tests {
  2077  		synctestSubtest(t, tt.name, func(t *testing.T) {
  2078  			db := newTestDB(t, "people")
  2079  			defer closeDB(t, db)
  2080  
  2081  			ctx := t.Context()
  2082  			conn, err := db.Conn(ctx)
  2083  			if err != nil {
  2084  				t.Fatal(err)
  2085  			}
  2086  			getFakeConn(conn.dc.ci).skipDirtySession = true
  2087  			defer conn.Close()
  2088  
  2089  			err = conn.QueryRowContext(ctx, "SELECT|people|bdate|age=?", 1).Scan(tt.input)
  2090  			if err == nil {
  2091  				t.Fatal("expected error when querying nil column, but succeeded")
  2092  			}
  2093  			if err.Error() != tt.expectedError {
  2094  				t.Fatalf("Expected error: %s\nReceived: %s", tt.expectedError, err.Error())
  2095  			}
  2096  
  2097  			err = conn.PingContext(ctx)
  2098  			if err != nil {
  2099  				t.Fatal(err)
  2100  			}
  2101  		})
  2102  	}
  2103  }
  2104  
  2105  func TestConnTx(t *testing.T) {
  2106  	testDatabase(t, testConnTx)
  2107  }
  2108  func testConnTx(t *testing.T, db *DB) {
  2109  	populate(t, db, "people")
  2110  
  2111  	ctx := t.Context()
  2112  	conn, err := db.Conn(ctx)
  2113  	if err != nil {
  2114  		t.Fatal(err)
  2115  	}
  2116  	getFakeConn(conn.dc.ci).skipDirtySession = true
  2117  	defer conn.Close()
  2118  
  2119  	tx, err := conn.BeginTx(ctx, nil)
  2120  	if err != nil {
  2121  		t.Fatal(err)
  2122  	}
  2123  	insertName, insertAge := "Nancy", 33
  2124  	_, err = tx.ExecContext(ctx, "INSERT|people|name=?,age=?,photo=APHOTO", insertName, insertAge)
  2125  	if err != nil {
  2126  		t.Fatal(err)
  2127  	}
  2128  	err = tx.Commit()
  2129  	if err != nil {
  2130  		t.Fatal(err)
  2131  	}
  2132  
  2133  	var selectName string
  2134  	err = conn.QueryRowContext(ctx, "SELECT|people|name|age=?", insertAge).Scan(&selectName)
  2135  	if err != nil {
  2136  		t.Fatal(err)
  2137  	}
  2138  	if selectName != insertName {
  2139  		t.Fatalf("got %q want %q", selectName, insertName)
  2140  	}
  2141  }
  2142  
  2143  // TestConnIsValid verifies that a database connection that should be discarded,
  2144  // is actually discarded and does not re-enter the connection pool.
  2145  // If the IsValid method from *fakeConn is removed, this test will fail.
  2146  func TestConnIsValid(t *testing.T) {
  2147  	testDatabase(t, testConnIsValid, requireFeature("Validator"))
  2148  }
  2149  func testConnIsValid(t *testing.T, db *DB) {
  2150  	populate(t, db, "people")
  2151  
  2152  	db.SetMaxOpenConns(1)
  2153  
  2154  	ctx := context.Background()
  2155  
  2156  	c, err := db.Conn(ctx)
  2157  	if err != nil {
  2158  		t.Fatal(err)
  2159  	}
  2160  
  2161  	err = c.Raw(func(raw any) error {
  2162  		dc := getFakeConn(raw.(driver.Conn))
  2163  		dc.stickyBad = true
  2164  		return nil
  2165  	})
  2166  	if err != nil {
  2167  		t.Fatal(err)
  2168  	}
  2169  	c.Close()
  2170  
  2171  	if len(db.freeConn) > 0 && getFakeConn(db.freeConn[0].ci).stickyBad {
  2172  		t.Fatal("bad connection returned to pool; expected bad connection to be discarded")
  2173  	}
  2174  }
  2175  
  2176  // Tests fix for issue 2542, that we release a lock when querying on
  2177  // a closed connection.
  2178  func TestIssue2542Deadlock(t *testing.T) {
  2179  	testDatabase(t, testIssue2542Deadlock)
  2180  }
  2181  func testIssue2542Deadlock(t *testing.T, db *DB) {
  2182  	populate(t, db, "people")
  2183  	closeDB(t, db)
  2184  	for i := 0; i < 2; i++ {
  2185  		_, err := db.Query("SELECT|people|age,name|")
  2186  		if err == nil {
  2187  			t.Fatalf("expected error")
  2188  		}
  2189  	}
  2190  }
  2191  
  2192  // From golang.org/issue/3865
  2193  func TestCloseStmtBeforeRows(t *testing.T) {
  2194  	testDatabase(t, testCloseStmtBeforeRows)
  2195  }
  2196  func testCloseStmtBeforeRows(t *testing.T, db *DB) {
  2197  	populate(t, db, "people")
  2198  
  2199  	s, err := db.Prepare("SELECT|people|name|")
  2200  	if err != nil {
  2201  		t.Fatal(err)
  2202  	}
  2203  
  2204  	r, err := s.Query()
  2205  	if err != nil {
  2206  		s.Close()
  2207  		t.Fatal(err)
  2208  	}
  2209  
  2210  	err = s.Close()
  2211  	if err != nil {
  2212  		t.Fatal(err)
  2213  	}
  2214  
  2215  	r.Close()
  2216  }
  2217  
  2218  // Tests fix for issue 2788, that we bind nil to a []byte if the
  2219  // value in the column is sql null
  2220  func TestNullByteSlice(t *testing.T) {
  2221  	testDatabase(t, testNullByteSlice)
  2222  }
  2223  func testNullByteSlice(t *testing.T, db *DB) {
  2224  	exec(t, db, "CREATE|t|id=int32,name=nullstring")
  2225  	exec(t, db, "INSERT|t|id=10,name=?", nil)
  2226  
  2227  	var name []byte
  2228  
  2229  	err := db.QueryRow("SELECT|t|name|id=?", 10).Scan(&name)
  2230  	if err != nil {
  2231  		t.Fatal(err)
  2232  	}
  2233  	if name != nil {
  2234  		t.Fatalf("name []byte should be nil for null column value, got: %#v", name)
  2235  	}
  2236  
  2237  	exec(t, db, "INSERT|t|id=11,name=?", "bob")
  2238  	err = db.QueryRow("SELECT|t|name|id=?", 11).Scan(&name)
  2239  	if err != nil {
  2240  		t.Fatal(err)
  2241  	}
  2242  	if string(name) != "bob" {
  2243  		t.Fatalf("name []byte should be bob, got: %q", string(name))
  2244  	}
  2245  }
  2246  
  2247  func TestPointerParamsAndScans(t *testing.T) {
  2248  	testDatabase(t, testPointerParamsAndScans)
  2249  }
  2250  func testPointerParamsAndScans(t *testing.T, db *DB) {
  2251  	exec(t, db, "CREATE|t|id=int32,name=nullstring")
  2252  
  2253  	bob := "bob"
  2254  	var name *string
  2255  
  2256  	name = &bob
  2257  	exec(t, db, "INSERT|t|id=10,name=?", name)
  2258  	name = nil
  2259  	exec(t, db, "INSERT|t|id=20,name=?", name)
  2260  
  2261  	err := db.QueryRow("SELECT|t|name|id=?", 10).Scan(&name)
  2262  	if err != nil {
  2263  		t.Fatalf("querying id 10: %v", err)
  2264  	}
  2265  	if name == nil {
  2266  		t.Errorf("id 10's name = nil; want bob")
  2267  	} else if *name != "bob" {
  2268  		t.Errorf("id 10's name = %q; want bob", *name)
  2269  	}
  2270  
  2271  	err = db.QueryRow("SELECT|t|name|id=?", 20).Scan(&name)
  2272  	if err != nil {
  2273  		t.Fatalf("querying id 20: %v", err)
  2274  	}
  2275  	if name != nil {
  2276  		t.Errorf("id 20 = %q; want nil", *name)
  2277  	}
  2278  }
  2279  
  2280  func TestQueryRowClosingStmt(t *testing.T) {
  2281  	testDatabase(t, testQueryRowClosingStmt)
  2282  }
  2283  func testQueryRowClosingStmt(t *testing.T, db *DB) {
  2284  	populate(t, db, "people")
  2285  	var name string
  2286  	var age int
  2287  	err := db.QueryRow("SELECT|people|age,name|age=?", 3).Scan(&age, &name)
  2288  	if err != nil {
  2289  		t.Fatal(err)
  2290  	}
  2291  	if len(db.freeConn) != 1 {
  2292  		t.Fatalf("expected 1 free conn")
  2293  	}
  2294  	fakeConn := getFakeConn(db.freeConn[0].ci)
  2295  	if made, closed := fakeConn.stmtsMade, fakeConn.stmtsClosed; made != closed {
  2296  		t.Errorf("statement close mismatch: made %d, closed %d", made, closed)
  2297  	}
  2298  }
  2299  
  2300  var atomicRowsCloseHook atomic.Value // of func(*Rows, *error)
  2301  
  2302  func init() {
  2303  	rowsCloseHook = func() func(*Rows, *error) {
  2304  		fn, _ := atomicRowsCloseHook.Load().(func(*Rows, *error))
  2305  		return fn
  2306  	}
  2307  }
  2308  
  2309  func setRowsCloseHook(fn func(*Rows, *error)) {
  2310  	if fn == nil {
  2311  		// Can't change an atomic.Value back to nil, so set it to this
  2312  		// no-op func instead.
  2313  		fn = func(*Rows, *error) {}
  2314  	}
  2315  	atomicRowsCloseHook.Store(fn)
  2316  }
  2317  
  2318  // Test issue 6651
  2319  func TestIssue6651(t *testing.T) {
  2320  	testDatabase(t, testIssue6651)
  2321  }
  2322  func testIssue6651(t *testing.T, db *DB) {
  2323  	populate(t, db, "people")
  2324  
  2325  	var v string
  2326  
  2327  	want := "error in rows.Next"
  2328  	rowsCursorNextHook = func(dest []driver.Value) error {
  2329  		return errors.New(want)
  2330  	}
  2331  	defer func() { rowsCursorNextHook = nil }()
  2332  
  2333  	err := db.QueryRow("SELECT|people|name|").Scan(&v)
  2334  	if err == nil || err.Error() != want {
  2335  		t.Errorf("error = %q; want %q", err, want)
  2336  	}
  2337  	rowsCursorNextHook = nil
  2338  
  2339  	want = "error in rows.Close"
  2340  	setRowsCloseHook(func(rows *Rows, err *error) {
  2341  		*err = errors.New(want)
  2342  	})
  2343  	defer setRowsCloseHook(nil)
  2344  	err = db.QueryRow("SELECT|people|name|").Scan(&v)
  2345  	if err == nil || err.Error() != want {
  2346  		t.Errorf("error = %q; want %q", err, want)
  2347  	}
  2348  }
  2349  
  2350  type nullTestRow struct {
  2351  	nullParam    any
  2352  	notNullParam any
  2353  	scanNullVal  any
  2354  }
  2355  
  2356  type nullTestSpec struct {
  2357  	nullType    string
  2358  	notNullType string
  2359  	rows        [6]nullTestRow
  2360  }
  2361  
  2362  func TestNullStringParam(t *testing.T) {
  2363  	spec := nullTestSpec{"nullstring", "string", [6]nullTestRow{
  2364  		{NullString{"aqua", true}, "", NullString{"aqua", true}},
  2365  		{NullString{"brown", false}, "", NullString{"", false}},
  2366  		{"chartreuse", "", NullString{"chartreuse", true}},
  2367  		{NullString{"darkred", true}, "", NullString{"darkred", true}},
  2368  		{NullString{"eel", false}, "", NullString{"", false}},
  2369  		{"foo", NullString{"black", false}, nil},
  2370  	}}
  2371  	testDatabase(t, func(t *testing.T, db *DB) {
  2372  		nullTestRun(t, spec, db)
  2373  	})
  2374  }
  2375  
  2376  func TestGenericNullStringParam(t *testing.T) {
  2377  	spec := nullTestSpec{"nullstring", "string", [6]nullTestRow{
  2378  		{Null[string]{"aqua", true}, "", Null[string]{"aqua", true}},
  2379  		{Null[string]{"brown", false}, "", Null[string]{"", false}},
  2380  		{"chartreuse", "", Null[string]{"chartreuse", true}},
  2381  		{Null[string]{"darkred", true}, "", Null[string]{"darkred", true}},
  2382  		{Null[string]{"eel", false}, "", Null[string]{"", false}},
  2383  		{"foo", Null[string]{"black", false}, nil},
  2384  	}}
  2385  	testDatabase(t, func(t *testing.T, db *DB) {
  2386  		nullTestRun(t, spec, db)
  2387  	})
  2388  }
  2389  
  2390  func TestNullInt64Param(t *testing.T) {
  2391  	spec := nullTestSpec{"nullint64", "int64", [6]nullTestRow{
  2392  		{NullInt64{31, true}, 1, NullInt64{31, true}},
  2393  		{NullInt64{-22, false}, 1, NullInt64{0, false}},
  2394  		{22, 1, NullInt64{22, true}},
  2395  		{NullInt64{33, true}, 1, NullInt64{33, true}},
  2396  		{NullInt64{222, false}, 1, NullInt64{0, false}},
  2397  		{0, NullInt64{31, false}, nil},
  2398  	}}
  2399  	testDatabase(t, func(t *testing.T, db *DB) {
  2400  		nullTestRun(t, spec, db)
  2401  	})
  2402  }
  2403  
  2404  func TestNullInt32Param(t *testing.T) {
  2405  	spec := nullTestSpec{"nullint32", "int32", [6]nullTestRow{
  2406  		{NullInt32{31, true}, 1, NullInt32{31, true}},
  2407  		{NullInt32{-22, false}, 1, NullInt32{0, false}},
  2408  		{22, 1, NullInt32{22, true}},
  2409  		{NullInt32{33, true}, 1, NullInt32{33, true}},
  2410  		{NullInt32{222, false}, 1, NullInt32{0, false}},
  2411  		{0, NullInt32{31, false}, nil},
  2412  	}}
  2413  	testDatabase(t, func(t *testing.T, db *DB) {
  2414  		nullTestRun(t, spec, db)
  2415  	})
  2416  }
  2417  
  2418  func TestNullInt16Param(t *testing.T) {
  2419  	spec := nullTestSpec{"nullint16", "int16", [6]nullTestRow{
  2420  		{NullInt16{31, true}, 1, NullInt16{31, true}},
  2421  		{NullInt16{-22, false}, 1, NullInt16{0, false}},
  2422  		{22, 1, NullInt16{22, true}},
  2423  		{NullInt16{33, true}, 1, NullInt16{33, true}},
  2424  		{NullInt16{222, false}, 1, NullInt16{0, false}},
  2425  		{0, NullInt16{31, false}, nil},
  2426  	}}
  2427  	testDatabase(t, func(t *testing.T, db *DB) {
  2428  		nullTestRun(t, spec, db)
  2429  	})
  2430  }
  2431  
  2432  func TestNullByteParam(t *testing.T) {
  2433  	spec := nullTestSpec{"nullbyte", "byte", [6]nullTestRow{
  2434  		{NullByte{31, true}, 1, NullByte{31, true}},
  2435  		{NullByte{0, false}, 1, NullByte{0, false}},
  2436  		{22, 1, NullByte{22, true}},
  2437  		{NullByte{33, true}, 1, NullByte{33, true}},
  2438  		{NullByte{222, false}, 1, NullByte{0, false}},
  2439  		{0, NullByte{31, false}, nil},
  2440  	}}
  2441  	testDatabase(t, func(t *testing.T, db *DB) {
  2442  		nullTestRun(t, spec, db)
  2443  	})
  2444  }
  2445  
  2446  func TestNullFloat64Param(t *testing.T) {
  2447  	spec := nullTestSpec{"nullfloat64", "float64", [6]nullTestRow{
  2448  		{NullFloat64{31.2, true}, 1, NullFloat64{31.2, true}},
  2449  		{NullFloat64{13.1, false}, 1, NullFloat64{0, false}},
  2450  		{-22.9, 1, NullFloat64{-22.9, true}},
  2451  		{NullFloat64{33.81, true}, 1, NullFloat64{33.81, true}},
  2452  		{NullFloat64{222, false}, 1, NullFloat64{0, false}},
  2453  		{10, NullFloat64{31.2, false}, nil},
  2454  	}}
  2455  	testDatabase(t, func(t *testing.T, db *DB) {
  2456  		nullTestRun(t, spec, db)
  2457  	})
  2458  }
  2459  
  2460  func TestNullBoolParam(t *testing.T) {
  2461  	spec := nullTestSpec{"nullbool", "bool", [6]nullTestRow{
  2462  		{NullBool{false, true}, true, NullBool{false, true}},
  2463  		{NullBool{true, false}, false, NullBool{false, false}},
  2464  		{true, true, NullBool{true, true}},
  2465  		{NullBool{true, true}, false, NullBool{true, true}},
  2466  		{NullBool{true, false}, true, NullBool{false, false}},
  2467  		{true, NullBool{true, false}, nil},
  2468  	}}
  2469  	testDatabase(t, func(t *testing.T, db *DB) {
  2470  		nullTestRun(t, spec, db)
  2471  	})
  2472  }
  2473  
  2474  func TestNullTimeParam(t *testing.T) {
  2475  	t0 := time.Time{}
  2476  	t1 := time.Date(2000, 1, 1, 8, 9, 10, 11, time.UTC)
  2477  	t2 := time.Date(2010, 1, 1, 8, 9, 10, 11, time.UTC)
  2478  	spec := nullTestSpec{"nulldatetime", "datetime", [6]nullTestRow{
  2479  		{NullTime{t1, true}, t2, NullTime{t1, true}},
  2480  		{NullTime{t1, false}, t2, NullTime{t0, false}},
  2481  		{t1, t2, NullTime{t1, true}},
  2482  		{NullTime{t1, true}, t2, NullTime{t1, true}},
  2483  		{NullTime{t1, false}, t2, NullTime{t0, false}},
  2484  		{t2, NullTime{t1, false}, nil},
  2485  	}}
  2486  	testDatabase(t, func(t *testing.T, db *DB) {
  2487  		nullTestRun(t, spec, db)
  2488  	})
  2489  }
  2490  
  2491  func TestNullUUIDParam(t *testing.T) {
  2492  	u0 := uuid.UUID{}
  2493  	u1 := uuid.MustParse("46cd2740-6081-4289-a659-03b61ebb92f7")
  2494  	u2 := uuid.MustParse("46cd2740-6081-4289-a659-03b61ebb92f7")
  2495  	spec := nullTestSpec{"nulluuid", "uuid", [6]nullTestRow{
  2496  		{Null[uuid.UUID]{u1, true}, u2, Null[uuid.UUID]{u1, true}},
  2497  		{Null[uuid.UUID]{u1, false}, u2, Null[uuid.UUID]{u0, false}},
  2498  		{u1, u2, Null[uuid.UUID]{u1, true}},
  2499  		{Null[uuid.UUID]{u1, true}, u2, Null[uuid.UUID]{u1, true}},
  2500  		{Null[uuid.UUID]{u1, false}, u2, Null[uuid.UUID]{u0, false}},
  2501  		{u2, Null[uuid.UUID]{u1, false}, nil},
  2502  	}}
  2503  	testDatabase(t, func(t *testing.T, db *DB) {
  2504  		nullTestRun(t, spec, db)
  2505  	})
  2506  }
  2507  
  2508  func nullTestRun(t *testing.T, spec nullTestSpec, db *DB) {
  2509  	exec(t, db, fmt.Sprintf("CREATE|t|id=int32,name=string,nullf=%s,notnullf=%s", spec.nullType, spec.notNullType))
  2510  
  2511  	// Inserts with db.Exec:
  2512  	exec(t, db, "INSERT|t|id=?,name=?,nullf=?,notnullf=?", 1, "alice", spec.rows[0].nullParam, spec.rows[0].notNullParam)
  2513  	exec(t, db, "INSERT|t|id=?,name=?,nullf=?,notnullf=?", 2, "bob", spec.rows[1].nullParam, spec.rows[1].notNullParam)
  2514  
  2515  	// Inserts with a prepared statement:
  2516  	stmt, err := db.Prepare("INSERT|t|id=?,name=?,nullf=?,notnullf=?")
  2517  	if err != nil {
  2518  		t.Fatalf("prepare: %v", err)
  2519  	}
  2520  	defer stmt.Close()
  2521  	if _, err := stmt.Exec(3, "chris", spec.rows[2].nullParam, spec.rows[2].notNullParam); err != nil {
  2522  		t.Errorf("exec insert chris: %v", err)
  2523  	}
  2524  	if _, err := stmt.Exec(4, "dave", spec.rows[3].nullParam, spec.rows[3].notNullParam); err != nil {
  2525  		t.Errorf("exec insert dave: %v", err)
  2526  	}
  2527  	if _, err := stmt.Exec(5, "eleanor", spec.rows[4].nullParam, spec.rows[4].notNullParam); err != nil {
  2528  		t.Errorf("exec insert eleanor: %v", err)
  2529  	}
  2530  
  2531  	// Can't put null val into non-null col
  2532  	row5 := spec.rows[5]
  2533  	if _, err := stmt.Exec(6, "bob", row5.nullParam, row5.notNullParam); err == nil {
  2534  		t.Errorf("expected error inserting nil val with prepared statement Exec: NULL=%#v, NOT-NULL=%#v", row5.nullParam, row5.notNullParam)
  2535  	}
  2536  
  2537  	_, err = db.Exec("INSERT|t|id=?,name=?,nullf=?", 999, nil, nil)
  2538  	if err == nil {
  2539  		// TODO: this test fails, but it's just because
  2540  		// fakeConn implements the optional Execer interface,
  2541  		// so arguably this is the correct behavior. But
  2542  		// maybe I should flesh out the fakeConn.Exec
  2543  		// implementation so this properly fails.
  2544  		// t.Errorf("expected error inserting nil name with Exec")
  2545  	}
  2546  
  2547  	paramtype := reflect.TypeOf(spec.rows[0].nullParam)
  2548  	bindVal := reflect.New(paramtype).Interface()
  2549  
  2550  	for i := 0; i < 5; i++ {
  2551  		id := i + 1
  2552  		if err := db.QueryRow("SELECT|t|nullf|id=?", id).Scan(bindVal); err != nil {
  2553  			t.Errorf("id=%d Scan: %v", id, err)
  2554  		}
  2555  		bindValDeref := reflect.ValueOf(bindVal).Elem().Interface()
  2556  		if !reflect.DeepEqual(bindValDeref, spec.rows[i].scanNullVal) {
  2557  			t.Errorf("id=%d got %#v, want %#v", id, bindValDeref, spec.rows[i].scanNullVal)
  2558  		}
  2559  	}
  2560  }
  2561  
  2562  // golang.org/issue/4859
  2563  func TestQueryRowNilScanDest(t *testing.T) {
  2564  	testDatabase(t, testQueryRowNilScanDest)
  2565  }
  2566  func testQueryRowNilScanDest(t *testing.T, db *DB) {
  2567  	populate(t, db, "people")
  2568  	var name *string // nil pointer
  2569  	err := db.QueryRow("SELECT|people|name|").Scan(name)
  2570  	want := `sql: Scan error on column index 0, name "name": destination pointer is nil`
  2571  	if err == nil || err.Error() != want {
  2572  		t.Errorf("error = %q; want %q", err.Error(), want)
  2573  	}
  2574  }
  2575  
  2576  func TestIssue4902(t *testing.T) {
  2577  	testDatabase(t, testIssue4902)
  2578  }
  2579  func testIssue4902(t *testing.T, db *DB) {
  2580  	populate(t, db, "people")
  2581  
  2582  	driver := db.Driver().(*fakeDriver)
  2583  	opens0 := driver.openCount
  2584  
  2585  	var stmt *Stmt
  2586  	var err error
  2587  	for i := 0; i < 10; i++ {
  2588  		stmt, err = db.Prepare("SELECT|people|name|")
  2589  		if err != nil {
  2590  			t.Fatal(err)
  2591  		}
  2592  		err = stmt.Close()
  2593  		if err != nil {
  2594  			t.Fatal(err)
  2595  		}
  2596  	}
  2597  
  2598  	opens := driver.openCount - opens0
  2599  	if opens > 1 {
  2600  		t.Errorf("opens = %d; want <= 1", opens)
  2601  		t.Logf("db = %#v", db)
  2602  		t.Logf("driver = %#v", driver)
  2603  		t.Logf("stmt = %#v", stmt)
  2604  	}
  2605  }
  2606  
  2607  // Issue 3857
  2608  // This used to deadlock.
  2609  func TestSimultaneousQueries(t *testing.T) {
  2610  	testDatabase(t, testSimultaneousQueries)
  2611  }
  2612  func testSimultaneousQueries(t *testing.T, db *DB) {
  2613  	populate(t, db, "people")
  2614  
  2615  	tx, err := db.Begin()
  2616  	if err != nil {
  2617  		t.Fatal(err)
  2618  	}
  2619  	defer tx.Rollback()
  2620  
  2621  	r1, err := tx.Query("SELECT|people|name|")
  2622  	if err != nil {
  2623  		t.Fatal(err)
  2624  	}
  2625  	defer r1.Close()
  2626  
  2627  	r2, err := tx.Query("SELECT|people|name|")
  2628  	if err != nil {
  2629  		t.Fatal(err)
  2630  	}
  2631  	defer r2.Close()
  2632  }
  2633  
  2634  func TestMaxIdleConns(t *testing.T) {
  2635  	testDatabase(t, testMaxIdleConns)
  2636  }
  2637  func testMaxIdleConns(t *testing.T, db *DB) {
  2638  	populate(t, db, "people")
  2639  
  2640  	tx, err := db.Begin()
  2641  	if err != nil {
  2642  		t.Fatal(err)
  2643  	}
  2644  	tx.Commit()
  2645  	if got := len(db.freeConn); got != 1 {
  2646  		t.Errorf("freeConns = %d; want 1", got)
  2647  	}
  2648  
  2649  	db.SetMaxIdleConns(0)
  2650  
  2651  	if got := len(db.freeConn); got != 0 {
  2652  		t.Errorf("freeConns after set to zero = %d; want 0", got)
  2653  	}
  2654  
  2655  	tx, err = db.Begin()
  2656  	if err != nil {
  2657  		t.Fatal(err)
  2658  	}
  2659  	tx.Commit()
  2660  	if got := len(db.freeConn); got != 0 {
  2661  		t.Errorf("freeConns = %d; want 0", got)
  2662  	}
  2663  }
  2664  
  2665  func TestMaxOpenConns(t *testing.T) {
  2666  	testDatabase(t, testMaxOpenConns)
  2667  }
  2668  func testMaxOpenConns(t *testing.T, db *DB) {
  2669  	if testing.Short() {
  2670  		t.Skip("skipping in short mode")
  2671  	}
  2672  	defer setHookpostCloseConn(nil)
  2673  	setHookpostCloseConn(func(_ *fakeConn, err error) {
  2674  		if err != nil {
  2675  			t.Errorf("Error closing fakeConn: %v", err)
  2676  		}
  2677  	})
  2678  
  2679  	populate(t, db, "magicquery")
  2680  
  2681  	driver := db.Driver().(*fakeDriver)
  2682  
  2683  	// Force the number of open connections to 0 so we can get an accurate
  2684  	// count for the test
  2685  	db.clearAllConns(t)
  2686  
  2687  	driver.mu.Lock()
  2688  	opens0 := driver.openCount
  2689  	closes0 := driver.closeCount
  2690  	driver.mu.Unlock()
  2691  
  2692  	db.SetMaxIdleConns(10)
  2693  	db.SetMaxOpenConns(10)
  2694  
  2695  	stmt, err := db.Prepare("SELECT|magicquery|op|op=?,millis=?")
  2696  	if err != nil {
  2697  		t.Fatal(err)
  2698  	}
  2699  
  2700  	// Start 50 parallel slow queries.
  2701  	const (
  2702  		nquery      = 50
  2703  		sleepMillis = 25
  2704  		nbatch      = 2
  2705  	)
  2706  	var wg sync.WaitGroup
  2707  	for batch := 0; batch < nbatch; batch++ {
  2708  		for i := 0; i < nquery; i++ {
  2709  			wg.Add(1)
  2710  			go func() {
  2711  				defer wg.Done()
  2712  				var op string
  2713  				if err := stmt.QueryRow("sleep", sleepMillis).Scan(&op); err != nil && err != ErrNoRows {
  2714  					t.Error(err)
  2715  				}
  2716  			}()
  2717  		}
  2718  		// Wait for the batch of queries above to finish before starting the next round.
  2719  		wg.Wait()
  2720  	}
  2721  
  2722  	if g, w := db.numFreeConns(), 10; g != w {
  2723  		t.Errorf("free conns = %d; want %d", g, w)
  2724  	}
  2725  
  2726  	if n := db.numDeps(); n > 20 {
  2727  		t.Errorf("number of dependencies = %d; expected <= 20", n)
  2728  		db.dumpDeps(t)
  2729  	}
  2730  
  2731  	driver.mu.Lock()
  2732  	opens := driver.openCount - opens0
  2733  	closes := driver.closeCount - closes0
  2734  	driver.mu.Unlock()
  2735  
  2736  	if opens > 10 {
  2737  		t.Logf("open calls = %d", opens)
  2738  		t.Logf("close calls = %d", closes)
  2739  		t.Errorf("db connections opened = %d; want <= 10", opens)
  2740  		db.dumpDeps(t)
  2741  	}
  2742  
  2743  	if err := stmt.Close(); err != nil {
  2744  		t.Fatal(err)
  2745  	}
  2746  
  2747  	if g, w := db.numFreeConns(), 10; g != w {
  2748  		t.Errorf("free conns = %d; want %d", g, w)
  2749  	}
  2750  
  2751  	if n := db.numDeps(); n > 10 {
  2752  		t.Errorf("number of dependencies = %d; expected <= 10", n)
  2753  		db.dumpDeps(t)
  2754  	}
  2755  
  2756  	db.SetMaxOpenConns(5)
  2757  
  2758  	if g, w := db.numFreeConns(), 5; g != w {
  2759  		t.Errorf("free conns = %d; want %d", g, w)
  2760  	}
  2761  
  2762  	if n := db.numDeps(); n > 5 {
  2763  		t.Errorf("number of dependencies = %d; expected 0", n)
  2764  		db.dumpDeps(t)
  2765  	}
  2766  
  2767  	db.SetMaxOpenConns(0)
  2768  
  2769  	if g, w := db.numFreeConns(), 5; g != w {
  2770  		t.Errorf("free conns = %d; want %d", g, w)
  2771  	}
  2772  
  2773  	if n := db.numDeps(); n > 5 {
  2774  		t.Errorf("number of dependencies = %d; expected 0", n)
  2775  		db.dumpDeps(t)
  2776  	}
  2777  
  2778  	db.clearAllConns(t)
  2779  }
  2780  
  2781  // Issue 9453: tests that SetMaxOpenConns can be lowered at runtime
  2782  // and affects the subsequent release of connections.
  2783  func TestMaxOpenConnsOnBusy(t *testing.T) {
  2784  	testDatabase(t, testMaxOpenConnsOnBusy)
  2785  }
  2786  func testMaxOpenConnsOnBusy(t *testing.T, db *DB) {
  2787  	defer setHookpostCloseConn(nil)
  2788  	setHookpostCloseConn(func(_ *fakeConn, err error) {
  2789  		if err != nil {
  2790  			t.Errorf("Error closing fakeConn: %v", err)
  2791  		}
  2792  	})
  2793  
  2794  	populate(t, db, "magicquery")
  2795  
  2796  	db.SetMaxOpenConns(3)
  2797  
  2798  	ctx := context.Background()
  2799  
  2800  	conn0, err := db.conn(ctx, cachedOrNewConn)
  2801  	if err != nil {
  2802  		t.Fatalf("db open conn fail: %v", err)
  2803  	}
  2804  
  2805  	conn1, err := db.conn(ctx, cachedOrNewConn)
  2806  	if err != nil {
  2807  		t.Fatalf("db open conn fail: %v", err)
  2808  	}
  2809  
  2810  	conn2, err := db.conn(ctx, cachedOrNewConn)
  2811  	if err != nil {
  2812  		t.Fatalf("db open conn fail: %v", err)
  2813  	}
  2814  
  2815  	if g, w := db.numOpen, 3; g != w {
  2816  		t.Errorf("free conns = %d; want %d", g, w)
  2817  	}
  2818  
  2819  	db.SetMaxOpenConns(2)
  2820  	if g, w := db.numOpen, 3; g != w {
  2821  		t.Errorf("free conns = %d; want %d", g, w)
  2822  	}
  2823  
  2824  	conn0.releaseConn(nil)
  2825  	conn1.releaseConn(nil)
  2826  	if g, w := db.numOpen, 2; g != w {
  2827  		t.Errorf("free conns = %d; want %d", g, w)
  2828  	}
  2829  
  2830  	conn2.releaseConn(nil)
  2831  	if g, w := db.numOpen, 2; g != w {
  2832  		t.Errorf("free conns = %d; want %d", g, w)
  2833  	}
  2834  }
  2835  
  2836  // Issue 10886: tests that all connection attempts return when more than
  2837  // DB.maxOpen connections are in flight and the first DB.maxOpen fail.
  2838  func TestPendingConnsAfterErr(t *testing.T) {
  2839  	synctest.Test(t, testPendingConnsAfterErr)
  2840  }
  2841  func testPendingConnsAfterErr(t *testing.T) {
  2842  	const (
  2843  		maxOpen = 2
  2844  		tryOpen = maxOpen*2 + 2
  2845  	)
  2846  
  2847  	// No queries will be run.
  2848  	db, err := Open("test", fakeDBName)
  2849  	if err != nil {
  2850  		t.Fatalf("Open: %v", err)
  2851  	}
  2852  	defer closeDB(t, db)
  2853  	defer func() {
  2854  		for k, v := range db.lastPut {
  2855  			t.Logf("%p: %v", k, v)
  2856  		}
  2857  	}()
  2858  
  2859  	db.SetMaxOpenConns(maxOpen)
  2860  	db.SetMaxIdleConns(0)
  2861  
  2862  	errOffline := errors.New("db offline")
  2863  
  2864  	defer func() { setHookOpenErr(nil) }()
  2865  
  2866  	errs := make(chan error, tryOpen)
  2867  
  2868  	var opening sync.WaitGroup
  2869  	opening.Add(tryOpen)
  2870  
  2871  	setHookOpenErr(func() error {
  2872  		// Wait for all connections to enqueue.
  2873  		opening.Wait()
  2874  		return errOffline
  2875  	})
  2876  
  2877  	for i := 0; i < tryOpen; i++ {
  2878  		go func() {
  2879  			opening.Done() // signal one connection is in flight
  2880  			_, err := db.Exec("will never run")
  2881  			errs <- err
  2882  		}()
  2883  	}
  2884  
  2885  	opening.Wait() // wait for all workers to begin running
  2886  
  2887  	const timeout = 5 * time.Second
  2888  	to := time.NewTimer(timeout)
  2889  	defer to.Stop()
  2890  
  2891  	// check that all connections fail without deadlock
  2892  	for i := 0; i < tryOpen; i++ {
  2893  		select {
  2894  		case err := <-errs:
  2895  			if got, want := err, errOffline; got != want {
  2896  				t.Errorf("unexpected err: got %v, want %v", got, want)
  2897  			}
  2898  		case <-to.C:
  2899  			t.Fatalf("orphaned connection request(s), still waiting after %v", timeout)
  2900  		}
  2901  	}
  2902  
  2903  	// Wait a reasonable time for the database to close all connections.
  2904  	tick := time.NewTicker(3 * time.Millisecond)
  2905  	defer tick.Stop()
  2906  	for {
  2907  		select {
  2908  		case <-tick.C:
  2909  			db.mu.Lock()
  2910  			if db.numOpen == 0 {
  2911  				db.mu.Unlock()
  2912  				return
  2913  			}
  2914  			db.mu.Unlock()
  2915  		case <-to.C:
  2916  			// Closing the database will check for numOpen and fail the test.
  2917  			return
  2918  		}
  2919  	}
  2920  }
  2921  
  2922  func TestSingleOpenConn(t *testing.T) {
  2923  	testDatabase(t, testSingleOpenConn)
  2924  }
  2925  func testSingleOpenConn(t *testing.T, db *DB) {
  2926  	populate(t, db, "people")
  2927  
  2928  	db.SetMaxOpenConns(1)
  2929  
  2930  	rows, err := db.Query("SELECT|people|name|")
  2931  	if err != nil {
  2932  		t.Fatal(err)
  2933  	}
  2934  	if err = rows.Close(); err != nil {
  2935  		t.Fatal(err)
  2936  	}
  2937  	// shouldn't deadlock
  2938  	rows, err = db.Query("SELECT|people|name|")
  2939  	if err != nil {
  2940  		t.Fatal(err)
  2941  	}
  2942  	if err = rows.Close(); err != nil {
  2943  		t.Fatal(err)
  2944  	}
  2945  }
  2946  
  2947  func TestStats(t *testing.T) {
  2948  	testDatabase(t, testStats)
  2949  }
  2950  func testStats(t *testing.T, db *DB) {
  2951  	populate(t, db, "people")
  2952  	stats := db.Stats()
  2953  	if got := stats.OpenConnections; got != 1 {
  2954  		t.Errorf("stats.OpenConnections = %d; want 1", got)
  2955  	}
  2956  
  2957  	tx, err := db.Begin()
  2958  	if err != nil {
  2959  		t.Fatal(err)
  2960  	}
  2961  	tx.Commit()
  2962  
  2963  	closeDB(t, db)
  2964  	stats = db.Stats()
  2965  	if got := stats.OpenConnections; got != 0 {
  2966  		t.Errorf("stats.OpenConnections = %d; want 0", got)
  2967  	}
  2968  }
  2969  
  2970  func TestConnMaxLifetime(t *testing.T) {
  2971  	testDatabase(t, testConnMaxLifetime)
  2972  }
  2973  func testConnMaxLifetime(t *testing.T, db *DB) {
  2974  	populate(t, db, "magicquery")
  2975  
  2976  	driver := db.Driver().(*fakeDriver)
  2977  
  2978  	// Force the number of open connections to 0 so we can get an accurate
  2979  	// count for the test
  2980  	db.clearAllConns(t)
  2981  
  2982  	driver.mu.Lock()
  2983  	opens0 := driver.openCount
  2984  	closes0 := driver.closeCount
  2985  	driver.mu.Unlock()
  2986  
  2987  	db.SetMaxIdleConns(10)
  2988  	db.SetMaxOpenConns(10)
  2989  
  2990  	tx, err := db.Begin()
  2991  	if err != nil {
  2992  		t.Fatal(err)
  2993  	}
  2994  
  2995  	synctest.Sleep(1 * time.Second)
  2996  	tx2, err := db.Begin()
  2997  	if err != nil {
  2998  		t.Fatal(err)
  2999  	}
  3000  
  3001  	tx.Commit()
  3002  	tx2.Commit()
  3003  
  3004  	driver.mu.Lock()
  3005  	opens := driver.openCount - opens0
  3006  	closes := driver.closeCount - closes0
  3007  	driver.mu.Unlock()
  3008  
  3009  	if opens != 2 {
  3010  		t.Errorf("opens = %d; want 2", opens)
  3011  	}
  3012  	if closes != 0 {
  3013  		t.Errorf("closes = %d; want 0", closes)
  3014  	}
  3015  	if g, w := db.numFreeConns(), 2; g != w {
  3016  		t.Errorf("free conns = %d; want %d", g, w)
  3017  	}
  3018  
  3019  	// Expire first conn
  3020  	synctest.Sleep(10 * time.Second)
  3021  	db.SetConnMaxLifetime(10 * time.Second)
  3022  
  3023  	tx, err = db.Begin()
  3024  	if err != nil {
  3025  		t.Fatal(err)
  3026  	}
  3027  	tx2, err = db.Begin()
  3028  	if err != nil {
  3029  		t.Fatal(err)
  3030  	}
  3031  	tx.Commit()
  3032  	tx2.Commit()
  3033  
  3034  	// Give connectionCleaner chance to run.
  3035  	synctest.Wait()
  3036  	driver.mu.Lock()
  3037  	opens = driver.openCount - opens0
  3038  	closes = driver.closeCount - closes0
  3039  	driver.mu.Unlock()
  3040  
  3041  	if opens != 3 {
  3042  		t.Errorf("opens = %d; want 3", opens)
  3043  	}
  3044  	if closes != 1 {
  3045  		t.Errorf("closes = %d; want 1", closes)
  3046  	}
  3047  
  3048  	if s := db.Stats(); s.MaxLifetimeClosed != 1 {
  3049  		t.Errorf("MaxLifetimeClosed = %d; want 1 %#v", s.MaxLifetimeClosed, s)
  3050  	}
  3051  }
  3052  
  3053  // golang.org/issue/5323
  3054  func TestStmtCloseDeps(t *testing.T) {
  3055  	testDatabase(t, testStmtCloseDeps)
  3056  }
  3057  func testStmtCloseDeps(t *testing.T, db *DB) {
  3058  	if testing.Short() {
  3059  		t.Skip("skipping in short mode")
  3060  	}
  3061  	defer setHookpostCloseConn(nil)
  3062  	setHookpostCloseConn(func(_ *fakeConn, err error) {
  3063  		if err != nil {
  3064  			t.Errorf("Error closing fakeConn: %v", err)
  3065  		}
  3066  	})
  3067  
  3068  	populate(t, db, "magicquery")
  3069  
  3070  	driver := db.Driver().(*fakeDriver)
  3071  
  3072  	driver.mu.Lock()
  3073  	opens0 := driver.openCount
  3074  	closes0 := driver.closeCount
  3075  	driver.mu.Unlock()
  3076  	openDelta0 := opens0 - closes0
  3077  
  3078  	stmt, err := db.Prepare("SELECT|magicquery|op|op=?,millis=?")
  3079  	if err != nil {
  3080  		t.Fatal(err)
  3081  	}
  3082  
  3083  	// Start 50 parallel slow queries.
  3084  	const (
  3085  		nquery      = 50
  3086  		sleepMillis = 25
  3087  		nbatch      = 2
  3088  	)
  3089  	var wg sync.WaitGroup
  3090  	for batch := 0; batch < nbatch; batch++ {
  3091  		for i := 0; i < nquery; i++ {
  3092  			wg.Add(1)
  3093  			go func() {
  3094  				defer wg.Done()
  3095  				var op string
  3096  				if err := stmt.QueryRow("sleep", sleepMillis).Scan(&op); err != nil && err != ErrNoRows {
  3097  					t.Error(err)
  3098  				}
  3099  			}()
  3100  		}
  3101  		// Wait for the batch of queries above to finish before starting the next round.
  3102  		wg.Wait()
  3103  	}
  3104  
  3105  	if g, w := db.numFreeConns(), 2; g != w {
  3106  		t.Errorf("free conns = %d; want %d", g, w)
  3107  	}
  3108  
  3109  	if n := db.numDeps(); n > 4 {
  3110  		t.Errorf("number of dependencies = %d; expected <= 4", n)
  3111  		db.dumpDeps(t)
  3112  	}
  3113  
  3114  	driver.mu.Lock()
  3115  	opens := driver.openCount - opens0
  3116  	closes := driver.closeCount - closes0
  3117  	openDelta := (driver.openCount - driver.closeCount) - openDelta0
  3118  	driver.mu.Unlock()
  3119  
  3120  	if openDelta > 2 {
  3121  		t.Logf("open calls = %d", opens)
  3122  		t.Logf("close calls = %d", closes)
  3123  		t.Logf("open delta = %d", openDelta)
  3124  		t.Errorf("db connections opened = %d; want <= 2", openDelta)
  3125  		db.dumpDeps(t)
  3126  	}
  3127  
  3128  	synctest.Wait()
  3129  	if len(stmt.css) > nquery {
  3130  		t.Errorf("len(stmt.css) = %d; want <= %d", len(stmt.css), nquery)
  3131  	}
  3132  
  3133  	if err := stmt.Close(); err != nil {
  3134  		t.Fatal(err)
  3135  	}
  3136  
  3137  	if g, w := db.numFreeConns(), 2; g != w {
  3138  		t.Errorf("free conns = %d; want %d", g, w)
  3139  	}
  3140  
  3141  	if n := db.numDeps(); n > 2 {
  3142  		t.Errorf("number of dependencies = %d; expected <= 2", n)
  3143  		db.dumpDeps(t)
  3144  	}
  3145  
  3146  	db.clearAllConns(t)
  3147  }
  3148  
  3149  // golang.org/issue/5046
  3150  func TestCloseConnBeforeStmts(t *testing.T) {
  3151  	testDatabase(t, testCloseConnBeforeStmts)
  3152  }
  3153  func testCloseConnBeforeStmts(t *testing.T, db *DB) {
  3154  	populate(t, db, "people")
  3155  
  3156  	defer setHookpostCloseConn(nil)
  3157  	setHookpostCloseConn(func(_ *fakeConn, err error) {
  3158  		if err != nil {
  3159  			t.Errorf("Error closing fakeConn: %v; from %s", err, stack())
  3160  			db.dumpDeps(t)
  3161  			t.Errorf("DB = %#v", db)
  3162  		}
  3163  	})
  3164  
  3165  	stmt, err := db.Prepare("SELECT|people|name|")
  3166  	if err != nil {
  3167  		t.Fatal(err)
  3168  	}
  3169  
  3170  	if len(db.freeConn) != 1 {
  3171  		t.Fatalf("expected 1 freeConn; got %d", len(db.freeConn))
  3172  	}
  3173  	dc := db.freeConn[0]
  3174  	if dc.closed {
  3175  		t.Errorf("conn shouldn't be closed")
  3176  	}
  3177  
  3178  	if n := len(dc.openStmt); n != 1 {
  3179  		t.Errorf("driverConn num openStmt = %d; want 1", n)
  3180  	}
  3181  	err = db.Close()
  3182  	if err != nil {
  3183  		t.Errorf("db Close = %v", err)
  3184  	}
  3185  	if !dc.closed {
  3186  		t.Errorf("after db.Close, driverConn should be closed")
  3187  	}
  3188  	if n := len(dc.openStmt); n != 0 {
  3189  		t.Errorf("driverConn num openStmt = %d; want 0", n)
  3190  	}
  3191  
  3192  	err = stmt.Close()
  3193  	if err != nil {
  3194  		t.Errorf("Stmt close = %v", err)
  3195  	}
  3196  
  3197  	if !dc.closed {
  3198  		t.Errorf("conn should be closed")
  3199  	}
  3200  	if dc.ci != nil {
  3201  		t.Errorf("after Stmt Close, driverConn's Conn interface should be nil")
  3202  	}
  3203  }
  3204  
  3205  // golang.org/issue/5283: don't release the Rows' connection in Close
  3206  // before calling Stmt.Close.
  3207  func TestRowsCloseOrder(t *testing.T) {
  3208  	testDatabase(t, testRowsCloseOrder)
  3209  }
  3210  func testRowsCloseOrder(t *testing.T, db *DB) {
  3211  	populate(t, db, "people")
  3212  
  3213  	db.SetMaxIdleConns(0)
  3214  	setStrictFakeConnClose(t)
  3215  	defer setStrictFakeConnClose(nil)
  3216  
  3217  	rows, err := db.Query("SELECT|people|age,name|")
  3218  	if err != nil {
  3219  		t.Fatal(err)
  3220  	}
  3221  	err = rows.Close()
  3222  	if err != nil {
  3223  		t.Fatal(err)
  3224  	}
  3225  }
  3226  
  3227  func TestRowsImplicitClose(t *testing.T) {
  3228  	testDatabase(t, testRowsImplicitClose)
  3229  }
  3230  func testRowsImplicitClose(t *testing.T, db *DB) {
  3231  	populate(t, db, "people")
  3232  
  3233  	rows, err := db.Query("SELECT|people|age,name|")
  3234  	if err != nil {
  3235  		t.Fatal(err)
  3236  	}
  3237  
  3238  	want, fail := 2, errors.New("fail")
  3239  	r := getRowsCursor(rows)
  3240  	r.errPos, r.err = want, fail
  3241  
  3242  	got := 0
  3243  	for rows.Next() {
  3244  		got++
  3245  	}
  3246  	if got != want {
  3247  		t.Errorf("got %d rows, want %d", got, want)
  3248  	}
  3249  	if err := rows.Err(); err != fail {
  3250  		t.Errorf("got error %v, want %v", err, fail)
  3251  	}
  3252  	if !r.closed {
  3253  		t.Errorf("r.closed is false, want true")
  3254  	}
  3255  }
  3256  
  3257  func TestRowsCloseError(t *testing.T) {
  3258  	testDatabase(t, testRowsCloseError)
  3259  }
  3260  func testRowsCloseError(t *testing.T, db *DB) {
  3261  	populate(t, db, "people")
  3262  	rows, err := db.Query("SELECT|people|age,name|")
  3263  	if err != nil {
  3264  		t.Fatalf("Query: %v", err)
  3265  	}
  3266  	type row struct {
  3267  		age  int
  3268  		name string
  3269  	}
  3270  	got := []row{}
  3271  
  3272  	rc := getRowsCursor(rows)
  3273  	rc.closeErr = errors.New("rowsCursor: failed to close")
  3274  
  3275  	for rows.Next() {
  3276  		var r row
  3277  		err = rows.Scan(&r.age, &r.name)
  3278  		if err != nil {
  3279  			t.Fatalf("Scan: %v", err)
  3280  		}
  3281  		got = append(got, r)
  3282  	}
  3283  	err = rows.Err()
  3284  	if err != rc.closeErr {
  3285  		t.Fatalf("unexpected err: got %v, want %v", err, rc.closeErr)
  3286  	}
  3287  }
  3288  
  3289  func TestStmtCloseOrder(t *testing.T) {
  3290  	testDatabase(t, testStmtCloseOrder)
  3291  }
  3292  func testStmtCloseOrder(t *testing.T, db *DB) {
  3293  	populate(t, db, "people")
  3294  
  3295  	db.SetMaxIdleConns(0)
  3296  	setStrictFakeConnClose(t)
  3297  	defer setStrictFakeConnClose(nil)
  3298  
  3299  	_, err := db.Query("SELECT|non_existent|name|")
  3300  	if err == nil {
  3301  		t.Fatal("Querying non-existent table should fail")
  3302  	}
  3303  }
  3304  
  3305  // Test cases where there's more than maxBadConnRetries bad connections in the
  3306  // pool (issue 8834)
  3307  func TestManyErrBadConn(t *testing.T) {
  3308  	synctest.Test(t, testManyErrBadConn)
  3309  }
  3310  func testManyErrBadConn(t *testing.T) {
  3311  	manyErrBadConnSetup := func(first ...func(db *DB)) *DB {
  3312  		db := newTestDB(t, "people")
  3313  
  3314  		for _, f := range first {
  3315  			f(db)
  3316  		}
  3317  
  3318  		nconn := maxBadConnRetries + 1
  3319  		db.SetMaxIdleConns(nconn)
  3320  		db.SetMaxOpenConns(nconn)
  3321  		// open enough connections
  3322  		func() {
  3323  			for i := 0; i < nconn; i++ {
  3324  				rows, err := db.Query("SELECT|people|age,name|")
  3325  				if err != nil {
  3326  					t.Fatal(err)
  3327  				}
  3328  				defer rows.Close()
  3329  			}
  3330  		}()
  3331  
  3332  		db.mu.Lock()
  3333  		defer db.mu.Unlock()
  3334  		if db.numOpen != nconn {
  3335  			t.Fatalf("unexpected numOpen %d (was expecting %d)", db.numOpen, nconn)
  3336  		} else if len(db.freeConn) != nconn {
  3337  			t.Fatalf("unexpected len(db.freeConn) %d (was expecting %d)", len(db.freeConn), nconn)
  3338  		}
  3339  		for _, conn := range db.freeConn {
  3340  			conn.Lock()
  3341  			getFakeConn(conn.ci).stickyBad = true
  3342  			conn.Unlock()
  3343  		}
  3344  		return db
  3345  	}
  3346  
  3347  	// Query
  3348  	db := manyErrBadConnSetup()
  3349  	defer closeDB(t, db)
  3350  	rows, err := db.Query("SELECT|people|age,name|")
  3351  	if err != nil {
  3352  		t.Fatal(err)
  3353  	}
  3354  	if err = rows.Close(); err != nil {
  3355  		t.Fatal(err)
  3356  	}
  3357  
  3358  	// Exec
  3359  	db = manyErrBadConnSetup()
  3360  	defer closeDB(t, db)
  3361  	_, err = db.Exec("INSERT|people|name=Julia,age=19")
  3362  	if err != nil {
  3363  		t.Fatal(err)
  3364  	}
  3365  
  3366  	// Begin
  3367  	db = manyErrBadConnSetup()
  3368  	defer closeDB(t, db)
  3369  	tx, err := db.Begin()
  3370  	if err != nil {
  3371  		t.Fatal(err)
  3372  	}
  3373  	if err = tx.Rollback(); err != nil {
  3374  		t.Fatal(err)
  3375  	}
  3376  
  3377  	// Prepare
  3378  	db = manyErrBadConnSetup()
  3379  	defer closeDB(t, db)
  3380  	stmt, err := db.Prepare("SELECT|people|age,name|")
  3381  	if err != nil {
  3382  		t.Fatal(err)
  3383  	}
  3384  	if err = stmt.Close(); err != nil {
  3385  		t.Fatal(err)
  3386  	}
  3387  
  3388  	// Stmt.Exec
  3389  	db = manyErrBadConnSetup(func(db *DB) {
  3390  		stmt, err = db.Prepare("INSERT|people|name=Julia,age=19")
  3391  		if err != nil {
  3392  			t.Fatal(err)
  3393  		}
  3394  	})
  3395  	defer closeDB(t, db)
  3396  	_, err = stmt.Exec()
  3397  	if err != nil {
  3398  		t.Fatal(err)
  3399  	}
  3400  	if err = stmt.Close(); err != nil {
  3401  		t.Fatal(err)
  3402  	}
  3403  
  3404  	// Stmt.Query
  3405  	db = manyErrBadConnSetup(func(db *DB) {
  3406  		stmt, err = db.Prepare("SELECT|people|age,name|")
  3407  		if err != nil {
  3408  			t.Fatal(err)
  3409  		}
  3410  	})
  3411  	defer closeDB(t, db)
  3412  	rows, err = stmt.Query()
  3413  	if err != nil {
  3414  		t.Fatal(err)
  3415  	}
  3416  	if err = rows.Close(); err != nil {
  3417  		t.Fatal(err)
  3418  	}
  3419  	if err = stmt.Close(); err != nil {
  3420  		t.Fatal(err)
  3421  	}
  3422  
  3423  	// Conn
  3424  	db = manyErrBadConnSetup()
  3425  	defer closeDB(t, db)
  3426  	ctx := t.Context()
  3427  	conn, err := db.Conn(ctx)
  3428  	if err != nil {
  3429  		t.Fatal(err)
  3430  	}
  3431  	getFakeConn(conn.dc.ci).skipDirtySession = true
  3432  	err = conn.Close()
  3433  	if err != nil {
  3434  		t.Fatal(err)
  3435  	}
  3436  
  3437  	// Ping
  3438  	db = manyErrBadConnSetup()
  3439  	defer closeDB(t, db)
  3440  	err = db.PingContext(ctx)
  3441  	if err != nil {
  3442  		t.Fatal(err)
  3443  	}
  3444  }
  3445  
  3446  // Issue 34775: Ensure that a Tx cannot commit after a rollback.
  3447  func TestTxCannotCommitAfterRollback(t *testing.T) {
  3448  	testDatabase(t, testTxCannotCommitAfterRollback)
  3449  }
  3450  func testTxCannotCommitAfterRollback(t *testing.T, db *DB) {
  3451  	populate(t, db, "tx_status")
  3452  
  3453  	// First check query reporting is correct.
  3454  	var txStatus string
  3455  	err := db.QueryRow("SELECT|tx_status|tx_status|").Scan(&txStatus)
  3456  	if err != nil {
  3457  		t.Fatal(err)
  3458  	}
  3459  	if g, w := txStatus, "autocommit"; g != w {
  3460  		t.Fatalf("tx_status=%q, wanted %q", g, w)
  3461  	}
  3462  
  3463  	ctx, cancel := context.WithCancel(context.Background())
  3464  	defer cancel()
  3465  
  3466  	tx, err := db.BeginTx(ctx, nil)
  3467  	if err != nil {
  3468  		t.Fatal(err)
  3469  	}
  3470  
  3471  	// Ignore dirty session for this test.
  3472  	// A failing test should trigger the dirty session flag as well,
  3473  	// but that isn't exactly what this should test for.
  3474  	tx.txi.(*fakeTx).c.skipDirtySession = true
  3475  
  3476  	defer tx.Rollback()
  3477  
  3478  	err = tx.QueryRow("SELECT|tx_status|tx_status|").Scan(&txStatus)
  3479  	if err != nil {
  3480  		t.Fatal(err)
  3481  	}
  3482  	if g, w := txStatus, "transaction"; g != w {
  3483  		t.Fatalf("tx_status=%q, wanted %q", g, w)
  3484  	}
  3485  
  3486  	// 1. Begin a transaction.
  3487  	// 2. (A) Start a query, (B) begin Tx rollback through a ctx cancel.
  3488  	// 3. Check if 2.A has committed in Tx (pass) or outside of Tx (fail).
  3489  	sendQuery := make(chan struct{})
  3490  	// The Tx status is returned through the row results, ensure
  3491  	// that the rows results are not canceled.
  3492  	bypassRowsAwaitDone = true
  3493  	hookTxGrabConn = func() {
  3494  		cancel()
  3495  		<-sendQuery
  3496  	}
  3497  	rollbackHook = func() {
  3498  		close(sendQuery)
  3499  	}
  3500  	defer func() {
  3501  		hookTxGrabConn = nil
  3502  		rollbackHook = nil
  3503  		bypassRowsAwaitDone = false
  3504  	}()
  3505  
  3506  	err = tx.QueryRow("SELECT|tx_status|tx_status|").Scan(&txStatus)
  3507  	if err != nil {
  3508  		// A failure here would be expected if skipDirtySession was not set to true above.
  3509  		t.Fatal(err)
  3510  	}
  3511  	if g, w := txStatus, "transaction"; g != w {
  3512  		t.Fatalf("tx_status=%q, wanted %q", g, w)
  3513  	}
  3514  }
  3515  
  3516  // Issue 40985 transaction statement deadlock while context cancel.
  3517  func TestTxStmtDeadlock(t *testing.T) {
  3518  	testDatabase(t, testTxStmtDeadlock)
  3519  }
  3520  func testTxStmtDeadlock(t *testing.T, db *DB) {
  3521  	populate(t, db, "people")
  3522  
  3523  	ctx, cancel := context.WithCancel(context.Background())
  3524  	defer cancel()
  3525  	tx, err := db.BeginTx(ctx, nil)
  3526  	if err != nil {
  3527  		t.Fatal(err)
  3528  	}
  3529  
  3530  	stmt, err := tx.Prepare("SELECT|people|name,age|age=?")
  3531  	if err != nil {
  3532  		t.Fatal(err)
  3533  	}
  3534  	cancel()
  3535  	// Run number of stmt queries to reproduce deadlock from context cancel
  3536  	for i := 0; i < 1e3; i++ {
  3537  		// Encounter any close related errors (e.g. ErrTxDone, stmt is closed)
  3538  		// is expected due to context cancel.
  3539  		_, err = stmt.Query(1)
  3540  		if err != nil {
  3541  			break
  3542  		}
  3543  	}
  3544  	_ = tx.Rollback()
  3545  }
  3546  
  3547  func synctestSubtest(t *testing.T, name string, f func(t *testing.T)) {
  3548  	t.Run(name, func(t *testing.T) {
  3549  		synctest.Test(t, f)
  3550  	})
  3551  }
  3552  
  3553  // Issue32530 encounters an issue where a connection may
  3554  // expire right after it comes out of a used connection pool
  3555  // even when a new connection is requested.
  3556  func TestConnExpiresFreshOutOfPool(t *testing.T) {
  3557  	execCases := []struct {
  3558  		expired  bool
  3559  		badReset bool
  3560  	}{
  3561  		{false, false},
  3562  		{true, false},
  3563  		{false, true},
  3564  	}
  3565  
  3566  	for _, ec := range execCases {
  3567  		name := fmt.Sprintf("expired=%t,badReset=%t", ec.expired, ec.badReset)
  3568  		synctestSubtest(t, name, func(t *testing.T) {
  3569  			ctx := t.Context()
  3570  
  3571  			db := newTestDB(t, "magicquery")
  3572  
  3573  			db.SetMaxOpenConns(1)
  3574  
  3575  			db.clearAllConns(t)
  3576  
  3577  			db.SetMaxIdleConns(1)
  3578  			db.SetConnMaxLifetime(10 * time.Second)
  3579  
  3580  			conn, err := db.conn(ctx, alwaysNewConn)
  3581  			if err != nil {
  3582  				t.Fatal(err)
  3583  			}
  3584  
  3585  			afterPutConn := make(chan struct{})
  3586  
  3587  			go func() {
  3588  				defer close(afterPutConn)
  3589  
  3590  				conn, err := db.conn(ctx, alwaysNewConn)
  3591  				if err == nil {
  3592  					db.putConn(conn, err, false)
  3593  				} else {
  3594  					t.Errorf("db.conn: %v", err)
  3595  				}
  3596  			}()
  3597  			synctest.Wait()
  3598  
  3599  			if t.Failed() {
  3600  				return
  3601  			}
  3602  
  3603  			synctest.Sleep(11 * time.Second)
  3604  
  3605  			getFakeConn(conn.ci).stickyBad = ec.badReset
  3606  
  3607  			db.putConn(conn, err, true)
  3608  
  3609  			<-afterPutConn
  3610  		})
  3611  	}
  3612  }
  3613  
  3614  // TestIssue20575 ensures the Rows from query does not block
  3615  // closing a transaction. Ensure Rows is closed while closing a transaction.
  3616  func TestIssue20575(t *testing.T) {
  3617  	testDatabase(t, testIssue20575)
  3618  }
  3619  func testIssue20575(t *testing.T, db *DB) {
  3620  	populate(t, db, "people")
  3621  
  3622  	tx, err := db.Begin()
  3623  	if err != nil {
  3624  		t.Fatal(err)
  3625  	}
  3626  	ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
  3627  	defer cancel()
  3628  	_, err = tx.QueryContext(ctx, "SELECT|people|age,name|")
  3629  	if err != nil {
  3630  		t.Fatal(err)
  3631  	}
  3632  	// Do not close Rows from QueryContext.
  3633  	err = tx.Rollback()
  3634  	if err != nil {
  3635  		t.Fatal(err)
  3636  	}
  3637  	select {
  3638  	default:
  3639  	case <-ctx.Done():
  3640  		t.Fatal("timeout: failed to rollback query without closing rows:", ctx.Err())
  3641  	}
  3642  }
  3643  
  3644  // TestIssue20622 tests closing the transaction before rows is closed, requires
  3645  // the race detector to fail.
  3646  func TestIssue20622(t *testing.T) {
  3647  	testDatabase(t, testIssue20622)
  3648  }
  3649  func testIssue20622(t *testing.T, db *DB) {
  3650  	populate(t, db, "people")
  3651  
  3652  	ctx, cancel := context.WithCancel(context.Background())
  3653  	defer cancel()
  3654  
  3655  	tx, err := db.BeginTx(ctx, nil)
  3656  	if err != nil {
  3657  		t.Fatal(err)
  3658  	}
  3659  
  3660  	rows, err := tx.Query("SELECT|people|age,name|")
  3661  	if err != nil {
  3662  		t.Fatal(err)
  3663  	}
  3664  
  3665  	count := 0
  3666  	for rows.Next() {
  3667  		count++
  3668  		var age int
  3669  		var name string
  3670  		if err := rows.Scan(&age, &name); err != nil {
  3671  			t.Fatal("scan failed", err)
  3672  		}
  3673  
  3674  		if count == 1 {
  3675  			cancel()
  3676  		}
  3677  		time.Sleep(100 * time.Millisecond)
  3678  	}
  3679  	rows.Close()
  3680  	tx.Commit()
  3681  }
  3682  
  3683  // golang.org/issue/5718
  3684  func TestErrBadConnReconnect(t *testing.T) {
  3685  	testDatabase(t, testErrBadConnReconnect)
  3686  }
  3687  func testErrBadConnReconnect(t *testing.T, db *DB) {
  3688  	exec(t, db, "CREATE|t1|name=string,age=int32,dead=bool")
  3689  
  3690  	simulateBadConn := func(name string, hook *func() bool, op func() error) {
  3691  		broken, retried := false, false
  3692  		numOpen := db.numOpen
  3693  
  3694  		// simulate a broken connection on the first try
  3695  		*hook = func() bool {
  3696  			if !broken {
  3697  				broken = true
  3698  				return true
  3699  			}
  3700  			retried = true
  3701  			return false
  3702  		}
  3703  
  3704  		if err := op(); err != nil {
  3705  			t.Errorf(name+": %v", err)
  3706  			return
  3707  		}
  3708  
  3709  		if !broken || !retried {
  3710  			t.Error(name + ": Failed to simulate broken connection")
  3711  		}
  3712  		*hook = nil
  3713  
  3714  		if numOpen != db.numOpen {
  3715  			t.Errorf(name+": leaked %d connection(s)!", db.numOpen-numOpen)
  3716  			numOpen = db.numOpen
  3717  		}
  3718  	}
  3719  
  3720  	// db.Exec
  3721  	dbExec := func() error {
  3722  		_, err := db.Exec("INSERT|t1|name=?,age=?,dead=?", "Gordon", 3, true)
  3723  		return err
  3724  	}
  3725  	simulateBadConn("db.Exec prepare", &hookPrepareBadConn, dbExec)
  3726  	simulateBadConn("db.Exec exec", &hookExecBadConn, dbExec)
  3727  
  3728  	// db.Query
  3729  	dbQuery := func() error {
  3730  		rows, err := db.Query("SELECT|t1|age,name|")
  3731  		if err == nil {
  3732  			err = rows.Close()
  3733  		}
  3734  		return err
  3735  	}
  3736  	simulateBadConn("db.Query prepare", &hookPrepareBadConn, dbQuery)
  3737  	simulateBadConn("db.Query query", &hookQueryBadConn, dbQuery)
  3738  
  3739  	// db.Prepare
  3740  	simulateBadConn("db.Prepare", &hookPrepareBadConn, func() error {
  3741  		stmt, err := db.Prepare("INSERT|t1|name=?,age=?,dead=?")
  3742  		if err != nil {
  3743  			return err
  3744  		}
  3745  		stmt.Close()
  3746  		return nil
  3747  	})
  3748  
  3749  	// Provide a way to force a re-prepare of a statement on next execution
  3750  	forcePrepare := func(stmt *Stmt) {
  3751  		stmt.css = nil
  3752  	}
  3753  
  3754  	// stmt.Exec
  3755  	stmt1, err := db.Prepare("INSERT|t1|name=?,age=?,dead=?")
  3756  	if err != nil {
  3757  		t.Fatalf("prepare: %v", err)
  3758  	}
  3759  	defer stmt1.Close()
  3760  	// make sure we must prepare the stmt first
  3761  	forcePrepare(stmt1)
  3762  
  3763  	stmtExec := func() error {
  3764  		_, err := stmt1.Exec("Gopher", 3, false)
  3765  		return err
  3766  	}
  3767  	simulateBadConn("stmt.Exec prepare", &hookPrepareBadConn, stmtExec)
  3768  	simulateBadConn("stmt.Exec exec", &hookExecBadConn, stmtExec)
  3769  
  3770  	// stmt.Query
  3771  	stmt2, err := db.Prepare("SELECT|t1|age,name|")
  3772  	if err != nil {
  3773  		t.Fatalf("prepare: %v", err)
  3774  	}
  3775  	defer stmt2.Close()
  3776  	// make sure we must prepare the stmt first
  3777  	forcePrepare(stmt2)
  3778  
  3779  	stmtQuery := func() error {
  3780  		rows, err := stmt2.Query()
  3781  		if err == nil {
  3782  			err = rows.Close()
  3783  		}
  3784  		return err
  3785  	}
  3786  	simulateBadConn("stmt.Query prepare", &hookPrepareBadConn, stmtQuery)
  3787  	simulateBadConn("stmt.Query exec", &hookQueryBadConn, stmtQuery)
  3788  }
  3789  
  3790  // golang.org/issue/11264
  3791  func TestTxEndBadConn(t *testing.T) {
  3792  	testDatabase(t, testTxEndBadConn)
  3793  }
  3794  func testTxEndBadConn(t *testing.T, db *DB) {
  3795  	db.SetMaxIdleConns(0)
  3796  	exec(t, db, "CREATE|t1|name=string,age=int32,dead=bool")
  3797  	db.SetMaxIdleConns(1)
  3798  
  3799  	simulateBadConn := func(name string, hook *func() bool, op func() error) {
  3800  		broken := false
  3801  		numOpen := db.numOpen
  3802  
  3803  		*hook = func() bool {
  3804  			if !broken {
  3805  				broken = true
  3806  			}
  3807  			return broken
  3808  		}
  3809  
  3810  		if err := op(); !errors.Is(err, driver.ErrBadConn) {
  3811  			t.Errorf(name+": %v", err)
  3812  			return
  3813  		}
  3814  
  3815  		if !broken {
  3816  			t.Error(name + ": Failed to simulate broken connection")
  3817  		}
  3818  		*hook = nil
  3819  
  3820  		if numOpen != db.numOpen {
  3821  			t.Errorf(name+": leaked %d connection(s)!", db.numOpen-numOpen)
  3822  		}
  3823  	}
  3824  
  3825  	// db.Exec
  3826  	dbExec := func(endTx func(tx *Tx) error) func() error {
  3827  		return func() error {
  3828  			tx, err := db.Begin()
  3829  			if err != nil {
  3830  				return err
  3831  			}
  3832  			_, err = tx.Exec("INSERT|t1|name=?,age=?,dead=?", "Gordon", 3, true)
  3833  			if err != nil {
  3834  				return err
  3835  			}
  3836  			return endTx(tx)
  3837  		}
  3838  	}
  3839  	simulateBadConn("db.Tx.Exec commit", &hookCommitBadConn, dbExec((*Tx).Commit))
  3840  	simulateBadConn("db.Tx.Exec rollback", &hookRollbackBadConn, dbExec((*Tx).Rollback))
  3841  
  3842  	// db.Query
  3843  	dbQuery := func(endTx func(tx *Tx) error) func() error {
  3844  		return func() error {
  3845  			tx, err := db.Begin()
  3846  			if err != nil {
  3847  				return err
  3848  			}
  3849  			rows, err := tx.Query("SELECT|t1|age,name|")
  3850  			if err == nil {
  3851  				err = rows.Close()
  3852  			} else {
  3853  				return err
  3854  			}
  3855  			return endTx(tx)
  3856  		}
  3857  	}
  3858  	simulateBadConn("db.Tx.Query commit", &hookCommitBadConn, dbQuery((*Tx).Commit))
  3859  	simulateBadConn("db.Tx.Query rollback", &hookRollbackBadConn, dbQuery((*Tx).Rollback))
  3860  }
  3861  
  3862  type concurrentTest interface {
  3863  	init(t testing.TB, db *DB)
  3864  	finish(t testing.TB)
  3865  	test(t testing.TB) error
  3866  }
  3867  
  3868  type concurrentDBQueryTest struct {
  3869  	db *DB
  3870  }
  3871  
  3872  func (c *concurrentDBQueryTest) init(t testing.TB, db *DB) {
  3873  	c.db = db
  3874  }
  3875  
  3876  func (c *concurrentDBQueryTest) finish(t testing.TB) {
  3877  	c.db = nil
  3878  }
  3879  
  3880  func (c *concurrentDBQueryTest) test(t testing.TB) error {
  3881  	rows, err := c.db.Query("SELECT|people|name|")
  3882  	if err != nil {
  3883  		t.Error(err)
  3884  		return err
  3885  	}
  3886  	var name string
  3887  	for rows.Next() {
  3888  		rows.Scan(&name)
  3889  	}
  3890  	rows.Close()
  3891  	return nil
  3892  }
  3893  
  3894  type concurrentDBExecTest struct {
  3895  	db *DB
  3896  }
  3897  
  3898  func (c *concurrentDBExecTest) init(t testing.TB, db *DB) {
  3899  	c.db = db
  3900  }
  3901  
  3902  func (c *concurrentDBExecTest) finish(t testing.TB) {
  3903  	c.db = nil
  3904  }
  3905  
  3906  func (c *concurrentDBExecTest) test(t testing.TB) error {
  3907  	_, err := c.db.Exec("NOSERT|people|name=Chris,age=?,photo=CPHOTO,bdate=?", 3, chrisBirthday)
  3908  	if err != nil {
  3909  		t.Error(err)
  3910  		return err
  3911  	}
  3912  	return nil
  3913  }
  3914  
  3915  type concurrentStmtQueryTest struct {
  3916  	db   *DB
  3917  	stmt *Stmt
  3918  }
  3919  
  3920  func (c *concurrentStmtQueryTest) init(t testing.TB, db *DB) {
  3921  	c.db = db
  3922  	var err error
  3923  	c.stmt, err = db.Prepare("SELECT|people|name|")
  3924  	if err != nil {
  3925  		t.Fatal(err)
  3926  	}
  3927  }
  3928  
  3929  func (c *concurrentStmtQueryTest) finish(t testing.TB) {
  3930  	if c.stmt != nil {
  3931  		c.stmt.Close()
  3932  		c.stmt = nil
  3933  	}
  3934  	c.db = nil
  3935  }
  3936  
  3937  func (c *concurrentStmtQueryTest) test(t testing.TB) error {
  3938  	rows, err := c.stmt.Query()
  3939  	if err != nil {
  3940  		t.Errorf("error on query:  %v", err)
  3941  		return err
  3942  	}
  3943  
  3944  	var name string
  3945  	for rows.Next() {
  3946  		rows.Scan(&name)
  3947  	}
  3948  	rows.Close()
  3949  	return nil
  3950  }
  3951  
  3952  type concurrentStmtExecTest struct {
  3953  	db   *DB
  3954  	stmt *Stmt
  3955  }
  3956  
  3957  func (c *concurrentStmtExecTest) init(t testing.TB, db *DB) {
  3958  	c.db = db
  3959  	var err error
  3960  	c.stmt, err = db.Prepare("NOSERT|people|name=Chris,age=?,photo=CPHOTO,bdate=?")
  3961  	if err != nil {
  3962  		t.Fatal(err)
  3963  	}
  3964  }
  3965  
  3966  func (c *concurrentStmtExecTest) finish(t testing.TB) {
  3967  	if c.stmt != nil {
  3968  		c.stmt.Close()
  3969  		c.stmt = nil
  3970  	}
  3971  	c.db = nil
  3972  }
  3973  
  3974  func (c *concurrentStmtExecTest) test(t testing.TB) error {
  3975  	_, err := c.stmt.Exec(3, chrisBirthday)
  3976  	if err != nil {
  3977  		t.Errorf("error on exec:  %v", err)
  3978  		return err
  3979  	}
  3980  	return nil
  3981  }
  3982  
  3983  type concurrentTxQueryTest struct {
  3984  	db *DB
  3985  	tx *Tx
  3986  }
  3987  
  3988  func (c *concurrentTxQueryTest) init(t testing.TB, db *DB) {
  3989  	c.db = db
  3990  	var err error
  3991  	c.tx, err = c.db.Begin()
  3992  	if err != nil {
  3993  		t.Fatal(err)
  3994  	}
  3995  }
  3996  
  3997  func (c *concurrentTxQueryTest) finish(t testing.TB) {
  3998  	if c.tx != nil {
  3999  		c.tx.Rollback()
  4000  		c.tx = nil
  4001  	}
  4002  	c.db = nil
  4003  }
  4004  
  4005  func (c *concurrentTxQueryTest) test(t testing.TB) error {
  4006  	rows, err := c.db.Query("SELECT|people|name|")
  4007  	if err != nil {
  4008  		t.Error(err)
  4009  		return err
  4010  	}
  4011  	var name string
  4012  	for rows.Next() {
  4013  		rows.Scan(&name)
  4014  	}
  4015  	rows.Close()
  4016  	return nil
  4017  }
  4018  
  4019  type concurrentTxExecTest struct {
  4020  	db *DB
  4021  	tx *Tx
  4022  }
  4023  
  4024  func (c *concurrentTxExecTest) init(t testing.TB, db *DB) {
  4025  	c.db = db
  4026  	var err error
  4027  	c.tx, err = c.db.Begin()
  4028  	if err != nil {
  4029  		t.Fatal(err)
  4030  	}
  4031  }
  4032  
  4033  func (c *concurrentTxExecTest) finish(t testing.TB) {
  4034  	if c.tx != nil {
  4035  		c.tx.Rollback()
  4036  		c.tx = nil
  4037  	}
  4038  	c.db = nil
  4039  }
  4040  
  4041  func (c *concurrentTxExecTest) test(t testing.TB) error {
  4042  	_, err := c.tx.Exec("NOSERT|people|name=Chris,age=?,photo=CPHOTO,bdate=?", 3, chrisBirthday)
  4043  	if err != nil {
  4044  		t.Error(err)
  4045  		return err
  4046  	}
  4047  	return nil
  4048  }
  4049  
  4050  type concurrentTxStmtQueryTest struct {
  4051  	db   *DB
  4052  	tx   *Tx
  4053  	stmt *Stmt
  4054  }
  4055  
  4056  func (c *concurrentTxStmtQueryTest) init(t testing.TB, db *DB) {
  4057  	c.db = db
  4058  	var err error
  4059  	c.tx, err = c.db.Begin()
  4060  	if err != nil {
  4061  		t.Fatal(err)
  4062  	}
  4063  	c.stmt, err = c.tx.Prepare("SELECT|people|name|")
  4064  	if err != nil {
  4065  		t.Fatal(err)
  4066  	}
  4067  }
  4068  
  4069  func (c *concurrentTxStmtQueryTest) finish(t testing.TB) {
  4070  	if c.stmt != nil {
  4071  		c.stmt.Close()
  4072  		c.stmt = nil
  4073  	}
  4074  	if c.tx != nil {
  4075  		c.tx.Rollback()
  4076  		c.tx = nil
  4077  	}
  4078  	c.db = nil
  4079  }
  4080  
  4081  func (c *concurrentTxStmtQueryTest) test(t testing.TB) error {
  4082  	rows, err := c.stmt.Query()
  4083  	if err != nil {
  4084  		t.Errorf("error on query:  %v", err)
  4085  		return err
  4086  	}
  4087  
  4088  	var name string
  4089  	for rows.Next() {
  4090  		rows.Scan(&name)
  4091  	}
  4092  	rows.Close()
  4093  	return nil
  4094  }
  4095  
  4096  type concurrentTxStmtExecTest struct {
  4097  	db   *DB
  4098  	tx   *Tx
  4099  	stmt *Stmt
  4100  }
  4101  
  4102  func (c *concurrentTxStmtExecTest) init(t testing.TB, db *DB) {
  4103  	c.db = db
  4104  	var err error
  4105  	c.tx, err = c.db.Begin()
  4106  	if err != nil {
  4107  		t.Fatal(err)
  4108  	}
  4109  	c.stmt, err = c.tx.Prepare("NOSERT|people|name=Chris,age=?,photo=CPHOTO,bdate=?")
  4110  	if err != nil {
  4111  		t.Fatal(err)
  4112  	}
  4113  }
  4114  
  4115  func (c *concurrentTxStmtExecTest) finish(t testing.TB) {
  4116  	if c.stmt != nil {
  4117  		c.stmt.Close()
  4118  		c.stmt = nil
  4119  	}
  4120  	if c.tx != nil {
  4121  		c.tx.Rollback()
  4122  		c.tx = nil
  4123  	}
  4124  	c.db = nil
  4125  }
  4126  
  4127  func (c *concurrentTxStmtExecTest) test(t testing.TB) error {
  4128  	_, err := c.stmt.Exec(3, chrisBirthday)
  4129  	if err != nil {
  4130  		t.Errorf("error on exec:  %v", err)
  4131  		return err
  4132  	}
  4133  	return nil
  4134  }
  4135  
  4136  type concurrentRandomTest struct {
  4137  	tests []concurrentTest
  4138  }
  4139  
  4140  func (c *concurrentRandomTest) init(t testing.TB, db *DB) {
  4141  	c.tests = []concurrentTest{
  4142  		new(concurrentDBQueryTest),
  4143  		new(concurrentDBExecTest),
  4144  		new(concurrentStmtQueryTest),
  4145  		new(concurrentStmtExecTest),
  4146  		new(concurrentTxQueryTest),
  4147  		new(concurrentTxExecTest),
  4148  		new(concurrentTxStmtQueryTest),
  4149  		new(concurrentTxStmtExecTest),
  4150  	}
  4151  	for _, ct := range c.tests {
  4152  		ct.init(t, db)
  4153  	}
  4154  }
  4155  
  4156  func (c *concurrentRandomTest) finish(t testing.TB) {
  4157  	for _, ct := range c.tests {
  4158  		ct.finish(t)
  4159  	}
  4160  }
  4161  
  4162  func (c *concurrentRandomTest) test(t testing.TB) error {
  4163  	ct := c.tests[rand.Intn(len(c.tests))]
  4164  	return ct.test(t)
  4165  }
  4166  
  4167  func doConcurrentTest(t testing.TB, ct concurrentTest) {
  4168  	maxProcs, numReqs := 1, 500
  4169  	if testing.Short() {
  4170  		maxProcs, numReqs = 4, 50
  4171  	}
  4172  	defer runtime.GOMAXPROCS(runtime.GOMAXPROCS(maxProcs))
  4173  
  4174  	db := newTestDB(t, "people")
  4175  	defer closeDB(t, db)
  4176  
  4177  	ct.init(t, db)
  4178  	defer ct.finish(t)
  4179  
  4180  	var wg sync.WaitGroup
  4181  	wg.Add(numReqs)
  4182  
  4183  	reqs := make(chan bool)
  4184  	defer close(reqs)
  4185  
  4186  	for i := 0; i < maxProcs*2; i++ {
  4187  		go func() {
  4188  			for range reqs {
  4189  				err := ct.test(t)
  4190  				if err != nil {
  4191  					wg.Done()
  4192  					continue
  4193  				}
  4194  				wg.Done()
  4195  			}
  4196  		}()
  4197  	}
  4198  
  4199  	for i := 0; i < numReqs; i++ {
  4200  		reqs <- true
  4201  	}
  4202  
  4203  	wg.Wait()
  4204  }
  4205  
  4206  func TestIssue6081(t *testing.T) {
  4207  	testDatabase(t, testIssue6081)
  4208  }
  4209  func testIssue6081(t *testing.T, db *DB) {
  4210  	populate(t, db, "people")
  4211  
  4212  	drv := db.Driver().(*fakeDriver)
  4213  	drv.mu.Lock()
  4214  	opens0 := drv.openCount
  4215  	closes0 := drv.closeCount
  4216  	drv.mu.Unlock()
  4217  
  4218  	stmt, err := db.Prepare("SELECT|people|name|")
  4219  	if err != nil {
  4220  		t.Fatal(err)
  4221  	}
  4222  	setRowsCloseHook(func(rows *Rows, err *error) {
  4223  		*err = driver.ErrBadConn
  4224  	})
  4225  	defer setRowsCloseHook(nil)
  4226  	for i := 0; i < 10; i++ {
  4227  		rows, err := stmt.Query()
  4228  		if err != nil {
  4229  			t.Fatal(err)
  4230  		}
  4231  		rows.Close()
  4232  	}
  4233  	if n := len(stmt.css); n > 1 {
  4234  		t.Errorf("len(css slice) = %d; want <= 1", n)
  4235  	}
  4236  	stmt.Close()
  4237  	if n := len(stmt.css); n != 0 {
  4238  		t.Errorf("len(css slice) after Close = %d; want 0", n)
  4239  	}
  4240  
  4241  	drv.mu.Lock()
  4242  	opens := drv.openCount - opens0
  4243  	closes := drv.closeCount - closes0
  4244  	drv.mu.Unlock()
  4245  	if opens < 9 {
  4246  		t.Errorf("opens = %d; want >= 9", opens)
  4247  	}
  4248  	if closes < 9 {
  4249  		t.Errorf("closes = %d; want >= 9", closes)
  4250  	}
  4251  }
  4252  
  4253  // TestIssue18429 attempts to stress rolling back the transaction from a
  4254  // context cancel while simultaneously calling Tx.Rollback. Rolling back from a
  4255  // context happens concurrently so tx.rollback and tx.Commit must guard against
  4256  // double entry.
  4257  //
  4258  // In the test, a context is canceled while the query is in process so
  4259  // the internal rollback will run concurrently with the explicitly called
  4260  // Tx.Rollback.
  4261  //
  4262  // The addition of calling rows.Next also tests
  4263  // Issue 21117.
  4264  func TestIssue18429(t *testing.T) {
  4265  	testDatabase(t, testIssue18429)
  4266  }
  4267  func testIssue18429(t *testing.T, db *DB) {
  4268  	populate(t, db, "people")
  4269  
  4270  	ctx := context.Background()
  4271  	sem := make(chan bool, 20)
  4272  	var wg sync.WaitGroup
  4273  
  4274  	const milliWait = 30
  4275  
  4276  	for i := 0; i < 100; i++ {
  4277  		sem <- true
  4278  		wg.Add(1)
  4279  		go func() {
  4280  			defer func() {
  4281  				<-sem
  4282  				wg.Done()
  4283  			}()
  4284  			qwait := (time.Duration(rand.Intn(milliWait)) * time.Millisecond).String()
  4285  
  4286  			ctx, cancel := context.WithTimeout(ctx, time.Duration(rand.Intn(milliWait))*time.Millisecond)
  4287  			defer cancel()
  4288  
  4289  			tx, err := db.BeginTx(ctx, nil)
  4290  			if err != nil {
  4291  				return
  4292  			}
  4293  			// This is expected to give a cancel error most, but not all the time.
  4294  			// Test failure will happen with a panic or other race condition being
  4295  			// reported.
  4296  			rows, _ := tx.QueryContext(ctx, "WAIT|"+qwait+"|SELECT|people|name|")
  4297  			if rows != nil {
  4298  				var name string
  4299  				// Call Next to test Issue 21117 and check for races.
  4300  				for rows.Next() {
  4301  					// Scan the buffer so it is read and checked for races.
  4302  					rows.Scan(&name)
  4303  				}
  4304  				rows.Close()
  4305  			}
  4306  			// This call will race with the context cancel rollback to complete
  4307  			// if the rollback itself isn't guarded.
  4308  			tx.Rollback()
  4309  		}()
  4310  	}
  4311  	wg.Wait()
  4312  }
  4313  
  4314  // TestIssue20160 attempts to test a short context life on a stmt Query.
  4315  func TestIssue20160(t *testing.T) {
  4316  	testDatabase(t, testIssue20160)
  4317  }
  4318  func testIssue20160(t *testing.T, db *DB) {
  4319  	populate(t, db, "people")
  4320  
  4321  	ctx := context.Background()
  4322  	sem := make(chan bool, 20)
  4323  	var wg sync.WaitGroup
  4324  
  4325  	const milliWait = 30
  4326  
  4327  	stmt, err := db.PrepareContext(ctx, "SELECT|people|name|")
  4328  	if err != nil {
  4329  		t.Fatal(err)
  4330  	}
  4331  	defer stmt.Close()
  4332  
  4333  	for i := 0; i < 100; i++ {
  4334  		sem <- true
  4335  		wg.Add(1)
  4336  		go func() {
  4337  			defer func() {
  4338  				<-sem
  4339  				wg.Done()
  4340  			}()
  4341  			ctx, cancel := context.WithTimeout(ctx, time.Duration(rand.Intn(milliWait))*time.Millisecond)
  4342  			defer cancel()
  4343  
  4344  			// This is expected to give a cancel error most, but not all the time.
  4345  			// Test failure will happen with a panic or other race condition being
  4346  			// reported.
  4347  			rows, _ := stmt.QueryContext(ctx)
  4348  			if rows != nil {
  4349  				rows.Close()
  4350  			}
  4351  		}()
  4352  	}
  4353  	wg.Wait()
  4354  }
  4355  
  4356  // TestIssue18719 closes the context right before use. The sql.driverConn
  4357  // will nil out the ci on close in a lock, but if another process uses it right after
  4358  // it will panic with on the nil ref.
  4359  //
  4360  // See https://golang.org/cl/35550 .
  4361  func TestIssue18719(t *testing.T) {
  4362  	testDatabase(t, testIssue18719, requireFeature("BeginTx"))
  4363  }
  4364  func testIssue18719(t *testing.T, db *DB) {
  4365  	populate(t, db, "people")
  4366  
  4367  	ctx, cancel := context.WithCancel(context.Background())
  4368  	defer cancel()
  4369  
  4370  	tx, err := db.BeginTx(ctx, nil)
  4371  	if err != nil {
  4372  		t.Fatal(err)
  4373  	}
  4374  
  4375  	hookTxGrabConn = func() {
  4376  		cancel()
  4377  		synctest.Wait()
  4378  		if !tx.isDone() {
  4379  			t.Errorf("tx is not done")
  4380  		}
  4381  	}
  4382  	defer func() { hookTxGrabConn = nil }()
  4383  
  4384  	// This call will grab the connection and cancel the context
  4385  	// after it has done so. Code after must deal with the canceled state.
  4386  	_, err = tx.QueryContext(ctx, "SELECT|people|name|")
  4387  	if err != nil {
  4388  		t.Fatalf("expected error %v but got %v", nil, err)
  4389  	}
  4390  
  4391  	// Rows may be ignored because it will be closed when the context is canceled.
  4392  
  4393  	// Do not explicitly rollback. The rollback will happen from the
  4394  	// canceled context.
  4395  
  4396  	cancel()
  4397  }
  4398  
  4399  func TestIssue20647(t *testing.T) {
  4400  	testDatabase(t, testIssue20647)
  4401  }
  4402  func testIssue20647(t *testing.T, db *DB) {
  4403  	populate(t, db, "people")
  4404  
  4405  	ctx := t.Context()
  4406  
  4407  	conn, err := db.Conn(ctx)
  4408  	if err != nil {
  4409  		t.Fatal(err)
  4410  	}
  4411  	getFakeConn(conn.dc.ci).skipDirtySession = true
  4412  	defer conn.Close()
  4413  
  4414  	stmt, err := conn.PrepareContext(ctx, "SELECT|people|name|")
  4415  	if err != nil {
  4416  		t.Fatal(err)
  4417  	}
  4418  	defer stmt.Close()
  4419  
  4420  	rows1, err := stmt.QueryContext(ctx)
  4421  	if err != nil {
  4422  		t.Fatal("rows1", err)
  4423  	}
  4424  	defer rows1.Close()
  4425  
  4426  	rows2, err := stmt.QueryContext(ctx)
  4427  	if err != nil {
  4428  		t.Fatal("rows2", err)
  4429  	}
  4430  	defer rows2.Close()
  4431  
  4432  	if rows1.dc != rows2.dc {
  4433  		t.Fatal("stmt prepared on Conn does not use same connection")
  4434  	}
  4435  }
  4436  
  4437  func TestConcurrency(t *testing.T) {
  4438  	list := []struct {
  4439  		name string
  4440  		ct   concurrentTest
  4441  	}{
  4442  		{"Query", new(concurrentDBQueryTest)},
  4443  		{"Exec", new(concurrentDBExecTest)},
  4444  		{"StmtQuery", new(concurrentStmtQueryTest)},
  4445  		{"StmtExec", new(concurrentStmtExecTest)},
  4446  		{"TxQuery", new(concurrentTxQueryTest)},
  4447  		{"TxExec", new(concurrentTxExecTest)},
  4448  		{"TxStmtQuery", new(concurrentTxStmtQueryTest)},
  4449  		{"TxStmtExec", new(concurrentTxStmtExecTest)},
  4450  		{"Random", new(concurrentRandomTest)},
  4451  	}
  4452  	for _, item := range list {
  4453  		synctestSubtest(t, item.name, func(t *testing.T) {
  4454  			doConcurrentTest(t, item.ct)
  4455  		})
  4456  	}
  4457  }
  4458  
  4459  func TestConnectionLeak(t *testing.T) {
  4460  	testDatabase(t, testConnectionLeak)
  4461  }
  4462  func testConnectionLeak(t *testing.T, db *DB) {
  4463  	populate(t, db, "people")
  4464  	// Start by opening defaultMaxIdleConns
  4465  	rows := make([]*Rows, defaultMaxIdleConns)
  4466  	// We need to SetMaxOpenConns > MaxIdleConns, so the DB can open
  4467  	// a new connection and we can fill the idle queue with the released
  4468  	// connections.
  4469  	db.SetMaxOpenConns(len(rows) + 1)
  4470  	for ii := range rows {
  4471  		r, err := db.Query("SELECT|people|name|")
  4472  		if err != nil {
  4473  			t.Fatal(err)
  4474  		}
  4475  		r.Next()
  4476  		if err := r.Err(); err != nil {
  4477  			t.Fatal(err)
  4478  		}
  4479  		rows[ii] = r
  4480  	}
  4481  	// Now we have defaultMaxIdleConns busy connections. Open
  4482  	// a new one, but wait until the busy connections are released
  4483  	// before returning control to DB.
  4484  	drv := db.Driver().(*fakeDriver)
  4485  	drv.waitCh = make(chan struct{}, 1)
  4486  	drv.waitingCh = make(chan struct{}, 1)
  4487  	var wg sync.WaitGroup
  4488  	wg.Add(1)
  4489  	go func() {
  4490  		r, err := db.Query("SELECT|people|name|")
  4491  		if err != nil {
  4492  			t.Error(err)
  4493  			return
  4494  		}
  4495  		r.Close()
  4496  		wg.Done()
  4497  	}()
  4498  	// Wait until the goroutine we've just created has started waiting.
  4499  	<-drv.waitingCh
  4500  	// Now close the busy connections. This provides a connection for
  4501  	// the blocked goroutine and then fills up the idle queue.
  4502  	for _, v := range rows {
  4503  		v.Close()
  4504  	}
  4505  	// At this point we give the new connection to DB. This connection is
  4506  	// now useless, since the idle queue is full and there are no pending
  4507  	// requests. DB should deal with this situation without leaking the
  4508  	// connection.
  4509  	drv.waitCh <- struct{}{}
  4510  	wg.Wait()
  4511  }
  4512  
  4513  func TestStatsMaxIdleClosedZero(t *testing.T) {
  4514  	testDatabase(t, testStatsMaxIdleClosedZero)
  4515  }
  4516  func testStatsMaxIdleClosedZero(t *testing.T, db *DB) {
  4517  	populate(t, db, "people")
  4518  
  4519  	db.SetMaxOpenConns(1)
  4520  	db.SetMaxIdleConns(1)
  4521  	db.SetConnMaxLifetime(0)
  4522  
  4523  	preMaxIdleClosed := db.Stats().MaxIdleClosed
  4524  
  4525  	for i := 0; i < 10; i++ {
  4526  		rows, err := db.Query("SELECT|people|name|")
  4527  		if err != nil {
  4528  			t.Fatal(err)
  4529  		}
  4530  		rows.Close()
  4531  	}
  4532  
  4533  	st := db.Stats()
  4534  	maxIdleClosed := st.MaxIdleClosed - preMaxIdleClosed
  4535  	t.Logf("MaxIdleClosed: %d", maxIdleClosed)
  4536  	if maxIdleClosed != 0 {
  4537  		t.Fatal("expected 0 max idle closed conns, got: ", maxIdleClosed)
  4538  	}
  4539  }
  4540  
  4541  func TestStatsMaxIdleClosedTen(t *testing.T) {
  4542  	testDatabase(t, testStatsMaxIdleClosedTen)
  4543  }
  4544  func testStatsMaxIdleClosedTen(t *testing.T, db *DB) {
  4545  	populate(t, db, "people")
  4546  
  4547  	db.SetMaxOpenConns(1)
  4548  	db.SetMaxIdleConns(0)
  4549  	db.SetConnMaxLifetime(0)
  4550  
  4551  	preMaxIdleClosed := db.Stats().MaxIdleClosed
  4552  
  4553  	for i := 0; i < 10; i++ {
  4554  		rows, err := db.Query("SELECT|people|name|")
  4555  		if err != nil {
  4556  			t.Fatal(err)
  4557  		}
  4558  		rows.Close()
  4559  	}
  4560  
  4561  	st := db.Stats()
  4562  	maxIdleClosed := st.MaxIdleClosed - preMaxIdleClosed
  4563  	t.Logf("MaxIdleClosed: %d", maxIdleClosed)
  4564  	if maxIdleClosed != 10 {
  4565  		t.Fatal("expected 0 max idle closed conns, got: ", maxIdleClosed)
  4566  	}
  4567  }
  4568  
  4569  // testUseConns uses count concurrent connections with 1 nanosecond apart.
  4570  func testUseConns(t *testing.T, count int, db *DB) {
  4571  	conns := make([]*Conn, count)
  4572  	ctx := context.Background()
  4573  	for i := range conns {
  4574  		time.Sleep(1 * time.Nanosecond)
  4575  		c, err := db.Conn(ctx)
  4576  		if err != nil {
  4577  			t.Error(err)
  4578  		}
  4579  		conns[i] = c
  4580  	}
  4581  
  4582  	for i := len(conns) - 1; i >= 0; i-- {
  4583  		time.Sleep(1 * time.Nanosecond)
  4584  		if err := conns[i].Close(); err != nil {
  4585  			t.Error(err)
  4586  		}
  4587  	}
  4588  }
  4589  
  4590  func TestMaxIdleTime(t *testing.T) {
  4591  	usedConns := 5
  4592  	reusedConns := 2
  4593  	list := []struct {
  4594  		wantMaxIdleTime   time.Duration
  4595  		wantMaxLifetime   time.Duration
  4596  		wantNextCheck     time.Duration
  4597  		wantIdleClosed    int64
  4598  		wantMaxIdleClosed int64
  4599  		timeOffset        time.Duration
  4600  		secondTimeOffset  time.Duration
  4601  	}{
  4602  		{
  4603  			time.Millisecond,
  4604  			0,
  4605  			time.Millisecond - time.Nanosecond,
  4606  			int64(usedConns - reusedConns),
  4607  			int64(usedConns - reusedConns),
  4608  			10 * time.Millisecond,
  4609  			0,
  4610  		},
  4611  		{
  4612  			// Want to close some connections via max idle time and one by max lifetime.
  4613  			time.Millisecond,
  4614  			// nowFunc() - MaxLifetime should be 1 * time.Nanosecond in connectionCleanerRunLocked.
  4615  			// This guarantees that first opened connection is to be closed.
  4616  			// Thus it is timeOffset + secondTimeOffset + 3 (+2 for Close while reusing conns and +1 for Conn).
  4617  			10*time.Millisecond + 100*time.Nanosecond + 3*time.Nanosecond,
  4618  			time.Nanosecond,
  4619  			// Closed all not reused connections and extra one by max lifetime.
  4620  			int64(usedConns - reusedConns + 1),
  4621  			int64(usedConns - reusedConns),
  4622  			10 * time.Millisecond,
  4623  			// Add second offset because otherwise connections are expired via max lifetime in Close.
  4624  			100 * time.Nanosecond,
  4625  		},
  4626  		{
  4627  			time.Hour,
  4628  			0,
  4629  			time.Second,
  4630  			0,
  4631  			0,
  4632  			10 * time.Millisecond,
  4633  			0},
  4634  	}
  4635  	for _, item := range list {
  4636  		synctestSubtest(t, fmt.Sprintf("%v", item.wantMaxIdleTime), func(t *testing.T) {
  4637  			startTime := time.Now()
  4638  			db := newTestDB(t, "people")
  4639  			defer closeDB(t, db)
  4640  
  4641  			db.SetMaxOpenConns(usedConns)
  4642  			db.SetMaxIdleConns(usedConns)
  4643  			db.SetConnMaxIdleTime(item.wantMaxIdleTime)
  4644  			db.SetConnMaxLifetime(item.wantMaxLifetime)
  4645  
  4646  			preMaxIdleClosed := db.Stats().MaxIdleTimeClosed
  4647  
  4648  			// Busy usedConns.
  4649  			testUseConns(t, usedConns, db)
  4650  
  4651  			time.Sleep(time.Until(startTime.Add(item.timeOffset)))
  4652  
  4653  			// Reuse connections which should never be considered idle
  4654  			// and exercises the sorting for issue 39471.
  4655  			testUseConns(t, reusedConns, db)
  4656  
  4657  			time.Sleep(item.secondTimeOffset)
  4658  
  4659  			db.mu.Lock()
  4660  			nc, closing := db.connectionCleanerRunLocked(time.Second)
  4661  			if nc != item.wantNextCheck {
  4662  				t.Errorf("got %v; want %v next check duration", nc, item.wantNextCheck)
  4663  			}
  4664  
  4665  			// Validate freeConn order.
  4666  			var last time.Time
  4667  			for _, c := range db.freeConn {
  4668  				if last.After(c.returnedAt) {
  4669  					t.Error("freeConn is not ordered by returnedAt")
  4670  					break
  4671  				}
  4672  				last = c.returnedAt
  4673  			}
  4674  
  4675  			db.mu.Unlock()
  4676  			for _, c := range closing {
  4677  				c.Close()
  4678  			}
  4679  			if g, w := int64(len(closing)), item.wantIdleClosed; g != w {
  4680  				t.Errorf("got: %d; want %d closed conns", g, w)
  4681  			}
  4682  
  4683  			st := db.Stats()
  4684  			maxIdleClosed := st.MaxIdleTimeClosed - preMaxIdleClosed
  4685  			if g, w := maxIdleClosed, item.wantMaxIdleClosed; g != w {
  4686  				t.Errorf("got: %d; want %d max idle closed conns", g, w)
  4687  			}
  4688  		})
  4689  	}
  4690  }
  4691  
  4692  type nvcDriver struct {
  4693  	fakeDriver
  4694  	skipNamedValueCheck bool
  4695  }
  4696  
  4697  func (d *nvcDriver) Open(dsn string) (driver.Conn, error) {
  4698  	c, err := d.fakeDriver.Open(dsn)
  4699  	fc := getFakeConn(c)
  4700  	fc.db.allowAny = true
  4701  	return &nvcConn{fc, d.skipNamedValueCheck}, err
  4702  }
  4703  
  4704  type nvcConn struct {
  4705  	*fakeConn
  4706  	skipNamedValueCheck bool
  4707  }
  4708  
  4709  type decimalInt struct {
  4710  	value int
  4711  }
  4712  
  4713  type doNotInclude struct{}
  4714  
  4715  var _ driver.NamedValueChecker = &nvcConn{}
  4716  
  4717  func (c *nvcConn) CheckNamedValue(nv *driver.NamedValue) error {
  4718  	if c.skipNamedValueCheck {
  4719  		return driver.ErrSkip
  4720  	}
  4721  	switch v := nv.Value.(type) {
  4722  	default:
  4723  		return driver.ErrSkip
  4724  	case Out:
  4725  		switch ov := v.Dest.(type) {
  4726  		default:
  4727  			return errors.New("unknown NameValueCheck OUTPUT type")
  4728  		case *string:
  4729  			*ov = "from-server"
  4730  			nv.Value = "OUT:*string"
  4731  		}
  4732  		return nil
  4733  	case decimalInt, []int64:
  4734  		return nil
  4735  	case doNotInclude:
  4736  		return driver.ErrRemoveArgument
  4737  	}
  4738  }
  4739  
  4740  func TestNamedValueChecker(t *testing.T) {
  4741  	synctest.Test(t, testNamedValueChecker)
  4742  }
  4743  func testNamedValueChecker(t *testing.T) {
  4744  	Register("NamedValueCheck", &nvcDriver{})
  4745  	db, err := Open("NamedValueCheck", "")
  4746  	if err != nil {
  4747  		t.Fatal(err)
  4748  	}
  4749  	defer db.Close()
  4750  
  4751  	ctx := t.Context()
  4752  	_, err = db.ExecContext(ctx, "WIPE")
  4753  	if err != nil {
  4754  		t.Fatal("exec wipe", err)
  4755  	}
  4756  
  4757  	_, err = db.ExecContext(ctx, "CREATE|keys|dec1=any,str1=string,out1=string,array1=any")
  4758  	if err != nil {
  4759  		t.Fatal("exec create", err)
  4760  	}
  4761  
  4762  	o1 := ""
  4763  	_, 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{})
  4764  	if err != nil {
  4765  		t.Fatal("exec insert", err)
  4766  	}
  4767  	var (
  4768  		str1 string
  4769  		dec1 decimalInt
  4770  		arr1 []int64
  4771  	)
  4772  	err = db.QueryRowContext(ctx, "SELECT|keys|dec1,str1,array1|").Scan(&dec1, &str1, &arr1)
  4773  	if err != nil {
  4774  		t.Fatal("select", err)
  4775  	}
  4776  
  4777  	list := []struct{ got, want any }{
  4778  		{o1, "from-server"},
  4779  		{dec1, decimalInt{123}},
  4780  		{str1, "hello"},
  4781  		{arr1, []int64{42, 128, 707}},
  4782  	}
  4783  
  4784  	for index, item := range list {
  4785  		if !reflect.DeepEqual(item.got, item.want) {
  4786  			t.Errorf("got %#v wanted %#v for index %d", item.got, item.want, index)
  4787  		}
  4788  	}
  4789  }
  4790  
  4791  func TestNamedValueCheckerSkip(t *testing.T) {
  4792  	synctest.Test(t, testNamedValueCheckerSkip)
  4793  }
  4794  func testNamedValueCheckerSkip(t *testing.T) {
  4795  	Register("NamedValueCheckSkip", &nvcDriver{skipNamedValueCheck: true})
  4796  	db, err := Open("NamedValueCheckSkip", "")
  4797  	if err != nil {
  4798  		t.Fatal(err)
  4799  	}
  4800  	defer db.Close()
  4801  
  4802  	ctx := t.Context()
  4803  	_, err = db.ExecContext(ctx, "WIPE")
  4804  	if err != nil {
  4805  		t.Fatal("exec wipe", err)
  4806  	}
  4807  
  4808  	_, err = db.ExecContext(ctx, "CREATE|keys|dec1=any")
  4809  	if err != nil {
  4810  		t.Fatal("exec create", err)
  4811  	}
  4812  
  4813  	_, err = db.ExecContext(ctx, "INSERT|keys|dec1=?A", Named("A", decimalInt{123}))
  4814  	if err == nil {
  4815  		t.Fatalf("expected error with bad argument, got %v", err)
  4816  	}
  4817  }
  4818  
  4819  func TestOpenConnector(t *testing.T) {
  4820  	synctest.Test(t, testOpenConnector)
  4821  }
  4822  func testOpenConnector(t *testing.T) {
  4823  	Register("testctx", &fakeDriverCtx{})
  4824  	db, err := Open("testctx", "people")
  4825  	if err != nil {
  4826  		t.Fatal(err)
  4827  	}
  4828  	defer db.Close()
  4829  
  4830  	c, ok := db.connector.(*fakeConnector)
  4831  	if !ok {
  4832  		t.Fatal("not using *fakeConnector")
  4833  	}
  4834  
  4835  	if err := db.Close(); err != nil {
  4836  		t.Fatal(err)
  4837  	}
  4838  
  4839  	if !c.closed {
  4840  		t.Fatal("connector is not closed")
  4841  	}
  4842  }
  4843  
  4844  type ctxOnlyDriver struct {
  4845  	fakeDriver
  4846  }
  4847  
  4848  func (d *ctxOnlyDriver) Open(dsn string) (driver.Conn, error) {
  4849  	conn, err := d.fakeDriver.Open(dsn)
  4850  	if err != nil {
  4851  		return nil, err
  4852  	}
  4853  	return &ctxOnlyConn{fc: getFakeConn(conn)}, nil
  4854  }
  4855  
  4856  var (
  4857  	_ driver.Conn           = &ctxOnlyConn{}
  4858  	_ driver.QueryerContext = &ctxOnlyConn{}
  4859  	_ driver.ExecerContext  = &ctxOnlyConn{}
  4860  )
  4861  
  4862  type ctxOnlyConn struct {
  4863  	fc *fakeConn
  4864  
  4865  	queryCtxCalled bool
  4866  	execCtxCalled  bool
  4867  }
  4868  
  4869  func (c *ctxOnlyConn) Begin() (driver.Tx, error) {
  4870  	return c.fc.Begin()
  4871  }
  4872  
  4873  func (c *ctxOnlyConn) Close() error {
  4874  	return c.fc.Close()
  4875  }
  4876  
  4877  // Prepare is still part of the Conn interface, so while it isn't used
  4878  // must be defined for compatibility.
  4879  func (c *ctxOnlyConn) Prepare(q string) (driver.Stmt, error) {
  4880  	panic("not used")
  4881  }
  4882  
  4883  func (c *ctxOnlyConn) PrepareContext(ctx context.Context, q string) (driver.Stmt, error) {
  4884  	return c.fc.PrepareContext(ctx, q)
  4885  }
  4886  
  4887  func (c *ctxOnlyConn) QueryContext(ctx context.Context, q string, args []driver.NamedValue) (driver.Rows, error) {
  4888  	c.queryCtxCalled = true
  4889  	return c.fc.QueryContext(ctx, q, args)
  4890  }
  4891  
  4892  func (c *ctxOnlyConn) ExecContext(ctx context.Context, q string, args []driver.NamedValue) (driver.Result, error) {
  4893  	c.execCtxCalled = true
  4894  	return c.fc.ExecContext(ctx, q, args)
  4895  }
  4896  
  4897  // TestQueryExecContextOnly ensures drivers only need to implement QueryContext
  4898  // and ExecContext methods.
  4899  func TestQueryExecContextOnly(t *testing.T) {
  4900  	synctest.Test(t, testQueryExecContextOnly)
  4901  }
  4902  func testQueryExecContextOnly(t *testing.T) {
  4903  	// Ensure connection does not implement non-context interfaces.
  4904  	var connType driver.Conn = &ctxOnlyConn{}
  4905  	if _, ok := connType.(driver.Execer); ok {
  4906  		t.Fatalf("%T must not implement driver.Execer", connType)
  4907  	}
  4908  	if _, ok := connType.(driver.Queryer); ok {
  4909  		t.Fatalf("%T must not implement driver.Queryer", connType)
  4910  	}
  4911  
  4912  	Register("ContextOnly", &ctxOnlyDriver{})
  4913  	db, err := Open("ContextOnly", "")
  4914  	if err != nil {
  4915  		t.Fatal(err)
  4916  	}
  4917  	defer db.Close()
  4918  
  4919  	ctx := t.Context()
  4920  
  4921  	conn, err := db.Conn(ctx)
  4922  	if err != nil {
  4923  		t.Fatal("db.Conn", err)
  4924  	}
  4925  	defer conn.Close()
  4926  	coc := conn.dc.ci.(*ctxOnlyConn)
  4927  	coc.fc.skipDirtySession = true
  4928  
  4929  	_, err = conn.ExecContext(ctx, "WIPE")
  4930  	if err != nil {
  4931  		t.Fatal("exec wipe", err)
  4932  	}
  4933  
  4934  	_, err = conn.ExecContext(ctx, "CREATE|keys|v1=string")
  4935  	if err != nil {
  4936  		t.Fatal("exec create", err)
  4937  	}
  4938  	expectedValue := "value1"
  4939  	_, err = conn.ExecContext(ctx, "INSERT|keys|v1=?", expectedValue)
  4940  	if err != nil {
  4941  		t.Fatal("exec insert", err)
  4942  	}
  4943  	rows, err := conn.QueryContext(ctx, "SELECT|keys|v1|")
  4944  	if err != nil {
  4945  		t.Fatal("query select", err)
  4946  	}
  4947  	v1 := ""
  4948  	for rows.Next() {
  4949  		err = rows.Scan(&v1)
  4950  		if err != nil {
  4951  			t.Fatal("rows scan", err)
  4952  		}
  4953  	}
  4954  	rows.Close()
  4955  
  4956  	if v1 != expectedValue {
  4957  		t.Fatalf("expected %q, got %q", expectedValue, v1)
  4958  	}
  4959  
  4960  	if !coc.execCtxCalled {
  4961  		t.Error("ExecContext not called")
  4962  	}
  4963  	if !coc.queryCtxCalled {
  4964  		t.Error("QueryContext not called")
  4965  	}
  4966  }
  4967  
  4968  type alwaysErrScanner struct{}
  4969  
  4970  var errTestScanWrap = errors.New("errTestScanWrap")
  4971  
  4972  func (alwaysErrScanner) Scan(any) error {
  4973  	return errTestScanWrap
  4974  }
  4975  
  4976  // Issue 38099: Ensure that Rows.Scan properly wraps underlying errors.
  4977  func TestRowsScanProperlyWrapsErrors(t *testing.T) {
  4978  	testDatabase(t, testRowsScanProperlyWrapsErrors)
  4979  }
  4980  func testRowsScanProperlyWrapsErrors(t *testing.T, db *DB) {
  4981  	populate(t, db, "people")
  4982  
  4983  	rows, err := db.Query("SELECT|people|age|")
  4984  	if err != nil {
  4985  		t.Fatalf("Query: %v", err)
  4986  	}
  4987  
  4988  	var res alwaysErrScanner
  4989  
  4990  	for rows.Next() {
  4991  		err = rows.Scan(&res)
  4992  		if err == nil {
  4993  			t.Fatal("expecting back an error")
  4994  		}
  4995  		if !errors.Is(err, errTestScanWrap) {
  4996  			t.Fatalf("errors.Is mismatch\n%v\nWant: %v", err, errTestScanWrap)
  4997  		}
  4998  		// Ensure that error substring matching still correctly works.
  4999  		if !strings.Contains(err.Error(), errTestScanWrap.Error()) {
  5000  			t.Fatalf("Error %v does not contain %v", err, errTestScanWrap)
  5001  		}
  5002  	}
  5003  }
  5004  
  5005  type alwaysErrValuer struct{}
  5006  
  5007  // errEmpty is returned when an empty value is found
  5008  var errEmpty = errors.New("empty value")
  5009  
  5010  func (v alwaysErrValuer) Value() (driver.Value, error) {
  5011  	return nil, errEmpty
  5012  }
  5013  
  5014  // Issue 64707: Ensure that Stmt.Exec and Stmt.Query properly wraps underlying errors.
  5015  func TestDriverArgsWrapsErrors(t *testing.T) {
  5016  
  5017  	synctestSubtest(t, "exec", func(t *testing.T) {
  5018  		db := newTestDB(t, "people")
  5019  		defer closeDB(t, db)
  5020  		_, err := db.Exec("INSERT|keys|dec1=?", alwaysErrValuer{})
  5021  		if err == nil {
  5022  			t.Fatal("expecting back an error")
  5023  		}
  5024  		if !errors.Is(err, errEmpty) {
  5025  			t.Fatalf("errors.Is mismatch\n%v\nWant: %v", err, errEmpty)
  5026  		}
  5027  		// Ensure that error substring matching still correctly works.
  5028  		if !strings.Contains(err.Error(), errEmpty.Error()) {
  5029  			t.Fatalf("Error %v does not contain %v", err, errEmpty)
  5030  		}
  5031  	})
  5032  
  5033  	synctestSubtest(t, "query", func(t *testing.T) {
  5034  		db := newTestDB(t, "people")
  5035  		defer closeDB(t, db)
  5036  		_, err := db.Query("INSERT|keys|dec1=?", alwaysErrValuer{})
  5037  		if err == nil {
  5038  			t.Fatal("expecting back an error")
  5039  		}
  5040  		if !errors.Is(err, errEmpty) {
  5041  			t.Fatalf("errors.Is mismatch\n%v\nWant: %v", err, errEmpty)
  5042  		}
  5043  		// Ensure that error substring matching still correctly works.
  5044  		if !strings.Contains(err.Error(), errEmpty.Error()) {
  5045  			t.Fatalf("Error %v does not contain %v", err, errEmpty)
  5046  		}
  5047  	})
  5048  }
  5049  
  5050  func TestContextCancelDuringRawBytesScan(t *testing.T) {
  5051  	for _, mode := range []string{"nocancel", "top", "bottom", "go"} {
  5052  		synctestSubtest(t, mode, func(t *testing.T) {
  5053  			testContextCancelDuringRawBytesScan(t, mode)
  5054  		})
  5055  	}
  5056  }
  5057  
  5058  // From go.dev/issue/60304
  5059  func testContextCancelDuringRawBytesScan(t *testing.T, mode string) {
  5060  	db := newTestDB(t, "people")
  5061  	defer closeDB(t, db)
  5062  
  5063  	// cancel used to call close asynchronously.
  5064  	// This test checks that it waits so as not to interfere with RawBytes.
  5065  	ctx, cancel := context.WithCancel(context.Background())
  5066  	defer cancel()
  5067  
  5068  	r, err := db.QueryContext(ctx, "SELECT|people|name|")
  5069  	if err != nil {
  5070  		t.Fatal(err)
  5071  	}
  5072  	numRows := 0
  5073  	var sink byte
  5074  	for r.Next() {
  5075  		if mode == "top" && numRows == 2 {
  5076  			// cancel between Next and Scan is observed by Scan as err = context.Canceled.
  5077  			cancel()
  5078  			synctest.Wait()
  5079  		}
  5080  		numRows++
  5081  		var s RawBytes
  5082  		err = r.Scan(&s)
  5083  		if numRows == 3 && err == context.Canceled {
  5084  			if r.closemuScanHold {
  5085  				t.Errorf("expected closemu NOT to be held")
  5086  			}
  5087  			break
  5088  		}
  5089  		if !r.closemuScanHold {
  5090  			t.Errorf("expected closemu to be held")
  5091  		}
  5092  		if err != nil {
  5093  			t.Fatal(err)
  5094  		}
  5095  		t.Logf("read %q", s)
  5096  		if mode == "bottom" && numRows == 2 {
  5097  			// cancel before Next should be observed by Next, exiting the loop.
  5098  			cancel()
  5099  			synctest.Wait()
  5100  		}
  5101  		if mode == "go" && numRows == 2 {
  5102  			// cancel at any future time, to catch other cases
  5103  			go cancel()
  5104  		}
  5105  		for _, b := range s { // some operation reading from the raw memory
  5106  			sink += b
  5107  		}
  5108  		// r.Columns must not deadlock acquiring closemu.RLock.
  5109  		_, _ = r.Columns()
  5110  	}
  5111  	if r.closemuScanHold {
  5112  		t.Errorf("closemu held; should not be")
  5113  	}
  5114  
  5115  	// There are 3 rows. We canceled after reading 2 so we expect either
  5116  	// 2 or 3 depending on how the awaitDone goroutine schedules.
  5117  	switch numRows {
  5118  	case 0, 1:
  5119  		t.Errorf("got %d rows; want 2+", numRows)
  5120  	case 2:
  5121  		if err := r.Err(); err != context.Canceled {
  5122  			t.Errorf("unexpected error: %v (%T)", err, err)
  5123  		}
  5124  	default:
  5125  		// Made it to the end. This is rare, but fine. Permit it.
  5126  	}
  5127  
  5128  	if err := r.Close(); err != nil {
  5129  		t.Fatal(err)
  5130  	}
  5131  }
  5132  
  5133  func TestContextCancelBetweenNextAndErr(t *testing.T) {
  5134  	testDatabase(t, testContextCancelBetweenNextAndErr)
  5135  }
  5136  func testContextCancelBetweenNextAndErr(t *testing.T, db *DB) {
  5137  	populate(t, db, "people")
  5138  	ctx, cancel := context.WithCancel(context.Background())
  5139  	defer cancel()
  5140  
  5141  	r, err := db.QueryContext(ctx, "SELECT|people|name|")
  5142  	if err != nil {
  5143  		t.Fatal(err)
  5144  	}
  5145  	for r.Next() {
  5146  	}
  5147  	cancel() // wake up the awaitDone goroutine
  5148  	synctest.Wait()
  5149  	if err := r.Err(); err != nil {
  5150  		t.Fatal(err)
  5151  	}
  5152  }
  5153  
  5154  type testScanner struct {
  5155  	scanf func(src any) error
  5156  }
  5157  
  5158  func (ts testScanner) Scan(src any) error { return ts.scanf(src) }
  5159  
  5160  func TestContextCancelDuringScan(t *testing.T) {
  5161  	testDatabase(t, testContextCancelDuringScan)
  5162  }
  5163  func testContextCancelDuringScan(t *testing.T, db *DB) {
  5164  	populate(t, db, "people")
  5165  
  5166  	ctx, cancel := context.WithCancel(context.Background())
  5167  	defer cancel()
  5168  
  5169  	scanStart := make(chan any)
  5170  	scanEnd := make(chan error)
  5171  	scanner := &testScanner{
  5172  		scanf: func(src any) error {
  5173  			scanStart <- src
  5174  			return <-scanEnd
  5175  		},
  5176  	}
  5177  
  5178  	// Start a query, and pause it mid-scan.
  5179  	want := []byte("Alice")
  5180  	r, err := db.QueryContext(ctx, "SELECT|people|name|name=?", string(want))
  5181  	if err != nil {
  5182  		t.Fatal(err)
  5183  	}
  5184  	if !r.Next() {
  5185  		t.Fatalf("r.Next() = false, want true")
  5186  	}
  5187  	go func() {
  5188  		r.Scan(scanner)
  5189  	}()
  5190  	got := <-scanStart
  5191  	defer close(scanEnd)
  5192  	gotBytes, ok := got.([]byte)
  5193  	if !ok {
  5194  		t.Fatalf("r.Scan returned %T, want []byte", got)
  5195  	}
  5196  	if !bytes.Equal(gotBytes, want) {
  5197  		t.Fatalf("before cancel: r.Scan returned %q, want %q", gotBytes, want)
  5198  	}
  5199  
  5200  	// Cancel the query.
  5201  	cancel()
  5202  	synctest.Wait()
  5203  
  5204  	// Cancelling the query should not have changed the result.
  5205  	if !bytes.Equal(gotBytes, want) {
  5206  		t.Fatalf("after cancel: r.Scan result is now %q, want %q", gotBytes, want)
  5207  	}
  5208  }
  5209  
  5210  func TestNilErrorAfterClose(t *testing.T) {
  5211  	testDatabase(t, testNilErrorAfterClose)
  5212  }
  5213  func testNilErrorAfterClose(t *testing.T, db *DB) {
  5214  	populate(t, db, "people")
  5215  
  5216  	// This WithCancel is important; Rows contains an optimization to avoid
  5217  	// spawning a goroutine when the query/transaction context cannot be
  5218  	// canceled, but this test tests a bug which is caused by said goroutine.
  5219  	ctx, cancel := context.WithCancel(context.Background())
  5220  	defer cancel()
  5221  
  5222  	r, err := db.QueryContext(ctx, "SELECT|people|name|")
  5223  	if err != nil {
  5224  		t.Fatal(err)
  5225  	}
  5226  
  5227  	if err := r.Close(); err != nil {
  5228  		t.Fatal(err)
  5229  	}
  5230  
  5231  	synctest.Wait()
  5232  	if err := r.Err(); err != nil {
  5233  		t.Fatal(err)
  5234  	}
  5235  }
  5236  
  5237  // Issue #65201.
  5238  //
  5239  // If a RawBytes is reused across multiple queries,
  5240  // subsequent queries shouldn't overwrite driver-owned memory from previous queries.
  5241  func TestRawBytesReuse(t *testing.T) {
  5242  	testDatabase(t, testRawBytesReuse)
  5243  }
  5244  func testRawBytesReuse(t *testing.T, db *DB) {
  5245  	populate(t, db, "people")
  5246  
  5247  	var raw RawBytes
  5248  
  5249  	// The RawBytes in this query aliases driver-owned memory.
  5250  	rows, err := db.Query("SELECT|people|name|")
  5251  	if err != nil {
  5252  		t.Fatal(err)
  5253  	}
  5254  	rows.Next()
  5255  	rows.Scan(&raw) // now raw is pointing to driver-owned memory
  5256  	name1 := string(raw)
  5257  	rows.Close()
  5258  
  5259  	// The RawBytes in this query does not alias driver-owned memory.
  5260  	rows, err = db.Query("SELECT|people|age|")
  5261  	if err != nil {
  5262  		t.Fatal(err)
  5263  	}
  5264  	rows.Next()
  5265  	rows.Scan(&raw) // this must not write to the driver-owned memory in raw
  5266  	rows.Close()
  5267  
  5268  	// Repeat the first query. Nothing should have changed.
  5269  	rows, err = db.Query("SELECT|people|name|")
  5270  	if err != nil {
  5271  		t.Fatal(err)
  5272  	}
  5273  	rows.Next()
  5274  	rows.Scan(&raw) // raw points to driver-owned memory again
  5275  	name2 := string(raw)
  5276  	rows.Close()
  5277  	if name1 != name2 {
  5278  		t.Fatalf("Scan read name %q, want %q", name2, name1)
  5279  	}
  5280  }
  5281  
  5282  // badConn implements a bad driver.Conn, for TestBadDriver.
  5283  // The Exec method panics.
  5284  type badConn struct{}
  5285  
  5286  func (bc badConn) Prepare(query string) (driver.Stmt, error) {
  5287  	return nil, errors.New("badConn Prepare")
  5288  }
  5289  
  5290  func (bc badConn) Close() error {
  5291  	return nil
  5292  }
  5293  
  5294  func (bc badConn) Begin() (driver.Tx, error) {
  5295  	return nil, errors.New("badConn Begin")
  5296  }
  5297  
  5298  func (bc badConn) Exec(query string, args []driver.Value) (driver.Result, error) {
  5299  	panic("badConn.Exec")
  5300  }
  5301  
  5302  // badDriver is a driver.Driver that uses badConn.
  5303  type badDriver struct{}
  5304  
  5305  func (bd badDriver) Open(name string) (driver.Conn, error) {
  5306  	return badConn{}, nil
  5307  }
  5308  
  5309  // Issue 15901.
  5310  func TestBadDriver(t *testing.T) {
  5311  	synctest.Test(t, testBadDriver)
  5312  }
  5313  func testBadDriver(t *testing.T) {
  5314  	Register("bad", badDriver{})
  5315  	db, err := Open("bad", "ignored")
  5316  	if err != nil {
  5317  		t.Fatal(err)
  5318  	}
  5319  	defer func() {
  5320  		if r := recover(); r == nil {
  5321  			t.Error("expected panic")
  5322  		} else {
  5323  			if want := "badConn.Exec"; r.(string) != want {
  5324  				t.Errorf("panic was %v, expected %v", r, want)
  5325  			}
  5326  		}
  5327  	}()
  5328  	defer db.Close()
  5329  	db.Exec("ignored")
  5330  }
  5331  
  5332  type pingDriver struct {
  5333  	fails bool
  5334  }
  5335  
  5336  type pingConn struct {
  5337  	badConn
  5338  	driver *pingDriver
  5339  }
  5340  
  5341  var pingError = errors.New("Ping failed")
  5342  
  5343  func (pc pingConn) Ping(ctx context.Context) error {
  5344  	if pc.driver.fails {
  5345  		return pingError
  5346  	}
  5347  	return nil
  5348  }
  5349  
  5350  var _ driver.Pinger = pingConn{}
  5351  
  5352  func (pd *pingDriver) Open(name string) (driver.Conn, error) {
  5353  	return pingConn{driver: pd}, nil
  5354  }
  5355  
  5356  func TestPing(t *testing.T) {
  5357  	synctest.Test(t, testPing)
  5358  }
  5359  func testPing(t *testing.T) {
  5360  	driver := &pingDriver{}
  5361  	Register("ping", driver)
  5362  
  5363  	db, err := Open("ping", "ignored")
  5364  	if err != nil {
  5365  		t.Fatal(err)
  5366  	}
  5367  	defer db.Close()
  5368  
  5369  	if err := db.Ping(); err != nil {
  5370  		t.Errorf("err was %#v, expected nil", err)
  5371  		return
  5372  	}
  5373  
  5374  	driver.fails = true
  5375  	if err := db.Ping(); err != pingError {
  5376  		t.Errorf("err was %#v, expected pingError", err)
  5377  	}
  5378  }
  5379  
  5380  // Issue 18101.
  5381  func TestTypedString(t *testing.T) {
  5382  	testDatabase(t, testTypedString)
  5383  }
  5384  func testTypedString(t *testing.T, db *DB) {
  5385  	populate(t, db, "people")
  5386  
  5387  	type Str string
  5388  	var scanned Str
  5389  
  5390  	err := db.QueryRow("SELECT|people|name|name=?", "Alice").Scan(&scanned)
  5391  	if err != nil {
  5392  		t.Fatal(err)
  5393  	}
  5394  	expected := Str("Alice")
  5395  	if scanned != expected {
  5396  		t.Errorf("expected %+v, got %+v", expected, scanned)
  5397  	}
  5398  }
  5399  
  5400  func BenchmarkConcurrentDBExec(b *testing.B) {
  5401  	b.ReportAllocs()
  5402  	ct := new(concurrentDBExecTest)
  5403  	for i := 0; i < b.N; i++ {
  5404  		doConcurrentTest(b, ct)
  5405  	}
  5406  }
  5407  
  5408  func BenchmarkConcurrentStmtQuery(b *testing.B) {
  5409  	b.ReportAllocs()
  5410  	ct := new(concurrentStmtQueryTest)
  5411  	for i := 0; i < b.N; i++ {
  5412  		doConcurrentTest(b, ct)
  5413  	}
  5414  }
  5415  
  5416  func BenchmarkConcurrentStmtExec(b *testing.B) {
  5417  	b.ReportAllocs()
  5418  	ct := new(concurrentStmtExecTest)
  5419  	for i := 0; i < b.N; i++ {
  5420  		doConcurrentTest(b, ct)
  5421  	}
  5422  }
  5423  
  5424  func BenchmarkConcurrentTxQuery(b *testing.B) {
  5425  	b.ReportAllocs()
  5426  	ct := new(concurrentTxQueryTest)
  5427  	for i := 0; i < b.N; i++ {
  5428  		doConcurrentTest(b, ct)
  5429  	}
  5430  }
  5431  
  5432  func BenchmarkConcurrentTxExec(b *testing.B) {
  5433  	b.ReportAllocs()
  5434  	ct := new(concurrentTxExecTest)
  5435  	for i := 0; i < b.N; i++ {
  5436  		doConcurrentTest(b, ct)
  5437  	}
  5438  }
  5439  
  5440  func BenchmarkConcurrentTxStmtQuery(b *testing.B) {
  5441  	b.ReportAllocs()
  5442  	ct := new(concurrentTxStmtQueryTest)
  5443  	for i := 0; i < b.N; i++ {
  5444  		doConcurrentTest(b, ct)
  5445  	}
  5446  }
  5447  
  5448  func BenchmarkConcurrentTxStmtExec(b *testing.B) {
  5449  	b.ReportAllocs()
  5450  	ct := new(concurrentTxStmtExecTest)
  5451  	for i := 0; i < b.N; i++ {
  5452  		doConcurrentTest(b, ct)
  5453  	}
  5454  }
  5455  
  5456  func BenchmarkConcurrentRandom(b *testing.B) {
  5457  	b.ReportAllocs()
  5458  	ct := new(concurrentRandomTest)
  5459  	for i := 0; i < b.N; i++ {
  5460  		doConcurrentTest(b, ct)
  5461  	}
  5462  }
  5463  
  5464  func BenchmarkManyConcurrentQueries(b *testing.B) {
  5465  	b.ReportAllocs()
  5466  	// To see lock contention in Go 1.4, 16~ cores and 128~ goroutines are required.
  5467  	const parallelism = 16
  5468  
  5469  	db := newTestDB(b, "magicquery")
  5470  	defer closeDB(b, db)
  5471  	db.SetMaxIdleConns(runtime.GOMAXPROCS(0) * parallelism)
  5472  
  5473  	stmt, err := db.Prepare("SELECT|magicquery|op|op=?,millis=?")
  5474  	if err != nil {
  5475  		b.Fatal(err)
  5476  	}
  5477  	defer stmt.Close()
  5478  
  5479  	b.SetParallelism(parallelism)
  5480  	b.RunParallel(func(pb *testing.PB) {
  5481  		for pb.Next() {
  5482  			rows, err := stmt.Query("sleep", 1)
  5483  			if err != nil {
  5484  				b.Error(err)
  5485  				return
  5486  			}
  5487  			rows.Close()
  5488  		}
  5489  	})
  5490  }
  5491  
  5492  func TestGrabConnAllocs(t *testing.T) {
  5493  	synctest.Test(t, testGrabConnAllocs)
  5494  }
  5495  func testGrabConnAllocs(t *testing.T) {
  5496  	testenv.SkipIfOptimizationOff(t)
  5497  	if race.Enabled {
  5498  		t.Skip("skipping allocation test when using race detector")
  5499  	}
  5500  	c := new(Conn)
  5501  	ctx := context.Background()
  5502  	n := int(testing.AllocsPerRun(1000, func() {
  5503  		_, release, err := c.grabConn(ctx)
  5504  		if err != nil {
  5505  			t.Fatal(err)
  5506  		}
  5507  		release(nil)
  5508  	}))
  5509  	if n > 0 {
  5510  		t.Fatalf("Conn.grabConn allocated %v objects; want 0", n)
  5511  	}
  5512  }
  5513  
  5514  func BenchmarkGrabConn(b *testing.B) {
  5515  	b.ReportAllocs()
  5516  	c := new(Conn)
  5517  	ctx := context.Background()
  5518  	for i := 0; i < b.N; i++ {
  5519  		_, release, err := c.grabConn(ctx)
  5520  		if err != nil {
  5521  			b.Fatal(err)
  5522  		}
  5523  		release(nil)
  5524  	}
  5525  }
  5526  
  5527  func TestConnRequestSet(t *testing.T) {
  5528  	var s connRequestSet
  5529  	wantLen := func(want int) {
  5530  		t.Helper()
  5531  		if got := s.Len(); got != want {
  5532  			t.Errorf("Len = %d; want %d", got, want)
  5533  		}
  5534  		if want == 0 && !t.Failed() {
  5535  			if _, ok := s.TakeRandom(); ok {
  5536  				t.Fatalf("TakeRandom returned result when empty")
  5537  			}
  5538  		}
  5539  	}
  5540  	reset := func() { s = connRequestSet{} }
  5541  
  5542  	t.Run("add-delete", func(t *testing.T) {
  5543  		reset()
  5544  		wantLen(0)
  5545  		dh := s.Add(nil)
  5546  		wantLen(1)
  5547  		if !s.Delete(dh) {
  5548  			t.Fatal("failed to delete")
  5549  		}
  5550  		wantLen(0)
  5551  		if s.Delete(dh) {
  5552  			t.Error("delete worked twice")
  5553  		}
  5554  		wantLen(0)
  5555  	})
  5556  	t.Run("take-before-delete", func(t *testing.T) {
  5557  		reset()
  5558  		ch1 := make(chan connRequest)
  5559  		dh := s.Add(ch1)
  5560  		wantLen(1)
  5561  		if got, ok := s.TakeRandom(); !ok || got != ch1 {
  5562  			t.Fatalf("wrong take; ok=%v", ok)
  5563  		}
  5564  		wantLen(0)
  5565  		if s.Delete(dh) {
  5566  			t.Error("unexpected delete after take")
  5567  		}
  5568  	})
  5569  	t.Run("get-take-many", func(t *testing.T) {
  5570  		reset()
  5571  		m := map[chan connRequest]bool{}
  5572  		const N = 100
  5573  		var inOrder, backOut []chan connRequest
  5574  		for range N {
  5575  			c := make(chan connRequest)
  5576  			m[c] = true
  5577  			s.Add(c)
  5578  			inOrder = append(inOrder, c)
  5579  		}
  5580  		if s.Len() != N {
  5581  			t.Fatalf("Len = %v; want %v", s.Len(), N)
  5582  		}
  5583  		for s.Len() > 0 {
  5584  			c, ok := s.TakeRandom()
  5585  			if !ok {
  5586  				t.Fatal("failed to take when non-empty")
  5587  			}
  5588  			if !m[c] {
  5589  				t.Fatal("returned item not in remaining set")
  5590  			}
  5591  			delete(m, c)
  5592  			backOut = append(backOut, c)
  5593  		}
  5594  		if len(m) > 0 {
  5595  			t.Error("items remain in expected map")
  5596  		}
  5597  		if slices.Equal(inOrder, backOut) { // N! chance of flaking; N=100 is fine
  5598  			t.Error("wasn't random")
  5599  		}
  5600  	})
  5601  	t.Run("close-delete", func(t *testing.T) {
  5602  		reset()
  5603  		ch := make(chan connRequest)
  5604  		dh := s.Add(ch)
  5605  		wantLen(1)
  5606  		s.CloseAndRemoveAll()
  5607  		wantLen(0)
  5608  		if s.Delete(dh) {
  5609  			t.Error("unexpected delete after CloseAndRemoveAll")
  5610  		}
  5611  	})
  5612  }
  5613  
  5614  func BenchmarkConnRequestSet(b *testing.B) {
  5615  	var s connRequestSet
  5616  	for range b.N {
  5617  		for range 16 {
  5618  			s.Add(nil)
  5619  		}
  5620  		for range 8 {
  5621  			if _, ok := s.TakeRandom(); !ok {
  5622  				b.Fatal("want ok")
  5623  			}
  5624  		}
  5625  		for range 8 {
  5626  			s.Add(nil)
  5627  		}
  5628  		for range 16 {
  5629  			if _, ok := s.TakeRandom(); !ok {
  5630  				b.Fatal("want ok")
  5631  			}
  5632  		}
  5633  		if _, ok := s.TakeRandom(); ok {
  5634  			b.Fatal("unexpected ok")
  5635  		}
  5636  	}
  5637  }
  5638  
  5639  func TestIssue69837(t *testing.T) {
  5640  	u := Null[uint]{V: 1, Valid: true}
  5641  	val, err := driver.DefaultParameterConverter.ConvertValue(u)
  5642  	if err != nil {
  5643  		t.Errorf("ConvertValue() error = %v, want nil", err)
  5644  	}
  5645  
  5646  	if v, ok := val.(int64); !ok {
  5647  		t.Errorf("val.(type): got %T, expected int64", val)
  5648  	} else if v != 1 {
  5649  		t.Errorf("val: got %d, expected 1", v)
  5650  	}
  5651  }
  5652  
  5653  type issue69728Type struct {
  5654  	ID   int
  5655  	Name string
  5656  }
  5657  
  5658  func (t issue69728Type) Value() (driver.Value, error) {
  5659  	return []byte(fmt.Sprintf("%d, %s", t.ID, t.Name)), nil
  5660  }
  5661  
  5662  func TestIssue69728(t *testing.T) {
  5663  	forValue := Null[issue69728Type]{
  5664  		Valid: true,
  5665  		V: issue69728Type{
  5666  			ID:   42,
  5667  			Name: "foobar",
  5668  		},
  5669  	}
  5670  
  5671  	v1, err := forValue.Value()
  5672  	if err != nil {
  5673  		t.Errorf("forValue.Value() error = %v, want nil", err)
  5674  	}
  5675  
  5676  	v2, err := forValue.V.Value()
  5677  	if err != nil {
  5678  		t.Errorf("forValue.V.Value() error = %v, want nil", err)
  5679  	}
  5680  
  5681  	if !reflect.DeepEqual(v1, v2) {
  5682  		t.Errorf("not equal; v1 = %v, v2 = %v", v1, v2)
  5683  	}
  5684  }
  5685  
  5686  func TestColumnConverterWithUnknownInputCount(t *testing.T) {
  5687  	db := OpenDB(&unknownInputsConnector{})
  5688  	stmt, err := db.Prepare("SELECT ?")
  5689  	if err != nil {
  5690  		t.Fatal(err)
  5691  	}
  5692  	_, err = stmt.Exec(1)
  5693  	if err != nil {
  5694  		t.Fatal(err)
  5695  	}
  5696  }
  5697  
  5698  type unknownInputsConnector struct{}
  5699  
  5700  func (unknownInputsConnector) Connect(context.Context) (driver.Conn, error) {
  5701  	return unknownInputsConn{}, nil
  5702  }
  5703  
  5704  func (unknownInputsConnector) Driver() driver.Driver { return nil }
  5705  
  5706  type unknownInputsConn struct{}
  5707  
  5708  func (unknownInputsConn) Prepare(string) (driver.Stmt, error) { return unknownInputsStmt{}, nil }
  5709  func (unknownInputsConn) Close() error                        { return nil }
  5710  func (unknownInputsConn) Begin() (driver.Tx, error)           { return nil, nil }
  5711  
  5712  type unknownInputsStmt struct{}
  5713  
  5714  func (unknownInputsStmt) Close() error  { return nil }
  5715  func (unknownInputsStmt) NumInput() int { return -1 }
  5716  func (unknownInputsStmt) Exec(args []driver.Value) (driver.Result, error) {
  5717  	if _, ok := args[0].(string); !ok {
  5718  		return nil, fmt.Errorf("Expected string, got %T", args[0])
  5719  	}
  5720  	return nil, nil
  5721  }
  5722  func (unknownInputsStmt) Query([]driver.Value) (driver.Rows, error) { return nil, nil }
  5723  func (unknownInputsStmt) ColumnConverter(idx int) driver.ValueConverter {
  5724  	return unknownInputsValueConverter{}
  5725  }
  5726  
  5727  type unknownInputsValueConverter struct{}
  5728  
  5729  func (unknownInputsValueConverter) ConvertValue(v any) (driver.Value, error) {
  5730  	return "string", nil
  5731  }
  5732  
  5733  func TestNullTypeScanErrorConsistency(t *testing.T) {
  5734  	// Issue #45662: Null* types should have Valid=false when Scan returns an error.
  5735  	// Previously, Valid was set to true before convertAssign was called,
  5736  	// so if conversion failed, Valid would still be true despite the error.
  5737  
  5738  	tests := []struct {
  5739  		name    string
  5740  		scanner Scanner
  5741  		input   any
  5742  		wantErr bool
  5743  	}{
  5744  		{
  5745  			name:    "NullInt32 with invalid input",
  5746  			scanner: &NullInt32{},
  5747  			input:   []byte("not_a_number"),
  5748  			wantErr: true,
  5749  		},
  5750  		{
  5751  			name:    "NullInt64 with invalid input",
  5752  			scanner: &NullInt64{},
  5753  			input:   []byte("not_a_number"),
  5754  			wantErr: true,
  5755  		},
  5756  		{
  5757  			name:    "NullFloat64 with invalid input",
  5758  			scanner: &NullFloat64{},
  5759  			input:   []byte("not_a_float"),
  5760  			wantErr: true,
  5761  		},
  5762  		{
  5763  			name:    "NullBool with invalid input",
  5764  			scanner: &NullBool{},
  5765  			input:   []byte("not_a_bool"),
  5766  			wantErr: true,
  5767  		},
  5768  		// Valid cases should still work
  5769  		{
  5770  			name:    "NullInt32 with valid input",
  5771  			scanner: &NullInt32{},
  5772  			input:   int64(42),
  5773  			wantErr: false,
  5774  		},
  5775  		{
  5776  			name:    "NullInt64 with valid input",
  5777  			scanner: &NullInt64{},
  5778  			input:   int64(42),
  5779  			wantErr: false,
  5780  		},
  5781  		{
  5782  			name:    "NullFloat64 with valid input",
  5783  			scanner: &NullFloat64{},
  5784  			input:   float64(3.14),
  5785  			wantErr: false,
  5786  		},
  5787  		{
  5788  			name:    "NullBool with valid input",
  5789  			scanner: &NullBool{},
  5790  			input:   true,
  5791  			wantErr: false,
  5792  		},
  5793  		{
  5794  			name:    "NullString with valid input",
  5795  			scanner: &NullString{},
  5796  			input:   "hello",
  5797  			wantErr: false,
  5798  		},
  5799  	}
  5800  
  5801  	for _, tt := range tests {
  5802  		t.Run(tt.name, func(t *testing.T) {
  5803  			err := tt.scanner.Scan(tt.input)
  5804  
  5805  			// Check that error matches expectation
  5806  			if (err != nil) != tt.wantErr {
  5807  				t.Errorf("Scan() error = %v, wantErr %v", err, tt.wantErr)
  5808  			}
  5809  
  5810  			// The key invariant: Valid should be the opposite of whether we got an error
  5811  			// (assuming non-nil input)
  5812  			var valid bool
  5813  			switch s := tt.scanner.(type) {
  5814  			case *NullInt32:
  5815  				valid = s.Valid
  5816  			case *NullInt64:
  5817  				valid = s.Valid
  5818  			case *NullFloat64:
  5819  				valid = s.Valid
  5820  			case *NullBool:
  5821  				valid = s.Valid
  5822  			case *NullString:
  5823  				valid = s.Valid
  5824  			case *NullTime:
  5825  				valid = s.Valid
  5826  			}
  5827  
  5828  			if err != nil && valid {
  5829  				t.Errorf("Scan() returned error but Valid=true; want Valid=false when err!=nil")
  5830  			}
  5831  			if err == nil && !valid {
  5832  				t.Errorf("Scan() returned nil error but Valid=false; want Valid=true when err==nil")
  5833  			}
  5834  		})
  5835  	}
  5836  }
  5837  
  5838  // TestNullTypeScanNil verifies that scanning nil sets Valid=false without error.
  5839  func TestNullTypeScanNil(t *testing.T) {
  5840  	tests := []struct {
  5841  		name    string
  5842  		scanner Scanner
  5843  	}{
  5844  		{"NullString", &NullString{String: "preset", Valid: true}},
  5845  		{"NullInt64", &NullInt64{Int64: 42, Valid: true}},
  5846  		{"NullInt32", &NullInt32{Int32: 42, Valid: true}},
  5847  		{"NullFloat64", &NullFloat64{Float64: 3.14, Valid: true}},
  5848  		{"NullBool", &NullBool{Bool: true, Valid: true}},
  5849  		{"NullTime", &NullTime{Time: time.Now(), Valid: true}},
  5850  	}
  5851  
  5852  	for _, tt := range tests {
  5853  		t.Run(tt.name, func(t *testing.T) {
  5854  			err := tt.scanner.Scan(nil)
  5855  			if err != nil {
  5856  				t.Errorf("Scan(nil) error = %v; want nil", err)
  5857  			}
  5858  
  5859  			var valid bool
  5860  			switch s := tt.scanner.(type) {
  5861  			case *NullString:
  5862  				valid = s.Valid
  5863  			case *NullInt64:
  5864  				valid = s.Valid
  5865  			case *NullInt32:
  5866  				valid = s.Valid
  5867  			case *NullFloat64:
  5868  				valid = s.Valid
  5869  			case *NullBool:
  5870  				valid = s.Valid
  5871  			case *NullTime:
  5872  				valid = s.Valid
  5873  			}
  5874  
  5875  			if valid {
  5876  				t.Errorf("Scan(nil) left Valid=true; want Valid=false")
  5877  			}
  5878  		})
  5879  	}
  5880  }
  5881  
  5882  type testStringType struct {
  5883  	s string
  5884  }
  5885  
  5886  func TestQueryRowsScanner(t *testing.T) {
  5887  	testDatabase(t, testQueryRowsScanner, requireFeature("ScanColumn"))
  5888  }
  5889  func testQueryRowsScanner(t *testing.T, db *DB) {
  5890  	populate(t, db, "people")
  5891  	rows, err := db.Query("SELECT|people|age,name|")
  5892  	if err != nil {
  5893  		t.Fatalf("Query: %v", err)
  5894  	}
  5895  	defer rows.Close()
  5896  	type row struct {
  5897  		age  int
  5898  		name testStringType
  5899  	}
  5900  	got := []row{}
  5901  	for rows.Next() {
  5902  		var r row
  5903  		err = rows.Scan(&r.age, &r.name)
  5904  		if err != nil {
  5905  			t.Fatalf("Scan: %v", err)
  5906  		}
  5907  		got = append(got, r)
  5908  	}
  5909  	err = rows.Err()
  5910  	if err != nil {
  5911  		t.Fatalf("Err: %v", err)
  5912  	}
  5913  	want := []row{
  5914  		{age: 1, name: testStringType{"Alice"}},
  5915  		{age: 2, name: testStringType{"Bob"}},
  5916  		{age: 3, name: testStringType{"Chris"}},
  5917  	}
  5918  	if !slices.Equal(got, want) {
  5919  		t.Errorf("mismatch.\n got: %#v\nwant: %#v", got, want)
  5920  	}
  5921  }
  5922  
  5923  type rowsColumnScannerConnector struct {
  5924  	fakeConnector
  5925  }
  5926  
  5927  func (c *rowsColumnScannerConnector) Connect(ctx context.Context) (driver.Conn, error) {
  5928  	conn, err := c.fakeConnector.Connect(ctx)
  5929  	fc := getFakeConn(conn)
  5930  	return &rowsColumnScannerConn{fc}, err
  5931  }
  5932  
  5933  // rowsColumnScannerConn is a Conn with rows that implement RowsColumnScanner.
  5934  type rowsColumnScannerConn struct {
  5935  	*fakeConn
  5936  }
  5937  
  5938  func (s *rowsColumnScannerConn) PrepareContext(ctx context.Context, query string) (driver.Stmt, error) {
  5939  	stmt, err := s.fakeConn.PrepareContext(ctx, query)
  5940  	if err != nil {
  5941  		return nil, err
  5942  	}
  5943  	return &rowsColumnScannerStmt{stmt.(*fakeStmt)}, nil
  5944  }
  5945  
  5946  type rowsColumnScannerStmt struct {
  5947  	*fakeStmt
  5948  }
  5949  
  5950  func (s *rowsColumnScannerStmt) QueryContext(ctx context.Context, args []driver.NamedValue) (driver.Rows, error) {
  5951  	rows, err := s.fakeStmt.QueryContext(ctx, args)
  5952  	if err != nil {
  5953  		return nil, err
  5954  	}
  5955  	return &rowsColumnScannerRows{rowsCursor: rows.(*rowsCursor)}, nil
  5956  }
  5957  
  5958  type rowsColumnScannerRows struct {
  5959  	*rowsCursor
  5960  	row []driver.Value
  5961  }
  5962  
  5963  func (c *rowsColumnScannerRows) NextRow() error {
  5964  	if c.row == nil {
  5965  		c.row = make([]driver.Value, len(c.rowsCursor.Columns()))
  5966  	}
  5967  	return c.rowsCursor.Next(c.row)
  5968  }
  5969  
  5970  func (c *rowsColumnScannerRows) NextResultSet() error {
  5971  	c.row = nil
  5972  	return c.rowsCursor.NextResultSet()
  5973  }
  5974  
  5975  func (c *rowsColumnScannerRows) ScanColumn(ctx driver.ScanContext, index int, dest any) error {
  5976  	if index < 0 || index >= len(c.row) {
  5977  		return fmt.Errorf("index %v out of range", index)
  5978  	}
  5979  	switch d := dest.(type) {
  5980  	case *testStringType:
  5981  		switch s := c.row[index].(type) {
  5982  		case string:
  5983  			d.s = s
  5984  			return nil
  5985  		case []byte:
  5986  			d.s = string(s)
  5987  			return nil
  5988  		}
  5989  	}
  5990  	return ConvertAssign(ctx, dest, c.row[index])
  5991  }
  5992  
  5993  func BenchmarkConvertAssignRows(b *testing.B) {
  5994  	now := time.Now()
  5995  	b.Run("Int64ToInt64", func(b *testing.B) {
  5996  		var d int64
  5997  		b.ReportAllocs()
  5998  		for range b.N {
  5999  			if err := convertAssignRows(&d, int64(42), nil); err != nil {
  6000  				b.Fatal(err)
  6001  			}
  6002  		}
  6003  	})
  6004  	b.Run("Int64ToInt", func(b *testing.B) {
  6005  		var d int
  6006  		b.ReportAllocs()
  6007  		for range b.N {
  6008  			if err := convertAssignRows(&d, int64(1234567890123), nil); err != nil {
  6009  				b.Fatal(err)
  6010  			}
  6011  		}
  6012  	})
  6013  	b.Run("Int64ToNullInt64", func(b *testing.B) {
  6014  		var d NullInt64
  6015  		b.ReportAllocs()
  6016  		for range b.N {
  6017  			if err := convertAssignRows(&d, int64(42), nil); err != nil {
  6018  				b.Fatal(err)
  6019  			}
  6020  		}
  6021  	})
  6022  	b.Run("Float64ToFloat64", func(b *testing.B) {
  6023  		var d float64
  6024  		b.ReportAllocs()
  6025  		for range b.N {
  6026  			if err := convertAssignRows(&d, float64(3.14159), nil); err != nil {
  6027  				b.Fatal(err)
  6028  			}
  6029  		}
  6030  	})
  6031  	b.Run("BoolToBool", func(b *testing.B) {
  6032  		var d bool
  6033  		b.ReportAllocs()
  6034  		for range b.N {
  6035  			if err := convertAssignRows(&d, true, nil); err != nil {
  6036  				b.Fatal(err)
  6037  			}
  6038  		}
  6039  	})
  6040  	b.Run("Int64ToInt32", func(b *testing.B) {
  6041  		var d int32
  6042  		b.ReportAllocs()
  6043  		for range b.N {
  6044  			if err := convertAssignRows(&d, int64(123456), nil); err != nil {
  6045  				b.Fatal(err)
  6046  			}
  6047  		}
  6048  	})
  6049  	b.Run("Int64ToAny", func(b *testing.B) {
  6050  		var d any
  6051  		b.ReportAllocs()
  6052  		for range b.N {
  6053  			if err := convertAssignRows(&d, int64(42), nil); err != nil {
  6054  				b.Fatal(err)
  6055  			}
  6056  		}
  6057  	})
  6058  	b.Run("StringToInt64", func(b *testing.B) {
  6059  		var d int64
  6060  		b.ReportAllocs()
  6061  		for range b.N {
  6062  			if err := convertAssignRows(&d, "1234567890123", nil); err != nil {
  6063  				b.Fatal(err)
  6064  			}
  6065  		}
  6066  	})
  6067  	b.Run("BytesToBytes", func(b *testing.B) {
  6068  		var d []byte
  6069  		var src any = []byte("alice-example-name") // box once: per-op boxing would add a phantom alloc
  6070  		b.ReportAllocs()
  6071  		for range b.N {
  6072  			if err := convertAssignRows(&d, src, nil); err != nil {
  6073  				b.Fatal(err)
  6074  			}
  6075  		}
  6076  	})
  6077  	b.Run("BytesToRawBytes", func(b *testing.B) {
  6078  		var d RawBytes
  6079  		var src any = []byte("alice-example-name")
  6080  		b.ReportAllocs()
  6081  		for range b.N {
  6082  			if err := convertAssignRows(&d, src, nil); err != nil {
  6083  				b.Fatal(err)
  6084  			}
  6085  		}
  6086  	})
  6087  	b.Run("BytesToInt64", func(b *testing.B) {
  6088  		var d int64
  6089  		var src any = []byte("1234567890123")
  6090  		b.ReportAllocs()
  6091  		for range b.N {
  6092  			if err := convertAssignRows(&d, src, nil); err != nil {
  6093  				b.Fatal(err)
  6094  			}
  6095  		}
  6096  	})
  6097  	b.Run("NilToAny", func(b *testing.B) {
  6098  		var d any
  6099  		b.ReportAllocs()
  6100  		for range b.N {
  6101  			if err := convertAssignRows(&d, nil, nil); err != nil {
  6102  				b.Fatal(err)
  6103  			}
  6104  		}
  6105  	})
  6106  	b.Run("BytesToString", func(b *testing.B) {
  6107  		var d string
  6108  		var src any = []byte("alice-example-name")
  6109  		b.ReportAllocs()
  6110  		for range b.N {
  6111  			if err := convertAssignRows(&d, src, nil); err != nil {
  6112  				b.Fatal(err)
  6113  			}
  6114  		}
  6115  	})
  6116  	b.Run("StringToString", func(b *testing.B) {
  6117  		var d string
  6118  		b.ReportAllocs()
  6119  		for range b.N {
  6120  			if err := convertAssignRows(&d, "alice-example-name", nil); err != nil {
  6121  				b.Fatal(err)
  6122  			}
  6123  		}
  6124  	})
  6125  	b.Run("TimeToTime", func(b *testing.B) {
  6126  		var d time.Time
  6127  		var src any = now
  6128  		b.ReportAllocs()
  6129  		for range b.N {
  6130  			if err := convertAssignRows(&d, src, nil); err != nil {
  6131  				b.Fatal(err)
  6132  			}
  6133  		}
  6134  	})
  6135  }
  6136  

View as plain text