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