github.com/ccccaoqing/test@v0.0.0-20220510085219-3985d23445c0/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 http://golang.org/s/sqldrivers for a list of drivers. 10 // 11 // For more usage examples, see the wiki page at 12 // http://golang.org/s/sqlwiki. 13 package sql 14 15 import ( 16 "database/sql/driver" 17 "errors" 18 "fmt" 19 "io" 20 "runtime" 21 "sort" 22 "sync" 23 ) 24 25 var drivers = make(map[string]driver.Driver) 26 27 // Register makes a database driver available by the provided name. 28 // If Register is called twice with the same name or if driver is nil, 29 // it panics. 30 func Register(name string, driver driver.Driver) { 31 if driver == nil { 32 panic("sql: Register driver is nil") 33 } 34 if _, dup := drivers[name]; dup { 35 panic("sql: Register called twice for driver " + name) 36 } 37 drivers[name] = driver 38 } 39 40 func unregisterAllDrivers() { 41 // For tests. 42 drivers = make(map[string]driver.Driver) 43 } 44 45 // Drivers returns a sorted list of the names of the registered drivers. 46 func Drivers() []string { 47 var list []string 48 for name := range drivers { 49 list = append(list, name) 50 } 51 sort.Strings(list) 52 return list 53 } 54 55 // RawBytes is a byte slice that holds a reference to memory owned by 56 // the database itself. After a Scan into a RawBytes, the slice is only 57 // valid until the next call to Next, Scan, or Close. 58 type RawBytes []byte 59 60 // NullString represents a string that may be null. 61 // NullString implements the Scanner interface so 62 // it can be used as a scan destination: 63 // 64 // var s NullString 65 // err := db.QueryRow("SELECT name FROM foo WHERE id=?", id).Scan(&s) 66 // ... 67 // if s.Valid { 68 // // use s.String 69 // } else { 70 // // NULL value 71 // } 72 // 73 type NullString struct { 74 String string 75 Valid bool // Valid is true if String is not NULL 76 } 77 78 // Scan implements the Scanner interface. 79 func (ns *NullString) Scan(value interface{}) error { 80 if value == nil { 81 ns.String, ns.Valid = "", false 82 return nil 83 } 84 ns.Valid = true 85 return convertAssign(&ns.String, value) 86 } 87 88 // Value implements the driver Valuer interface. 89 func (ns NullString) Value() (driver.Value, error) { 90 if !ns.Valid { 91 return nil, nil 92 } 93 return ns.String, nil 94 } 95 96 // NullInt64 represents an int64 that may be null. 97 // NullInt64 implements the Scanner interface so 98 // it can be used as a scan destination, similar to NullString. 99 type NullInt64 struct { 100 Int64 int64 101 Valid bool // Valid is true if Int64 is not NULL 102 } 103 104 // Scan implements the Scanner interface. 105 func (n *NullInt64) Scan(value interface{}) error { 106 if value == nil { 107 n.Int64, n.Valid = 0, false 108 return nil 109 } 110 n.Valid = true 111 return convertAssign(&n.Int64, value) 112 } 113 114 // Value implements the driver Valuer interface. 115 func (n NullInt64) Value() (driver.Value, error) { 116 if !n.Valid { 117 return nil, nil 118 } 119 return n.Int64, nil 120 } 121 122 // NullFloat64 represents a float64 that may be null. 123 // NullFloat64 implements the Scanner interface so 124 // it can be used as a scan destination, similar to NullString. 125 type NullFloat64 struct { 126 Float64 float64 127 Valid bool // Valid is true if Float64 is not NULL 128 } 129 130 // Scan implements the Scanner interface. 131 func (n *NullFloat64) Scan(value interface{}) error { 132 if value == nil { 133 n.Float64, n.Valid = 0, false 134 return nil 135 } 136 n.Valid = true 137 return convertAssign(&n.Float64, value) 138 } 139 140 // Value implements the driver Valuer interface. 141 func (n NullFloat64) Value() (driver.Value, error) { 142 if !n.Valid { 143 return nil, nil 144 } 145 return n.Float64, nil 146 } 147 148 // NullBool represents a bool that may be null. 149 // NullBool implements the Scanner interface so 150 // it can be used as a scan destination, similar to NullString. 151 type NullBool struct { 152 Bool bool 153 Valid bool // Valid is true if Bool is not NULL 154 } 155 156 // Scan implements the Scanner interface. 157 func (n *NullBool) Scan(value interface{}) error { 158 if value == nil { 159 n.Bool, n.Valid = false, false 160 return nil 161 } 162 n.Valid = true 163 return convertAssign(&n.Bool, value) 164 } 165 166 // Value implements the driver Valuer interface. 167 func (n NullBool) Value() (driver.Value, error) { 168 if !n.Valid { 169 return nil, nil 170 } 171 return n.Bool, nil 172 } 173 174 // Scanner is an interface used by Scan. 175 type Scanner interface { 176 // Scan assigns a value from a database driver. 177 // 178 // The src value will be of one of the following restricted 179 // set of types: 180 // 181 // int64 182 // float64 183 // bool 184 // []byte 185 // string 186 // time.Time 187 // nil - for NULL values 188 // 189 // An error should be returned if the value can not be stored 190 // without loss of information. 191 Scan(src interface{}) error 192 } 193 194 // ErrNoRows is returned by Scan when QueryRow doesn't return a 195 // row. In such a case, QueryRow returns a placeholder *Row value that 196 // defers this error until a Scan. 197 var ErrNoRows = errors.New("sql: no rows in result set") 198 199 // DB is a database handle representing a pool of zero or more 200 // underlying connections. It's safe for concurrent use by multiple 201 // goroutines. 202 // 203 // The sql package creates and frees connections automatically; it 204 // also maintains a free pool of idle connections. If the database has 205 // a concept of per-connection state, such state can only be reliably 206 // observed within a transaction. Once DB.Begin is called, the 207 // returned Tx is bound to a single connection. Once Commit or 208 // Rollback is called on the transaction, that transaction's 209 // connection is returned to DB's idle connection pool. The pool size 210 // can be controlled with SetMaxIdleConns. 211 type DB struct { 212 driver driver.Driver 213 dsn string 214 215 mu sync.Mutex // protects following fields 216 freeConn []*driverConn 217 connRequests []chan connRequest 218 numOpen int 219 pendingOpens int 220 // Used to signal the need for new connections 221 // a goroutine running connectionOpener() reads on this chan and 222 // maybeOpenNewConnections sends on the chan (one send per needed connection) 223 // It is closed during db.Close(). The close tells the connectionOpener 224 // goroutine to exit. 225 openerCh chan struct{} 226 closed bool 227 dep map[finalCloser]depSet 228 lastPut map[*driverConn]string // stacktrace of last conn's put; debug only 229 maxIdle int // zero means defaultMaxIdleConns; negative means 0 230 maxOpen int // <= 0 means unlimited 231 } 232 233 // driverConn wraps a driver.Conn with a mutex, to 234 // be held during all calls into the Conn. (including any calls onto 235 // interfaces returned via that Conn, such as calls on Tx, Stmt, 236 // Result, Rows) 237 type driverConn struct { 238 db *DB 239 240 sync.Mutex // guards following 241 ci driver.Conn 242 closed bool 243 finalClosed bool // ci.Close has been called 244 openStmt map[driver.Stmt]bool 245 246 // guarded by db.mu 247 inUse bool 248 onPut []func() // code (with db.mu held) run when conn is next returned 249 dbmuClosed bool // same as closed, but guarded by db.mu, for connIfFree 250 } 251 252 func (dc *driverConn) releaseConn(err error) { 253 dc.db.putConn(dc, err) 254 } 255 256 func (dc *driverConn) removeOpenStmt(si driver.Stmt) { 257 dc.Lock() 258 defer dc.Unlock() 259 delete(dc.openStmt, si) 260 } 261 262 func (dc *driverConn) prepareLocked(query string) (driver.Stmt, error) { 263 si, err := dc.ci.Prepare(query) 264 if err == nil { 265 // Track each driverConn's open statements, so we can close them 266 // before closing the conn. 267 // 268 // TODO(bradfitz): let drivers opt out of caring about 269 // stmt closes if the conn is about to close anyway? For now 270 // do the safe thing, in case stmts need to be closed. 271 // 272 // TODO(bradfitz): after Go 1.2, closing driver.Stmts 273 // should be moved to driverStmt, using unique 274 // *driverStmts everywhere (including from 275 // *Stmt.connStmt, instead of returning a 276 // driver.Stmt), using driverStmt as a pointer 277 // everywhere, and making it a finalCloser. 278 if dc.openStmt == nil { 279 dc.openStmt = make(map[driver.Stmt]bool) 280 } 281 dc.openStmt[si] = true 282 } 283 return si, err 284 } 285 286 // the dc.db's Mutex is held. 287 func (dc *driverConn) closeDBLocked() func() error { 288 dc.Lock() 289 defer dc.Unlock() 290 if dc.closed { 291 return func() error { return errors.New("sql: duplicate driverConn close") } 292 } 293 dc.closed = true 294 return dc.db.removeDepLocked(dc, dc) 295 } 296 297 func (dc *driverConn) Close() error { 298 dc.Lock() 299 if dc.closed { 300 dc.Unlock() 301 return errors.New("sql: duplicate driverConn close") 302 } 303 dc.closed = true 304 dc.Unlock() // not defer; removeDep finalClose calls may need to lock 305 306 // And now updates that require holding dc.mu.Lock. 307 dc.db.mu.Lock() 308 dc.dbmuClosed = true 309 fn := dc.db.removeDepLocked(dc, dc) 310 dc.db.mu.Unlock() 311 return fn() 312 } 313 314 func (dc *driverConn) finalClose() error { 315 dc.Lock() 316 317 for si := range dc.openStmt { 318 si.Close() 319 } 320 dc.openStmt = nil 321 322 err := dc.ci.Close() 323 dc.ci = nil 324 dc.finalClosed = true 325 dc.Unlock() 326 327 dc.db.mu.Lock() 328 dc.db.numOpen-- 329 dc.db.maybeOpenNewConnections() 330 dc.db.mu.Unlock() 331 332 return err 333 } 334 335 // driverStmt associates a driver.Stmt with the 336 // *driverConn from which it came, so the driverConn's lock can be 337 // held during calls. 338 type driverStmt struct { 339 sync.Locker // the *driverConn 340 si driver.Stmt 341 } 342 343 func (ds *driverStmt) Close() error { 344 ds.Lock() 345 defer ds.Unlock() 346 return ds.si.Close() 347 } 348 349 // depSet is a finalCloser's outstanding dependencies 350 type depSet map[interface{}]bool // set of true bools 351 352 // The finalCloser interface is used by (*DB).addDep and related 353 // dependency reference counting. 354 type finalCloser interface { 355 // finalClose is called when the reference count of an object 356 // goes to zero. (*DB).mu is not held while calling it. 357 finalClose() error 358 } 359 360 // addDep notes that x now depends on dep, and x's finalClose won't be 361 // called until all of x's dependencies are removed with removeDep. 362 func (db *DB) addDep(x finalCloser, dep interface{}) { 363 //println(fmt.Sprintf("addDep(%T %p, %T %p)", x, x, dep, dep)) 364 db.mu.Lock() 365 defer db.mu.Unlock() 366 db.addDepLocked(x, dep) 367 } 368 369 func (db *DB) addDepLocked(x finalCloser, dep interface{}) { 370 if db.dep == nil { 371 db.dep = make(map[finalCloser]depSet) 372 } 373 xdep := db.dep[x] 374 if xdep == nil { 375 xdep = make(depSet) 376 db.dep[x] = xdep 377 } 378 xdep[dep] = true 379 } 380 381 // removeDep notes that x no longer depends on dep. 382 // If x still has dependencies, nil is returned. 383 // If x no longer has any dependencies, its finalClose method will be 384 // called and its error value will be returned. 385 func (db *DB) removeDep(x finalCloser, dep interface{}) error { 386 db.mu.Lock() 387 fn := db.removeDepLocked(x, dep) 388 db.mu.Unlock() 389 return fn() 390 } 391 392 func (db *DB) removeDepLocked(x finalCloser, dep interface{}) func() error { 393 //println(fmt.Sprintf("removeDep(%T %p, %T %p)", x, x, dep, dep)) 394 395 xdep, ok := db.dep[x] 396 if !ok { 397 panic(fmt.Sprintf("unpaired removeDep: no deps for %T", x)) 398 } 399 400 l0 := len(xdep) 401 delete(xdep, dep) 402 403 switch len(xdep) { 404 case l0: 405 // Nothing removed. Shouldn't happen. 406 panic(fmt.Sprintf("unpaired removeDep: no %T dep on %T", dep, x)) 407 case 0: 408 // No more dependencies. 409 delete(db.dep, x) 410 return x.finalClose 411 default: 412 // Dependencies remain. 413 return func() error { return nil } 414 } 415 } 416 417 // This is the size of the connectionOpener request chan (dn.openerCh). 418 // This value should be larger than the maximum typical value 419 // used for db.maxOpen. If maxOpen is significantly larger than 420 // connectionRequestQueueSize then it is possible for ALL calls into the *DB 421 // to block until the connectionOpener can satisfy the backlog of requests. 422 var connectionRequestQueueSize = 1000000 423 424 // Open opens a database specified by its database driver name and a 425 // driver-specific data source name, usually consisting of at least a 426 // database name and connection information. 427 // 428 // Most users will open a database via a driver-specific connection 429 // helper function that returns a *DB. No database drivers are included 430 // in the Go standard library. See http://golang.org/s/sqldrivers for 431 // a list of third-party drivers. 432 // 433 // Open may just validate its arguments without creating a connection 434 // to the database. To verify that the data source name is valid, call 435 // Ping. 436 // 437 // The returned DB is safe for concurrent use by multiple goroutines 438 // and maintains its own pool of idle connections. Thus, the Open 439 // function should be called just once. It is rarely necessary to 440 // close a DB. 441 func Open(driverName, dataSourceName string) (*DB, error) { 442 driveri, ok := drivers[driverName] 443 if !ok { 444 return nil, fmt.Errorf("sql: unknown driver %q (forgotten import?)", driverName) 445 } 446 db := &DB{ 447 driver: driveri, 448 dsn: dataSourceName, 449 openerCh: make(chan struct{}, connectionRequestQueueSize), 450 lastPut: make(map[*driverConn]string), 451 } 452 go db.connectionOpener() 453 return db, nil 454 } 455 456 // Ping verifies a connection to the database is still alive, 457 // establishing a connection if necessary. 458 func (db *DB) Ping() error { 459 // TODO(bradfitz): give drivers an optional hook to implement 460 // this in a more efficient or more reliable way, if they 461 // have one. 462 dc, err := db.conn() 463 if err != nil { 464 return err 465 } 466 db.putConn(dc, nil) 467 return nil 468 } 469 470 // Close closes the database, releasing any open resources. 471 // 472 // It is rare to Close a DB, as the DB handle is meant to be 473 // long-lived and shared between many goroutines. 474 func (db *DB) Close() error { 475 db.mu.Lock() 476 if db.closed { // Make DB.Close idempotent 477 db.mu.Unlock() 478 return nil 479 } 480 close(db.openerCh) 481 var err error 482 fns := make([]func() error, 0, len(db.freeConn)) 483 for _, dc := range db.freeConn { 484 fns = append(fns, dc.closeDBLocked()) 485 } 486 db.freeConn = nil 487 db.closed = true 488 for _, req := range db.connRequests { 489 close(req) 490 } 491 db.mu.Unlock() 492 for _, fn := range fns { 493 err1 := fn() 494 if err1 != nil { 495 err = err1 496 } 497 } 498 return err 499 } 500 501 const defaultMaxIdleConns = 2 502 503 func (db *DB) maxIdleConnsLocked() int { 504 n := db.maxIdle 505 switch { 506 case n == 0: 507 // TODO(bradfitz): ask driver, if supported, for its default preference 508 return defaultMaxIdleConns 509 case n < 0: 510 return 0 511 default: 512 return n 513 } 514 } 515 516 // SetMaxIdleConns sets the maximum number of connections in the idle 517 // connection pool. 518 // 519 // If MaxOpenConns is greater than 0 but less than the new MaxIdleConns 520 // then the new MaxIdleConns will be reduced to match the MaxOpenConns limit 521 // 522 // If n <= 0, no idle connections are retained. 523 func (db *DB) SetMaxIdleConns(n int) { 524 db.mu.Lock() 525 if n > 0 { 526 db.maxIdle = n 527 } else { 528 // No idle connections. 529 db.maxIdle = -1 530 } 531 // Make sure maxIdle doesn't exceed maxOpen 532 if db.maxOpen > 0 && db.maxIdleConnsLocked() > db.maxOpen { 533 db.maxIdle = db.maxOpen 534 } 535 var closing []*driverConn 536 idleCount := len(db.freeConn) 537 maxIdle := db.maxIdleConnsLocked() 538 if idleCount > maxIdle { 539 closing = db.freeConn[maxIdle:] 540 db.freeConn = db.freeConn[:maxIdle] 541 } 542 db.mu.Unlock() 543 for _, c := range closing { 544 c.Close() 545 } 546 } 547 548 // SetMaxOpenConns sets the maximum number of open connections to the database. 549 // 550 // If MaxIdleConns is greater than 0 and the new MaxOpenConns is less than 551 // MaxIdleConns, then MaxIdleConns will be reduced to match the new 552 // MaxOpenConns limit 553 // 554 // If n <= 0, then there is no limit on the number of open connections. 555 // The default is 0 (unlimited). 556 func (db *DB) SetMaxOpenConns(n int) { 557 db.mu.Lock() 558 db.maxOpen = n 559 if n < 0 { 560 db.maxOpen = 0 561 } 562 syncMaxIdle := db.maxOpen > 0 && db.maxIdleConnsLocked() > db.maxOpen 563 db.mu.Unlock() 564 if syncMaxIdle { 565 db.SetMaxIdleConns(n) 566 } 567 } 568 569 // Assumes db.mu is locked. 570 // If there are connRequests and the connection limit hasn't been reached, 571 // then tell the connectionOpener to open new connections. 572 func (db *DB) maybeOpenNewConnections() { 573 numRequests := len(db.connRequests) - db.pendingOpens 574 if db.maxOpen > 0 { 575 numCanOpen := db.maxOpen - (db.numOpen + db.pendingOpens) 576 if numRequests > numCanOpen { 577 numRequests = numCanOpen 578 } 579 } 580 for numRequests > 0 { 581 db.pendingOpens++ 582 numRequests-- 583 db.openerCh <- struct{}{} 584 } 585 } 586 587 // Runs in a separate goroutine, opens new connections when requested. 588 func (db *DB) connectionOpener() { 589 for range db.openerCh { 590 db.openNewConnection() 591 } 592 } 593 594 // Open one new connection 595 func (db *DB) openNewConnection() { 596 ci, err := db.driver.Open(db.dsn) 597 db.mu.Lock() 598 defer db.mu.Unlock() 599 if db.closed { 600 if err == nil { 601 ci.Close() 602 } 603 return 604 } 605 db.pendingOpens-- 606 if err != nil { 607 db.putConnDBLocked(nil, err) 608 return 609 } 610 dc := &driverConn{ 611 db: db, 612 ci: ci, 613 } 614 if db.putConnDBLocked(dc, err) { 615 db.addDepLocked(dc, dc) 616 db.numOpen++ 617 } else { 618 ci.Close() 619 } 620 } 621 622 // connRequest represents one request for a new connection 623 // When there are no idle connections available, DB.conn will create 624 // a new connRequest and put it on the db.connRequests list. 625 type connRequest struct { 626 conn *driverConn 627 err error 628 } 629 630 var errDBClosed = errors.New("sql: database is closed") 631 632 // conn returns a newly-opened or cached *driverConn 633 func (db *DB) conn() (*driverConn, error) { 634 db.mu.Lock() 635 if db.closed { 636 db.mu.Unlock() 637 return nil, errDBClosed 638 } 639 640 // If db.maxOpen > 0 and the number of open connections is over the limit 641 // and there are no free connection, make a request and wait. 642 if db.maxOpen > 0 && db.numOpen >= db.maxOpen && len(db.freeConn) == 0 { 643 // Make the connRequest channel. It's buffered so that the 644 // connectionOpener doesn't block while waiting for the req to be read. 645 req := make(chan connRequest, 1) 646 db.connRequests = append(db.connRequests, req) 647 db.maybeOpenNewConnections() 648 db.mu.Unlock() 649 ret := <-req 650 return ret.conn, ret.err 651 } 652 653 if c := len(db.freeConn); c > 0 { 654 conn := db.freeConn[0] 655 copy(db.freeConn, db.freeConn[1:]) 656 db.freeConn = db.freeConn[:c-1] 657 conn.inUse = true 658 db.mu.Unlock() 659 return conn, nil 660 } 661 662 db.numOpen++ // optimistically 663 db.mu.Unlock() 664 ci, err := db.driver.Open(db.dsn) 665 if err != nil { 666 db.mu.Lock() 667 db.numOpen-- // correct for earlier optimism 668 db.mu.Unlock() 669 return nil, err 670 } 671 db.mu.Lock() 672 dc := &driverConn{ 673 db: db, 674 ci: ci, 675 } 676 db.addDepLocked(dc, dc) 677 dc.inUse = true 678 db.mu.Unlock() 679 return dc, nil 680 } 681 682 var ( 683 errConnClosed = errors.New("database/sql: internal sentinel error: conn is closed") 684 errConnBusy = errors.New("database/sql: internal sentinel error: conn is busy") 685 ) 686 687 // connIfFree returns (wanted, nil) if wanted is still a valid conn and 688 // isn't in use. 689 // 690 // The error is errConnClosed if the connection if the requested connection 691 // is invalid because it's been closed. 692 // 693 // The error is errConnBusy if the connection is in use. 694 func (db *DB) connIfFree(wanted *driverConn) (*driverConn, error) { 695 db.mu.Lock() 696 defer db.mu.Unlock() 697 if wanted.dbmuClosed { 698 return nil, errConnClosed 699 } 700 if wanted.inUse { 701 return nil, errConnBusy 702 } 703 idx := -1 704 for ii, v := range db.freeConn { 705 if v == wanted { 706 idx = ii 707 break 708 } 709 } 710 if idx >= 0 { 711 db.freeConn = append(db.freeConn[:idx], db.freeConn[idx+1:]...) 712 wanted.inUse = true 713 return wanted, nil 714 } 715 // TODO(bradfitz): shouldn't get here. After Go 1.1, change this to: 716 // panic("connIfFree call requested a non-closed, non-busy, non-free conn") 717 // Which passes all the tests, but I'm too paranoid to include this 718 // late in Go 1.1. 719 // Instead, treat it like a busy connection: 720 return nil, errConnBusy 721 } 722 723 // putConnHook is a hook for testing. 724 var putConnHook func(*DB, *driverConn) 725 726 // noteUnusedDriverStatement notes that si is no longer used and should 727 // be closed whenever possible (when c is next not in use), unless c is 728 // already closed. 729 func (db *DB) noteUnusedDriverStatement(c *driverConn, si driver.Stmt) { 730 db.mu.Lock() 731 defer db.mu.Unlock() 732 if c.inUse { 733 c.onPut = append(c.onPut, func() { 734 si.Close() 735 }) 736 } else { 737 c.Lock() 738 defer c.Unlock() 739 if !c.finalClosed { 740 si.Close() 741 } 742 } 743 } 744 745 // debugGetPut determines whether getConn & putConn calls' stack traces 746 // are returned for more verbose crashes. 747 const debugGetPut = false 748 749 // putConn adds a connection to the db's free pool. 750 // err is optionally the last error that occurred on this connection. 751 func (db *DB) putConn(dc *driverConn, err error) { 752 db.mu.Lock() 753 if !dc.inUse { 754 if debugGetPut { 755 fmt.Printf("putConn(%v) DUPLICATE was: %s\n\nPREVIOUS was: %s", dc, stack(), db.lastPut[dc]) 756 } 757 panic("sql: connection returned that was never out") 758 } 759 if debugGetPut { 760 db.lastPut[dc] = stack() 761 } 762 dc.inUse = false 763 764 for _, fn := range dc.onPut { 765 fn() 766 } 767 dc.onPut = nil 768 769 if err == driver.ErrBadConn { 770 // Don't reuse bad connections. 771 // Since the conn is considered bad and is being discarded, treat it 772 // as closed. Don't decrement the open count here, finalClose will 773 // take care of that. 774 db.maybeOpenNewConnections() 775 db.mu.Unlock() 776 dc.Close() 777 return 778 } 779 if putConnHook != nil { 780 putConnHook(db, dc) 781 } 782 added := db.putConnDBLocked(dc, nil) 783 db.mu.Unlock() 784 785 if !added { 786 dc.Close() 787 } 788 } 789 790 // Satisfy a connRequest or put the driverConn in the idle pool and return true 791 // or return false. 792 // putConnDBLocked will satisfy a connRequest if there is one, or it will 793 // return the *driverConn to the freeConn list if err == nil and the idle 794 // connection limit will not be exceeded. 795 // If err != nil, the value of dc is ignored. 796 // If err == nil, then dc must not equal nil. 797 // If a connRequest was fulfilled or the *driverConn was placed in the 798 // freeConn list, then true is returned, otherwise false is returned. 799 func (db *DB) putConnDBLocked(dc *driverConn, err error) bool { 800 if c := len(db.connRequests); c > 0 { 801 req := db.connRequests[0] 802 // This copy is O(n) but in practice faster than a linked list. 803 // TODO: consider compacting it down less often and 804 // moving the base instead? 805 copy(db.connRequests, db.connRequests[1:]) 806 db.connRequests = db.connRequests[:c-1] 807 if err == nil { 808 dc.inUse = true 809 } 810 req <- connRequest{ 811 conn: dc, 812 err: err, 813 } 814 return true 815 } else if err == nil && !db.closed && db.maxIdleConnsLocked() > len(db.freeConn) { 816 db.freeConn = append(db.freeConn, dc) 817 return true 818 } 819 return false 820 } 821 822 // maxBadConnRetries is the number of maximum retries if the driver returns 823 // driver.ErrBadConn to signal a broken connection. 824 const maxBadConnRetries = 10 825 826 // Prepare creates a prepared statement for later queries or executions. 827 // Multiple queries or executions may be run concurrently from the 828 // returned statement. 829 func (db *DB) Prepare(query string) (*Stmt, error) { 830 var stmt *Stmt 831 var err error 832 for i := 0; i < maxBadConnRetries; i++ { 833 stmt, err = db.prepare(query) 834 if err != driver.ErrBadConn { 835 break 836 } 837 } 838 return stmt, err 839 } 840 841 func (db *DB) prepare(query string) (*Stmt, error) { 842 // TODO: check if db.driver supports an optional 843 // driver.Preparer interface and call that instead, if so, 844 // otherwise we make a prepared statement that's bound 845 // to a connection, and to execute this prepared statement 846 // we either need to use this connection (if it's free), else 847 // get a new connection + re-prepare + execute on that one. 848 dc, err := db.conn() 849 if err != nil { 850 return nil, err 851 } 852 dc.Lock() 853 si, err := dc.prepareLocked(query) 854 dc.Unlock() 855 if err != nil { 856 db.putConn(dc, err) 857 return nil, err 858 } 859 stmt := &Stmt{ 860 db: db, 861 query: query, 862 css: []connStmt{{dc, si}}, 863 } 864 db.addDep(stmt, stmt) 865 db.putConn(dc, nil) 866 return stmt, nil 867 } 868 869 // Exec executes a query without returning any rows. 870 // The args are for any placeholder parameters in the query. 871 func (db *DB) Exec(query string, args ...interface{}) (Result, error) { 872 var res Result 873 var err error 874 for i := 0; i < maxBadConnRetries; i++ { 875 res, err = db.exec(query, args) 876 if err != driver.ErrBadConn { 877 break 878 } 879 } 880 return res, err 881 } 882 883 func (db *DB) exec(query string, args []interface{}) (res Result, err error) { 884 dc, err := db.conn() 885 if err != nil { 886 return nil, err 887 } 888 defer func() { 889 db.putConn(dc, err) 890 }() 891 892 if execer, ok := dc.ci.(driver.Execer); ok { 893 dargs, err := driverArgs(nil, args) 894 if err != nil { 895 return nil, err 896 } 897 dc.Lock() 898 resi, err := execer.Exec(query, dargs) 899 dc.Unlock() 900 if err != driver.ErrSkip { 901 if err != nil { 902 return nil, err 903 } 904 return driverResult{dc, resi}, nil 905 } 906 } 907 908 dc.Lock() 909 si, err := dc.ci.Prepare(query) 910 dc.Unlock() 911 if err != nil { 912 return nil, err 913 } 914 defer withLock(dc, func() { si.Close() }) 915 return resultFromStatement(driverStmt{dc, si}, args...) 916 } 917 918 // Query executes a query that returns rows, typically a SELECT. 919 // The args are for any placeholder parameters in the query. 920 func (db *DB) Query(query string, args ...interface{}) (*Rows, error) { 921 var rows *Rows 922 var err error 923 for i := 0; i < maxBadConnRetries; i++ { 924 rows, err = db.query(query, args) 925 if err != driver.ErrBadConn { 926 break 927 } 928 } 929 return rows, err 930 } 931 932 func (db *DB) query(query string, args []interface{}) (*Rows, error) { 933 ci, err := db.conn() 934 if err != nil { 935 return nil, err 936 } 937 938 return db.queryConn(ci, ci.releaseConn, query, args) 939 } 940 941 // queryConn executes a query on the given connection. 942 // The connection gets released by the releaseConn function. 943 func (db *DB) queryConn(dc *driverConn, releaseConn func(error), query string, args []interface{}) (*Rows, error) { 944 if queryer, ok := dc.ci.(driver.Queryer); ok { 945 dargs, err := driverArgs(nil, args) 946 if err != nil { 947 releaseConn(err) 948 return nil, err 949 } 950 dc.Lock() 951 rowsi, err := queryer.Query(query, dargs) 952 dc.Unlock() 953 if err != driver.ErrSkip { 954 if err != nil { 955 releaseConn(err) 956 return nil, err 957 } 958 // Note: ownership of dc passes to the *Rows, to be freed 959 // with releaseConn. 960 rows := &Rows{ 961 dc: dc, 962 releaseConn: releaseConn, 963 rowsi: rowsi, 964 } 965 return rows, nil 966 } 967 } 968 969 dc.Lock() 970 si, err := dc.ci.Prepare(query) 971 dc.Unlock() 972 if err != nil { 973 releaseConn(err) 974 return nil, err 975 } 976 977 ds := driverStmt{dc, si} 978 rowsi, err := rowsiFromStatement(ds, args...) 979 if err != nil { 980 dc.Lock() 981 si.Close() 982 dc.Unlock() 983 releaseConn(err) 984 return nil, err 985 } 986 987 // Note: ownership of ci passes to the *Rows, to be freed 988 // with releaseConn. 989 rows := &Rows{ 990 dc: dc, 991 releaseConn: releaseConn, 992 rowsi: rowsi, 993 closeStmt: si, 994 } 995 return rows, nil 996 } 997 998 // QueryRow executes a query that is expected to return at most one row. 999 // QueryRow always return a non-nil value. Errors are deferred until 1000 // Row's Scan method is called. 1001 func (db *DB) QueryRow(query string, args ...interface{}) *Row { 1002 rows, err := db.Query(query, args...) 1003 return &Row{rows: rows, err: err} 1004 } 1005 1006 // Begin starts a transaction. The isolation level is dependent on 1007 // the driver. 1008 func (db *DB) Begin() (*Tx, error) { 1009 var tx *Tx 1010 var err error 1011 for i := 0; i < maxBadConnRetries; i++ { 1012 tx, err = db.begin() 1013 if err != driver.ErrBadConn { 1014 break 1015 } 1016 } 1017 return tx, err 1018 } 1019 1020 func (db *DB) begin() (tx *Tx, err error) { 1021 dc, err := db.conn() 1022 if err != nil { 1023 return nil, err 1024 } 1025 dc.Lock() 1026 txi, err := dc.ci.Begin() 1027 dc.Unlock() 1028 if err != nil { 1029 db.putConn(dc, err) 1030 return nil, err 1031 } 1032 return &Tx{ 1033 db: db, 1034 dc: dc, 1035 txi: txi, 1036 }, nil 1037 } 1038 1039 // Driver returns the database's underlying driver. 1040 func (db *DB) Driver() driver.Driver { 1041 return db.driver 1042 } 1043 1044 // Tx is an in-progress database transaction. 1045 // 1046 // A transaction must end with a call to Commit or Rollback. 1047 // 1048 // After a call to Commit or Rollback, all operations on the 1049 // transaction fail with ErrTxDone. 1050 type Tx struct { 1051 db *DB 1052 1053 // dc is owned exclusively until Commit or Rollback, at which point 1054 // it's returned with putConn. 1055 dc *driverConn 1056 txi driver.Tx 1057 1058 // done transitions from false to true exactly once, on Commit 1059 // or Rollback. once done, all operations fail with 1060 // ErrTxDone. 1061 done bool 1062 1063 // All Stmts prepared for this transaction. These will be closed after the 1064 // transaction has been committed or rolled back. 1065 stmts struct { 1066 sync.Mutex 1067 v []*Stmt 1068 } 1069 } 1070 1071 var ErrTxDone = errors.New("sql: Transaction has already been committed or rolled back") 1072 1073 func (tx *Tx) close() { 1074 if tx.done { 1075 panic("double close") // internal error 1076 } 1077 tx.done = true 1078 tx.db.putConn(tx.dc, nil) 1079 tx.dc = nil 1080 tx.txi = nil 1081 } 1082 1083 func (tx *Tx) grabConn() (*driverConn, error) { 1084 if tx.done { 1085 return nil, ErrTxDone 1086 } 1087 return tx.dc, nil 1088 } 1089 1090 // Closes all Stmts prepared for this transaction. 1091 func (tx *Tx) closePrepared() { 1092 tx.stmts.Lock() 1093 for _, stmt := range tx.stmts.v { 1094 stmt.Close() 1095 } 1096 tx.stmts.Unlock() 1097 } 1098 1099 // Commit commits the transaction. 1100 func (tx *Tx) Commit() error { 1101 if tx.done { 1102 return ErrTxDone 1103 } 1104 defer tx.close() 1105 tx.dc.Lock() 1106 err := tx.txi.Commit() 1107 tx.dc.Unlock() 1108 if err != driver.ErrBadConn { 1109 tx.closePrepared() 1110 } 1111 return err 1112 } 1113 1114 // Rollback aborts the transaction. 1115 func (tx *Tx) Rollback() error { 1116 if tx.done { 1117 return ErrTxDone 1118 } 1119 defer tx.close() 1120 tx.dc.Lock() 1121 err := tx.txi.Rollback() 1122 tx.dc.Unlock() 1123 if err != driver.ErrBadConn { 1124 tx.closePrepared() 1125 } 1126 return err 1127 } 1128 1129 // Prepare creates a prepared statement for use within a transaction. 1130 // 1131 // The returned statement operates within the transaction and can no longer 1132 // be used once the transaction has been committed or rolled back. 1133 // 1134 // To use an existing prepared statement on this transaction, see Tx.Stmt. 1135 func (tx *Tx) Prepare(query string) (*Stmt, error) { 1136 // TODO(bradfitz): We could be more efficient here and either 1137 // provide a method to take an existing Stmt (created on 1138 // perhaps a different Conn), and re-create it on this Conn if 1139 // necessary. Or, better: keep a map in DB of query string to 1140 // Stmts, and have Stmt.Execute do the right thing and 1141 // re-prepare if the Conn in use doesn't have that prepared 1142 // statement. But we'll want to avoid caching the statement 1143 // in the case where we only call conn.Prepare implicitly 1144 // (such as in db.Exec or tx.Exec), but the caller package 1145 // can't be holding a reference to the returned statement. 1146 // Perhaps just looking at the reference count (by noting 1147 // Stmt.Close) would be enough. We might also want a finalizer 1148 // on Stmt to drop the reference count. 1149 dc, err := tx.grabConn() 1150 if err != nil { 1151 return nil, err 1152 } 1153 1154 dc.Lock() 1155 si, err := dc.ci.Prepare(query) 1156 dc.Unlock() 1157 if err != nil { 1158 return nil, err 1159 } 1160 1161 stmt := &Stmt{ 1162 db: tx.db, 1163 tx: tx, 1164 txsi: &driverStmt{ 1165 Locker: dc, 1166 si: si, 1167 }, 1168 query: query, 1169 } 1170 tx.stmts.Lock() 1171 tx.stmts.v = append(tx.stmts.v, stmt) 1172 tx.stmts.Unlock() 1173 return stmt, nil 1174 } 1175 1176 // Stmt returns a transaction-specific prepared statement from 1177 // an existing statement. 1178 // 1179 // Example: 1180 // updateMoney, err := db.Prepare("UPDATE balance SET money=money+? WHERE id=?") 1181 // ... 1182 // tx, err := db.Begin() 1183 // ... 1184 // res, err := tx.Stmt(updateMoney).Exec(123.45, 98293203) 1185 func (tx *Tx) Stmt(stmt *Stmt) *Stmt { 1186 // TODO(bradfitz): optimize this. Currently this re-prepares 1187 // each time. This is fine for now to illustrate the API but 1188 // we should really cache already-prepared statements 1189 // per-Conn. See also the big comment in Tx.Prepare. 1190 1191 if tx.db != stmt.db { 1192 return &Stmt{stickyErr: errors.New("sql: Tx.Stmt: statement from different database used")} 1193 } 1194 dc, err := tx.grabConn() 1195 if err != nil { 1196 return &Stmt{stickyErr: err} 1197 } 1198 dc.Lock() 1199 si, err := dc.ci.Prepare(stmt.query) 1200 dc.Unlock() 1201 txs := &Stmt{ 1202 db: tx.db, 1203 tx: tx, 1204 txsi: &driverStmt{ 1205 Locker: dc, 1206 si: si, 1207 }, 1208 query: stmt.query, 1209 stickyErr: err, 1210 } 1211 tx.stmts.Lock() 1212 tx.stmts.v = append(tx.stmts.v, txs) 1213 tx.stmts.Unlock() 1214 return txs 1215 } 1216 1217 // Exec executes a query that doesn't return rows. 1218 // For example: an INSERT and UPDATE. 1219 func (tx *Tx) Exec(query string, args ...interface{}) (Result, error) { 1220 dc, err := tx.grabConn() 1221 if err != nil { 1222 return nil, err 1223 } 1224 1225 if execer, ok := dc.ci.(driver.Execer); ok { 1226 dargs, err := driverArgs(nil, args) 1227 if err != nil { 1228 return nil, err 1229 } 1230 dc.Lock() 1231 resi, err := execer.Exec(query, dargs) 1232 dc.Unlock() 1233 if err == nil { 1234 return driverResult{dc, resi}, nil 1235 } 1236 if err != driver.ErrSkip { 1237 return nil, err 1238 } 1239 } 1240 1241 dc.Lock() 1242 si, err := dc.ci.Prepare(query) 1243 dc.Unlock() 1244 if err != nil { 1245 return nil, err 1246 } 1247 defer withLock(dc, func() { si.Close() }) 1248 1249 return resultFromStatement(driverStmt{dc, si}, args...) 1250 } 1251 1252 // Query executes a query that returns rows, typically a SELECT. 1253 func (tx *Tx) Query(query string, args ...interface{}) (*Rows, error) { 1254 dc, err := tx.grabConn() 1255 if err != nil { 1256 return nil, err 1257 } 1258 releaseConn := func(error) {} 1259 return tx.db.queryConn(dc, releaseConn, query, args) 1260 } 1261 1262 // QueryRow executes a query that is expected to return at most one row. 1263 // QueryRow always return a non-nil value. Errors are deferred until 1264 // Row's Scan method is called. 1265 func (tx *Tx) QueryRow(query string, args ...interface{}) *Row { 1266 rows, err := tx.Query(query, args...) 1267 return &Row{rows: rows, err: err} 1268 } 1269 1270 // connStmt is a prepared statement on a particular connection. 1271 type connStmt struct { 1272 dc *driverConn 1273 si driver.Stmt 1274 } 1275 1276 // Stmt is a prepared statement. Stmt is safe for concurrent use by multiple goroutines. 1277 type Stmt struct { 1278 // Immutable: 1279 db *DB // where we came from 1280 query string // that created the Stmt 1281 stickyErr error // if non-nil, this error is returned for all operations 1282 1283 closemu sync.RWMutex // held exclusively during close, for read otherwise. 1284 1285 // If in a transaction, else both nil: 1286 tx *Tx 1287 txsi *driverStmt 1288 1289 mu sync.Mutex // protects the rest of the fields 1290 closed bool 1291 1292 // css is a list of underlying driver statement interfaces 1293 // that are valid on particular connections. This is only 1294 // used if tx == nil and one is found that has idle 1295 // connections. If tx != nil, txsi is always used. 1296 css []connStmt 1297 } 1298 1299 // Exec executes a prepared statement with the given arguments and 1300 // returns a Result summarizing the effect of the statement. 1301 func (s *Stmt) Exec(args ...interface{}) (Result, error) { 1302 s.closemu.RLock() 1303 defer s.closemu.RUnlock() 1304 1305 var res Result 1306 for i := 0; i < maxBadConnRetries; i++ { 1307 dc, releaseConn, si, err := s.connStmt() 1308 if err != nil { 1309 if err == driver.ErrBadConn { 1310 continue 1311 } 1312 return nil, err 1313 } 1314 1315 res, err = resultFromStatement(driverStmt{dc, si}, args...) 1316 releaseConn(err) 1317 if err != driver.ErrBadConn { 1318 return res, err 1319 } 1320 } 1321 return nil, driver.ErrBadConn 1322 } 1323 1324 func resultFromStatement(ds driverStmt, args ...interface{}) (Result, error) { 1325 ds.Lock() 1326 want := ds.si.NumInput() 1327 ds.Unlock() 1328 1329 // -1 means the driver doesn't know how to count the number of 1330 // placeholders, so we won't sanity check input here and instead let the 1331 // driver deal with errors. 1332 if want != -1 && len(args) != want { 1333 return nil, fmt.Errorf("sql: expected %d arguments, got %d", want, len(args)) 1334 } 1335 1336 dargs, err := driverArgs(&ds, args) 1337 if err != nil { 1338 return nil, err 1339 } 1340 1341 ds.Lock() 1342 resi, err := ds.si.Exec(dargs) 1343 ds.Unlock() 1344 if err != nil { 1345 return nil, err 1346 } 1347 return driverResult{ds.Locker, resi}, nil 1348 } 1349 1350 // connStmt returns a free driver connection on which to execute the 1351 // statement, a function to call to release the connection, and a 1352 // statement bound to that connection. 1353 func (s *Stmt) connStmt() (ci *driverConn, releaseConn func(error), si driver.Stmt, err error) { 1354 if err = s.stickyErr; err != nil { 1355 return 1356 } 1357 s.mu.Lock() 1358 if s.closed { 1359 s.mu.Unlock() 1360 err = errors.New("sql: statement is closed") 1361 return 1362 } 1363 1364 // In a transaction, we always use the connection that the 1365 // transaction was created on. 1366 if s.tx != nil { 1367 s.mu.Unlock() 1368 ci, err = s.tx.grabConn() // blocks, waiting for the connection. 1369 if err != nil { 1370 return 1371 } 1372 releaseConn = func(error) {} 1373 return ci, releaseConn, s.txsi.si, nil 1374 } 1375 1376 for i := 0; i < len(s.css); i++ { 1377 v := s.css[i] 1378 _, err := s.db.connIfFree(v.dc) 1379 if err == nil { 1380 s.mu.Unlock() 1381 return v.dc, v.dc.releaseConn, v.si, nil 1382 } 1383 if err == errConnClosed { 1384 // Lazily remove dead conn from our freelist. 1385 s.css[i] = s.css[len(s.css)-1] 1386 s.css = s.css[:len(s.css)-1] 1387 i-- 1388 } 1389 1390 } 1391 s.mu.Unlock() 1392 1393 // If all connections are busy, either wait for one to become available (if 1394 // we've already hit the maximum number of open connections) or create a 1395 // new one. 1396 // 1397 // TODO(bradfitz): or always wait for one? make configurable later? 1398 dc, err := s.db.conn() 1399 if err != nil { 1400 return nil, nil, nil, err 1401 } 1402 1403 // Do another pass over the list to see whether this statement has 1404 // already been prepared on the connection assigned to us. 1405 s.mu.Lock() 1406 for _, v := range s.css { 1407 if v.dc == dc { 1408 s.mu.Unlock() 1409 return dc, dc.releaseConn, v.si, nil 1410 } 1411 } 1412 s.mu.Unlock() 1413 1414 // No luck; we need to prepare the statement on this connection 1415 dc.Lock() 1416 si, err = dc.prepareLocked(s.query) 1417 dc.Unlock() 1418 if err != nil { 1419 s.db.putConn(dc, err) 1420 return nil, nil, nil, err 1421 } 1422 s.mu.Lock() 1423 cs := connStmt{dc, si} 1424 s.css = append(s.css, cs) 1425 s.mu.Unlock() 1426 1427 return dc, dc.releaseConn, si, nil 1428 } 1429 1430 // Query executes a prepared query statement with the given arguments 1431 // and returns the query results as a *Rows. 1432 func (s *Stmt) Query(args ...interface{}) (*Rows, error) { 1433 s.closemu.RLock() 1434 defer s.closemu.RUnlock() 1435 1436 var rowsi driver.Rows 1437 for i := 0; i < maxBadConnRetries; i++ { 1438 dc, releaseConn, si, err := s.connStmt() 1439 if err != nil { 1440 if err == driver.ErrBadConn { 1441 continue 1442 } 1443 return nil, err 1444 } 1445 1446 rowsi, err = rowsiFromStatement(driverStmt{dc, si}, args...) 1447 if err == nil { 1448 // Note: ownership of ci passes to the *Rows, to be freed 1449 // with releaseConn. 1450 rows := &Rows{ 1451 dc: dc, 1452 rowsi: rowsi, 1453 // releaseConn set below 1454 } 1455 s.db.addDep(s, rows) 1456 rows.releaseConn = func(err error) { 1457 releaseConn(err) 1458 s.db.removeDep(s, rows) 1459 } 1460 return rows, nil 1461 } 1462 1463 releaseConn(err) 1464 if err != driver.ErrBadConn { 1465 return nil, err 1466 } 1467 } 1468 return nil, driver.ErrBadConn 1469 } 1470 1471 func rowsiFromStatement(ds driverStmt, args ...interface{}) (driver.Rows, error) { 1472 ds.Lock() 1473 want := ds.si.NumInput() 1474 ds.Unlock() 1475 1476 // -1 means the driver doesn't know how to count the number of 1477 // placeholders, so we won't sanity check input here and instead let the 1478 // driver deal with errors. 1479 if want != -1 && len(args) != want { 1480 return nil, fmt.Errorf("sql: statement expects %d inputs; got %d", want, len(args)) 1481 } 1482 1483 dargs, err := driverArgs(&ds, args) 1484 if err != nil { 1485 return nil, err 1486 } 1487 1488 ds.Lock() 1489 rowsi, err := ds.si.Query(dargs) 1490 ds.Unlock() 1491 if err != nil { 1492 return nil, err 1493 } 1494 return rowsi, nil 1495 } 1496 1497 // QueryRow executes a prepared query statement with the given arguments. 1498 // If an error occurs during the execution of the statement, that error will 1499 // be returned by a call to Scan on the returned *Row, which is always non-nil. 1500 // If the query selects no rows, the *Row's Scan will return ErrNoRows. 1501 // Otherwise, the *Row's Scan scans the first selected row and discards 1502 // the rest. 1503 // 1504 // Example usage: 1505 // 1506 // var name string 1507 // err := nameByUseridStmt.QueryRow(id).Scan(&name) 1508 func (s *Stmt) QueryRow(args ...interface{}) *Row { 1509 rows, err := s.Query(args...) 1510 if err != nil { 1511 return &Row{err: err} 1512 } 1513 return &Row{rows: rows} 1514 } 1515 1516 // Close closes the statement. 1517 func (s *Stmt) Close() error { 1518 s.closemu.Lock() 1519 defer s.closemu.Unlock() 1520 1521 if s.stickyErr != nil { 1522 return s.stickyErr 1523 } 1524 s.mu.Lock() 1525 if s.closed { 1526 s.mu.Unlock() 1527 return nil 1528 } 1529 s.closed = true 1530 1531 if s.tx != nil { 1532 s.txsi.Close() 1533 s.mu.Unlock() 1534 return nil 1535 } 1536 s.mu.Unlock() 1537 1538 return s.db.removeDep(s, s) 1539 } 1540 1541 func (s *Stmt) finalClose() error { 1542 s.mu.Lock() 1543 defer s.mu.Unlock() 1544 if s.css != nil { 1545 for _, v := range s.css { 1546 s.db.noteUnusedDriverStatement(v.dc, v.si) 1547 v.dc.removeOpenStmt(v.si) 1548 } 1549 s.css = nil 1550 } 1551 return nil 1552 } 1553 1554 // Rows is the result of a query. Its cursor starts before the first row 1555 // of the result set. Use Next to advance through the rows: 1556 // 1557 // rows, err := db.Query("SELECT ...") 1558 // ... 1559 // defer rows.Close() 1560 // for rows.Next() { 1561 // var id int 1562 // var name string 1563 // err = rows.Scan(&id, &name) 1564 // ... 1565 // } 1566 // err = rows.Err() // get any error encountered during iteration 1567 // ... 1568 type Rows struct { 1569 dc *driverConn // owned; must call releaseConn when closed to release 1570 releaseConn func(error) 1571 rowsi driver.Rows 1572 1573 closed bool 1574 lastcols []driver.Value 1575 lasterr error // non-nil only if closed is true 1576 closeStmt driver.Stmt // if non-nil, statement to Close on close 1577 } 1578 1579 // Next prepares the next result row for reading with the Scan method. It 1580 // returns true on success, or false if there is no next result row or an error 1581 // happened while preparing it. Err should be consulted to distinguish between 1582 // the two cases. 1583 // 1584 // Every call to Scan, even the first one, must be preceded by a call to Next. 1585 func (rs *Rows) Next() bool { 1586 if rs.closed { 1587 return false 1588 } 1589 if rs.lastcols == nil { 1590 rs.lastcols = make([]driver.Value, len(rs.rowsi.Columns())) 1591 } 1592 rs.lasterr = rs.rowsi.Next(rs.lastcols) 1593 if rs.lasterr != nil { 1594 rs.Close() 1595 return false 1596 } 1597 return true 1598 } 1599 1600 // Err returns the error, if any, that was encountered during iteration. 1601 // Err may be called after an explicit or implicit Close. 1602 func (rs *Rows) Err() error { 1603 if rs.lasterr == io.EOF { 1604 return nil 1605 } 1606 return rs.lasterr 1607 } 1608 1609 // Columns returns the column names. 1610 // Columns returns an error if the rows are closed, or if the rows 1611 // are from QueryRow and there was a deferred error. 1612 func (rs *Rows) Columns() ([]string, error) { 1613 if rs.closed { 1614 return nil, errors.New("sql: Rows are closed") 1615 } 1616 if rs.rowsi == nil { 1617 return nil, errors.New("sql: no Rows available") 1618 } 1619 return rs.rowsi.Columns(), nil 1620 } 1621 1622 // Scan copies the columns in the current row into the values pointed 1623 // at by dest. 1624 // 1625 // If an argument has type *[]byte, Scan saves in that argument a copy 1626 // of the corresponding data. The copy is owned by the caller and can 1627 // be modified and held indefinitely. The copy can be avoided by using 1628 // an argument of type *RawBytes instead; see the documentation for 1629 // RawBytes for restrictions on its use. 1630 // 1631 // If an argument has type *interface{}, Scan copies the value 1632 // provided by the underlying driver without conversion. If the value 1633 // is of type []byte, a copy is made and the caller owns the result. 1634 func (rs *Rows) Scan(dest ...interface{}) error { 1635 if rs.closed { 1636 return errors.New("sql: Rows are closed") 1637 } 1638 if rs.lastcols == nil { 1639 return errors.New("sql: Scan called without calling Next") 1640 } 1641 if len(dest) != len(rs.lastcols) { 1642 return fmt.Errorf("sql: expected %d destination arguments in Scan, not %d", len(rs.lastcols), len(dest)) 1643 } 1644 for i, sv := range rs.lastcols { 1645 err := convertAssign(dest[i], sv) 1646 if err != nil { 1647 return fmt.Errorf("sql: Scan error on column index %d: %v", i, err) 1648 } 1649 } 1650 return nil 1651 } 1652 1653 var rowsCloseHook func(*Rows, *error) 1654 1655 // Close closes the Rows, preventing further enumeration. If Next returns 1656 // false, the Rows are closed automatically and it will suffice to check the 1657 // result of Err. Close is idempotent and does not affect the result of Err. 1658 func (rs *Rows) Close() error { 1659 if rs.closed { 1660 return nil 1661 } 1662 rs.closed = true 1663 err := rs.rowsi.Close() 1664 if fn := rowsCloseHook; fn != nil { 1665 fn(rs, &err) 1666 } 1667 if rs.closeStmt != nil { 1668 rs.closeStmt.Close() 1669 } 1670 rs.releaseConn(err) 1671 return err 1672 } 1673 1674 // Row is the result of calling QueryRow to select a single row. 1675 type Row struct { 1676 // One of these two will be non-nil: 1677 err error // deferred error for easy chaining 1678 rows *Rows 1679 } 1680 1681 // Scan copies the columns from the matched row into the values 1682 // pointed at by dest. If more than one row matches the query, 1683 // Scan uses the first row and discards the rest. If no row matches 1684 // the query, Scan returns ErrNoRows. 1685 func (r *Row) Scan(dest ...interface{}) error { 1686 if r.err != nil { 1687 return r.err 1688 } 1689 1690 // TODO(bradfitz): for now we need to defensively clone all 1691 // []byte that the driver returned (not permitting 1692 // *RawBytes in Rows.Scan), since we're about to close 1693 // the Rows in our defer, when we return from this function. 1694 // the contract with the driver.Next(...) interface is that it 1695 // can return slices into read-only temporary memory that's 1696 // only valid until the next Scan/Close. But the TODO is that 1697 // for a lot of drivers, this copy will be unnecessary. We 1698 // should provide an optional interface for drivers to 1699 // implement to say, "don't worry, the []bytes that I return 1700 // from Next will not be modified again." (for instance, if 1701 // they were obtained from the network anyway) But for now we 1702 // don't care. 1703 defer r.rows.Close() 1704 for _, dp := range dest { 1705 if _, ok := dp.(*RawBytes); ok { 1706 return errors.New("sql: RawBytes isn't allowed on Row.Scan") 1707 } 1708 } 1709 1710 if !r.rows.Next() { 1711 if err := r.rows.Err(); err != nil { 1712 return err 1713 } 1714 return ErrNoRows 1715 } 1716 err := r.rows.Scan(dest...) 1717 if err != nil { 1718 return err 1719 } 1720 // Make sure the query can be processed to completion with no errors. 1721 if err := r.rows.Close(); err != nil { 1722 return err 1723 } 1724 1725 return nil 1726 } 1727 1728 // A Result summarizes an executed SQL command. 1729 type Result interface { 1730 // LastInsertId returns the integer generated by the database 1731 // in response to a command. Typically this will be from an 1732 // "auto increment" column when inserting a new row. Not all 1733 // databases support this feature, and the syntax of such 1734 // statements varies. 1735 LastInsertId() (int64, error) 1736 1737 // RowsAffected returns the number of rows affected by an 1738 // update, insert, or delete. Not every database or database 1739 // driver may support this. 1740 RowsAffected() (int64, error) 1741 } 1742 1743 type driverResult struct { 1744 sync.Locker // the *driverConn 1745 resi driver.Result 1746 } 1747 1748 func (dr driverResult) LastInsertId() (int64, error) { 1749 dr.Lock() 1750 defer dr.Unlock() 1751 return dr.resi.LastInsertId() 1752 } 1753 1754 func (dr driverResult) RowsAffected() (int64, error) { 1755 dr.Lock() 1756 defer dr.Unlock() 1757 return dr.resi.RowsAffected() 1758 } 1759 1760 func stack() string { 1761 var buf [2 << 10]byte 1762 return string(buf[:runtime.Stack(buf[:], false)]) 1763 } 1764 1765 // withLock runs while holding lk. 1766 func withLock(lk sync.Locker, fn func()) { 1767 lk.Lock() 1768 fn() 1769 lk.Unlock() 1770 }