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

View as plain text