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 https://golang.org/s/sqldrivers for a list of drivers.
11 // Drivers that do not support context cancelation will not return until
12 // after the query is completed.
14 // For usage examples, see the wiki page at
15 // https://golang.org/s/sqlwiki.
33 driversMu sync
.RWMutex
34 drivers
= make(map[string]driver
.Driver
)
37 // nowFunc returns the current time; it's overridden in tests.
38 var nowFunc
= time
.Now
40 // Register makes a database driver available by the provided name.
41 // If Register is called twice with the same name or if driver is nil,
43 func Register(name
string, driver driver
.Driver
) {
45 defer driversMu
.Unlock()
47 panic("sql: Register driver is nil")
49 if _
, dup
:= drivers
[name
]; dup
{
50 panic("sql: Register called twice for driver " + name
)
52 drivers
[name
] = driver
55 func unregisterAllDrivers() {
57 defer driversMu
.Unlock()
59 drivers
= make(map[string]driver
.Driver
)
62 // Drivers returns a sorted list of the names of the registered drivers.
63 func Drivers() []string {
65 defer driversMu
.RUnlock()
67 for name
:= range drivers
{
68 list
= append(list
, name
)
74 // A NamedArg is a named argument. NamedArg values may be used as
75 // arguments to Query or Exec and bind to the corresponding named
76 // parameter in the SQL statement.
78 // For a more concise way to create NamedArg values, see
79 // the Named function.
80 type NamedArg
struct {
81 _Named_Fields_Required
struct{}
83 // Name is the name of the parameter placeholder.
85 // If empty, the ordinal position in the argument list will be
88 // Name must omit any symbol prefix.
91 // Value is the value of the parameter.
92 // It may be assigned the same value types as the query
97 // Named provides a more concise way to create NamedArg values.
101 // db.ExecContext(ctx, `
102 // delete from Invoice
104 // TimeCreated < @end
105 // and TimeCreated >= @start;`,
106 // sql.Named("start", startTime),
107 // sql.Named("end", endTime),
109 func Named(name
string, value
interface{}) NamedArg
{
110 // This method exists because the go1compat promise
111 // doesn't guarantee that structs don't grow more fields,
112 // so unkeyed struct literals are a vet error. Thus, we don't
113 // want to allow sql.NamedArg{name, value}.
114 return NamedArg
{Name
: name
, Value
: value
}
117 // IsolationLevel is the transaction isolation level used in TxOptions.
118 type IsolationLevel
int
120 // Various isolation levels that drivers may support in BeginTx.
121 // If a driver does not support a given isolation level an error may be returned.
123 // See https://en.wikipedia.org/wiki/Isolation_(database_systems)#Isolation_levels.
125 LevelDefault IsolationLevel
= iota
135 // TxOptions holds the transaction options to be used in DB.BeginTx.
136 type TxOptions
struct {
137 // Isolation is the transaction isolation level.
138 // If zero, the driver or database's default level is used.
139 Isolation IsolationLevel
143 // RawBytes is a byte slice that holds a reference to memory owned by
144 // the database itself. After a Scan into a RawBytes, the slice is only
145 // valid until the next call to Next, Scan, or Close.
148 // NullString represents a string that may be null.
149 // NullString implements the Scanner interface so
150 // it can be used as a scan destination:
153 // err := db.QueryRow("SELECT name FROM foo WHERE id=?", id).Scan(&s)
161 type NullString
struct {
163 Valid
bool // Valid is true if String is not NULL
166 // Scan implements the Scanner interface.
167 func (ns
*NullString
) Scan(value
interface{}) error
{
169 ns
.String
, ns
.Valid
= "", false
173 return convertAssign(&ns
.String
, value
)
176 // Value implements the driver Valuer interface.
177 func (ns NullString
) Value() (driver
.Value
, error
) {
181 return ns
.String
, nil
184 // NullInt64 represents an int64 that may be null.
185 // NullInt64 implements the Scanner interface so
186 // it can be used as a scan destination, similar to NullString.
187 type NullInt64
struct {
189 Valid
bool // Valid is true if Int64 is not NULL
192 // Scan implements the Scanner interface.
193 func (n
*NullInt64
) Scan(value
interface{}) error
{
195 n
.Int64
, n
.Valid
= 0, false
199 return convertAssign(&n
.Int64
, value
)
202 // Value implements the driver Valuer interface.
203 func (n NullInt64
) Value() (driver
.Value
, error
) {
210 // NullFloat64 represents a float64 that may be null.
211 // NullFloat64 implements the Scanner interface so
212 // it can be used as a scan destination, similar to NullString.
213 type NullFloat64
struct {
215 Valid
bool // Valid is true if Float64 is not NULL
218 // Scan implements the Scanner interface.
219 func (n
*NullFloat64
) Scan(value
interface{}) error
{
221 n
.Float64
, n
.Valid
= 0, false
225 return convertAssign(&n
.Float64
, value
)
228 // Value implements the driver Valuer interface.
229 func (n NullFloat64
) Value() (driver
.Value
, error
) {
233 return n
.Float64
, nil
236 // NullBool represents a bool that may be null.
237 // NullBool implements the Scanner interface so
238 // it can be used as a scan destination, similar to NullString.
239 type NullBool
struct {
241 Valid
bool // Valid is true if Bool is not NULL
244 // Scan implements the Scanner interface.
245 func (n
*NullBool
) Scan(value
interface{}) error
{
247 n
.Bool
, n
.Valid
= false, false
251 return convertAssign(&n
.Bool
, value
)
254 // Value implements the driver Valuer interface.
255 func (n NullBool
) Value() (driver
.Value
, error
) {
262 // Scanner is an interface used by Scan.
263 type Scanner
interface {
264 // Scan assigns a value from a database driver.
266 // The src value will be of one of the following types:
274 // nil - for NULL values
276 // An error should be returned if the value cannot be stored
277 // without loss of information.
278 Scan(src
interface{}) error
281 // ErrNoRows is returned by Scan when QueryRow doesn't return a
282 // row. In such a case, QueryRow returns a placeholder *Row value that
283 // defers this error until a Scan.
284 var ErrNoRows
= errors
.New("sql: no rows in result set")
286 // DB is a database handle representing a pool of zero or more
287 // underlying connections. It's safe for concurrent use by multiple
290 // The sql package creates and frees connections automatically; it
291 // also maintains a free pool of idle connections. If the database has
292 // a concept of per-connection state, such state can only be reliably
293 // observed within a transaction. Once DB.Begin is called, the
294 // returned Tx is bound to a single connection. Once Commit or
295 // Rollback is called on the transaction, that transaction's
296 // connection is returned to DB's idle connection pool. The pool size
297 // can be controlled with SetMaxIdleConns.
301 // numClosed is an atomic counter which represents a total number of
302 // closed connections. Stmt.openStmt checks it before cleaning closed
303 // connections in Stmt.css.
306 mu sync
.Mutex
// protects following fields
307 freeConn
[]*driverConn
308 connRequests
map[uint64]chan connRequest
309 nextRequest
uint64 // Next key to use in connRequests.
310 numOpen
int // number of opened and pending open connections
311 // Used to signal the need for new connections
312 // a goroutine running connectionOpener() reads on this chan and
313 // maybeOpenNewConnections sends on the chan (one send per needed connection)
314 // It is closed during db.Close(). The close tells the connectionOpener
315 // goroutine to exit.
316 openerCh
chan struct{}
318 dep
map[finalCloser
]depSet
319 lastPut
map[*driverConn
]string // stacktrace of last conn's put; debug only
320 maxIdle
int // zero means defaultMaxIdleConns; negative means 0
321 maxOpen
int // <= 0 means unlimited
322 maxLifetime time
.Duration
// maximum amount of time a connection may be reused
323 cleanerCh
chan struct{}
326 // connReuseStrategy determines how (*DB).conn returns database connections.
327 type connReuseStrategy
uint8
330 // alwaysNewConn forces a new connection to the database.
331 alwaysNewConn connReuseStrategy
= iota
332 // cachedOrNewConn returns a cached connection, if available, else waits
333 // for one to become available (if MaxOpenConns has been reached) or
334 // creates a new database connection.
338 // driverConn wraps a driver.Conn with a mutex, to
339 // be held during all calls into the Conn. (including any calls onto
340 // interfaces returned via that Conn, such as calls on Tx, Stmt,
342 type driverConn
struct {
346 sync
.Mutex
// guards following
349 finalClosed
bool // ci.Close has been called
350 openStmt
map[*driverStmt
]bool
354 onPut
[]func() // code (with db.mu held) run when conn is next returned
355 dbmuClosed
bool // same as closed, but guarded by db.mu, for removeClosedStmtLocked
358 func (dc
*driverConn
) releaseConn(err error
) {
359 dc
.db
.putConn(dc
, err
)
362 func (dc
*driverConn
) removeOpenStmt(ds
*driverStmt
) {
365 delete(dc
.openStmt
, ds
)
368 func (dc
*driverConn
) expired(timeout time
.Duration
) bool {
372 return dc
.createdAt
.Add(timeout
).Before(nowFunc())
375 func (dc
*driverConn
) prepareLocked(ctx context
.Context
, query
string) (*driverStmt
, error
) {
376 si
, err
:= ctxDriverPrepare(ctx
, dc
.ci
, query
)
381 // Track each driverConn's open statements, so we can close them
382 // before closing the conn.
384 // Wrap all driver.Stmt is *driverStmt to ensure they are only closed once.
385 if dc
.openStmt
== nil {
386 dc
.openStmt
= make(map[*driverStmt
]bool)
388 ds
:= &driverStmt
{Locker
: dc
, si
: si
}
389 dc
.openStmt
[ds
] = true
394 // the dc.db's Mutex is held.
395 func (dc
*driverConn
) closeDBLocked() func() error
{
399 return func() error
{ return errors
.New("sql: duplicate driverConn close") }
402 return dc
.db
.removeDepLocked(dc
, dc
)
405 func (dc
*driverConn
) Close() error
{
409 return errors
.New("sql: duplicate driverConn close")
412 dc
.Unlock() // not defer; removeDep finalClose calls may need to lock
414 // And now updates that require holding dc.mu.Lock.
417 fn
:= dc
.db
.removeDepLocked(dc
, dc
)
422 func (dc
*driverConn
) finalClose() error
{
425 // Each *driverStmt has a lock to the dc. Copy the list out of the dc
426 // before calling close on each stmt.
427 var openStmt
[]*driverStmt
428 withLock(dc
, func() {
429 openStmt
= make([]*driverStmt
, 0, len(dc
.openStmt
))
430 for ds
:= range dc
.openStmt
{
431 openStmt
= append(openStmt
, ds
)
435 for _
, ds
:= range openStmt
{
438 withLock(dc
, func() {
439 dc
.finalClosed
= true
446 dc
.db
.maybeOpenNewConnections()
449 atomic
.AddUint64(&dc
.db
.numClosed
, 1)
453 // driverStmt associates a driver.Stmt with the
454 // *driverConn from which it came, so the driverConn's lock can be
455 // held during calls.
456 type driverStmt
struct {
457 sync
.Locker
// the *driverConn
460 closeErr error
// return value of previous Close call
463 // Close ensures dirver.Stmt is only closed once any always returns the same
465 func (ds
*driverStmt
) Close() error
{
472 ds
.closeErr
= ds
.si
.Close()
476 // depSet is a finalCloser's outstanding dependencies
477 type depSet
map[interface{}]bool // set of true bools
479 // The finalCloser interface is used by (*DB).addDep and related
480 // dependency reference counting.
481 type finalCloser
interface {
482 // finalClose is called when the reference count of an object
483 // goes to zero. (*DB).mu is not held while calling it.
487 // addDep notes that x now depends on dep, and x's finalClose won't be
488 // called until all of x's dependencies are removed with removeDep.
489 func (db
*DB
) addDep(x finalCloser
, dep
interface{}) {
490 //println(fmt.Sprintf("addDep(%T %p, %T %p)", x, x, dep, dep))
493 db
.addDepLocked(x
, dep
)
496 func (db
*DB
) addDepLocked(x finalCloser
, dep
interface{}) {
498 db
.dep
= make(map[finalCloser
]depSet
)
508 // removeDep notes that x no longer depends on dep.
509 // If x still has dependencies, nil is returned.
510 // If x no longer has any dependencies, its finalClose method will be
511 // called and its error value will be returned.
512 func (db
*DB
) removeDep(x finalCloser
, dep
interface{}) error
{
514 fn
:= db
.removeDepLocked(x
, dep
)
519 func (db
*DB
) removeDepLocked(x finalCloser
, dep
interface{}) func() error
{
520 //println(fmt.Sprintf("removeDep(%T %p, %T %p)", x, x, dep, dep))
522 xdep
, ok
:= db
.dep
[x
]
524 panic(fmt
.Sprintf("unpaired removeDep: no deps for %T", x
))
532 // Nothing removed. Shouldn't happen.
533 panic(fmt
.Sprintf("unpaired removeDep: no %T dep on %T", dep
, x
))
535 // No more dependencies.
539 // Dependencies remain.
540 return func() error
{ return nil }
544 // This is the size of the connectionOpener request chan (DB.openerCh).
545 // This value should be larger than the maximum typical value
546 // used for db.maxOpen. If maxOpen is significantly larger than
547 // connectionRequestQueueSize then it is possible for ALL calls into the *DB
548 // to block until the connectionOpener can satisfy the backlog of requests.
549 var connectionRequestQueueSize
= 1000000
551 // Open opens a database specified by its database driver name and a
552 // driver-specific data source name, usually consisting of at least a
553 // database name and connection information.
555 // Most users will open a database via a driver-specific connection
556 // helper function that returns a *DB. No database drivers are included
557 // in the Go standard library. See https://golang.org/s/sqldrivers for
558 // a list of third-party drivers.
560 // Open may just validate its arguments without creating a connection
561 // to the database. To verify that the data source name is valid, call
564 // The returned DB is safe for concurrent use by multiple goroutines
565 // and maintains its own pool of idle connections. Thus, the Open
566 // function should be called just once. It is rarely necessary to
568 func Open(driverName
, dataSourceName
string) (*DB
, error
) {
570 driveri
, ok
:= drivers
[driverName
]
573 return nil, fmt
.Errorf("sql: unknown driver %q (forgotten import?)", driverName
)
578 openerCh
: make(chan struct{}, connectionRequestQueueSize
),
579 lastPut
: make(map[*driverConn
]string),
580 connRequests
: make(map[uint64]chan connRequest
),
582 go db
.connectionOpener()
586 // PingContext verifies a connection to the database is still alive,
587 // establishing a connection if necessary.
588 func (db
*DB
) PingContext(ctx context
.Context
) error
{
592 for i
:= 0; i
< maxBadConnRetries
; i
++ {
593 dc
, err
= db
.conn(ctx
, cachedOrNewConn
)
594 if err
!= driver
.ErrBadConn
{
598 if err
== driver
.ErrBadConn
{
599 dc
, err
= db
.conn(ctx
, alwaysNewConn
)
605 if pinger
, ok
:= dc
.ci
.(driver
.Pinger
); ok
{
606 err
= pinger
.Ping(ctx
)
612 // Ping verifies a connection to the database is still alive,
613 // establishing a connection if necessary.
614 func (db
*DB
) Ping() error
{
615 return db
.PingContext(context
.Background())
618 // Close closes the database, releasing any open resources.
620 // It is rare to Close a DB, as the DB handle is meant to be
621 // long-lived and shared between many goroutines.
622 func (db
*DB
) Close() error
{
624 if db
.closed { // Make DB.Close idempotent
629 if db
.cleanerCh
!= nil {
633 fns
:= make([]func() error
, 0, len(db
.freeConn
))
634 for _
, dc
:= range db
.freeConn
{
635 fns
= append(fns
, dc
.closeDBLocked())
639 for _
, req
:= range db
.connRequests
{
643 for _
, fn
:= range fns
{
652 const defaultMaxIdleConns
= 2
654 func (db
*DB
) maxIdleConnsLocked() int {
658 // TODO(bradfitz): ask driver, if supported, for its default preference
659 return defaultMaxIdleConns
667 // SetMaxIdleConns sets the maximum number of connections in the idle
670 // If MaxOpenConns is greater than 0 but less than the new MaxIdleConns
671 // then the new MaxIdleConns will be reduced to match the MaxOpenConns limit
673 // If n <= 0, no idle connections are retained.
674 func (db
*DB
) SetMaxIdleConns(n
int) {
679 // No idle connections.
682 // Make sure maxIdle doesn't exceed maxOpen
683 if db
.maxOpen
> 0 && db
.maxIdleConnsLocked() > db
.maxOpen
{
684 db
.maxIdle
= db
.maxOpen
686 var closing
[]*driverConn
687 idleCount
:= len(db
.freeConn
)
688 maxIdle
:= db
.maxIdleConnsLocked()
689 if idleCount
> maxIdle
{
690 closing
= db
.freeConn
[maxIdle
:]
691 db
.freeConn
= db
.freeConn
[:maxIdle
]
694 for _
, c
:= range closing
{
699 // SetMaxOpenConns sets the maximum number of open connections to the database.
701 // If MaxIdleConns is greater than 0 and the new MaxOpenConns is less than
702 // MaxIdleConns, then MaxIdleConns will be reduced to match the new
703 // MaxOpenConns limit
705 // If n <= 0, then there is no limit on the number of open connections.
706 // The default is 0 (unlimited).
707 func (db
*DB
) SetMaxOpenConns(n
int) {
713 syncMaxIdle
:= db
.maxOpen
> 0 && db
.maxIdleConnsLocked() > db
.maxOpen
716 db
.SetMaxIdleConns(n
)
720 // SetConnMaxLifetime sets the maximum amount of time a connection may be reused.
722 // Expired connections may be closed lazily before reuse.
724 // If d <= 0, connections are reused forever.
725 func (db
*DB
) SetConnMaxLifetime(d time
.Duration
) {
730 // wake cleaner up when lifetime is shortened.
731 if d
> 0 && d
< db
.maxLifetime
&& db
.cleanerCh
!= nil {
733 case db
.cleanerCh
<- struct{}{}:
738 db
.startCleanerLocked()
742 // startCleanerLocked starts connectionCleaner if needed.
743 func (db
*DB
) startCleanerLocked() {
744 if db
.maxLifetime
> 0 && db
.numOpen
> 0 && db
.cleanerCh
== nil {
745 db
.cleanerCh
= make(chan struct{}, 1)
746 go db
.connectionCleaner(db
.maxLifetime
)
750 func (db
*DB
) connectionCleaner(d time
.Duration
) {
751 const minInterval
= time
.Second
756 t
:= time
.NewTimer(d
)
761 case <-db
.cleanerCh
: // maxLifetime was changed or db was closed.
766 if db
.closed || db
.numOpen
== 0 || d
<= 0 {
772 expiredSince
:= nowFunc().Add(-d
)
773 var closing
[]*driverConn
774 for i
:= 0; i
< len(db
.freeConn
); i
++ {
776 if c
.createdAt
.Before(expiredSince
) {
777 closing
= append(closing
, c
)
778 last
:= len(db
.freeConn
) - 1
779 db
.freeConn
[i
] = db
.freeConn
[last
]
780 db
.freeConn
[last
] = nil
781 db
.freeConn
= db
.freeConn
[:last
]
787 for _
, c
:= range closing
{
798 // DBStats contains database statistics.
799 type DBStats
struct {
800 // OpenConnections is the number of open connections to the database.
804 // Stats returns database statistics.
805 func (db
*DB
) Stats() DBStats
{
808 OpenConnections
: db
.numOpen
,
814 // Assumes db.mu is locked.
815 // If there are connRequests and the connection limit hasn't been reached,
816 // then tell the connectionOpener to open new connections.
817 func (db
*DB
) maybeOpenNewConnections() {
818 numRequests
:= len(db
.connRequests
)
820 numCanOpen
:= db
.maxOpen
- db
.numOpen
821 if numRequests
> numCanOpen
{
822 numRequests
= numCanOpen
825 for numRequests
> 0 {
826 db
.numOpen
++ // optimistically
831 db
.openerCh
<- struct{}{}
835 // Runs in a separate goroutine, opens new connections when requested.
836 func (db
*DB
) connectionOpener() {
837 for range db
.openerCh
{
838 db
.openNewConnection()
842 // Open one new connection
843 func (db
*DB
) openNewConnection() {
844 // maybeOpenNewConnctions has already executed db.numOpen++ before it sent
845 // on db.openerCh. This function must execute db.numOpen-- if the
846 // connection fails or is closed before returning.
847 ci
, err
:= db
.driver
.Open(db
.dsn
)
859 db
.putConnDBLocked(nil, err
)
860 db
.maybeOpenNewConnections()
865 createdAt
: nowFunc(),
868 if db
.putConnDBLocked(dc
, err
) {
869 db
.addDepLocked(dc
, dc
)
876 // connRequest represents one request for a new connection
877 // When there are no idle connections available, DB.conn will create
878 // a new connRequest and put it on the db.connRequests list.
879 type connRequest
struct {
884 var errDBClosed
= errors
.New("sql: database is closed")
886 // nextRequestKeyLocked returns the next connection request key.
887 // It is assumed that nextRequest will not overflow.
888 func (db
*DB
) nextRequestKeyLocked() uint64 {
889 next
:= db
.nextRequest
894 // conn returns a newly-opened or cached *driverConn.
895 func (db
*DB
) conn(ctx context
.Context
, strategy connReuseStrategy
) (*driverConn
, error
) {
899 return nil, errDBClosed
901 // Check if the context is expired.
906 return nil, ctx
.Err()
908 lifetime
:= db
.maxLifetime
910 // Prefer a free connection, if possible.
911 numFree
:= len(db
.freeConn
)
912 if strategy
== cachedOrNewConn
&& numFree
> 0 {
913 conn
:= db
.freeConn
[0]
914 copy(db
.freeConn
, db
.freeConn
[1:])
915 db
.freeConn
= db
.freeConn
[:numFree
-1]
918 if conn
.expired(lifetime
) {
920 return nil, driver
.ErrBadConn
925 // Out of free connections or we were asked not to use one. If we're not
926 // allowed to open any more connections, make a request and wait.
927 if db
.maxOpen
> 0 && db
.numOpen
>= db
.maxOpen
{
928 // Make the connRequest channel. It's buffered so that the
929 // connectionOpener doesn't block while waiting for the req to be read.
930 req
:= make(chan connRequest
, 1)
931 reqKey
:= db
.nextRequestKeyLocked()
932 db
.connRequests
[reqKey
] = req
935 // Timeout the connection request with the context.
938 // Remove the connection request and ensure no value has been sent
939 // on it after removing.
941 delete(db
.connRequests
, reqKey
)
945 case ret
, ok
:= <-req
:
947 db
.putConn(ret
.conn
, ret
.err
)
950 return nil, ctx
.Err()
951 case ret
, ok
:= <-req
:
953 return nil, errDBClosed
955 if ret
.err
== nil && ret
.conn
.expired(lifetime
) {
957 return nil, driver
.ErrBadConn
959 return ret
.conn
, ret
.err
963 db
.numOpen
++ // optimistically
965 ci
, err
:= db
.driver
.Open(db
.dsn
)
968 db
.numOpen
-- // correct for earlier optimism
969 db
.maybeOpenNewConnections()
976 createdAt
: nowFunc(),
979 db
.addDepLocked(dc
, dc
)
985 // putConnHook is a hook for testing.
986 var putConnHook
func(*DB
, *driverConn
)
988 // noteUnusedDriverStatement notes that ds is no longer used and should
989 // be closed whenever possible (when c is next not in use), unless c is
991 func (db
*DB
) noteUnusedDriverStatement(c
*driverConn
, ds
*driverStmt
) {
995 c
.onPut
= append(c
.onPut
, func() {
1008 // debugGetPut determines whether getConn & putConn calls' stack traces
1009 // are returned for more verbose crashes.
1010 const debugGetPut
= false
1012 // putConn adds a connection to the db's free pool.
1013 // err is optionally the last error that occurred on this connection.
1014 func (db
*DB
) putConn(dc
*driverConn
, err error
) {
1018 fmt
.Printf("putConn(%v) DUPLICATE was: %s\n\nPREVIOUS was: %s", dc
, stack(), db
.lastPut
[dc
])
1020 panic("sql: connection returned that was never out")
1023 db
.lastPut
[dc
] = stack()
1027 for _
, fn
:= range dc
.onPut
{
1032 if err
== driver
.ErrBadConn
{
1033 // Don't reuse bad connections.
1034 // Since the conn is considered bad and is being discarded, treat it
1035 // as closed. Don't decrement the open count here, finalClose will
1036 // take care of that.
1037 db
.maybeOpenNewConnections()
1042 if putConnHook
!= nil {
1045 added
:= db
.putConnDBLocked(dc
, nil)
1053 // Satisfy a connRequest or put the driverConn in the idle pool and return true
1055 // putConnDBLocked will satisfy a connRequest if there is one, or it will
1056 // return the *driverConn to the freeConn list if err == nil and the idle
1057 // connection limit will not be exceeded.
1058 // If err != nil, the value of dc is ignored.
1059 // If err == nil, then dc must not equal nil.
1060 // If a connRequest was fulfilled or the *driverConn was placed in the
1061 // freeConn list, then true is returned, otherwise false is returned.
1062 func (db
*DB
) putConnDBLocked(dc
*driverConn
, err error
) bool {
1066 if db
.maxOpen
> 0 && db
.numOpen
> db
.maxOpen
{
1069 if c
:= len(db
.connRequests
); c
> 0 {
1070 var req
chan connRequest
1072 for reqKey
, req
= range db
.connRequests
{
1075 delete(db
.connRequests
, reqKey
) // Remove from pending requests.
1084 } else if err
== nil && !db
.closed && db
.maxIdleConnsLocked() > len(db
.freeConn
) {
1085 db
.freeConn
= append(db
.freeConn
, dc
)
1086 db
.startCleanerLocked()
1092 // maxBadConnRetries is the number of maximum retries if the driver returns
1093 // driver.ErrBadConn to signal a broken connection before forcing a new
1094 // connection to be opened.
1095 const maxBadConnRetries
= 2
1097 // PrepareContext creates a prepared statement for later queries or executions.
1098 // Multiple queries or executions may be run concurrently from the
1099 // returned statement.
1100 // The caller must call the statement's Close method
1101 // when the statement is no longer needed.
1103 // The provided context is used for the preparation of the statement, not for the
1104 // execution of the statement.
1105 func (db
*DB
) PrepareContext(ctx context
.Context
, query
string) (*Stmt
, error
) {
1108 for i
:= 0; i
< maxBadConnRetries
; i
++ {
1109 stmt
, err
= db
.prepare(ctx
, query
, cachedOrNewConn
)
1110 if err
!= driver
.ErrBadConn
{
1114 if err
== driver
.ErrBadConn
{
1115 return db
.prepare(ctx
, query
, alwaysNewConn
)
1120 // Prepare creates a prepared statement for later queries or executions.
1121 // Multiple queries or executions may be run concurrently from the
1122 // returned statement.
1123 // The caller must call the statement's Close method
1124 // when the statement is no longer needed.
1125 func (db
*DB
) Prepare(query
string) (*Stmt
, error
) {
1126 return db
.PrepareContext(context
.Background(), query
)
1129 func (db
*DB
) prepare(ctx context
.Context
, query
string, strategy connReuseStrategy
) (*Stmt
, error
) {
1130 // TODO: check if db.driver supports an optional
1131 // driver.Preparer interface and call that instead, if so,
1132 // otherwise we make a prepared statement that's bound
1133 // to a connection, and to execute this prepared statement
1134 // we either need to use this connection (if it's free), else
1135 // get a new connection + re-prepare + execute on that one.
1136 dc
, err
:= db
.conn(ctx
, strategy
)
1141 withLock(dc
, func() {
1142 ds
, err
= dc
.prepareLocked(ctx
, query
)
1151 css
: []connStmt
{{dc
, ds
}},
1152 lastNumClosed
: atomic
.LoadUint64(&db
.numClosed
),
1154 db
.addDep(stmt
, stmt
)
1159 // ExecContext executes a query without returning any rows.
1160 // The args are for any placeholder parameters in the query.
1161 func (db
*DB
) ExecContext(ctx context
.Context
, query
string, args
...interface{}) (Result
, error
) {
1164 for i
:= 0; i
< maxBadConnRetries
; i
++ {
1165 res
, err
= db
.exec(ctx
, query
, args
, cachedOrNewConn
)
1166 if err
!= driver
.ErrBadConn
{
1170 if err
== driver
.ErrBadConn
{
1171 return db
.exec(ctx
, query
, args
, alwaysNewConn
)
1176 // Exec executes a query without returning any rows.
1177 // The args are for any placeholder parameters in the query.
1178 func (db
*DB
) Exec(query
string, args
...interface{}) (Result
, error
) {
1179 return db
.ExecContext(context
.Background(), query
, args
...)
1182 func (db
*DB
) exec(ctx context
.Context
, query
string, args
[]interface{}, strategy connReuseStrategy
) (res Result
, err error
) {
1183 dc
, err
:= db
.conn(ctx
, strategy
)
1191 if execer
, ok
:= dc
.ci
.(driver
.Execer
); ok
{
1192 var dargs
[]driver
.NamedValue
1193 dargs
, err
= driverArgs(nil, args
)
1197 var resi driver
.Result
1198 withLock(dc
, func() {
1199 resi
, err
= ctxDriverExec(ctx
, execer
, query
, dargs
)
1201 if err
!= driver
.ErrSkip
{
1205 return driverResult
{dc
, resi
}, nil
1210 withLock(dc
, func() {
1211 si
, err
= ctxDriverPrepare(ctx
, dc
.ci
, query
)
1216 ds
:= &driverStmt
{Locker
: dc
, si
: si
}
1218 return resultFromStatement(ctx
, ds
, args
...)
1221 // QueryContext executes a query that returns rows, typically a SELECT.
1222 // The args are for any placeholder parameters in the query.
1223 func (db
*DB
) QueryContext(ctx context
.Context
, query
string, args
...interface{}) (*Rows
, error
) {
1226 for i
:= 0; i
< maxBadConnRetries
; i
++ {
1227 rows
, err
= db
.query(ctx
, query
, args
, cachedOrNewConn
)
1228 if err
!= driver
.ErrBadConn
{
1232 if err
== driver
.ErrBadConn
{
1233 return db
.query(ctx
, query
, args
, alwaysNewConn
)
1238 // Query executes a query that returns rows, typically a SELECT.
1239 // The args are for any placeholder parameters in the query.
1240 func (db
*DB
) Query(query
string, args
...interface{}) (*Rows
, error
) {
1241 return db
.QueryContext(context
.Background(), query
, args
...)
1244 func (db
*DB
) query(ctx context
.Context
, query
string, args
[]interface{}, strategy connReuseStrategy
) (*Rows
, error
) {
1245 ci
, err
:= db
.conn(ctx
, strategy
)
1250 return db
.queryConn(ctx
, ci
, ci
.releaseConn
, query
, args
)
1253 // queryConn executes a query on the given connection.
1254 // The connection gets released by the releaseConn function.
1255 func (db
*DB
) queryConn(ctx context
.Context
, dc
*driverConn
, releaseConn
func(error
), query
string, args
[]interface{}) (*Rows
, error
) {
1256 if queryer
, ok
:= dc
.ci
.(driver
.Queryer
); ok
{
1257 dargs
, err
:= driverArgs(nil, args
)
1262 var rowsi driver
.Rows
1263 withLock(dc
, func() {
1264 rowsi
, err
= ctxDriverQuery(ctx
, queryer
, query
, dargs
)
1266 if err
!= driver
.ErrSkip
{
1271 // Note: ownership of dc passes to the *Rows, to be freed
1272 // with releaseConn.
1275 releaseConn
: releaseConn
,
1278 rows
.initContextClose(ctx
)
1285 withLock(dc
, func() {
1286 si
, err
= ctxDriverPrepare(ctx
, dc
.ci
, query
)
1293 ds
:= &driverStmt
{Locker
: dc
, si
: si
}
1294 rowsi
, err
:= rowsiFromStatement(ctx
, ds
, args
...)
1301 // Note: ownership of ci passes to the *Rows, to be freed
1302 // with releaseConn.
1305 releaseConn
: releaseConn
,
1309 rows
.initContextClose(ctx
)
1313 // QueryRowContext executes a query that is expected to return at most one row.
1314 // QueryRowContext always returns a non-nil value. Errors are deferred until
1315 // Row's Scan method is called.
1316 func (db
*DB
) QueryRowContext(ctx context
.Context
, query
string, args
...interface{}) *Row
{
1317 rows
, err
:= db
.QueryContext(ctx
, query
, args
...)
1318 return &Row
{rows
: rows
, err
: err
}
1321 // QueryRow executes a query that is expected to return at most one row.
1322 // QueryRow always returns a non-nil value. Errors are deferred until
1323 // Row's Scan method is called.
1324 func (db
*DB
) QueryRow(query
string, args
...interface{}) *Row
{
1325 return db
.QueryRowContext(context
.Background(), query
, args
...)
1328 // BeginTx starts a transaction.
1330 // The provided context is used until the transaction is committed or rolled back.
1331 // If the context is canceled, the sql package will roll back
1332 // the transaction. Tx.Commit will return an error if the context provided to
1333 // BeginTx is canceled.
1335 // The provided TxOptions is optional and may be nil if defaults should be used.
1336 // If a non-default isolation level is used that the driver doesn't support,
1337 // an error will be returned.
1338 func (db
*DB
) BeginTx(ctx context
.Context
, opts
*TxOptions
) (*Tx
, error
) {
1341 for i
:= 0; i
< maxBadConnRetries
; i
++ {
1342 tx
, err
= db
.begin(ctx
, opts
, cachedOrNewConn
)
1343 if err
!= driver
.ErrBadConn
{
1347 if err
== driver
.ErrBadConn
{
1348 return db
.begin(ctx
, opts
, alwaysNewConn
)
1353 // Begin starts a transaction. The default isolation level is dependent on
1355 func (db
*DB
) Begin() (*Tx
, error
) {
1356 return db
.BeginTx(context
.Background(), nil)
1359 func (db
*DB
) begin(ctx context
.Context
, opts
*TxOptions
, strategy connReuseStrategy
) (tx
*Tx
, err error
) {
1360 dc
, err
:= db
.conn(ctx
, strategy
)
1365 withLock(dc
, func() {
1366 txi
, err
= ctxDriverBegin(ctx
, opts
, dc
.ci
)
1373 // Schedule the transaction to rollback when the context is cancelled.
1374 // The cancel function in Tx will be called after done is set to true.
1375 ctx
, cancel
:= context
.WithCancel(ctx
)
1387 // Driver returns the database's underlying driver.
1388 func (db
*DB
) Driver() driver
.Driver
{
1392 // Tx is an in-progress database transaction.
1394 // A transaction must end with a call to Commit or Rollback.
1396 // After a call to Commit or Rollback, all operations on the
1397 // transaction fail with ErrTxDone.
1399 // The statements prepared for a transaction by calling
1400 // the transaction's Prepare or Stmt methods are closed
1401 // by the call to Commit or Rollback.
1405 // closemu prevents the transaction from closing while there
1406 // is an active query. It is held for read during queries
1407 // and exclusively during close.
1408 closemu sync
.RWMutex
1410 // dc is owned exclusively until Commit or Rollback, at which point
1411 // it's returned with putConn.
1415 // done transitions from 0 to 1 exactly once, on Commit
1416 // or Rollback. once done, all operations fail with
1418 // Use atomic operations on value when checking value.
1421 // All Stmts prepared for this transaction. These will be closed after the
1422 // transaction has been committed or rolled back.
1428 // cancel is called after done transitions from false to true.
1431 // ctx lives for the life of the transaction.
1435 // awaitDone blocks until the context in Tx is canceled and rolls back
1436 // the transaction if it's not already done.
1437 func (tx
*Tx
) awaitDone() {
1438 // Wait for either the transaction to be committed or rolled
1439 // back, or for the associated context to be closed.
1442 // Discard and close the connection used to ensure the
1443 // transaction is closed and the resources are released. This
1444 // rollback does nothing if the transaction has already been
1445 // committed or rolled back.
1449 func (tx
*Tx
) isDone() bool {
1450 return atomic
.LoadInt32(&tx
.done
) != 0
1453 // ErrTxDone is returned by any operation that is performed on a transaction
1454 // that has already been committed or rolled back.
1455 var ErrTxDone
= errors
.New("sql: Transaction has already been committed or rolled back")
1457 // close returns the connection to the pool and
1458 // must only be called by Tx.rollback or Tx.Commit.
1459 func (tx
*Tx
) close(err error
) {
1461 defer tx
.closemu
.Unlock()
1463 tx
.db
.putConn(tx
.dc
, err
)
1469 // hookTxGrabConn specifies an optional hook to be called on
1470 // a successful call to (*Tx).grabConn. For tests.
1471 var hookTxGrabConn
func()
1473 func (tx
*Tx
) grabConn(ctx context
.Context
) (*driverConn
, error
) {
1477 return nil, ctx
.Err()
1480 return nil, ErrTxDone
1482 if hookTxGrabConn
!= nil { // test hook
1488 // Closes all Stmts prepared for this transaction.
1489 func (tx
*Tx
) closePrepared() {
1491 defer tx
.stmts
.Unlock()
1492 for _
, stmt
:= range tx
.stmts
.v
{
1497 // Commit commits the transaction.
1498 func (tx
*Tx
) Commit() error
{
1499 if !atomic
.CompareAndSwapInt32(&tx
.done
, 0, 1) {
1504 case <-tx
.ctx
.Done():
1508 withLock(tx
.dc
, func() {
1509 err
= tx
.txi
.Commit()
1511 if err
!= driver
.ErrBadConn
{
1518 // rollback aborts the transaction and optionally forces the pool to discard
1520 func (tx
*Tx
) rollback(discardConn
bool) error
{
1521 if !atomic
.CompareAndSwapInt32(&tx
.done
, 0, 1) {
1525 withLock(tx
.dc
, func() {
1526 err
= tx
.txi
.Rollback()
1528 if err
!= driver
.ErrBadConn
{
1532 err
= driver
.ErrBadConn
1538 // Rollback aborts the transaction.
1539 func (tx
*Tx
) Rollback() error
{
1540 return tx
.rollback(false)
1543 // Prepare creates a prepared statement for use within a transaction.
1545 // The returned statement operates within the transaction and will be closed
1546 // when the transaction has been committed or rolled back.
1548 // To use an existing prepared statement on this transaction, see Tx.Stmt.
1550 // The provided context will be used for the preparation of the context, not
1551 // for the execution of the returned statement. The returned statement
1552 // will run in the transaction context.
1553 func (tx
*Tx
) PrepareContext(ctx context
.Context
, query
string) (*Stmt
, error
) {
1555 defer tx
.closemu
.RUnlock()
1557 // TODO(bradfitz): We could be more efficient here and either
1558 // provide a method to take an existing Stmt (created on
1559 // perhaps a different Conn), and re-create it on this Conn if
1560 // necessary. Or, better: keep a map in DB of query string to
1561 // Stmts, and have Stmt.Execute do the right thing and
1562 // re-prepare if the Conn in use doesn't have that prepared
1563 // statement. But we'll want to avoid caching the statement
1564 // in the case where we only call conn.Prepare implicitly
1565 // (such as in db.Exec or tx.Exec), but the caller package
1566 // can't be holding a reference to the returned statement.
1567 // Perhaps just looking at the reference count (by noting
1568 // Stmt.Close) would be enough. We might also want a finalizer
1569 // on Stmt to drop the reference count.
1570 dc
, err
:= tx
.grabConn(ctx
)
1576 withLock(dc
, func() {
1577 si
, err
= ctxDriverPrepare(ctx
, dc
.ci
, query
)
1593 tx
.stmts
.v
= append(tx
.stmts
.v
, stmt
)
1598 // Prepare creates a prepared statement for use within a transaction.
1600 // The returned statement operates within the transaction and can no longer
1601 // be used once the transaction has been committed or rolled back.
1603 // To use an existing prepared statement on this transaction, see Tx.Stmt.
1604 func (tx
*Tx
) Prepare(query
string) (*Stmt
, error
) {
1605 return tx
.PrepareContext(context
.Background(), query
)
1608 // StmtContext returns a transaction-specific prepared statement from
1609 // an existing statement.
1612 // updateMoney, err := db.Prepare("UPDATE balance SET money=money+? WHERE id=?")
1614 // tx, err := db.Begin()
1616 // res, err := tx.StmtContext(ctx, updateMoney).Exec(123.45, 98293203)
1618 // The returned statement operates within the transaction and will be closed
1619 // when the transaction has been committed or rolled back.
1620 func (tx
*Tx
) StmtContext(ctx context
.Context
, stmt
*Stmt
) *Stmt
{
1622 defer tx
.closemu
.RUnlock()
1624 // TODO(bradfitz): optimize this. Currently this re-prepares
1625 // each time. This is fine for now to illustrate the API but
1626 // we should really cache already-prepared statements
1627 // per-Conn. See also the big comment in Tx.Prepare.
1629 if tx
.db
!= stmt
.db
{
1630 return &Stmt
{stickyErr
: errors
.New("sql: Tx.Stmt: statement from different database used")}
1632 dc
, err
:= tx
.grabConn(ctx
)
1634 return &Stmt
{stickyErr
: err
}
1637 withLock(dc
, func() {
1638 si
, err
= ctxDriverPrepare(ctx
, dc
.ci
, stmt
.query
)
1651 tx
.stmts
.v
= append(tx
.stmts
.v
, txs
)
1656 // Stmt returns a transaction-specific prepared statement from
1657 // an existing statement.
1660 // updateMoney, err := db.Prepare("UPDATE balance SET money=money+? WHERE id=?")
1662 // tx, err := db.Begin()
1664 // res, err := tx.Stmt(updateMoney).Exec(123.45, 98293203)
1666 // The returned statement operates within the transaction and will be closed
1667 // when the transaction has been committed or rolled back.
1668 func (tx
*Tx
) Stmt(stmt
*Stmt
) *Stmt
{
1669 return tx
.StmtContext(context
.Background(), stmt
)
1672 // ExecContext executes a query that doesn't return rows.
1673 // For example: an INSERT and UPDATE.
1674 func (tx
*Tx
) ExecContext(ctx context
.Context
, query
string, args
...interface{}) (Result
, error
) {
1676 defer tx
.closemu
.RUnlock()
1678 dc
, err
:= tx
.grabConn(ctx
)
1683 if execer
, ok
:= dc
.ci
.(driver
.Execer
); ok
{
1684 dargs
, err
:= driverArgs(nil, args
)
1688 var resi driver
.Result
1689 withLock(dc
, func() {
1690 resi
, err
= ctxDriverExec(ctx
, execer
, query
, dargs
)
1693 return driverResult
{dc
, resi
}, nil
1695 if err
!= driver
.ErrSkip
{
1701 withLock(dc
, func() {
1702 si
, err
= ctxDriverPrepare(ctx
, dc
.ci
, query
)
1707 ds
:= &driverStmt
{Locker
: dc
, si
: si
}
1710 return resultFromStatement(ctx
, ds
, args
...)
1713 // Exec executes a query that doesn't return rows.
1714 // For example: an INSERT and UPDATE.
1715 func (tx
*Tx
) Exec(query
string, args
...interface{}) (Result
, error
) {
1716 return tx
.ExecContext(context
.Background(), query
, args
...)
1719 // QueryContext executes a query that returns rows, typically a SELECT.
1720 func (tx
*Tx
) QueryContext(ctx context
.Context
, query
string, args
...interface{}) (*Rows
, error
) {
1722 defer tx
.closemu
.RUnlock()
1724 dc
, err
:= tx
.grabConn(ctx
)
1728 releaseConn
:= func(error
) {}
1729 return tx
.db
.queryConn(ctx
, dc
, releaseConn
, query
, args
)
1732 // Query executes a query that returns rows, typically a SELECT.
1733 func (tx
*Tx
) Query(query
string, args
...interface{}) (*Rows
, error
) {
1734 return tx
.QueryContext(context
.Background(), query
, args
...)
1737 // QueryRowContext executes a query that is expected to return at most one row.
1738 // QueryRowContext always returns a non-nil value. Errors are deferred until
1739 // Row's Scan method is called.
1740 func (tx
*Tx
) QueryRowContext(ctx context
.Context
, query
string, args
...interface{}) *Row
{
1741 rows
, err
:= tx
.QueryContext(ctx
, query
, args
...)
1742 return &Row
{rows
: rows
, err
: err
}
1745 // QueryRow executes a query that is expected to return at most one row.
1746 // QueryRow always returns a non-nil value. Errors are deferred until
1747 // Row's Scan method is called.
1748 func (tx
*Tx
) QueryRow(query
string, args
...interface{}) *Row
{
1749 return tx
.QueryRowContext(context
.Background(), query
, args
...)
1752 // connStmt is a prepared statement on a particular connection.
1753 type connStmt
struct {
1758 // Stmt is a prepared statement.
1759 // A Stmt is safe for concurrent use by multiple goroutines.
1762 db
*DB
// where we came from
1763 query
string // that created the Stmt
1764 stickyErr error
// if non-nil, this error is returned for all operations
1766 closemu sync
.RWMutex
// held exclusively during close, for read otherwise.
1768 // If in a transaction, else both nil:
1772 mu sync
.Mutex
// protects the rest of the fields
1775 // css is a list of underlying driver statement interfaces
1776 // that are valid on particular connections. This is only
1777 // used if tx == nil and one is found that has idle
1778 // connections. If tx != nil, txsi is always used.
1781 // lastNumClosed is copied from db.numClosed when Stmt is created
1782 // without tx and closed connections in css are removed.
1783 lastNumClosed
uint64
1786 // ExecContext executes a prepared statement with the given arguments and
1787 // returns a Result summarizing the effect of the statement.
1788 func (s
*Stmt
) ExecContext(ctx context
.Context
, args
...interface{}) (Result
, error
) {
1790 defer s
.closemu
.RUnlock()
1793 for i
:= 0; i
< maxBadConnRetries
; i
++ {
1794 _
, releaseConn
, ds
, err
:= s
.connStmt(ctx
)
1796 if err
== driver
.ErrBadConn
{
1802 res
, err
= resultFromStatement(ctx
, ds
, args
...)
1804 if err
!= driver
.ErrBadConn
{
1808 return nil, driver
.ErrBadConn
1811 // Exec executes a prepared statement with the given arguments and
1812 // returns a Result summarizing the effect of the statement.
1813 func (s
*Stmt
) Exec(args
...interface{}) (Result
, error
) {
1814 return s
.ExecContext(context
.Background(), args
...)
1817 func driverNumInput(ds
*driverStmt
) int {
1819 defer ds
.Unlock() // in case NumInput panics
1820 return ds
.si
.NumInput()
1823 func resultFromStatement(ctx context
.Context
, ds
*driverStmt
, args
...interface{}) (Result
, error
) {
1824 want
:= driverNumInput(ds
)
1826 // -1 means the driver doesn't know how to count the number of
1827 // placeholders, so we won't sanity check input here and instead let the
1828 // driver deal with errors.
1829 if want
!= -1 && len(args
) != want
{
1830 return nil, fmt
.Errorf("sql: expected %d arguments, got %d", want
, len(args
))
1833 dargs
, err
:= driverArgs(ds
, args
)
1841 resi
, err
:= ctxDriverStmtExec(ctx
, ds
.si
, dargs
)
1845 return driverResult
{ds
.Locker
, resi
}, nil
1848 // removeClosedStmtLocked removes closed conns in s.css.
1850 // To avoid lock contention on DB.mu, we do it only when
1851 // s.db.numClosed - s.lastNum is large enough.
1852 func (s
*Stmt
) removeClosedStmtLocked() {
1853 t
:= len(s
.css
)/2 + 1
1857 dbClosed
:= atomic
.LoadUint64(&s
.db
.numClosed
)
1858 if dbClosed
-s
.lastNumClosed
< uint64(t
) {
1863 for i
:= 0; i
< len(s
.css
); i
++ {
1864 if s
.css
[i
].dc
.dbmuClosed
{
1865 s
.css
[i
] = s
.css
[len(s
.css
)-1]
1866 s
.css
= s
.css
[:len(s
.css
)-1]
1871 s
.lastNumClosed
= dbClosed
1874 // connStmt returns a free driver connection on which to execute the
1875 // statement, a function to call to release the connection, and a
1876 // statement bound to that connection.
1877 func (s
*Stmt
) connStmt(ctx context
.Context
) (ci
*driverConn
, releaseConn
func(error
), ds
*driverStmt
, err error
) {
1878 if err
= s
.stickyErr
; err
!= nil {
1884 err
= errors
.New("sql: statement is closed")
1888 // In a transaction, we always use the connection that the
1889 // transaction was created on.
1892 ci
, err
= s
.tx
.grabConn(ctx
) // blocks, waiting for the connection.
1896 releaseConn
= func(error
) {}
1897 return ci
, releaseConn
, s
.txds
, nil
1900 s
.removeClosedStmtLocked()
1903 dc
, err
:= s
.db
.conn(ctx
, cachedOrNewConn
)
1905 return nil, nil, nil, err
1909 for _
, v
:= range s
.css
{
1912 return dc
, dc
.releaseConn
, v
.ds
, nil
1917 // No luck; we need to prepare the statement on this connection
1918 withLock(dc
, func() {
1919 ds
, err
= dc
.prepareLocked(ctx
, s
.query
)
1922 s
.db
.putConn(dc
, err
)
1923 return nil, nil, nil, err
1926 cs
:= connStmt
{dc
, ds
}
1927 s
.css
= append(s
.css
, cs
)
1930 return dc
, dc
.releaseConn
, ds
, nil
1933 // QueryContext executes a prepared query statement with the given arguments
1934 // and returns the query results as a *Rows.
1935 func (s
*Stmt
) QueryContext(ctx context
.Context
, args
...interface{}) (*Rows
, error
) {
1937 defer s
.closemu
.RUnlock()
1939 var rowsi driver
.Rows
1940 for i
:= 0; i
< maxBadConnRetries
; i
++ {
1941 dc
, releaseConn
, ds
, err
:= s
.connStmt(ctx
)
1943 if err
== driver
.ErrBadConn
{
1949 rowsi
, err
= rowsiFromStatement(ctx
, ds
, args
...)
1951 // Note: ownership of ci passes to the *Rows, to be freed
1952 // with releaseConn.
1956 // releaseConn set below
1958 rows
.initContextClose(ctx
)
1959 s
.db
.addDep(s
, rows
)
1960 rows
.releaseConn
= func(err error
) {
1962 s
.db
.removeDep(s
, rows
)
1968 if err
!= driver
.ErrBadConn
{
1972 return nil, driver
.ErrBadConn
1975 // Query executes a prepared query statement with the given arguments
1976 // and returns the query results as a *Rows.
1977 func (s
*Stmt
) Query(args
...interface{}) (*Rows
, error
) {
1978 return s
.QueryContext(context
.Background(), args
...)
1981 func rowsiFromStatement(ctx context
.Context
, ds
*driverStmt
, args
...interface{}) (driver
.Rows
, error
) {
1983 withLock(ds
, func() {
1984 want
= ds
.si
.NumInput()
1987 // -1 means the driver doesn't know how to count the number of
1988 // placeholders, so we won't sanity check input here and instead let the
1989 // driver deal with errors.
1990 if want
!= -1 && len(args
) != want
{
1991 return nil, fmt
.Errorf("sql: statement expects %d inputs; got %d", want
, len(args
))
1994 dargs
, err
:= driverArgs(ds
, args
)
2002 rowsi
, err
:= ctxDriverStmtQuery(ctx
, ds
.si
, dargs
)
2009 // QueryRowContext executes a prepared query statement with the given arguments.
2010 // If an error occurs during the execution of the statement, that error will
2011 // be returned by a call to Scan on the returned *Row, which is always non-nil.
2012 // If the query selects no rows, the *Row's Scan will return ErrNoRows.
2013 // Otherwise, the *Row's Scan scans the first selected row and discards
2019 // err := nameByUseridStmt.QueryRowContext(ctx, id).Scan(&name)
2020 func (s
*Stmt
) QueryRowContext(ctx context
.Context
, args
...interface{}) *Row
{
2021 rows
, err
:= s
.QueryContext(ctx
, args
...)
2023 return &Row
{err
: err
}
2025 return &Row
{rows
: rows
}
2028 // QueryRow executes a prepared query statement with the given arguments.
2029 // If an error occurs during the execution of the statement, that error will
2030 // be returned by a call to Scan on the returned *Row, which is always non-nil.
2031 // If the query selects no rows, the *Row's Scan will return ErrNoRows.
2032 // Otherwise, the *Row's Scan scans the first selected row and discards
2038 // err := nameByUseridStmt.QueryRow(id).Scan(&name)
2039 func (s
*Stmt
) QueryRow(args
...interface{}) *Row
{
2040 return s
.QueryRowContext(context
.Background(), args
...)
2043 // Close closes the statement.
2044 func (s
*Stmt
) Close() error
{
2046 defer s
.closemu
.Unlock()
2048 if s
.stickyErr
!= nil {
2060 return s
.txds
.Close()
2063 return s
.db
.removeDep(s
, s
)
2066 func (s
*Stmt
) finalClose() error
{
2070 for _
, v
:= range s
.css
{
2071 s
.db
.noteUnusedDriverStatement(v
.dc
, v
.ds
)
2072 v
.dc
.removeOpenStmt(v
.ds
)
2079 // Rows is the result of a query. Its cursor starts before the first row
2080 // of the result set. Use Next to advance through the rows:
2082 // rows, err := db.Query("SELECT ...")
2084 // defer rows.Close()
2085 // for rows.Next() {
2088 // err = rows.Scan(&id, &name)
2091 // err = rows.Err() // get any error encountered during iteration
2094 dc
*driverConn
// owned; must call releaseConn when closed to release
2095 releaseConn
func(error
)
2097 cancel
func() // called when Rows is closed, may be nil.
2098 closeStmt
*driverStmt
// if non-nil, statement to Close on close
2100 // closemu prevents Rows from closing while there
2101 // is an active streaming result. It is held for read during non-close operations
2102 // and exclusively during close.
2104 // closemu guards lasterr and closed.
2105 closemu sync
.RWMutex
2107 lasterr error
// non-nil only if closed is true
2109 // lastcols is only used in Scan, Next, and NextResultSet which are expected
2110 // not not be called concurrently.
2111 lastcols
[]driver
.Value
2114 func (rs
*Rows
) initContextClose(ctx context
.Context
) {
2115 ctx
, rs
.cancel
= context
.WithCancel(ctx
)
2116 go rs
.awaitDone(ctx
)
2119 // awaitDone blocks until the rows are closed or the context canceled.
2120 func (rs
*Rows
) awaitDone(ctx context
.Context
) {
2125 // Next prepares the next result row for reading with the Scan method. It
2126 // returns true on success, or false if there is no next result row or an error
2127 // happened while preparing it. Err should be consulted to distinguish between
2130 // Every call to Scan, even the first one, must be preceded by a call to Next.
2131 func (rs
*Rows
) Next() bool {
2132 var doClose
, ok
bool
2133 withLock(rs
.closemu
.RLocker(), func() {
2134 doClose
, ok
= rs
.nextLocked()
2142 func (rs
*Rows
) nextLocked() (doClose
, ok
bool) {
2146 if rs
.lastcols
== nil {
2147 rs
.lastcols
= make([]driver
.Value
, len(rs
.rowsi
.Columns()))
2149 rs
.lasterr
= rs
.rowsi
.Next(rs
.lastcols
)
2150 if rs
.lasterr
!= nil {
2151 // Close the connection if there is a driver error.
2152 if rs
.lasterr
!= io
.EOF
{
2155 nextResultSet
, ok
:= rs
.rowsi
.(driver
.RowsNextResultSet
)
2159 // The driver is at the end of the current result set.
2160 // Test to see if there is another result set after the current one.
2161 // Only close Rows if there is no further result sets to read.
2162 if !nextResultSet
.HasNextResultSet() {
2165 return doClose
, false
2170 // NextResultSet prepares the next result set for reading. It returns true if
2171 // there is further result sets, or false if there is no further result set
2172 // or if there is an error advancing to it. The Err method should be consulted
2173 // to distinguish between the two cases.
2175 // After calling NextResultSet, the Next method should always be called before
2176 // scanning. If there are further result sets they may not have rows in the result
2178 func (rs
*Rows
) NextResultSet() bool {
2186 defer rs
.closemu
.RUnlock()
2193 nextResultSet
, ok
:= rs
.rowsi
.(driver
.RowsNextResultSet
)
2198 rs
.lasterr
= nextResultSet
.NextResultSet()
2199 if rs
.lasterr
!= nil {
2206 // Err returns the error, if any, that was encountered during iteration.
2207 // Err may be called after an explicit or implicit Close.
2208 func (rs
*Rows
) Err() error
{
2210 defer rs
.closemu
.RUnlock()
2211 if rs
.lasterr
== io
.EOF
{
2217 // Columns returns the column names.
2218 // Columns returns an error if the rows are closed, or if the rows
2219 // are from QueryRow and there was a deferred error.
2220 func (rs
*Rows
) Columns() ([]string, error
) {
2222 defer rs
.closemu
.RUnlock()
2224 return nil, errors
.New("sql: Rows are closed")
2226 if rs
.rowsi
== nil {
2227 return nil, errors
.New("sql: no Rows available")
2229 return rs
.rowsi
.Columns(), nil
2232 // ColumnTypes returns column information such as column type, length,
2233 // and nullable. Some information may not be available from some drivers.
2234 func (rs
*Rows
) ColumnTypes() ([]*ColumnType
, error
) {
2236 defer rs
.closemu
.RUnlock()
2238 return nil, errors
.New("sql: Rows are closed")
2240 if rs
.rowsi
== nil {
2241 return nil, errors
.New("sql: no Rows available")
2243 return rowsColumnInfoSetup(rs
.rowsi
), nil
2246 // ColumnType contains the name and type of a column.
2247 type ColumnType
struct {
2252 hasPrecisionScale
bool
2259 scanType reflect
.Type
2262 // Name returns the name or alias of the column.
2263 func (ci
*ColumnType
) Name() string {
2267 // Length returns the column type length for variable length column types such
2268 // as text and binary field types. If the type length is unbounded the value will
2269 // be math.MaxInt64 (any database limits will still apply).
2270 // If the column type is not variable length, such as an int, or if not supported
2271 // by the driver ok is false.
2272 func (ci
*ColumnType
) Length() (length
int64, ok
bool) {
2273 return ci
.length
, ci
.hasLength
2276 // DecimalSize returns the scale and precision of a decimal type.
2277 // If not applicable or if not supported ok is false.
2278 func (ci
*ColumnType
) DecimalSize() (precision
, scale
int64, ok
bool) {
2279 return ci
.precision
, ci
.scale
, ci
.hasPrecisionScale
2282 // ScanType returns a Go type suitable for scanning into using Rows.Scan.
2283 // If a driver does not support this property ScanType will return
2284 // the type of an empty interface.
2285 func (ci
*ColumnType
) ScanType() reflect
.Type
{
2289 // Nullable returns whether the column may be null.
2290 // If a driver does not support this property ok will be false.
2291 func (ci
*ColumnType
) Nullable() (nullable
, ok
bool) {
2292 return ci
.nullable
, ci
.hasNullable
2295 // DatabaseTypeName returns the database system name of the column type. If an empty
2296 // string is returned the driver type name is not supported.
2297 // Consult your driver documentation for a list of driver data types. Length specifiers
2298 // are not included.
2299 // Common type include "VARCHAR", "TEXT", "NVARCHAR", "DECIMAL", "BOOL", "INT", "BIGINT".
2300 func (ci
*ColumnType
) DatabaseTypeName() string {
2301 return ci
.databaseType
2304 func rowsColumnInfoSetup(rowsi driver
.Rows
) []*ColumnType
{
2305 names
:= rowsi
.Columns()
2307 list
:= make([]*ColumnType
, len(names
))
2308 for i
:= range list
{
2314 if prop
, ok
:= rowsi
.(driver
.RowsColumnTypeScanType
); ok
{
2315 ci
.scanType
= prop
.ColumnTypeScanType(i
)
2317 ci
.scanType
= reflect
.TypeOf(new(interface{})).Elem()
2319 if prop
, ok
:= rowsi
.(driver
.RowsColumnTypeDatabaseTypeName
); ok
{
2320 ci
.databaseType
= prop
.ColumnTypeDatabaseTypeName(i
)
2322 if prop
, ok
:= rowsi
.(driver
.RowsColumnTypeLength
); ok
{
2323 ci
.length
, ci
.hasLength
= prop
.ColumnTypeLength(i
)
2325 if prop
, ok
:= rowsi
.(driver
.RowsColumnTypeNullable
); ok
{
2326 ci
.nullable
, ci
.hasNullable
= prop
.ColumnTypeNullable(i
)
2328 if prop
, ok
:= rowsi
.(driver
.RowsColumnTypePrecisionScale
); ok
{
2329 ci
.precision
, ci
.scale
, ci
.hasPrecisionScale
= prop
.ColumnTypePrecisionScale(i
)
2335 // Scan copies the columns in the current row into the values pointed
2336 // at by dest. The number of values in dest must be the same as the
2337 // number of columns in Rows.
2339 // Scan converts columns read from the database into the following
2340 // common Go types and special types provided by the sql package:
2344 // *int, *int8, *int16, *int32, *int64
2345 // *uint, *uint8, *uint16, *uint32, *uint64
2347 // *float32, *float64
2350 // any type implementing Scanner (see Scanner docs)
2352 // In the most simple case, if the type of the value from the source
2353 // column is an integer, bool or string type T and dest is of type *T,
2354 // Scan simply assigns the value through the pointer.
2356 // Scan also converts between string and numeric types, as long as no
2357 // information would be lost. While Scan stringifies all numbers
2358 // scanned from numeric database columns into *string, scans into
2359 // numeric types are checked for overflow. For example, a float64 with
2360 // value 300 or a string with value "300" can scan into a uint16, but
2361 // not into a uint8, though float64(255) or "255" can scan into a
2362 // uint8. One exception is that scans of some float64 numbers to
2363 // strings may lose information when stringifying. In general, scan
2364 // floating point columns into *float64.
2366 // If a dest argument has type *[]byte, Scan saves in that argument a
2367 // copy of the corresponding data. The copy is owned by the caller and
2368 // can be modified and held indefinitely. The copy can be avoided by
2369 // using an argument of type *RawBytes instead; see the documentation
2370 // for RawBytes for restrictions on its use.
2372 // If an argument has type *interface{}, Scan copies the value
2373 // provided by the underlying driver without conversion. When scanning
2374 // from a source value of type []byte to *interface{}, a copy of the
2375 // slice is made and the caller owns the result.
2377 // Source values of type time.Time may be scanned into values of type
2378 // *time.Time, *interface{}, *string, or *[]byte. When converting to
2379 // the latter two, time.Format3339Nano is used.
2381 // Source values of type bool may be scanned into types *bool,
2382 // *interface{}, *string, *[]byte, or *RawBytes.
2384 // For scanning into *bool, the source may be true, false, 1, 0, or
2385 // string inputs parseable by strconv.ParseBool.
2386 func (rs
*Rows
) Scan(dest
...interface{}) error
{
2389 rs
.closemu
.RUnlock()
2390 return errors
.New("sql: Rows are closed")
2392 rs
.closemu
.RUnlock()
2394 if rs
.lastcols
== nil {
2395 return errors
.New("sql: Scan called without calling Next")
2397 if len(dest
) != len(rs
.lastcols
) {
2398 return fmt
.Errorf("sql: expected %d destination arguments in Scan, not %d", len(rs
.lastcols
), len(dest
))
2400 for i
, sv
:= range rs
.lastcols
{
2401 err
:= convertAssign(dest
[i
], sv
)
2403 return fmt
.Errorf("sql: Scan error on column index %d: %v", i
, err
)
2409 // rowsCloseHook returns a function so tests may install the
2410 // hook throug a test only mutex.
2411 var rowsCloseHook
= func() func(*Rows
, *error
) { return nil }
2413 // Close closes the Rows, preventing further enumeration. If Next is called
2414 // and returns false and there are no further result sets,
2415 // the Rows are closed automatically and it will suffice to check the
2416 // result of Err. Close is idempotent and does not affect the result of Err.
2417 func (rs
*Rows
) Close() error
{
2418 return rs
.close(nil)
2421 func (rs
*Rows
) close(err error
) error
{
2423 defer rs
.closemu
.Unlock()
2430 if rs
.lasterr
== nil {
2434 err
= rs
.rowsi
.Close()
2435 if fn
:= rowsCloseHook(); fn
!= nil {
2438 if rs
.cancel
!= nil {
2442 if rs
.closeStmt
!= nil {
2443 rs
.closeStmt
.Close()
2449 // Row is the result of calling QueryRow to select a single row.
2451 // One of these two will be non-nil:
2452 err error
// deferred error for easy chaining
2456 // Scan copies the columns from the matched row into the values
2457 // pointed at by dest. See the documentation on Rows.Scan for details.
2458 // If more than one row matches the query,
2459 // Scan uses the first row and discards the rest. If no row matches
2460 // the query, Scan returns ErrNoRows.
2461 func (r
*Row
) Scan(dest
...interface{}) error
{
2466 // TODO(bradfitz): for now we need to defensively clone all
2467 // []byte that the driver returned (not permitting
2468 // *RawBytes in Rows.Scan), since we're about to close
2469 // the Rows in our defer, when we return from this function.
2470 // the contract with the driver.Next(...) interface is that it
2471 // can return slices into read-only temporary memory that's
2472 // only valid until the next Scan/Close. But the TODO is that
2473 // for a lot of drivers, this copy will be unnecessary. We
2474 // should provide an optional interface for drivers to
2475 // implement to say, "don't worry, the []bytes that I return
2476 // from Next will not be modified again." (for instance, if
2477 // they were obtained from the network anyway) But for now we
2479 defer r
.rows
.Close()
2480 for _
, dp
:= range dest
{
2481 if _
, ok
:= dp
.(*RawBytes
); ok
{
2482 return errors
.New("sql: RawBytes isn't allowed on Row.Scan")
2487 if err
:= r
.rows
.Err(); err
!= nil {
2492 err
:= r
.rows
.Scan(dest
...)
2496 // Make sure the query can be processed to completion with no errors.
2497 if err
:= r
.rows
.Close(); err
!= nil {
2504 // A Result summarizes an executed SQL command.
2505 type Result
interface {
2506 // LastInsertId returns the integer generated by the database
2507 // in response to a command. Typically this will be from an
2508 // "auto increment" column when inserting a new row. Not all
2509 // databases support this feature, and the syntax of such
2510 // statements varies.
2511 LastInsertId() (int64, error
)
2513 // RowsAffected returns the number of rows affected by an
2514 // update, insert, or delete. Not every database or database
2515 // driver may support this.
2516 RowsAffected() (int64, error
)
2519 type driverResult
struct {
2520 sync
.Locker
// the *driverConn
2524 func (dr driverResult
) LastInsertId() (int64, error
) {
2527 return dr
.resi
.LastInsertId()
2530 func (dr driverResult
) RowsAffected() (int64, error
) {
2533 return dr
.resi
.RowsAffected()
2536 func stack() string {
2537 var buf
[2 << 10]byte
2538 return string(buf
[:runtime
.Stack(buf
[:], false)])
2541 // withLock runs while holding lk.
2542 func withLock(lk sync
.Locker
, fn
func()) {
2544 defer lk
.Unlock() // in case fn panics