Black Lives Matter. Support the Equal Justice Initiative.

Source file src/database/sql/sql.go

Documentation: database/sql

     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 provides a generic interface around SQL (or SQL-like)
     6  // databases.
     7  //
     8  // The sql package must be used in conjunction with a database driver.
     9  // See https://golang.org/s/sqldrivers for a list of drivers.
    10  //
    11  // Drivers that do not support context cancellation will not return until
    12  // after the query is completed.
    13  //
    14  // For usage examples, see the wiki page at
    15  // https://golang.org/s/sqlwiki.
    16  package sql
    17  
    18  import (
    19  	"context"
    20  	"database/sql/driver"
    21  	"errors"
    22  	"fmt"
    23  	"io"
    24  	"reflect"
    25  	"runtime"
    26  	"sort"
    27  	"strconv"
    28  	"sync"
    29  	"sync/atomic"
    30  	"time"
    31  )
    32  
    33  var (
    34  	driversMu sync.RWMutex
    35  	drivers   = make(map[string]driver.Driver)
    36  )
    37  
    38  // nowFunc returns the current time; it's overridden in tests.
    39  var nowFunc = time.Now
    40  
    41  // Register makes a database driver available by the provided name.
    42  // If Register is called twice with the same name or if driver is nil,
    43  // it panics.
    44  func Register(name string, driver driver.Driver) {
    45  	driversMu.Lock()
    46  	defer driversMu.Unlock()
    47  	if driver == nil {
    48  		panic("sql: Register driver is nil")
    49  	}
    50  	if _, dup := drivers[name]; dup {
    51  		panic("sql: Register called twice for driver " + name)
    52  	}
    53  	drivers[name] = driver
    54  }
    55  
    56  func unregisterAllDrivers() {
    57  	driversMu.Lock()
    58  	defer driversMu.Unlock()
    59  	// For tests.
    60  	drivers = make(map[string]driver.Driver)
    61  }
    62  
    63  // Drivers returns a sorted list of the names of the registered drivers.
    64  func Drivers() []string {
    65  	driversMu.RLock()
    66  	defer driversMu.RUnlock()
    67  	list := make([]string, 0, len(drivers))
    68  	for name := range drivers {
    69  		list = append(list, name)
    70  	}
    71  	sort.Strings(list)
    72  	return list
    73  }
    74  
    75  // A NamedArg is a named argument. NamedArg values may be used as
    76  // arguments to Query or Exec and bind to the corresponding named
    77  // parameter in the SQL statement.
    78  //
    79  // For a more concise way to create NamedArg values, see
    80  // the Named function.
    81  type NamedArg struct {
    82  	_Named_Fields_Required struct{}
    83  
    84  	// Name is the name of the parameter placeholder.
    85  	//
    86  	// If empty, the ordinal position in the argument list will be
    87  	// used.
    88  	//
    89  	// Name must omit any symbol prefix.
    90  	Name string
    91  
    92  	// Value is the value of the parameter.
    93  	// It may be assigned the same value types as the query
    94  	// arguments.
    95  	Value interface{}
    96  }
    97  
    98  // Named provides a more concise way to create NamedArg values.
    99  //
   100  // Example usage:
   101  //
   102  //     db.ExecContext(ctx, `
   103  //         delete from Invoice
   104  //         where
   105  //             TimeCreated < @end
   106  //             and TimeCreated >= @start;`,
   107  //         sql.Named("start", startTime),
   108  //         sql.Named("end", endTime),
   109  //     )
   110  func Named(name string, value interface{}) NamedArg {
   111  	// This method exists because the go1compat promise
   112  	// doesn't guarantee that structs don't grow more fields,
   113  	// so unkeyed struct literals are a vet error. Thus, we don't
   114  	// want to allow sql.NamedArg{name, value}.
   115  	return NamedArg{Name: name, Value: value}
   116  }
   117  
   118  // IsolationLevel is the transaction isolation level used in TxOptions.
   119  type IsolationLevel int
   120  
   121  // Various isolation levels that drivers may support in BeginTx.
   122  // If a driver does not support a given isolation level an error may be returned.
   123  //
   124  // See https://en.wikipedia.org/wiki/Isolation_(database_systems)#Isolation_levels.
   125  const (
   126  	LevelDefault IsolationLevel = iota
   127  	LevelReadUncommitted
   128  	LevelReadCommitted
   129  	LevelWriteCommitted
   130  	LevelRepeatableRead
   131  	LevelSnapshot
   132  	LevelSerializable
   133  	LevelLinearizable
   134  )
   135  
   136  // String returns the name of the transaction isolation level.
   137  func (i IsolationLevel) String() string {
   138  	switch i {
   139  	case LevelDefault:
   140  		return "Default"
   141  	case LevelReadUncommitted:
   142  		return "Read Uncommitted"
   143  	case LevelReadCommitted:
   144  		return "Read Committed"
   145  	case LevelWriteCommitted:
   146  		return "Write Committed"
   147  	case LevelRepeatableRead:
   148  		return "Repeatable Read"
   149  	case LevelSnapshot:
   150  		return "Snapshot"
   151  	case LevelSerializable:
   152  		return "Serializable"
   153  	case LevelLinearizable:
   154  		return "Linearizable"
   155  	default:
   156  		return "IsolationLevel(" + strconv.Itoa(int(i)) + ")"
   157  	}
   158  }
   159  
   160  var _ fmt.Stringer = LevelDefault
   161  
   162  // TxOptions holds the transaction options to be used in DB.BeginTx.
   163  type TxOptions struct {
   164  	// Isolation is the transaction isolation level.
   165  	// If zero, the driver or database's default level is used.
   166  	Isolation IsolationLevel
   167  	ReadOnly  bool
   168  }
   169  
   170  // RawBytes is a byte slice that holds a reference to memory owned by
   171  // the database itself. After a Scan into a RawBytes, the slice is only
   172  // valid until the next call to Next, Scan, or Close.
   173  type RawBytes []byte
   174  
   175  // NullString represents a string that may be null.
   176  // NullString implements the Scanner interface so
   177  // it can be used as a scan destination:
   178  //
   179  //  var s NullString
   180  //  err := db.QueryRow("SELECT name FROM foo WHERE id=?", id).Scan(&s)
   181  //  ...
   182  //  if s.Valid {
   183  //     // use s.String
   184  //  } else {
   185  //     // NULL value
   186  //  }
   187  //
   188  type NullString struct {
   189  	String string
   190  	Valid  bool // Valid is true if String is not NULL
   191  }
   192  
   193  // Scan implements the Scanner interface.
   194  func (ns *NullString) Scan(value interface{}) error {
   195  	if value == nil {
   196  		ns.String, ns.Valid = "", false
   197  		return nil
   198  	}
   199  	ns.Valid = true
   200  	return convertAssign(&ns.String, value)
   201  }
   202  
   203  // Value implements the driver Valuer interface.
   204  func (ns NullString) Value() (driver.Value, error) {
   205  	if !ns.Valid {
   206  		return nil, nil
   207  	}
   208  	return ns.String, nil
   209  }
   210  
   211  // NullInt64 represents an int64 that may be null.
   212  // NullInt64 implements the Scanner interface so
   213  // it can be used as a scan destination, similar to NullString.
   214  type NullInt64 struct {
   215  	Int64 int64
   216  	Valid bool // Valid is true if Int64 is not NULL
   217  }
   218  
   219  // Scan implements the Scanner interface.
   220  func (n *NullInt64) Scan(value interface{}) error {
   221  	if value == nil {
   222  		n.Int64, n.Valid = 0, false
   223  		return nil
   224  	}
   225  	n.Valid = true
   226  	return convertAssign(&n.Int64, value)
   227  }
   228  
   229  // Value implements the driver Valuer interface.
   230  func (n NullInt64) Value() (driver.Value, error) {
   231  	if !n.Valid {
   232  		return nil, nil
   233  	}
   234  	return n.Int64, nil
   235  }
   236  
   237  // NullInt32 represents an int32 that may be null.
   238  // NullInt32 implements the Scanner interface so
   239  // it can be used as a scan destination, similar to NullString.
   240  type NullInt32 struct {
   241  	Int32 int32
   242  	Valid bool // Valid is true if Int32 is not NULL
   243  }
   244  
   245  // Scan implements the Scanner interface.
   246  func (n *NullInt32) Scan(value interface{}) error {
   247  	if value == nil {
   248  		n.Int32, n.Valid = 0, false
   249  		return nil
   250  	}
   251  	n.Valid = true
   252  	return convertAssign(&n.Int32, value)
   253  }
   254  
   255  // Value implements the driver Valuer interface.
   256  func (n NullInt32) Value() (driver.Value, error) {
   257  	if !n.Valid {
   258  		return nil, nil
   259  	}
   260  	return int64(n.Int32), nil
   261  }
   262  
   263  // NullFloat64 represents a float64 that may be null.
   264  // NullFloat64 implements the Scanner interface so
   265  // it can be used as a scan destination, similar to NullString.
   266  type NullFloat64 struct {
   267  	Float64 float64
   268  	Valid   bool // Valid is true if Float64 is not NULL
   269  }
   270  
   271  // Scan implements the Scanner interface.
   272  func (n *NullFloat64) Scan(value interface{}) error {
   273  	if value == nil {
   274  		n.Float64, n.Valid = 0, false
   275  		return nil
   276  	}
   277  	n.Valid = true
   278  	return convertAssign(&n.Float64, value)
   279  }
   280  
   281  // Value implements the driver Valuer interface.
   282  func (n NullFloat64) Value() (driver.Value, error) {
   283  	if !n.Valid {
   284  		return nil, nil
   285  	}
   286  	return n.Float64, nil
   287  }
   288  
   289  // NullBool represents a bool that may be null.
   290  // NullBool implements the Scanner interface so
   291  // it can be used as a scan destination, similar to NullString.
   292  type NullBool struct {
   293  	Bool  bool
   294  	Valid bool // Valid is true if Bool is not NULL
   295  }
   296  
   297  // Scan implements the Scanner interface.
   298  func (n *NullBool) Scan(value interface{}) error {
   299  	if value == nil {
   300  		n.Bool, n.Valid = false, false
   301  		return nil
   302  	}
   303  	n.Valid = true
   304  	return convertAssign(&n.Bool, value)
   305  }
   306  
   307  // Value implements the driver Valuer interface.
   308  func (n NullBool) Value() (driver.Value, error) {
   309  	if !n.Valid {
   310  		return nil, nil
   311  	}
   312  	return n.Bool, nil
   313  }
   314  
   315  // NullTime represents a time.Time that may be null.
   316  // NullTime implements the Scanner interface so
   317  // it can be used as a scan destination, similar to NullString.
   318  type NullTime struct {
   319  	Time  time.Time
   320  	Valid bool // Valid is true if Time is not NULL
   321  }
   322  
   323  // Scan implements the Scanner interface.
   324  func (n *NullTime) Scan(value interface{}) error {
   325  	if value == nil {
   326  		n.Time, n.Valid = time.Time{}, false
   327  		return nil
   328  	}
   329  	n.Valid = true
   330  	return convertAssign(&n.Time, value)
   331  }
   332  
   333  // Value implements the driver Valuer interface.
   334  func (n NullTime) Value() (driver.Value, error) {
   335  	if !n.Valid {
   336  		return nil, nil
   337  	}
   338  	return n.Time, nil
   339  }
   340  
   341  // Scanner is an interface used by Scan.
   342  type Scanner interface {
   343  	// Scan assigns a value from a database driver.
   344  	//
   345  	// The src value will be of one of the following types:
   346  	//
   347  	//    int64
   348  	//    float64
   349  	//    bool
   350  	//    []byte
   351  	//    string
   352  	//    time.Time
   353  	//    nil - for NULL values
   354  	//
   355  	// An error should be returned if the value cannot be stored
   356  	// without loss of information.
   357  	//
   358  	// Reference types such as []byte are only valid until the next call to Scan
   359  	// and should not be retained. Their underlying memory is owned by the driver.
   360  	// If retention is necessary, copy their values before the next call to Scan.
   361  	Scan(src interface{}) error
   362  }
   363  
   364  // Out may be used to retrieve OUTPUT value parameters from stored procedures.
   365  //
   366  // Not all drivers and databases support OUTPUT value parameters.
   367  //
   368  // Example usage:
   369  //
   370  //   var outArg string
   371  //   _, err := db.ExecContext(ctx, "ProcName", sql.Named("Arg1", sql.Out{Dest: &outArg}))
   372  type Out struct {
   373  	_Named_Fields_Required struct{}
   374  
   375  	// Dest is a pointer to the value that will be set to the result of the
   376  	// stored procedure's OUTPUT parameter.
   377  	Dest interface{}
   378  
   379  	// In is whether the parameter is an INOUT parameter. If so, the input value to the stored
   380  	// procedure is the dereferenced value of Dest's pointer, which is then replaced with
   381  	// the output value.
   382  	In bool
   383  }
   384  
   385  // ErrNoRows is returned by Scan when QueryRow doesn't return a
   386  // row. In such a case, QueryRow returns a placeholder *Row value that
   387  // defers this error until a Scan.
   388  var ErrNoRows = errors.New("sql: no rows in result set")
   389  
   390  // DB is a database handle representing a pool of zero or more
   391  // underlying connections. It's safe for concurrent use by multiple
   392  // goroutines.
   393  //
   394  // The sql package creates and frees connections automatically; it
   395  // also maintains a free pool of idle connections. If the database has
   396  // a concept of per-connection state, such state can be reliably observed
   397  // within a transaction (Tx) or connection (Conn). Once DB.Begin is called, the
   398  // returned Tx is bound to a single connection. Once Commit or
   399  // Rollback is called on the transaction, that transaction's
   400  // connection is returned to DB's idle connection pool. The pool size
   401  // can be controlled with SetMaxIdleConns.
   402  type DB struct {
   403  	// Atomic access only. At top of struct to prevent mis-alignment
   404  	// on 32-bit platforms. Of type time.Duration.
   405  	waitDuration int64 // Total time waited for new connections.
   406  
   407  	connector driver.Connector
   408  	// numClosed is an atomic counter which represents a total number of
   409  	// closed connections. Stmt.openStmt checks it before cleaning closed
   410  	// connections in Stmt.css.
   411  	numClosed uint64
   412  
   413  	mu           sync.Mutex // protects following fields
   414  	freeConn     []*driverConn
   415  	connRequests map[uint64]chan connRequest
   416  	nextRequest  uint64 // Next key to use in connRequests.
   417  	numOpen      int    // number of opened and pending open connections
   418  	// Used to signal the need for new connections
   419  	// a goroutine running connectionOpener() reads on this chan and
   420  	// maybeOpenNewConnections sends on the chan (one send per needed connection)
   421  	// It is closed during db.Close(). The close tells the connectionOpener
   422  	// goroutine to exit.
   423  	openerCh          chan struct{}
   424  	closed            bool
   425  	dep               map[finalCloser]depSet
   426  	lastPut           map[*driverConn]string // stacktrace of last conn's put; debug only
   427  	maxIdle           int                    // zero means defaultMaxIdleConns; negative means 0
   428  	maxOpen           int                    // <= 0 means unlimited
   429  	maxLifetime       time.Duration          // maximum amount of time a connection may be reused
   430  	cleanerCh         chan struct{}
   431  	waitCount         int64 // Total number of connections waited for.
   432  	maxIdleClosed     int64 // Total number of connections closed due to idle.
   433  	maxLifetimeClosed int64 // Total number of connections closed due to max free limit.
   434  
   435  	stop func() // stop cancels the connection opener and the session resetter.
   436  }
   437  
   438  // connReuseStrategy determines how (*DB).conn returns database connections.
   439  type connReuseStrategy uint8
   440  
   441  const (
   442  	// alwaysNewConn forces a new connection to the database.
   443  	alwaysNewConn connReuseStrategy = iota
   444  	// cachedOrNewConn returns a cached connection, if available, else waits
   445  	// for one to become available (if MaxOpenConns has been reached) or
   446  	// creates a new database connection.
   447  	cachedOrNewConn
   448  )
   449  
   450  // driverConn wraps a driver.Conn with a mutex, to
   451  // be held during all calls into the Conn. (including any calls onto
   452  // interfaces returned via that Conn, such as calls on Tx, Stmt,
   453  // Result, Rows)
   454  type driverConn struct {
   455  	db        *DB
   456  	createdAt time.Time
   457  
   458  	sync.Mutex  // guards following
   459  	ci          driver.Conn
   460  	needReset   bool // The connection session should be reset before use if true.
   461  	closed      bool
   462  	finalClosed bool // ci.Close has been called
   463  	openStmt    map[*driverStmt]bool
   464  
   465  	// guarded by db.mu
   466  	inUse      bool
   467  	onPut      []func() // code (with db.mu held) run when conn is next returned
   468  	dbmuClosed bool     // same as closed, but guarded by db.mu, for removeClosedStmtLocked
   469  }
   470  
   471  func (dc *driverConn) releaseConn(err error) {
   472  	dc.db.putConn(dc, err, true)
   473  }
   474  
   475  func (dc *driverConn) removeOpenStmt(ds *driverStmt) {
   476  	dc.Lock()
   477  	defer dc.Unlock()
   478  	delete(dc.openStmt, ds)
   479  }
   480  
   481  func (dc *driverConn) expired(timeout time.Duration) bool {
   482  	if timeout <= 0 {
   483  		return false
   484  	}
   485  	return dc.createdAt.Add(timeout).Before(nowFunc())
   486  }
   487  
   488  // resetSession checks if the driver connection needs the
   489  // session to be reset and if required, resets it.
   490  func (dc *driverConn) resetSession(ctx context.Context) error {
   491  	dc.Lock()
   492  	defer dc.Unlock()
   493  
   494  	if !dc.needReset {
   495  		return nil
   496  	}
   497  	if cr, ok := dc.ci.(driver.SessionResetter); ok {
   498  		return cr.ResetSession(ctx)
   499  	}
   500  	return nil
   501  }
   502  
   503  // validator was introduced for Go1.15, but backported to Go1.14.
   504  type validator interface {
   505  	IsValid() bool
   506  }
   507  
   508  // validateConnection checks if the connection is valid and can
   509  // still be used. It also marks the session for reset if required.
   510  func (dc *driverConn) validateConnection(needsReset bool) bool {
   511  	dc.Lock()
   512  	defer dc.Unlock()
   513  
   514  	if needsReset {
   515  		dc.needReset = true
   516  	}
   517  	if cv, ok := dc.ci.(validator); ok {
   518  		return cv.IsValid()
   519  	}
   520  	return true
   521  }
   522  
   523  // prepareLocked prepares the query on dc. When cg == nil the dc must keep track of
   524  // the prepared statements in a pool.
   525  func (dc *driverConn) prepareLocked(ctx context.Context, cg stmtConnGrabber, query string) (*driverStmt, error) {
   526  	si, err := ctxDriverPrepare(ctx, dc.ci, query)
   527  	if err != nil {
   528  		return nil, err
   529  	}
   530  	ds := &driverStmt{Locker: dc, si: si}
   531  
   532  	// No need to manage open statements if there is a single connection grabber.
   533  	if cg != nil {
   534  		return ds, nil
   535  	}
   536  
   537  	// Track each driverConn's open statements, so we can close them
   538  	// before closing the conn.
   539  	//
   540  	// Wrap all driver.Stmt is *driverStmt to ensure they are only closed once.
   541  	if dc.openStmt == nil {
   542  		dc.openStmt = make(map[*driverStmt]bool)
   543  	}
   544  	dc.openStmt[ds] = true
   545  	return ds, nil
   546  }
   547  
   548  // the dc.db's Mutex is held.
   549  func (dc *driverConn) closeDBLocked() func() error {
   550  	dc.Lock()
   551  	defer dc.Unlock()
   552  	if dc.closed {
   553  		return func() error { return errors.New("sql: duplicate driverConn close") }
   554  	}
   555  	dc.closed = true
   556  	return dc.db.removeDepLocked(dc, dc)
   557  }
   558  
   559  func (dc *driverConn) Close() error {
   560  	dc.Lock()
   561  	if dc.closed {
   562  		dc.Unlock()
   563  		return errors.New("sql: duplicate driverConn close")
   564  	}
   565  	dc.closed = true
   566  	dc.Unlock() // not defer; removeDep finalClose calls may need to lock
   567  
   568  	// And now updates that require holding dc.mu.Lock.
   569  	dc.db.mu.Lock()
   570  	dc.dbmuClosed = true
   571  	fn := dc.db.removeDepLocked(dc, dc)
   572  	dc.db.mu.Unlock()
   573  	return fn()
   574  }
   575  
   576  func (dc *driverConn) finalClose() error {
   577  	var err error
   578  
   579  	// Each *driverStmt has a lock to the dc. Copy the list out of the dc
   580  	// before calling close on each stmt.
   581  	var openStmt []*driverStmt
   582  	withLock(dc, func() {
   583  		openStmt = make([]*driverStmt, 0, len(dc.openStmt))
   584  		for ds := range dc.openStmt {
   585  			openStmt = append(openStmt, ds)
   586  		}
   587  		dc.openStmt = nil
   588  	})
   589  	for _, ds := range openStmt {
   590  		ds.Close()
   591  	}
   592  	withLock(dc, func() {
   593  		dc.finalClosed = true
   594  		err = dc.ci.Close()
   595  		dc.ci = nil
   596  	})
   597  
   598  	dc.db.mu.Lock()
   599  	dc.db.numOpen--
   600  	dc.db.maybeOpenNewConnections()
   601  	dc.db.mu.Unlock()
   602  
   603  	atomic.AddUint64(&dc.db.numClosed, 1)
   604  	return err
   605  }
   606  
   607  // driverStmt associates a driver.Stmt with the
   608  // *driverConn from which it came, so the driverConn's lock can be
   609  // held during calls.
   610  type driverStmt struct {
   611  	sync.Locker // the *driverConn
   612  	si          driver.Stmt
   613  	closed      bool
   614  	closeErr    error // return value of previous Close call
   615  }
   616  
   617  // Close ensures driver.Stmt is only closed once and always returns the same
   618  // result.
   619  func (ds *driverStmt) Close() error {
   620  	ds.Lock()
   621  	defer ds.Unlock()
   622  	if ds.closed {
   623  		return ds.closeErr
   624  	}
   625  	ds.closed = true
   626  	ds.closeErr = ds.si.Close()
   627  	return ds.closeErr
   628  }
   629  
   630  // depSet is a finalCloser's outstanding dependencies
   631  type depSet map[interface{}]bool // set of true bools
   632  
   633  // The finalCloser interface is used by (*DB).addDep and related
   634  // dependency reference counting.
   635  type finalCloser interface {
   636  	// finalClose is called when the reference count of an object
   637  	// goes to zero. (*DB).mu is not held while calling it.
   638  	finalClose() error
   639  }
   640  
   641  // addDep notes that x now depends on dep, and x's finalClose won't be
   642  // called until all of x's dependencies are removed with removeDep.
   643  func (db *DB) addDep(x finalCloser, dep interface{}) {
   644  	db.mu.Lock()
   645  	defer db.mu.Unlock()
   646  	db.addDepLocked(x, dep)
   647  }
   648  
   649  func (db *DB) addDepLocked(x finalCloser, dep interface{}) {
   650  	if db.dep == nil {
   651  		db.dep = make(map[finalCloser]depSet)
   652  	}
   653  	xdep := db.dep[x]
   654  	if xdep == nil {
   655  		xdep = make(depSet)
   656  		db.dep[x] = xdep
   657  	}
   658  	xdep[dep] = true
   659  }
   660  
   661  // removeDep notes that x no longer depends on dep.
   662  // If x still has dependencies, nil is returned.
   663  // If x no longer has any dependencies, its finalClose method will be
   664  // called and its error value will be returned.
   665  func (db *DB) removeDep(x finalCloser, dep interface{}) error {
   666  	db.mu.Lock()
   667  	fn := db.removeDepLocked(x, dep)
   668  	db.mu.Unlock()
   669  	return fn()
   670  }
   671  
   672  func (db *DB) removeDepLocked(x finalCloser, dep interface{}) func() error {
   673  
   674  	xdep, ok := db.dep[x]
   675  	if !ok {
   676  		panic(fmt.Sprintf("unpaired removeDep: no deps for %T", x))
   677  	}
   678  
   679  	l0 := len(xdep)
   680  	delete(xdep, dep)
   681  
   682  	switch len(xdep) {
   683  	case l0:
   684  		// Nothing removed. Shouldn't happen.
   685  		panic(fmt.Sprintf("unpaired removeDep: no %T dep on %T", dep, x))
   686  	case 0:
   687  		// No more dependencies.
   688  		delete(db.dep, x)
   689  		return x.finalClose
   690  	default:
   691  		// Dependencies remain.
   692  		return func() error { return nil }
   693  	}
   694  }
   695  
   696  // This is the size of the connectionOpener request chan (DB.openerCh).
   697  // This value should be larger than the maximum typical value
   698  // used for db.maxOpen. If maxOpen is significantly larger than
   699  // connectionRequestQueueSize then it is possible for ALL calls into the *DB
   700  // to block until the connectionOpener can satisfy the backlog of requests.
   701  var connectionRequestQueueSize = 1000000
   702  
   703  type dsnConnector struct {
   704  	dsn    string
   705  	driver driver.Driver
   706  }
   707  
   708  func (t dsnConnector) Connect(_ context.Context) (driver.Conn, error) {
   709  	return t.driver.Open(t.dsn)
   710  }
   711  
   712  func (t dsnConnector) Driver() driver.Driver {
   713  	return t.driver
   714  }
   715  
   716  // OpenDB opens a database using a Connector, allowing drivers to
   717  // bypass a string based data source name.
   718  //
   719  // Most users will open a database via a driver-specific connection
   720  // helper function that returns a *DB. No database drivers are included
   721  // in the Go standard library. See https://golang.org/s/sqldrivers for
   722  // a list of third-party drivers.
   723  //
   724  // OpenDB may just validate its arguments without creating a connection
   725  // to the database. To verify that the data source name is valid, call
   726  // Ping.
   727  //
   728  // The returned DB is safe for concurrent use by multiple goroutines
   729  // and maintains its own pool of idle connections. Thus, the OpenDB
   730  // function should be called just once. It is rarely necessary to
   731  // close a DB.
   732  func OpenDB(c driver.Connector) *DB {
   733  	ctx, cancel := context.WithCancel(context.Background())
   734  	db := &DB{
   735  		connector:    c,
   736  		openerCh:     make(chan struct{}, connectionRequestQueueSize),
   737  		lastPut:      make(map[*driverConn]string),
   738  		connRequests: make(map[uint64]chan connRequest),
   739  		stop:         cancel,
   740  	}
   741  
   742  	go db.connectionOpener(ctx)
   743  
   744  	return db
   745  }
   746  
   747  // Open opens a database specified by its database driver name and a
   748  // driver-specific data source name, usually consisting of at least a
   749  // database name and connection information.
   750  //
   751  // Most users will open a database via a driver-specific connection
   752  // helper function that returns a *DB. No database drivers are included
   753  // in the Go standard library. See https://golang.org/s/sqldrivers for
   754  // a list of third-party drivers.
   755  //
   756  // Open may just validate its arguments without creating a connection
   757  // to the database. To verify that the data source name is valid, call
   758  // Ping.
   759  //
   760  // The returned DB is safe for concurrent use by multiple goroutines
   761  // and maintains its own pool of idle connections. Thus, the Open
   762  // function should be called just once. It is rarely necessary to
   763  // close a DB.
   764  func Open(driverName, dataSourceName string) (*DB, error) {
   765  	driversMu.RLock()
   766  	driveri, ok := drivers[driverName]
   767  	driversMu.RUnlock()
   768  	if !ok {
   769  		return nil, fmt.Errorf("sql: unknown driver %q (forgotten import?)", driverName)
   770  	}
   771  
   772  	if driverCtx, ok := driveri.(driver.DriverContext); ok {
   773  		connector, err := driverCtx.OpenConnector(dataSourceName)
   774  		if err != nil {
   775  			return nil, err
   776  		}
   777  		return OpenDB(connector), nil
   778  	}
   779  
   780  	return OpenDB(dsnConnector{dsn: dataSourceName, driver: driveri}), nil
   781  }
   782  
   783  func (db *DB) pingDC(ctx context.Context, dc *driverConn, release func(error)) error {
   784  	var err error
   785  	if pinger, ok := dc.ci.(driver.Pinger); ok {
   786  		withLock(dc, func() {
   787  			err = pinger.Ping(ctx)
   788  		})
   789  	}
   790  	release(err)
   791  	return err
   792  }
   793  
   794  // PingContext verifies a connection to the database is still alive,
   795  // establishing a connection if necessary.
   796  func (db *DB) PingContext(ctx context.Context) error {
   797  	var dc *driverConn
   798  	var err error
   799  
   800  	for i := 0; i < maxBadConnRetries; i++ {
   801  		dc, err = db.conn(ctx, cachedOrNewConn)
   802  		if err != driver.ErrBadConn {
   803  			break
   804  		}
   805  	}
   806  	if err == driver.ErrBadConn {
   807  		dc, err = db.conn(ctx, alwaysNewConn)
   808  	}
   809  	if err != nil {
   810  		return err
   811  	}
   812  
   813  	return db.pingDC(ctx, dc, dc.releaseConn)
   814  }
   815  
   816  // Ping verifies a connection to the database is still alive,
   817  // establishing a connection if necessary.
   818  func (db *DB) Ping() error {
   819  	return db.PingContext(context.Background())
   820  }
   821  
   822  // Close closes the database and prevents new queries from starting.
   823  // Close then waits for all queries that have started processing on the server
   824  // to finish.
   825  //
   826  // It is rare to Close a DB, as the DB handle is meant to be
   827  // long-lived and shared between many goroutines.
   828  func (db *DB) Close() error {
   829  	db.mu.Lock()
   830  	if db.closed { // Make DB.Close idempotent
   831  		db.mu.Unlock()
   832  		return nil
   833  	}
   834  	if db.cleanerCh != nil {
   835  		close(db.cleanerCh)
   836  	}
   837  	var err error
   838  	fns := make([]func() error, 0, len(db.freeConn))
   839  	for _, dc := range db.freeConn {
   840  		fns = append(fns, dc.closeDBLocked())
   841  	}
   842  	db.freeConn = nil
   843  	db.closed = true
   844  	for _, req := range db.connRequests {
   845  		close(req)
   846  	}
   847  	db.mu.Unlock()
   848  	for _, fn := range fns {
   849  		err1 := fn()
   850  		if err1 != nil {
   851  			err = err1
   852  		}
   853  	}
   854  	db.stop()
   855  	return err
   856  }
   857  
   858  const defaultMaxIdleConns = 2
   859  
   860  func (db *DB) maxIdleConnsLocked() int {
   861  	n := db.maxIdle
   862  	switch {
   863  	case n == 0:
   864  		// TODO(bradfitz): ask driver, if supported, for its default preference
   865  		return defaultMaxIdleConns
   866  	case n < 0:
   867  		return 0
   868  	default:
   869  		return n
   870  	}
   871  }
   872  
   873  // SetMaxIdleConns sets the maximum number of connections in the idle
   874  // connection pool.
   875  //
   876  // If MaxOpenConns is greater than 0 but less than the new MaxIdleConns,
   877  // then the new MaxIdleConns will be reduced to match the MaxOpenConns limit.
   878  //
   879  // If n <= 0, no idle connections are retained.
   880  //
   881  // The default max idle connections is currently 2. This may change in
   882  // a future release.
   883  func (db *DB) SetMaxIdleConns(n int) {
   884  	db.mu.Lock()
   885  	if n > 0 {
   886  		db.maxIdle = n
   887  	} else {
   888  		// No idle connections.
   889  		db.maxIdle = -1
   890  	}
   891  	// Make sure maxIdle doesn't exceed maxOpen
   892  	if db.maxOpen > 0 && db.maxIdleConnsLocked() > db.maxOpen {
   893  		db.maxIdle = db.maxOpen
   894  	}
   895  	var closing []*driverConn
   896  	idleCount := len(db.freeConn)
   897  	maxIdle := db.maxIdleConnsLocked()
   898  	if idleCount > maxIdle {
   899  		closing = db.freeConn[maxIdle:]
   900  		db.freeConn = db.freeConn[:maxIdle]
   901  	}
   902  	db.maxIdleClosed += int64(len(closing))
   903  	db.mu.Unlock()
   904  	for _, c := range closing {
   905  		c.Close()
   906  	}
   907  }
   908  
   909  // SetMaxOpenConns sets the maximum number of open connections to the database.
   910  //
   911  // If MaxIdleConns is greater than 0 and the new MaxOpenConns is less than
   912  // MaxIdleConns, then MaxIdleConns will be reduced to match the new
   913  // MaxOpenConns limit.
   914  //
   915  // If n <= 0, then there is no limit on the number of open connections.
   916  // The default is 0 (unlimited).
   917  func (db *DB) SetMaxOpenConns(n int) {
   918  	db.mu.Lock()
   919  	db.maxOpen = n
   920  	if n < 0 {
   921  		db.maxOpen = 0
   922  	}
   923  	syncMaxIdle := db.maxOpen > 0 && db.maxIdleConnsLocked() > db.maxOpen
   924  	db.mu.Unlock()
   925  	if syncMaxIdle {
   926  		db.SetMaxIdleConns(n)
   927  	}
   928  }
   929  
   930  // SetConnMaxLifetime sets the maximum amount of time a connection may be reused.
   931  //
   932  // Expired connections may be closed lazily before reuse.
   933  //
   934  // If d <= 0, connections are reused forever.
   935  func (db *DB) SetConnMaxLifetime(d time.Duration) {
   936  	if d < 0 {
   937  		d = 0
   938  	}
   939  	db.mu.Lock()
   940  	// wake cleaner up when lifetime is shortened.
   941  	if d > 0 && d < db.maxLifetime && db.cleanerCh != nil {
   942  		select {
   943  		case db.cleanerCh <- struct{}{}:
   944  		default:
   945  		}
   946  	}
   947  	db.maxLifetime = d
   948  	db.startCleanerLocked()
   949  	db.mu.Unlock()
   950  }
   951  
   952  // startCleanerLocked starts connectionCleaner if needed.
   953  func (db *DB) startCleanerLocked() {
   954  	if db.maxLifetime > 0 && db.numOpen > 0 && db.cleanerCh == nil {
   955  		db.cleanerCh = make(chan struct{}, 1)
   956  		go db.connectionCleaner(db.maxLifetime)
   957  	}
   958  }
   959  
   960  func (db *DB) connectionCleaner(d time.Duration) {
   961  	const minInterval = time.Second
   962  
   963  	if d < minInterval {
   964  		d = minInterval
   965  	}
   966  	t := time.NewTimer(d)
   967  
   968  	for {
   969  		select {
   970  		case <-t.C:
   971  		case <-db.cleanerCh: // maxLifetime was changed or db was closed.
   972  		}
   973  
   974  		db.mu.Lock()
   975  		d = db.maxLifetime
   976  		if db.closed || db.numOpen == 0 || d <= 0 {
   977  			db.cleanerCh = nil
   978  			db.mu.Unlock()
   979  			return
   980  		}
   981  
   982  		expiredSince := nowFunc().Add(-d)
   983  		var closing []*driverConn
   984  		for i := 0; i < len(db.freeConn); i++ {
   985  			c := db.freeConn[i]
   986  			if c.createdAt.Before(expiredSince) {
   987  				closing = append(closing, c)
   988  				last := len(db.freeConn) - 1
   989  				db.freeConn[i] = db.freeConn[last]
   990  				db.freeConn[last] = nil
   991  				db.freeConn = db.freeConn[:last]
   992  				i--
   993  			}
   994  		}
   995  		db.maxLifetimeClosed += int64(len(closing))
   996  		db.mu.Unlock()
   997  
   998  		for _, c := range closing {
   999  			c.Close()
  1000  		}
  1001  
  1002  		if d < minInterval {
  1003  			d = minInterval
  1004  		}
  1005  		t.Reset(d)
  1006  	}
  1007  }
  1008  
  1009  // DBStats contains database statistics.
  1010  type DBStats struct {
  1011  	MaxOpenConnections int // Maximum number of open connections to the database.
  1012  
  1013  	// Pool Status
  1014  	OpenConnections int // The number of established connections both in use and idle.
  1015  	InUse           int // The number of connections currently in use.
  1016  	Idle            int // The number of idle connections.
  1017  
  1018  	// Counters
  1019  	WaitCount         int64         // The total number of connections waited for.
  1020  	WaitDuration      time.Duration // The total time blocked waiting for a new connection.
  1021  	MaxIdleClosed     int64         // The total number of connections closed due to SetMaxIdleConns.
  1022  	MaxLifetimeClosed int64         // The total number of connections closed due to SetConnMaxLifetime.
  1023  }
  1024  
  1025  // Stats returns database statistics.
  1026  func (db *DB) Stats() DBStats {
  1027  	wait := atomic.LoadInt64(&db.waitDuration)
  1028  
  1029  	db.mu.Lock()
  1030  	defer db.mu.Unlock()
  1031  
  1032  	stats := DBStats{
  1033  		MaxOpenConnections: db.maxOpen,
  1034  
  1035  		Idle:            len(db.freeConn),
  1036  		OpenConnections: db.numOpen,
  1037  		InUse:           db.numOpen - len(db.freeConn),
  1038  
  1039  		WaitCount:         db.waitCount,
  1040  		WaitDuration:      time.Duration(wait),
  1041  		MaxIdleClosed:     db.maxIdleClosed,
  1042  		MaxLifetimeClosed: db.maxLifetimeClosed,
  1043  	}
  1044  	return stats
  1045  }
  1046  
  1047  // Assumes db.mu is locked.
  1048  // If there are connRequests and the connection limit hasn't been reached,
  1049  // then tell the connectionOpener to open new connections.
  1050  func (db *DB) maybeOpenNewConnections() {
  1051  	numRequests := len(db.connRequests)
  1052  	if db.maxOpen > 0 {
  1053  		numCanOpen := db.maxOpen - db.numOpen
  1054  		if numRequests > numCanOpen {
  1055  			numRequests = numCanOpen
  1056  		}
  1057  	}
  1058  	for numRequests > 0 {
  1059  		db.numOpen++ // optimistically
  1060  		numRequests--
  1061  		if db.closed {
  1062  			return
  1063  		}
  1064  		db.openerCh <- struct{}{}
  1065  	}
  1066  }
  1067  
  1068  // Runs in a separate goroutine, opens new connections when requested.
  1069  func (db *DB) connectionOpener(ctx context.Context) {
  1070  	for {
  1071  		select {
  1072  		case <-ctx.Done():
  1073  			return
  1074  		case <-db.openerCh:
  1075  			db.openNewConnection(ctx)
  1076  		}
  1077  	}
  1078  }
  1079  
  1080  // Open one new connection
  1081  func (db *DB) openNewConnection(ctx context.Context) {
  1082  	// maybeOpenNewConnctions has already executed db.numOpen++ before it sent
  1083  	// on db.openerCh. This function must execute db.numOpen-- if the
  1084  	// connection fails or is closed before returning.
  1085  	ci, err := db.connector.Connect(ctx)
  1086  	db.mu.Lock()
  1087  	defer db.mu.Unlock()
  1088  	if db.closed {
  1089  		if err == nil {
  1090  			ci.Close()
  1091  		}
  1092  		db.numOpen--
  1093  		return
  1094  	}
  1095  	if err != nil {
  1096  		db.numOpen--
  1097  		db.putConnDBLocked(nil, err)
  1098  		db.maybeOpenNewConnections()
  1099  		return
  1100  	}
  1101  	dc := &driverConn{
  1102  		db:        db,
  1103  		createdAt: nowFunc(),
  1104  		ci:        ci,
  1105  	}
  1106  	if db.putConnDBLocked(dc, err) {
  1107  		db.addDepLocked(dc, dc)
  1108  	} else {
  1109  		db.numOpen--
  1110  		ci.Close()
  1111  	}
  1112  }
  1113  
  1114  // connRequest represents one request for a new connection
  1115  // When there are no idle connections available, DB.conn will create
  1116  // a new connRequest and put it on the db.connRequests list.
  1117  type connRequest struct {
  1118  	conn *driverConn
  1119  	err  error
  1120  }
  1121  
  1122  var errDBClosed = errors.New("sql: database is closed")
  1123  
  1124  // nextRequestKeyLocked returns the next connection request key.
  1125  // It is assumed that nextRequest will not overflow.
  1126  func (db *DB) nextRequestKeyLocked() uint64 {
  1127  	next := db.nextRequest
  1128  	db.nextRequest++
  1129  	return next
  1130  }
  1131  
  1132  // conn returns a newly-opened or cached *driverConn.
  1133  func (db *DB) conn(ctx context.Context, strategy connReuseStrategy) (*driverConn, error) {
  1134  	db.mu.Lock()
  1135  	if db.closed {
  1136  		db.mu.Unlock()
  1137  		return nil, errDBClosed
  1138  	}
  1139  	// Check if the context is expired.
  1140  	select {
  1141  	default:
  1142  	case <-ctx.Done():
  1143  		db.mu.Unlock()
  1144  		return nil, ctx.Err()
  1145  	}
  1146  	lifetime := db.maxLifetime
  1147  
  1148  	// Prefer a free connection, if possible.
  1149  	numFree := len(db.freeConn)
  1150  	if strategy == cachedOrNewConn && numFree > 0 {
  1151  		conn := db.freeConn[0]
  1152  		copy(db.freeConn, db.freeConn[1:])
  1153  		db.freeConn = db.freeConn[:numFree-1]
  1154  		conn.inUse = true
  1155  		db.mu.Unlock()
  1156  		if conn.expired(lifetime) {
  1157  			conn.Close()
  1158  			return nil, driver.ErrBadConn
  1159  		}
  1160  
  1161  		// Reset the session if required.
  1162  		if err := conn.resetSession(ctx); err == driver.ErrBadConn {
  1163  			conn.Close()
  1164  			return nil, driver.ErrBadConn
  1165  		}
  1166  
  1167  		return conn, nil
  1168  	}
  1169  
  1170  	// Out of free connections or we were asked not to use one. If we're not
  1171  	// allowed to open any more connections, make a request and wait.
  1172  	if db.maxOpen > 0 && db.numOpen >= db.maxOpen {
  1173  		// Make the connRequest channel. It's buffered so that the
  1174  		// connectionOpener doesn't block while waiting for the req to be read.
  1175  		req := make(chan connRequest, 1)
  1176  		reqKey := db.nextRequestKeyLocked()
  1177  		db.connRequests[reqKey] = req
  1178  		db.waitCount++
  1179  		db.mu.Unlock()
  1180  
  1181  		waitStart := time.Now()
  1182  
  1183  		// Timeout the connection request with the context.
  1184  		select {
  1185  		case <-ctx.Done():
  1186  			// Remove the connection request and ensure no value has been sent
  1187  			// on it after removing.
  1188  			db.mu.Lock()
  1189  			delete(db.connRequests, reqKey)
  1190  			db.mu.Unlock()
  1191  
  1192  			atomic.AddInt64(&db.waitDuration, int64(time.Since(waitStart)))
  1193  
  1194  			select {
  1195  			default:
  1196  			case ret, ok := <-req:
  1197  				if ok && ret.conn != nil {
  1198  					db.putConn(ret.conn, ret.err, false)
  1199  				}
  1200  			}
  1201  			return nil, ctx.Err()
  1202  		case ret, ok := <-req:
  1203  			atomic.AddInt64(&db.waitDuration, int64(time.Since(waitStart)))
  1204  
  1205  			if !ok {
  1206  				return nil, errDBClosed
  1207  			}
  1208  			// Only check if the connection is expired if the strategy is cachedOrNewConns.
  1209  			// If we require a new connection, just re-use the connection without looking
  1210  			// at the expiry time. If it is expired, it will be checked when it is placed
  1211  			// back into the connection pool.
  1212  			// This prioritizes giving a valid connection to a client over the exact connection
  1213  			// lifetime, which could expire exactly after this point anyway.
  1214  			if strategy == cachedOrNewConn && ret.err == nil && ret.conn.expired(lifetime) {
  1215  				ret.conn.Close()
  1216  				return nil, driver.ErrBadConn
  1217  			}
  1218  			if ret.conn == nil {
  1219  				return nil, ret.err
  1220  			}
  1221  
  1222  			// Reset the session if required.
  1223  			if err := ret.conn.resetSession(ctx); err == driver.ErrBadConn {
  1224  				ret.conn.Close()
  1225  				return nil, driver.ErrBadConn
  1226  			}
  1227  			return ret.conn, ret.err
  1228  		}
  1229  	}
  1230  
  1231  	db.numOpen++ // optimistically
  1232  	db.mu.Unlock()
  1233  	ci, err := db.connector.Connect(ctx)
  1234  	if err != nil {
  1235  		db.mu.Lock()
  1236  		db.numOpen-- // correct for earlier optimism
  1237  		db.maybeOpenNewConnections()
  1238  		db.mu.Unlock()
  1239  		return nil, err
  1240  	}
  1241  	db.mu.Lock()
  1242  	dc := &driverConn{
  1243  		db:        db,
  1244  		createdAt: nowFunc(),
  1245  		ci:        ci,
  1246  		inUse:     true,
  1247  	}
  1248  	db.addDepLocked(dc, dc)
  1249  	db.mu.Unlock()
  1250  	return dc, nil
  1251  }
  1252  
  1253  // putConnHook is a hook for testing.
  1254  var putConnHook func(*DB, *driverConn)
  1255  
  1256  // noteUnusedDriverStatement notes that ds is no longer used and should
  1257  // be closed whenever possible (when c is next not in use), unless c is
  1258  // already closed.
  1259  func (db *DB) noteUnusedDriverStatement(c *driverConn, ds *driverStmt) {
  1260  	db.mu.Lock()
  1261  	defer db.mu.Unlock()
  1262  	if c.inUse {
  1263  		c.onPut = append(c.onPut, func() {
  1264  			ds.Close()
  1265  		})
  1266  	} else {
  1267  		c.Lock()
  1268  		fc := c.finalClosed
  1269  		c.Unlock()
  1270  		if !fc {
  1271  			ds.Close()
  1272  		}
  1273  	}
  1274  }
  1275  
  1276  // debugGetPut determines whether getConn & putConn calls' stack traces
  1277  // are returned for more verbose crashes.
  1278  const debugGetPut = false
  1279  
  1280  // putConn adds a connection to the db's free pool.
  1281  // err is optionally the last error that occurred on this connection.
  1282  func (db *DB) putConn(dc *driverConn, err error, resetSession bool) {
  1283  	if err != driver.ErrBadConn {
  1284  		if !dc.validateConnection(resetSession) {
  1285  			err = driver.ErrBadConn
  1286  		}
  1287  	}
  1288  	db.mu.Lock()
  1289  	if !dc.inUse {
  1290  		db.mu.Unlock()
  1291  		if debugGetPut {
  1292  			fmt.Printf("putConn(%v) DUPLICATE was: %s\n\nPREVIOUS was: %s", dc, stack(), db.lastPut[dc])
  1293  		}
  1294  		panic("sql: connection returned that was never out")
  1295  	}
  1296  
  1297  	if err != driver.ErrBadConn && dc.expired(db.maxLifetime) {
  1298  		err = driver.ErrBadConn
  1299  	}
  1300  	if debugGetPut {
  1301  		db.lastPut[dc] = stack()
  1302  	}
  1303  	dc.inUse = false
  1304  
  1305  	for _, fn := range dc.onPut {
  1306  		fn()
  1307  	}
  1308  	dc.onPut = nil
  1309  
  1310  	if err == driver.ErrBadConn {
  1311  		// Don't reuse bad connections.
  1312  		// Since the conn is considered bad and is being discarded, treat it
  1313  		// as closed. Don't decrement the open count here, finalClose will
  1314  		// take care of that.
  1315  		db.maybeOpenNewConnections()
  1316  		db.mu.Unlock()
  1317  		dc.Close()
  1318  		return
  1319  	}
  1320  	if putConnHook != nil {
  1321  		putConnHook(db, dc)
  1322  	}
  1323  	added := db.putConnDBLocked(dc, nil)
  1324  	db.mu.Unlock()
  1325  
  1326  	if !added {
  1327  		dc.Close()
  1328  		return
  1329  	}
  1330  }
  1331  
  1332  // Satisfy a connRequest or put the driverConn in the idle pool and return true
  1333  // or return false.
  1334  // putConnDBLocked will satisfy a connRequest if there is one, or it will
  1335  // return the *driverConn to the freeConn list if err == nil and the idle
  1336  // connection limit will not be exceeded.
  1337  // If err != nil, the value of dc is ignored.
  1338  // If err == nil, then dc must not equal nil.
  1339  // If a connRequest was fulfilled or the *driverConn was placed in the
  1340  // freeConn list, then true is returned, otherwise false is returned.
  1341  func (db *DB) putConnDBLocked(dc *driverConn, err error) bool {
  1342  	if db.closed {
  1343  		return false
  1344  	}
  1345  	if db.maxOpen > 0 && db.numOpen > db.maxOpen {
  1346  		return false
  1347  	}
  1348  	if c := len(db.connRequests); c > 0 {
  1349  		var req chan connRequest
  1350  		var reqKey uint64
  1351  		for reqKey, req = range db.connRequests {
  1352  			break
  1353  		}
  1354  		delete(db.connRequests, reqKey) // Remove from pending requests.
  1355  		if err == nil {
  1356  			dc.inUse = true
  1357  		}
  1358  		req <- connRequest{
  1359  			conn: dc,
  1360  			err:  err,
  1361  		}
  1362  		return true
  1363  	} else if err == nil && !db.closed {
  1364  		if db.maxIdleConnsLocked() > len(db.freeConn) {
  1365  			db.freeConn = append(db.freeConn, dc)
  1366  			db.startCleanerLocked()
  1367  			return true
  1368  		}
  1369  		db.maxIdleClosed++
  1370  	}
  1371  	return false
  1372  }
  1373  
  1374  // maxBadConnRetries is the number of maximum retries if the driver returns
  1375  // driver.ErrBadConn to signal a broken connection before forcing a new
  1376  // connection to be opened.
  1377  const maxBadConnRetries = 2
  1378  
  1379  // PrepareContext creates a prepared statement for later queries or executions.
  1380  // Multiple queries or executions may be run concurrently from the
  1381  // returned statement.
  1382  // The caller must call the statement's Close method
  1383  // when the statement is no longer needed.
  1384  //
  1385  // The provided context is used for the preparation of the statement, not for the
  1386  // execution of the statement.
  1387  func (db *DB) PrepareContext(ctx context.Context, query string) (*Stmt, error) {
  1388  	var stmt *Stmt
  1389  	var err error
  1390  	for i := 0; i < maxBadConnRetries; i++ {
  1391  		stmt, err = db.prepare(ctx, query, cachedOrNewConn)
  1392  		if err != driver.ErrBadConn {
  1393  			break
  1394  		}
  1395  	}
  1396  	if err == driver.ErrBadConn {
  1397  		return db.prepare(ctx, query, alwaysNewConn)
  1398  	}
  1399  	return stmt, err
  1400  }
  1401  
  1402  // Prepare creates a prepared statement for later queries or executions.
  1403  // Multiple queries or executions may be run concurrently from the
  1404  // returned statement.
  1405  // The caller must call the statement's Close method
  1406  // when the statement is no longer needed.
  1407  func (db *DB) Prepare(query string) (*Stmt, error) {
  1408  	return db.PrepareContext(context.Background(), query)
  1409  }
  1410  
  1411  func (db *DB) prepare(ctx context.Context, query string, strategy connReuseStrategy) (*Stmt, error) {
  1412  	// TODO: check if db.driver supports an optional
  1413  	// driver.Preparer interface and call that instead, if so,
  1414  	// otherwise we make a prepared statement that's bound
  1415  	// to a connection, and to execute this prepared statement
  1416  	// we either need to use this connection (if it's free), else
  1417  	// get a new connection + re-prepare + execute on that one.
  1418  	dc, err := db.conn(ctx, strategy)
  1419  	if err != nil {
  1420  		return nil, err
  1421  	}
  1422  	return db.prepareDC(ctx, dc, dc.releaseConn, nil, query)
  1423  }
  1424  
  1425  // prepareDC prepares a query on the driverConn and calls release before
  1426  // returning. When cg == nil it implies that a connection pool is used, and
  1427  // when cg != nil only a single driver connection is used.
  1428  func (db *DB) prepareDC(ctx context.Context, dc *driverConn, release func(error), cg stmtConnGrabber, query string) (*Stmt, error) {
  1429  	var ds *driverStmt
  1430  	var err error
  1431  	defer func() {
  1432  		release(err)
  1433  	}()
  1434  	withLock(dc, func() {
  1435  		ds, err = dc.prepareLocked(ctx, cg, query)
  1436  	})
  1437  	if err != nil {
  1438  		return nil, err
  1439  	}
  1440  	stmt := &Stmt{
  1441  		db:    db,
  1442  		query: query,
  1443  		cg:    cg,
  1444  		cgds:  ds,
  1445  	}
  1446  
  1447  	// When cg == nil this statement will need to keep track of various
  1448  	// connections they are prepared on and record the stmt dependency on
  1449  	// the DB.
  1450  	if cg == nil {
  1451  		stmt.css = []connStmt{{dc, ds}}
  1452  		stmt.lastNumClosed = atomic.LoadUint64(&db.numClosed)
  1453  		db.addDep(stmt, stmt)
  1454  	}
  1455  	return stmt, nil
  1456  }
  1457  
  1458  // ExecContext executes a query without returning any rows.
  1459  // The args are for any placeholder parameters in the query.
  1460  func (db *DB) ExecContext(ctx context.Context, query string, args ...interface{}) (Result, error) {
  1461  	var res Result
  1462  	var err error
  1463  	for i := 0; i < maxBadConnRetries; i++ {
  1464  		res, err = db.exec(ctx, query, args, cachedOrNewConn)
  1465  		if err != driver.ErrBadConn {
  1466  			break
  1467  		}
  1468  	}
  1469  	if err == driver.ErrBadConn {
  1470  		return db.exec(ctx, query, args, alwaysNewConn)
  1471  	}
  1472  	return res, err
  1473  }
  1474  
  1475  // Exec executes a query without returning any rows.
  1476  // The args are for any placeholder parameters in the query.
  1477  func (db *DB) Exec(query string, args ...interface{}) (Result, error) {
  1478  	return db.ExecContext(context.Background(), query, args...)
  1479  }
  1480  
  1481  func (db *DB) exec(ctx context.Context, query string, args []interface{}, strategy connReuseStrategy) (Result, error) {
  1482  	dc, err := db.conn(ctx, strategy)
  1483  	if err != nil {
  1484  		return nil, err
  1485  	}
  1486  	return db.execDC(ctx, dc, dc.releaseConn, query, args)
  1487  }
  1488  
  1489  func (db *DB) execDC(ctx context.Context, dc *driverConn, release func(error), query string, args []interface{}) (res Result, err error) {
  1490  	defer func() {
  1491  		release(err)
  1492  	}()
  1493  	execerCtx, ok := dc.ci.(driver.ExecerContext)
  1494  	var execer driver.Execer
  1495  	if !ok {
  1496  		execer, ok = dc.ci.(driver.Execer)
  1497  	}
  1498  	if ok {
  1499  		var nvdargs []driver.NamedValue
  1500  		var resi driver.Result
  1501  		withLock(dc, func() {
  1502  			nvdargs, err = driverArgsConnLocked(dc.ci, nil, args)
  1503  			if err != nil {
  1504  				return
  1505  			}
  1506  			resi, err = ctxDriverExec(ctx, execerCtx, execer, query, nvdargs)
  1507  		})
  1508  		if err != driver.ErrSkip {
  1509  			if err != nil {
  1510  				return nil, err
  1511  			}
  1512  			return driverResult{dc, resi}, nil
  1513  		}
  1514  	}
  1515  
  1516  	var si driver.Stmt
  1517  	withLock(dc, func() {
  1518  		si, err = ctxDriverPrepare(ctx, dc.ci, query)
  1519  	})
  1520  	if err != nil {
  1521  		return nil, err
  1522  	}
  1523  	ds := &driverStmt{Locker: dc, si: si}
  1524  	defer ds.Close()
  1525  	return resultFromStatement(ctx, dc.ci, ds, args...)
  1526  }
  1527  
  1528  // QueryContext executes a query that returns rows, typically a SELECT.
  1529  // The args are for any placeholder parameters in the query.
  1530  func (db *DB) QueryContext(ctx context.Context, query string, args ...interface{}) (*Rows, error) {
  1531  	var rows *Rows
  1532  	var err error
  1533  	for i := 0; i < maxBadConnRetries; i++ {
  1534  		rows, err = db.query(ctx, query, args, cachedOrNewConn)
  1535  		if err != driver.ErrBadConn {
  1536  			break
  1537  		}
  1538  	}
  1539  	if err == driver.ErrBadConn {
  1540  		return db.query(ctx, query, args, alwaysNewConn)
  1541  	}
  1542  	return rows, err
  1543  }
  1544  
  1545  // Query executes a query that returns rows, typically a SELECT.
  1546  // The args are for any placeholder parameters in the query.
  1547  func (db *DB) Query(query string, args ...interface{}) (*Rows, error) {
  1548  	return db.QueryContext(context.Background(), query, args...)
  1549  }
  1550  
  1551  func (db *DB) query(ctx context.Context, query string, args []interface{}, strategy connReuseStrategy) (*Rows, error) {
  1552  	dc, err := db.conn(ctx, strategy)
  1553  	if err != nil {
  1554  		return nil, err
  1555  	}
  1556  
  1557  	return db.queryDC(ctx, nil, dc, dc.releaseConn, query, args)
  1558  }
  1559  
  1560  // queryDC executes a query on the given connection.
  1561  // The connection gets released by the releaseConn function.
  1562  // The ctx context is from a query method and the txctx context is from an
  1563  // optional transaction context.
  1564  func (db *DB) queryDC(ctx, txctx context.Context, dc *driverConn, releaseConn func(error), query string, args []interface{}) (*Rows, error) {
  1565  	queryerCtx, ok := dc.ci.(driver.QueryerContext)
  1566  	var queryer driver.Queryer
  1567  	if !ok {
  1568  		queryer, ok = dc.ci.(driver.Queryer)
  1569  	}
  1570  	if ok {
  1571  		var nvdargs []driver.NamedValue
  1572  		var rowsi driver.Rows
  1573  		var err error
  1574  		withLock(dc, func() {
  1575  			nvdargs, err = driverArgsConnLocked(dc.ci, nil, args)
  1576  			if err != nil {
  1577  				return
  1578  			}
  1579  			rowsi, err = ctxDriverQuery(ctx, queryerCtx, queryer, query, nvdargs)
  1580  		})
  1581  		if err != driver.ErrSkip {
  1582  			if err != nil {
  1583  				releaseConn(err)
  1584  				return nil, err
  1585  			}
  1586  			// Note: ownership of dc passes to the *Rows, to be freed
  1587  			// with releaseConn.
  1588  			rows := &Rows{
  1589  				dc:          dc,
  1590  				releaseConn: releaseConn,
  1591  				rowsi:       rowsi,
  1592  			}
  1593  			rows.initContextClose(ctx, txctx)
  1594  			return rows, nil
  1595  		}
  1596  	}
  1597  
  1598  	var si driver.Stmt
  1599  	var err error
  1600  	withLock(dc, func() {
  1601  		si, err = ctxDriverPrepare(ctx, dc.ci, query)
  1602  	})
  1603  	if err != nil {
  1604  		releaseConn(err)
  1605  		return nil, err
  1606  	}
  1607  
  1608  	ds := &driverStmt{Locker: dc, si: si}
  1609  	rowsi, err := rowsiFromStatement(ctx, dc.ci, ds, args...)
  1610  	if err != nil {
  1611  		ds.Close()
  1612  		releaseConn(err)
  1613  		return nil, err
  1614  	}
  1615  
  1616  	// Note: ownership of ci passes to the *Rows, to be freed
  1617  	// with releaseConn.
  1618  	rows := &Rows{
  1619  		dc:          dc,
  1620  		releaseConn: releaseConn,
  1621  		rowsi:       rowsi,
  1622  		closeStmt:   ds,
  1623  	}
  1624  	rows.initContextClose(ctx, txctx)
  1625  	return rows, nil
  1626  }
  1627  
  1628  // QueryRowContext executes a query that is expected to return at most one row.
  1629  // QueryRowContext always returns a non-nil value. Errors are deferred until
  1630  // Row's Scan method is called.
  1631  // If the query selects no rows, the *Row's Scan will return ErrNoRows.
  1632  // Otherwise, the *Row's Scan scans the first selected row and discards
  1633  // the rest.
  1634  func (db *DB) QueryRowContext(ctx context.Context, query string, args ...interface{}) *Row {
  1635  	rows, err := db.QueryContext(ctx, query, args...)
  1636  	return &Row{rows: rows, err: err}
  1637  }
  1638  
  1639  // QueryRow executes a query that is expected to return at most one row.
  1640  // QueryRow always returns a non-nil value. Errors are deferred until
  1641  // Row's Scan method is called.
  1642  // If the query selects no rows, the *Row's Scan will return ErrNoRows.
  1643  // Otherwise, the *Row's Scan scans the first selected row and discards
  1644  // the rest.
  1645  func (db *DB) QueryRow(query string, args ...interface{}) *Row {
  1646  	return db.QueryRowContext(context.Background(), query, args...)
  1647  }
  1648  
  1649  // BeginTx starts a transaction.
  1650  //
  1651  // The provided context is used until the transaction is committed or rolled back.
  1652  // If the context is canceled, the sql package will roll back
  1653  // the transaction. Tx.Commit will return an error if the context provided to
  1654  // BeginTx is canceled.
  1655  //
  1656  // The provided TxOptions is optional and may be nil if defaults should be used.
  1657  // If a non-default isolation level is used that the driver doesn't support,
  1658  // an error will be returned.
  1659  func (db *DB) BeginTx(ctx context.Context, opts *TxOptions) (*Tx, error) {
  1660  	var tx *Tx
  1661  	var err error
  1662  	for i := 0; i < maxBadConnRetries; i++ {
  1663  		tx, err = db.begin(ctx, opts, cachedOrNewConn)
  1664  		if err != driver.ErrBadConn {
  1665  			break
  1666  		}
  1667  	}
  1668  	if err == driver.ErrBadConn {
  1669  		return db.begin(ctx, opts, alwaysNewConn)
  1670  	}
  1671  	return tx, err
  1672  }
  1673  
  1674  // Begin starts a transaction. The default isolation level is dependent on
  1675  // the driver.
  1676  func (db *DB) Begin() (*Tx, error) {
  1677  	return db.BeginTx(context.Background(), nil)
  1678  }
  1679  
  1680  func (db *DB) begin(ctx context.Context, opts *TxOptions, strategy connReuseStrategy) (tx *Tx, err error) {
  1681  	dc, err := db.conn(ctx, strategy)
  1682  	if err != nil {
  1683  		return nil, err
  1684  	}
  1685  	return db.beginDC(ctx, dc, dc.releaseConn, opts)
  1686  }
  1687  
  1688  // beginDC starts a transaction. The provided dc must be valid and ready to use.
  1689  func (db *DB) beginDC(ctx context.Context, dc *driverConn, release func(error), opts *TxOptions) (tx *Tx, err error) {
  1690  	var txi driver.Tx
  1691  	keepConnOnRollback := false
  1692  	withLock(dc, func() {
  1693  		_, hasSessionResetter := dc.ci.(driver.SessionResetter)
  1694  		_, hasConnectionValidator := dc.ci.(validator)
  1695  		keepConnOnRollback = hasSessionResetter && hasConnectionValidator
  1696  		txi, err = ctxDriverBegin(ctx, opts, dc.ci)
  1697  	})
  1698  	if err != nil {
  1699  		release(err)
  1700  		return nil, err
  1701  	}
  1702  
  1703  	// Schedule the transaction to rollback when the context is cancelled.
  1704  	// The cancel function in Tx will be called after done is set to true.
  1705  	ctx, cancel := context.WithCancel(ctx)
  1706  	tx = &Tx{
  1707  		db:                 db,
  1708  		dc:                 dc,
  1709  		releaseConn:        release,
  1710  		txi:                txi,
  1711  		cancel:             cancel,
  1712  		keepConnOnRollback: keepConnOnRollback,
  1713  		ctx:                ctx,
  1714  	}
  1715  	go tx.awaitDone()
  1716  	return tx, nil
  1717  }
  1718  
  1719  // Driver returns the database's underlying driver.
  1720  func (db *DB) Driver() driver.Driver {
  1721  	return db.connector.Driver()
  1722  }
  1723  
  1724  // ErrConnDone is returned by any operation that is performed on a connection
  1725  // that has already been returned to the connection pool.
  1726  var ErrConnDone = errors.New("sql: connection is already closed")
  1727  
  1728  // Conn returns a single connection by either opening a new connection
  1729  // or returning an existing connection from the connection pool. Conn will
  1730  // block until either a connection is returned or ctx is canceled.
  1731  // Queries run on the same Conn will be run in the same database session.
  1732  //
  1733  // Every Conn must be returned to the database pool after use by
  1734  // calling Conn.Close.
  1735  func (db *DB) Conn(ctx context.Context) (*Conn, error) {
  1736  	var dc *driverConn
  1737  	var err error
  1738  	for i := 0; i < maxBadConnRetries; i++ {
  1739  		dc, err = db.conn(ctx, cachedOrNewConn)
  1740  		if err != driver.ErrBadConn {
  1741  			break
  1742  		}
  1743  	}
  1744  	if err == driver.ErrBadConn {
  1745  		dc, err = db.conn(ctx, alwaysNewConn)
  1746  	}
  1747  	if err != nil {
  1748  		return nil, err
  1749  	}
  1750  
  1751  	conn := &Conn{
  1752  		db: db,
  1753  		dc: dc,
  1754  	}
  1755  	return conn, nil
  1756  }
  1757  
  1758  type releaseConn func(error)
  1759  
  1760  // Conn represents a single database connection rather than a pool of database
  1761  // connections. Prefer running queries from DB unless there is a specific
  1762  // need for a continuous single database connection.
  1763  //
  1764  // A Conn must call Close to return the connection to the database pool
  1765  // and may do so concurrently with a running query.
  1766  //
  1767  // After a call to Close, all operations on the
  1768  // connection fail with ErrConnDone.
  1769  type Conn struct {
  1770  	db *DB
  1771  
  1772  	// closemu prevents the connection from closing while there
  1773  	// is an active query. It is held for read during queries
  1774  	// and exclusively during close.
  1775  	closemu sync.RWMutex
  1776  
  1777  	// dc is owned until close, at which point
  1778  	// it's returned to the connection pool.
  1779  	dc *driverConn
  1780  
  1781  	// done transitions from 0 to 1 exactly once, on close.
  1782  	// Once done, all operations fail with ErrConnDone.
  1783  	// Use atomic operations on value when checking value.
  1784  	done int32
  1785  }
  1786  
  1787  // grabConn takes a context to implement stmtConnGrabber
  1788  // but the context is not used.
  1789  func (c *Conn) grabConn(context.Context) (*driverConn, releaseConn, error) {
  1790  	if atomic.LoadInt32(&c.done) != 0 {
  1791  		return nil, nil, ErrConnDone
  1792  	}
  1793  	c.closemu.RLock()
  1794  	return c.dc, c.closemuRUnlockCondReleaseConn, nil
  1795  }
  1796  
  1797  // PingContext verifies the connection to the database is still alive.
  1798  func (c *Conn) PingContext(ctx context.Context) error {
  1799  	dc, release, err := c.grabConn(ctx)
  1800  	if err != nil {
  1801  		return err
  1802  	}
  1803  	return c.db.pingDC(ctx, dc, release)
  1804  }
  1805  
  1806  // ExecContext executes a query without returning any rows.
  1807  // The args are for any placeholder parameters in the query.
  1808  func (c *Conn) ExecContext(ctx context.Context, query string, args ...interface{}) (Result, error) {
  1809  	dc, release, err := c.grabConn(ctx)
  1810  	if err != nil {
  1811  		return nil, err
  1812  	}
  1813  	return c.db.execDC(ctx, dc, release, query, args)
  1814  }
  1815  
  1816  // QueryContext executes a query that returns rows, typically a SELECT.
  1817  // The args are for any placeholder parameters in the query.
  1818  func (c *Conn) QueryContext(ctx context.Context, query string, args ...interface{}) (*Rows, error) {
  1819  	dc, release, err := c.grabConn(ctx)
  1820  	if err != nil {
  1821  		return nil, err
  1822  	}
  1823  	return c.db.queryDC(ctx, nil, dc, release, query, args)
  1824  }
  1825  
  1826  // QueryRowContext executes a query that is expected to return at most one row.
  1827  // QueryRowContext always returns a non-nil value. Errors are deferred until
  1828  // Row's Scan method is called.
  1829  // If the query selects no rows, the *Row's Scan will return ErrNoRows.
  1830  // Otherwise, the *Row's Scan scans the first selected row and discards
  1831  // the rest.
  1832  func (c *Conn) QueryRowContext(ctx context.Context, query string, args ...interface{}) *Row {
  1833  	rows, err := c.QueryContext(ctx, query, args...)
  1834  	return &Row{rows: rows, err: err}
  1835  }
  1836  
  1837  // PrepareContext creates a prepared statement for later queries or executions.
  1838  // Multiple queries or executions may be run concurrently from the
  1839  // returned statement.
  1840  // The caller must call the statement's Close method
  1841  // when the statement is no longer needed.
  1842  //
  1843  // The provided context is used for the preparation of the statement, not for the
  1844  // execution of the statement.
  1845  func (c *Conn) PrepareContext(ctx context.Context, query string) (*Stmt, error) {
  1846  	dc, release, err := c.grabConn(ctx)
  1847  	if err != nil {
  1848  		return nil, err
  1849  	}
  1850  	return c.db.prepareDC(ctx, dc, release, c, query)
  1851  }
  1852  
  1853  // Raw executes f exposing the underlying driver connection for the
  1854  // duration of f. The driverConn must not be used outside of f.
  1855  //
  1856  // Once f returns and err is nil, the Conn will continue to be usable
  1857  // until Conn.Close is called.
  1858  func (c *Conn) Raw(f func(driverConn interface{}) error) (err error) {
  1859  	var dc *driverConn
  1860  	var release releaseConn
  1861  
  1862  	// grabConn takes a context to implement stmtConnGrabber, but the context is not used.
  1863  	dc, release, err = c.grabConn(nil)
  1864  	if err != nil {
  1865  		return
  1866  	}
  1867  	fPanic := true
  1868  	dc.Mutex.Lock()
  1869  	defer func() {
  1870  		dc.Mutex.Unlock()
  1871  
  1872  		// If f panics fPanic will remain true.
  1873  		// Ensure an error is passed to release so the connection
  1874  		// may be discarded.
  1875  		if fPanic {
  1876  			err = driver.ErrBadConn
  1877  		}
  1878  		release(err)
  1879  	}()
  1880  	err = f(dc.ci)
  1881  	fPanic = false
  1882  
  1883  	return
  1884  }
  1885  
  1886  // BeginTx starts a transaction.
  1887  //
  1888  // The provided context is used until the transaction is committed or rolled back.
  1889  // If the context is canceled, the sql package will roll back
  1890  // the transaction. Tx.Commit will return an error if the context provided to
  1891  // BeginTx is canceled.
  1892  //
  1893  // The provided TxOptions is optional and may be nil if defaults should be used.
  1894  // If a non-default isolation level is used that the driver doesn't support,
  1895  // an error will be returned.
  1896  func (c *Conn) BeginTx(ctx context.Context, opts *TxOptions) (*Tx, error) {
  1897  	dc, release, err := c.grabConn(ctx)
  1898  	if err != nil {
  1899  		return nil, err
  1900  	}
  1901  	return c.db.beginDC(ctx, dc, release, opts)
  1902  }
  1903  
  1904  // closemuRUnlockCondReleaseConn read unlocks closemu
  1905  // as the sql operation is done with the dc.
  1906  func (c *Conn) closemuRUnlockCondReleaseConn(err error) {
  1907  	c.closemu.RUnlock()
  1908  	if err == driver.ErrBadConn {
  1909  		c.close(err)
  1910  	}
  1911  }
  1912  
  1913  func (c *Conn) txCtx() context.Context {
  1914  	return nil
  1915  }
  1916  
  1917  func (c *Conn) close(err error) error {
  1918  	if !atomic.CompareAndSwapInt32(&c.done, 0, 1) {
  1919  		return ErrConnDone
  1920  	}
  1921  
  1922  	// Lock around releasing the driver connection
  1923  	// to ensure all queries have been stopped before doing so.
  1924  	c.closemu.Lock()
  1925  	defer c.closemu.Unlock()
  1926  
  1927  	c.dc.releaseConn(err)
  1928  	c.dc = nil
  1929  	c.db = nil
  1930  	return err
  1931  }
  1932  
  1933  // Close returns the connection to the connection pool.
  1934  // All operations after a Close will return with ErrConnDone.
  1935  // Close is safe to call concurrently with other operations and will
  1936  // block until all other operations finish. It may be useful to first
  1937  // cancel any used context and then call close directly after.
  1938  func (c *Conn) Close() error {
  1939  	return c.close(nil)
  1940  }
  1941  
  1942  // Tx is an in-progress database transaction.
  1943  //
  1944  // A transaction must end with a call to Commit or Rollback.
  1945  //
  1946  // After a call to Commit or Rollback, all operations on the
  1947  // transaction fail with ErrTxDone.
  1948  //
  1949  // The statements prepared for a transaction by calling
  1950  // the transaction's Prepare or Stmt methods are closed
  1951  // by the call to Commit or Rollback.
  1952  type Tx struct {
  1953  	db *DB
  1954  
  1955  	// closemu prevents the transaction from closing while there
  1956  	// is an active query. It is held for read during queries
  1957  	// and exclusively during close.
  1958  	closemu sync.RWMutex
  1959  
  1960  	// dc is owned exclusively until Commit or Rollback, at which point
  1961  	// it's returned with putConn.
  1962  	dc  *driverConn
  1963  	txi driver.Tx
  1964  
  1965  	// releaseConn is called once the Tx is closed to release
  1966  	// any held driverConn back to the pool.
  1967  	releaseConn func(error)
  1968  
  1969  	// done transitions from 0 to 1 exactly once, on Commit
  1970  	// or Rollback. once done, all operations fail with
  1971  	// ErrTxDone.
  1972  	// Use atomic operations on value when checking value.
  1973  	done int32
  1974  
  1975  	// keepConnOnRollback is true if the driver knows
  1976  	// how to reset the connection's session and if need be discard
  1977  	// the connection.
  1978  	keepConnOnRollback bool
  1979  
  1980  	// All Stmts prepared for this transaction. These will be closed after the
  1981  	// transaction has been committed or rolled back.
  1982  	stmts struct {
  1983  		sync.Mutex
  1984  		v []*Stmt
  1985  	}
  1986  
  1987  	// cancel is called after done transitions from 0 to 1.
  1988  	cancel func()
  1989  
  1990  	// ctx lives for the life of the transaction.
  1991  	ctx context.Context
  1992  }
  1993  
  1994  // awaitDone blocks until the context in Tx is canceled and rolls back
  1995  // the transaction if it's not already done.
  1996  func (tx *Tx) awaitDone() {
  1997  	// Wait for either the transaction to be committed or rolled
  1998  	// back, or for the associated context to be closed.
  1999  	<-tx.ctx.Done()
  2000  
  2001  	// Discard and close the connection used to ensure the
  2002  	// transaction is closed and the resources are released.  This
  2003  	// rollback does nothing if the transaction has already been
  2004  	// committed or rolled back.
  2005  	// Do not discard the connection if the connection knows
  2006  	// how to reset the session.
  2007  	discardConnection := !tx.keepConnOnRollback
  2008  	tx.rollback(discardConnection)
  2009  }
  2010  
  2011  func (tx *Tx) isDone() bool {
  2012  	return atomic.LoadInt32(&tx.done) != 0
  2013  }
  2014  
  2015  // ErrTxDone is returned by any operation that is performed on a transaction
  2016  // that has already been committed or rolled back.
  2017  var ErrTxDone = errors.New("sql: transaction has already been committed or rolled back")
  2018  
  2019  // closeLocked returns the connection to the pool and
  2020  // must only be called by Tx.rollback or Tx.Commit while
  2021  // closemu is Locked and tx already canceled.
  2022  func (tx *Tx) closeLocked(err error) {
  2023  	tx.releaseConn(err)
  2024  	tx.dc = nil
  2025  	tx.txi = nil
  2026  }
  2027  
  2028  // hookTxGrabConn specifies an optional hook to be called on
  2029  // a successful call to (*Tx).grabConn. For tests.
  2030  var hookTxGrabConn func()
  2031  
  2032  func (tx *Tx) grabConn(ctx context.Context) (*driverConn, releaseConn, error) {
  2033  	select {
  2034  	default:
  2035  	case <-ctx.Done():
  2036  		return nil, nil, ctx.Err()
  2037  	}
  2038  
  2039  	// closemu.RLock must come before the check for isDone to prevent the Tx from
  2040  	// closing while a query is executing.
  2041  	tx.closemu.RLock()
  2042  	if tx.isDone() {
  2043  		tx.closemu.RUnlock()
  2044  		return nil, nil, ErrTxDone
  2045  	}
  2046  	if hookTxGrabConn != nil { // test hook
  2047  		hookTxGrabConn()
  2048  	}
  2049  	return tx.dc, tx.closemuRUnlockRelease, nil
  2050  }
  2051  
  2052  func (tx *Tx) txCtx() context.Context {
  2053  	return tx.ctx
  2054  }
  2055  
  2056  // closemuRUnlockRelease is used as a func(error) method value in
  2057  // ExecContext and QueryContext. Unlocking in the releaseConn keeps
  2058  // the driver conn from being returned to the connection pool until
  2059  // the Rows has been closed.
  2060  func (tx *Tx) closemuRUnlockRelease(error) {
  2061  	tx.closemu.RUnlock()
  2062  }
  2063  
  2064  // Closes all Stmts prepared for this transaction.
  2065  func (tx *Tx) closePrepared() {
  2066  	tx.stmts.Lock()
  2067  	defer tx.stmts.Unlock()
  2068  	for _, stmt := range tx.stmts.v {
  2069  		stmt.Close()
  2070  	}
  2071  }
  2072  
  2073  // Commit commits the transaction.
  2074  func (tx *Tx) Commit() error {
  2075  	// Check context first to avoid transaction leak.
  2076  	// If put it behind tx.done CompareAndSwap statement, we can't ensure
  2077  	// the consistency between tx.done and the real COMMIT operation.
  2078  	select {
  2079  	default:
  2080  	case <-tx.ctx.Done():
  2081  		if atomic.LoadInt32(&tx.done) == 1 {
  2082  			return ErrTxDone
  2083  		}
  2084  		return tx.ctx.Err()
  2085  	}
  2086  	if !atomic.CompareAndSwapInt32(&tx.done, 0, 1) {
  2087  		return ErrTxDone
  2088  	}
  2089  
  2090  	// Cancel the Tx to release any active R-closemu locks.
  2091  	// This is safe to do because tx.done has already transitioned
  2092  	// from 0 to 1. Hold the W-closemu lock prior to rollback
  2093  	// to ensure no other connection has an active query.
  2094  	tx.cancel()
  2095  	tx.closemu.Lock()
  2096  	defer tx.closemu.Unlock()
  2097  
  2098  	var err error
  2099  	withLock(tx.dc, func() {
  2100  		err = tx.txi.Commit()
  2101  	})
  2102  	if err != driver.ErrBadConn {
  2103  		tx.closePrepared()
  2104  	}
  2105  	tx.closeLocked(err)
  2106  	return err
  2107  }
  2108  
  2109  var rollbackHook func()
  2110  
  2111  // rollback aborts the transaction and optionally forces the pool to discard
  2112  // the connection.
  2113  func (tx *Tx) rollback(discardConn bool) error {
  2114  	if !atomic.CompareAndSwapInt32(&tx.done, 0, 1) {
  2115  		return ErrTxDone
  2116  	}
  2117  
  2118  	if rollbackHook != nil {
  2119  		rollbackHook()
  2120  	}
  2121  
  2122  	// Cancel the Tx to release any active R-closemu locks.
  2123  	// This is safe to do because tx.done has already transitioned
  2124  	// from 0 to 1. Hold the W-closemu lock prior to rollback
  2125  	// to ensure no other connection has an active query.
  2126  	tx.cancel()
  2127  	tx.closemu.Lock()
  2128  	defer tx.closemu.Unlock()
  2129  
  2130  	var err error
  2131  	withLock(tx.dc, func() {
  2132  		err = tx.txi.Rollback()
  2133  	})
  2134  	if err != driver.ErrBadConn {
  2135  		tx.closePrepared()
  2136  	}
  2137  	if discardConn {
  2138  		err = driver.ErrBadConn
  2139  	}
  2140  	tx.closeLocked(err)
  2141  	return err
  2142  }
  2143  
  2144  // Rollback aborts the transaction.
  2145  func (tx *Tx) Rollback() error {
  2146  	return tx.rollback(false)
  2147  }
  2148  
  2149  // PrepareContext creates a prepared statement for use within a transaction.
  2150  //
  2151  // The returned statement operates within the transaction and will be closed
  2152  // when the transaction has been committed or rolled back.
  2153  //
  2154  // To use an existing prepared statement on this transaction, see Tx.Stmt.
  2155  //
  2156  // The provided context will be used for the preparation of the context, not
  2157  // for the execution of the returned statement. The returned statement
  2158  // will run in the transaction context.
  2159  func (tx *Tx) PrepareContext(ctx context.Context, query string) (*Stmt, error) {
  2160  	dc, release, err := tx.grabConn(ctx)
  2161  	if err != nil {
  2162  		return nil, err
  2163  	}
  2164  
  2165  	stmt, err := tx.db.prepareDC(ctx, dc, release, tx, query)
  2166  	if err != nil {
  2167  		return nil, err
  2168  	}
  2169  	tx.stmts.Lock()
  2170  	tx.stmts.v = append(tx.stmts.v, stmt)
  2171  	tx.stmts.Unlock()
  2172  	return stmt, nil
  2173  }
  2174  
  2175  // Prepare creates a prepared statement for use within a transaction.
  2176  //
  2177  // The returned statement operates within the transaction and can no longer
  2178  // be used once the transaction has been committed or rolled back.
  2179  //
  2180  // To use an existing prepared statement on this transaction, see Tx.Stmt.
  2181  func (tx *Tx) Prepare(query string) (*Stmt, error) {
  2182  	return tx.PrepareContext(context.Background(), query)
  2183  }
  2184  
  2185  // StmtContext returns a transaction-specific prepared statement from
  2186  // an existing statement.
  2187  //
  2188  // Example:
  2189  //  updateMoney, err := db.Prepare("UPDATE balance SET money=money+? WHERE id=?")
  2190  //  ...
  2191  //  tx, err := db.Begin()
  2192  //  ...
  2193  //  res, err := tx.StmtContext(ctx, updateMoney).Exec(123.45, 98293203)
  2194  //
  2195  // The provided context is used for the preparation of the statement, not for the
  2196  // execution of the statement.
  2197  //
  2198  // The returned statement operates within the transaction and will be closed
  2199  // when the transaction has been committed or rolled back.
  2200  func (tx *Tx) StmtContext(ctx context.Context, stmt *Stmt) *Stmt {
  2201  	dc, release, err := tx.grabConn(ctx)
  2202  	if err != nil {
  2203  		return &Stmt{stickyErr: err}
  2204  	}
  2205  	defer release(nil)
  2206  
  2207  	if tx.db != stmt.db {
  2208  		return &Stmt{stickyErr: errors.New("sql: Tx.Stmt: statement from different database used")}
  2209  	}
  2210  	var si driver.Stmt
  2211  	var parentStmt *Stmt
  2212  	stmt.mu.Lock()
  2213  	if stmt.closed || stmt.cg != nil {
  2214  		// If the statement has been closed or already belongs to a
  2215  		// transaction, we can't reuse it in this connection.
  2216  		// Since tx.StmtContext should never need to be called with a
  2217  		// Stmt already belonging to tx, we ignore this edge case and
  2218  		// re-prepare the statement in this case. No need to add
  2219  		// code-complexity for this.
  2220  		stmt.mu.Unlock()
  2221  		withLock(dc, func() {
  2222  			si, err = ctxDriverPrepare(ctx, dc.ci, stmt.query)
  2223  		})
  2224  		if err != nil {
  2225  			return &Stmt{stickyErr: err}
  2226  		}
  2227  	} else {
  2228  		stmt.removeClosedStmtLocked()
  2229  		// See if the statement has already been prepared on this connection,
  2230  		// and reuse it if possible.
  2231  		for _, v := range stmt.css {
  2232  			if v.dc == dc {
  2233  				si = v.ds.si
  2234  				break
  2235  			}
  2236  		}
  2237  
  2238  		stmt.mu.Unlock()
  2239  
  2240  		if si == nil {
  2241  			var ds *driverStmt
  2242  			withLock(dc, func() {
  2243  				ds, err = stmt.prepareOnConnLocked(ctx, dc)
  2244  			})
  2245  			if err != nil {
  2246  				return &Stmt{stickyErr: err}
  2247  			}
  2248  			si = ds.si
  2249  		}
  2250  		parentStmt = stmt
  2251  	}
  2252  
  2253  	txs := &Stmt{
  2254  		db: tx.db,
  2255  		cg: tx,
  2256  		cgds: &driverStmt{
  2257  			Locker: dc,
  2258  			si:     si,
  2259  		},
  2260  		parentStmt: parentStmt,
  2261  		query:      stmt.query,
  2262  	}
  2263  	if parentStmt != nil {
  2264  		tx.db.addDep(parentStmt, txs)
  2265  	}
  2266  	tx.stmts.Lock()
  2267  	tx.stmts.v = append(tx.stmts.v, txs)
  2268  	tx.stmts.Unlock()
  2269  	return txs
  2270  }
  2271  
  2272  // Stmt returns a transaction-specific prepared statement from
  2273  // an existing statement.
  2274  //
  2275  // Example:
  2276  //  updateMoney, err := db.Prepare("UPDATE balance SET money=money+? WHERE id=?")
  2277  //  ...
  2278  //  tx, err := db.Begin()
  2279  //  ...
  2280  //  res, err := tx.Stmt(updateMoney).Exec(123.45, 98293203)
  2281  //
  2282  // The returned statement operates within the transaction and will be closed
  2283  // when the transaction has been committed or rolled back.
  2284  func (tx *Tx) Stmt(stmt *Stmt) *Stmt {
  2285  	return tx.StmtContext(context.Background(), stmt)
  2286  }
  2287  
  2288  // ExecContext executes a query that doesn't return rows.
  2289  // For example: an INSERT and UPDATE.
  2290  func (tx *Tx) ExecContext(ctx context.Context, query string, args ...interface{}) (Result, error) {
  2291  	dc, release, err := tx.grabConn(ctx)
  2292  	if err != nil {
  2293  		return nil, err
  2294  	}
  2295  	return tx.db.execDC(ctx, dc, release, query, args)
  2296  }
  2297  
  2298  // Exec executes a query that doesn't return rows.
  2299  // For example: an INSERT and UPDATE.
  2300  func (tx *Tx) Exec(query string, args ...interface{}) (Result, error) {
  2301  	return tx.ExecContext(context.Background(), query, args...)
  2302  }
  2303  
  2304  // QueryContext executes a query that returns rows, typically a SELECT.
  2305  func (tx *Tx) QueryContext(ctx context.Context, query string, args ...interface{}) (*Rows, error) {
  2306  	dc, release, err := tx.grabConn(ctx)
  2307  	if err != nil {
  2308  		return nil, err
  2309  	}
  2310  
  2311  	return tx.db.queryDC(ctx, tx.ctx, dc, release, query, args)
  2312  }
  2313  
  2314  // Query executes a query that returns rows, typically a SELECT.
  2315  func (tx *Tx) Query(query string, args ...interface{}) (*Rows, error) {
  2316  	return tx.QueryContext(context.Background(), query, args...)
  2317  }
  2318  
  2319  // QueryRowContext executes a query that is expected to return at most one row.
  2320  // QueryRowContext always returns a non-nil value. Errors are deferred until
  2321  // Row's Scan method is called.
  2322  // If the query selects no rows, the *Row's Scan will return ErrNoRows.
  2323  // Otherwise, the *Row's Scan scans the first selected row and discards
  2324  // the rest.
  2325  func (tx *Tx) QueryRowContext(ctx context.Context, query string, args ...interface{}) *Row {
  2326  	rows, err := tx.QueryContext(ctx, query, args...)
  2327  	return &Row{rows: rows, err: err}
  2328  }
  2329  
  2330  // QueryRow executes a query that is expected to return at most one row.
  2331  // QueryRow always returns a non-nil value. Errors are deferred until
  2332  // Row's Scan method is called.
  2333  // If the query selects no rows, the *Row's Scan will return ErrNoRows.
  2334  // Otherwise, the *Row's Scan scans the first selected row and discards
  2335  // the rest.
  2336  func (tx *Tx) QueryRow(query string, args ...interface{}) *Row {
  2337  	return tx.QueryRowContext(context.Background(), query, args...)
  2338  }
  2339  
  2340  // connStmt is a prepared statement on a particular connection.
  2341  type connStmt struct {
  2342  	dc *driverConn
  2343  	ds *driverStmt
  2344  }
  2345  
  2346  // stmtConnGrabber represents a Tx or Conn that will return the underlying
  2347  // driverConn and release function.
  2348  type stmtConnGrabber interface {
  2349  	// grabConn returns the driverConn and the associated release function
  2350  	// that must be called when the operation completes.
  2351  	grabConn(context.Context) (*driverConn, releaseConn, error)
  2352  
  2353  	// txCtx returns the transaction context if available.
  2354  	// The returned context should be selected on along with
  2355  	// any query context when awaiting a cancel.
  2356  	txCtx() context.Context
  2357  }
  2358  
  2359  var (
  2360  	_ stmtConnGrabber = &Tx{}
  2361  	_ stmtConnGrabber = &Conn{}
  2362  )
  2363  
  2364  // Stmt is a prepared statement.
  2365  // A Stmt is safe for concurrent use by multiple goroutines.
  2366  //
  2367  // If a Stmt is prepared on a Tx or Conn, it will be bound to a single
  2368  // underlying connection forever. If the Tx or Conn closes, the Stmt will
  2369  // become unusable and all operations will return an error.
  2370  // If a Stmt is prepared on a DB, it will remain usable for the lifetime of the
  2371  // DB. When the Stmt needs to execute on a new underlying connection, it will
  2372  // prepare itself on the new connection automatically.
  2373  type Stmt struct {
  2374  	// Immutable:
  2375  	db        *DB    // where we came from
  2376  	query     string // that created the Stmt
  2377  	stickyErr error  // if non-nil, this error is returned for all operations
  2378  
  2379  	closemu sync.RWMutex // held exclusively during close, for read otherwise.
  2380  
  2381  	// If Stmt is prepared on a Tx or Conn then cg is present and will
  2382  	// only ever grab a connection from cg.
  2383  	// If cg is nil then the Stmt must grab an arbitrary connection
  2384  	// from db and determine if it must prepare the stmt again by
  2385  	// inspecting css.
  2386  	cg   stmtConnGrabber
  2387  	cgds *driverStmt
  2388  
  2389  	// parentStmt is set when a transaction-specific statement
  2390  	// is requested from an identical statement prepared on the same
  2391  	// conn. parentStmt is used to track the dependency of this statement
  2392  	// on its originating ("parent") statement so that parentStmt may
  2393  	// be closed by the user without them having to know whether or not
  2394  	// any transactions are still using it.
  2395  	parentStmt *Stmt
  2396  
  2397  	mu     sync.Mutex // protects the rest of the fields
  2398  	closed bool
  2399  
  2400  	// css is a list of underlying driver statement interfaces
  2401  	// that are valid on particular connections. This is only
  2402  	// used if cg == nil and one is found that has idle
  2403  	// connections. If cg != nil, cgds is always used.
  2404  	css []connStmt
  2405  
  2406  	// lastNumClosed is copied from db.numClosed when Stmt is created
  2407  	// without tx and closed connections in css are removed.
  2408  	lastNumClosed uint64
  2409  }
  2410  
  2411  // ExecContext executes a prepared statement with the given arguments and
  2412  // returns a Result summarizing the effect of the statement.
  2413  func (s *Stmt) ExecContext(ctx context.Context, args ...interface{}) (Result, error) {
  2414  	s.closemu.RLock()
  2415  	defer s.closemu.RUnlock()
  2416  
  2417  	var res Result
  2418  	strategy := cachedOrNewConn
  2419  	for i := 0; i < maxBadConnRetries+1; i++ {
  2420  		if i == maxBadConnRetries {
  2421  			strategy = alwaysNewConn
  2422  		}
  2423  		dc, releaseConn, ds, err := s.connStmt(ctx, strategy)
  2424  		if err != nil {
  2425  			if err == driver.ErrBadConn {
  2426  				continue
  2427  			}
  2428  			return nil, err
  2429  		}
  2430  
  2431  		res, err = resultFromStatement(ctx, dc.ci, ds, args...)
  2432  		releaseConn(err)
  2433  		if err != driver.ErrBadConn {
  2434  			return res, err
  2435  		}
  2436  	}
  2437  	return nil, driver.ErrBadConn
  2438  }
  2439  
  2440  // Exec executes a prepared statement with the given arguments and
  2441  // returns a Result summarizing the effect of the statement.
  2442  func (s *Stmt) Exec(args ...interface{}) (Result, error) {
  2443  	return s.ExecContext(context.Background(), args...)
  2444  }
  2445  
  2446  func resultFromStatement(ctx context.Context, ci driver.Conn, ds *driverStmt, args ...interface{}) (Result, error) {
  2447  	ds.Lock()
  2448  	defer ds.Unlock()
  2449  
  2450  	dargs, err := driverArgsConnLocked(ci, ds, args)
  2451  	if err != nil {
  2452  		return nil, err
  2453  	}
  2454  
  2455  	resi, err := ctxDriverStmtExec(ctx, ds.si, dargs)
  2456  	if err != nil {
  2457  		return nil, err
  2458  	}
  2459  	return driverResult{ds.Locker, resi}, nil
  2460  }
  2461  
  2462  // removeClosedStmtLocked removes closed conns in s.css.
  2463  //
  2464  // To avoid lock contention on DB.mu, we do it only when
  2465  // s.db.numClosed - s.lastNum is large enough.
  2466  func (s *Stmt) removeClosedStmtLocked() {
  2467  	t := len(s.css)/2 + 1
  2468  	if t > 10 {
  2469  		t = 10
  2470  	}
  2471  	dbClosed := atomic.LoadUint64(&s.db.numClosed)
  2472  	if dbClosed-s.lastNumClosed < uint64(t) {
  2473  		return
  2474  	}
  2475  
  2476  	s.db.mu.Lock()
  2477  	for i := 0; i < len(s.css); i++ {
  2478  		if s.css[i].dc.dbmuClosed {
  2479  			s.css[i] = s.css[len(s.css)-1]
  2480  			s.css = s.css[:len(s.css)-1]
  2481  			i--
  2482  		}
  2483  	}
  2484  	s.db.mu.Unlock()
  2485  	s.lastNumClosed = dbClosed
  2486  }
  2487  
  2488  // connStmt returns a free driver connection on which to execute the
  2489  // statement, a function to call to release the connection, and a
  2490  // statement bound to that connection.
  2491  func (s *Stmt) connStmt(ctx context.Context, strategy connReuseStrategy) (dc *driverConn, releaseConn func(error), ds *driverStmt, err error) {
  2492  	if err = s.stickyErr; err != nil {
  2493  		return
  2494  	}
  2495  	s.mu.Lock()
  2496  	if s.closed {
  2497  		s.mu.Unlock()
  2498  		err = errors.New("sql: statement is closed")
  2499  		return
  2500  	}
  2501  
  2502  	// In a transaction or connection, we always use the connection that the
  2503  	// stmt was created on.
  2504  	if s.cg != nil {
  2505  		s.mu.Unlock()
  2506  		dc, releaseConn, err = s.cg.grabConn(ctx) // blocks, waiting for the connection.
  2507  		if err != nil {
  2508  			return
  2509  		}
  2510  		return dc, releaseConn, s.cgds, nil
  2511  	}
  2512  
  2513  	s.removeClosedStmtLocked()
  2514  	s.mu.Unlock()
  2515  
  2516  	dc, err = s.db.conn(ctx, strategy)
  2517  	if err != nil {
  2518  		return nil, nil, nil, err
  2519  	}
  2520  
  2521  	s.mu.Lock()
  2522  	for _, v := range s.css {
  2523  		if v.dc == dc {
  2524  			s.mu.Unlock()
  2525  			return dc, dc.releaseConn, v.ds, nil
  2526  		}
  2527  	}
  2528  	s.mu.Unlock()
  2529  
  2530  	// No luck; we need to prepare the statement on this connection
  2531  	withLock(dc, func() {
  2532  		ds, err = s.prepareOnConnLocked(ctx, dc)
  2533  	})
  2534  	if err != nil {
  2535  		dc.releaseConn(err)
  2536  		return nil, nil, nil, err
  2537  	}
  2538  
  2539  	return dc, dc.releaseConn, ds, nil
  2540  }
  2541  
  2542  // prepareOnConnLocked prepares the query in Stmt s on dc and adds it to the list of
  2543  // open connStmt on the statement. It assumes the caller is holding the lock on dc.
  2544  func (s *Stmt) prepareOnConnLocked(ctx context.Context, dc *driverConn) (*driverStmt, error) {
  2545  	si, err := dc.prepareLocked(ctx, s.cg, s.query)
  2546  	if err != nil {
  2547  		return nil, err
  2548  	}
  2549  	cs := connStmt{dc, si}
  2550  	s.mu.Lock()
  2551  	s.css = append(s.css, cs)
  2552  	s.mu.Unlock()
  2553  	return cs.ds, nil
  2554  }
  2555  
  2556  // QueryContext executes a prepared query statement with the given arguments
  2557  // and returns the query results as a *Rows.
  2558  func (s *Stmt) QueryContext(ctx context.Context, args ...interface{}) (*Rows, error) {
  2559  	s.closemu.RLock()
  2560  	defer s.closemu.RUnlock()
  2561  
  2562  	var rowsi driver.Rows
  2563  	strategy := cachedOrNewConn
  2564  	for i := 0; i < maxBadConnRetries+1; i++ {
  2565  		if i == maxBadConnRetries {
  2566  			strategy = alwaysNewConn
  2567  		}
  2568  		dc, releaseConn, ds, err := s.connStmt(ctx, strategy)
  2569  		if err != nil {
  2570  			if err == driver.ErrBadConn {
  2571  				continue
  2572  			}
  2573  			return nil, err
  2574  		}
  2575  
  2576  		rowsi, err = rowsiFromStatement(ctx, dc.ci, ds, args...)
  2577  		if err == nil {
  2578  			// Note: ownership of ci passes to the *Rows, to be freed
  2579  			// with releaseConn.
  2580  			rows := &Rows{
  2581  				dc:    dc,
  2582  				rowsi: rowsi,
  2583  				// releaseConn set below
  2584  			}
  2585  			// addDep must be added before initContextClose or it could attempt
  2586  			// to removeDep before it has been added.
  2587  			s.db.addDep(s, rows)
  2588  
  2589  			// releaseConn must be set before initContextClose or it could
  2590  			// release the connection before it is set.
  2591  			rows.releaseConn = func(err error) {
  2592  				releaseConn(err)
  2593  				s.db.removeDep(s, rows)
  2594  			}
  2595  			var txctx context.Context
  2596  			if s.cg != nil {
  2597  				txctx = s.cg.txCtx()
  2598  			}
  2599  			rows.initContextClose(ctx, txctx)
  2600  			return rows, nil
  2601  		}
  2602  
  2603  		releaseConn(err)
  2604  		if err != driver.ErrBadConn {
  2605  			return nil, err
  2606  		}
  2607  	}
  2608  	return nil, driver.ErrBadConn
  2609  }
  2610  
  2611  // Query executes a prepared query statement with the given arguments
  2612  // and returns the query results as a *Rows.
  2613  func (s *Stmt) Query(args ...interface{}) (*Rows, error) {
  2614  	return s.QueryContext(context.Background(), args...)
  2615  }
  2616  
  2617  func rowsiFromStatement(ctx context.Context, ci driver.Conn, ds *driverStmt, args ...interface{}) (driver.Rows, error) {
  2618  	ds.Lock()
  2619  	defer ds.Unlock()
  2620  	dargs, err := driverArgsConnLocked(ci, ds, args)
  2621  	if err != nil {
  2622  		return nil, err
  2623  	}
  2624  	return ctxDriverStmtQuery(ctx, ds.si, dargs)
  2625  }
  2626  
  2627  // QueryRowContext executes a prepared query statement with the given arguments.
  2628  // If an error occurs during the execution of the statement, that error will
  2629  // be returned by a call to Scan on the returned *Row, which is always non-nil.
  2630  // If the query selects no rows, the *Row's Scan will return ErrNoRows.
  2631  // Otherwise, the *Row's Scan scans the first selected row and discards
  2632  // the rest.
  2633  func (s *Stmt) QueryRowContext(ctx context.Context, args ...interface{}) *Row {
  2634  	rows, err := s.QueryContext(ctx, args...)
  2635  	if err != nil {
  2636  		return &Row{err: err}
  2637  	}
  2638  	return &Row{rows: rows}
  2639  }
  2640  
  2641  // QueryRow executes a prepared query statement with the given arguments.
  2642  // If an error occurs during the execution of the statement, that error will
  2643  // be returned by a call to Scan on the returned *Row, which is always non-nil.
  2644  // If the query selects no rows, the *Row's Scan will return ErrNoRows.
  2645  // Otherwise, the *Row's Scan scans the first selected row and discards
  2646  // the rest.
  2647  //
  2648  // Example usage:
  2649  //
  2650  //  var name string
  2651  //  err := nameByUseridStmt.QueryRow(id).Scan(&name)
  2652  func (s *Stmt) QueryRow(args ...interface{}) *Row {
  2653  	return s.QueryRowContext(context.Background(), args...)
  2654  }
  2655  
  2656  // Close closes the statement.
  2657  func (s *Stmt) Close() error {
  2658  	s.closemu.Lock()
  2659  	defer s.closemu.Unlock()
  2660  
  2661  	if s.stickyErr != nil {
  2662  		return s.stickyErr
  2663  	}
  2664  	s.mu.Lock()
  2665  	if s.closed {
  2666  		s.mu.Unlock()
  2667  		return nil
  2668  	}
  2669  	s.closed = true
  2670  	txds := s.cgds
  2671  	s.cgds = nil
  2672  
  2673  	s.mu.Unlock()
  2674  
  2675  	if s.cg == nil {
  2676  		return s.db.removeDep(s, s)
  2677  	}
  2678  
  2679  	if s.parentStmt != nil {
  2680  		// If parentStmt is set, we must not close s.txds since it's stored
  2681  		// in the css array of the parentStmt.
  2682  		return s.db.removeDep(s.parentStmt, s)
  2683  	}
  2684  	return txds.Close()
  2685  }
  2686  
  2687  func (s *Stmt) finalClose() error {
  2688  	s.mu.Lock()
  2689  	defer s.mu.Unlock()
  2690  	if s.css != nil {
  2691  		for _, v := range s.css {
  2692  			s.db.noteUnusedDriverStatement(v.dc, v.ds)
  2693  			v.dc.removeOpenStmt(v.ds)
  2694  		}
  2695  		s.css = nil
  2696  	}
  2697  	return nil
  2698  }
  2699  
  2700  // Rows is the result of a query. Its cursor starts before the first row
  2701  // of the result set. Use Next to advance from row to row.
  2702  type Rows struct {
  2703  	dc          *driverConn // owned; must call releaseConn when closed to release
  2704  	releaseConn func(error)
  2705  	rowsi       driver.Rows
  2706  	cancel      func()      // called when Rows is closed, may be nil.
  2707  	closeStmt   *driverStmt // if non-nil, statement to Close on close
  2708  
  2709  	// closemu prevents Rows from closing while there
  2710  	// is an active streaming result. It is held for read during non-close operations
  2711  	// and exclusively during close.
  2712  	//
  2713  	// closemu guards lasterr and closed.
  2714  	closemu sync.RWMutex
  2715  	closed  bool
  2716  	lasterr error // non-nil only if closed is true
  2717  
  2718  	// lastcols is only used in Scan, Next, and NextResultSet which are expected
  2719  	// not to be called concurrently.
  2720  	lastcols []driver.Value
  2721  }
  2722  
  2723  // lasterrOrErrLocked returns either lasterr or the provided err.
  2724  // rs.closemu must be read-locked.
  2725  func (rs *Rows) lasterrOrErrLocked(err error) error {
  2726  	if rs.lasterr != nil && rs.lasterr != io.EOF {
  2727  		return rs.lasterr
  2728  	}
  2729  	return err
  2730  }
  2731  
  2732  func (rs *Rows) initContextClose(ctx, txctx context.Context) {
  2733  	if ctx.Done() == nil && (txctx == nil || txctx.Done() == nil) {
  2734  		return
  2735  	}
  2736  	ctx, rs.cancel = context.WithCancel(ctx)
  2737  	go rs.awaitDone(ctx, txctx)
  2738  }
  2739  
  2740  // awaitDone blocks until either ctx or txctx is canceled. The ctx is provided
  2741  // from the query context and is canceled when the query Rows is closed.
  2742  // If the query was issued in a transaction, the transaction's context
  2743  // is also provided in txctx to ensure Rows is closed if the Tx is closed.
  2744  func (rs *Rows) awaitDone(ctx, txctx context.Context) {
  2745  	var txctxDone <-chan struct{}
  2746  	if txctx != nil {
  2747  		txctxDone = txctx.Done()
  2748  	}
  2749  	select {
  2750  	case <-ctx.Done():
  2751  	case <-txctxDone:
  2752  	}
  2753  	rs.close(ctx.Err())
  2754  }
  2755  
  2756  // Next prepares the next result row for reading with the Scan method. It
  2757  // returns true on success, or false if there is no next result row or an error
  2758  // happened while preparing it. Err should be consulted to distinguish between
  2759  // the two cases.
  2760  //
  2761  // Every call to Scan, even the first one, must be preceded by a call to Next.
  2762  func (rs *Rows) Next() bool {
  2763  	var doClose, ok bool
  2764  	withLock(rs.closemu.RLocker(), func() {
  2765  		doClose, ok = rs.nextLocked()
  2766  	})
  2767  	if doClose {
  2768  		rs.Close()
  2769  	}
  2770  	return ok
  2771  }
  2772  
  2773  func (rs *Rows) nextLocked() (doClose, ok bool) {
  2774  	if rs.closed {
  2775  		return false, false
  2776  	}
  2777  
  2778  	// Lock the driver connection before calling the driver interface
  2779  	// rowsi to prevent a Tx from rolling back the connection at the same time.
  2780  	rs.dc.Lock()
  2781  	defer rs.dc.Unlock()
  2782  
  2783  	if rs.lastcols == nil {
  2784  		rs.lastcols = make([]driver.Value, len(rs.rowsi.Columns()))
  2785  	}
  2786  
  2787  	rs.lasterr = rs.rowsi.Next(rs.lastcols)
  2788  	if rs.lasterr != nil {
  2789  		// Close the connection if there is a driver error.
  2790  		if rs.lasterr != io.EOF {
  2791  			return true, false
  2792  		}
  2793  		nextResultSet, ok := rs.rowsi.(driver.RowsNextResultSet)
  2794  		if !ok {
  2795  			return true, false
  2796  		}
  2797  		// The driver is at the end of the current result set.
  2798  		// Test to see if there is another result set after the current one.
  2799  		// Only close Rows if there is no further result sets to read.
  2800  		if !nextResultSet.HasNextResultSet() {
  2801  			doClose = true
  2802  		}
  2803  		return doClose, false
  2804  	}
  2805  	return false, true
  2806  }
  2807  
  2808  // NextResultSet prepares the next result set for reading. It reports whether
  2809  // there is further result sets, or false if there is no further result set
  2810  // or if there is an error advancing to it. The Err method should be consulted
  2811  // to distinguish between the two cases.
  2812  //
  2813  // After calling NextResultSet, the Next method should always be called before
  2814  // scanning. If there are further result sets they may not have rows in the result
  2815  // set.
  2816  func (rs *Rows) NextResultSet() bool {
  2817  	var doClose bool
  2818  	defer func() {
  2819  		if doClose {
  2820  			rs.Close()
  2821  		}
  2822  	}()
  2823  	rs.closemu.RLock()
  2824  	defer rs.closemu.RUnlock()
  2825  
  2826  	if rs.closed {
  2827  		return false
  2828  	}
  2829  
  2830  	rs.lastcols = nil
  2831  	nextResultSet, ok := rs.rowsi.(driver.RowsNextResultSet)
  2832  	if !ok {
  2833  		doClose = true
  2834  		return false
  2835  	}
  2836  
  2837  	// Lock the driver connection before calling the driver interface
  2838  	// rowsi to prevent a Tx from rolling back the connection at the same time.
  2839  	rs.dc.Lock()
  2840  	defer rs.dc.Unlock()
  2841  
  2842  	rs.lasterr = nextResultSet.NextResultSet()
  2843  	if rs.lasterr != nil {
  2844  		doClose = true
  2845  		return false
  2846  	}
  2847  	return true
  2848  }
  2849  
  2850  // Err returns the error, if any, that was encountered during iteration.
  2851  // Err may be called after an explicit or implicit Close.
  2852  func (rs *Rows) Err() error {
  2853  	rs.closemu.RLock()
  2854  	defer rs.closemu.RUnlock()
  2855  	return rs.lasterrOrErrLocked(nil)
  2856  }
  2857  
  2858  var errRowsClosed = errors.New("sql: Rows are closed")
  2859  var errNoRows = errors.New("sql: no Rows available")
  2860  
  2861  // Columns returns the column names.
  2862  // Columns returns an error if the rows are closed.
  2863  func (rs *Rows) Columns() ([]string, error) {
  2864  	rs.closemu.RLock()
  2865  	defer rs.closemu.RUnlock()
  2866  	if rs.closed {
  2867  		return nil, rs.lasterrOrErrLocked(errRowsClosed)
  2868  	}
  2869  	if rs.rowsi == nil {
  2870  		return nil, rs.lasterrOrErrLocked(errNoRows)
  2871  	}
  2872  	rs.dc.Lock()
  2873  	defer rs.dc.Unlock()
  2874  
  2875  	return rs.rowsi.Columns(), nil
  2876  }
  2877  
  2878  // ColumnTypes returns column information such as column type, length,
  2879  // and nullable. Some information may not be available from some drivers.
  2880  func (rs *Rows) ColumnTypes() ([]*ColumnType, error) {
  2881  	rs.closemu.RLock()
  2882  	defer rs.closemu.RUnlock()
  2883  	if rs.closed {
  2884  		return nil, rs.lasterrOrErrLocked(errRowsClosed)
  2885  	}
  2886  	if rs.rowsi == nil {
  2887  		return nil, rs.lasterrOrErrLocked(errNoRows)
  2888  	}
  2889  	rs.dc.Lock()
  2890  	defer rs.dc.Unlock()
  2891  
  2892  	return rowsColumnInfoSetupConnLocked(rs.rowsi), nil
  2893  }
  2894  
  2895  // ColumnType contains the name and type of a column.
  2896  type ColumnType struct {
  2897  	name string
  2898  
  2899  	hasNullable       bool
  2900  	hasLength         bool
  2901  	hasPrecisionScale bool
  2902  
  2903  	nullable     bool
  2904  	length       int64
  2905  	databaseType string
  2906  	precision    int64
  2907  	scale        int64
  2908  	scanType     reflect.Type
  2909  }
  2910  
  2911  // Name returns the name or alias of the column.
  2912  func (ci *ColumnType) Name() string {
  2913  	return ci.name
  2914  }
  2915  
  2916  // Length returns the column type length for variable length column types such
  2917  // as text and binary field types. If the type length is unbounded the value will
  2918  // be math.MaxInt64 (any database limits will still apply).
  2919  // If the column type is not variable length, such as an int, or if not supported
  2920  // by the driver ok is false.
  2921  func (ci *ColumnType) Length() (length int64, ok bool) {
  2922  	return ci.length, ci.hasLength
  2923  }
  2924  
  2925  // DecimalSize returns the scale and precision of a decimal type.
  2926  // If not applicable or if not supported ok is false.
  2927  func (ci *ColumnType) DecimalSize() (precision, scale int64, ok bool) {
  2928  	return ci.precision, ci.scale, ci.hasPrecisionScale
  2929  }
  2930  
  2931  // ScanType returns a Go type suitable for scanning into using Rows.Scan.
  2932  // If a driver does not support this property ScanType will return
  2933  // the type of an empty interface.
  2934  func (ci *ColumnType) ScanType() reflect.Type {
  2935  	return ci.scanType
  2936  }
  2937  
  2938  // Nullable reports whether the column may be null.
  2939  // If a driver does not support this property ok will be false.
  2940  func (ci *ColumnType) Nullable() (nullable, ok bool) {
  2941  	return ci.nullable, ci.hasNullable
  2942  }
  2943  
  2944  // DatabaseTypeName returns the database system name of the column type. If an empty
  2945  // string is returned the driver type name is not supported.
  2946  // Consult your driver documentation for a list of driver data types. Length specifiers
  2947  // are not included.
  2948  // Common type include "VARCHAR", "TEXT", "NVARCHAR", "DECIMAL", "BOOL", "INT", "BIGINT".
  2949  func (ci *ColumnType) DatabaseTypeName() string {
  2950  	return ci.databaseType
  2951  }
  2952  
  2953  func rowsColumnInfoSetupConnLocked(rowsi driver.Rows) []*ColumnType {
  2954  	names := rowsi.Columns()
  2955  
  2956  	list := make([]*ColumnType, len(names))
  2957  	for i := range list {
  2958  		ci := &ColumnType{
  2959  			name: names[i],
  2960  		}
  2961  		list[i] = ci
  2962  
  2963  		if prop, ok := rowsi.(driver.RowsColumnTypeScanType); ok {
  2964  			ci.scanType = prop.ColumnTypeScanType(i)
  2965  		} else {
  2966  			ci.scanType = reflect.TypeOf(new(interface{})).Elem()
  2967  		}
  2968  		if prop, ok := rowsi.(driver.RowsColumnTypeDatabaseTypeName); ok {
  2969  			ci.databaseType = prop.ColumnTypeDatabaseTypeName(i)
  2970  		}
  2971  		if prop, ok := rowsi.(driver.RowsColumnTypeLength); ok {
  2972  			ci.length, ci.hasLength = prop.ColumnTypeLength(i)
  2973  		}
  2974  		if prop, ok := rowsi.(driver.RowsColumnTypeNullable); ok {
  2975  			ci.nullable, ci.hasNullable = prop.ColumnTypeNullable(i)
  2976  		}
  2977  		if prop, ok := rowsi.(driver.RowsColumnTypePrecisionScale); ok {
  2978  			ci.precision, ci.scale, ci.hasPrecisionScale = prop.ColumnTypePrecisionScale(i)
  2979  		}
  2980  	}
  2981  	return list
  2982  }
  2983  
  2984  // Scan copies the columns in the current row into the values pointed
  2985  // at by dest. The number of values in dest must be the same as the
  2986  // number of columns in Rows.
  2987  //
  2988  // Scan converts columns read from the database into the following
  2989  // common Go types and special types provided by the sql package:
  2990  //
  2991  //    *string
  2992  //    *[]byte
  2993  //    *int, *int8, *int16, *int32, *int64
  2994  //    *uint, *uint8, *uint16, *uint32, *uint64
  2995  //    *bool
  2996  //    *float32, *float64
  2997  //    *interface{}
  2998  //    *RawBytes
  2999  //    *Rows (cursor value)
  3000  //    any type implementing Scanner (see Scanner docs)
  3001  //
  3002  // In the most simple case, if the type of the value from the source
  3003  // column is an integer, bool or string type T and dest is of type *T,
  3004  // Scan simply assigns the value through the pointer.
  3005  //
  3006  // Scan also converts between string and numeric types, as long as no
  3007  // information would be lost. While Scan stringifies all numbers
  3008  // scanned from numeric database columns into *string, scans into
  3009  // numeric types are checked for overflow. For example, a float64 with
  3010  // value 300 or a string with value "300" can scan into a uint16, but
  3011  // not into a uint8, though float64(255) or "255" can scan into a
  3012  // uint8. One exception is that scans of some float64 numbers to
  3013  // strings may lose information when stringifying. In general, scan
  3014  // floating point columns into *float64.
  3015  //
  3016  // If a dest argument has type *[]byte, Scan saves in that argument a
  3017  // copy of the corresponding data. The copy is owned by the caller and
  3018  // can be modified and held indefinitely. The copy can be avoided by
  3019  // using an argument of type *RawBytes instead; see the documentation
  3020  // for RawBytes for restrictions on its use.
  3021  //
  3022  // If an argument has type *interface{}, Scan copies the value
  3023  // provided by the underlying driver without conversion. When scanning
  3024  // from a source value of type []byte to *interface{}, a copy of the
  3025  // slice is made and the caller owns the result.
  3026  //
  3027  // Source values of type time.Time may be scanned into values of type
  3028  // *time.Time, *interface{}, *string, or *[]byte. When converting to
  3029  // the latter two, time.RFC3339Nano is used.
  3030  //
  3031  // Source values of type bool may be scanned into types *bool,
  3032  // *interface{}, *string, *[]byte, or *RawBytes.
  3033  //
  3034  // For scanning into *bool, the source may be true, false, 1, 0, or
  3035  // string inputs parseable by strconv.ParseBool.
  3036  //
  3037  // Scan can also convert a cursor returned from a query, such as
  3038  // "select cursor(select * from my_table) from dual", into a
  3039  // *Rows value that can itself be scanned from. The parent
  3040  // select query will close any cursor *Rows if the parent *Rows is closed.
  3041  func (rs *Rows) Scan(dest ...interface{}) error {
  3042  	rs.closemu.RLock()
  3043  
  3044  	if rs.lasterr != nil && rs.lasterr != io.EOF {
  3045  		rs.closemu.RUnlock()
  3046  		return rs.lasterr
  3047  	}
  3048  	if rs.closed {
  3049  		err := rs.lasterrOrErrLocked(errRowsClosed)
  3050  		rs.closemu.RUnlock()
  3051  		return err
  3052  	}
  3053  	rs.closemu.RUnlock()
  3054  
  3055  	if rs.lastcols == nil {
  3056  		return errors.New("sql: Scan called without calling Next")
  3057  	}
  3058  	if len(dest) != len(rs.lastcols) {
  3059  		return fmt.Errorf("sql: expected %d destination arguments in Scan, not %d", len(rs.lastcols), len(dest))
  3060  	}
  3061  	for i, sv := range rs.lastcols {
  3062  		err := convertAssignRows(dest[i], sv, rs)
  3063  		if err != nil {
  3064  			return fmt.Errorf(`sql: Scan error on column index %d, name %q: %v`, i, rs.rowsi.Columns()[i], err)
  3065  		}
  3066  	}
  3067  	return nil
  3068  }
  3069  
  3070  // rowsCloseHook returns a function so tests may install the
  3071  // hook through a test only mutex.
  3072  var rowsCloseHook = func() func(*Rows, *error) { return nil }
  3073  
  3074  // Close closes the Rows, preventing further enumeration. If Next is called
  3075  // and returns false and there are no further result sets,
  3076  // the Rows are closed automatically and it will suffice to check the
  3077  // result of Err. Close is idempotent and does not affect the result of Err.
  3078  func (rs *Rows) Close() error {
  3079  	return rs.close(nil)
  3080  }
  3081  
  3082  func (rs *Rows) close(err error) error {
  3083  	rs.closemu.Lock()
  3084  	defer rs.closemu.Unlock()
  3085  
  3086  	if rs.closed {
  3087  		return nil
  3088  	}
  3089  	rs.closed = true
  3090  
  3091  	if rs.lasterr == nil {
  3092  		rs.lasterr = err
  3093  	}
  3094  
  3095  	withLock(rs.dc, func() {
  3096  		err = rs.rowsi.Close()
  3097  	})
  3098  	if fn := rowsCloseHook(); fn != nil {
  3099  		fn(rs, &err)
  3100  	}
  3101  	if rs.cancel != nil {
  3102  		rs.cancel()
  3103  	}
  3104  
  3105  	if rs.closeStmt != nil {
  3106  		rs.closeStmt.Close()
  3107  	}
  3108  	rs.releaseConn(err)
  3109  	return err
  3110  }
  3111  
  3112  // Row is the result of calling QueryRow to select a single row.
  3113  type Row struct {
  3114  	// One of these two will be non-nil:
  3115  	err  error // deferred error for easy chaining
  3116  	rows *Rows
  3117  }
  3118  
  3119  // Scan copies the columns from the matched row into the values
  3120  // pointed at by dest. See the documentation on Rows.Scan for details.
  3121  // If more than one row matches the query,
  3122  // Scan uses the first row and discards the rest. If no row matches
  3123  // the query, Scan returns ErrNoRows.
  3124  func (r *Row) Scan(dest ...interface{}) error {
  3125  	if r.err != nil {
  3126  		return r.err
  3127  	}
  3128  
  3129  	// TODO(bradfitz): for now we need to defensively clone all
  3130  	// []byte that the driver returned (not permitting
  3131  	// *RawBytes in Rows.Scan), since we're about to close
  3132  	// the Rows in our defer, when we return from this function.
  3133  	// the contract with the driver.Next(...) interface is that it
  3134  	// can return slices into read-only temporary memory that's
  3135  	// only valid until the next Scan/Close. But the TODO is that
  3136  	// for a lot of drivers, this copy will be unnecessary. We
  3137  	// should provide an optional interface for drivers to
  3138  	// implement to say, "don't worry, the []bytes that I return
  3139  	// from Next will not be modified again." (for instance, if
  3140  	// they were obtained from the network anyway) But for now we
  3141  	// don't care.
  3142  	defer r.rows.Close()
  3143  	for _, dp := range dest {
  3144  		if _, ok := dp.(*RawBytes); ok {
  3145  			return errors.New("sql: RawBytes isn't allowed on Row.Scan")
  3146  		}
  3147  	}
  3148  
  3149  	if !r.rows.Next() {
  3150  		if err := r.rows.Err(); err != nil {
  3151  			return err
  3152  		}
  3153  		return ErrNoRows
  3154  	}
  3155  	err := r.rows.Scan(dest...)
  3156  	if err != nil {
  3157  		return err
  3158  	}
  3159  	// Make sure the query can be processed to completion with no errors.
  3160  	return r.rows.Close()
  3161  }
  3162  
  3163  // A Result summarizes an executed SQL command.
  3164  type Result interface {
  3165  	// LastInsertId returns the integer generated by the database
  3166  	// in response to a command. Typically this will be from an
  3167  	// "auto increment" column when inserting a new row. Not all
  3168  	// databases support this feature, and the syntax of such
  3169  	// statements varies.
  3170  	LastInsertId() (int64, error)
  3171  
  3172  	// RowsAffected returns the number of rows affected by an
  3173  	// update, insert, or delete. Not every database or database
  3174  	// driver may support this.
  3175  	RowsAffected() (int64, error)
  3176  }
  3177  
  3178  type driverResult struct {
  3179  	sync.Locker // the *driverConn
  3180  	resi        driver.Result
  3181  }
  3182  
  3183  func (dr driverResult) LastInsertId() (int64, error) {
  3184  	dr.Lock()
  3185  	defer dr.Unlock()
  3186  	return dr.resi.LastInsertId()
  3187  }
  3188  
  3189  func (dr driverResult) RowsAffected() (int64, error) {
  3190  	dr.Lock()
  3191  	defer dr.Unlock()
  3192  	return dr.resi.RowsAffected()
  3193  }
  3194  
  3195  func stack() string {
  3196  	var buf [2 << 10]byte
  3197  	return string(buf[:runtime.Stack(buf[:], false)])
  3198  }
  3199  
  3200  // withLock runs while holding lk.
  3201  func withLock(lk sync.Locker, fn func()) {
  3202  	lk.Lock()
  3203  	defer lk.Unlock() // in case fn panics
  3204  	fn()
  3205  }
  3206  

View as plain text