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