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