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