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