github.com/goproxy0/go@v0.0.0-20171111080102-49cc0c489d2c/src/database/sql/sql.go (about)

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