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.
5 // Package sql provides a generic interface around SQL (or SQL-like)
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.
21 var drivers = make(map[string]driver.Driver)
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,
26 func Register(name string, driver driver.Driver) {
28 panic("sql: Register driver is nil")
30 if _, dup := drivers[name]; dup {
31 panic("sql: Register called twice for driver " + name)
33 drivers[name] = driver
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.
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:
46 // err := db.QueryRow("SELECT name FROM foo WHERE id=?", id).Scan(&s)
54 type NullString struct {
56 Valid bool // Valid is true if String is not NULL
59 // Scan implements the Scanner interface.
60 func (ns *NullString) Scan(value interface{}) error {
62 ns.String, ns.Valid = "", false
66 return convertAssign(&ns.String, value)
69 // Value implements the driver Valuer interface.
70 func (ns NullString) Value() (driver.Value, error) {
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 {
82 Valid bool // Valid is true if Int64 is not NULL
85 // Scan implements the Scanner interface.
86 func (n *NullInt64) Scan(value interface{}) error {
88 n.Int64, n.Valid = 0, false
92 return convertAssign(&n.Int64, value)
95 // Value implements the driver Valuer interface.
96 func (n NullInt64) Value() (driver.Value, error) {
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 {
108 Valid bool // Valid is true if Float64 is not NULL
111 // Scan implements the Scanner interface.
112 func (n *NullFloat64) Scan(value interface{}) error {
114 n.Float64, n.Valid = 0, false
118 return convertAssign(&n.Float64, value)
121 // Value implements the driver Valuer interface.
122 func (n NullFloat64) Value() (driver.Value, error) {
126 return n.Float64, nil
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 {
134 Valid bool // Valid is true if Bool is not NULL
137 // Scan implements the Scanner interface.
138 func (n *NullBool) Scan(value interface{}) error {
140 n.Bool, n.Valid = false, false
144 return convertAssign(&n.Bool, value)
147 // Value implements the driver Valuer interface.
148 func (n NullBool) Value() (driver.Value, error) {
155 // Scanner is an interface used by Scan.
156 type Scanner interface {
157 // Scan assigns a value from a database driver.
159 // The src value will be of one of the following restricted
168 // nil - for NULL values
170 // An error should be returned if the value can not be stored
171 // without loss of information.
172 Scan(src interface{}) error
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")
180 // DB is a database handle. It's safe for concurrent use by multiple
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.
195 mu sync.Mutex // protects following fields
196 freeConn []*driverConn
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
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,
207 type driverConn struct {
210 sync.Mutex // guards following
213 finalClosed bool // ci.Close has been called
214 openStmt map[driver.Stmt]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
222 func (dc *driverConn) removeOpenStmt(si driver.Stmt) {
225 delete(dc.openStmt, si)
228 func (dc *driverConn) prepareLocked(query string) (driver.Stmt, error) {
229 si, err := dc.ci.Prepare(query)
231 // Track each driverConn's open statements, so we can close them
232 // before closing the conn.
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.
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)
247 dc.openStmt[si] = true
252 // the dc.db's Mutex is held.
253 func (dc *driverConn) closeDBLocked() error {
257 return errors.New("sql: duplicate driverConn close")
260 dc.Unlock() // not defer; removeDep finalClose calls may need to lock
261 return dc.db.removeDepLocked(dc, dc)()
264 func (dc *driverConn) Close() error {
268 return errors.New("sql: duplicate driverConn close")
271 dc.Unlock() // not defer; removeDep finalClose calls may need to lock
273 // And now updates that require holding dc.mu.Lock.
276 fn := dc.db.removeDepLocked(dc, dc)
281 func (dc *driverConn) finalClose() error {
284 for si := range dc.openStmt {
291 dc.finalClosed = true
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
305 func (ds *driverStmt) Close() error {
311 // depSet is a finalCloser's outstanding dependencies
312 type depSet map[interface{}]bool // set of true bools
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.
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))
328 db.addDepLocked(x, dep)
331 func (db *DB) addDepLocked(x finalCloser, dep interface{}) {
333 db.dep = make(map[finalCloser]depSet)
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 {
349 fn := db.removeDepLocked(x, dep)
354 func (db *DB) removeDepLocked(x finalCloser, dep interface{}) func() error {
355 //println(fmt.Sprintf("removeDep(%T %p, %T %p)", x, x, dep, dep))
368 return func() error { return nil }
370 return func() error {
371 //println(fmt.Sprintf("calling final close on %T %v (%#v)", x, x, x))
372 return x.finalClose()
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.
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.
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
388 func Open(driverName, dataSourceName string) (*DB, error) {
389 driveri, ok := drivers[driverName]
391 return nil, fmt.Errorf("sql: unknown driver %q (forgotten import?)", driverName)
396 lastPut: make(map[*driverConn]string),
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
415 // Close closes the database, releasing any open resources.
416 func (db *DB) Close() error {
420 for _, dc := range db.freeConn {
421 err1 := dc.closeDBLocked()
431 const defaultMaxIdleConns = 2
433 func (db *DB) maxIdleConnsLocked() int {
437 // TODO(bradfitz): ask driver, if supported, for its default preference
438 return defaultMaxIdleConns
446 // SetMaxIdleConns sets the maximum number of connections in the idle
449 // If n <= 0, no idle connections are retained.
450 func (db *DB) SetMaxIdleConns(n int) {
456 // No idle connections.
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]
468 // conn returns a newly-opened or cached *driverConn
469 func (db *DB) conn() (*driverConn, error) {
473 return nil, errors.New("sql: database is closed")
475 if n := len(db.freeConn); n > 0 {
476 conn := db.freeConn[n-1]
477 db.freeConn = db.freeConn[:n-1]
484 ci, err := db.driver.Open(db.dsn)
493 db.addDepLocked(dc, dc)
500 errConnClosed = errors.New("database/sql: internal sentinel error: conn is closed")
501 errConnBusy = errors.New("database/sql: internal sentinel error: conn is busy")
504 // connIfFree returns (wanted, nil) if wanted is still a valid conn and
507 // The error is errConnClosed if the connection if the requested connection
508 // is invalid because it's been closed.
510 // The error is errConnBusy if the connection is in use.
511 func (db *DB) connIfFree(wanted *driverConn) (*driverConn, error) {
515 return nil, errConnBusy
517 if wanted.dbmuClosed {
518 return nil, errConnClosed
520 for i, conn := range db.freeConn {
524 db.freeConn[i] = db.freeConn[len(db.freeConn)-1]
525 db.freeConn = db.freeConn[:len(db.freeConn)-1]
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
533 // Instead, treat it like a busy connection:
534 return nil, errConnBusy
537 // putConnHook is a hook for testing.
538 var putConnHook func(*DB, *driverConn)
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
543 func (db *DB) noteUnusedDriverStatement(c *driverConn, si driver.Stmt) {
547 c.onPut = append(c.onPut, func() {
559 // debugGetPut determines whether getConn & putConn calls' stack traces
560 // are returned for more verbose crashes.
561 const debugGetPut = false
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) {
569 fmt.Printf("putConn(%v) DUPLICATE was: %s\n\nPREVIOUS was: %s", dc, stack(), db.lastPut[dc])
571 panic("sql: connection returned that was never out")
574 db.lastPut[dc] = stack()
578 for _, fn := range dc.onPut {
583 if err == driver.ErrBadConn {
584 // Don't reuse bad connections.
588 if putConnHook != nil {
591 if n := len(db.freeConn); !db.closed && n < db.maxIdleConnsLocked() {
592 db.freeConn = append(db.freeConn, dc)
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) {
607 for i := 0; i < 10; i++ {
608 stmt, err = db.prepare(query)
609 if err != driver.ErrBadConn {
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.
628 si, err := dc.prepareLocked(query)
637 css: []connStmt{{dc, si}},
639 db.addDep(stmt, stmt)
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) {
649 for i := 0; i < 10; i++ {
650 res, err = db.exec(query, args)
651 if err != driver.ErrBadConn {
658 func (db *DB) exec(query string, args []interface{}) (res Result, err error) {
667 if execer, ok := dc.ci.(driver.Execer); ok {
668 dargs, err := driverArgs(nil, args)
673 resi, err := execer.Exec(query, dargs)
675 if err != driver.ErrSkip {
679 return driverResult{dc, resi}, nil
684 si, err := dc.ci.Prepare(query)
689 defer withLock(dc, func() { si.Close() })
690 return resultFromStatement(driverStmt{dc, si}, args...)
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) {
698 for i := 0; i < 10; i++ {
699 rows, err = db.query(query, args)
700 if err != driver.ErrBadConn {
707 func (db *DB) query(query string, args []interface{}) (*Rows, error) {
713 releaseConn := func(err error) { db.putConn(ci, err) }
715 return db.queryConn(ci, releaseConn, query, args)
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)
728 rowsi, err := queryer.Query(query, dargs)
730 if err != driver.ErrSkip {
735 // Note: ownership of dc passes to the *Rows, to be freed
739 releaseConn: releaseConn,
747 si, err := dc.ci.Prepare(query)
754 ds := driverStmt{dc, si}
755 rowsi, err := rowsiFromStatement(ds, args...)
764 // Note: ownership of ci passes to the *Rows, to be freed
768 releaseConn: releaseConn,
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}
783 // Begin starts a transaction. The isolation level is dependent on
785 func (db *DB) Begin() (*Tx, error) {
788 for i := 0; i < 10; i++ {
790 if err != driver.ErrBadConn {
797 func (db *DB) begin() (tx *Tx, err error) {
803 txi, err := dc.ci.Begin()
816 // Driver returns the database's underlying driver.
817 func (db *DB) Driver() driver.Driver {
821 // Tx is an in-progress database transaction.
823 // A transaction must end with a call to Commit or Rollback.
825 // After a call to Commit or Rollback, all operations on the
826 // transaction fail with ErrTxDone.
830 // dc is owned exclusively until Commit or Rollback, at which point
831 // it's returned with putConn.
835 // done transitions from false to true exactly once, on Commit
836 // or Rollback. once done, all operations fail with
841 var ErrTxDone = errors.New("sql: Transaction has already been committed or rolled back")
843 func (tx *Tx) close() {
845 panic("double close") // internal error
848 tx.db.putConn(tx.dc, nil)
853 func (tx *Tx) grabConn() (*driverConn, error) {
855 return nil, ErrTxDone
860 // Commit commits the transaction.
861 func (tx *Tx) Commit() error {
868 return tx.txi.Commit()
871 // Rollback aborts the transaction.
872 func (tx *Tx) Rollback() error {
879 return tx.txi.Rollback()
882 // Prepare creates a prepared statement for use within a transaction.
884 // The returned statement operates within the transaction and can no longer
885 // be used once the transaction has been committed or rolled back.
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()
908 si, err := dc.ci.Prepare(query)
926 // Stmt returns a transaction-specific prepared statement from
927 // an existing statement.
930 // updateMoney, err := db.Prepare("UPDATE balance SET money=money+? WHERE id=?")
932 // tx, err := db.Begin()
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.
941 if tx.db != stmt.db {
942 return &Stmt{stickyErr: errors.New("sql: Tx.Stmt: statement from different database used")}
944 dc, err := tx.grabConn()
946 return &Stmt{stickyErr: err}
949 si, err := dc.ci.Prepare(stmt.query)
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()
971 if execer, ok := dc.ci.(driver.Execer); ok {
972 dargs, err := driverArgs(nil, args)
977 resi, err := execer.Exec(query, dargs)
980 return driverResult{dc, resi}, nil
982 if err != driver.ErrSkip {
988 si, err := dc.ci.Prepare(query)
993 defer withLock(dc, func() { si.Close() })
995 return resultFromStatement(driverStmt{dc, si}, args...)
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()
1004 releaseConn := func(error) {}
1005 return tx.db.queryConn(dc, releaseConn, query, args)
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}
1016 // connStmt is a prepared statement on a particular connection.
1017 type connStmt struct {
1022 // Stmt is a prepared statement. Stmt is safe for concurrent use by multiple goroutines.
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
1029 closemu sync.RWMutex // held exclusively during close, for read otherwise.
1031 // If in a transaction, else both nil:
1035 mu sync.Mutex // protects the rest of the fields
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.
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) {
1049 defer s.closemu.RUnlock()
1050 dc, releaseConn, si, err := s.connStmt()
1054 defer releaseConn(nil)
1056 return resultFromStatement(driverStmt{dc, si}, args...)
1059 func resultFromStatement(ds driverStmt, args ...interface{}) (Result, error) {
1061 want := ds.si.NumInput()
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))
1071 dargs, err := driverArgs(&ds, args)
1077 resi, err := ds.si.Exec(dargs)
1082 return driverResult{ds.Locker, resi}, nil
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 {
1095 err = errors.New("sql: statement is closed")
1099 // In a transaction, we always use the connection that the
1100 // transaction was created on.
1103 ci, err = s.tx.grabConn() // blocks, waiting for the connection.
1107 releaseConn = func(error) {}
1108 return ci, releaseConn, s.txsi.si, nil
1113 for i := 0; i < len(s.css); i++ {
1115 _, err := s.db.connIfFree(v.dc)
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]
1131 // Make a new conn if all are busy.
1132 // TODO(bradfitz): or wait for one? make configurable later?
1135 dc, err := s.db.conn()
1137 return nil, nil, nil, err
1140 si, err := dc.prepareLocked(s.query)
1142 if err == driver.ErrBadConn && i < 10 {
1146 return nil, nil, nil, err
1149 cs = connStmt{dc, si}
1150 s.css = append(s.css, cs)
1157 releaseConn = func(err error) { s.db.putConn(conn, err) }
1158 return conn, releaseConn, cs.si, nil
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) {
1165 defer s.closemu.RUnlock()
1167 dc, releaseConn, si, err := s.connStmt()
1172 ds := driverStmt{dc, si}
1173 rowsi, err := rowsiFromStatement(ds, args...)
1179 // Note: ownership of ci passes to the *Rows, to be freed
1180 // with releaseConn.
1184 // releaseConn set below
1186 s.db.addDep(s, rows)
1187 rows.releaseConn = func(err error) {
1189 s.db.removeDep(s, rows)
1194 func rowsiFromStatement(ds driverStmt, args ...interface{}) (driver.Rows, error) {
1196 want := ds.si.NumInput()
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))
1206 dargs, err := driverArgs(&ds, args)
1212 rowsi, err := ds.si.Query(dargs)
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
1230 // err := nameByUseridStmt.QueryRow(id).Scan(&name)
1231 func (s *Stmt) QueryRow(args ...interface{}) *Row {
1232 rows, err := s.Query(args...)
1234 return &Row{err: err}
1236 return &Row{rows: rows}
1239 // Close closes the statement.
1240 func (s *Stmt) Close() error {
1242 defer s.closemu.Unlock()
1244 if s.stickyErr != nil {
1259 return s.db.removeDep(s, s)
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)
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:
1275 // rows, err := db.Query("SELECT ...")
1277 // for rows.Next() {
1280 // err = rows.Scan(&id, &name)
1283 // err = rows.Err() // get any error encountered during iteration
1286 dc *driverConn // owned; must call releaseConn when closed to release
1287 releaseConn func(error)
1291 lastcols []driver.Value
1293 closeStmt driver.Stmt // if non-nil, statement to Close on close
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
1300 func (rs *Rows) Next() bool {
1304 if rs.lasterr != nil {
1307 if rs.lastcols == nil {
1308 rs.lastcols = make([]driver.Value, len(rs.rowsi.Columns()))
1310 rs.lasterr = rs.rowsi.Next(rs.lastcols)
1311 if rs.lasterr == io.EOF {
1314 return rs.lasterr == nil
1317 // Err returns the error, if any, that was encountered during iteration.
1318 func (rs *Rows) Err() error {
1319 if rs.lasterr == io.EOF {
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) {
1330 return nil, errors.New("sql: Rows are closed")
1332 if rs.rowsi == nil {
1333 return nil, errors.New("sql: no Rows available")
1335 return rs.rowsi.Columns(), nil
1338 // Scan copies the columns in the current row into the values pointed
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.
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 {
1352 return errors.New("sql: Rows closed")
1354 if rs.lasterr != nil {
1357 if rs.lastcols == nil {
1358 return errors.New("sql: Scan called without calling Next")
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))
1363 for i, sv := range rs.lastcols {
1364 err := convertAssign(dest[i], sv)
1366 return fmt.Errorf("sql: Scan error on column index %d: %v", i, err)
1372 // Close closes the Rows, preventing further enumeration. If the
1373 // end is encountered, the Rows are closed automatically. Close
1375 func (rs *Rows) Close() error {
1380 err := rs.rowsi.Close()
1381 if rs.closeStmt != nil {
1382 rs.closeStmt.Close()
1388 // Row is the result of calling QueryRow to select a single row.
1390 // One of these two will be non-nil:
1391 err error // deferred error for easy chaining
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 {
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
1417 for _, dp := range dest {
1418 if _, ok := dp.(*RawBytes); ok {
1419 return errors.New("sql: RawBytes isn't allowed on Row.Scan")
1423 defer r.rows.Close()
1427 err := r.rows.Scan(dest...)
1435 // A Result summarizes an executed SQL command.
1436 type Result interface {
1437 LastInsertId() (int64, error)
1438 RowsAffected() (int64, error)
1441 type driverResult struct {
1442 sync.Locker // the *driverConn
1446 func (dr driverResult) LastInsertId() (int64, error) {
1449 return dr.resi.LastInsertId()
1452 func (dr driverResult) RowsAffected() (int64, error) {
1455 return dr.resi.RowsAffected()
1458 func stack() string {
1459 var buf [2 << 10]byte
1460 return string(buf[:runtime.Stack(buf[:], false)])
1463 // withLock runs while holding lk.
1464 func withLock(lk sync.Locker, fn func()) {