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