github.com/corona10/go@v0.0.0-20180224231303-7a218942be57/src/database/sql/sql.go (about) 1 // Copyright 2011 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 // Package sql provides a generic interface around SQL (or SQL-like) 6 // databases. 7 // 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. 10 // 11 // Drivers that do not support context cancelation will not return until 12 // after the query is completed. 13 // 14 // For usage examples, see the wiki page at 15 // https://golang.org/s/sqlwiki. 16 package sql 17 18 import ( 19 "context" 20 "database/sql/driver" 21 "errors" 22 "fmt" 23 "io" 24 "reflect" 25 "runtime" 26 "sort" 27 "strconv" 28 "sync" 29 "sync/atomic" 30 "time" 31 ) 32 33 var ( 34 driversMu sync.RWMutex 35 drivers = make(map[string]driver.Driver) 36 ) 37 38 // nowFunc returns the current time; it's overridden in tests. 39 var nowFunc = time.Now 40 41 // Register makes a database driver available by the provided name. 42 // If Register is called twice with the same name or if driver is nil, 43 // it panics. 44 func Register(name string, driver driver.Driver) { 45 driversMu.Lock() 46 defer driversMu.Unlock() 47 if driver == nil { 48 panic("sql: Register driver is nil") 49 } 50 if _, dup := drivers[name]; dup { 51 panic("sql: Register called twice for driver " + name) 52 } 53 drivers[name] = driver 54 } 55 56 func unregisterAllDrivers() { 57 driversMu.Lock() 58 defer driversMu.Unlock() 59 // For tests. 60 drivers = make(map[string]driver.Driver) 61 } 62 63 // Drivers returns a sorted list of the names of the registered drivers. 64 func Drivers() []string { 65 driversMu.RLock() 66 defer driversMu.RUnlock() 67 var list []string 68 for name := range drivers { 69 list = append(list, name) 70 } 71 sort.Strings(list) 72 return list 73 } 74 75 // A NamedArg is a named argument. NamedArg values may be used as 76 // arguments to Query or Exec and bind to the corresponding named 77 // parameter in the SQL statement. 78 // 79 // For a more concise way to create NamedArg values, see 80 // the Named function. 81 type NamedArg struct { 82 _Named_Fields_Required struct{} 83 84 // Name is the name of the parameter placeholder. 85 // 86 // If empty, the ordinal position in the argument list will be 87 // used. 88 // 89 // Name must omit any symbol prefix. 90 Name string 91 92 // Value is the value of the parameter. 93 // It may be assigned the same value types as the query 94 // arguments. 95 Value interface{} 96 } 97 98 // Named provides a more concise way to create NamedArg values. 99 // 100 // Example usage: 101 // 102 // db.ExecContext(ctx, ` 103 // delete from Invoice 104 // where 105 // TimeCreated < @end 106 // and TimeCreated >= @start;`, 107 // sql.Named("start", startTime), 108 // sql.Named("end", endTime), 109 // ) 110 func Named(name string, value interface{}) NamedArg { 111 // This method exists because the go1compat promise 112 // doesn't guarantee that structs don't grow more fields, 113 // so unkeyed struct literals are a vet error. Thus, we don't 114 // want to allow sql.NamedArg{name, value}. 115 return NamedArg{Name: name, Value: value} 116 } 117 118 // IsolationLevel is the transaction isolation level used in TxOptions. 119 type IsolationLevel int 120 121 // Various isolation levels that drivers may support in BeginTx. 122 // If a driver does not support a given isolation level an error may be returned. 123 // 124 // See https://en.wikipedia.org/wiki/Isolation_(database_systems)#Isolation_levels. 125 const ( 126 LevelDefault IsolationLevel = iota 127 LevelReadUncommitted 128 LevelReadCommitted 129 LevelWriteCommitted 130 LevelRepeatableRead 131 LevelSnapshot 132 LevelSerializable 133 LevelLinearizable 134 ) 135 136 func (i IsolationLevel) String() string { 137 switch i { 138 case LevelDefault: 139 return "Default" 140 case LevelReadUncommitted: 141 return "Read Uncommitted" 142 case LevelReadCommitted: 143 return "Read Committed" 144 case LevelWriteCommitted: 145 return "Write Committed" 146 case LevelRepeatableRead: 147 return "Repeatable Read" 148 case LevelSnapshot: 149 return "Snapshot" 150 case LevelSerializable: 151 return "Serializable" 152 case LevelLinearizable: 153 return "Linearizable" 154 default: 155 return "IsolationLevel(" + strconv.Itoa(int(i)) + ")" 156 } 157 } 158 159 var _ fmt.Stringer = LevelDefault 160 161 // TxOptions holds the transaction options to be used in DB.BeginTx. 162 type TxOptions struct { 163 // Isolation is the transaction isolation level. 164 // If zero, the driver or database's default level is used. 165 Isolation IsolationLevel 166 ReadOnly bool 167 } 168 169 // RawBytes is a byte slice that holds a reference to memory owned by 170 // the database itself. After a Scan into a RawBytes, the slice is only 171 // valid until the next call to Next, Scan, or Close. 172 type RawBytes []byte 173 174 // NullString represents a string that may be null. 175 // NullString implements the Scanner interface so 176 // it can be used as a scan destination: 177 // 178 // var s NullString 179 // err := db.QueryRow("SELECT name FROM foo WHERE id=?", id).Scan(&s) 180 // ... 181 // if s.Valid { 182 // // use s.String 183 // } else { 184 // // NULL value 185 // } 186 // 187 type NullString struct { 188 String string 189 Valid bool // Valid is true if String is not NULL 190 } 191 192 // Scan implements the Scanner interface. 193 func (ns *NullString) Scan(value interface{}) error { 194 if value == nil { 195 ns.String, ns.Valid = "", false 196 return nil 197 } 198 ns.Valid = true 199 return convertAssign(&ns.String, value) 200 } 201 202 // Value implements the driver Valuer interface. 203 func (ns NullString) Value() (driver.Value, error) { 204 if !ns.Valid { 205 return nil, nil 206 } 207 return ns.String, nil 208 } 209 210 // NullInt64 represents an int64 that may be null. 211 // NullInt64 implements the Scanner interface so 212 // it can be used as a scan destination, similar to NullString. 213 type NullInt64 struct { 214 Int64 int64 215 Valid bool // Valid is true if Int64 is not NULL 216 } 217 218 // Scan implements the Scanner interface. 219 func (n *NullInt64) Scan(value interface{}) error { 220 if value == nil { 221 n.Int64, n.Valid = 0, false 222 return nil 223 } 224 n.Valid = true 225 return convertAssign(&n.Int64, value) 226 } 227 228 // Value implements the driver Valuer interface. 229 func (n NullInt64) Value() (driver.Value, error) { 230 if !n.Valid { 231 return nil, nil 232 } 233 return n.Int64, nil 234 } 235 236 // NullFloat64 represents a float64 that may be null. 237 // NullFloat64 implements the Scanner interface so 238 // it can be used as a scan destination, similar to NullString. 239 type NullFloat64 struct { 240 Float64 float64 241 Valid bool // Valid is true if Float64 is not NULL 242 } 243 244 // Scan implements the Scanner interface. 245 func (n *NullFloat64) Scan(value interface{}) error { 246 if value == nil { 247 n.Float64, n.Valid = 0, false 248 return nil 249 } 250 n.Valid = true 251 return convertAssign(&n.Float64, value) 252 } 253 254 // Value implements the driver Valuer interface. 255 func (n NullFloat64) Value() (driver.Value, error) { 256 if !n.Valid { 257 return nil, nil 258 } 259 return n.Float64, nil 260 } 261 262 // NullBool represents a bool that may be null. 263 // NullBool implements the Scanner interface so 264 // it can be used as a scan destination, similar to NullString. 265 type NullBool struct { 266 Bool bool 267 Valid bool // Valid is true if Bool is not NULL 268 } 269 270 // Scan implements the Scanner interface. 271 func (n *NullBool) Scan(value interface{}) error { 272 if value == nil { 273 n.Bool, n.Valid = false, false 274 return nil 275 } 276 n.Valid = true 277 return convertAssign(&n.Bool, value) 278 } 279 280 // Value implements the driver Valuer interface. 281 func (n NullBool) Value() (driver.Value, error) { 282 if !n.Valid { 283 return nil, nil 284 } 285 return n.Bool, nil 286 } 287 288 // Scanner is an interface used by Scan. 289 type Scanner interface { 290 // Scan assigns a value from a database driver. 291 // 292 // The src value will be of one of the following types: 293 // 294 // int64 295 // float64 296 // bool 297 // []byte 298 // string 299 // time.Time 300 // nil - for NULL values 301 // 302 // An error should be returned if the value cannot be stored 303 // without loss of information. 304 Scan(src interface{}) error 305 } 306 307 // Out may be used to retrieve OUTPUT value parameters from stored procedures. 308 // 309 // Not all drivers and databases support OUTPUT value parameters. 310 // 311 // Example usage: 312 // 313 // var outArg string 314 // _, err := db.ExecContext(ctx, "ProcName", sql.Named("Arg1", sql.Out{Dest: &outArg})) 315 type Out struct { 316 _Named_Fields_Required struct{} 317 318 // Dest is a pointer to the value that will be set to the result of the 319 // stored procedure's OUTPUT parameter. 320 Dest interface{} 321 322 // In is whether the parameter is an INOUT parameter. If so, the input value to the stored 323 // procedure is the dereferenced value of Dest's pointer, which is then replaced with 324 // the output value. 325 In bool 326 } 327 328 // ErrNoRows is returned by Scan when QueryRow doesn't return a 329 // row. In such a case, QueryRow returns a placeholder *Row value that 330 // defers this error until a Scan. 331 var ErrNoRows = errors.New("sql: no rows in result set") 332 333 // DB is a database handle representing a pool of zero or more 334 // underlying connections. It's safe for concurrent use by multiple 335 // goroutines. 336 // 337 // The sql package creates and frees connections automatically; it 338 // also maintains a free pool of idle connections. If the database has 339 // a concept of per-connection state, such state can only be reliably 340 // observed within a transaction. Once DB.Begin is called, the 341 // returned Tx is bound to a single connection. Once Commit or 342 // Rollback is called on the transaction, that transaction's 343 // connection is returned to DB's idle connection pool. The pool size 344 // can be controlled with SetMaxIdleConns. 345 type DB struct { 346 connector driver.Connector 347 // numClosed is an atomic counter which represents a total number of 348 // closed connections. Stmt.openStmt checks it before cleaning closed 349 // connections in Stmt.css. 350 numClosed uint64 351 352 mu sync.Mutex // protects following fields 353 freeConn []*driverConn 354 connRequests map[uint64]chan connRequest 355 nextRequest uint64 // Next key to use in connRequests. 356 numOpen int // number of opened and pending open connections 357 // Used to signal the need for new connections 358 // a goroutine running connectionOpener() reads on this chan and 359 // maybeOpenNewConnections sends on the chan (one send per needed connection) 360 // It is closed during db.Close(). The close tells the connectionOpener 361 // goroutine to exit. 362 openerCh chan struct{} 363 resetterCh chan *driverConn 364 closed bool 365 dep map[finalCloser]depSet 366 lastPut map[*driverConn]string // stacktrace of last conn's put; debug only 367 maxIdle int // zero means defaultMaxIdleConns; negative means 0 368 maxOpen int // <= 0 means unlimited 369 maxLifetime time.Duration // maximum amount of time a connection may be reused 370 cleanerCh chan struct{} 371 372 stop func() // stop cancels the connection opener and the session resetter. 373 } 374 375 // connReuseStrategy determines how (*DB).conn returns database connections. 376 type connReuseStrategy uint8 377 378 const ( 379 // alwaysNewConn forces a new connection to the database. 380 alwaysNewConn connReuseStrategy = iota 381 // cachedOrNewConn returns a cached connection, if available, else waits 382 // for one to become available (if MaxOpenConns has been reached) or 383 // creates a new database connection. 384 cachedOrNewConn 385 ) 386 387 // driverConn wraps a driver.Conn with a mutex, to 388 // be held during all calls into the Conn. (including any calls onto 389 // interfaces returned via that Conn, such as calls on Tx, Stmt, 390 // Result, Rows) 391 type driverConn struct { 392 db *DB 393 createdAt time.Time 394 395 sync.Mutex // guards following 396 ci driver.Conn 397 closed bool 398 finalClosed bool // ci.Close has been called 399 openStmt map[*driverStmt]bool 400 lastErr error // lastError captures the result of the session resetter. 401 402 // guarded by db.mu 403 inUse bool 404 onPut []func() // code (with db.mu held) run when conn is next returned 405 dbmuClosed bool // same as closed, but guarded by db.mu, for removeClosedStmtLocked 406 } 407 408 func (dc *driverConn) releaseConn(err error) { 409 dc.db.putConn(dc, err, true) 410 } 411 412 func (dc *driverConn) removeOpenStmt(ds *driverStmt) { 413 dc.Lock() 414 defer dc.Unlock() 415 delete(dc.openStmt, ds) 416 } 417 418 func (dc *driverConn) expired(timeout time.Duration) bool { 419 if timeout <= 0 { 420 return false 421 } 422 return dc.createdAt.Add(timeout).Before(nowFunc()) 423 } 424 425 // prepareLocked prepares the query on dc. When cg == nil the dc must keep track of 426 // the prepared statements in a pool. 427 func (dc *driverConn) prepareLocked(ctx context.Context, cg stmtConnGrabber, query string) (*driverStmt, error) { 428 si, err := ctxDriverPrepare(ctx, dc.ci, query) 429 if err != nil { 430 return nil, err 431 } 432 ds := &driverStmt{Locker: dc, si: si} 433 434 // No need to manage open statements if there is a single connection grabber. 435 if cg != nil { 436 return ds, nil 437 } 438 439 // Track each driverConn's open statements, so we can close them 440 // before closing the conn. 441 // 442 // Wrap all driver.Stmt is *driverStmt to ensure they are only closed once. 443 if dc.openStmt == nil { 444 dc.openStmt = make(map[*driverStmt]bool) 445 } 446 dc.openStmt[ds] = true 447 return ds, nil 448 } 449 450 // resetSession resets the connection session and sets the lastErr 451 // that is checked before returning the connection to another query. 452 // 453 // resetSession assumes that the embedded mutex is locked when the connection 454 // was returned to the pool. This unlocks the mutex. 455 func (dc *driverConn) resetSession(ctx context.Context) { 456 defer dc.Unlock() // In case of panic. 457 if dc.closed { // Check if the database has been closed. 458 return 459 } 460 dc.lastErr = dc.ci.(driver.SessionResetter).ResetSession(ctx) 461 } 462 463 // the dc.db's Mutex is held. 464 func (dc *driverConn) closeDBLocked() func() error { 465 dc.Lock() 466 defer dc.Unlock() 467 if dc.closed { 468 return func() error { return errors.New("sql: duplicate driverConn close") } 469 } 470 dc.closed = true 471 return dc.db.removeDepLocked(dc, dc) 472 } 473 474 func (dc *driverConn) Close() error { 475 dc.Lock() 476 if dc.closed { 477 dc.Unlock() 478 return errors.New("sql: duplicate driverConn close") 479 } 480 dc.closed = true 481 dc.Unlock() // not defer; removeDep finalClose calls may need to lock 482 483 // And now updates that require holding dc.mu.Lock. 484 dc.db.mu.Lock() 485 dc.dbmuClosed = true 486 fn := dc.db.removeDepLocked(dc, dc) 487 dc.db.mu.Unlock() 488 return fn() 489 } 490 491 func (dc *driverConn) finalClose() error { 492 var err error 493 494 // Each *driverStmt has a lock to the dc. Copy the list out of the dc 495 // before calling close on each stmt. 496 var openStmt []*driverStmt 497 withLock(dc, func() { 498 openStmt = make([]*driverStmt, 0, len(dc.openStmt)) 499 for ds := range dc.openStmt { 500 openStmt = append(openStmt, ds) 501 } 502 dc.openStmt = nil 503 }) 504 for _, ds := range openStmt { 505 ds.Close() 506 } 507 withLock(dc, func() { 508 dc.finalClosed = true 509 err = dc.ci.Close() 510 dc.ci = nil 511 }) 512 513 dc.db.mu.Lock() 514 dc.db.numOpen-- 515 dc.db.maybeOpenNewConnections() 516 dc.db.mu.Unlock() 517 518 atomic.AddUint64(&dc.db.numClosed, 1) 519 return err 520 } 521 522 // driverStmt associates a driver.Stmt with the 523 // *driverConn from which it came, so the driverConn's lock can be 524 // held during calls. 525 type driverStmt struct { 526 sync.Locker // the *driverConn 527 si driver.Stmt 528 closed bool 529 closeErr error // return value of previous Close call 530 } 531 532 // Close ensures dirver.Stmt is only closed once any always returns the same 533 // result. 534 func (ds *driverStmt) Close() error { 535 ds.Lock() 536 defer ds.Unlock() 537 if ds.closed { 538 return ds.closeErr 539 } 540 ds.closed = true 541 ds.closeErr = ds.si.Close() 542 return ds.closeErr 543 } 544 545 // depSet is a finalCloser's outstanding dependencies 546 type depSet map[interface{}]bool // set of true bools 547 548 // The finalCloser interface is used by (*DB).addDep and related 549 // dependency reference counting. 550 type finalCloser interface { 551 // finalClose is called when the reference count of an object 552 // goes to zero. (*DB).mu is not held while calling it. 553 finalClose() error 554 } 555 556 // addDep notes that x now depends on dep, and x's finalClose won't be 557 // called until all of x's dependencies are removed with removeDep. 558 func (db *DB) addDep(x finalCloser, dep interface{}) { 559 //println(fmt.Sprintf("addDep(%T %p, %T %p)", x, x, dep, dep)) 560 db.mu.Lock() 561 defer db.mu.Unlock() 562 db.addDepLocked(x, dep) 563 } 564 565 func (db *DB) addDepLocked(x finalCloser, dep interface{}) { 566 if db.dep == nil { 567 db.dep = make(map[finalCloser]depSet) 568 } 569 xdep := db.dep[x] 570 if xdep == nil { 571 xdep = make(depSet) 572 db.dep[x] = xdep 573 } 574 xdep[dep] = true 575 } 576 577 // removeDep notes that x no longer depends on dep. 578 // If x still has dependencies, nil is returned. 579 // If x no longer has any dependencies, its finalClose method will be 580 // called and its error value will be returned. 581 func (db *DB) removeDep(x finalCloser, dep interface{}) error { 582 db.mu.Lock() 583 fn := db.removeDepLocked(x, dep) 584 db.mu.Unlock() 585 return fn() 586 } 587 588 func (db *DB) removeDepLocked(x finalCloser, dep interface{}) func() error { 589 //println(fmt.Sprintf("removeDep(%T %p, %T %p)", x, x, dep, dep)) 590 591 xdep, ok := db.dep[x] 592 if !ok { 593 panic(fmt.Sprintf("unpaired removeDep: no deps for %T", x)) 594 } 595 596 l0 := len(xdep) 597 delete(xdep, dep) 598 599 switch len(xdep) { 600 case l0: 601 // Nothing removed. Shouldn't happen. 602 panic(fmt.Sprintf("unpaired removeDep: no %T dep on %T", dep, x)) 603 case 0: 604 // No more dependencies. 605 delete(db.dep, x) 606 return x.finalClose 607 default: 608 // Dependencies remain. 609 return func() error { return nil } 610 } 611 } 612 613 // This is the size of the connectionOpener request chan (DB.openerCh). 614 // This value should be larger than the maximum typical value 615 // used for db.maxOpen. If maxOpen is significantly larger than 616 // connectionRequestQueueSize then it is possible for ALL calls into the *DB 617 // to block until the connectionOpener can satisfy the backlog of requests. 618 var connectionRequestQueueSize = 1000000 619 620 type dsnConnector struct { 621 dsn string 622 driver driver.Driver 623 } 624 625 func (t dsnConnector) Connect(_ context.Context) (driver.Conn, error) { 626 return t.driver.Open(t.dsn) 627 } 628 629 func (t dsnConnector) Driver() driver.Driver { 630 return t.driver 631 } 632 633 // OpenDB opens a database using a Connector, allowing drivers to 634 // bypass a string based data source name. 635 // 636 // Most users will open a database via a driver-specific connection 637 // helper function that returns a *DB. No database drivers are included 638 // in the Go standard library. See https://golang.org/s/sqldrivers for 639 // a list of third-party drivers. 640 // 641 // OpenDB may just validate its arguments without creating a connection 642 // to the database. To verify that the data source name is valid, call 643 // Ping. 644 // 645 // The returned DB is safe for concurrent use by multiple goroutines 646 // and maintains its own pool of idle connections. Thus, the OpenDB 647 // function should be called just once. It is rarely necessary to 648 // close a DB. 649 func OpenDB(c driver.Connector) *DB { 650 ctx, cancel := context.WithCancel(context.Background()) 651 db := &DB{ 652 connector: c, 653 openerCh: make(chan struct{}, connectionRequestQueueSize), 654 resetterCh: make(chan *driverConn, 50), 655 lastPut: make(map[*driverConn]string), 656 connRequests: make(map[uint64]chan connRequest), 657 stop: cancel, 658 } 659 660 go db.connectionOpener(ctx) 661 go db.connectionResetter(ctx) 662 663 return db 664 } 665 666 // Open opens a database specified by its database driver name and a 667 // driver-specific data source name, usually consisting of at least a 668 // database name and connection information. 669 // 670 // Most users will open a database via a driver-specific connection 671 // helper function that returns a *DB. No database drivers are included 672 // in the Go standard library. See https://golang.org/s/sqldrivers for 673 // a list of third-party drivers. 674 // 675 // Open may just validate its arguments without creating a connection 676 // to the database. To verify that the data source name is valid, call 677 // Ping. 678 // 679 // The returned DB is safe for concurrent use by multiple goroutines 680 // and maintains its own pool of idle connections. Thus, the Open 681 // function should be called just once. It is rarely necessary to 682 // close a DB. 683 func Open(driverName, dataSourceName string) (*DB, error) { 684 driversMu.RLock() 685 driveri, ok := drivers[driverName] 686 driversMu.RUnlock() 687 if !ok { 688 return nil, fmt.Errorf("sql: unknown driver %q (forgotten import?)", driverName) 689 } 690 691 if driverCtx, ok := driveri.(driver.DriverContext); ok { 692 connector, err := driverCtx.OpenConnector(dataSourceName) 693 if err != nil { 694 return nil, err 695 } 696 return OpenDB(connector), nil 697 } 698 699 return OpenDB(dsnConnector{dsn: dataSourceName, driver: driveri}), nil 700 } 701 702 func (db *DB) pingDC(ctx context.Context, dc *driverConn, release func(error)) error { 703 var err error 704 if pinger, ok := dc.ci.(driver.Pinger); ok { 705 withLock(dc, func() { 706 err = pinger.Ping(ctx) 707 }) 708 } 709 release(err) 710 return err 711 } 712 713 // PingContext verifies a connection to the database is still alive, 714 // establishing a connection if necessary. 715 func (db *DB) PingContext(ctx context.Context) error { 716 var dc *driverConn 717 var err error 718 719 for i := 0; i < maxBadConnRetries; i++ { 720 dc, err = db.conn(ctx, cachedOrNewConn) 721 if err != driver.ErrBadConn { 722 break 723 } 724 } 725 if err == driver.ErrBadConn { 726 dc, err = db.conn(ctx, alwaysNewConn) 727 } 728 if err != nil { 729 return err 730 } 731 732 return db.pingDC(ctx, dc, dc.releaseConn) 733 } 734 735 // Ping verifies a connection to the database is still alive, 736 // establishing a connection if necessary. 737 func (db *DB) Ping() error { 738 return db.PingContext(context.Background()) 739 } 740 741 // Close closes the database, releasing any open resources. 742 // 743 // It is rare to Close a DB, as the DB handle is meant to be 744 // long-lived and shared between many goroutines. 745 func (db *DB) Close() error { 746 db.mu.Lock() 747 if db.closed { // Make DB.Close idempotent 748 db.mu.Unlock() 749 return nil 750 } 751 if db.cleanerCh != nil { 752 close(db.cleanerCh) 753 } 754 var err error 755 fns := make([]func() error, 0, len(db.freeConn)) 756 for _, dc := range db.freeConn { 757 fns = append(fns, dc.closeDBLocked()) 758 } 759 db.freeConn = nil 760 db.closed = true 761 for _, req := range db.connRequests { 762 close(req) 763 } 764 db.mu.Unlock() 765 for _, fn := range fns { 766 err1 := fn() 767 if err1 != nil { 768 err = err1 769 } 770 } 771 db.stop() 772 return err 773 } 774 775 const defaultMaxIdleConns = 2 776 777 func (db *DB) maxIdleConnsLocked() int { 778 n := db.maxIdle 779 switch { 780 case n == 0: 781 // TODO(bradfitz): ask driver, if supported, for its default preference 782 return defaultMaxIdleConns 783 case n < 0: 784 return 0 785 default: 786 return n 787 } 788 } 789 790 // SetMaxIdleConns sets the maximum number of connections in the idle 791 // connection pool. 792 // 793 // If MaxOpenConns is greater than 0 but less than the new MaxIdleConns 794 // then the new MaxIdleConns will be reduced to match the MaxOpenConns limit 795 // 796 // If n <= 0, no idle connections are retained. 797 func (db *DB) SetMaxIdleConns(n int) { 798 db.mu.Lock() 799 if n > 0 { 800 db.maxIdle = n 801 } else { 802 // No idle connections. 803 db.maxIdle = -1 804 } 805 // Make sure maxIdle doesn't exceed maxOpen 806 if db.maxOpen > 0 && db.maxIdleConnsLocked() > db.maxOpen { 807 db.maxIdle = db.maxOpen 808 } 809 var closing []*driverConn 810 idleCount := len(db.freeConn) 811 maxIdle := db.maxIdleConnsLocked() 812 if idleCount > maxIdle { 813 closing = db.freeConn[maxIdle:] 814 db.freeConn = db.freeConn[:maxIdle] 815 } 816 db.mu.Unlock() 817 for _, c := range closing { 818 c.Close() 819 } 820 } 821 822 // SetMaxOpenConns sets the maximum number of open connections to the database. 823 // 824 // If MaxIdleConns is greater than 0 and the new MaxOpenConns is less than 825 // MaxIdleConns, then MaxIdleConns will be reduced to match the new 826 // MaxOpenConns limit 827 // 828 // If n <= 0, then there is no limit on the number of open connections. 829 // The default is 0 (unlimited). 830 func (db *DB) SetMaxOpenConns(n int) { 831 db.mu.Lock() 832 db.maxOpen = n 833 if n < 0 { 834 db.maxOpen = 0 835 } 836 syncMaxIdle := db.maxOpen > 0 && db.maxIdleConnsLocked() > db.maxOpen 837 db.mu.Unlock() 838 if syncMaxIdle { 839 db.SetMaxIdleConns(n) 840 } 841 } 842 843 // SetConnMaxLifetime sets the maximum amount of time a connection may be reused. 844 // 845 // Expired connections may be closed lazily before reuse. 846 // 847 // If d <= 0, connections are reused forever. 848 func (db *DB) SetConnMaxLifetime(d time.Duration) { 849 if d < 0 { 850 d = 0 851 } 852 db.mu.Lock() 853 // wake cleaner up when lifetime is shortened. 854 if d > 0 && d < db.maxLifetime && db.cleanerCh != nil { 855 select { 856 case db.cleanerCh <- struct{}{}: 857 default: 858 } 859 } 860 db.maxLifetime = d 861 db.startCleanerLocked() 862 db.mu.Unlock() 863 } 864 865 // startCleanerLocked starts connectionCleaner if needed. 866 func (db *DB) startCleanerLocked() { 867 if db.maxLifetime > 0 && db.numOpen > 0 && db.cleanerCh == nil { 868 db.cleanerCh = make(chan struct{}, 1) 869 go db.connectionCleaner(db.maxLifetime) 870 } 871 } 872 873 func (db *DB) connectionCleaner(d time.Duration) { 874 const minInterval = time.Second 875 876 if d < minInterval { 877 d = minInterval 878 } 879 t := time.NewTimer(d) 880 881 for { 882 select { 883 case <-t.C: 884 case <-db.cleanerCh: // maxLifetime was changed or db was closed. 885 } 886 887 db.mu.Lock() 888 d = db.maxLifetime 889 if db.closed || db.numOpen == 0 || d <= 0 { 890 db.cleanerCh = nil 891 db.mu.Unlock() 892 return 893 } 894 895 expiredSince := nowFunc().Add(-d) 896 var closing []*driverConn 897 for i := 0; i < len(db.freeConn); i++ { 898 c := db.freeConn[i] 899 if c.createdAt.Before(expiredSince) { 900 closing = append(closing, c) 901 last := len(db.freeConn) - 1 902 db.freeConn[i] = db.freeConn[last] 903 db.freeConn[last] = nil 904 db.freeConn = db.freeConn[:last] 905 i-- 906 } 907 } 908 db.mu.Unlock() 909 910 for _, c := range closing { 911 c.Close() 912 } 913 914 if d < minInterval { 915 d = minInterval 916 } 917 t.Reset(d) 918 } 919 } 920 921 // DBStats contains database statistics. 922 type DBStats struct { 923 // OpenConnections is the number of open connections to the database. 924 OpenConnections int 925 } 926 927 // Stats returns database statistics. 928 func (db *DB) Stats() DBStats { 929 db.mu.Lock() 930 stats := DBStats{ 931 OpenConnections: db.numOpen, 932 } 933 db.mu.Unlock() 934 return stats 935 } 936 937 // Assumes db.mu is locked. 938 // If there are connRequests and the connection limit hasn't been reached, 939 // then tell the connectionOpener to open new connections. 940 func (db *DB) maybeOpenNewConnections() { 941 numRequests := len(db.connRequests) 942 if db.maxOpen > 0 { 943 numCanOpen := db.maxOpen - db.numOpen 944 if numRequests > numCanOpen { 945 numRequests = numCanOpen 946 } 947 } 948 for numRequests > 0 { 949 db.numOpen++ // optimistically 950 numRequests-- 951 if db.closed { 952 return 953 } 954 db.openerCh <- struct{}{} 955 } 956 } 957 958 // Runs in a separate goroutine, opens new connections when requested. 959 func (db *DB) connectionOpener(ctx context.Context) { 960 for { 961 select { 962 case <-ctx.Done(): 963 return 964 case <-db.openerCh: 965 db.openNewConnection(ctx) 966 } 967 } 968 } 969 970 // connectionResetter runs in a separate goroutine to reset connections async 971 // to exported API. 972 func (db *DB) connectionResetter(ctx context.Context) { 973 for { 974 select { 975 case <-ctx.Done(): 976 close(db.resetterCh) 977 for dc := range db.resetterCh { 978 dc.Unlock() 979 } 980 return 981 case dc := <-db.resetterCh: 982 dc.resetSession(ctx) 983 } 984 } 985 } 986 987 // Open one new connection 988 func (db *DB) openNewConnection(ctx context.Context) { 989 // maybeOpenNewConnctions has already executed db.numOpen++ before it sent 990 // on db.openerCh. This function must execute db.numOpen-- if the 991 // connection fails or is closed before returning. 992 ci, err := db.connector.Connect(ctx) 993 db.mu.Lock() 994 defer db.mu.Unlock() 995 if db.closed { 996 if err == nil { 997 ci.Close() 998 } 999 db.numOpen-- 1000 return 1001 } 1002 if err != nil { 1003 db.numOpen-- 1004 db.putConnDBLocked(nil, err) 1005 db.maybeOpenNewConnections() 1006 return 1007 } 1008 dc := &driverConn{ 1009 db: db, 1010 createdAt: nowFunc(), 1011 ci: ci, 1012 } 1013 if db.putConnDBLocked(dc, err) { 1014 db.addDepLocked(dc, dc) 1015 } else { 1016 db.numOpen-- 1017 ci.Close() 1018 } 1019 } 1020 1021 // connRequest represents one request for a new connection 1022 // When there are no idle connections available, DB.conn will create 1023 // a new connRequest and put it on the db.connRequests list. 1024 type connRequest struct { 1025 conn *driverConn 1026 err error 1027 } 1028 1029 var errDBClosed = errors.New("sql: database is closed") 1030 1031 // nextRequestKeyLocked returns the next connection request key. 1032 // It is assumed that nextRequest will not overflow. 1033 func (db *DB) nextRequestKeyLocked() uint64 { 1034 next := db.nextRequest 1035 db.nextRequest++ 1036 return next 1037 } 1038 1039 // conn returns a newly-opened or cached *driverConn. 1040 func (db *DB) conn(ctx context.Context, strategy connReuseStrategy) (*driverConn, error) { 1041 db.mu.Lock() 1042 if db.closed { 1043 db.mu.Unlock() 1044 return nil, errDBClosed 1045 } 1046 // Check if the context is expired. 1047 select { 1048 default: 1049 case <-ctx.Done(): 1050 db.mu.Unlock() 1051 return nil, ctx.Err() 1052 } 1053 lifetime := db.maxLifetime 1054 1055 // Prefer a free connection, if possible. 1056 numFree := len(db.freeConn) 1057 if strategy == cachedOrNewConn && numFree > 0 { 1058 conn := db.freeConn[0] 1059 copy(db.freeConn, db.freeConn[1:]) 1060 db.freeConn = db.freeConn[:numFree-1] 1061 conn.inUse = true 1062 db.mu.Unlock() 1063 if conn.expired(lifetime) { 1064 conn.Close() 1065 return nil, driver.ErrBadConn 1066 } 1067 // Lock around reading lastErr to ensure the session resetter finished. 1068 conn.Lock() 1069 err := conn.lastErr 1070 conn.Unlock() 1071 if err == driver.ErrBadConn { 1072 conn.Close() 1073 return nil, driver.ErrBadConn 1074 } 1075 return conn, nil 1076 } 1077 1078 // Out of free connections or we were asked not to use one. If we're not 1079 // allowed to open any more connections, make a request and wait. 1080 if db.maxOpen > 0 && db.numOpen >= db.maxOpen { 1081 // Make the connRequest channel. It's buffered so that the 1082 // connectionOpener doesn't block while waiting for the req to be read. 1083 req := make(chan connRequest, 1) 1084 reqKey := db.nextRequestKeyLocked() 1085 db.connRequests[reqKey] = req 1086 db.mu.Unlock() 1087 1088 // Timeout the connection request with the context. 1089 select { 1090 case <-ctx.Done(): 1091 // Remove the connection request and ensure no value has been sent 1092 // on it after removing. 1093 db.mu.Lock() 1094 delete(db.connRequests, reqKey) 1095 db.mu.Unlock() 1096 select { 1097 default: 1098 case ret, ok := <-req: 1099 if ok { 1100 db.putConn(ret.conn, ret.err, false) 1101 } 1102 } 1103 return nil, ctx.Err() 1104 case ret, ok := <-req: 1105 if !ok { 1106 return nil, errDBClosed 1107 } 1108 if ret.err == nil && ret.conn.expired(lifetime) { 1109 ret.conn.Close() 1110 return nil, driver.ErrBadConn 1111 } 1112 if ret.conn == nil { 1113 return nil, ret.err 1114 } 1115 // Lock around reading lastErr to ensure the session resetter finished. 1116 ret.conn.Lock() 1117 err := ret.conn.lastErr 1118 ret.conn.Unlock() 1119 if err == driver.ErrBadConn { 1120 ret.conn.Close() 1121 return nil, driver.ErrBadConn 1122 } 1123 return ret.conn, ret.err 1124 } 1125 } 1126 1127 db.numOpen++ // optimistically 1128 db.mu.Unlock() 1129 ci, err := db.connector.Connect(ctx) 1130 if err != nil { 1131 db.mu.Lock() 1132 db.numOpen-- // correct for earlier optimism 1133 db.maybeOpenNewConnections() 1134 db.mu.Unlock() 1135 return nil, err 1136 } 1137 db.mu.Lock() 1138 dc := &driverConn{ 1139 db: db, 1140 createdAt: nowFunc(), 1141 ci: ci, 1142 inUse: true, 1143 } 1144 db.addDepLocked(dc, dc) 1145 db.mu.Unlock() 1146 return dc, nil 1147 } 1148 1149 // putConnHook is a hook for testing. 1150 var putConnHook func(*DB, *driverConn) 1151 1152 // noteUnusedDriverStatement notes that ds is no longer used and should 1153 // be closed whenever possible (when c is next not in use), unless c is 1154 // already closed. 1155 func (db *DB) noteUnusedDriverStatement(c *driverConn, ds *driverStmt) { 1156 db.mu.Lock() 1157 defer db.mu.Unlock() 1158 if c.inUse { 1159 c.onPut = append(c.onPut, func() { 1160 ds.Close() 1161 }) 1162 } else { 1163 c.Lock() 1164 fc := c.finalClosed 1165 c.Unlock() 1166 if !fc { 1167 ds.Close() 1168 } 1169 } 1170 } 1171 1172 // debugGetPut determines whether getConn & putConn calls' stack traces 1173 // are returned for more verbose crashes. 1174 const debugGetPut = false 1175 1176 // putConn adds a connection to the db's free pool. 1177 // err is optionally the last error that occurred on this connection. 1178 func (db *DB) putConn(dc *driverConn, err error, resetSession bool) { 1179 db.mu.Lock() 1180 if !dc.inUse { 1181 if debugGetPut { 1182 fmt.Printf("putConn(%v) DUPLICATE was: %s\n\nPREVIOUS was: %s", dc, stack(), db.lastPut[dc]) 1183 } 1184 panic("sql: connection returned that was never out") 1185 } 1186 if debugGetPut { 1187 db.lastPut[dc] = stack() 1188 } 1189 dc.inUse = false 1190 1191 for _, fn := range dc.onPut { 1192 fn() 1193 } 1194 dc.onPut = nil 1195 1196 if err == driver.ErrBadConn { 1197 // Don't reuse bad connections. 1198 // Since the conn is considered bad and is being discarded, treat it 1199 // as closed. Don't decrement the open count here, finalClose will 1200 // take care of that. 1201 db.maybeOpenNewConnections() 1202 db.mu.Unlock() 1203 dc.Close() 1204 return 1205 } 1206 if putConnHook != nil { 1207 putConnHook(db, dc) 1208 } 1209 if db.closed { 1210 // Connections do not need to be reset if they will be closed. 1211 // Prevents writing to resetterCh after the DB has closed. 1212 resetSession = false 1213 } 1214 if resetSession { 1215 if _, resetSession = dc.ci.(driver.SessionResetter); resetSession { 1216 // Lock the driverConn here so it isn't released until 1217 // the connection is reset. 1218 // The lock must be taken before the connection is put into 1219 // the pool to prevent it from being taken out before it is reset. 1220 dc.Lock() 1221 } 1222 } 1223 added := db.putConnDBLocked(dc, nil) 1224 db.mu.Unlock() 1225 1226 if !added { 1227 if resetSession { 1228 dc.Unlock() 1229 } 1230 dc.Close() 1231 return 1232 } 1233 if !resetSession { 1234 return 1235 } 1236 select { 1237 default: 1238 // If the resetterCh is blocking then mark the connection 1239 // as bad and continue on. 1240 dc.lastErr = driver.ErrBadConn 1241 dc.Unlock() 1242 case db.resetterCh <- dc: 1243 } 1244 } 1245 1246 // Satisfy a connRequest or put the driverConn in the idle pool and return true 1247 // or return false. 1248 // putConnDBLocked will satisfy a connRequest if there is one, or it will 1249 // return the *driverConn to the freeConn list if err == nil and the idle 1250 // connection limit will not be exceeded. 1251 // If err != nil, the value of dc is ignored. 1252 // If err == nil, then dc must not equal nil. 1253 // If a connRequest was fulfilled or the *driverConn was placed in the 1254 // freeConn list, then true is returned, otherwise false is returned. 1255 func (db *DB) putConnDBLocked(dc *driverConn, err error) bool { 1256 if db.closed { 1257 return false 1258 } 1259 if db.maxOpen > 0 && db.numOpen > db.maxOpen { 1260 return false 1261 } 1262 if c := len(db.connRequests); c > 0 { 1263 var req chan connRequest 1264 var reqKey uint64 1265 for reqKey, req = range db.connRequests { 1266 break 1267 } 1268 delete(db.connRequests, reqKey) // Remove from pending requests. 1269 if err == nil { 1270 dc.inUse = true 1271 } 1272 req <- connRequest{ 1273 conn: dc, 1274 err: err, 1275 } 1276 return true 1277 } else if err == nil && !db.closed && db.maxIdleConnsLocked() > len(db.freeConn) { 1278 db.freeConn = append(db.freeConn, dc) 1279 db.startCleanerLocked() 1280 return true 1281 } 1282 return false 1283 } 1284 1285 // maxBadConnRetries is the number of maximum retries if the driver returns 1286 // driver.ErrBadConn to signal a broken connection before forcing a new 1287 // connection to be opened. 1288 const maxBadConnRetries = 2 1289 1290 // PrepareContext creates a prepared statement for later queries or executions. 1291 // Multiple queries or executions may be run concurrently from the 1292 // returned statement. 1293 // The caller must call the statement's Close method 1294 // when the statement is no longer needed. 1295 // 1296 // The provided context is used for the preparation of the statement, not for the 1297 // execution of the statement. 1298 func (db *DB) PrepareContext(ctx context.Context, query string) (*Stmt, error) { 1299 var stmt *Stmt 1300 var err error 1301 for i := 0; i < maxBadConnRetries; i++ { 1302 stmt, err = db.prepare(ctx, query, cachedOrNewConn) 1303 if err != driver.ErrBadConn { 1304 break 1305 } 1306 } 1307 if err == driver.ErrBadConn { 1308 return db.prepare(ctx, query, alwaysNewConn) 1309 } 1310 return stmt, err 1311 } 1312 1313 // Prepare creates a prepared statement for later queries or executions. 1314 // Multiple queries or executions may be run concurrently from the 1315 // returned statement. 1316 // The caller must call the statement's Close method 1317 // when the statement is no longer needed. 1318 func (db *DB) Prepare(query string) (*Stmt, error) { 1319 return db.PrepareContext(context.Background(), query) 1320 } 1321 1322 func (db *DB) prepare(ctx context.Context, query string, strategy connReuseStrategy) (*Stmt, error) { 1323 // TODO: check if db.driver supports an optional 1324 // driver.Preparer interface and call that instead, if so, 1325 // otherwise we make a prepared statement that's bound 1326 // to a connection, and to execute this prepared statement 1327 // we either need to use this connection (if it's free), else 1328 // get a new connection + re-prepare + execute on that one. 1329 dc, err := db.conn(ctx, strategy) 1330 if err != nil { 1331 return nil, err 1332 } 1333 return db.prepareDC(ctx, dc, dc.releaseConn, nil, query) 1334 } 1335 1336 // prepareDC prepares a query on the driverConn and calls release before 1337 // returning. When cg == nil it implies that a connection pool is used, and 1338 // when cg != nil only a single driver connection is used. 1339 func (db *DB) prepareDC(ctx context.Context, dc *driverConn, release func(error), cg stmtConnGrabber, query string) (*Stmt, error) { 1340 var ds *driverStmt 1341 var err error 1342 defer func() { 1343 release(err) 1344 }() 1345 withLock(dc, func() { 1346 ds, err = dc.prepareLocked(ctx, cg, query) 1347 }) 1348 if err != nil { 1349 return nil, err 1350 } 1351 stmt := &Stmt{ 1352 db: db, 1353 query: query, 1354 cg: cg, 1355 cgds: ds, 1356 } 1357 1358 // When cg == nil this statement will need to keep track of various 1359 // connections they are prepared on and record the stmt dependency on 1360 // the DB. 1361 if cg == nil { 1362 stmt.css = []connStmt{{dc, ds}} 1363 stmt.lastNumClosed = atomic.LoadUint64(&db.numClosed) 1364 db.addDep(stmt, stmt) 1365 } 1366 return stmt, nil 1367 } 1368 1369 // ExecContext executes a query without returning any rows. 1370 // The args are for any placeholder parameters in the query. 1371 func (db *DB) ExecContext(ctx context.Context, query string, args ...interface{}) (Result, error) { 1372 var res Result 1373 var err error 1374 for i := 0; i < maxBadConnRetries; i++ { 1375 res, err = db.exec(ctx, query, args, cachedOrNewConn) 1376 if err != driver.ErrBadConn { 1377 break 1378 } 1379 } 1380 if err == driver.ErrBadConn { 1381 return db.exec(ctx, query, args, alwaysNewConn) 1382 } 1383 return res, err 1384 } 1385 1386 // Exec executes a query without returning any rows. 1387 // The args are for any placeholder parameters in the query. 1388 func (db *DB) Exec(query string, args ...interface{}) (Result, error) { 1389 return db.ExecContext(context.Background(), query, args...) 1390 } 1391 1392 func (db *DB) exec(ctx context.Context, query string, args []interface{}, strategy connReuseStrategy) (Result, error) { 1393 dc, err := db.conn(ctx, strategy) 1394 if err != nil { 1395 return nil, err 1396 } 1397 return db.execDC(ctx, dc, dc.releaseConn, query, args) 1398 } 1399 1400 func (db *DB) execDC(ctx context.Context, dc *driverConn, release func(error), query string, args []interface{}) (res Result, err error) { 1401 defer func() { 1402 release(err) 1403 }() 1404 execerCtx, ok := dc.ci.(driver.ExecerContext) 1405 var execer driver.Execer 1406 if !ok { 1407 execer, ok = dc.ci.(driver.Execer) 1408 } 1409 if ok { 1410 var nvdargs []driver.NamedValue 1411 var resi driver.Result 1412 withLock(dc, func() { 1413 nvdargs, err = driverArgsConnLocked(dc.ci, nil, args) 1414 if err != nil { 1415 return 1416 } 1417 resi, err = ctxDriverExec(ctx, execerCtx, execer, query, nvdargs) 1418 }) 1419 if err != driver.ErrSkip { 1420 if err != nil { 1421 return nil, err 1422 } 1423 return driverResult{dc, resi}, nil 1424 } 1425 } 1426 1427 var si driver.Stmt 1428 withLock(dc, func() { 1429 si, err = ctxDriverPrepare(ctx, dc.ci, query) 1430 }) 1431 if err != nil { 1432 return nil, err 1433 } 1434 ds := &driverStmt{Locker: dc, si: si} 1435 defer ds.Close() 1436 return resultFromStatement(ctx, dc.ci, ds, args...) 1437 } 1438 1439 // QueryContext executes a query that returns rows, typically a SELECT. 1440 // The args are for any placeholder parameters in the query. 1441 func (db *DB) QueryContext(ctx context.Context, query string, args ...interface{}) (*Rows, error) { 1442 var rows *Rows 1443 var err error 1444 for i := 0; i < maxBadConnRetries; i++ { 1445 rows, err = db.query(ctx, query, args, cachedOrNewConn) 1446 if err != driver.ErrBadConn { 1447 break 1448 } 1449 } 1450 if err == driver.ErrBadConn { 1451 return db.query(ctx, query, args, alwaysNewConn) 1452 } 1453 return rows, err 1454 } 1455 1456 // Query executes a query that returns rows, typically a SELECT. 1457 // The args are for any placeholder parameters in the query. 1458 func (db *DB) Query(query string, args ...interface{}) (*Rows, error) { 1459 return db.QueryContext(context.Background(), query, args...) 1460 } 1461 1462 func (db *DB) query(ctx context.Context, query string, args []interface{}, strategy connReuseStrategy) (*Rows, error) { 1463 dc, err := db.conn(ctx, strategy) 1464 if err != nil { 1465 return nil, err 1466 } 1467 1468 return db.queryDC(ctx, nil, dc, dc.releaseConn, query, args) 1469 } 1470 1471 // queryDC executes a query on the given connection. 1472 // The connection gets released by the releaseConn function. 1473 // The ctx context is from a query method and the txctx context is from an 1474 // optional transaction context. 1475 func (db *DB) queryDC(ctx, txctx context.Context, dc *driverConn, releaseConn func(error), query string, args []interface{}) (*Rows, error) { 1476 queryerCtx, ok := dc.ci.(driver.QueryerContext) 1477 var queryer driver.Queryer 1478 if !ok { 1479 queryer, ok = dc.ci.(driver.Queryer) 1480 } 1481 if ok { 1482 var nvdargs []driver.NamedValue 1483 var rowsi driver.Rows 1484 var err error 1485 withLock(dc, func() { 1486 nvdargs, err = driverArgsConnLocked(dc.ci, nil, args) 1487 if err != nil { 1488 return 1489 } 1490 rowsi, err = ctxDriverQuery(ctx, queryerCtx, queryer, query, nvdargs) 1491 }) 1492 if err != driver.ErrSkip { 1493 if err != nil { 1494 releaseConn(err) 1495 return nil, err 1496 } 1497 // Note: ownership of dc passes to the *Rows, to be freed 1498 // with releaseConn. 1499 rows := &Rows{ 1500 dc: dc, 1501 releaseConn: releaseConn, 1502 rowsi: rowsi, 1503 } 1504 rows.initContextClose(ctx, txctx) 1505 return rows, nil 1506 } 1507 } 1508 1509 var si driver.Stmt 1510 var err error 1511 withLock(dc, func() { 1512 si, err = ctxDriverPrepare(ctx, dc.ci, query) 1513 }) 1514 if err != nil { 1515 releaseConn(err) 1516 return nil, err 1517 } 1518 1519 ds := &driverStmt{Locker: dc, si: si} 1520 rowsi, err := rowsiFromStatement(ctx, dc.ci, ds, args...) 1521 if err != nil { 1522 ds.Close() 1523 releaseConn(err) 1524 return nil, err 1525 } 1526 1527 // Note: ownership of ci passes to the *Rows, to be freed 1528 // with releaseConn. 1529 rows := &Rows{ 1530 dc: dc, 1531 releaseConn: releaseConn, 1532 rowsi: rowsi, 1533 closeStmt: ds, 1534 } 1535 rows.initContextClose(ctx, txctx) 1536 return rows, nil 1537 } 1538 1539 // QueryRowContext executes a query that is expected to return at most one row. 1540 // QueryRowContext always returns a non-nil value. Errors are deferred until 1541 // Row's Scan method is called. 1542 // If the query selects no rows, the *Row's Scan will return ErrNoRows. 1543 // Otherwise, the *Row's Scan scans the first selected row and discards 1544 // the rest. 1545 func (db *DB) QueryRowContext(ctx context.Context, query string, args ...interface{}) *Row { 1546 rows, err := db.QueryContext(ctx, query, args...) 1547 return &Row{rows: rows, err: err} 1548 } 1549 1550 // QueryRow executes a query that is expected to return at most one row. 1551 // QueryRow always returns a non-nil value. Errors are deferred until 1552 // Row's Scan method is called. 1553 // If the query selects no rows, the *Row's Scan will return ErrNoRows. 1554 // Otherwise, the *Row's Scan scans the first selected row and discards 1555 // the rest. 1556 func (db *DB) QueryRow(query string, args ...interface{}) *Row { 1557 return db.QueryRowContext(context.Background(), query, args...) 1558 } 1559 1560 // BeginTx starts a transaction. 1561 // 1562 // The provided context is used until the transaction is committed or rolled back. 1563 // If the context is canceled, the sql package will roll back 1564 // the transaction. Tx.Commit will return an error if the context provided to 1565 // BeginTx is canceled. 1566 // 1567 // The provided TxOptions is optional and may be nil if defaults should be used. 1568 // If a non-default isolation level is used that the driver doesn't support, 1569 // an error will be returned. 1570 func (db *DB) BeginTx(ctx context.Context, opts *TxOptions) (*Tx, error) { 1571 var tx *Tx 1572 var err error 1573 for i := 0; i < maxBadConnRetries; i++ { 1574 tx, err = db.begin(ctx, opts, cachedOrNewConn) 1575 if err != driver.ErrBadConn { 1576 break 1577 } 1578 } 1579 if err == driver.ErrBadConn { 1580 return db.begin(ctx, opts, alwaysNewConn) 1581 } 1582 return tx, err 1583 } 1584 1585 // Begin starts a transaction. The default isolation level is dependent on 1586 // the driver. 1587 func (db *DB) Begin() (*Tx, error) { 1588 return db.BeginTx(context.Background(), nil) 1589 } 1590 1591 func (db *DB) begin(ctx context.Context, opts *TxOptions, strategy connReuseStrategy) (tx *Tx, err error) { 1592 dc, err := db.conn(ctx, strategy) 1593 if err != nil { 1594 return nil, err 1595 } 1596 return db.beginDC(ctx, dc, dc.releaseConn, opts) 1597 } 1598 1599 // beginDC starts a transaction. The provided dc must be valid and ready to use. 1600 func (db *DB) beginDC(ctx context.Context, dc *driverConn, release func(error), opts *TxOptions) (tx *Tx, err error) { 1601 var txi driver.Tx 1602 withLock(dc, func() { 1603 txi, err = ctxDriverBegin(ctx, opts, dc.ci) 1604 }) 1605 if err != nil { 1606 release(err) 1607 return nil, err 1608 } 1609 1610 // Schedule the transaction to rollback when the context is cancelled. 1611 // The cancel function in Tx will be called after done is set to true. 1612 ctx, cancel := context.WithCancel(ctx) 1613 tx = &Tx{ 1614 db: db, 1615 dc: dc, 1616 releaseConn: release, 1617 txi: txi, 1618 cancel: cancel, 1619 ctx: ctx, 1620 } 1621 go tx.awaitDone() 1622 return tx, nil 1623 } 1624 1625 // Driver returns the database's underlying driver. 1626 func (db *DB) Driver() driver.Driver { 1627 return db.connector.Driver() 1628 } 1629 1630 // ErrConnDone is returned by any operation that is performed on a connection 1631 // that has already been returned to the connection pool. 1632 var ErrConnDone = errors.New("database/sql: connection is already closed") 1633 1634 // Conn returns a single connection by either opening a new connection 1635 // or returning an existing connection from the connection pool. Conn will 1636 // block until either a connection is returned or ctx is canceled. 1637 // Queries run on the same Conn will be run in the same database session. 1638 // 1639 // Every Conn must be returned to the database pool after use by 1640 // calling Conn.Close. 1641 func (db *DB) Conn(ctx context.Context) (*Conn, error) { 1642 var dc *driverConn 1643 var err error 1644 for i := 0; i < maxBadConnRetries; i++ { 1645 dc, err = db.conn(ctx, cachedOrNewConn) 1646 if err != driver.ErrBadConn { 1647 break 1648 } 1649 } 1650 if err == driver.ErrBadConn { 1651 dc, err = db.conn(ctx, cachedOrNewConn) 1652 } 1653 if err != nil { 1654 return nil, err 1655 } 1656 1657 conn := &Conn{ 1658 db: db, 1659 dc: dc, 1660 } 1661 return conn, nil 1662 } 1663 1664 type releaseConn func(error) 1665 1666 // Conn represents a single database connection rather than a pool of database 1667 // connections. Prefer running queries from DB unless there is a specific 1668 // need for a continuous single database connection. 1669 // 1670 // A Conn must call Close to return the connection to the database pool 1671 // and may do so concurrently with a running query. 1672 // 1673 // After a call to Close, all operations on the 1674 // connection fail with ErrConnDone. 1675 type Conn struct { 1676 db *DB 1677 1678 // closemu prevents the connection from closing while there 1679 // is an active query. It is held for read during queries 1680 // and exclusively during close. 1681 closemu sync.RWMutex 1682 1683 // dc is owned until close, at which point 1684 // it's returned to the connection pool. 1685 dc *driverConn 1686 1687 // done transitions from 0 to 1 exactly once, on close. 1688 // Once done, all operations fail with ErrConnDone. 1689 // Use atomic operations on value when checking value. 1690 done int32 1691 } 1692 1693 func (c *Conn) grabConn(context.Context) (*driverConn, releaseConn, error) { 1694 if atomic.LoadInt32(&c.done) != 0 { 1695 return nil, nil, ErrConnDone 1696 } 1697 c.closemu.RLock() 1698 return c.dc, c.closemuRUnlockCondReleaseConn, nil 1699 } 1700 1701 // PingContext verifies the connection to the database is still alive. 1702 func (c *Conn) PingContext(ctx context.Context) error { 1703 dc, release, err := c.grabConn(ctx) 1704 if err != nil { 1705 return err 1706 } 1707 return c.db.pingDC(ctx, dc, release) 1708 } 1709 1710 // ExecContext executes a query without returning any rows. 1711 // The args are for any placeholder parameters in the query. 1712 func (c *Conn) ExecContext(ctx context.Context, query string, args ...interface{}) (Result, error) { 1713 dc, release, err := c.grabConn(ctx) 1714 if err != nil { 1715 return nil, err 1716 } 1717 return c.db.execDC(ctx, dc, release, query, args) 1718 } 1719 1720 // QueryContext executes a query that returns rows, typically a SELECT. 1721 // The args are for any placeholder parameters in the query. 1722 func (c *Conn) QueryContext(ctx context.Context, query string, args ...interface{}) (*Rows, error) { 1723 dc, release, err := c.grabConn(ctx) 1724 if err != nil { 1725 return nil, err 1726 } 1727 return c.db.queryDC(ctx, nil, dc, release, query, args) 1728 } 1729 1730 // QueryRowContext executes a query that is expected to return at most one row. 1731 // QueryRowContext always returns a non-nil value. Errors are deferred until 1732 // Row's Scan method is called. 1733 // If the query selects no rows, the *Row's Scan will return ErrNoRows. 1734 // Otherwise, the *Row's Scan scans the first selected row and discards 1735 // the rest. 1736 func (c *Conn) QueryRowContext(ctx context.Context, query string, args ...interface{}) *Row { 1737 rows, err := c.QueryContext(ctx, query, args...) 1738 return &Row{rows: rows, err: err} 1739 } 1740 1741 // PrepareContext creates a prepared statement for later queries or executions. 1742 // Multiple queries or executions may be run concurrently from the 1743 // returned statement. 1744 // The caller must call the statement's Close method 1745 // when the statement is no longer needed. 1746 // 1747 // The provided context is used for the preparation of the statement, not for the 1748 // execution of the statement. 1749 func (c *Conn) PrepareContext(ctx context.Context, query string) (*Stmt, error) { 1750 dc, release, err := c.grabConn(ctx) 1751 if err != nil { 1752 return nil, err 1753 } 1754 return c.db.prepareDC(ctx, dc, release, c, query) 1755 } 1756 1757 // BeginTx starts a transaction. 1758 // 1759 // The provided context is used until the transaction is committed or rolled back. 1760 // If the context is canceled, the sql package will roll back 1761 // the transaction. Tx.Commit will return an error if the context provided to 1762 // BeginTx is canceled. 1763 // 1764 // The provided TxOptions is optional and may be nil if defaults should be used. 1765 // If a non-default isolation level is used that the driver doesn't support, 1766 // an error will be returned. 1767 func (c *Conn) BeginTx(ctx context.Context, opts *TxOptions) (*Tx, error) { 1768 dc, release, err := c.grabConn(ctx) 1769 if err != nil { 1770 return nil, err 1771 } 1772 return c.db.beginDC(ctx, dc, release, opts) 1773 } 1774 1775 // closemuRUnlockCondReleaseConn read unlocks closemu 1776 // as the sql operation is done with the dc. 1777 func (c *Conn) closemuRUnlockCondReleaseConn(err error) { 1778 c.closemu.RUnlock() 1779 if err == driver.ErrBadConn { 1780 c.close(err) 1781 } 1782 } 1783 1784 func (c *Conn) txCtx() context.Context { 1785 return nil 1786 } 1787 1788 func (c *Conn) close(err error) error { 1789 if !atomic.CompareAndSwapInt32(&c.done, 0, 1) { 1790 return ErrConnDone 1791 } 1792 1793 // Lock around releasing the driver connection 1794 // to ensure all queries have been stopped before doing so. 1795 c.closemu.Lock() 1796 defer c.closemu.Unlock() 1797 1798 c.dc.releaseConn(err) 1799 c.dc = nil 1800 c.db = nil 1801 return err 1802 } 1803 1804 // Close returns the connection to the connection pool. 1805 // All operations after a Close will return with ErrConnDone. 1806 // Close is safe to call concurrently with other operations and will 1807 // block until all other operations finish. It may be useful to first 1808 // cancel any used context and then call close directly after. 1809 func (c *Conn) Close() error { 1810 return c.close(nil) 1811 } 1812 1813 // Tx is an in-progress database transaction. 1814 // 1815 // A transaction must end with a call to Commit or Rollback. 1816 // 1817 // After a call to Commit or Rollback, all operations on the 1818 // transaction fail with ErrTxDone. 1819 // 1820 // The statements prepared for a transaction by calling 1821 // the transaction's Prepare or Stmt methods are closed 1822 // by the call to Commit or Rollback. 1823 type Tx struct { 1824 db *DB 1825 1826 // closemu prevents the transaction from closing while there 1827 // is an active query. It is held for read during queries 1828 // and exclusively during close. 1829 closemu sync.RWMutex 1830 1831 // dc is owned exclusively until Commit or Rollback, at which point 1832 // it's returned with putConn. 1833 dc *driverConn 1834 txi driver.Tx 1835 1836 // releaseConn is called once the Tx is closed to release 1837 // any held driverConn back to the pool. 1838 releaseConn func(error) 1839 1840 // done transitions from 0 to 1 exactly once, on Commit 1841 // or Rollback. once done, all operations fail with 1842 // ErrTxDone. 1843 // Use atomic operations on value when checking value. 1844 done int32 1845 1846 // All Stmts prepared for this transaction. These will be closed after the 1847 // transaction has been committed or rolled back. 1848 stmts struct { 1849 sync.Mutex 1850 v []*Stmt 1851 } 1852 1853 // cancel is called after done transitions from 0 to 1. 1854 cancel func() 1855 1856 // ctx lives for the life of the transaction. 1857 ctx context.Context 1858 } 1859 1860 // awaitDone blocks until the context in Tx is canceled and rolls back 1861 // the transaction if it's not already done. 1862 func (tx *Tx) awaitDone() { 1863 // Wait for either the transaction to be committed or rolled 1864 // back, or for the associated context to be closed. 1865 <-tx.ctx.Done() 1866 1867 // Discard and close the connection used to ensure the 1868 // transaction is closed and the resources are released. This 1869 // rollback does nothing if the transaction has already been 1870 // committed or rolled back. 1871 tx.rollback(true) 1872 } 1873 1874 func (tx *Tx) isDone() bool { 1875 return atomic.LoadInt32(&tx.done) != 0 1876 } 1877 1878 // ErrTxDone is returned by any operation that is performed on a transaction 1879 // that has already been committed or rolled back. 1880 var ErrTxDone = errors.New("sql: Transaction has already been committed or rolled back") 1881 1882 // close returns the connection to the pool and 1883 // must only be called by Tx.rollback or Tx.Commit. 1884 func (tx *Tx) close(err error) { 1885 tx.cancel() 1886 1887 tx.closemu.Lock() 1888 defer tx.closemu.Unlock() 1889 1890 tx.releaseConn(err) 1891 tx.dc = nil 1892 tx.txi = nil 1893 } 1894 1895 // hookTxGrabConn specifies an optional hook to be called on 1896 // a successful call to (*Tx).grabConn. For tests. 1897 var hookTxGrabConn func() 1898 1899 func (tx *Tx) grabConn(ctx context.Context) (*driverConn, releaseConn, error) { 1900 select { 1901 default: 1902 case <-ctx.Done(): 1903 return nil, nil, ctx.Err() 1904 } 1905 1906 // closeme.RLock must come before the check for isDone to prevent the Tx from 1907 // closing while a query is executing. 1908 tx.closemu.RLock() 1909 if tx.isDone() { 1910 tx.closemu.RUnlock() 1911 return nil, nil, ErrTxDone 1912 } 1913 if hookTxGrabConn != nil { // test hook 1914 hookTxGrabConn() 1915 } 1916 return tx.dc, tx.closemuRUnlockRelease, nil 1917 } 1918 1919 func (tx *Tx) txCtx() context.Context { 1920 return tx.ctx 1921 } 1922 1923 // closemuRUnlockRelease is used as a func(error) method value in 1924 // ExecContext and QueryContext. Unlocking in the releaseConn keeps 1925 // the driver conn from being returned to the connection pool until 1926 // the Rows has been closed. 1927 func (tx *Tx) closemuRUnlockRelease(error) { 1928 tx.closemu.RUnlock() 1929 } 1930 1931 // Closes all Stmts prepared for this transaction. 1932 func (tx *Tx) closePrepared() { 1933 tx.stmts.Lock() 1934 defer tx.stmts.Unlock() 1935 for _, stmt := range tx.stmts.v { 1936 stmt.Close() 1937 } 1938 } 1939 1940 // Commit commits the transaction. 1941 func (tx *Tx) Commit() error { 1942 // Check context first to avoid transaction leak. 1943 // If put it behind tx.done CompareAndSwap statement, we cant't ensure 1944 // the consistency between tx.done and the real COMMIT operation. 1945 select { 1946 default: 1947 case <-tx.ctx.Done(): 1948 if atomic.LoadInt32(&tx.done) == 1 { 1949 return ErrTxDone 1950 } 1951 return tx.ctx.Err() 1952 } 1953 if !atomic.CompareAndSwapInt32(&tx.done, 0, 1) { 1954 return ErrTxDone 1955 } 1956 var err error 1957 withLock(tx.dc, func() { 1958 err = tx.txi.Commit() 1959 }) 1960 if err != driver.ErrBadConn { 1961 tx.closePrepared() 1962 } 1963 tx.close(err) 1964 return err 1965 } 1966 1967 // rollback aborts the transaction and optionally forces the pool to discard 1968 // the connection. 1969 func (tx *Tx) rollback(discardConn bool) error { 1970 if !atomic.CompareAndSwapInt32(&tx.done, 0, 1) { 1971 return ErrTxDone 1972 } 1973 var err error 1974 withLock(tx.dc, func() { 1975 err = tx.txi.Rollback() 1976 }) 1977 if err != driver.ErrBadConn { 1978 tx.closePrepared() 1979 } 1980 if discardConn { 1981 err = driver.ErrBadConn 1982 } 1983 tx.close(err) 1984 return err 1985 } 1986 1987 // Rollback aborts the transaction. 1988 func (tx *Tx) Rollback() error { 1989 return tx.rollback(false) 1990 } 1991 1992 // PrepareContext creates a prepared statement for use within a transaction. 1993 // 1994 // The returned statement operates within the transaction and will be closed 1995 // when the transaction has been committed or rolled back. 1996 // 1997 // To use an existing prepared statement on this transaction, see Tx.Stmt. 1998 // 1999 // The provided context will be used for the preparation of the context, not 2000 // for the execution of the returned statement. The returned statement 2001 // will run in the transaction context. 2002 func (tx *Tx) PrepareContext(ctx context.Context, query string) (*Stmt, error) { 2003 dc, release, err := tx.grabConn(ctx) 2004 if err != nil { 2005 return nil, err 2006 } 2007 2008 stmt, err := tx.db.prepareDC(ctx, dc, release, tx, query) 2009 if err != nil { 2010 return nil, err 2011 } 2012 tx.stmts.Lock() 2013 tx.stmts.v = append(tx.stmts.v, stmt) 2014 tx.stmts.Unlock() 2015 return stmt, nil 2016 } 2017 2018 // Prepare creates a prepared statement for use within a transaction. 2019 // 2020 // The returned statement operates within the transaction and can no longer 2021 // be used once the transaction has been committed or rolled back. 2022 // 2023 // To use an existing prepared statement on this transaction, see Tx.Stmt. 2024 func (tx *Tx) Prepare(query string) (*Stmt, error) { 2025 return tx.PrepareContext(context.Background(), query) 2026 } 2027 2028 // StmtContext returns a transaction-specific prepared statement from 2029 // an existing statement. 2030 // 2031 // Example: 2032 // updateMoney, err := db.Prepare("UPDATE balance SET money=money+? WHERE id=?") 2033 // ... 2034 // tx, err := db.Begin() 2035 // ... 2036 // res, err := tx.StmtContext(ctx, updateMoney).Exec(123.45, 98293203) 2037 // 2038 // The provided context is used for the preparation of the statement, not for the 2039 // execution of the statement. 2040 // 2041 // The returned statement operates within the transaction and will be closed 2042 // when the transaction has been committed or rolled back. 2043 func (tx *Tx) StmtContext(ctx context.Context, stmt *Stmt) *Stmt { 2044 dc, release, err := tx.grabConn(ctx) 2045 if err != nil { 2046 return &Stmt{stickyErr: err} 2047 } 2048 defer release(nil) 2049 2050 if tx.db != stmt.db { 2051 return &Stmt{stickyErr: errors.New("sql: Tx.Stmt: statement from different database used")} 2052 } 2053 var si driver.Stmt 2054 var parentStmt *Stmt 2055 stmt.mu.Lock() 2056 if stmt.closed || stmt.cg != nil { 2057 // If the statement has been closed or already belongs to a 2058 // transaction, we can't reuse it in this connection. 2059 // Since tx.StmtContext should never need to be called with a 2060 // Stmt already belonging to tx, we ignore this edge case and 2061 // re-prepare the statement in this case. No need to add 2062 // code-complexity for this. 2063 stmt.mu.Unlock() 2064 withLock(dc, func() { 2065 si, err = ctxDriverPrepare(ctx, dc.ci, stmt.query) 2066 }) 2067 if err != nil { 2068 return &Stmt{stickyErr: err} 2069 } 2070 } else { 2071 stmt.removeClosedStmtLocked() 2072 // See if the statement has already been prepared on this connection, 2073 // and reuse it if possible. 2074 for _, v := range stmt.css { 2075 if v.dc == dc { 2076 si = v.ds.si 2077 break 2078 } 2079 } 2080 2081 stmt.mu.Unlock() 2082 2083 if si == nil { 2084 var ds *driverStmt 2085 withLock(dc, func() { 2086 ds, err = stmt.prepareOnConnLocked(ctx, dc) 2087 }) 2088 if err != nil { 2089 return &Stmt{stickyErr: err} 2090 } 2091 si = ds.si 2092 } 2093 parentStmt = stmt 2094 } 2095 2096 txs := &Stmt{ 2097 db: tx.db, 2098 cg: tx, 2099 cgds: &driverStmt{ 2100 Locker: dc, 2101 si: si, 2102 }, 2103 parentStmt: parentStmt, 2104 query: stmt.query, 2105 } 2106 if parentStmt != nil { 2107 tx.db.addDep(parentStmt, txs) 2108 } 2109 tx.stmts.Lock() 2110 tx.stmts.v = append(tx.stmts.v, txs) 2111 tx.stmts.Unlock() 2112 return txs 2113 } 2114 2115 // Stmt returns a transaction-specific prepared statement from 2116 // an existing statement. 2117 // 2118 // Example: 2119 // updateMoney, err := db.Prepare("UPDATE balance SET money=money+? WHERE id=?") 2120 // ... 2121 // tx, err := db.Begin() 2122 // ... 2123 // res, err := tx.Stmt(updateMoney).Exec(123.45, 98293203) 2124 // 2125 // The returned statement operates within the transaction and will be closed 2126 // when the transaction has been committed or rolled back. 2127 func (tx *Tx) Stmt(stmt *Stmt) *Stmt { 2128 return tx.StmtContext(context.Background(), stmt) 2129 } 2130 2131 // ExecContext executes a query that doesn't return rows. 2132 // For example: an INSERT and UPDATE. 2133 func (tx *Tx) ExecContext(ctx context.Context, query string, args ...interface{}) (Result, error) { 2134 dc, release, err := tx.grabConn(ctx) 2135 if err != nil { 2136 return nil, err 2137 } 2138 return tx.db.execDC(ctx, dc, release, query, args) 2139 } 2140 2141 // Exec executes a query that doesn't return rows. 2142 // For example: an INSERT and UPDATE. 2143 func (tx *Tx) Exec(query string, args ...interface{}) (Result, error) { 2144 return tx.ExecContext(context.Background(), query, args...) 2145 } 2146 2147 // QueryContext executes a query that returns rows, typically a SELECT. 2148 func (tx *Tx) QueryContext(ctx context.Context, query string, args ...interface{}) (*Rows, error) { 2149 dc, release, err := tx.grabConn(ctx) 2150 if err != nil { 2151 return nil, err 2152 } 2153 2154 return tx.db.queryDC(ctx, tx.ctx, dc, release, query, args) 2155 } 2156 2157 // Query executes a query that returns rows, typically a SELECT. 2158 func (tx *Tx) Query(query string, args ...interface{}) (*Rows, error) { 2159 return tx.QueryContext(context.Background(), query, args...) 2160 } 2161 2162 // QueryRowContext executes a query that is expected to return at most one row. 2163 // QueryRowContext always returns a non-nil value. Errors are deferred until 2164 // Row's Scan method is called. 2165 // If the query selects no rows, the *Row's Scan will return ErrNoRows. 2166 // Otherwise, the *Row's Scan scans the first selected row and discards 2167 // the rest. 2168 func (tx *Tx) QueryRowContext(ctx context.Context, query string, args ...interface{}) *Row { 2169 rows, err := tx.QueryContext(ctx, query, args...) 2170 return &Row{rows: rows, err: err} 2171 } 2172 2173 // QueryRow executes a query that is expected to return at most one row. 2174 // QueryRow always returns a non-nil value. Errors are deferred until 2175 // Row's Scan method is called. 2176 // If the query selects no rows, the *Row's Scan will return ErrNoRows. 2177 // Otherwise, the *Row's Scan scans the first selected row and discards 2178 // the rest. 2179 func (tx *Tx) QueryRow(query string, args ...interface{}) *Row { 2180 return tx.QueryRowContext(context.Background(), query, args...) 2181 } 2182 2183 // connStmt is a prepared statement on a particular connection. 2184 type connStmt struct { 2185 dc *driverConn 2186 ds *driverStmt 2187 } 2188 2189 // stmtConnGrabber represents a Tx or Conn that will return the underlying 2190 // driverConn and release function. 2191 type stmtConnGrabber interface { 2192 // grabConn returns the driverConn and the associated release function 2193 // that must be called when the operation completes. 2194 grabConn(context.Context) (*driverConn, releaseConn, error) 2195 2196 // txCtx returns the transaction context if available. 2197 // The returned context should be selected on along with 2198 // any query context when awaiting a cancel. 2199 txCtx() context.Context 2200 } 2201 2202 var ( 2203 _ stmtConnGrabber = &Tx{} 2204 _ stmtConnGrabber = &Conn{} 2205 ) 2206 2207 // Stmt is a prepared statement. 2208 // A Stmt is safe for concurrent use by multiple goroutines. 2209 type Stmt struct { 2210 // Immutable: 2211 db *DB // where we came from 2212 query string // that created the Stmt 2213 stickyErr error // if non-nil, this error is returned for all operations 2214 2215 closemu sync.RWMutex // held exclusively during close, for read otherwise. 2216 2217 // If Stmt is prepared on a Tx or Conn then cg is present and will 2218 // only ever grab a connection from cg. 2219 // If cg is nil then the Stmt must grab an arbitrary connection 2220 // from db and determine if it must prepare the stmt again by 2221 // inspecting css. 2222 cg stmtConnGrabber 2223 cgds *driverStmt 2224 2225 // parentStmt is set when a transaction-specific statement 2226 // is requested from an identical statement prepared on the same 2227 // conn. parentStmt is used to track the dependency of this statement 2228 // on its originating ("parent") statement so that parentStmt may 2229 // be closed by the user without them having to know whether or not 2230 // any transactions are still using it. 2231 parentStmt *Stmt 2232 2233 mu sync.Mutex // protects the rest of the fields 2234 closed bool 2235 2236 // css is a list of underlying driver statement interfaces 2237 // that are valid on particular connections. This is only 2238 // used if cg == nil and one is found that has idle 2239 // connections. If cg != nil, cgds is always used. 2240 css []connStmt 2241 2242 // lastNumClosed is copied from db.numClosed when Stmt is created 2243 // without tx and closed connections in css are removed. 2244 lastNumClosed uint64 2245 } 2246 2247 // ExecContext executes a prepared statement with the given arguments and 2248 // returns a Result summarizing the effect of the statement. 2249 func (s *Stmt) ExecContext(ctx context.Context, args ...interface{}) (Result, error) { 2250 s.closemu.RLock() 2251 defer s.closemu.RUnlock() 2252 2253 var res Result 2254 strategy := cachedOrNewConn 2255 for i := 0; i < maxBadConnRetries+1; i++ { 2256 if i == maxBadConnRetries { 2257 strategy = alwaysNewConn 2258 } 2259 dc, releaseConn, ds, err := s.connStmt(ctx, strategy) 2260 if err != nil { 2261 if err == driver.ErrBadConn { 2262 continue 2263 } 2264 return nil, err 2265 } 2266 2267 res, err = resultFromStatement(ctx, dc.ci, ds, args...) 2268 releaseConn(err) 2269 if err != driver.ErrBadConn { 2270 return res, err 2271 } 2272 } 2273 return nil, driver.ErrBadConn 2274 } 2275 2276 // Exec executes a prepared statement with the given arguments and 2277 // returns a Result summarizing the effect of the statement. 2278 func (s *Stmt) Exec(args ...interface{}) (Result, error) { 2279 return s.ExecContext(context.Background(), args...) 2280 } 2281 2282 func resultFromStatement(ctx context.Context, ci driver.Conn, ds *driverStmt, args ...interface{}) (Result, error) { 2283 ds.Lock() 2284 defer ds.Unlock() 2285 2286 dargs, err := driverArgsConnLocked(ci, ds, args) 2287 if err != nil { 2288 return nil, err 2289 } 2290 2291 resi, err := ctxDriverStmtExec(ctx, ds.si, dargs) 2292 if err != nil { 2293 return nil, err 2294 } 2295 return driverResult{ds.Locker, resi}, nil 2296 } 2297 2298 // removeClosedStmtLocked removes closed conns in s.css. 2299 // 2300 // To avoid lock contention on DB.mu, we do it only when 2301 // s.db.numClosed - s.lastNum is large enough. 2302 func (s *Stmt) removeClosedStmtLocked() { 2303 t := len(s.css)/2 + 1 2304 if t > 10 { 2305 t = 10 2306 } 2307 dbClosed := atomic.LoadUint64(&s.db.numClosed) 2308 if dbClosed-s.lastNumClosed < uint64(t) { 2309 return 2310 } 2311 2312 s.db.mu.Lock() 2313 for i := 0; i < len(s.css); i++ { 2314 if s.css[i].dc.dbmuClosed { 2315 s.css[i] = s.css[len(s.css)-1] 2316 s.css = s.css[:len(s.css)-1] 2317 i-- 2318 } 2319 } 2320 s.db.mu.Unlock() 2321 s.lastNumClosed = dbClosed 2322 } 2323 2324 // connStmt returns a free driver connection on which to execute the 2325 // statement, a function to call to release the connection, and a 2326 // statement bound to that connection. 2327 func (s *Stmt) connStmt(ctx context.Context, strategy connReuseStrategy) (dc *driverConn, releaseConn func(error), ds *driverStmt, err error) { 2328 if err = s.stickyErr; err != nil { 2329 return 2330 } 2331 s.mu.Lock() 2332 if s.closed { 2333 s.mu.Unlock() 2334 err = errors.New("sql: statement is closed") 2335 return 2336 } 2337 2338 // In a transaction or connection, we always use the connection that the 2339 // stmt was created on. 2340 if s.cg != nil { 2341 s.mu.Unlock() 2342 dc, releaseConn, err = s.cg.grabConn(ctx) // blocks, waiting for the connection. 2343 if err != nil { 2344 return 2345 } 2346 return dc, releaseConn, s.cgds, nil 2347 } 2348 2349 s.removeClosedStmtLocked() 2350 s.mu.Unlock() 2351 2352 dc, err = s.db.conn(ctx, strategy) 2353 if err != nil { 2354 return nil, nil, nil, err 2355 } 2356 2357 s.mu.Lock() 2358 for _, v := range s.css { 2359 if v.dc == dc { 2360 s.mu.Unlock() 2361 return dc, dc.releaseConn, v.ds, nil 2362 } 2363 } 2364 s.mu.Unlock() 2365 2366 // No luck; we need to prepare the statement on this connection 2367 withLock(dc, func() { 2368 ds, err = s.prepareOnConnLocked(ctx, dc) 2369 }) 2370 if err != nil { 2371 dc.releaseConn(err) 2372 return nil, nil, nil, err 2373 } 2374 2375 return dc, dc.releaseConn, ds, nil 2376 } 2377 2378 // prepareOnConnLocked prepares the query in Stmt s on dc and adds it to the list of 2379 // open connStmt on the statement. It assumes the caller is holding the lock on dc. 2380 func (s *Stmt) prepareOnConnLocked(ctx context.Context, dc *driverConn) (*driverStmt, error) { 2381 si, err := dc.prepareLocked(ctx, s.cg, s.query) 2382 if err != nil { 2383 return nil, err 2384 } 2385 cs := connStmt{dc, si} 2386 s.mu.Lock() 2387 s.css = append(s.css, cs) 2388 s.mu.Unlock() 2389 return cs.ds, nil 2390 } 2391 2392 // QueryContext executes a prepared query statement with the given arguments 2393 // and returns the query results as a *Rows. 2394 func (s *Stmt) QueryContext(ctx context.Context, args ...interface{}) (*Rows, error) { 2395 s.closemu.RLock() 2396 defer s.closemu.RUnlock() 2397 2398 var rowsi driver.Rows 2399 strategy := cachedOrNewConn 2400 for i := 0; i < maxBadConnRetries+1; i++ { 2401 if i == maxBadConnRetries { 2402 strategy = alwaysNewConn 2403 } 2404 dc, releaseConn, ds, err := s.connStmt(ctx, strategy) 2405 if err != nil { 2406 if err == driver.ErrBadConn { 2407 continue 2408 } 2409 return nil, err 2410 } 2411 2412 rowsi, err = rowsiFromStatement(ctx, dc.ci, ds, args...) 2413 if err == nil { 2414 // Note: ownership of ci passes to the *Rows, to be freed 2415 // with releaseConn. 2416 rows := &Rows{ 2417 dc: dc, 2418 rowsi: rowsi, 2419 // releaseConn set below 2420 } 2421 // addDep must be added before initContextClose or it could attempt 2422 // to removeDep before it has been added. 2423 s.db.addDep(s, rows) 2424 2425 // releaseConn must be set before initContextClose or it could 2426 // release the connection before it is set. 2427 rows.releaseConn = func(err error) { 2428 releaseConn(err) 2429 s.db.removeDep(s, rows) 2430 } 2431 var txctx context.Context 2432 if s.cg != nil { 2433 txctx = s.cg.txCtx() 2434 } 2435 rows.initContextClose(ctx, txctx) 2436 return rows, nil 2437 } 2438 2439 releaseConn(err) 2440 if err != driver.ErrBadConn { 2441 return nil, err 2442 } 2443 } 2444 return nil, driver.ErrBadConn 2445 } 2446 2447 // Query executes a prepared query statement with the given arguments 2448 // and returns the query results as a *Rows. 2449 func (s *Stmt) Query(args ...interface{}) (*Rows, error) { 2450 return s.QueryContext(context.Background(), args...) 2451 } 2452 2453 func rowsiFromStatement(ctx context.Context, ci driver.Conn, ds *driverStmt, args ...interface{}) (driver.Rows, error) { 2454 ds.Lock() 2455 defer ds.Unlock() 2456 2457 dargs, err := driverArgsConnLocked(ci, ds, args) 2458 if err != nil { 2459 return nil, err 2460 } 2461 2462 rowsi, err := ctxDriverStmtQuery(ctx, ds.si, dargs) 2463 if err != nil { 2464 return nil, err 2465 } 2466 return rowsi, nil 2467 } 2468 2469 // QueryRowContext executes a prepared query statement with the given arguments. 2470 // If an error occurs during the execution of the statement, that error will 2471 // be returned by a call to Scan on the returned *Row, which is always non-nil. 2472 // If the query selects no rows, the *Row's Scan will return ErrNoRows. 2473 // Otherwise, the *Row's Scan scans the first selected row and discards 2474 // the rest. 2475 // 2476 // Example usage: 2477 // 2478 // var name string 2479 // err := nameByUseridStmt.QueryRowContext(ctx, id).Scan(&name) 2480 func (s *Stmt) QueryRowContext(ctx context.Context, args ...interface{}) *Row { 2481 rows, err := s.QueryContext(ctx, args...) 2482 if err != nil { 2483 return &Row{err: err} 2484 } 2485 return &Row{rows: rows} 2486 } 2487 2488 // QueryRow executes a prepared query statement with the given arguments. 2489 // If an error occurs during the execution of the statement, that error will 2490 // be returned by a call to Scan on the returned *Row, which is always non-nil. 2491 // If the query selects no rows, the *Row's Scan will return ErrNoRows. 2492 // Otherwise, the *Row's Scan scans the first selected row and discards 2493 // the rest. 2494 // 2495 // Example usage: 2496 // 2497 // var name string 2498 // err := nameByUseridStmt.QueryRow(id).Scan(&name) 2499 func (s *Stmt) QueryRow(args ...interface{}) *Row { 2500 return s.QueryRowContext(context.Background(), args...) 2501 } 2502 2503 // Close closes the statement. 2504 func (s *Stmt) Close() error { 2505 s.closemu.Lock() 2506 defer s.closemu.Unlock() 2507 2508 if s.stickyErr != nil { 2509 return s.stickyErr 2510 } 2511 s.mu.Lock() 2512 if s.closed { 2513 s.mu.Unlock() 2514 return nil 2515 } 2516 s.closed = true 2517 txds := s.cgds 2518 s.cgds = nil 2519 2520 s.mu.Unlock() 2521 2522 if s.cg == nil { 2523 return s.db.removeDep(s, s) 2524 } 2525 2526 if s.parentStmt != nil { 2527 // If parentStmt is set, we must not close s.txds since it's stored 2528 // in the css array of the parentStmt. 2529 return s.db.removeDep(s.parentStmt, s) 2530 } 2531 return txds.Close() 2532 } 2533 2534 func (s *Stmt) finalClose() error { 2535 s.mu.Lock() 2536 defer s.mu.Unlock() 2537 if s.css != nil { 2538 for _, v := range s.css { 2539 s.db.noteUnusedDriverStatement(v.dc, v.ds) 2540 v.dc.removeOpenStmt(v.ds) 2541 } 2542 s.css = nil 2543 } 2544 return nil 2545 } 2546 2547 // Rows is the result of a query. Its cursor starts before the first row 2548 // of the result set. Use Next to advance through the rows: 2549 // 2550 // rows, err := db.Query("SELECT ...") 2551 // ... 2552 // defer rows.Close() 2553 // for rows.Next() { 2554 // var id int 2555 // var name string 2556 // err = rows.Scan(&id, &name) 2557 // ... 2558 // } 2559 // err = rows.Err() // get any error encountered during iteration 2560 // ... 2561 type Rows struct { 2562 dc *driverConn // owned; must call releaseConn when closed to release 2563 releaseConn func(error) 2564 rowsi driver.Rows 2565 cancel func() // called when Rows is closed, may be nil. 2566 closeStmt *driverStmt // if non-nil, statement to Close on close 2567 2568 // closemu prevents Rows from closing while there 2569 // is an active streaming result. It is held for read during non-close operations 2570 // and exclusively during close. 2571 // 2572 // closemu guards lasterr and closed. 2573 closemu sync.RWMutex 2574 closed bool 2575 lasterr error // non-nil only if closed is true 2576 2577 // lastcols is only used in Scan, Next, and NextResultSet which are expected 2578 // not to be called concurrently. 2579 lastcols []driver.Value 2580 } 2581 2582 func (rs *Rows) initContextClose(ctx, txctx context.Context) { 2583 ctx, rs.cancel = context.WithCancel(ctx) 2584 go rs.awaitDone(ctx, txctx) 2585 } 2586 2587 // awaitDone blocks until either ctx or txctx is canceled. The ctx is provided 2588 // from the query context and is canceled when the query Rows is closed. 2589 // If the query was issued in a transaction, the transaction's context 2590 // is also provided in txctx to ensure Rows is closed if the Tx is closed. 2591 func (rs *Rows) awaitDone(ctx, txctx context.Context) { 2592 var txctxDone <-chan struct{} 2593 if txctx != nil { 2594 txctxDone = txctx.Done() 2595 } 2596 select { 2597 case <-ctx.Done(): 2598 case <-txctxDone: 2599 } 2600 rs.close(ctx.Err()) 2601 } 2602 2603 // Next prepares the next result row for reading with the Scan method. It 2604 // returns true on success, or false if there is no next result row or an error 2605 // happened while preparing it. Err should be consulted to distinguish between 2606 // the two cases. 2607 // 2608 // Every call to Scan, even the first one, must be preceded by a call to Next. 2609 func (rs *Rows) Next() bool { 2610 var doClose, ok bool 2611 withLock(rs.closemu.RLocker(), func() { 2612 doClose, ok = rs.nextLocked() 2613 }) 2614 if doClose { 2615 rs.Close() 2616 } 2617 return ok 2618 } 2619 2620 func (rs *Rows) nextLocked() (doClose, ok bool) { 2621 if rs.closed { 2622 return false, false 2623 } 2624 2625 // Lock the driver connection before calling the driver interface 2626 // rowsi to prevent a Tx from rolling back the connection at the same time. 2627 rs.dc.Lock() 2628 defer rs.dc.Unlock() 2629 2630 if rs.lastcols == nil { 2631 rs.lastcols = make([]driver.Value, len(rs.rowsi.Columns())) 2632 } 2633 2634 rs.lasterr = rs.rowsi.Next(rs.lastcols) 2635 if rs.lasterr != nil { 2636 // Close the connection if there is a driver error. 2637 if rs.lasterr != io.EOF { 2638 return true, false 2639 } 2640 nextResultSet, ok := rs.rowsi.(driver.RowsNextResultSet) 2641 if !ok { 2642 return true, false 2643 } 2644 // The driver is at the end of the current result set. 2645 // Test to see if there is another result set after the current one. 2646 // Only close Rows if there is no further result sets to read. 2647 if !nextResultSet.HasNextResultSet() { 2648 doClose = true 2649 } 2650 return doClose, false 2651 } 2652 return false, true 2653 } 2654 2655 // NextResultSet prepares the next result set for reading. It returns true if 2656 // there is further result sets, or false if there is no further result set 2657 // or if there is an error advancing to it. The Err method should be consulted 2658 // to distinguish between the two cases. 2659 // 2660 // After calling NextResultSet, the Next method should always be called before 2661 // scanning. If there are further result sets they may not have rows in the result 2662 // set. 2663 func (rs *Rows) NextResultSet() bool { 2664 var doClose bool 2665 defer func() { 2666 if doClose { 2667 rs.Close() 2668 } 2669 }() 2670 rs.closemu.RLock() 2671 defer rs.closemu.RUnlock() 2672 2673 if rs.closed { 2674 return false 2675 } 2676 2677 rs.lastcols = nil 2678 nextResultSet, ok := rs.rowsi.(driver.RowsNextResultSet) 2679 if !ok { 2680 doClose = true 2681 return false 2682 } 2683 2684 // Lock the driver connection before calling the driver interface 2685 // rowsi to prevent a Tx from rolling back the connection at the same time. 2686 rs.dc.Lock() 2687 defer rs.dc.Unlock() 2688 2689 rs.lasterr = nextResultSet.NextResultSet() 2690 if rs.lasterr != nil { 2691 doClose = true 2692 return false 2693 } 2694 return true 2695 } 2696 2697 // Err returns the error, if any, that was encountered during iteration. 2698 // Err may be called after an explicit or implicit Close. 2699 func (rs *Rows) Err() error { 2700 rs.closemu.RLock() 2701 defer rs.closemu.RUnlock() 2702 if rs.lasterr == io.EOF { 2703 return nil 2704 } 2705 return rs.lasterr 2706 } 2707 2708 // Columns returns the column names. 2709 // Columns returns an error if the rows are closed, or if the rows 2710 // are from QueryRow and there was a deferred error. 2711 func (rs *Rows) Columns() ([]string, error) { 2712 rs.closemu.RLock() 2713 defer rs.closemu.RUnlock() 2714 if rs.closed { 2715 return nil, errors.New("sql: Rows are closed") 2716 } 2717 if rs.rowsi == nil { 2718 return nil, errors.New("sql: no Rows available") 2719 } 2720 rs.dc.Lock() 2721 defer rs.dc.Unlock() 2722 2723 return rs.rowsi.Columns(), nil 2724 } 2725 2726 // ColumnTypes returns column information such as column type, length, 2727 // and nullable. Some information may not be available from some drivers. 2728 func (rs *Rows) ColumnTypes() ([]*ColumnType, error) { 2729 rs.closemu.RLock() 2730 defer rs.closemu.RUnlock() 2731 if rs.closed { 2732 return nil, errors.New("sql: Rows are closed") 2733 } 2734 if rs.rowsi == nil { 2735 return nil, errors.New("sql: no Rows available") 2736 } 2737 rs.dc.Lock() 2738 defer rs.dc.Unlock() 2739 2740 return rowsColumnInfoSetupConnLocked(rs.rowsi), nil 2741 } 2742 2743 // ColumnType contains the name and type of a column. 2744 type ColumnType struct { 2745 name string 2746 2747 hasNullable bool 2748 hasLength bool 2749 hasPrecisionScale bool 2750 2751 nullable bool 2752 length int64 2753 databaseType string 2754 precision int64 2755 scale int64 2756 scanType reflect.Type 2757 } 2758 2759 // Name returns the name or alias of the column. 2760 func (ci *ColumnType) Name() string { 2761 return ci.name 2762 } 2763 2764 // Length returns the column type length for variable length column types such 2765 // as text and binary field types. If the type length is unbounded the value will 2766 // be math.MaxInt64 (any database limits will still apply). 2767 // If the column type is not variable length, such as an int, or if not supported 2768 // by the driver ok is false. 2769 func (ci *ColumnType) Length() (length int64, ok bool) { 2770 return ci.length, ci.hasLength 2771 } 2772 2773 // DecimalSize returns the scale and precision of a decimal type. 2774 // If not applicable or if not supported ok is false. 2775 func (ci *ColumnType) DecimalSize() (precision, scale int64, ok bool) { 2776 return ci.precision, ci.scale, ci.hasPrecisionScale 2777 } 2778 2779 // ScanType returns a Go type suitable for scanning into using Rows.Scan. 2780 // If a driver does not support this property ScanType will return 2781 // the type of an empty interface. 2782 func (ci *ColumnType) ScanType() reflect.Type { 2783 return ci.scanType 2784 } 2785 2786 // Nullable returns whether the column may be null. 2787 // If a driver does not support this property ok will be false. 2788 func (ci *ColumnType) Nullable() (nullable, ok bool) { 2789 return ci.nullable, ci.hasNullable 2790 } 2791 2792 // DatabaseTypeName returns the database system name of the column type. If an empty 2793 // string is returned the driver type name is not supported. 2794 // Consult your driver documentation for a list of driver data types. Length specifiers 2795 // are not included. 2796 // Common type include "VARCHAR", "TEXT", "NVARCHAR", "DECIMAL", "BOOL", "INT", "BIGINT". 2797 func (ci *ColumnType) DatabaseTypeName() string { 2798 return ci.databaseType 2799 } 2800 2801 func rowsColumnInfoSetupConnLocked(rowsi driver.Rows) []*ColumnType { 2802 names := rowsi.Columns() 2803 2804 list := make([]*ColumnType, len(names)) 2805 for i := range list { 2806 ci := &ColumnType{ 2807 name: names[i], 2808 } 2809 list[i] = ci 2810 2811 if prop, ok := rowsi.(driver.RowsColumnTypeScanType); ok { 2812 ci.scanType = prop.ColumnTypeScanType(i) 2813 } else { 2814 ci.scanType = reflect.TypeOf(new(interface{})).Elem() 2815 } 2816 if prop, ok := rowsi.(driver.RowsColumnTypeDatabaseTypeName); ok { 2817 ci.databaseType = prop.ColumnTypeDatabaseTypeName(i) 2818 } 2819 if prop, ok := rowsi.(driver.RowsColumnTypeLength); ok { 2820 ci.length, ci.hasLength = prop.ColumnTypeLength(i) 2821 } 2822 if prop, ok := rowsi.(driver.RowsColumnTypeNullable); ok { 2823 ci.nullable, ci.hasNullable = prop.ColumnTypeNullable(i) 2824 } 2825 if prop, ok := rowsi.(driver.RowsColumnTypePrecisionScale); ok { 2826 ci.precision, ci.scale, ci.hasPrecisionScale = prop.ColumnTypePrecisionScale(i) 2827 } 2828 } 2829 return list 2830 } 2831 2832 // Scan copies the columns in the current row into the values pointed 2833 // at by dest. The number of values in dest must be the same as the 2834 // number of columns in Rows. 2835 // 2836 // Scan converts columns read from the database into the following 2837 // common Go types and special types provided by the sql package: 2838 // 2839 // *string 2840 // *[]byte 2841 // *int, *int8, *int16, *int32, *int64 2842 // *uint, *uint8, *uint16, *uint32, *uint64 2843 // *bool 2844 // *float32, *float64 2845 // *interface{} 2846 // *RawBytes 2847 // any type implementing Scanner (see Scanner docs) 2848 // 2849 // In the most simple case, if the type of the value from the source 2850 // column is an integer, bool or string type T and dest is of type *T, 2851 // Scan simply assigns the value through the pointer. 2852 // 2853 // Scan also converts between string and numeric types, as long as no 2854 // information would be lost. While Scan stringifies all numbers 2855 // scanned from numeric database columns into *string, scans into 2856 // numeric types are checked for overflow. For example, a float64 with 2857 // value 300 or a string with value "300" can scan into a uint16, but 2858 // not into a uint8, though float64(255) or "255" can scan into a 2859 // uint8. One exception is that scans of some float64 numbers to 2860 // strings may lose information when stringifying. In general, scan 2861 // floating point columns into *float64. 2862 // 2863 // If a dest argument has type *[]byte, Scan saves in that argument a 2864 // copy of the corresponding data. The copy is owned by the caller and 2865 // can be modified and held indefinitely. The copy can be avoided by 2866 // using an argument of type *RawBytes instead; see the documentation 2867 // for RawBytes for restrictions on its use. 2868 // 2869 // If an argument has type *interface{}, Scan copies the value 2870 // provided by the underlying driver without conversion. When scanning 2871 // from a source value of type []byte to *interface{}, a copy of the 2872 // slice is made and the caller owns the result. 2873 // 2874 // Source values of type time.Time may be scanned into values of type 2875 // *time.Time, *interface{}, *string, or *[]byte. When converting to 2876 // the latter two, time.Format3339Nano is used. 2877 // 2878 // Source values of type bool may be scanned into types *bool, 2879 // *interface{}, *string, *[]byte, or *RawBytes. 2880 // 2881 // For scanning into *bool, the source may be true, false, 1, 0, or 2882 // string inputs parseable by strconv.ParseBool. 2883 func (rs *Rows) Scan(dest ...interface{}) error { 2884 rs.closemu.RLock() 2885 if rs.closed { 2886 rs.closemu.RUnlock() 2887 return errors.New("sql: Rows are closed") 2888 } 2889 rs.closemu.RUnlock() 2890 2891 if rs.lastcols == nil { 2892 return errors.New("sql: Scan called without calling Next") 2893 } 2894 if len(dest) != len(rs.lastcols) { 2895 return fmt.Errorf("sql: expected %d destination arguments in Scan, not %d", len(rs.lastcols), len(dest)) 2896 } 2897 for i, sv := range rs.lastcols { 2898 err := convertAssign(dest[i], sv) 2899 if err != nil { 2900 return fmt.Errorf(`sql: Scan error on column index %d, name %q: %v`, i, rs.rowsi.Columns()[i], err) 2901 } 2902 } 2903 return nil 2904 } 2905 2906 // rowsCloseHook returns a function so tests may install the 2907 // hook through a test only mutex. 2908 var rowsCloseHook = func() func(*Rows, *error) { return nil } 2909 2910 // Close closes the Rows, preventing further enumeration. If Next is called 2911 // and returns false and there are no further result sets, 2912 // the Rows are closed automatically and it will suffice to check the 2913 // result of Err. Close is idempotent and does not affect the result of Err. 2914 func (rs *Rows) Close() error { 2915 return rs.close(nil) 2916 } 2917 2918 func (rs *Rows) close(err error) error { 2919 rs.closemu.Lock() 2920 defer rs.closemu.Unlock() 2921 2922 if rs.closed { 2923 return nil 2924 } 2925 rs.closed = true 2926 2927 if rs.lasterr == nil { 2928 rs.lasterr = err 2929 } 2930 2931 withLock(rs.dc, func() { 2932 err = rs.rowsi.Close() 2933 }) 2934 if fn := rowsCloseHook(); fn != nil { 2935 fn(rs, &err) 2936 } 2937 if rs.cancel != nil { 2938 rs.cancel() 2939 } 2940 2941 if rs.closeStmt != nil { 2942 rs.closeStmt.Close() 2943 } 2944 rs.releaseConn(err) 2945 return err 2946 } 2947 2948 // Row is the result of calling QueryRow to select a single row. 2949 type Row struct { 2950 // One of these two will be non-nil: 2951 err error // deferred error for easy chaining 2952 rows *Rows 2953 } 2954 2955 // Scan copies the columns from the matched row into the values 2956 // pointed at by dest. See the documentation on Rows.Scan for details. 2957 // If more than one row matches the query, 2958 // Scan uses the first row and discards the rest. If no row matches 2959 // the query, Scan returns ErrNoRows. 2960 func (r *Row) Scan(dest ...interface{}) error { 2961 if r.err != nil { 2962 return r.err 2963 } 2964 2965 // TODO(bradfitz): for now we need to defensively clone all 2966 // []byte that the driver returned (not permitting 2967 // *RawBytes in Rows.Scan), since we're about to close 2968 // the Rows in our defer, when we return from this function. 2969 // the contract with the driver.Next(...) interface is that it 2970 // can return slices into read-only temporary memory that's 2971 // only valid until the next Scan/Close. But the TODO is that 2972 // for a lot of drivers, this copy will be unnecessary. We 2973 // should provide an optional interface for drivers to 2974 // implement to say, "don't worry, the []bytes that I return 2975 // from Next will not be modified again." (for instance, if 2976 // they were obtained from the network anyway) But for now we 2977 // don't care. 2978 defer r.rows.Close() 2979 for _, dp := range dest { 2980 if _, ok := dp.(*RawBytes); ok { 2981 return errors.New("sql: RawBytes isn't allowed on Row.Scan") 2982 } 2983 } 2984 2985 if !r.rows.Next() { 2986 if err := r.rows.Err(); err != nil { 2987 return err 2988 } 2989 return ErrNoRows 2990 } 2991 err := r.rows.Scan(dest...) 2992 if err != nil { 2993 return err 2994 } 2995 // Make sure the query can be processed to completion with no errors. 2996 if err := r.rows.Close(); err != nil { 2997 return err 2998 } 2999 3000 return nil 3001 } 3002 3003 // A Result summarizes an executed SQL command. 3004 type Result interface { 3005 // LastInsertId returns the integer generated by the database 3006 // in response to a command. Typically this will be from an 3007 // "auto increment" column when inserting a new row. Not all 3008 // databases support this feature, and the syntax of such 3009 // statements varies. 3010 LastInsertId() (int64, error) 3011 3012 // RowsAffected returns the number of rows affected by an 3013 // update, insert, or delete. Not every database or database 3014 // driver may support this. 3015 RowsAffected() (int64, error) 3016 } 3017 3018 type driverResult struct { 3019 sync.Locker // the *driverConn 3020 resi driver.Result 3021 } 3022 3023 func (dr driverResult) LastInsertId() (int64, error) { 3024 dr.Lock() 3025 defer dr.Unlock() 3026 return dr.resi.LastInsertId() 3027 } 3028 3029 func (dr driverResult) RowsAffected() (int64, error) { 3030 dr.Lock() 3031 defer dr.Unlock() 3032 return dr.resi.RowsAffected() 3033 } 3034 3035 func stack() string { 3036 var buf [2 << 10]byte 3037 return string(buf[:runtime.Stack(buf[:], false)]) 3038 } 3039 3040 // withLock runs while holding lk. 3041 func withLock(lk sync.Locker, fn func()) { 3042 lk.Lock() 3043 defer lk.Unlock() // in case fn panics 3044 fn() 3045 }