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