src/pkg/database/sql/sql.go - The Go Programming Language

Golang

Source file src/pkg/database/sql/sql.go

     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	package sql
     8	
     9	import (
    10		"database/sql/driver"
    11		"errors"
    12		"fmt"
    13		"io"
    14		"sync"
    15	)
    16	
    17	var drivers = make(map[string]driver.Driver)
    18	
    19	// Register makes a database driver available by the provided name.
    20	// If Register is called twice with the same name or if driver is nil,
    21	// it panics.
    22	func Register(name string, driver driver.Driver) {
    23		if driver == nil {
    24			panic("sql: Register driver is nil")
    25		}
    26		if _, dup := drivers[name]; dup {
    27			panic("sql: Register called twice for driver " + name)
    28		}
    29		drivers[name] = driver
    30	}
    31	
    32	// RawBytes is a byte slice that holds a reference to memory owned by
    33	// the database itself. After a Scan into a RawBytes, the slice is only
    34	// valid until the next call to Next, Scan, or Close.
    35	type RawBytes []byte
    36	
    37	// NullString represents a string that may be null.
    38	// NullString implements the Scanner interface so
    39	// it can be used as a scan destination:
    40	//
    41	//  var s NullString
    42	//  err := db.QueryRow("SELECT name FROM foo WHERE id=?", id).Scan(&s)
    43	//  ...
    44	//  if s.Valid {
    45	//     // use s.String
    46	//  } else {
    47	//     // NULL value
    48	//  }
    49	//
    50	type NullString struct {
    51		String string
    52		Valid  bool // Valid is true if String is not NULL
    53	}
    54	
    55	// Scan implements the Scanner interface.
    56	func (ns *NullString) Scan(value interface{}) error {
    57		if value == nil {
    58			ns.String, ns.Valid = "", false
    59			return nil
    60		}
    61		ns.Valid = true
    62		return convertAssign(&ns.String, value)
    63	}
    64	
    65	// Value implements the driver Valuer interface.
    66	func (ns NullString) Value() (driver.Value, error) {
    67		if !ns.Valid {
    68			return nil, nil
    69		}
    70		return ns.String, nil
    71	}
    72	
    73	// NullInt64 represents an int64 that may be null.
    74	// NullInt64 implements the Scanner interface so
    75	// it can be used as a scan destination, similar to NullString.
    76	type NullInt64 struct {
    77		Int64 int64
    78		Valid bool // Valid is true if Int64 is not NULL
    79	}
    80	
    81	// Scan implements the Scanner interface.
    82	func (n *NullInt64) Scan(value interface{}) error {
    83		if value == nil {
    84			n.Int64, n.Valid = 0, false
    85			return nil
    86		}
    87		n.Valid = true
    88		return convertAssign(&n.Int64, value)
    89	}
    90	
    91	// Value implements the driver Valuer interface.
    92	func (n NullInt64) Value() (driver.Value, error) {
    93		if !n.Valid {
    94			return nil, nil
    95		}
    96		return n.Int64, nil
    97	}
    98	
    99	// NullFloat64 represents a float64 that may be null.
   100	// NullFloat64 implements the Scanner interface so
   101	// it can be used as a scan destination, similar to NullString.
   102	type NullFloat64 struct {
   103		Float64 float64
   104		Valid   bool // Valid is true if Float64 is not NULL
   105	}
   106	
   107	// Scan implements the Scanner interface.
   108	func (n *NullFloat64) Scan(value interface{}) error {
   109		if value == nil {
   110			n.Float64, n.Valid = 0, false
   111			return nil
   112		}
   113		n.Valid = true
   114		return convertAssign(&n.Float64, value)
   115	}
   116	
   117	// Value implements the driver Valuer interface.
   118	func (n NullFloat64) Value() (driver.Value, error) {
   119		if !n.Valid {
   120			return nil, nil
   121		}
   122		return n.Float64, nil
   123	}
   124	
   125	// NullBool represents a bool that may be null.
   126	// NullBool implements the Scanner interface so
   127	// it can be used as a scan destination, similar to NullString.
   128	type NullBool struct {
   129		Bool  bool
   130		Valid bool // Valid is true if Bool is not NULL
   131	}
   132	
   133	// Scan implements the Scanner interface.
   134	func (n *NullBool) Scan(value interface{}) error {
   135		if value == nil {
   136			n.Bool, n.Valid = false, false
   137			return nil
   138		}
   139		n.Valid = true
   140		return convertAssign(&n.Bool, value)
   141	}
   142	
   143	// Value implements the driver Valuer interface.
   144	func (n NullBool) Value() (driver.Value, error) {
   145		if !n.Valid {
   146			return nil, nil
   147		}
   148		return n.Bool, nil
   149	}
   150	
   151	// Scanner is an interface used by Scan.
   152	type Scanner interface {
   153		// Scan assigns a value from a database driver.
   154		//
   155		// The src value will be of one of the following restricted
   156		// set of types:
   157		//
   158		//    int64
   159		//    float64
   160		//    bool
   161		//    []byte
   162		//    string
   163		//    time.Time
   164		//    nil - for NULL values
   165		//
   166		// An error should be returned if the value can not be stored
   167		// without loss of information.
   168		Scan(src interface{}) error
   169	}
   170	
   171	// ErrNoRows is returned by Scan when QueryRow doesn't return a
   172	// row. In such a case, QueryRow returns a placeholder *Row value that
   173	// defers this error until a Scan.
   174	var ErrNoRows = errors.New("sql: no rows in result set")
   175	
   176	// DB is a database handle. It's safe for concurrent use by multiple
   177	// goroutines.
   178	//
   179	// If the underlying database driver has the concept of a connection
   180	// and per-connection session state, the sql package manages creating
   181	// and freeing connections automatically, including maintaining a free
   182	// pool of idle connections. If observing session state is required,
   183	// either do not share a *DB between multiple concurrent goroutines or
   184	// create and observe all state only within a transaction. Once
   185	// DB.Open is called, the returned Tx is bound to a single isolated
   186	// connection. Once Tx.Commit or Tx.Rollback is called, that
   187	// connection is returned to DB's idle connection pool.
   188	type DB struct {
   189		driver driver.Driver
   190		dsn    string
   191	
   192		mu       sync.Mutex // protects freeConn and closed
   193		freeConn []driver.Conn
   194		closed   bool
   195	}
   196	
   197	// Open opens a database specified by its database driver name and a
   198	// driver-specific data source name, usually consisting of at least a
   199	// database name and connection information.
   200	//
   201	// Most users will open a database via a driver-specific connection
   202	// helper function that returns a *DB.
   203	func Open(driverName, dataSourceName string) (*DB, error) {
   204		driver, ok := drivers[driverName]
   205		if !ok {
   206			return nil, fmt.Errorf("sql: unknown driver %q (forgotten import?)", driverName)
   207		}
   208		return &DB{driver: driver, dsn: dataSourceName}, nil
   209	}
   210	
   211	// Close closes the database, releasing any open resources.
   212	func (db *DB) Close() error {
   213		db.mu.Lock()
   214		defer db.mu.Unlock()
   215		var err error
   216		for _, c := range db.freeConn {
   217			err1 := c.Close()
   218			if err1 != nil {
   219				err = err1
   220			}
   221		}
   222		db.freeConn = nil
   223		db.closed = true
   224		return err
   225	}
   226	
   227	func (db *DB) maxIdleConns() int {
   228		const defaultMaxIdleConns = 2
   229		// TODO(bradfitz): ask driver, if supported, for its default preference
   230		// TODO(bradfitz): let users override?
   231		return defaultMaxIdleConns
   232	}
   233	
   234	// conn returns a newly-opened or cached driver.Conn
   235	func (db *DB) conn() (driver.Conn, error) {
   236		db.mu.Lock()
   237		if db.closed {
   238			db.mu.Unlock()
   239			return nil, errors.New("sql: database is closed")
   240		}
   241		if n := len(db.freeConn); n > 0 {
   242			conn := db.freeConn[n-1]
   243			db.freeConn = db.freeConn[:n-1]
   244			db.mu.Unlock()
   245			return conn, nil
   246		}
   247		db.mu.Unlock()
   248		return db.driver.Open(db.dsn)
   249	}
   250	
   251	func (db *DB) connIfFree(wanted driver.Conn) (conn driver.Conn, ok bool) {
   252		db.mu.Lock()
   253		defer db.mu.Unlock()
   254		for i, conn := range db.freeConn {
   255			if conn != wanted {
   256				continue
   257			}
   258			db.freeConn[i] = db.freeConn[len(db.freeConn)-1]
   259			db.freeConn = db.freeConn[:len(db.freeConn)-1]
   260			return wanted, true
   261		}
   262		return nil, false
   263	}
   264	
   265	// putConnHook is a hook for testing.
   266	var putConnHook func(*DB, driver.Conn)
   267	
   268	// putConn adds a connection to the db's free pool.
   269	// err is optionally the last error that occured on this connection.
   270	func (db *DB) putConn(c driver.Conn, err error) {
   271		if err == driver.ErrBadConn {
   272			// Don't reuse bad connections.
   273			return
   274		}
   275		db.mu.Lock()
   276		if putConnHook != nil {
   277			putConnHook(db, c)
   278		}
   279		if n := len(db.freeConn); !db.closed && n < db.maxIdleConns() {
   280			db.freeConn = append(db.freeConn, c)
   281			db.mu.Unlock()
   282			return
   283		}
   284		// TODO: check to see if we need this Conn for any prepared
   285		// statements which are still active?
   286		db.mu.Unlock()
   287		c.Close()
   288	}
   289	
   290	// Prepare creates a prepared statement for later execution.
   291	func (db *DB) Prepare(query string) (*Stmt, error) {
   292		var stmt *Stmt
   293		var err error
   294		for i := 0; i < 10; i++ {
   295			stmt, err = db.prepare(query)
   296			if err != driver.ErrBadConn {
   297				break
   298			}
   299		}
   300		return stmt, err
   301	}
   302	
   303	func (db *DB) prepare(query string) (stmt *Stmt, err error) {
   304		// TODO: check if db.driver supports an optional
   305		// driver.Preparer interface and call that instead, if so,
   306		// otherwise we make a prepared statement that's bound
   307		// to a connection, and to execute this prepared statement
   308		// we either need to use this connection (if it's free), else
   309		// get a new connection + re-prepare + execute on that one.
   310		ci, err := db.conn()
   311		if err != nil {
   312			return nil, err
   313		}
   314		defer db.putConn(ci, err)
   315		si, err := ci.Prepare(query)
   316		if err != nil {
   317			return nil, err
   318		}
   319		stmt = &Stmt{
   320			db:    db,
   321			query: query,
   322			css:   []connStmt{{ci, si}},
   323		}
   324		return stmt, nil
   325	}
   326	
   327	// Exec executes a query without returning any rows.
   328	func (db *DB) Exec(query string, args ...interface{}) (Result, error) {
   329		sargs, err := subsetTypeArgs(args)
   330		if err != nil {
   331			return nil, err
   332		}
   333		var res Result
   334		for i := 0; i < 10; i++ {
   335			res, err = db.exec(query, sargs)
   336			if err != driver.ErrBadConn {
   337				break
   338			}
   339		}
   340		return res, err
   341	}
   342	
   343	func (db *DB) exec(query string, sargs []driver.Value) (res Result, err error) {
   344		ci, err := db.conn()
   345		if err != nil {
   346			return nil, err
   347		}
   348		defer db.putConn(ci, err)
   349	
   350		if execer, ok := ci.(driver.Execer); ok {
   351			resi, err := execer.Exec(query, sargs)
   352			if err != driver.ErrSkip {
   353				if err != nil {
   354					return nil, err
   355				}
   356				return result{resi}, nil
   357			}
   358		}
   359	
   360		sti, err := ci.Prepare(query)
   361		if err != nil {
   362			return nil, err
   363		}
   364		defer sti.Close()
   365	
   366		resi, err := sti.Exec(sargs)
   367		if err != nil {
   368			return nil, err
   369		}
   370		return result{resi}, nil
   371	}
   372	
   373	// Query executes a query that returns rows, typically a SELECT.
   374	func (db *DB) Query(query string, args ...interface{}) (*Rows, error) {
   375		stmt, err := db.Prepare(query)
   376		if err != nil {
   377			return nil, err
   378		}
   379		rows, err := stmt.Query(args...)
   380		if err != nil {
   381			stmt.Close()
   382			return nil, err
   383		}
   384		rows.closeStmt = stmt
   385		return rows, nil
   386	}
   387	
   388	// QueryRow executes a query that is expected to return at most one row.
   389	// QueryRow always return a non-nil value. Errors are deferred until
   390	// Row's Scan method is called.
   391	func (db *DB) QueryRow(query string, args ...interface{}) *Row {
   392		rows, err := db.Query(query, args...)
   393		return &Row{rows: rows, err: err}
   394	}
   395	
   396	// Begin starts a transaction. The isolation level is dependent on
   397	// the driver.
   398	func (db *DB) Begin() (*Tx, error) {
   399		var tx *Tx
   400		var err error
   401		for i := 0; i < 10; i++ {
   402			tx, err = db.begin()
   403			if err != driver.ErrBadConn {
   404				break
   405			}
   406		}
   407		return tx, err
   408	}
   409	
   410	func (db *DB) begin() (tx *Tx, err error) {
   411		ci, err := db.conn()
   412		if err != nil {
   413			return nil, err
   414		}
   415		txi, err := ci.Begin()
   416		if err != nil {
   417			db.putConn(ci, err)
   418			return nil, fmt.Errorf("sql: failed to Begin transaction: %v", err)
   419		}
   420		return &Tx{
   421			db:  db,
   422			ci:  ci,
   423			txi: txi,
   424		}, nil
   425	}
   426	
   427	// Driver returns the database's underlying driver.
   428	func (db *DB) Driver() driver.Driver {
   429		return db.driver
   430	}
   431	
   432	// Tx is an in-progress database transaction.
   433	//
   434	// A transaction must end with a call to Commit or Rollback.
   435	//
   436	// After a call to Commit or Rollback, all operations on the
   437	// transaction fail with ErrTxDone.
   438	type Tx struct {
   439		db *DB
   440	
   441		// ci is owned exclusively until Commit or Rollback, at which point
   442		// it's returned with putConn.
   443		ci  driver.Conn
   444		txi driver.Tx
   445	
   446		// cimu is held while somebody is using ci (between grabConn
   447		// and releaseConn)
   448		cimu sync.Mutex
   449	
   450		// done transitions from false to true exactly once, on Commit
   451		// or Rollback. once done, all operations fail with
   452		// ErrTxDone.
   453		done bool
   454	}
   455	
   456	var ErrTxDone = errors.New("sql: Transaction has already been committed or rolled back")
   457	
   458	func (tx *Tx) close() {
   459		if tx.done {
   460			panic("double close") // internal error
   461		}
   462		tx.done = true
   463		tx.db.putConn(tx.ci, nil)
   464		tx.ci = nil
   465		tx.txi = nil
   466	}
   467	
   468	func (tx *Tx) grabConn() (driver.Conn, error) {
   469		if tx.done {
   470			return nil, ErrTxDone
   471		}
   472		tx.cimu.Lock()
   473		return tx.ci, nil
   474	}
   475	
   476	func (tx *Tx) releaseConn() {
   477		tx.cimu.Unlock()
   478	}
   479	
   480	// Commit commits the transaction.
   481	func (tx *Tx) Commit() error {
   482		if tx.done {
   483			return ErrTxDone
   484		}
   485		defer tx.close()
   486		return tx.txi.Commit()
   487	}
   488	
   489	// Rollback aborts the transaction.
   490	func (tx *Tx) Rollback() error {
   491		if tx.done {
   492			return ErrTxDone
   493		}
   494		defer tx.close()
   495		return tx.txi.Rollback()
   496	}
   497	
   498	// Prepare creates a prepared statement for use within a transaction.
   499	//
   500	// The returned statement operates within the transaction and can no longer
   501	// be used once the transaction has been committed or rolled back.
   502	//
   503	// To use an existing prepared statement on this transaction, see Tx.Stmt.
   504	func (tx *Tx) Prepare(query string) (*Stmt, error) {
   505		// TODO(bradfitz): We could be more efficient here and either
   506		// provide a method to take an existing Stmt (created on
   507		// perhaps a different Conn), and re-create it on this Conn if
   508		// necessary. Or, better: keep a map in DB of query string to
   509		// Stmts, and have Stmt.Execute do the right thing and
   510		// re-prepare if the Conn in use doesn't have that prepared
   511		// statement.  But we'll want to avoid caching the statement
   512		// in the case where we only call conn.Prepare implicitly
   513		// (such as in db.Exec or tx.Exec), but the caller package
   514		// can't be holding a reference to the returned statement.
   515		// Perhaps just looking at the reference count (by noting
   516		// Stmt.Close) would be enough. We might also want a finalizer
   517		// on Stmt to drop the reference count.
   518		ci, err := tx.grabConn()
   519		if err != nil {
   520			return nil, err
   521		}
   522		defer tx.releaseConn()
   523	
   524		si, err := ci.Prepare(query)
   525		if err != nil {
   526			return nil, err
   527		}
   528	
   529		stmt := &Stmt{
   530			db:    tx.db,
   531			tx:    tx,
   532			txsi:  si,
   533			query: query,
   534		}
   535		return stmt, nil
   536	}
   537	
   538	// Stmt returns a transaction-specific prepared statement from
   539	// an existing statement.
   540	//
   541	// Example:
   542	//  updateMoney, err := db.Prepare("UPDATE balance SET money=money+? WHERE id=?")
   543	//  ...
   544	//  tx, err := db.Begin()
   545	//  ...
   546	//  res, err := tx.Stmt(updateMoney).Exec(123.45, 98293203)
   547	func (tx *Tx) Stmt(stmt *Stmt) *Stmt {
   548		// TODO(bradfitz): optimize this. Currently this re-prepares
   549		// each time.  This is fine for now to illustrate the API but
   550		// we should really cache already-prepared statements
   551		// per-Conn. See also the big comment in Tx.Prepare.
   552	
   553		if tx.db != stmt.db {
   554			return &Stmt{stickyErr: errors.New("sql: Tx.Stmt: statement from different database used")}
   555		}
   556		ci, err := tx.grabConn()
   557		if err != nil {
   558			return &Stmt{stickyErr: err}
   559		}
   560		defer tx.releaseConn()
   561		si, err := ci.Prepare(stmt.query)
   562		return &Stmt{
   563			db:        tx.db,
   564			tx:        tx,
   565			txsi:      si,
   566			query:     stmt.query,
   567			stickyErr: err,
   568		}
   569	}
   570	
   571	// Exec executes a query that doesn't return rows.
   572	// For example: an INSERT and UPDATE.
   573	func (tx *Tx) Exec(query string, args ...interface{}) (Result, error) {
   574		ci, err := tx.grabConn()
   575		if err != nil {
   576			return nil, err
   577		}
   578		defer tx.releaseConn()
   579	
   580		sargs, err := subsetTypeArgs(args)
   581		if err != nil {
   582			return nil, err
   583		}
   584	
   585		if execer, ok := ci.(driver.Execer); ok {
   586			resi, err := execer.Exec(query, sargs)
   587			if err == nil {
   588				return result{resi}, nil
   589			}
   590			if err != driver.ErrSkip {
   591				return nil, err
   592			}
   593		}
   594	
   595		sti, err := ci.Prepare(query)
   596		if err != nil {
   597			return nil, err
   598		}
   599		defer sti.Close()
   600	
   601		resi, err := sti.Exec(sargs)
   602		if err != nil {
   603			return nil, err
   604		}
   605		return result{resi}, nil
   606	}
   607	
   608	// Query executes a query that returns rows, typically a SELECT.
   609	func (tx *Tx) Query(query string, args ...interface{}) (*Rows, error) {
   610		if tx.done {
   611			return nil, ErrTxDone
   612		}
   613		stmt, err := tx.Prepare(query)
   614		if err != nil {
   615			return nil, err
   616		}
   617		rows, err := stmt.Query(args...)
   618		if err != nil {
   619			stmt.Close()
   620			return nil, err
   621		}
   622		rows.closeStmt = stmt
   623		return rows, err
   624	}
   625	
   626	// QueryRow executes a query that is expected to return at most one row.
   627	// QueryRow always return a non-nil value. Errors are deferred until
   628	// Row's Scan method is called.
   629	func (tx *Tx) QueryRow(query string, args ...interface{}) *Row {
   630		rows, err := tx.Query(query, args...)
   631		return &Row{rows: rows, err: err}
   632	}
   633	
   634	// connStmt is a prepared statement on a particular connection.
   635	type connStmt struct {
   636		ci driver.Conn
   637		si driver.Stmt
   638	}
   639	
   640	// Stmt is a prepared statement. Stmt is safe for concurrent use by multiple goroutines.
   641	type Stmt struct {
   642		// Immutable:
   643		db        *DB    // where we came from
   644		query     string // that created the Stmt
   645		stickyErr error  // if non-nil, this error is returned for all operations
   646	
   647		// If in a transaction, else both nil:
   648		tx   *Tx
   649		txsi driver.Stmt
   650	
   651		mu     sync.Mutex // protects the rest of the fields
   652		closed bool
   653	
   654		// css is a list of underlying driver statement interfaces
   655		// that are valid on particular connections.  This is only
   656		// used if tx == nil and one is found that has idle
   657		// connections.  If tx != nil, txsi is always used.
   658		css []connStmt
   659	}
   660	
   661	// Exec executes a prepared statement with the given arguments and
   662	// returns a Result summarizing the effect of the statement.
   663	func (s *Stmt) Exec(args ...interface{}) (Result, error) {
   664		_, releaseConn, si, err := s.connStmt()
   665		if err != nil {
   666			return nil, err
   667		}
   668		defer releaseConn(nil)
   669	
   670		// -1 means the driver doesn't know how to count the number of
   671		// placeholders, so we won't sanity check input here and instead let the
   672		// driver deal with errors.
   673		if want := si.NumInput(); want != -1 && len(args) != want {
   674			return nil, fmt.Errorf("sql: expected %d arguments, got %d", want, len(args))
   675		}
   676	
   677		sargs := make([]driver.Value, len(args))
   678	
   679		// Convert args to subset types.
   680		if cc, ok := si.(driver.ColumnConverter); ok {
   681			for n, arg := range args {
   682				// First, see if the value itself knows how to convert
   683				// itself to a driver type.  For example, a NullString
   684				// struct changing into a string or nil.
   685				if svi, ok := arg.(driver.Valuer); ok {
   686					sv, err := svi.Value()
   687					if err != nil {
   688						return nil, fmt.Errorf("sql: argument index %d from Value: %v", n, err)
   689					}
   690					if !driver.IsValue(sv) {
   691						return nil, fmt.Errorf("sql: argument index %d: non-subset type %T returned from Value", n, sv)
   692					}
   693					arg = sv
   694				}
   695	
   696				// Second, ask the column to sanity check itself. For
   697				// example, drivers might use this to make sure that
   698				// an int64 values being inserted into a 16-bit
   699				// integer field is in range (before getting
   700				// truncated), or that a nil can't go into a NOT NULL
   701				// column before going across the network to get the
   702				// same error.
   703				sargs[n], err = cc.ColumnConverter(n).ConvertValue(arg)
   704				if err != nil {
   705					return nil, fmt.Errorf("sql: converting Exec argument #%d's type: %v", n, err)
   706				}
   707				if !driver.IsValue(sargs[n]) {
   708					return nil, fmt.Errorf("sql: driver ColumnConverter error converted %T to unsupported type %T",
   709						arg, sargs[n])
   710				}
   711			}
   712		} else {
   713			for n, arg := range args {
   714				sargs[n], err = driver.DefaultParameterConverter.ConvertValue(arg)
   715				if err != nil {
   716					return nil, fmt.Errorf("sql: converting Exec argument #%d's type: %v", n, err)
   717				}
   718			}
   719		}
   720	
   721		resi, err := si.Exec(sargs)
   722		if err != nil {
   723			return nil, err
   724		}
   725		return result{resi}, nil
   726	}
   727	
   728	// connStmt returns a free driver connection on which to execute the
   729	// statement, a function to call to release the connection, and a
   730	// statement bound to that connection.
   731	func (s *Stmt) connStmt() (ci driver.Conn, releaseConn func(error), si driver.Stmt, err error) {
   732		if err = s.stickyErr; err != nil {
   733			return
   734		}
   735		s.mu.Lock()
   736		if s.closed {
   737			s.mu.Unlock()
   738			err = errors.New("sql: statement is closed")
   739			return
   740		}
   741	
   742		// In a transaction, we always use the connection that the
   743		// transaction was created on.
   744		if s.tx != nil {
   745			s.mu.Unlock()
   746			ci, err = s.tx.grabConn() // blocks, waiting for the connection.
   747			if err != nil {
   748				return
   749			}
   750			releaseConn = func(error) { s.tx.releaseConn() }
   751			return ci, releaseConn, s.txsi, nil
   752		}
   753	
   754		var cs connStmt
   755		match := false
   756		for _, v := range s.css {
   757			// TODO(bradfitz): lazily clean up entries in this
   758			// list with dead conns while enumerating
   759			if _, match = s.db.connIfFree(v.ci); match {
   760				cs = v
   761				break
   762			}
   763		}
   764		s.mu.Unlock()
   765	
   766		// Make a new conn if all are busy.
   767		// TODO(bradfitz): or wait for one? make configurable later?
   768		if !match {
   769			for i := 0; ; i++ {
   770				ci, err := s.db.conn()
   771				if err != nil {
   772					return nil, nil, nil, err
   773				}
   774				si, err := ci.Prepare(s.query)
   775				if err == driver.ErrBadConn && i < 10 {
   776					continue
   777				}
   778				if err != nil {
   779					return nil, nil, nil, err
   780				}
   781				s.mu.Lock()
   782				cs = connStmt{ci, si}
   783				s.css = append(s.css, cs)
   784				s.mu.Unlock()
   785				break
   786			}
   787		}
   788	
   789		conn := cs.ci
   790		releaseConn = func(err error) { s.db.putConn(conn, err) }
   791		return conn, releaseConn, cs.si, nil
   792	}
   793	
   794	// Query executes a prepared query statement with the given arguments
   795	// and returns the query results as a *Rows.
   796	func (s *Stmt) Query(args ...interface{}) (*Rows, error) {
   797		ci, releaseConn, si, err := s.connStmt()
   798		if err != nil {
   799			return nil, err
   800		}
   801	
   802		// -1 means the driver doesn't know how to count the number of
   803		// placeholders, so we won't sanity check input here and instead let the
   804		// driver deal with errors.
   805		if want := si.NumInput(); want != -1 && len(args) != want {
   806			return nil, fmt.Errorf("sql: statement expects %d inputs; got %d", si.NumInput(), len(args))
   807		}
   808		sargs, err := subsetTypeArgs(args)
   809		if err != nil {
   810			return nil, err
   811		}
   812		rowsi, err := si.Query(sargs)
   813		if err != nil {
   814			releaseConn(err)
   815			return nil, err
   816		}
   817		// Note: ownership of ci passes to the *Rows, to be freed
   818		// with releaseConn.
   819		rows := &Rows{
   820			db:          s.db,
   821			ci:          ci,
   822			releaseConn: releaseConn,
   823			rowsi:       rowsi,
   824		}
   825		return rows, nil
   826	}
   827	
   828	// QueryRow executes a prepared query statement with the given arguments.
   829	// If an error occurs during the execution of the statement, that error will
   830	// be returned by a call to Scan on the returned *Row, which is always non-nil.
   831	// If the query selects no rows, the *Row's Scan will return ErrNoRows.
   832	// Otherwise, the *Row's Scan scans the first selected row and discards
   833	// the rest.
   834	//
   835	// Example usage:
   836	//
   837	//  var name string
   838	//  err := nameByUseridStmt.QueryRow(id).Scan(&name)
   839	func (s *Stmt) QueryRow(args ...interface{}) *Row {
   840		rows, err := s.Query(args...)
   841		if err != nil {
   842			return &Row{err: err}
   843		}
   844		return &Row{rows: rows}
   845	}
   846	
   847	// Close closes the statement.
   848	func (s *Stmt) Close() error {
   849		if s.stickyErr != nil {
   850			return s.stickyErr
   851		}
   852		s.mu.Lock()
   853		defer s.mu.Unlock()
   854		if s.closed {
   855			return nil
   856		}
   857		s.closed = true
   858	
   859		if s.tx != nil {
   860			s.txsi.Close()
   861		} else {
   862			for _, v := range s.css {
   863				if ci, match := s.db.connIfFree(v.ci); match {
   864					v.si.Close()
   865					s.db.putConn(ci, nil)
   866				} else {
   867					// TODO(bradfitz): care that we can't close
   868					// this statement because the statement's
   869					// connection is in use?
   870				}
   871			}
   872		}
   873		return nil
   874	}
   875	
   876	// Rows is the result of a query. Its cursor starts before the first row
   877	// of the result set. Use Next to advance through the rows:
   878	//
   879	//     rows, err := db.Query("SELECT ...")
   880	//     ...
   881	//     for rows.Next() {
   882	//         var id int
   883	//         var name string
   884	//         err = rows.Scan(&id, &name)
   885	//         ...
   886	//     }
   887	//     err = rows.Err() // get any error encountered during iteration
   888	//     ...
   889	type Rows struct {
   890		db          *DB
   891		ci          driver.Conn // owned; must call putconn when closed to release
   892		releaseConn func(error)
   893		rowsi       driver.Rows
   894	
   895		closed    bool
   896		lastcols  []driver.Value
   897		lasterr   error
   898		closeStmt *Stmt // if non-nil, statement to Close on close
   899	}
   900	
   901	// Next prepares the next result row for reading with the Scan method.
   902	// It returns true on success, false if there is no next result row.
   903	// Every call to Scan, even the first one, must be preceded by a call
   904	// to Next.
   905	func (rs *Rows) Next() bool {
   906		if rs.closed {
   907			return false
   908		}
   909		if rs.lasterr != nil {
   910			return false
   911		}
   912		if rs.lastcols == nil {
   913			rs.lastcols = make([]driver.Value, len(rs.rowsi.Columns()))
   914		}
   915		rs.lasterr = rs.rowsi.Next(rs.lastcols)
   916		if rs.lasterr == io.EOF {
   917			rs.Close()
   918		}
   919		return rs.lasterr == nil
   920	}
   921	
   922	// Err returns the error, if any, that was encountered during iteration.
   923	func (rs *Rows) Err() error {
   924		if rs.lasterr == io.EOF {
   925			return nil
   926		}
   927		return rs.lasterr
   928	}
   929	
   930	// Columns returns the column names.
   931	// Columns returns an error if the rows are closed, or if the rows
   932	// are from QueryRow and there was a deferred error.
   933	func (rs *Rows) Columns() ([]string, error) {
   934		if rs.closed {
   935			return nil, errors.New("sql: Rows are closed")
   936		}
   937		if rs.rowsi == nil {
   938			return nil, errors.New("sql: no Rows available")
   939		}
   940		return rs.rowsi.Columns(), nil
   941	}
   942	
   943	// Scan copies the columns in the current row into the values pointed
   944	// at by dest.
   945	//
   946	// If an argument has type *[]byte, Scan saves in that argument a copy
   947	// of the corresponding data. The copy is owned by the caller and can
   948	// be modified and held indefinitely. The copy can be avoided by using
   949	// an argument of type *RawBytes instead; see the documentation for
   950	// RawBytes for restrictions on its use.
   951	//
   952	// If an argument has type *interface{}, Scan copies the value
   953	// provided by the underlying driver without conversion. If the value
   954	// is of type []byte, a copy is made and the caller owns the result.
   955	func (rs *Rows) Scan(dest ...interface{}) error {
   956		if rs.closed {
   957			return errors.New("sql: Rows closed")
   958		}
   959		if rs.lasterr != nil {
   960			return rs.lasterr
   961		}
   962		if rs.lastcols == nil {
   963			return errors.New("sql: Scan called without calling Next")
   964		}
   965		if len(dest) != len(rs.lastcols) {
   966			return fmt.Errorf("sql: expected %d destination arguments in Scan, not %d", len(rs.lastcols), len(dest))
   967		}
   968		for i, sv := range rs.lastcols {
   969			err := convertAssign(dest[i], sv)
   970			if err != nil {
   971				return fmt.Errorf("sql: Scan error on column index %d: %v", i, err)
   972			}
   973		}
   974		for _, dp := range dest {
   975			b, ok := dp.(*[]byte)
   976			if !ok {
   977				continue
   978			}
   979			if *b == nil {
   980				// If the []byte is now nil (for a NULL value),
   981				// don't fall through to below which would
   982				// turn it into a non-nil 0-length byte slice
   983				continue
   984			}
   985			if _, ok = dp.(*RawBytes); ok {
   986				continue
   987			}
   988			clone := make([]byte, len(*b))
   989			copy(clone, *b)
   990			*b = clone
   991		}
   992		return nil
   993	}
   994	
   995	// Close closes the Rows, preventing further enumeration. If the
   996	// end is encountered, the Rows are closed automatically. Close
   997	// is idempotent.
   998	func (rs *Rows) Close() error {
   999		if rs.closed {
  1000			return nil
  1001		}
  1002		rs.closed = true
  1003		err := rs.rowsi.Close()
  1004		rs.releaseConn(err)
  1005		if rs.closeStmt != nil {
  1006			rs.closeStmt.Close()
  1007		}
  1008		return err
  1009	}
  1010	
  1011	// Row is the result of calling QueryRow to select a single row.
  1012	type Row struct {
  1013		// One of these two will be non-nil:
  1014		err  error // deferred error for easy chaining
  1015		rows *Rows
  1016	}
  1017	
  1018	// Scan copies the columns from the matched row into the values
  1019	// pointed at by dest.  If more than one row matches the query,
  1020	// Scan uses the first row and discards the rest.  If no row matches
  1021	// the query, Scan returns ErrNoRows.
  1022	func (r *Row) Scan(dest ...interface{}) error {
  1023		if r.err != nil {
  1024			return r.err
  1025		}
  1026	
  1027		// TODO(bradfitz): for now we need to defensively clone all
  1028		// []byte that the driver returned (not permitting
  1029		// *RawBytes in Rows.Scan), since we're about to close
  1030		// the Rows in our defer, when we return from this function.
  1031		// the contract with the driver.Next(...) interface is that it
  1032		// can return slices into read-only temporary memory that's
  1033		// only valid until the next Scan/Close.  But the TODO is that
  1034		// for a lot of drivers, this copy will be unnecessary.  We
  1035		// should provide an optional interface for drivers to
  1036		// implement to say, "don't worry, the []bytes that I return
  1037		// from Next will not be modified again." (for instance, if
  1038		// they were obtained from the network anyway) But for now we
  1039		// don't care.
  1040		for _, dp := range dest {
  1041			if _, ok := dp.(*RawBytes); ok {
  1042				return errors.New("sql: RawBytes isn't allowed on Row.Scan")
  1043			}
  1044		}
  1045	
  1046		defer r.rows.Close()
  1047		if !r.rows.Next() {
  1048			return ErrNoRows
  1049		}
  1050		err := r.rows.Scan(dest...)
  1051		if err != nil {
  1052			return err
  1053		}
  1054	
  1055		return nil
  1056	}
  1057	
  1058	// A Result summarizes an executed SQL command.
  1059	type Result interface {
  1060		LastInsertId() (int64, error)
  1061		RowsAffected() (int64, error)
  1062	}
  1063	
  1064	type result struct {
  1065		driver.Result
  1066	}