github.com/bgentry/go@v0.0.0-20150121062915-6cf5a733d54d/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 http://golang.org/s/sqldrivers for a list of drivers.
    10  //
    11  // For more usage examples, see the wiki page at
    12  // http://golang.org/s/sqlwiki.
    13  package sql
    14  
    15  import (
    16  	"database/sql/driver"
    17  	"errors"
    18  	"fmt"
    19  	"io"
    20  	"runtime"
    21  	"sort"
    22  	"sync"
    23  )
    24  
    25  var drivers = make(map[string]driver.Driver)
    26  
    27  // Register makes a database driver available by the provided name.
    28  // If Register is called twice with the same name or if driver is nil,
    29  // it panics.
    30  func Register(name string, driver driver.Driver) {
    31  	if driver == nil {
    32  		panic("sql: Register driver is nil")
    33  	}
    34  	if _, dup := drivers[name]; dup {
    35  		panic("sql: Register called twice for driver " + name)
    36  	}
    37  	drivers[name] = driver
    38  }
    39  
    40  func unregisterAllDrivers() {
    41  	// For tests.
    42  	drivers = make(map[string]driver.Driver)
    43  }
    44  
    45  // Drivers returns a sorted list of the names of the registered drivers.
    46  func Drivers() []string {
    47  	var list []string
    48  	for name := range drivers {
    49  		list = append(list, name)
    50  	}
    51  	sort.Strings(list)
    52  	return list
    53  }
    54  
    55  // RawBytes is a byte slice that holds a reference to memory owned by
    56  // the database itself. After a Scan into a RawBytes, the slice is only
    57  // valid until the next call to Next, Scan, or Close.
    58  type RawBytes []byte
    59  
    60  // NullString represents a string that may be null.
    61  // NullString implements the Scanner interface so
    62  // it can be used as a scan destination:
    63  //
    64  //  var s NullString
    65  //  err := db.QueryRow("SELECT name FROM foo WHERE id=?", id).Scan(&s)
    66  //  ...
    67  //  if s.Valid {
    68  //     // use s.String
    69  //  } else {
    70  //     // NULL value
    71  //  }
    72  //
    73  type NullString struct {
    74  	String string
    75  	Valid  bool // Valid is true if String is not NULL
    76  }
    77  
    78  // Scan implements the Scanner interface.
    79  func (ns *NullString) Scan(value interface{}) error {
    80  	if value == nil {
    81  		ns.String, ns.Valid = "", false
    82  		return nil
    83  	}
    84  	ns.Valid = true
    85  	return convertAssign(&ns.String, value)
    86  }
    87  
    88  // Value implements the driver Valuer interface.
    89  func (ns NullString) Value() (driver.Value, error) {
    90  	if !ns.Valid {
    91  		return nil, nil
    92  	}
    93  	return ns.String, nil
    94  }
    95  
    96  // NullInt64 represents an int64 that may be null.
    97  // NullInt64 implements the Scanner interface so
    98  // it can be used as a scan destination, similar to NullString.
    99  type NullInt64 struct {
   100  	Int64 int64
   101  	Valid bool // Valid is true if Int64 is not NULL
   102  }
   103  
   104  // Scan implements the Scanner interface.
   105  func (n *NullInt64) Scan(value interface{}) error {
   106  	if value == nil {
   107  		n.Int64, n.Valid = 0, false
   108  		return nil
   109  	}
   110  	n.Valid = true
   111  	return convertAssign(&n.Int64, value)
   112  }
   113  
   114  // Value implements the driver Valuer interface.
   115  func (n NullInt64) Value() (driver.Value, error) {
   116  	if !n.Valid {
   117  		return nil, nil
   118  	}
   119  	return n.Int64, nil
   120  }
   121  
   122  // NullFloat64 represents a float64 that may be null.
   123  // NullFloat64 implements the Scanner interface so
   124  // it can be used as a scan destination, similar to NullString.
   125  type NullFloat64 struct {
   126  	Float64 float64
   127  	Valid   bool // Valid is true if Float64 is not NULL
   128  }
   129  
   130  // Scan implements the Scanner interface.
   131  func (n *NullFloat64) Scan(value interface{}) error {
   132  	if value == nil {
   133  		n.Float64, n.Valid = 0, false
   134  		return nil
   135  	}
   136  	n.Valid = true
   137  	return convertAssign(&n.Float64, value)
   138  }
   139  
   140  // Value implements the driver Valuer interface.
   141  func (n NullFloat64) Value() (driver.Value, error) {
   142  	if !n.Valid {
   143  		return nil, nil
   144  	}
   145  	return n.Float64, nil
   146  }
   147  
   148  // NullBool represents a bool that may be null.
   149  // NullBool implements the Scanner interface so
   150  // it can be used as a scan destination, similar to NullString.
   151  type NullBool struct {
   152  	Bool  bool
   153  	Valid bool // Valid is true if Bool is not NULL
   154  }
   155  
   156  // Scan implements the Scanner interface.
   157  func (n *NullBool) Scan(value interface{}) error {
   158  	if value == nil {
   159  		n.Bool, n.Valid = false, false
   160  		return nil
   161  	}
   162  	n.Valid = true
   163  	return convertAssign(&n.Bool, value)
   164  }
   165  
   166  // Value implements the driver Valuer interface.
   167  func (n NullBool) Value() (driver.Value, error) {
   168  	if !n.Valid {
   169  		return nil, nil
   170  	}
   171  	return n.Bool, nil
   172  }
   173  
   174  // Scanner is an interface used by Scan.
   175  type Scanner interface {
   176  	// Scan assigns a value from a database driver.
   177  	//
   178  	// The src value will be of one of the following restricted
   179  	// set of types:
   180  	//
   181  	//    int64
   182  	//    float64
   183  	//    bool
   184  	//    []byte
   185  	//    string
   186  	//    time.Time
   187  	//    nil - for NULL values
   188  	//
   189  	// An error should be returned if the value can not be stored
   190  	// without loss of information.
   191  	Scan(src interface{}) error
   192  }
   193  
   194  // ErrNoRows is returned by Scan when QueryRow doesn't return a
   195  // row. In such a case, QueryRow returns a placeholder *Row value that
   196  // defers this error until a Scan.
   197  var ErrNoRows = errors.New("sql: no rows in result set")
   198  
   199  // DB is a database handle representing a pool of zero or more
   200  // underlying connections. It's safe for concurrent use by multiple
   201  // goroutines.
   202  //
   203  // The sql package creates and frees connections automatically; it
   204  // also maintains a free pool of idle connections. If the database has
   205  // a concept of per-connection state, such state can only be reliably
   206  // observed within a transaction. Once DB.Begin is called, the
   207  // returned Tx is bound to a single connection. Once Commit or
   208  // Rollback is called on the transaction, that transaction's
   209  // connection is returned to DB's idle connection pool. The pool size
   210  // can be controlled with SetMaxIdleConns.
   211  type DB struct {
   212  	driver driver.Driver
   213  	dsn    string
   214  
   215  	mu           sync.Mutex // protects following fields
   216  	freeConn     []*driverConn
   217  	connRequests []chan connRequest
   218  	numOpen      int
   219  	pendingOpens int
   220  	// Used to signal the need for new connections
   221  	// a goroutine running connectionOpener() reads on this chan and
   222  	// maybeOpenNewConnections sends on the chan (one send per needed connection)
   223  	// It is closed during db.Close(). The close tells the connectionOpener
   224  	// goroutine to exit.
   225  	openerCh chan struct{}
   226  	closed   bool
   227  	dep      map[finalCloser]depSet
   228  	lastPut  map[*driverConn]string // stacktrace of last conn's put; debug only
   229  	maxIdle  int                    // zero means defaultMaxIdleConns; negative means 0
   230  	maxOpen  int                    // <= 0 means unlimited
   231  }
   232  
   233  // driverConn wraps a driver.Conn with a mutex, to
   234  // be held during all calls into the Conn. (including any calls onto
   235  // interfaces returned via that Conn, such as calls on Tx, Stmt,
   236  // Result, Rows)
   237  type driverConn struct {
   238  	db *DB
   239  
   240  	sync.Mutex  // guards following
   241  	ci          driver.Conn
   242  	closed      bool
   243  	finalClosed bool // ci.Close has been called
   244  	openStmt    map[driver.Stmt]bool
   245  
   246  	// guarded by db.mu
   247  	inUse      bool
   248  	onPut      []func() // code (with db.mu held) run when conn is next returned
   249  	dbmuClosed bool     // same as closed, but guarded by db.mu, for connIfFree
   250  }
   251  
   252  func (dc *driverConn) releaseConn(err error) {
   253  	dc.db.putConn(dc, err)
   254  }
   255  
   256  func (dc *driverConn) removeOpenStmt(si driver.Stmt) {
   257  	dc.Lock()
   258  	defer dc.Unlock()
   259  	delete(dc.openStmt, si)
   260  }
   261  
   262  func (dc *driverConn) prepareLocked(query string) (driver.Stmt, error) {
   263  	si, err := dc.ci.Prepare(query)
   264  	if err == nil {
   265  		// Track each driverConn's open statements, so we can close them
   266  		// before closing the conn.
   267  		//
   268  		// TODO(bradfitz): let drivers opt out of caring about
   269  		// stmt closes if the conn is about to close anyway? For now
   270  		// do the safe thing, in case stmts need to be closed.
   271  		//
   272  		// TODO(bradfitz): after Go 1.2, closing driver.Stmts
   273  		// should be moved to driverStmt, using unique
   274  		// *driverStmts everywhere (including from
   275  		// *Stmt.connStmt, instead of returning a
   276  		// driver.Stmt), using driverStmt as a pointer
   277  		// everywhere, and making it a finalCloser.
   278  		if dc.openStmt == nil {
   279  			dc.openStmt = make(map[driver.Stmt]bool)
   280  		}
   281  		dc.openStmt[si] = true
   282  	}
   283  	return si, err
   284  }
   285  
   286  // the dc.db's Mutex is held.
   287  func (dc *driverConn) closeDBLocked() func() error {
   288  	dc.Lock()
   289  	defer dc.Unlock()
   290  	if dc.closed {
   291  		return func() error { return errors.New("sql: duplicate driverConn close") }
   292  	}
   293  	dc.closed = true
   294  	return dc.db.removeDepLocked(dc, dc)
   295  }
   296  
   297  func (dc *driverConn) Close() error {
   298  	dc.Lock()
   299  	if dc.closed {
   300  		dc.Unlock()
   301  		return errors.New("sql: duplicate driverConn close")
   302  	}
   303  	dc.closed = true
   304  	dc.Unlock() // not defer; removeDep finalClose calls may need to lock
   305  
   306  	// And now updates that require holding dc.mu.Lock.
   307  	dc.db.mu.Lock()
   308  	dc.dbmuClosed = true
   309  	fn := dc.db.removeDepLocked(dc, dc)
   310  	dc.db.mu.Unlock()
   311  	return fn()
   312  }
   313  
   314  func (dc *driverConn) finalClose() error {
   315  	dc.Lock()
   316  
   317  	for si := range dc.openStmt {
   318  		si.Close()
   319  	}
   320  	dc.openStmt = nil
   321  
   322  	err := dc.ci.Close()
   323  	dc.ci = nil
   324  	dc.finalClosed = true
   325  	dc.Unlock()
   326  
   327  	dc.db.mu.Lock()
   328  	dc.db.numOpen--
   329  	dc.db.maybeOpenNewConnections()
   330  	dc.db.mu.Unlock()
   331  
   332  	return err
   333  }
   334  
   335  // driverStmt associates a driver.Stmt with the
   336  // *driverConn from which it came, so the driverConn's lock can be
   337  // held during calls.
   338  type driverStmt struct {
   339  	sync.Locker // the *driverConn
   340  	si          driver.Stmt
   341  }
   342  
   343  func (ds *driverStmt) Close() error {
   344  	ds.Lock()
   345  	defer ds.Unlock()
   346  	return ds.si.Close()
   347  }
   348  
   349  // depSet is a finalCloser's outstanding dependencies
   350  type depSet map[interface{}]bool // set of true bools
   351  
   352  // The finalCloser interface is used by (*DB).addDep and related
   353  // dependency reference counting.
   354  type finalCloser interface {
   355  	// finalClose is called when the reference count of an object
   356  	// goes to zero. (*DB).mu is not held while calling it.
   357  	finalClose() error
   358  }
   359  
   360  // addDep notes that x now depends on dep, and x's finalClose won't be
   361  // called until all of x's dependencies are removed with removeDep.
   362  func (db *DB) addDep(x finalCloser, dep interface{}) {
   363  	//println(fmt.Sprintf("addDep(%T %p, %T %p)", x, x, dep, dep))
   364  	db.mu.Lock()
   365  	defer db.mu.Unlock()
   366  	db.addDepLocked(x, dep)
   367  }
   368  
   369  func (db *DB) addDepLocked(x finalCloser, dep interface{}) {
   370  	if db.dep == nil {
   371  		db.dep = make(map[finalCloser]depSet)
   372  	}
   373  	xdep := db.dep[x]
   374  	if xdep == nil {
   375  		xdep = make(depSet)
   376  		db.dep[x] = xdep
   377  	}
   378  	xdep[dep] = true
   379  }
   380  
   381  // removeDep notes that x no longer depends on dep.
   382  // If x still has dependencies, nil is returned.
   383  // If x no longer has any dependencies, its finalClose method will be
   384  // called and its error value will be returned.
   385  func (db *DB) removeDep(x finalCloser, dep interface{}) error {
   386  	db.mu.Lock()
   387  	fn := db.removeDepLocked(x, dep)
   388  	db.mu.Unlock()
   389  	return fn()
   390  }
   391  
   392  func (db *DB) removeDepLocked(x finalCloser, dep interface{}) func() error {
   393  	//println(fmt.Sprintf("removeDep(%T %p, %T %p)", x, x, dep, dep))
   394  
   395  	xdep, ok := db.dep[x]
   396  	if !ok {
   397  		panic(fmt.Sprintf("unpaired removeDep: no deps for %T", x))
   398  	}
   399  
   400  	l0 := len(xdep)
   401  	delete(xdep, dep)
   402  
   403  	switch len(xdep) {
   404  	case l0:
   405  		// Nothing removed. Shouldn't happen.
   406  		panic(fmt.Sprintf("unpaired removeDep: no %T dep on %T", dep, x))
   407  	case 0:
   408  		// No more dependencies.
   409  		delete(db.dep, x)
   410  		return x.finalClose
   411  	default:
   412  		// Dependencies remain.
   413  		return func() error { return nil }
   414  	}
   415  }
   416  
   417  // This is the size of the connectionOpener request chan (dn.openerCh).
   418  // This value should be larger than the maximum typical value
   419  // used for db.maxOpen. If maxOpen is significantly larger than
   420  // connectionRequestQueueSize then it is possible for ALL calls into the *DB
   421  // to block until the connectionOpener can satisfy the backlog of requests.
   422  var connectionRequestQueueSize = 1000000
   423  
   424  // Open opens a database specified by its database driver name and a
   425  // driver-specific data source name, usually consisting of at least a
   426  // database name and connection information.
   427  //
   428  // Most users will open a database via a driver-specific connection
   429  // helper function that returns a *DB. No database drivers are included
   430  // in the Go standard library. See http://golang.org/s/sqldrivers for
   431  // a list of third-party drivers.
   432  //
   433  // Open may just validate its arguments without creating a connection
   434  // to the database. To verify that the data source name is valid, call
   435  // Ping.
   436  //
   437  // The returned DB is safe for concurrent use by multiple goroutines
   438  // and maintains its own pool of idle connections. Thus, the Open
   439  // function should be called just once. It is rarely necessary to
   440  // close a DB.
   441  func Open(driverName, dataSourceName string) (*DB, error) {
   442  	driveri, ok := drivers[driverName]
   443  	if !ok {
   444  		return nil, fmt.Errorf("sql: unknown driver %q (forgotten import?)", driverName)
   445  	}
   446  	db := &DB{
   447  		driver:   driveri,
   448  		dsn:      dataSourceName,
   449  		openerCh: make(chan struct{}, connectionRequestQueueSize),
   450  		lastPut:  make(map[*driverConn]string),
   451  	}
   452  	go db.connectionOpener()
   453  	return db, nil
   454  }
   455  
   456  // Ping verifies a connection to the database is still alive,
   457  // establishing a connection if necessary.
   458  func (db *DB) Ping() error {
   459  	// TODO(bradfitz): give drivers an optional hook to implement
   460  	// this in a more efficient or more reliable way, if they
   461  	// have one.
   462  	dc, err := db.conn()
   463  	if err != nil {
   464  		return err
   465  	}
   466  	db.putConn(dc, nil)
   467  	return nil
   468  }
   469  
   470  // Close closes the database, releasing any open resources.
   471  //
   472  // It is rare to Close a DB, as the DB handle is meant to be
   473  // long-lived and shared between many goroutines.
   474  func (db *DB) Close() error {
   475  	db.mu.Lock()
   476  	if db.closed { // Make DB.Close idempotent
   477  		db.mu.Unlock()
   478  		return nil
   479  	}
   480  	close(db.openerCh)
   481  	var err error
   482  	fns := make([]func() error, 0, len(db.freeConn))
   483  	for _, dc := range db.freeConn {
   484  		fns = append(fns, dc.closeDBLocked())
   485  	}
   486  	db.freeConn = nil
   487  	db.closed = true
   488  	for _, req := range db.connRequests {
   489  		close(req)
   490  	}
   491  	db.mu.Unlock()
   492  	for _, fn := range fns {
   493  		err1 := fn()
   494  		if err1 != nil {
   495  			err = err1
   496  		}
   497  	}
   498  	return err
   499  }
   500  
   501  const defaultMaxIdleConns = 2
   502  
   503  func (db *DB) maxIdleConnsLocked() int {
   504  	n := db.maxIdle
   505  	switch {
   506  	case n == 0:
   507  		// TODO(bradfitz): ask driver, if supported, for its default preference
   508  		return defaultMaxIdleConns
   509  	case n < 0:
   510  		return 0
   511  	default:
   512  		return n
   513  	}
   514  }
   515  
   516  // SetMaxIdleConns sets the maximum number of connections in the idle
   517  // connection pool.
   518  //
   519  // If MaxOpenConns is greater than 0 but less than the new MaxIdleConns
   520  // then the new MaxIdleConns will be reduced to match the MaxOpenConns limit
   521  //
   522  // If n <= 0, no idle connections are retained.
   523  func (db *DB) SetMaxIdleConns(n int) {
   524  	db.mu.Lock()
   525  	if n > 0 {
   526  		db.maxIdle = n
   527  	} else {
   528  		// No idle connections.
   529  		db.maxIdle = -1
   530  	}
   531  	// Make sure maxIdle doesn't exceed maxOpen
   532  	if db.maxOpen > 0 && db.maxIdleConnsLocked() > db.maxOpen {
   533  		db.maxIdle = db.maxOpen
   534  	}
   535  	var closing []*driverConn
   536  	idleCount := len(db.freeConn)
   537  	maxIdle := db.maxIdleConnsLocked()
   538  	if idleCount > maxIdle {
   539  		closing = db.freeConn[maxIdle:]
   540  		db.freeConn = db.freeConn[:maxIdle]
   541  	}
   542  	db.mu.Unlock()
   543  	for _, c := range closing {
   544  		c.Close()
   545  	}
   546  }
   547  
   548  // SetMaxOpenConns sets the maximum number of open connections to the database.
   549  //
   550  // If MaxIdleConns is greater than 0 and the new MaxOpenConns is less than
   551  // MaxIdleConns, then MaxIdleConns will be reduced to match the new
   552  // MaxOpenConns limit
   553  //
   554  // If n <= 0, then there is no limit on the number of open connections.
   555  // The default is 0 (unlimited).
   556  func (db *DB) SetMaxOpenConns(n int) {
   557  	db.mu.Lock()
   558  	db.maxOpen = n
   559  	if n < 0 {
   560  		db.maxOpen = 0
   561  	}
   562  	syncMaxIdle := db.maxOpen > 0 && db.maxIdleConnsLocked() > db.maxOpen
   563  	db.mu.Unlock()
   564  	if syncMaxIdle {
   565  		db.SetMaxIdleConns(n)
   566  	}
   567  }
   568  
   569  // Assumes db.mu is locked.
   570  // If there are connRequests and the connection limit hasn't been reached,
   571  // then tell the connectionOpener to open new connections.
   572  func (db *DB) maybeOpenNewConnections() {
   573  	numRequests := len(db.connRequests) - db.pendingOpens
   574  	if db.maxOpen > 0 {
   575  		numCanOpen := db.maxOpen - (db.numOpen + db.pendingOpens)
   576  		if numRequests > numCanOpen {
   577  			numRequests = numCanOpen
   578  		}
   579  	}
   580  	for numRequests > 0 {
   581  		db.pendingOpens++
   582  		numRequests--
   583  		db.openerCh <- struct{}{}
   584  	}
   585  }
   586  
   587  // Runs in a separate goroutine, opens new connections when requested.
   588  func (db *DB) connectionOpener() {
   589  	for range db.openerCh {
   590  		db.openNewConnection()
   591  	}
   592  }
   593  
   594  // Open one new connection
   595  func (db *DB) openNewConnection() {
   596  	ci, err := db.driver.Open(db.dsn)
   597  	db.mu.Lock()
   598  	defer db.mu.Unlock()
   599  	if db.closed {
   600  		if err == nil {
   601  			ci.Close()
   602  		}
   603  		return
   604  	}
   605  	db.pendingOpens--
   606  	if err != nil {
   607  		db.putConnDBLocked(nil, err)
   608  		return
   609  	}
   610  	dc := &driverConn{
   611  		db: db,
   612  		ci: ci,
   613  	}
   614  	if db.putConnDBLocked(dc, err) {
   615  		db.addDepLocked(dc, dc)
   616  		db.numOpen++
   617  	} else {
   618  		ci.Close()
   619  	}
   620  }
   621  
   622  // connRequest represents one request for a new connection
   623  // When there are no idle connections available, DB.conn will create
   624  // a new connRequest and put it on the db.connRequests list.
   625  type connRequest struct {
   626  	conn *driverConn
   627  	err  error
   628  }
   629  
   630  var errDBClosed = errors.New("sql: database is closed")
   631  
   632  // conn returns a newly-opened or cached *driverConn
   633  func (db *DB) conn() (*driverConn, error) {
   634  	db.mu.Lock()
   635  	if db.closed {
   636  		db.mu.Unlock()
   637  		return nil, errDBClosed
   638  	}
   639  
   640  	// If db.maxOpen > 0 and the number of open connections is over the limit
   641  	// and there are no free connection, make a request and wait.
   642  	if db.maxOpen > 0 && db.numOpen >= db.maxOpen && len(db.freeConn) == 0 {
   643  		// Make the connRequest channel. It's buffered so that the
   644  		// connectionOpener doesn't block while waiting for the req to be read.
   645  		req := make(chan connRequest, 1)
   646  		db.connRequests = append(db.connRequests, req)
   647  		db.mu.Unlock()
   648  		ret := <-req
   649  		return ret.conn, ret.err
   650  	}
   651  
   652  	if c := len(db.freeConn); c > 0 {
   653  		conn := db.freeConn[0]
   654  		copy(db.freeConn, db.freeConn[1:])
   655  		db.freeConn = db.freeConn[:c-1]
   656  		conn.inUse = true
   657  		db.mu.Unlock()
   658  		return conn, nil
   659  	}
   660  
   661  	db.numOpen++ // optimistically
   662  	db.mu.Unlock()
   663  	ci, err := db.driver.Open(db.dsn)
   664  	if err != nil {
   665  		db.mu.Lock()
   666  		db.numOpen-- // correct for earlier optimism
   667  		db.mu.Unlock()
   668  		return nil, err
   669  	}
   670  	db.mu.Lock()
   671  	dc := &driverConn{
   672  		db: db,
   673  		ci: ci,
   674  	}
   675  	db.addDepLocked(dc, dc)
   676  	dc.inUse = true
   677  	db.mu.Unlock()
   678  	return dc, nil
   679  }
   680  
   681  var (
   682  	errConnClosed = errors.New("database/sql: internal sentinel error: conn is closed")
   683  	errConnBusy   = errors.New("database/sql: internal sentinel error: conn is busy")
   684  )
   685  
   686  // connIfFree returns (wanted, nil) if wanted is still a valid conn and
   687  // isn't in use.
   688  //
   689  // The error is errConnClosed if the connection if the requested connection
   690  // is invalid because it's been closed.
   691  //
   692  // The error is errConnBusy if the connection is in use.
   693  func (db *DB) connIfFree(wanted *driverConn) (*driverConn, error) {
   694  	db.mu.Lock()
   695  	defer db.mu.Unlock()
   696  	if wanted.dbmuClosed {
   697  		return nil, errConnClosed
   698  	}
   699  	if wanted.inUse {
   700  		return nil, errConnBusy
   701  	}
   702  	idx := -1
   703  	for ii, v := range db.freeConn {
   704  		if v == wanted {
   705  			idx = ii
   706  			break
   707  		}
   708  	}
   709  	if idx >= 0 {
   710  		db.freeConn = append(db.freeConn[:idx], db.freeConn[idx+1:]...)
   711  		wanted.inUse = true
   712  		return wanted, nil
   713  	}
   714  	// TODO(bradfitz): shouldn't get here. After Go 1.1, change this to:
   715  	// panic("connIfFree call requested a non-closed, non-busy, non-free conn")
   716  	// Which passes all the tests, but I'm too paranoid to include this
   717  	// late in Go 1.1.
   718  	// Instead, treat it like a busy connection:
   719  	return nil, errConnBusy
   720  }
   721  
   722  // putConnHook is a hook for testing.
   723  var putConnHook func(*DB, *driverConn)
   724  
   725  // noteUnusedDriverStatement notes that si is no longer used and should
   726  // be closed whenever possible (when c is next not in use), unless c is
   727  // already closed.
   728  func (db *DB) noteUnusedDriverStatement(c *driverConn, si driver.Stmt) {
   729  	db.mu.Lock()
   730  	defer db.mu.Unlock()
   731  	if c.inUse {
   732  		c.onPut = append(c.onPut, func() {
   733  			si.Close()
   734  		})
   735  	} else {
   736  		c.Lock()
   737  		defer c.Unlock()
   738  		if !c.finalClosed {
   739  			si.Close()
   740  		}
   741  	}
   742  }
   743  
   744  // debugGetPut determines whether getConn & putConn calls' stack traces
   745  // are returned for more verbose crashes.
   746  const debugGetPut = false
   747  
   748  // putConn adds a connection to the db's free pool.
   749  // err is optionally the last error that occurred on this connection.
   750  func (db *DB) putConn(dc *driverConn, err error) {
   751  	db.mu.Lock()
   752  	if !dc.inUse {
   753  		if debugGetPut {
   754  			fmt.Printf("putConn(%v) DUPLICATE was: %s\n\nPREVIOUS was: %s", dc, stack(), db.lastPut[dc])
   755  		}
   756  		panic("sql: connection returned that was never out")
   757  	}
   758  	if debugGetPut {
   759  		db.lastPut[dc] = stack()
   760  	}
   761  	dc.inUse = false
   762  
   763  	for _, fn := range dc.onPut {
   764  		fn()
   765  	}
   766  	dc.onPut = nil
   767  
   768  	if err == driver.ErrBadConn {
   769  		// Don't reuse bad connections.
   770  		// Since the conn is considered bad and is being discarded, treat it
   771  		// as closed. Don't decrement the open count here, finalClose will
   772  		// take care of that.
   773  		db.maybeOpenNewConnections()
   774  		db.mu.Unlock()
   775  		dc.Close()
   776  		return
   777  	}
   778  	if putConnHook != nil {
   779  		putConnHook(db, dc)
   780  	}
   781  	added := db.putConnDBLocked(dc, nil)
   782  	db.mu.Unlock()
   783  
   784  	if !added {
   785  		dc.Close()
   786  	}
   787  }
   788  
   789  // Satisfy a connRequest or put the driverConn in the idle pool and return true
   790  // or return false.
   791  // putConnDBLocked will satisfy a connRequest if there is one, or it will
   792  // return the *driverConn to the freeConn list if err == nil and the idle
   793  // connection limit will not be exceeded.
   794  // If err != nil, the value of dc is ignored.
   795  // If err == nil, then dc must not equal nil.
   796  // If a connRequest was fulfilled or the *driverConn was placed in the
   797  // freeConn list, then true is returned, otherwise false is returned.
   798  func (db *DB) putConnDBLocked(dc *driverConn, err error) bool {
   799  	if c := len(db.connRequests); c > 0 {
   800  		req := db.connRequests[0]
   801  		// This copy is O(n) but in practice faster than a linked list.
   802  		// TODO: consider compacting it down less often and
   803  		// moving the base instead?
   804  		copy(db.connRequests, db.connRequests[1:])
   805  		db.connRequests = db.connRequests[:c-1]
   806  		if err == nil {
   807  			dc.inUse = true
   808  		}
   809  		req <- connRequest{
   810  			conn: dc,
   811  			err:  err,
   812  		}
   813  		return true
   814  	} else if err == nil && !db.closed && db.maxIdleConnsLocked() > len(db.freeConn) {
   815  		db.freeConn = append(db.freeConn, dc)
   816  		return true
   817  	}
   818  	return false
   819  }
   820  
   821  // maxBadConnRetries is the number of maximum retries if the driver returns
   822  // driver.ErrBadConn to signal a broken connection.
   823  const maxBadConnRetries = 10
   824  
   825  // Prepare creates a prepared statement for later queries or executions.
   826  // Multiple queries or executions may be run concurrently from the
   827  // returned statement.
   828  func (db *DB) Prepare(query string) (*Stmt, error) {
   829  	var stmt *Stmt
   830  	var err error
   831  	for i := 0; i < maxBadConnRetries; i++ {
   832  		stmt, err = db.prepare(query)
   833  		if err != driver.ErrBadConn {
   834  			break
   835  		}
   836  	}
   837  	return stmt, err
   838  }
   839  
   840  func (db *DB) prepare(query string) (*Stmt, error) {
   841  	// TODO: check if db.driver supports an optional
   842  	// driver.Preparer interface and call that instead, if so,
   843  	// otherwise we make a prepared statement that's bound
   844  	// to a connection, and to execute this prepared statement
   845  	// we either need to use this connection (if it's free), else
   846  	// get a new connection + re-prepare + execute on that one.
   847  	dc, err := db.conn()
   848  	if err != nil {
   849  		return nil, err
   850  	}
   851  	dc.Lock()
   852  	si, err := dc.prepareLocked(query)
   853  	dc.Unlock()
   854  	if err != nil {
   855  		db.putConn(dc, err)
   856  		return nil, err
   857  	}
   858  	stmt := &Stmt{
   859  		db:    db,
   860  		query: query,
   861  		css:   []connStmt{{dc, si}},
   862  	}
   863  	db.addDep(stmt, stmt)
   864  	db.putConn(dc, nil)
   865  	return stmt, nil
   866  }
   867  
   868  // Exec executes a query without returning any rows.
   869  // The args are for any placeholder parameters in the query.
   870  func (db *DB) Exec(query string, args ...interface{}) (Result, error) {
   871  	var res Result
   872  	var err error
   873  	for i := 0; i < maxBadConnRetries; i++ {
   874  		res, err = db.exec(query, args)
   875  		if err != driver.ErrBadConn {
   876  			break
   877  		}
   878  	}
   879  	return res, err
   880  }
   881  
   882  func (db *DB) exec(query string, args []interface{}) (res Result, err error) {
   883  	dc, err := db.conn()
   884  	if err != nil {
   885  		return nil, err
   886  	}
   887  	defer func() {
   888  		db.putConn(dc, err)
   889  	}()
   890  
   891  	if execer, ok := dc.ci.(driver.Execer); ok {
   892  		dargs, err := driverArgs(nil, args)
   893  		if err != nil {
   894  			return nil, err
   895  		}
   896  		dc.Lock()
   897  		resi, err := execer.Exec(query, dargs)
   898  		dc.Unlock()
   899  		if err != driver.ErrSkip {
   900  			if err != nil {
   901  				return nil, err
   902  			}
   903  			return driverResult{dc, resi}, nil
   904  		}
   905  	}
   906  
   907  	dc.Lock()
   908  	si, err := dc.ci.Prepare(query)
   909  	dc.Unlock()
   910  	if err != nil {
   911  		return nil, err
   912  	}
   913  	defer withLock(dc, func() { si.Close() })
   914  	return resultFromStatement(driverStmt{dc, si}, args...)
   915  }
   916  
   917  // Query executes a query that returns rows, typically a SELECT.
   918  // The args are for any placeholder parameters in the query.
   919  func (db *DB) Query(query string, args ...interface{}) (*Rows, error) {
   920  	var rows *Rows
   921  	var err error
   922  	for i := 0; i < maxBadConnRetries; i++ {
   923  		rows, err = db.query(query, args)
   924  		if err != driver.ErrBadConn {
   925  			break
   926  		}
   927  	}
   928  	return rows, err
   929  }
   930  
   931  func (db *DB) query(query string, args []interface{}) (*Rows, error) {
   932  	ci, err := db.conn()
   933  	if err != nil {
   934  		return nil, err
   935  	}
   936  
   937  	return db.queryConn(ci, ci.releaseConn, query, args)
   938  }
   939  
   940  // queryConn executes a query on the given connection.
   941  // The connection gets released by the releaseConn function.
   942  func (db *DB) queryConn(dc *driverConn, releaseConn func(error), query string, args []interface{}) (*Rows, error) {
   943  	if queryer, ok := dc.ci.(driver.Queryer); ok {
   944  		dargs, err := driverArgs(nil, args)
   945  		if err != nil {
   946  			releaseConn(err)
   947  			return nil, err
   948  		}
   949  		dc.Lock()
   950  		rowsi, err := queryer.Query(query, dargs)
   951  		dc.Unlock()
   952  		if err != driver.ErrSkip {
   953  			if err != nil {
   954  				releaseConn(err)
   955  				return nil, err
   956  			}
   957  			// Note: ownership of dc passes to the *Rows, to be freed
   958  			// with releaseConn.
   959  			rows := &Rows{
   960  				dc:          dc,
   961  				releaseConn: releaseConn,
   962  				rowsi:       rowsi,
   963  			}
   964  			return rows, nil
   965  		}
   966  	}
   967  
   968  	dc.Lock()
   969  	si, err := dc.ci.Prepare(query)
   970  	dc.Unlock()
   971  	if err != nil {
   972  		releaseConn(err)
   973  		return nil, err
   974  	}
   975  
   976  	ds := driverStmt{dc, si}
   977  	rowsi, err := rowsiFromStatement(ds, args...)
   978  	if err != nil {
   979  		dc.Lock()
   980  		si.Close()
   981  		dc.Unlock()
   982  		releaseConn(err)
   983  		return nil, err
   984  	}
   985  
   986  	// Note: ownership of ci passes to the *Rows, to be freed
   987  	// with releaseConn.
   988  	rows := &Rows{
   989  		dc:          dc,
   990  		releaseConn: releaseConn,
   991  		rowsi:       rowsi,
   992  		closeStmt:   si,
   993  	}
   994  	return rows, nil
   995  }
   996  
   997  // QueryRow executes a query that is expected to return at most one row.
   998  // QueryRow always return a non-nil value. Errors are deferred until
   999  // Row's Scan method is called.
  1000  func (db *DB) QueryRow(query string, args ...interface{}) *Row {
  1001  	rows, err := db.Query(query, args...)
  1002  	return &Row{rows: rows, err: err}
  1003  }
  1004  
  1005  // Begin starts a transaction. The isolation level is dependent on
  1006  // the driver.
  1007  func (db *DB) Begin() (*Tx, error) {
  1008  	var tx *Tx
  1009  	var err error
  1010  	for i := 0; i < maxBadConnRetries; i++ {
  1011  		tx, err = db.begin()
  1012  		if err != driver.ErrBadConn {
  1013  			break
  1014  		}
  1015  	}
  1016  	return tx, err
  1017  }
  1018  
  1019  func (db *DB) begin() (tx *Tx, err error) {
  1020  	dc, err := db.conn()
  1021  	if err != nil {
  1022  		return nil, err
  1023  	}
  1024  	dc.Lock()
  1025  	txi, err := dc.ci.Begin()
  1026  	dc.Unlock()
  1027  	if err != nil {
  1028  		db.putConn(dc, err)
  1029  		return nil, err
  1030  	}
  1031  	return &Tx{
  1032  		db:  db,
  1033  		dc:  dc,
  1034  		txi: txi,
  1035  	}, nil
  1036  }
  1037  
  1038  // Driver returns the database's underlying driver.
  1039  func (db *DB) Driver() driver.Driver {
  1040  	return db.driver
  1041  }
  1042  
  1043  // Tx is an in-progress database transaction.
  1044  //
  1045  // A transaction must end with a call to Commit or Rollback.
  1046  //
  1047  // After a call to Commit or Rollback, all operations on the
  1048  // transaction fail with ErrTxDone.
  1049  type Tx struct {
  1050  	db *DB
  1051  
  1052  	// dc is owned exclusively until Commit or Rollback, at which point
  1053  	// it's returned with putConn.
  1054  	dc  *driverConn
  1055  	txi driver.Tx
  1056  
  1057  	// done transitions from false to true exactly once, on Commit
  1058  	// or Rollback. once done, all operations fail with
  1059  	// ErrTxDone.
  1060  	done bool
  1061  
  1062  	// All Stmts prepared for this transaction.  These will be closed after the
  1063  	// transaction has been committed or rolled back.
  1064  	stmts struct {
  1065  		sync.Mutex
  1066  		v []*Stmt
  1067  	}
  1068  }
  1069  
  1070  var ErrTxDone = errors.New("sql: Transaction has already been committed or rolled back")
  1071  
  1072  func (tx *Tx) close() {
  1073  	if tx.done {
  1074  		panic("double close") // internal error
  1075  	}
  1076  	tx.done = true
  1077  	tx.db.putConn(tx.dc, nil)
  1078  	tx.dc = nil
  1079  	tx.txi = nil
  1080  }
  1081  
  1082  func (tx *Tx) grabConn() (*driverConn, error) {
  1083  	if tx.done {
  1084  		return nil, ErrTxDone
  1085  	}
  1086  	return tx.dc, nil
  1087  }
  1088  
  1089  // Closes all Stmts prepared for this transaction.
  1090  func (tx *Tx) closePrepared() {
  1091  	tx.stmts.Lock()
  1092  	for _, stmt := range tx.stmts.v {
  1093  		stmt.Close()
  1094  	}
  1095  	tx.stmts.Unlock()
  1096  }
  1097  
  1098  // Commit commits the transaction.
  1099  func (tx *Tx) Commit() error {
  1100  	if tx.done {
  1101  		return ErrTxDone
  1102  	}
  1103  	defer tx.close()
  1104  	tx.dc.Lock()
  1105  	err := tx.txi.Commit()
  1106  	tx.dc.Unlock()
  1107  	if err != driver.ErrBadConn {
  1108  		tx.closePrepared()
  1109  	}
  1110  	return err
  1111  }
  1112  
  1113  // Rollback aborts the transaction.
  1114  func (tx *Tx) Rollback() error {
  1115  	if tx.done {
  1116  		return ErrTxDone
  1117  	}
  1118  	defer tx.close()
  1119  	tx.dc.Lock()
  1120  	err := tx.txi.Rollback()
  1121  	tx.dc.Unlock()
  1122  	if err != driver.ErrBadConn {
  1123  		tx.closePrepared()
  1124  	}
  1125  	return err
  1126  }
  1127  
  1128  // Prepare creates a prepared statement for use within a transaction.
  1129  //
  1130  // The returned statement operates within the transaction and can no longer
  1131  // be used once the transaction has been committed or rolled back.
  1132  //
  1133  // To use an existing prepared statement on this transaction, see Tx.Stmt.
  1134  func (tx *Tx) Prepare(query string) (*Stmt, error) {
  1135  	// TODO(bradfitz): We could be more efficient here and either
  1136  	// provide a method to take an existing Stmt (created on
  1137  	// perhaps a different Conn), and re-create it on this Conn if
  1138  	// necessary. Or, better: keep a map in DB of query string to
  1139  	// Stmts, and have Stmt.Execute do the right thing and
  1140  	// re-prepare if the Conn in use doesn't have that prepared
  1141  	// statement.  But we'll want to avoid caching the statement
  1142  	// in the case where we only call conn.Prepare implicitly
  1143  	// (such as in db.Exec or tx.Exec), but the caller package
  1144  	// can't be holding a reference to the returned statement.
  1145  	// Perhaps just looking at the reference count (by noting
  1146  	// Stmt.Close) would be enough. We might also want a finalizer
  1147  	// on Stmt to drop the reference count.
  1148  	dc, err := tx.grabConn()
  1149  	if err != nil {
  1150  		return nil, err
  1151  	}
  1152  
  1153  	dc.Lock()
  1154  	si, err := dc.ci.Prepare(query)
  1155  	dc.Unlock()
  1156  	if err != nil {
  1157  		return nil, err
  1158  	}
  1159  
  1160  	stmt := &Stmt{
  1161  		db: tx.db,
  1162  		tx: tx,
  1163  		txsi: &driverStmt{
  1164  			Locker: dc,
  1165  			si:     si,
  1166  		},
  1167  		query: query,
  1168  	}
  1169  	tx.stmts.Lock()
  1170  	tx.stmts.v = append(tx.stmts.v, stmt)
  1171  	tx.stmts.Unlock()
  1172  	return stmt, nil
  1173  }
  1174  
  1175  // Stmt returns a transaction-specific prepared statement from
  1176  // an existing statement.
  1177  //
  1178  // Example:
  1179  //  updateMoney, err := db.Prepare("UPDATE balance SET money=money+? WHERE id=?")
  1180  //  ...
  1181  //  tx, err := db.Begin()
  1182  //  ...
  1183  //  res, err := tx.Stmt(updateMoney).Exec(123.45, 98293203)
  1184  func (tx *Tx) Stmt(stmt *Stmt) *Stmt {
  1185  	// TODO(bradfitz): optimize this. Currently this re-prepares
  1186  	// each time.  This is fine for now to illustrate the API but
  1187  	// we should really cache already-prepared statements
  1188  	// per-Conn. See also the big comment in Tx.Prepare.
  1189  
  1190  	if tx.db != stmt.db {
  1191  		return &Stmt{stickyErr: errors.New("sql: Tx.Stmt: statement from different database used")}
  1192  	}
  1193  	dc, err := tx.grabConn()
  1194  	if err != nil {
  1195  		return &Stmt{stickyErr: err}
  1196  	}
  1197  	dc.Lock()
  1198  	si, err := dc.ci.Prepare(stmt.query)
  1199  	dc.Unlock()
  1200  	txs := &Stmt{
  1201  		db: tx.db,
  1202  		tx: tx,
  1203  		txsi: &driverStmt{
  1204  			Locker: dc,
  1205  			si:     si,
  1206  		},
  1207  		query:     stmt.query,
  1208  		stickyErr: err,
  1209  	}
  1210  	tx.stmts.Lock()
  1211  	tx.stmts.v = append(tx.stmts.v, txs)
  1212  	tx.stmts.Unlock()
  1213  	return txs
  1214  }
  1215  
  1216  // Exec executes a query that doesn't return rows.
  1217  // For example: an INSERT and UPDATE.
  1218  func (tx *Tx) Exec(query string, args ...interface{}) (Result, error) {
  1219  	dc, err := tx.grabConn()
  1220  	if err != nil {
  1221  		return nil, err
  1222  	}
  1223  
  1224  	if execer, ok := dc.ci.(driver.Execer); ok {
  1225  		dargs, err := driverArgs(nil, args)
  1226  		if err != nil {
  1227  			return nil, err
  1228  		}
  1229  		dc.Lock()
  1230  		resi, err := execer.Exec(query, dargs)
  1231  		dc.Unlock()
  1232  		if err == nil {
  1233  			return driverResult{dc, resi}, nil
  1234  		}
  1235  		if err != driver.ErrSkip {
  1236  			return nil, err
  1237  		}
  1238  	}
  1239  
  1240  	dc.Lock()
  1241  	si, err := dc.ci.Prepare(query)
  1242  	dc.Unlock()
  1243  	if err != nil {
  1244  		return nil, err
  1245  	}
  1246  	defer withLock(dc, func() { si.Close() })
  1247  
  1248  	return resultFromStatement(driverStmt{dc, si}, args...)
  1249  }
  1250  
  1251  // Query executes a query that returns rows, typically a SELECT.
  1252  func (tx *Tx) Query(query string, args ...interface{}) (*Rows, error) {
  1253  	dc, err := tx.grabConn()
  1254  	if err != nil {
  1255  		return nil, err
  1256  	}
  1257  	releaseConn := func(error) {}
  1258  	return tx.db.queryConn(dc, releaseConn, query, args)
  1259  }
  1260  
  1261  // QueryRow executes a query that is expected to return at most one row.
  1262  // QueryRow always return a non-nil value. Errors are deferred until
  1263  // Row's Scan method is called.
  1264  func (tx *Tx) QueryRow(query string, args ...interface{}) *Row {
  1265  	rows, err := tx.Query(query, args...)
  1266  	return &Row{rows: rows, err: err}
  1267  }
  1268  
  1269  // connStmt is a prepared statement on a particular connection.
  1270  type connStmt struct {
  1271  	dc *driverConn
  1272  	si driver.Stmt
  1273  }
  1274  
  1275  // Stmt is a prepared statement. Stmt is safe for concurrent use by multiple goroutines.
  1276  type Stmt struct {
  1277  	// Immutable:
  1278  	db        *DB    // where we came from
  1279  	query     string // that created the Stmt
  1280  	stickyErr error  // if non-nil, this error is returned for all operations
  1281  
  1282  	closemu sync.RWMutex // held exclusively during close, for read otherwise.
  1283  
  1284  	// If in a transaction, else both nil:
  1285  	tx   *Tx
  1286  	txsi *driverStmt
  1287  
  1288  	mu     sync.Mutex // protects the rest of the fields
  1289  	closed bool
  1290  
  1291  	// css is a list of underlying driver statement interfaces
  1292  	// that are valid on particular connections.  This is only
  1293  	// used if tx == nil and one is found that has idle
  1294  	// connections.  If tx != nil, txsi is always used.
  1295  	css []connStmt
  1296  }
  1297  
  1298  // Exec executes a prepared statement with the given arguments and
  1299  // returns a Result summarizing the effect of the statement.
  1300  func (s *Stmt) Exec(args ...interface{}) (Result, error) {
  1301  	s.closemu.RLock()
  1302  	defer s.closemu.RUnlock()
  1303  
  1304  	var res Result
  1305  	for i := 0; i < maxBadConnRetries; i++ {
  1306  		dc, releaseConn, si, err := s.connStmt()
  1307  		if err != nil {
  1308  			if err == driver.ErrBadConn {
  1309  				continue
  1310  			}
  1311  			return nil, err
  1312  		}
  1313  
  1314  		res, err = resultFromStatement(driverStmt{dc, si}, args...)
  1315  		releaseConn(err)
  1316  		if err != driver.ErrBadConn {
  1317  			return res, err
  1318  		}
  1319  	}
  1320  	return nil, driver.ErrBadConn
  1321  }
  1322  
  1323  func resultFromStatement(ds driverStmt, args ...interface{}) (Result, error) {
  1324  	ds.Lock()
  1325  	want := ds.si.NumInput()
  1326  	ds.Unlock()
  1327  
  1328  	// -1 means the driver doesn't know how to count the number of
  1329  	// placeholders, so we won't sanity check input here and instead let the
  1330  	// driver deal with errors.
  1331  	if want != -1 && len(args) != want {
  1332  		return nil, fmt.Errorf("sql: expected %d arguments, got %d", want, len(args))
  1333  	}
  1334  
  1335  	dargs, err := driverArgs(&ds, args)
  1336  	if err != nil {
  1337  		return nil, err
  1338  	}
  1339  
  1340  	ds.Lock()
  1341  	resi, err := ds.si.Exec(dargs)
  1342  	ds.Unlock()
  1343  	if err != nil {
  1344  		return nil, err
  1345  	}
  1346  	return driverResult{ds.Locker, resi}, nil
  1347  }
  1348  
  1349  // connStmt returns a free driver connection on which to execute the
  1350  // statement, a function to call to release the connection, and a
  1351  // statement bound to that connection.
  1352  func (s *Stmt) connStmt() (ci *driverConn, releaseConn func(error), si driver.Stmt, err error) {
  1353  	if err = s.stickyErr; err != nil {
  1354  		return
  1355  	}
  1356  	s.mu.Lock()
  1357  	if s.closed {
  1358  		s.mu.Unlock()
  1359  		err = errors.New("sql: statement is closed")
  1360  		return
  1361  	}
  1362  
  1363  	// In a transaction, we always use the connection that the
  1364  	// transaction was created on.
  1365  	if s.tx != nil {
  1366  		s.mu.Unlock()
  1367  		ci, err = s.tx.grabConn() // blocks, waiting for the connection.
  1368  		if err != nil {
  1369  			return
  1370  		}
  1371  		releaseConn = func(error) {}
  1372  		return ci, releaseConn, s.txsi.si, nil
  1373  	}
  1374  
  1375  	for i := 0; i < len(s.css); i++ {
  1376  		v := s.css[i]
  1377  		_, err := s.db.connIfFree(v.dc)
  1378  		if err == nil {
  1379  			s.mu.Unlock()
  1380  			return v.dc, v.dc.releaseConn, v.si, nil
  1381  		}
  1382  		if err == errConnClosed {
  1383  			// Lazily remove dead conn from our freelist.
  1384  			s.css[i] = s.css[len(s.css)-1]
  1385  			s.css = s.css[:len(s.css)-1]
  1386  			i--
  1387  		}
  1388  
  1389  	}
  1390  	s.mu.Unlock()
  1391  
  1392  	// If all connections are busy, either wait for one to become available (if
  1393  	// we've already hit the maximum number of open connections) or create a
  1394  	// new one.
  1395  	//
  1396  	// TODO(bradfitz): or always wait for one? make configurable later?
  1397  	dc, err := s.db.conn()
  1398  	if err != nil {
  1399  		return nil, nil, nil, err
  1400  	}
  1401  
  1402  	// Do another pass over the list to see whether this statement has
  1403  	// already been prepared on the connection assigned to us.
  1404  	s.mu.Lock()
  1405  	for _, v := range s.css {
  1406  		if v.dc == dc {
  1407  			s.mu.Unlock()
  1408  			return dc, dc.releaseConn, v.si, nil
  1409  		}
  1410  	}
  1411  	s.mu.Unlock()
  1412  
  1413  	// No luck; we need to prepare the statement on this connection
  1414  	dc.Lock()
  1415  	si, err = dc.prepareLocked(s.query)
  1416  	dc.Unlock()
  1417  	if err != nil {
  1418  		s.db.putConn(dc, err)
  1419  		return nil, nil, nil, err
  1420  	}
  1421  	s.mu.Lock()
  1422  	cs := connStmt{dc, si}
  1423  	s.css = append(s.css, cs)
  1424  	s.mu.Unlock()
  1425  
  1426  	return dc, dc.releaseConn, si, nil
  1427  }
  1428  
  1429  // Query executes a prepared query statement with the given arguments
  1430  // and returns the query results as a *Rows.
  1431  func (s *Stmt) Query(args ...interface{}) (*Rows, error) {
  1432  	s.closemu.RLock()
  1433  	defer s.closemu.RUnlock()
  1434  
  1435  	var rowsi driver.Rows
  1436  	for i := 0; i < maxBadConnRetries; i++ {
  1437  		dc, releaseConn, si, err := s.connStmt()
  1438  		if err != nil {
  1439  			if err == driver.ErrBadConn {
  1440  				continue
  1441  			}
  1442  			return nil, err
  1443  		}
  1444  
  1445  		rowsi, err = rowsiFromStatement(driverStmt{dc, si}, args...)
  1446  		if err == nil {
  1447  			// Note: ownership of ci passes to the *Rows, to be freed
  1448  			// with releaseConn.
  1449  			rows := &Rows{
  1450  				dc:    dc,
  1451  				rowsi: rowsi,
  1452  				// releaseConn set below
  1453  			}
  1454  			s.db.addDep(s, rows)
  1455  			rows.releaseConn = func(err error) {
  1456  				releaseConn(err)
  1457  				s.db.removeDep(s, rows)
  1458  			}
  1459  			return rows, nil
  1460  		}
  1461  
  1462  		releaseConn(err)
  1463  		if err != driver.ErrBadConn {
  1464  			return nil, err
  1465  		}
  1466  	}
  1467  	return nil, driver.ErrBadConn
  1468  }
  1469  
  1470  func rowsiFromStatement(ds driverStmt, args ...interface{}) (driver.Rows, error) {
  1471  	ds.Lock()
  1472  	want := ds.si.NumInput()
  1473  	ds.Unlock()
  1474  
  1475  	// -1 means the driver doesn't know how to count the number of
  1476  	// placeholders, so we won't sanity check input here and instead let the
  1477  	// driver deal with errors.
  1478  	if want != -1 && len(args) != want {
  1479  		return nil, fmt.Errorf("sql: statement expects %d inputs; got %d", want, len(args))
  1480  	}
  1481  
  1482  	dargs, err := driverArgs(&ds, args)
  1483  	if err != nil {
  1484  		return nil, err
  1485  	}
  1486  
  1487  	ds.Lock()
  1488  	rowsi, err := ds.si.Query(dargs)
  1489  	ds.Unlock()
  1490  	if err != nil {
  1491  		return nil, err
  1492  	}
  1493  	return rowsi, nil
  1494  }
  1495  
  1496  // QueryRow executes a prepared query statement with the given arguments.
  1497  // If an error occurs during the execution of the statement, that error will
  1498  // be returned by a call to Scan on the returned *Row, which is always non-nil.
  1499  // If the query selects no rows, the *Row's Scan will return ErrNoRows.
  1500  // Otherwise, the *Row's Scan scans the first selected row and discards
  1501  // the rest.
  1502  //
  1503  // Example usage:
  1504  //
  1505  //  var name string
  1506  //  err := nameByUseridStmt.QueryRow(id).Scan(&name)
  1507  func (s *Stmt) QueryRow(args ...interface{}) *Row {
  1508  	rows, err := s.Query(args...)
  1509  	if err != nil {
  1510  		return &Row{err: err}
  1511  	}
  1512  	return &Row{rows: rows}
  1513  }
  1514  
  1515  // Close closes the statement.
  1516  func (s *Stmt) Close() error {
  1517  	s.closemu.Lock()
  1518  	defer s.closemu.Unlock()
  1519  
  1520  	if s.stickyErr != nil {
  1521  		return s.stickyErr
  1522  	}
  1523  	s.mu.Lock()
  1524  	if s.closed {
  1525  		s.mu.Unlock()
  1526  		return nil
  1527  	}
  1528  	s.closed = true
  1529  
  1530  	if s.tx != nil {
  1531  		s.txsi.Close()
  1532  		s.mu.Unlock()
  1533  		return nil
  1534  	}
  1535  	s.mu.Unlock()
  1536  
  1537  	return s.db.removeDep(s, s)
  1538  }
  1539  
  1540  func (s *Stmt) finalClose() error {
  1541  	s.mu.Lock()
  1542  	defer s.mu.Unlock()
  1543  	if s.css != nil {
  1544  		for _, v := range s.css {
  1545  			s.db.noteUnusedDriverStatement(v.dc, v.si)
  1546  			v.dc.removeOpenStmt(v.si)
  1547  		}
  1548  		s.css = nil
  1549  	}
  1550  	return nil
  1551  }
  1552  
  1553  // Rows is the result of a query. Its cursor starts before the first row
  1554  // of the result set. Use Next to advance through the rows:
  1555  //
  1556  //     rows, err := db.Query("SELECT ...")
  1557  //     ...
  1558  //     defer rows.Close()
  1559  //     for rows.Next() {
  1560  //         var id int
  1561  //         var name string
  1562  //         err = rows.Scan(&id, &name)
  1563  //         ...
  1564  //     }
  1565  //     err = rows.Err() // get any error encountered during iteration
  1566  //     ...
  1567  type Rows struct {
  1568  	dc          *driverConn // owned; must call releaseConn when closed to release
  1569  	releaseConn func(error)
  1570  	rowsi       driver.Rows
  1571  
  1572  	closed    bool
  1573  	lastcols  []driver.Value
  1574  	lasterr   error       // non-nil only if closed is true
  1575  	closeStmt driver.Stmt // if non-nil, statement to Close on close
  1576  }
  1577  
  1578  // Next prepares the next result row for reading with the Scan method.  It
  1579  // returns true on success, or false if there is no next result row or an error
  1580  // happened while preparing it.  Err should be consulted to distinguish between
  1581  // the two cases.
  1582  //
  1583  // Every call to Scan, even the first one, must be preceded by a call to Next.
  1584  func (rs *Rows) Next() bool {
  1585  	if rs.closed {
  1586  		return false
  1587  	}
  1588  	if rs.lastcols == nil {
  1589  		rs.lastcols = make([]driver.Value, len(rs.rowsi.Columns()))
  1590  	}
  1591  	rs.lasterr = rs.rowsi.Next(rs.lastcols)
  1592  	if rs.lasterr != nil {
  1593  		rs.Close()
  1594  		return false
  1595  	}
  1596  	return true
  1597  }
  1598  
  1599  // Err returns the error, if any, that was encountered during iteration.
  1600  // Err may be called after an explicit or implicit Close.
  1601  func (rs *Rows) Err() error {
  1602  	if rs.lasterr == io.EOF {
  1603  		return nil
  1604  	}
  1605  	return rs.lasterr
  1606  }
  1607  
  1608  // Columns returns the column names.
  1609  // Columns returns an error if the rows are closed, or if the rows
  1610  // are from QueryRow and there was a deferred error.
  1611  func (rs *Rows) Columns() ([]string, error) {
  1612  	if rs.closed {
  1613  		return nil, errors.New("sql: Rows are closed")
  1614  	}
  1615  	if rs.rowsi == nil {
  1616  		return nil, errors.New("sql: no Rows available")
  1617  	}
  1618  	return rs.rowsi.Columns(), nil
  1619  }
  1620  
  1621  // Scan copies the columns in the current row into the values pointed
  1622  // at by dest.
  1623  //
  1624  // If an argument has type *[]byte, Scan saves in that argument a copy
  1625  // of the corresponding data. The copy is owned by the caller and can
  1626  // be modified and held indefinitely. The copy can be avoided by using
  1627  // an argument of type *RawBytes instead; see the documentation for
  1628  // RawBytes for restrictions on its use.
  1629  //
  1630  // If an argument has type *interface{}, Scan copies the value
  1631  // provided by the underlying driver without conversion. If the value
  1632  // is of type []byte, a copy is made and the caller owns the result.
  1633  func (rs *Rows) Scan(dest ...interface{}) error {
  1634  	if rs.closed {
  1635  		return errors.New("sql: Rows are closed")
  1636  	}
  1637  	if rs.lastcols == nil {
  1638  		return errors.New("sql: Scan called without calling Next")
  1639  	}
  1640  	if len(dest) != len(rs.lastcols) {
  1641  		return fmt.Errorf("sql: expected %d destination arguments in Scan, not %d", len(rs.lastcols), len(dest))
  1642  	}
  1643  	for i, sv := range rs.lastcols {
  1644  		err := convertAssign(dest[i], sv)
  1645  		if err != nil {
  1646  			return fmt.Errorf("sql: Scan error on column index %d: %v", i, err)
  1647  		}
  1648  	}
  1649  	return nil
  1650  }
  1651  
  1652  var rowsCloseHook func(*Rows, *error)
  1653  
  1654  // Close closes the Rows, preventing further enumeration. If Next returns
  1655  // false, the Rows are closed automatically and it will suffice to check the
  1656  // result of Err. Close is idempotent and does not affect the result of Err.
  1657  func (rs *Rows) Close() error {
  1658  	if rs.closed {
  1659  		return nil
  1660  	}
  1661  	rs.closed = true
  1662  	err := rs.rowsi.Close()
  1663  	if fn := rowsCloseHook; fn != nil {
  1664  		fn(rs, &err)
  1665  	}
  1666  	if rs.closeStmt != nil {
  1667  		rs.closeStmt.Close()
  1668  	}
  1669  	rs.releaseConn(err)
  1670  	return err
  1671  }
  1672  
  1673  // Row is the result of calling QueryRow to select a single row.
  1674  type Row struct {
  1675  	// One of these two will be non-nil:
  1676  	err  error // deferred error for easy chaining
  1677  	rows *Rows
  1678  }
  1679  
  1680  // Scan copies the columns from the matched row into the values
  1681  // pointed at by dest.  If more than one row matches the query,
  1682  // Scan uses the first row and discards the rest.  If no row matches
  1683  // the query, Scan returns ErrNoRows.
  1684  func (r *Row) Scan(dest ...interface{}) error {
  1685  	if r.err != nil {
  1686  		return r.err
  1687  	}
  1688  
  1689  	// TODO(bradfitz): for now we need to defensively clone all
  1690  	// []byte that the driver returned (not permitting
  1691  	// *RawBytes in Rows.Scan), since we're about to close
  1692  	// the Rows in our defer, when we return from this function.
  1693  	// the contract with the driver.Next(...) interface is that it
  1694  	// can return slices into read-only temporary memory that's
  1695  	// only valid until the next Scan/Close.  But the TODO is that
  1696  	// for a lot of drivers, this copy will be unnecessary.  We
  1697  	// should provide an optional interface for drivers to
  1698  	// implement to say, "don't worry, the []bytes that I return
  1699  	// from Next will not be modified again." (for instance, if
  1700  	// they were obtained from the network anyway) But for now we
  1701  	// don't care.
  1702  	defer r.rows.Close()
  1703  	for _, dp := range dest {
  1704  		if _, ok := dp.(*RawBytes); ok {
  1705  			return errors.New("sql: RawBytes isn't allowed on Row.Scan")
  1706  		}
  1707  	}
  1708  
  1709  	if !r.rows.Next() {
  1710  		if err := r.rows.Err(); err != nil {
  1711  			return err
  1712  		}
  1713  		return ErrNoRows
  1714  	}
  1715  	err := r.rows.Scan(dest...)
  1716  	if err != nil {
  1717  		return err
  1718  	}
  1719  	// Make sure the query can be processed to completion with no errors.
  1720  	if err := r.rows.Close(); err != nil {
  1721  		return err
  1722  	}
  1723  
  1724  	return nil
  1725  }
  1726  
  1727  // A Result summarizes an executed SQL command.
  1728  type Result interface {
  1729  	// LastInsertId returns the integer generated by the database
  1730  	// in response to a command. Typically this will be from an
  1731  	// "auto increment" column when inserting a new row. Not all
  1732  	// databases support this feature, and the syntax of such
  1733  	// statements varies.
  1734  	LastInsertId() (int64, error)
  1735  
  1736  	// RowsAffected returns the number of rows affected by an
  1737  	// update, insert, or delete. Not every database or database
  1738  	// driver may support this.
  1739  	RowsAffected() (int64, error)
  1740  }
  1741  
  1742  type driverResult struct {
  1743  	sync.Locker // the *driverConn
  1744  	resi        driver.Result
  1745  }
  1746  
  1747  func (dr driverResult) LastInsertId() (int64, error) {
  1748  	dr.Lock()
  1749  	defer dr.Unlock()
  1750  	return dr.resi.LastInsertId()
  1751  }
  1752  
  1753  func (dr driverResult) RowsAffected() (int64, error) {
  1754  	dr.Lock()
  1755  	defer dr.Unlock()
  1756  	return dr.resi.RowsAffected()
  1757  }
  1758  
  1759  func stack() string {
  1760  	var buf [2 << 10]byte
  1761  	return string(buf[:runtime.Stack(buf[:], false)])
  1762  }
  1763  
  1764  // withLock runs while holding lk.
  1765  func withLock(lk sync.Locker, fn func()) {
  1766  	lk.Lock()
  1767  	fn()
  1768  	lk.Unlock()
  1769  }