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 // Out may be used to retrieve OUTPUT value parameters from stored procedures.
283 // Not all drivers and databases support OUTPUT value parameters.
288 // _, err := db.ExecContext(ctx, "ProcName", sql.Named("Arg1", Out{Dest: &outArg}))
290 _Named_Fields_Required
struct{}
292 // Dest is a pointer to the value that will be set to the result of the
293 // stored procedure's OUTPUT parameter.
296 // In is whether the parameter is an INOUT parameter. If so, the input value to the stored
297 // procedure is the dereferenced value of Dest's pointer, which is then replaced with
302 // ErrNoRows is returned by Scan when QueryRow doesn't return a
303 // row. In such a case, QueryRow returns a placeholder *Row value that
304 // defers this error until a Scan.
305 var ErrNoRows
= errors
.New("sql: no rows in result set")
307 // DB is a database handle representing a pool of zero or more
308 // underlying connections. It's safe for concurrent use by multiple
311 // The sql package creates and frees connections automatically; it
312 // also maintains a free pool of idle connections. If the database has
313 // a concept of per-connection state, such state can only be reliably
314 // observed within a transaction. Once DB.Begin is called, the
315 // returned Tx is bound to a single connection. Once Commit or
316 // Rollback is called on the transaction, that transaction's
317 // connection is returned to DB's idle connection pool. The pool size
318 // can be controlled with SetMaxIdleConns.
322 // numClosed is an atomic counter which represents a total number of
323 // closed connections. Stmt.openStmt checks it before cleaning closed
324 // connections in Stmt.css.
327 mu sync
.Mutex
// protects following fields
328 freeConn
[]*driverConn
329 connRequests
map[uint64]chan connRequest
330 nextRequest
uint64 // Next key to use in connRequests.
331 numOpen
int // number of opened and pending open connections
332 // Used to signal the need for new connections
333 // a goroutine running connectionOpener() reads on this chan and
334 // maybeOpenNewConnections sends on the chan (one send per needed connection)
335 // It is closed during db.Close(). The close tells the connectionOpener
336 // goroutine to exit.
337 openerCh
chan struct{}
339 dep
map[finalCloser
]depSet
340 lastPut
map[*driverConn
]string // stacktrace of last conn's put; debug only
341 maxIdle
int // zero means defaultMaxIdleConns; negative means 0
342 maxOpen
int // <= 0 means unlimited
343 maxLifetime time
.Duration
// maximum amount of time a connection may be reused
344 cleanerCh
chan struct{}
347 // connReuseStrategy determines how (*DB).conn returns database connections.
348 type connReuseStrategy
uint8
351 // alwaysNewConn forces a new connection to the database.
352 alwaysNewConn connReuseStrategy
= iota
353 // cachedOrNewConn returns a cached connection, if available, else waits
354 // for one to become available (if MaxOpenConns has been reached) or
355 // creates a new database connection.
359 // driverConn wraps a driver.Conn with a mutex, to
360 // be held during all calls into the Conn. (including any calls onto
361 // interfaces returned via that Conn, such as calls on Tx, Stmt,
363 type driverConn
struct {
367 sync
.Mutex
// guards following
370 finalClosed
bool // ci.Close has been called
371 openStmt
map[*driverStmt
]bool
375 onPut
[]func() // code (with db.mu held) run when conn is next returned
376 dbmuClosed
bool // same as closed, but guarded by db.mu, for removeClosedStmtLocked
379 func (dc
*driverConn
) releaseConn(err error
) {
380 dc
.db
.putConn(dc
, err
)
383 func (dc
*driverConn
) removeOpenStmt(ds
*driverStmt
) {
386 delete(dc
.openStmt
, ds
)
389 func (dc
*driverConn
) expired(timeout time
.Duration
) bool {
393 return dc
.createdAt
.Add(timeout
).Before(nowFunc())
396 // prepareLocked prepares the query on dc. When cg == nil the dc must keep track of
397 // the prepared statements in a pool.
398 func (dc
*driverConn
) prepareLocked(ctx context
.Context
, cg stmtConnGrabber
, query
string) (*driverStmt
, error
) {
399 si
, err
:= ctxDriverPrepare(ctx
, dc
.ci
, query
)
403 ds
:= &driverStmt
{Locker
: dc
, si
: si
}
405 // No need to manage open statements if there is a single connection grabber.
410 // Track each driverConn's open statements, so we can close them
411 // before closing the conn.
413 // Wrap all driver.Stmt is *driverStmt to ensure they are only closed once.
414 if dc
.openStmt
== nil {
415 dc
.openStmt
= make(map[*driverStmt
]bool)
417 dc
.openStmt
[ds
] = true
421 // the dc.db's Mutex is held.
422 func (dc
*driverConn
) closeDBLocked() func() error
{
426 return func() error
{ return errors
.New("sql: duplicate driverConn close") }
429 return dc
.db
.removeDepLocked(dc
, dc
)
432 func (dc
*driverConn
) Close() error
{
436 return errors
.New("sql: duplicate driverConn close")
439 dc
.Unlock() // not defer; removeDep finalClose calls may need to lock
441 // And now updates that require holding dc.mu.Lock.
444 fn
:= dc
.db
.removeDepLocked(dc
, dc
)
449 func (dc
*driverConn
) finalClose() error
{
452 // Each *driverStmt has a lock to the dc. Copy the list out of the dc
453 // before calling close on each stmt.
454 var openStmt
[]*driverStmt
455 withLock(dc
, func() {
456 openStmt
= make([]*driverStmt
, 0, len(dc
.openStmt
))
457 for ds
:= range dc
.openStmt
{
458 openStmt
= append(openStmt
, ds
)
462 for _
, ds
:= range openStmt
{
465 withLock(dc
, func() {
466 dc
.finalClosed
= true
473 dc
.db
.maybeOpenNewConnections()
476 atomic
.AddUint64(&dc
.db
.numClosed
, 1)
480 // driverStmt associates a driver.Stmt with the
481 // *driverConn from which it came, so the driverConn's lock can be
482 // held during calls.
483 type driverStmt
struct {
484 sync
.Locker
// the *driverConn
487 closeErr error
// return value of previous Close call
490 // Close ensures dirver.Stmt is only closed once any always returns the same
492 func (ds
*driverStmt
) Close() error
{
499 ds
.closeErr
= ds
.si
.Close()
503 // depSet is a finalCloser's outstanding dependencies
504 type depSet
map[interface{}]bool // set of true bools
506 // The finalCloser interface is used by (*DB).addDep and related
507 // dependency reference counting.
508 type finalCloser
interface {
509 // finalClose is called when the reference count of an object
510 // goes to zero. (*DB).mu is not held while calling it.
514 // addDep notes that x now depends on dep, and x's finalClose won't be
515 // called until all of x's dependencies are removed with removeDep.
516 func (db
*DB
) addDep(x finalCloser
, dep
interface{}) {
517 //println(fmt.Sprintf("addDep(%T %p, %T %p)", x, x, dep, dep))
520 db
.addDepLocked(x
, dep
)
523 func (db
*DB
) addDepLocked(x finalCloser
, dep
interface{}) {
525 db
.dep
= make(map[finalCloser
]depSet
)
535 // removeDep notes that x no longer depends on dep.
536 // If x still has dependencies, nil is returned.
537 // If x no longer has any dependencies, its finalClose method will be
538 // called and its error value will be returned.
539 func (db
*DB
) removeDep(x finalCloser
, dep
interface{}) error
{
541 fn
:= db
.removeDepLocked(x
, dep
)
546 func (db
*DB
) removeDepLocked(x finalCloser
, dep
interface{}) func() error
{
547 //println(fmt.Sprintf("removeDep(%T %p, %T %p)", x, x, dep, dep))
549 xdep
, ok
:= db
.dep
[x
]
551 panic(fmt
.Sprintf("unpaired removeDep: no deps for %T", x
))
559 // Nothing removed. Shouldn't happen.
560 panic(fmt
.Sprintf("unpaired removeDep: no %T dep on %T", dep
, x
))
562 // No more dependencies.
566 // Dependencies remain.
567 return func() error
{ return nil }
571 // This is the size of the connectionOpener request chan (DB.openerCh).
572 // This value should be larger than the maximum typical value
573 // used for db.maxOpen. If maxOpen is significantly larger than
574 // connectionRequestQueueSize then it is possible for ALL calls into the *DB
575 // to block until the connectionOpener can satisfy the backlog of requests.
576 var connectionRequestQueueSize
= 1000000
578 // Open opens a database specified by its database driver name and a
579 // driver-specific data source name, usually consisting of at least a
580 // database name and connection information.
582 // Most users will open a database via a driver-specific connection
583 // helper function that returns a *DB. No database drivers are included
584 // in the Go standard library. See https://golang.org/s/sqldrivers for
585 // a list of third-party drivers.
587 // Open may just validate its arguments without creating a connection
588 // to the database. To verify that the data source name is valid, call
591 // The returned DB is safe for concurrent use by multiple goroutines
592 // and maintains its own pool of idle connections. Thus, the Open
593 // function should be called just once. It is rarely necessary to
595 func Open(driverName
, dataSourceName
string) (*DB
, error
) {
597 driveri
, ok
:= drivers
[driverName
]
600 return nil, fmt
.Errorf("sql: unknown driver %q (forgotten import?)", driverName
)
605 openerCh
: make(chan struct{}, connectionRequestQueueSize
),
606 lastPut
: make(map[*driverConn
]string),
607 connRequests
: make(map[uint64]chan connRequest
),
609 go db
.connectionOpener()
613 func (db
*DB
) pingDC(ctx context
.Context
, dc
*driverConn
, release
func(error
)) error
{
615 if pinger
, ok
:= dc
.ci
.(driver
.Pinger
); ok
{
616 withLock(dc
, func() {
617 err
= pinger
.Ping(ctx
)
624 // PingContext verifies a connection to the database is still alive,
625 // establishing a connection if necessary.
626 func (db
*DB
) PingContext(ctx context
.Context
) error
{
630 for i
:= 0; i
< maxBadConnRetries
; i
++ {
631 dc
, err
= db
.conn(ctx
, cachedOrNewConn
)
632 if err
!= driver
.ErrBadConn
{
636 if err
== driver
.ErrBadConn
{
637 dc
, err
= db
.conn(ctx
, alwaysNewConn
)
643 return db
.pingDC(ctx
, dc
, dc
.releaseConn
)
646 // Ping verifies a connection to the database is still alive,
647 // establishing a connection if necessary.
648 func (db
*DB
) Ping() error
{
649 return db
.PingContext(context
.Background())
652 // Close closes the database, releasing any open resources.
654 // It is rare to Close a DB, as the DB handle is meant to be
655 // long-lived and shared between many goroutines.
656 func (db
*DB
) Close() error
{
658 if db
.closed { // Make DB.Close idempotent
663 if db
.cleanerCh
!= nil {
667 fns
:= make([]func() error
, 0, len(db
.freeConn
))
668 for _
, dc
:= range db
.freeConn
{
669 fns
= append(fns
, dc
.closeDBLocked())
673 for _
, req
:= range db
.connRequests
{
677 for _
, fn
:= range fns
{
686 const defaultMaxIdleConns
= 2
688 func (db
*DB
) maxIdleConnsLocked() int {
692 // TODO(bradfitz): ask driver, if supported, for its default preference
693 return defaultMaxIdleConns
701 // SetMaxIdleConns sets the maximum number of connections in the idle
704 // If MaxOpenConns is greater than 0 but less than the new MaxIdleConns
705 // then the new MaxIdleConns will be reduced to match the MaxOpenConns limit
707 // If n <= 0, no idle connections are retained.
708 func (db
*DB
) SetMaxIdleConns(n
int) {
713 // No idle connections.
716 // Make sure maxIdle doesn't exceed maxOpen
717 if db
.maxOpen
> 0 && db
.maxIdleConnsLocked() > db
.maxOpen
{
718 db
.maxIdle
= db
.maxOpen
720 var closing
[]*driverConn
721 idleCount
:= len(db
.freeConn
)
722 maxIdle
:= db
.maxIdleConnsLocked()
723 if idleCount
> maxIdle
{
724 closing
= db
.freeConn
[maxIdle
:]
725 db
.freeConn
= db
.freeConn
[:maxIdle
]
728 for _
, c
:= range closing
{
733 // SetMaxOpenConns sets the maximum number of open connections to the database.
735 // If MaxIdleConns is greater than 0 and the new MaxOpenConns is less than
736 // MaxIdleConns, then MaxIdleConns will be reduced to match the new
737 // MaxOpenConns limit
739 // If n <= 0, then there is no limit on the number of open connections.
740 // The default is 0 (unlimited).
741 func (db
*DB
) SetMaxOpenConns(n
int) {
747 syncMaxIdle
:= db
.maxOpen
> 0 && db
.maxIdleConnsLocked() > db
.maxOpen
750 db
.SetMaxIdleConns(n
)
754 // SetConnMaxLifetime sets the maximum amount of time a connection may be reused.
756 // Expired connections may be closed lazily before reuse.
758 // If d <= 0, connections are reused forever.
759 func (db
*DB
) SetConnMaxLifetime(d time
.Duration
) {
764 // wake cleaner up when lifetime is shortened.
765 if d
> 0 && d
< db
.maxLifetime
&& db
.cleanerCh
!= nil {
767 case db
.cleanerCh
<- struct{}{}:
772 db
.startCleanerLocked()
776 // startCleanerLocked starts connectionCleaner if needed.
777 func (db
*DB
) startCleanerLocked() {
778 if db
.maxLifetime
> 0 && db
.numOpen
> 0 && db
.cleanerCh
== nil {
779 db
.cleanerCh
= make(chan struct{}, 1)
780 go db
.connectionCleaner(db
.maxLifetime
)
784 func (db
*DB
) connectionCleaner(d time
.Duration
) {
785 const minInterval
= time
.Second
790 t
:= time
.NewTimer(d
)
795 case <-db
.cleanerCh
: // maxLifetime was changed or db was closed.
800 if db
.closed || db
.numOpen
== 0 || d
<= 0 {
806 expiredSince
:= nowFunc().Add(-d
)
807 var closing
[]*driverConn
808 for i
:= 0; i
< len(db
.freeConn
); i
++ {
810 if c
.createdAt
.Before(expiredSince
) {
811 closing
= append(closing
, c
)
812 last
:= len(db
.freeConn
) - 1
813 db
.freeConn
[i
] = db
.freeConn
[last
]
814 db
.freeConn
[last
] = nil
815 db
.freeConn
= db
.freeConn
[:last
]
821 for _
, c
:= range closing
{
832 // DBStats contains database statistics.
833 type DBStats
struct {
834 // OpenConnections is the number of open connections to the database.
838 // Stats returns database statistics.
839 func (db
*DB
) Stats() DBStats
{
842 OpenConnections
: db
.numOpen
,
848 // Assumes db.mu is locked.
849 // If there are connRequests and the connection limit hasn't been reached,
850 // then tell the connectionOpener to open new connections.
851 func (db
*DB
) maybeOpenNewConnections() {
852 numRequests
:= len(db
.connRequests
)
854 numCanOpen
:= db
.maxOpen
- db
.numOpen
855 if numRequests
> numCanOpen
{
856 numRequests
= numCanOpen
859 for numRequests
> 0 {
860 db
.numOpen
++ // optimistically
865 db
.openerCh
<- struct{}{}
869 // Runs in a separate goroutine, opens new connections when requested.
870 func (db
*DB
) connectionOpener() {
871 for range db
.openerCh
{
872 db
.openNewConnection()
876 // Open one new connection
877 func (db
*DB
) openNewConnection() {
878 // maybeOpenNewConnctions has already executed db.numOpen++ before it sent
879 // on db.openerCh. This function must execute db.numOpen-- if the
880 // connection fails or is closed before returning.
881 ci
, err
:= db
.driver
.Open(db
.dsn
)
893 db
.putConnDBLocked(nil, err
)
894 db
.maybeOpenNewConnections()
899 createdAt
: nowFunc(),
902 if db
.putConnDBLocked(dc
, err
) {
903 db
.addDepLocked(dc
, dc
)
910 // connRequest represents one request for a new connection
911 // When there are no idle connections available, DB.conn will create
912 // a new connRequest and put it on the db.connRequests list.
913 type connRequest
struct {
918 var errDBClosed
= errors
.New("sql: database is closed")
920 // nextRequestKeyLocked returns the next connection request key.
921 // It is assumed that nextRequest will not overflow.
922 func (db
*DB
) nextRequestKeyLocked() uint64 {
923 next
:= db
.nextRequest
928 // conn returns a newly-opened or cached *driverConn.
929 func (db
*DB
) conn(ctx context
.Context
, strategy connReuseStrategy
) (*driverConn
, error
) {
933 return nil, errDBClosed
935 // Check if the context is expired.
940 return nil, ctx
.Err()
942 lifetime
:= db
.maxLifetime
944 // Prefer a free connection, if possible.
945 numFree
:= len(db
.freeConn
)
946 if strategy
== cachedOrNewConn
&& numFree
> 0 {
947 conn
:= db
.freeConn
[0]
948 copy(db
.freeConn
, db
.freeConn
[1:])
949 db
.freeConn
= db
.freeConn
[:numFree
-1]
952 if conn
.expired(lifetime
) {
954 return nil, driver
.ErrBadConn
959 // Out of free connections or we were asked not to use one. If we're not
960 // allowed to open any more connections, make a request and wait.
961 if db
.maxOpen
> 0 && db
.numOpen
>= db
.maxOpen
{
962 // Make the connRequest channel. It's buffered so that the
963 // connectionOpener doesn't block while waiting for the req to be read.
964 req
:= make(chan connRequest
, 1)
965 reqKey
:= db
.nextRequestKeyLocked()
966 db
.connRequests
[reqKey
] = req
969 // Timeout the connection request with the context.
972 // Remove the connection request and ensure no value has been sent
973 // on it after removing.
975 delete(db
.connRequests
, reqKey
)
979 case ret
, ok
:= <-req
:
981 db
.putConn(ret
.conn
, ret
.err
)
984 return nil, ctx
.Err()
985 case ret
, ok
:= <-req
:
987 return nil, errDBClosed
989 if ret
.err
== nil && ret
.conn
.expired(lifetime
) {
991 return nil, driver
.ErrBadConn
993 return ret
.conn
, ret
.err
997 db
.numOpen
++ // optimistically
999 ci
, err
:= db
.driver
.Open(db
.dsn
)
1002 db
.numOpen
-- // correct for earlier optimism
1003 db
.maybeOpenNewConnections()
1010 createdAt
: nowFunc(),
1014 db
.addDepLocked(dc
, dc
)
1019 // putConnHook is a hook for testing.
1020 var putConnHook
func(*DB
, *driverConn
)
1022 // noteUnusedDriverStatement notes that ds is no longer used and should
1023 // be closed whenever possible (when c is next not in use), unless c is
1025 func (db
*DB
) noteUnusedDriverStatement(c
*driverConn
, ds
*driverStmt
) {
1027 defer db
.mu
.Unlock()
1029 c
.onPut
= append(c
.onPut
, func() {
1042 // debugGetPut determines whether getConn & putConn calls' stack traces
1043 // are returned for more verbose crashes.
1044 const debugGetPut
= false
1046 // putConn adds a connection to the db's free pool.
1047 // err is optionally the last error that occurred on this connection.
1048 func (db
*DB
) putConn(dc
*driverConn
, err error
) {
1052 fmt
.Printf("putConn(%v) DUPLICATE was: %s\n\nPREVIOUS was: %s", dc
, stack(), db
.lastPut
[dc
])
1054 panic("sql: connection returned that was never out")
1057 db
.lastPut
[dc
] = stack()
1061 for _
, fn
:= range dc
.onPut
{
1066 if err
== driver
.ErrBadConn
{
1067 // Don't reuse bad connections.
1068 // Since the conn is considered bad and is being discarded, treat it
1069 // as closed. Don't decrement the open count here, finalClose will
1070 // take care of that.
1071 db
.maybeOpenNewConnections()
1076 if putConnHook
!= nil {
1079 added
:= db
.putConnDBLocked(dc
, nil)
1087 // Satisfy a connRequest or put the driverConn in the idle pool and return true
1089 // putConnDBLocked will satisfy a connRequest if there is one, or it will
1090 // return the *driverConn to the freeConn list if err == nil and the idle
1091 // connection limit will not be exceeded.
1092 // If err != nil, the value of dc is ignored.
1093 // If err == nil, then dc must not equal nil.
1094 // If a connRequest was fulfilled or the *driverConn was placed in the
1095 // freeConn list, then true is returned, otherwise false is returned.
1096 func (db
*DB
) putConnDBLocked(dc
*driverConn
, err error
) bool {
1100 if db
.maxOpen
> 0 && db
.numOpen
> db
.maxOpen
{
1103 if c
:= len(db
.connRequests
); c
> 0 {
1104 var req
chan connRequest
1106 for reqKey
, req
= range db
.connRequests
{
1109 delete(db
.connRequests
, reqKey
) // Remove from pending requests.
1118 } else if err
== nil && !db
.closed && db
.maxIdleConnsLocked() > len(db
.freeConn
) {
1119 db
.freeConn
= append(db
.freeConn
, dc
)
1120 db
.startCleanerLocked()
1126 // maxBadConnRetries is the number of maximum retries if the driver returns
1127 // driver.ErrBadConn to signal a broken connection before forcing a new
1128 // connection to be opened.
1129 const maxBadConnRetries
= 2
1131 // PrepareContext creates a prepared statement for later queries or executions.
1132 // Multiple queries or executions may be run concurrently from the
1133 // returned statement.
1134 // The caller must call the statement's Close method
1135 // when the statement is no longer needed.
1137 // The provided context is used for the preparation of the statement, not for the
1138 // execution of the statement.
1139 func (db
*DB
) PrepareContext(ctx context
.Context
, query
string) (*Stmt
, error
) {
1142 for i
:= 0; i
< maxBadConnRetries
; i
++ {
1143 stmt
, err
= db
.prepare(ctx
, query
, cachedOrNewConn
)
1144 if err
!= driver
.ErrBadConn
{
1148 if err
== driver
.ErrBadConn
{
1149 return db
.prepare(ctx
, query
, alwaysNewConn
)
1154 // Prepare creates a prepared statement for later queries or executions.
1155 // Multiple queries or executions may be run concurrently from the
1156 // returned statement.
1157 // The caller must call the statement's Close method
1158 // when the statement is no longer needed.
1159 func (db
*DB
) Prepare(query
string) (*Stmt
, error
) {
1160 return db
.PrepareContext(context
.Background(), query
)
1163 func (db
*DB
) prepare(ctx context
.Context
, query
string, strategy connReuseStrategy
) (*Stmt
, error
) {
1164 // TODO: check if db.driver supports an optional
1165 // driver.Preparer interface and call that instead, if so,
1166 // otherwise we make a prepared statement that's bound
1167 // to a connection, and to execute this prepared statement
1168 // we either need to use this connection (if it's free), else
1169 // get a new connection + re-prepare + execute on that one.
1170 dc
, err
:= db
.conn(ctx
, strategy
)
1174 return db
.prepareDC(ctx
, dc
, dc
.releaseConn
, nil, query
)
1177 // prepareDC prepares a query on the driverConn and calls release before
1178 // returning. When cg == nil it implies that a connection pool is used, and
1179 // when cg != nil only a single driver connection is used.
1180 func (db
*DB
) prepareDC(ctx context
.Context
, dc
*driverConn
, release
func(error
), cg stmtConnGrabber
, query
string) (*Stmt
, error
) {
1186 withLock(dc
, func() {
1187 ds
, err
= dc
.prepareLocked(ctx
, cg
, query
)
1199 // When cg == nil this statement will need to keep track of various
1200 // connections they are prepared on and record the stmt dependency on
1203 stmt
.css
= []connStmt
{{dc
, ds
}}
1204 stmt
.lastNumClosed
= atomic
.LoadUint64(&db
.numClosed
)
1205 db
.addDep(stmt
, stmt
)
1210 // ExecContext executes a query without returning any rows.
1211 // The args are for any placeholder parameters in the query.
1212 func (db
*DB
) ExecContext(ctx context
.Context
, query
string, args
...interface{}) (Result
, error
) {
1215 for i
:= 0; i
< maxBadConnRetries
; i
++ {
1216 res
, err
= db
.exec(ctx
, query
, args
, cachedOrNewConn
)
1217 if err
!= driver
.ErrBadConn
{
1221 if err
== driver
.ErrBadConn
{
1222 return db
.exec(ctx
, query
, args
, alwaysNewConn
)
1227 // Exec executes a query without returning any rows.
1228 // The args are for any placeholder parameters in the query.
1229 func (db
*DB
) Exec(query
string, args
...interface{}) (Result
, error
) {
1230 return db
.ExecContext(context
.Background(), query
, args
...)
1233 func (db
*DB
) exec(ctx context
.Context
, query
string, args
[]interface{}, strategy connReuseStrategy
) (Result
, error
) {
1234 dc
, err
:= db
.conn(ctx
, strategy
)
1238 return db
.execDC(ctx
, dc
, dc
.releaseConn
, query
, args
)
1241 func (db
*DB
) execDC(ctx context
.Context
, dc
*driverConn
, release
func(error
), query
string, args
[]interface{}) (res Result
, err error
) {
1245 if execer
, ok
:= dc
.ci
.(driver
.Execer
); ok
{
1246 var dargs
[]driver
.NamedValue
1247 dargs
, err
= driverArgs(dc
.ci
, nil, args
)
1251 var resi driver
.Result
1252 withLock(dc
, func() {
1253 resi
, err
= ctxDriverExec(ctx
, execer
, query
, dargs
)
1255 if err
!= driver
.ErrSkip
{
1259 return driverResult
{dc
, resi
}, nil
1264 withLock(dc
, func() {
1265 si
, err
= ctxDriverPrepare(ctx
, dc
.ci
, query
)
1270 ds
:= &driverStmt
{Locker
: dc
, si
: si
}
1272 return resultFromStatement(ctx
, dc
.ci
, ds
, args
...)
1275 // QueryContext executes a query that returns rows, typically a SELECT.
1276 // The args are for any placeholder parameters in the query.
1277 func (db
*DB
) QueryContext(ctx context
.Context
, query
string, args
...interface{}) (*Rows
, error
) {
1280 for i
:= 0; i
< maxBadConnRetries
; i
++ {
1281 rows
, err
= db
.query(ctx
, query
, args
, cachedOrNewConn
)
1282 if err
!= driver
.ErrBadConn
{
1286 if err
== driver
.ErrBadConn
{
1287 return db
.query(ctx
, query
, args
, alwaysNewConn
)
1292 // Query executes a query that returns rows, typically a SELECT.
1293 // The args are for any placeholder parameters in the query.
1294 func (db
*DB
) Query(query
string, args
...interface{}) (*Rows
, error
) {
1295 return db
.QueryContext(context
.Background(), query
, args
...)
1298 func (db
*DB
) query(ctx context
.Context
, query
string, args
[]interface{}, strategy connReuseStrategy
) (*Rows
, error
) {
1299 dc
, err
:= db
.conn(ctx
, strategy
)
1304 return db
.queryDC(ctx
, nil, dc
, dc
.releaseConn
, query
, args
)
1307 // queryDC executes a query on the given connection.
1308 // The connection gets released by the releaseConn function.
1309 // The ctx context is from a query method and the txctx context is from an
1310 // optional transaction context.
1311 func (db
*DB
) queryDC(ctx
, txctx context
.Context
, dc
*driverConn
, releaseConn
func(error
), query
string, args
[]interface{}) (*Rows
, error
) {
1312 if queryer
, ok
:= dc
.ci
.(driver
.Queryer
); ok
{
1313 dargs
, err
:= driverArgs(dc
.ci
, nil, args
)
1318 var rowsi driver
.Rows
1319 withLock(dc
, func() {
1320 rowsi
, err
= ctxDriverQuery(ctx
, queryer
, query
, dargs
)
1322 if err
!= driver
.ErrSkip
{
1327 // Note: ownership of dc passes to the *Rows, to be freed
1328 // with releaseConn.
1331 releaseConn
: releaseConn
,
1334 rows
.initContextClose(ctx
, txctx
)
1341 withLock(dc
, func() {
1342 si
, err
= ctxDriverPrepare(ctx
, dc
.ci
, query
)
1349 ds
:= &driverStmt
{Locker
: dc
, si
: si
}
1350 rowsi
, err
:= rowsiFromStatement(ctx
, dc
.ci
, ds
, args
...)
1357 // Note: ownership of ci passes to the *Rows, to be freed
1358 // with releaseConn.
1361 releaseConn
: releaseConn
,
1365 rows
.initContextClose(ctx
, txctx
)
1369 // QueryRowContext executes a query that is expected to return at most one row.
1370 // QueryRowContext always returns a non-nil value. Errors are deferred until
1371 // Row's Scan method is called.
1372 // If the query selects no rows, the *Row's Scan will return ErrNoRows.
1373 // Otherwise, the *Row's Scan scans the first selected row and discards
1375 func (db
*DB
) QueryRowContext(ctx context
.Context
, query
string, args
...interface{}) *Row
{
1376 rows
, err
:= db
.QueryContext(ctx
, query
, args
...)
1377 return &Row
{rows
: rows
, err
: err
}
1380 // QueryRow executes a query that is expected to return at most one row.
1381 // QueryRow always returns a non-nil value. Errors are deferred until
1382 // Row's Scan method is called.
1383 // If the query selects no rows, the *Row's Scan will return ErrNoRows.
1384 // Otherwise, the *Row's Scan scans the first selected row and discards
1386 func (db
*DB
) QueryRow(query
string, args
...interface{}) *Row
{
1387 return db
.QueryRowContext(context
.Background(), query
, args
...)
1390 // BeginTx starts a transaction.
1392 // The provided context is used until the transaction is committed or rolled back.
1393 // If the context is canceled, the sql package will roll back
1394 // the transaction. Tx.Commit will return an error if the context provided to
1395 // BeginTx is canceled.
1397 // The provided TxOptions is optional and may be nil if defaults should be used.
1398 // If a non-default isolation level is used that the driver doesn't support,
1399 // an error will be returned.
1400 func (db
*DB
) BeginTx(ctx context
.Context
, opts
*TxOptions
) (*Tx
, error
) {
1403 for i
:= 0; i
< maxBadConnRetries
; i
++ {
1404 tx
, err
= db
.begin(ctx
, opts
, cachedOrNewConn
)
1405 if err
!= driver
.ErrBadConn
{
1409 if err
== driver
.ErrBadConn
{
1410 return db
.begin(ctx
, opts
, alwaysNewConn
)
1415 // Begin starts a transaction. The default isolation level is dependent on
1417 func (db
*DB
) Begin() (*Tx
, error
) {
1418 return db
.BeginTx(context
.Background(), nil)
1421 func (db
*DB
) begin(ctx context
.Context
, opts
*TxOptions
, strategy connReuseStrategy
) (tx
*Tx
, err error
) {
1422 dc
, err
:= db
.conn(ctx
, strategy
)
1426 return db
.beginDC(ctx
, dc
, dc
.releaseConn
, opts
)
1429 // beginDC starts a transaction. The provided dc must be valid and ready to use.
1430 func (db
*DB
) beginDC(ctx context
.Context
, dc
*driverConn
, release
func(error
), opts
*TxOptions
) (tx
*Tx
, err error
) {
1432 withLock(dc
, func() {
1433 txi
, err
= ctxDriverBegin(ctx
, opts
, dc
.ci
)
1440 // Schedule the transaction to rollback when the context is cancelled.
1441 // The cancel function in Tx will be called after done is set to true.
1442 ctx
, cancel
:= context
.WithCancel(ctx
)
1446 releaseConn
: release
,
1455 // Driver returns the database's underlying driver.
1456 func (db
*DB
) Driver() driver
.Driver
{
1460 // ErrConnDone is returned by any operation that is performed on a connection
1461 // that has already been committed or rolled back.
1462 var ErrConnDone
= errors
.New("database/sql: connection is already closed")
1464 // Conn returns a single connection by either opening a new connection
1465 // or returning an existing connection from the connection pool. Conn will
1466 // block until either a connection is returned or ctx is canceled.
1467 // Queries run on the same Conn will be run in the same database session.
1469 // Every Conn must be returned to the database pool after use by
1470 // calling Conn.Close.
1471 func (db
*DB
) Conn(ctx context
.Context
) (*Conn
, error
) {
1474 for i
:= 0; i
< maxBadConnRetries
; i
++ {
1475 dc
, err
= db
.conn(ctx
, cachedOrNewConn
)
1476 if err
!= driver
.ErrBadConn
{
1480 if err
== driver
.ErrBadConn
{
1481 dc
, err
= db
.conn(ctx
, cachedOrNewConn
)
1494 type releaseConn
func(error
)
1496 // Conn represents a single database session rather a pool of database
1497 // sessions. Prefer running queries from DB unless there is a specific
1498 // need for a continuous single database session.
1500 // A Conn must call Close to return the connection to the database pool
1501 // and may do so concurrently with a running query.
1503 // After a call to Close, all operations on the
1504 // connection fail with ErrConnDone.
1508 // closemu prevents the connection from closing while there
1509 // is an active query. It is held for read during queries
1510 // and exclusively during close.
1511 closemu sync
.RWMutex
1513 // dc is owned until close, at which point
1514 // it's returned to the connection pool.
1517 // done transitions from 0 to 1 exactly once, on close.
1518 // Once done, all operations fail with ErrConnDone.
1519 // Use atomic operations on value when checking value.
1523 func (c
*Conn
) grabConn(context
.Context
) (*driverConn
, releaseConn
, error
) {
1524 if atomic
.LoadInt32(&c
.done
) != 0 {
1525 return nil, nil, ErrConnDone
1528 return c
.dc
, c
.closemuRUnlockCondReleaseConn
, nil
1531 // PingContext verifies the connection to the database is still alive.
1532 func (c
*Conn
) PingContext(ctx context
.Context
) error
{
1533 dc
, release
, err
:= c
.grabConn(ctx
)
1537 return c
.db
.pingDC(ctx
, dc
, release
)
1540 // ExecContext executes a query without returning any rows.
1541 // The args are for any placeholder parameters in the query.
1542 func (c
*Conn
) ExecContext(ctx context
.Context
, query
string, args
...interface{}) (Result
, error
) {
1543 dc
, release
, err
:= c
.grabConn(ctx
)
1547 return c
.db
.execDC(ctx
, dc
, release
, query
, args
)
1550 // QueryContext executes a query that returns rows, typically a SELECT.
1551 // The args are for any placeholder parameters in the query.
1552 func (c
*Conn
) QueryContext(ctx context
.Context
, query
string, args
...interface{}) (*Rows
, error
) {
1553 dc
, release
, err
:= c
.grabConn(ctx
)
1557 return c
.db
.queryDC(ctx
, nil, dc
, release
, query
, args
)
1560 // QueryRowContext executes a query that is expected to return at most one row.
1561 // QueryRowContext always returns a non-nil value. Errors are deferred until
1562 // Row's Scan method is called.
1563 // If the query selects no rows, the *Row's Scan will return ErrNoRows.
1564 // Otherwise, the *Row's Scan scans the first selected row and discards
1566 func (c
*Conn
) QueryRowContext(ctx context
.Context
, query
string, args
...interface{}) *Row
{
1567 rows
, err
:= c
.QueryContext(ctx
, query
, args
...)
1568 return &Row
{rows
: rows
, err
: err
}
1571 // PrepareContext creates a prepared statement for later queries or executions.
1572 // Multiple queries or executions may be run concurrently from the
1573 // returned statement.
1574 // The caller must call the statement's Close method
1575 // when the statement is no longer needed.
1577 // The provided context is used for the preparation of the statement, not for the
1578 // execution of the statement.
1579 func (c
*Conn
) PrepareContext(ctx context
.Context
, query
string) (*Stmt
, error
) {
1580 dc
, release
, err
:= c
.grabConn(ctx
)
1584 return c
.db
.prepareDC(ctx
, dc
, release
, c
, query
)
1587 // BeginTx starts a transaction.
1589 // The provided context is used until the transaction is committed or rolled back.
1590 // If the context is canceled, the sql package will roll back
1591 // the transaction. Tx.Commit will return an error if the context provided to
1592 // BeginTx is canceled.
1594 // The provided TxOptions is optional and may be nil if defaults should be used.
1595 // If a non-default isolation level is used that the driver doesn't support,
1596 // an error will be returned.
1597 func (c
*Conn
) BeginTx(ctx context
.Context
, opts
*TxOptions
) (*Tx
, error
) {
1598 dc
, release
, err
:= c
.grabConn(ctx
)
1602 return c
.db
.beginDC(ctx
, dc
, release
, opts
)
1605 // closemuRUnlockCondReleaseConn read unlocks closemu
1606 // as the sql operation is done with the dc.
1607 func (c
*Conn
) closemuRUnlockCondReleaseConn(err error
) {
1609 if err
== driver
.ErrBadConn
{
1614 func (c
*Conn
) txCtx() context
.Context
{
1618 func (c
*Conn
) close(err error
) error
{
1619 if !atomic
.CompareAndSwapInt32(&c
.done
, 0, 1) {
1623 // Lock around releasing the driver connection
1624 // to ensure all queries have been stopped before doing so.
1626 defer c
.closemu
.Unlock()
1628 c
.dc
.releaseConn(err
)
1634 // Close returns the connection to the connection pool.
1635 // All operations after a Close will return with ErrConnDone.
1636 // Close is safe to call concurrently with other operations and will
1637 // block until all other operations finish. It may be useful to first
1638 // cancel any used context and then call close directly after.
1639 func (c
*Conn
) Close() error
{
1643 // Tx is an in-progress database transaction.
1645 // A transaction must end with a call to Commit or Rollback.
1647 // After a call to Commit or Rollback, all operations on the
1648 // transaction fail with ErrTxDone.
1650 // The statements prepared for a transaction by calling
1651 // the transaction's Prepare or Stmt methods are closed
1652 // by the call to Commit or Rollback.
1656 // closemu prevents the transaction from closing while there
1657 // is an active query. It is held for read during queries
1658 // and exclusively during close.
1659 closemu sync
.RWMutex
1661 // dc is owned exclusively until Commit or Rollback, at which point
1662 // it's returned with putConn.
1666 // releaseConn is called once the Tx is closed to release
1667 // any held driverConn back to the pool.
1668 releaseConn
func(error
)
1670 // done transitions from 0 to 1 exactly once, on Commit
1671 // or Rollback. once done, all operations fail with
1673 // Use atomic operations on value when checking value.
1676 // All Stmts prepared for this transaction. These will be closed after the
1677 // transaction has been committed or rolled back.
1683 // cancel is called after done transitions from 0 to 1.
1686 // ctx lives for the life of the transaction.
1690 // awaitDone blocks until the context in Tx is canceled and rolls back
1691 // the transaction if it's not already done.
1692 func (tx
*Tx
) awaitDone() {
1693 // Wait for either the transaction to be committed or rolled
1694 // back, or for the associated context to be closed.
1697 // Discard and close the connection used to ensure the
1698 // transaction is closed and the resources are released. This
1699 // rollback does nothing if the transaction has already been
1700 // committed or rolled back.
1704 func (tx
*Tx
) isDone() bool {
1705 return atomic
.LoadInt32(&tx
.done
) != 0
1708 // ErrTxDone is returned by any operation that is performed on a transaction
1709 // that has already been committed or rolled back.
1710 var ErrTxDone
= errors
.New("sql: Transaction has already been committed or rolled back")
1712 // close returns the connection to the pool and
1713 // must only be called by Tx.rollback or Tx.Commit.
1714 func (tx
*Tx
) close(err error
) {
1718 defer tx
.closemu
.Unlock()
1725 // hookTxGrabConn specifies an optional hook to be called on
1726 // a successful call to (*Tx).grabConn. For tests.
1727 var hookTxGrabConn
func()
1729 func (tx
*Tx
) grabConn(ctx context
.Context
) (*driverConn
, releaseConn
, error
) {
1733 return nil, nil, ctx
.Err()
1736 // closeme.RLock must come before the check for isDone to prevent the Tx from
1737 // closing while a query is executing.
1740 tx
.closemu
.RUnlock()
1741 return nil, nil, ErrTxDone
1743 if hookTxGrabConn
!= nil { // test hook
1746 return tx
.dc
, tx
.closemuRUnlockRelease
, nil
1749 func (tx
*Tx
) txCtx() context
.Context
{
1753 // closemuRUnlockRelease is used as a func(error) method value in
1754 // ExecContext and QueryContext. Unlocking in the releaseConn keeps
1755 // the driver conn from being returned to the connection pool until
1756 // the Rows has been closed.
1757 func (tx
*Tx
) closemuRUnlockRelease(error
) {
1758 tx
.closemu
.RUnlock()
1761 // Closes all Stmts prepared for this transaction.
1762 func (tx
*Tx
) closePrepared() {
1764 defer tx
.stmts
.Unlock()
1765 for _
, stmt
:= range tx
.stmts
.v
{
1770 // Commit commits the transaction.
1771 func (tx
*Tx
) Commit() error
{
1772 if !atomic
.CompareAndSwapInt32(&tx
.done
, 0, 1) {
1777 case <-tx
.ctx
.Done():
1781 withLock(tx
.dc
, func() {
1782 err
= tx
.txi
.Commit()
1784 if err
!= driver
.ErrBadConn
{
1791 // rollback aborts the transaction and optionally forces the pool to discard
1793 func (tx
*Tx
) rollback(discardConn
bool) error
{
1794 if !atomic
.CompareAndSwapInt32(&tx
.done
, 0, 1) {
1798 withLock(tx
.dc
, func() {
1799 err
= tx
.txi
.Rollback()
1801 if err
!= driver
.ErrBadConn
{
1805 err
= driver
.ErrBadConn
1811 // Rollback aborts the transaction.
1812 func (tx
*Tx
) Rollback() error
{
1813 return tx
.rollback(false)
1816 // PrepareContext creates a prepared statement for use within a transaction.
1818 // The returned statement operates within the transaction and will be closed
1819 // when the transaction has been committed or rolled back.
1821 // To use an existing prepared statement on this transaction, see Tx.Stmt.
1823 // The provided context will be used for the preparation of the context, not
1824 // for the execution of the returned statement. The returned statement
1825 // will run in the transaction context.
1826 func (tx
*Tx
) PrepareContext(ctx context
.Context
, query
string) (*Stmt
, error
) {
1827 dc
, release
, err
:= tx
.grabConn(ctx
)
1832 stmt
, err
:= tx
.db
.prepareDC(ctx
, dc
, release
, tx
, query
)
1837 tx
.stmts
.v
= append(tx
.stmts
.v
, stmt
)
1842 // Prepare creates a prepared statement for use within a transaction.
1844 // The returned statement operates within the transaction and can no longer
1845 // be used once the transaction has been committed or rolled back.
1847 // To use an existing prepared statement on this transaction, see Tx.Stmt.
1848 func (tx
*Tx
) Prepare(query
string) (*Stmt
, error
) {
1849 return tx
.PrepareContext(context
.Background(), query
)
1852 // StmtContext returns a transaction-specific prepared statement from
1853 // an existing statement.
1856 // updateMoney, err := db.Prepare("UPDATE balance SET money=money+? WHERE id=?")
1858 // tx, err := db.Begin()
1860 // res, err := tx.StmtContext(ctx, updateMoney).Exec(123.45, 98293203)
1862 // The returned statement operates within the transaction and will be closed
1863 // when the transaction has been committed or rolled back.
1864 func (tx
*Tx
) StmtContext(ctx context
.Context
, stmt
*Stmt
) *Stmt
{
1865 dc
, release
, err
:= tx
.grabConn(ctx
)
1867 return &Stmt
{stickyErr
: err
}
1871 if tx
.db
!= stmt
.db
{
1872 return &Stmt
{stickyErr
: errors
.New("sql: Tx.Stmt: statement from different database used")}
1875 var parentStmt
*Stmt
1877 if stmt
.closed || stmt
.cg
!= nil {
1878 // If the statement has been closed or already belongs to a
1879 // transaction, we can't reuse it in this connection.
1880 // Since tx.StmtContext should never need to be called with a
1881 // Stmt already belonging to tx, we ignore this edge case and
1882 // re-prepare the statement in this case. No need to add
1883 // code-complexity for this.
1885 withLock(dc
, func() {
1886 si
, err
= ctxDriverPrepare(ctx
, dc
.ci
, stmt
.query
)
1889 return &Stmt
{stickyErr
: err
}
1892 stmt
.removeClosedStmtLocked()
1893 // See if the statement has already been prepared on this connection,
1894 // and reuse it if possible.
1895 for _
, v
:= range stmt
.css
{
1905 cs
, err
:= stmt
.prepareOnConnLocked(ctx
, dc
)
1907 return &Stmt
{stickyErr
: err
}
1921 parentStmt
: parentStmt
,
1924 if parentStmt
!= nil {
1925 tx
.db
.addDep(parentStmt
, txs
)
1928 tx
.stmts
.v
= append(tx
.stmts
.v
, txs
)
1933 // Stmt returns a transaction-specific prepared statement from
1934 // an existing statement.
1937 // updateMoney, err := db.Prepare("UPDATE balance SET money=money+? WHERE id=?")
1939 // tx, err := db.Begin()
1941 // res, err := tx.Stmt(updateMoney).Exec(123.45, 98293203)
1943 // The returned statement operates within the transaction and will be closed
1944 // when the transaction has been committed or rolled back.
1945 func (tx
*Tx
) Stmt(stmt
*Stmt
) *Stmt
{
1946 return tx
.StmtContext(context
.Background(), stmt
)
1949 // ExecContext executes a query that doesn't return rows.
1950 // For example: an INSERT and UPDATE.
1951 func (tx
*Tx
) ExecContext(ctx context
.Context
, query
string, args
...interface{}) (Result
, error
) {
1952 dc
, release
, err
:= tx
.grabConn(ctx
)
1956 return tx
.db
.execDC(ctx
, dc
, release
, query
, args
)
1959 // Exec executes a query that doesn't return rows.
1960 // For example: an INSERT and UPDATE.
1961 func (tx
*Tx
) Exec(query
string, args
...interface{}) (Result
, error
) {
1962 return tx
.ExecContext(context
.Background(), query
, args
...)
1965 // QueryContext executes a query that returns rows, typically a SELECT.
1966 func (tx
*Tx
) QueryContext(ctx context
.Context
, query
string, args
...interface{}) (*Rows
, error
) {
1967 dc
, release
, err
:= tx
.grabConn(ctx
)
1972 return tx
.db
.queryDC(ctx
, tx
.ctx
, dc
, release
, query
, args
)
1975 // Query executes a query that returns rows, typically a SELECT.
1976 func (tx
*Tx
) Query(query
string, args
...interface{}) (*Rows
, error
) {
1977 return tx
.QueryContext(context
.Background(), query
, args
...)
1980 // QueryRowContext executes a query that is expected to return at most one row.
1981 // QueryRowContext always returns a non-nil value. Errors are deferred until
1982 // Row's Scan method is called.
1983 // If the query selects no rows, the *Row's Scan will return ErrNoRows.
1984 // Otherwise, the *Row's Scan scans the first selected row and discards
1986 func (tx
*Tx
) QueryRowContext(ctx context
.Context
, query
string, args
...interface{}) *Row
{
1987 rows
, err
:= tx
.QueryContext(ctx
, query
, args
...)
1988 return &Row
{rows
: rows
, err
: err
}
1991 // QueryRow executes a query that is expected to return at most one row.
1992 // QueryRow always returns a non-nil value. Errors are deferred until
1993 // Row's Scan method is called.
1994 // If the query selects no rows, the *Row's Scan will return ErrNoRows.
1995 // Otherwise, the *Row's Scan scans the first selected row and discards
1997 func (tx
*Tx
) QueryRow(query
string, args
...interface{}) *Row
{
1998 return tx
.QueryRowContext(context
.Background(), query
, args
...)
2001 // connStmt is a prepared statement on a particular connection.
2002 type connStmt
struct {
2007 // stmtConnGrabber represents a Tx or Conn that will return the underlying
2008 // driverConn and release function.
2009 type stmtConnGrabber
interface {
2010 // grabConn returns the driverConn and the associated release function
2011 // that must be called when the operation completes.
2012 grabConn(context
.Context
) (*driverConn
, releaseConn
, error
)
2014 // txCtx returns the transaction context if available.
2015 // The returned context should be selected on along with
2016 // any query context when awaiting a cancel.
2017 txCtx() context
.Context
2021 _ stmtConnGrabber
= &Tx
{}
2022 _ stmtConnGrabber
= &Conn
{}
2025 // Stmt is a prepared statement.
2026 // A Stmt is safe for concurrent use by multiple goroutines.
2029 db
*DB
// where we came from
2030 query
string // that created the Stmt
2031 stickyErr error
// if non-nil, this error is returned for all operations
2033 closemu sync
.RWMutex
// held exclusively during close, for read otherwise.
2035 // If Stmt is prepared on a Tx or Conn then cg is present and will
2036 // only ever grab a connection from cg.
2037 // If cg is nil then the Stmt must grab an arbitrary connection
2038 // from db and determine if it must prepare the stmt again by
2043 // parentStmt is set when a transaction-specific statement
2044 // is requested from an identical statement prepared on the same
2045 // conn. parentStmt is used to track the dependency of this statement
2046 // on its originating ("parent") statement so that parentStmt may
2047 // be closed by the user without them having to know whether or not
2048 // any transactions are still using it.
2051 mu sync
.Mutex
// protects the rest of the fields
2054 // css is a list of underlying driver statement interfaces
2055 // that are valid on particular connections. This is only
2056 // used if cg == nil and one is found that has idle
2057 // connections. If cg != nil, cgds is always used.
2060 // lastNumClosed is copied from db.numClosed when Stmt is created
2061 // without tx and closed connections in css are removed.
2062 lastNumClosed
uint64
2065 // ExecContext executes a prepared statement with the given arguments and
2066 // returns a Result summarizing the effect of the statement.
2067 func (s
*Stmt
) ExecContext(ctx context
.Context
, args
...interface{}) (Result
, error
) {
2069 defer s
.closemu
.RUnlock()
2072 strategy
:= cachedOrNewConn
2073 for i
:= 0; i
< maxBadConnRetries
+1; i
++ {
2074 if i
== maxBadConnRetries
{
2075 strategy
= alwaysNewConn
2077 dc
, releaseConn
, ds
, err
:= s
.connStmt(ctx
, strategy
)
2079 if err
== driver
.ErrBadConn
{
2085 res
, err
= resultFromStatement(ctx
, dc
.ci
, ds
, args
...)
2087 if err
!= driver
.ErrBadConn
{
2091 return nil, driver
.ErrBadConn
2094 // Exec executes a prepared statement with the given arguments and
2095 // returns a Result summarizing the effect of the statement.
2096 func (s
*Stmt
) Exec(args
...interface{}) (Result
, error
) {
2097 return s
.ExecContext(context
.Background(), args
...)
2100 func resultFromStatement(ctx context
.Context
, ci driver
.Conn
, ds
*driverStmt
, args
...interface{}) (Result
, error
) {
2101 dargs
, err
:= driverArgs(ci
, ds
, args
)
2109 resi
, err
:= ctxDriverStmtExec(ctx
, ds
.si
, dargs
)
2113 return driverResult
{ds
.Locker
, resi
}, nil
2116 // removeClosedStmtLocked removes closed conns in s.css.
2118 // To avoid lock contention on DB.mu, we do it only when
2119 // s.db.numClosed - s.lastNum is large enough.
2120 func (s
*Stmt
) removeClosedStmtLocked() {
2121 t
:= len(s
.css
)/2 + 1
2125 dbClosed
:= atomic
.LoadUint64(&s
.db
.numClosed
)
2126 if dbClosed
-s
.lastNumClosed
< uint64(t
) {
2131 for i
:= 0; i
< len(s
.css
); i
++ {
2132 if s
.css
[i
].dc
.dbmuClosed
{
2133 s
.css
[i
] = s
.css
[len(s
.css
)-1]
2134 s
.css
= s
.css
[:len(s
.css
)-1]
2139 s
.lastNumClosed
= dbClosed
2142 // connStmt returns a free driver connection on which to execute the
2143 // statement, a function to call to release the connection, and a
2144 // statement bound to that connection.
2145 func (s
*Stmt
) connStmt(ctx context
.Context
, strategy connReuseStrategy
) (dc
*driverConn
, releaseConn
func(error
), ds
*driverStmt
, err error
) {
2146 if err
= s
.stickyErr
; err
!= nil {
2152 err
= errors
.New("sql: statement is closed")
2156 // In a transaction or connection, we always use the connection that the
2157 // the stmt was created on.
2160 dc
, releaseConn
, err
= s
.cg
.grabConn(ctx
) // blocks, waiting for the connection.
2164 return dc
, releaseConn
, s
.cgds
, nil
2167 s
.removeClosedStmtLocked()
2170 dc
, err
= s
.db
.conn(ctx
, strategy
)
2172 return nil, nil, nil, err
2176 for _
, v
:= range s
.css
{
2179 return dc
, dc
.releaseConn
, v
.ds
, nil
2184 // No luck; we need to prepare the statement on this connection
2185 withLock(dc
, func() {
2186 ds
, err
= s
.prepareOnConnLocked(ctx
, dc
)
2190 return nil, nil, nil, err
2193 return dc
, dc
.releaseConn
, ds
, nil
2196 // prepareOnConnLocked prepares the query in Stmt s on dc and adds it to the list of
2197 // open connStmt on the statement. It assumes the caller is holding the lock on dc.
2198 func (s
*Stmt
) prepareOnConnLocked(ctx context
.Context
, dc
*driverConn
) (*driverStmt
, error
) {
2199 si
, err
:= dc
.prepareLocked(ctx
, s
.cg
, s
.query
)
2203 cs
:= connStmt
{dc
, si
}
2205 s
.css
= append(s
.css
, cs
)
2210 // QueryContext executes a prepared query statement with the given arguments
2211 // and returns the query results as a *Rows.
2212 func (s
*Stmt
) QueryContext(ctx context
.Context
, args
...interface{}) (*Rows
, error
) {
2214 defer s
.closemu
.RUnlock()
2216 var rowsi driver
.Rows
2217 strategy
:= cachedOrNewConn
2218 for i
:= 0; i
< maxBadConnRetries
+1; i
++ {
2219 if i
== maxBadConnRetries
{
2220 strategy
= alwaysNewConn
2222 dc
, releaseConn
, ds
, err
:= s
.connStmt(ctx
, strategy
)
2224 if err
== driver
.ErrBadConn
{
2230 rowsi
, err
= rowsiFromStatement(ctx
, dc
.ci
, ds
, args
...)
2232 // Note: ownership of ci passes to the *Rows, to be freed
2233 // with releaseConn.
2237 // releaseConn set below
2239 // addDep must be added before initContextClose or it could attempt
2240 // to removeDep before it has been added.
2241 s
.db
.addDep(s
, rows
)
2243 // releaseConn must be set before initContextClose or it could
2244 // release the connection before it is set.
2245 rows
.releaseConn
= func(err error
) {
2247 s
.db
.removeDep(s
, rows
)
2249 var txctx context
.Context
2251 txctx
= s
.cg
.txCtx()
2253 rows
.initContextClose(ctx
, txctx
)
2258 if err
!= driver
.ErrBadConn
{
2262 return nil, driver
.ErrBadConn
2265 // Query executes a prepared query statement with the given arguments
2266 // and returns the query results as a *Rows.
2267 func (s
*Stmt
) Query(args
...interface{}) (*Rows
, error
) {
2268 return s
.QueryContext(context
.Background(), args
...)
2271 func rowsiFromStatement(ctx context
.Context
, ci driver
.Conn
, ds
*driverStmt
, args
...interface{}) (driver
.Rows
, error
) {
2273 withLock(ds
, func() {
2274 want
= ds
.si
.NumInput()
2277 // -1 means the driver doesn't know how to count the number of
2278 // placeholders, so we won't sanity check input here and instead let the
2279 // driver deal with errors.
2280 if want
!= -1 && len(args
) != want
{
2281 return nil, fmt
.Errorf("sql: statement expects %d inputs; got %d", want
, len(args
))
2284 dargs
, err
:= driverArgs(ci
, ds
, args
)
2292 rowsi
, err
:= ctxDriverStmtQuery(ctx
, ds
.si
, dargs
)
2299 // QueryRowContext executes a prepared query statement with the given arguments.
2300 // If an error occurs during the execution of the statement, that error will
2301 // be returned by a call to Scan on the returned *Row, which is always non-nil.
2302 // If the query selects no rows, the *Row's Scan will return ErrNoRows.
2303 // Otherwise, the *Row's Scan scans the first selected row and discards
2309 // err := nameByUseridStmt.QueryRowContext(ctx, id).Scan(&name)
2310 func (s
*Stmt
) QueryRowContext(ctx context
.Context
, args
...interface{}) *Row
{
2311 rows
, err
:= s
.QueryContext(ctx
, args
...)
2313 return &Row
{err
: err
}
2315 return &Row
{rows
: rows
}
2318 // QueryRow executes a prepared query statement with the given arguments.
2319 // If an error occurs during the execution of the statement, that error will
2320 // be returned by a call to Scan on the returned *Row, which is always non-nil.
2321 // If the query selects no rows, the *Row's Scan will return ErrNoRows.
2322 // Otherwise, the *Row's Scan scans the first selected row and discards
2328 // err := nameByUseridStmt.QueryRow(id).Scan(&name)
2329 func (s
*Stmt
) QueryRow(args
...interface{}) *Row
{
2330 return s
.QueryRowContext(context
.Background(), args
...)
2333 // Close closes the statement.
2334 func (s
*Stmt
) Close() error
{
2336 defer s
.closemu
.Unlock()
2338 if s
.stickyErr
!= nil {
2353 return s
.db
.removeDep(s
, s
)
2356 if s
.parentStmt
!= nil {
2357 // If parentStmt is set, we must not close s.txds since it's stored
2358 // in the css array of the parentStmt.
2359 return s
.db
.removeDep(s
.parentStmt
, s
)
2364 func (s
*Stmt
) finalClose() error
{
2368 for _
, v
:= range s
.css
{
2369 s
.db
.noteUnusedDriverStatement(v
.dc
, v
.ds
)
2370 v
.dc
.removeOpenStmt(v
.ds
)
2377 // Rows is the result of a query. Its cursor starts before the first row
2378 // of the result set. Use Next to advance through the rows:
2380 // rows, err := db.Query("SELECT ...")
2382 // defer rows.Close()
2383 // for rows.Next() {
2386 // err = rows.Scan(&id, &name)
2389 // err = rows.Err() // get any error encountered during iteration
2392 dc
*driverConn
// owned; must call releaseConn when closed to release
2393 releaseConn
func(error
)
2395 cancel
func() // called when Rows is closed, may be nil.
2396 closeStmt
*driverStmt
// if non-nil, statement to Close on close
2398 // closemu prevents Rows from closing while there
2399 // is an active streaming result. It is held for read during non-close operations
2400 // and exclusively during close.
2402 // closemu guards lasterr and closed.
2403 closemu sync
.RWMutex
2405 lasterr error
// non-nil only if closed is true
2407 // lastcols is only used in Scan, Next, and NextResultSet which are expected
2408 // not to be called concurrently.
2409 lastcols
[]driver
.Value
2412 func (rs
*Rows
) initContextClose(ctx
, txctx context
.Context
) {
2413 ctx
, rs
.cancel
= context
.WithCancel(ctx
)
2414 go rs
.awaitDone(ctx
, txctx
)
2417 // awaitDone blocks until either ctx or txctx is canceled. The ctx is provided
2418 // from the query context and is canceled when the query Rows is closed.
2419 // If the query was issued in a transaction, the transaction's context
2420 // is also provided in txctx to ensure Rows is closed if the Tx is closed.
2421 func (rs
*Rows
) awaitDone(ctx
, txctx context
.Context
) {
2422 var txctxDone
<-chan struct{}
2424 txctxDone
= txctx
.Done()
2433 // Next prepares the next result row for reading with the Scan method. It
2434 // returns true on success, or false if there is no next result row or an error
2435 // happened while preparing it. Err should be consulted to distinguish between
2438 // Every call to Scan, even the first one, must be preceded by a call to Next.
2439 func (rs
*Rows
) Next() bool {
2440 var doClose
, ok
bool
2441 withLock(rs
.closemu
.RLocker(), func() {
2442 doClose
, ok
= rs
.nextLocked()
2450 func (rs
*Rows
) nextLocked() (doClose
, ok
bool) {
2454 if rs
.lastcols
== nil {
2455 rs
.lastcols
= make([]driver
.Value
, len(rs
.rowsi
.Columns()))
2457 rs
.lasterr
= rs
.rowsi
.Next(rs
.lastcols
)
2458 if rs
.lasterr
!= nil {
2459 // Close the connection if there is a driver error.
2460 if rs
.lasterr
!= io
.EOF
{
2463 nextResultSet
, ok
:= rs
.rowsi
.(driver
.RowsNextResultSet
)
2467 // The driver is at the end of the current result set.
2468 // Test to see if there is another result set after the current one.
2469 // Only close Rows if there is no further result sets to read.
2470 if !nextResultSet
.HasNextResultSet() {
2473 return doClose
, false
2478 // NextResultSet prepares the next result set for reading. It returns true if
2479 // there is further result sets, or false if there is no further result set
2480 // or if there is an error advancing to it. The Err method should be consulted
2481 // to distinguish between the two cases.
2483 // After calling NextResultSet, the Next method should always be called before
2484 // scanning. If there are further result sets they may not have rows in the result
2486 func (rs
*Rows
) NextResultSet() bool {
2494 defer rs
.closemu
.RUnlock()
2501 nextResultSet
, ok
:= rs
.rowsi
.(driver
.RowsNextResultSet
)
2506 rs
.lasterr
= nextResultSet
.NextResultSet()
2507 if rs
.lasterr
!= nil {
2514 // Err returns the error, if any, that was encountered during iteration.
2515 // Err may be called after an explicit or implicit Close.
2516 func (rs
*Rows
) Err() error
{
2518 defer rs
.closemu
.RUnlock()
2519 if rs
.lasterr
== io
.EOF
{
2525 // Columns returns the column names.
2526 // Columns returns an error if the rows are closed, or if the rows
2527 // are from QueryRow and there was a deferred error.
2528 func (rs
*Rows
) Columns() ([]string, error
) {
2530 defer rs
.closemu
.RUnlock()
2532 return nil, errors
.New("sql: Rows are closed")
2534 if rs
.rowsi
== nil {
2535 return nil, errors
.New("sql: no Rows available")
2537 return rs
.rowsi
.Columns(), nil
2540 // ColumnTypes returns column information such as column type, length,
2541 // and nullable. Some information may not be available from some drivers.
2542 func (rs
*Rows
) ColumnTypes() ([]*ColumnType
, error
) {
2544 defer rs
.closemu
.RUnlock()
2546 return nil, errors
.New("sql: Rows are closed")
2548 if rs
.rowsi
== nil {
2549 return nil, errors
.New("sql: no Rows available")
2551 return rowsColumnInfoSetup(rs
.rowsi
), nil
2554 // ColumnType contains the name and type of a column.
2555 type ColumnType
struct {
2560 hasPrecisionScale
bool
2567 scanType reflect
.Type
2570 // Name returns the name or alias of the column.
2571 func (ci
*ColumnType
) Name() string {
2575 // Length returns the column type length for variable length column types such
2576 // as text and binary field types. If the type length is unbounded the value will
2577 // be math.MaxInt64 (any database limits will still apply).
2578 // If the column type is not variable length, such as an int, or if not supported
2579 // by the driver ok is false.
2580 func (ci
*ColumnType
) Length() (length
int64, ok
bool) {
2581 return ci
.length
, ci
.hasLength
2584 // DecimalSize returns the scale and precision of a decimal type.
2585 // If not applicable or if not supported ok is false.
2586 func (ci
*ColumnType
) DecimalSize() (precision
, scale
int64, ok
bool) {
2587 return ci
.precision
, ci
.scale
, ci
.hasPrecisionScale
2590 // ScanType returns a Go type suitable for scanning into using Rows.Scan.
2591 // If a driver does not support this property ScanType will return
2592 // the type of an empty interface.
2593 func (ci
*ColumnType
) ScanType() reflect
.Type
{
2597 // Nullable returns whether the column may be null.
2598 // If a driver does not support this property ok will be false.
2599 func (ci
*ColumnType
) Nullable() (nullable
, ok
bool) {
2600 return ci
.nullable
, ci
.hasNullable
2603 // DatabaseTypeName returns the database system name of the column type. If an empty
2604 // string is returned the driver type name is not supported.
2605 // Consult your driver documentation for a list of driver data types. Length specifiers
2606 // are not included.
2607 // Common type include "VARCHAR", "TEXT", "NVARCHAR", "DECIMAL", "BOOL", "INT", "BIGINT".
2608 func (ci
*ColumnType
) DatabaseTypeName() string {
2609 return ci
.databaseType
2612 func rowsColumnInfoSetup(rowsi driver
.Rows
) []*ColumnType
{
2613 names
:= rowsi
.Columns()
2615 list
:= make([]*ColumnType
, len(names
))
2616 for i
:= range list
{
2622 if prop
, ok
:= rowsi
.(driver
.RowsColumnTypeScanType
); ok
{
2623 ci
.scanType
= prop
.ColumnTypeScanType(i
)
2625 ci
.scanType
= reflect
.TypeOf(new(interface{})).Elem()
2627 if prop
, ok
:= rowsi
.(driver
.RowsColumnTypeDatabaseTypeName
); ok
{
2628 ci
.databaseType
= prop
.ColumnTypeDatabaseTypeName(i
)
2630 if prop
, ok
:= rowsi
.(driver
.RowsColumnTypeLength
); ok
{
2631 ci
.length
, ci
.hasLength
= prop
.ColumnTypeLength(i
)
2633 if prop
, ok
:= rowsi
.(driver
.RowsColumnTypeNullable
); ok
{
2634 ci
.nullable
, ci
.hasNullable
= prop
.ColumnTypeNullable(i
)
2636 if prop
, ok
:= rowsi
.(driver
.RowsColumnTypePrecisionScale
); ok
{
2637 ci
.precision
, ci
.scale
, ci
.hasPrecisionScale
= prop
.ColumnTypePrecisionScale(i
)
2643 // Scan copies the columns in the current row into the values pointed
2644 // at by dest. The number of values in dest must be the same as the
2645 // number of columns in Rows.
2647 // Scan converts columns read from the database into the following
2648 // common Go types and special types provided by the sql package:
2652 // *int, *int8, *int16, *int32, *int64
2653 // *uint, *uint8, *uint16, *uint32, *uint64
2655 // *float32, *float64
2658 // any type implementing Scanner (see Scanner docs)
2660 // In the most simple case, if the type of the value from the source
2661 // column is an integer, bool or string type T and dest is of type *T,
2662 // Scan simply assigns the value through the pointer.
2664 // Scan also converts between string and numeric types, as long as no
2665 // information would be lost. While Scan stringifies all numbers
2666 // scanned from numeric database columns into *string, scans into
2667 // numeric types are checked for overflow. For example, a float64 with
2668 // value 300 or a string with value "300" can scan into a uint16, but
2669 // not into a uint8, though float64(255) or "255" can scan into a
2670 // uint8. One exception is that scans of some float64 numbers to
2671 // strings may lose information when stringifying. In general, scan
2672 // floating point columns into *float64.
2674 // If a dest argument has type *[]byte, Scan saves in that argument a
2675 // copy of the corresponding data. The copy is owned by the caller and
2676 // can be modified and held indefinitely. The copy can be avoided by
2677 // using an argument of type *RawBytes instead; see the documentation
2678 // for RawBytes for restrictions on its use.
2680 // If an argument has type *interface{}, Scan copies the value
2681 // provided by the underlying driver without conversion. When scanning
2682 // from a source value of type []byte to *interface{}, a copy of the
2683 // slice is made and the caller owns the result.
2685 // Source values of type time.Time may be scanned into values of type
2686 // *time.Time, *interface{}, *string, or *[]byte. When converting to
2687 // the latter two, time.Format3339Nano is used.
2689 // Source values of type bool may be scanned into types *bool,
2690 // *interface{}, *string, *[]byte, or *RawBytes.
2692 // For scanning into *bool, the source may be true, false, 1, 0, or
2693 // string inputs parseable by strconv.ParseBool.
2694 func (rs
*Rows
) Scan(dest
...interface{}) error
{
2697 rs
.closemu
.RUnlock()
2698 return errors
.New("sql: Rows are closed")
2700 rs
.closemu
.RUnlock()
2702 if rs
.lastcols
== nil {
2703 return errors
.New("sql: Scan called without calling Next")
2705 if len(dest
) != len(rs
.lastcols
) {
2706 return fmt
.Errorf("sql: expected %d destination arguments in Scan, not %d", len(rs
.lastcols
), len(dest
))
2708 for i
, sv
:= range rs
.lastcols
{
2709 err
:= convertAssign(dest
[i
], sv
)
2711 return fmt
.Errorf("sql: Scan error on column index %d: %v", i
, err
)
2717 // rowsCloseHook returns a function so tests may install the
2718 // hook through a test only mutex.
2719 var rowsCloseHook
= func() func(*Rows
, *error
) { return nil }
2721 // Close closes the Rows, preventing further enumeration. If Next is called
2722 // and returns false and there are no further result sets,
2723 // the Rows are closed automatically and it will suffice to check the
2724 // result of Err. Close is idempotent and does not affect the result of Err.
2725 func (rs
*Rows
) Close() error
{
2726 return rs
.close(nil)
2729 func (rs
*Rows
) close(err error
) error
{
2731 defer rs
.closemu
.Unlock()
2738 if rs
.lasterr
== nil {
2742 withLock(rs
.dc
, func() {
2743 err
= rs
.rowsi
.Close()
2745 if fn
:= rowsCloseHook(); fn
!= nil {
2748 if rs
.cancel
!= nil {
2752 if rs
.closeStmt
!= nil {
2753 rs
.closeStmt
.Close()
2759 // Row is the result of calling QueryRow to select a single row.
2761 // One of these two will be non-nil:
2762 err error
// deferred error for easy chaining
2766 // Scan copies the columns from the matched row into the values
2767 // pointed at by dest. See the documentation on Rows.Scan for details.
2768 // If more than one row matches the query,
2769 // Scan uses the first row and discards the rest. If no row matches
2770 // the query, Scan returns ErrNoRows.
2771 func (r
*Row
) Scan(dest
...interface{}) error
{
2776 // TODO(bradfitz): for now we need to defensively clone all
2777 // []byte that the driver returned (not permitting
2778 // *RawBytes in Rows.Scan), since we're about to close
2779 // the Rows in our defer, when we return from this function.
2780 // the contract with the driver.Next(...) interface is that it
2781 // can return slices into read-only temporary memory that's
2782 // only valid until the next Scan/Close. But the TODO is that
2783 // for a lot of drivers, this copy will be unnecessary. We
2784 // should provide an optional interface for drivers to
2785 // implement to say, "don't worry, the []bytes that I return
2786 // from Next will not be modified again." (for instance, if
2787 // they were obtained from the network anyway) But for now we
2789 defer r
.rows
.Close()
2790 for _
, dp
:= range dest
{
2791 if _
, ok
:= dp
.(*RawBytes
); ok
{
2792 return errors
.New("sql: RawBytes isn't allowed on Row.Scan")
2797 if err
:= r
.rows
.Err(); err
!= nil {
2802 err
:= r
.rows
.Scan(dest
...)
2806 // Make sure the query can be processed to completion with no errors.
2807 if err
:= r
.rows
.Close(); err
!= nil {
2814 // A Result summarizes an executed SQL command.
2815 type Result
interface {
2816 // LastInsertId returns the integer generated by the database
2817 // in response to a command. Typically this will be from an
2818 // "auto increment" column when inserting a new row. Not all
2819 // databases support this feature, and the syntax of such
2820 // statements varies.
2821 LastInsertId() (int64, error
)
2823 // RowsAffected returns the number of rows affected by an
2824 // update, insert, or delete. Not every database or database
2825 // driver may support this.
2826 RowsAffected() (int64, error
)
2829 type driverResult
struct {
2830 sync
.Locker
// the *driverConn
2834 func (dr driverResult
) LastInsertId() (int64, error
) {
2837 return dr
.resi
.LastInsertId()
2840 func (dr driverResult
) RowsAffected() (int64, error
) {
2843 return dr
.resi
.RowsAffected()
2846 func stack() string {
2847 var buf
[2 << 10]byte
2848 return string(buf
[:runtime
.Stack(buf
[:], false)])
2851 // withLock runs while holding lk.
2852 func withLock(lk sync
.Locker
, fn
func()) {
2854 defer lk
.Unlock() // in case fn panics