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