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