29aef78b2407e373ac2af62fe9cf80232c629f03
[platform/upstream/gcc48.git] / libgo / go / database / sql / sql.go
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 package sql
8
9 import (
10         "database/sql/driver"
11         "errors"
12         "fmt"
13         "io"
14         "sync"
15 )
16
17 var drivers = make(map[string]driver.Driver)
18
19 // Register makes a database driver available by the provided name.
20 // If Register is called twice with the same name or if driver is nil,
21 // it panics.
22 func Register(name string, driver driver.Driver) {
23         if driver == nil {
24                 panic("sql: Register driver is nil")
25         }
26         if _, dup := drivers[name]; dup {
27                 panic("sql: Register called twice for driver " + name)
28         }
29         drivers[name] = driver
30 }
31
32 // RawBytes is a byte slice that holds a reference to memory owned by
33 // the database itself. After a Scan into a RawBytes, the slice is only
34 // valid until the next call to Next, Scan, or Close.
35 type RawBytes []byte
36
37 // NullString represents a string that may be null.
38 // NullString implements the Scanner interface so
39 // it can be used as a scan destination:
40 //
41 //  var s NullString
42 //  err := db.QueryRow("SELECT name FROM foo WHERE id=?", id).Scan(&s)
43 //  ...
44 //  if s.Valid {
45 //     // use s.String
46 //  } else {
47 //     // NULL value
48 //  }
49 //
50 type NullString struct {
51         String string
52         Valid  bool // Valid is true if String is not NULL
53 }
54
55 // Scan implements the Scanner interface.
56 func (ns *NullString) Scan(value interface{}) error {
57         if value == nil {
58                 ns.String, ns.Valid = "", false
59                 return nil
60         }
61         ns.Valid = true
62         return convertAssign(&ns.String, value)
63 }
64
65 // Value implements the driver Valuer interface.
66 func (ns NullString) Value() (driver.Value, error) {
67         if !ns.Valid {
68                 return nil, nil
69         }
70         return ns.String, nil
71 }
72
73 // NullInt64 represents an int64 that may be null.
74 // NullInt64 implements the Scanner interface so
75 // it can be used as a scan destination, similar to NullString.
76 type NullInt64 struct {
77         Int64 int64
78         Valid bool // Valid is true if Int64 is not NULL
79 }
80
81 // Scan implements the Scanner interface.
82 func (n *NullInt64) Scan(value interface{}) error {
83         if value == nil {
84                 n.Int64, n.Valid = 0, false
85                 return nil
86         }
87         n.Valid = true
88         return convertAssign(&n.Int64, value)
89 }
90
91 // Value implements the driver Valuer interface.
92 func (n NullInt64) Value() (driver.Value, error) {
93         if !n.Valid {
94                 return nil, nil
95         }
96         return n.Int64, nil
97 }
98
99 // NullFloat64 represents a float64 that may be null.
100 // NullFloat64 implements the Scanner interface so
101 // it can be used as a scan destination, similar to NullString.
102 type NullFloat64 struct {
103         Float64 float64
104         Valid   bool // Valid is true if Float64 is not NULL
105 }
106
107 // Scan implements the Scanner interface.
108 func (n *NullFloat64) Scan(value interface{}) error {
109         if value == nil {
110                 n.Float64, n.Valid = 0, false
111                 return nil
112         }
113         n.Valid = true
114         return convertAssign(&n.Float64, value)
115 }
116
117 // Value implements the driver Valuer interface.
118 func (n NullFloat64) Value() (driver.Value, error) {
119         if !n.Valid {
120                 return nil, nil
121         }
122         return n.Float64, nil
123 }
124
125 // NullBool represents a bool that may be null.
126 // NullBool implements the Scanner interface so
127 // it can be used as a scan destination, similar to NullString.
128 type NullBool struct {
129         Bool  bool
130         Valid bool // Valid is true if Bool is not NULL
131 }
132
133 // Scan implements the Scanner interface.
134 func (n *NullBool) Scan(value interface{}) error {
135         if value == nil {
136                 n.Bool, n.Valid = false, false
137                 return nil
138         }
139         n.Valid = true
140         return convertAssign(&n.Bool, value)
141 }
142
143 // Value implements the driver Valuer interface.
144 func (n NullBool) Value() (driver.Value, error) {
145         if !n.Valid {
146                 return nil, nil
147         }
148         return n.Bool, nil
149 }
150
151 // Scanner is an interface used by Scan.
152 type Scanner interface {
153         // Scan assigns a value from a database driver.
154         //
155         // The src value will be of one of the following restricted
156         // set of types:
157         //
158         //    int64
159         //    float64
160         //    bool
161         //    []byte
162         //    string
163         //    time.Time
164         //    nil - for NULL values
165         //
166         // An error should be returned if the value can not be stored
167         // without loss of information.
168         Scan(src interface{}) error
169 }
170
171 // ErrNoRows is returned by Scan when QueryRow doesn't return a
172 // row. In such a case, QueryRow returns a placeholder *Row value that
173 // defers this error until a Scan.
174 var ErrNoRows = errors.New("sql: no rows in result set")
175
176 // DB is a database handle. It's safe for concurrent use by multiple
177 // goroutines.
178 //
179 // If the underlying database driver has the concept of a connection
180 // and per-connection session state, the sql package manages creating
181 // and freeing connections automatically, including maintaining a free
182 // pool of idle connections. If observing session state is required,
183 // either do not share a *DB between multiple concurrent goroutines or
184 // create and observe all state only within a transaction. Once
185 // DB.Open is called, the returned Tx is bound to a single isolated
186 // connection. Once Tx.Commit or Tx.Rollback is called, that
187 // connection is returned to DB's idle connection pool.
188 type DB struct {
189         driver driver.Driver
190         dsn    string
191
192         mu       sync.Mutex // protects freeConn and closed
193         freeConn []driver.Conn
194         closed   bool
195 }
196
197 // Open opens a database specified by its database driver name and a
198 // driver-specific data source name, usually consisting of at least a
199 // database name and connection information.
200 //
201 // Most users will open a database via a driver-specific connection
202 // helper function that returns a *DB.
203 func Open(driverName, dataSourceName string) (*DB, error) {
204         driver, ok := drivers[driverName]
205         if !ok {
206                 return nil, fmt.Errorf("sql: unknown driver %q (forgotten import?)", driverName)
207         }
208         return &DB{driver: driver, dsn: dataSourceName}, nil
209 }
210
211 // Close closes the database, releasing any open resources.
212 func (db *DB) Close() error {
213         db.mu.Lock()
214         defer db.mu.Unlock()
215         var err error
216         for _, c := range db.freeConn {
217                 err1 := c.Close()
218                 if err1 != nil {
219                         err = err1
220                 }
221         }
222         db.freeConn = nil
223         db.closed = true
224         return err
225 }
226
227 func (db *DB) maxIdleConns() int {
228         const defaultMaxIdleConns = 2
229         // TODO(bradfitz): ask driver, if supported, for its default preference
230         // TODO(bradfitz): let users override?
231         return defaultMaxIdleConns
232 }
233
234 // conn returns a newly-opened or cached driver.Conn
235 func (db *DB) conn() (driver.Conn, error) {
236         db.mu.Lock()
237         if db.closed {
238                 db.mu.Unlock()
239                 return nil, errors.New("sql: database is closed")
240         }
241         if n := len(db.freeConn); n > 0 {
242                 conn := db.freeConn[n-1]
243                 db.freeConn = db.freeConn[:n-1]
244                 db.mu.Unlock()
245                 return conn, nil
246         }
247         db.mu.Unlock()
248         return db.driver.Open(db.dsn)
249 }
250
251 func (db *DB) connIfFree(wanted driver.Conn) (conn driver.Conn, ok bool) {
252         db.mu.Lock()
253         defer db.mu.Unlock()
254         for i, conn := range db.freeConn {
255                 if conn != wanted {
256                         continue
257                 }
258                 db.freeConn[i] = db.freeConn[len(db.freeConn)-1]
259                 db.freeConn = db.freeConn[:len(db.freeConn)-1]
260                 return wanted, true
261         }
262         return nil, false
263 }
264
265 // putConnHook is a hook for testing.
266 var putConnHook func(*DB, driver.Conn)
267
268 // putConn adds a connection to the db's free pool.
269 // err is optionally the last error that occurred on this connection.
270 func (db *DB) putConn(c driver.Conn, err error) {
271         if err == driver.ErrBadConn {
272                 // Don't reuse bad connections.
273                 return
274         }
275         db.mu.Lock()
276         if putConnHook != nil {
277                 putConnHook(db, c)
278         }
279         if n := len(db.freeConn); !db.closed && n < db.maxIdleConns() {
280                 db.freeConn = append(db.freeConn, c)
281                 db.mu.Unlock()
282                 return
283         }
284         // TODO: check to see if we need this Conn for any prepared
285         // statements which are still active?
286         db.mu.Unlock()
287         c.Close()
288 }
289
290 // Prepare creates a prepared statement for later execution.
291 func (db *DB) Prepare(query string) (*Stmt, error) {
292         var stmt *Stmt
293         var err error
294         for i := 0; i < 10; i++ {
295                 stmt, err = db.prepare(query)
296                 if err != driver.ErrBadConn {
297                         break
298                 }
299         }
300         return stmt, err
301 }
302
303 func (db *DB) prepare(query string) (stmt *Stmt, err error) {
304         // TODO: check if db.driver supports an optional
305         // driver.Preparer interface and call that instead, if so,
306         // otherwise we make a prepared statement that's bound
307         // to a connection, and to execute this prepared statement
308         // we either need to use this connection (if it's free), else
309         // get a new connection + re-prepare + execute on that one.
310         ci, err := db.conn()
311         if err != nil {
312                 return nil, err
313         }
314         defer func() {
315                 db.putConn(ci, err)
316         }()
317
318         si, err := ci.Prepare(query)
319         if err != nil {
320                 return nil, err
321         }
322         stmt = &Stmt{
323                 db:    db,
324                 query: query,
325                 css:   []connStmt{{ci, si}},
326         }
327         return stmt, nil
328 }
329
330 // Exec executes a query without returning any rows.
331 func (db *DB) Exec(query string, args ...interface{}) (Result, error) {
332         var res Result
333         var err error
334         for i := 0; i < 10; i++ {
335                 res, err = db.exec(query, args)
336                 if err != driver.ErrBadConn {
337                         break
338                 }
339         }
340         return res, err
341 }
342
343 func (db *DB) exec(query string, args []interface{}) (res Result, err error) {
344         ci, err := db.conn()
345         if err != nil {
346                 return nil, err
347         }
348         defer func() {
349                 db.putConn(ci, err)
350         }()
351
352         if execer, ok := ci.(driver.Execer); ok {
353                 dargs, err := driverArgs(nil, args)
354                 if err != nil {
355                         return nil, err
356                 }
357                 resi, err := execer.Exec(query, dargs)
358                 if err != driver.ErrSkip {
359                         if err != nil {
360                                 return nil, err
361                         }
362                         return result{resi}, nil
363                 }
364         }
365
366         sti, err := ci.Prepare(query)
367         if err != nil {
368                 return nil, err
369         }
370         defer sti.Close()
371
372         return resultFromStatement(sti, args...)
373 }
374
375 // Query executes a query that returns rows, typically a SELECT.
376 // The args are for any placeholder parameters in the query.
377 func (db *DB) Query(query string, args ...interface{}) (*Rows, error) {
378         stmt, err := db.Prepare(query)
379         if err != nil {
380                 return nil, err
381         }
382         rows, err := stmt.Query(args...)
383         if err != nil {
384                 stmt.Close()
385                 return nil, err
386         }
387         rows.closeStmt = stmt
388         return rows, nil
389 }
390
391 // QueryRow executes a query that is expected to return at most one row.
392 // QueryRow always return a non-nil value. Errors are deferred until
393 // Row's Scan method is called.
394 func (db *DB) QueryRow(query string, args ...interface{}) *Row {
395         rows, err := db.Query(query, args...)
396         return &Row{rows: rows, err: err}
397 }
398
399 // Begin starts a transaction. The isolation level is dependent on
400 // the driver.
401 func (db *DB) Begin() (*Tx, error) {
402         var tx *Tx
403         var err error
404         for i := 0; i < 10; i++ {
405                 tx, err = db.begin()
406                 if err != driver.ErrBadConn {
407                         break
408                 }
409         }
410         return tx, err
411 }
412
413 func (db *DB) begin() (tx *Tx, err error) {
414         ci, err := db.conn()
415         if err != nil {
416                 return nil, err
417         }
418         txi, err := ci.Begin()
419         if err != nil {
420                 db.putConn(ci, err)
421                 return nil, err
422         }
423         return &Tx{
424                 db:  db,
425                 ci:  ci,
426                 txi: txi,
427         }, nil
428 }
429
430 // Driver returns the database's underlying driver.
431 func (db *DB) Driver() driver.Driver {
432         return db.driver
433 }
434
435 // Tx is an in-progress database transaction.
436 //
437 // A transaction must end with a call to Commit or Rollback.
438 //
439 // After a call to Commit or Rollback, all operations on the
440 // transaction fail with ErrTxDone.
441 type Tx struct {
442         db *DB
443
444         // ci is owned exclusively until Commit or Rollback, at which point
445         // it's returned with putConn.
446         ci  driver.Conn
447         txi driver.Tx
448
449         // cimu is held while somebody is using ci (between grabConn
450         // and releaseConn)
451         cimu sync.Mutex
452
453         // done transitions from false to true exactly once, on Commit
454         // or Rollback. once done, all operations fail with
455         // ErrTxDone.
456         done bool
457 }
458
459 var ErrTxDone = errors.New("sql: Transaction has already been committed or rolled back")
460
461 func (tx *Tx) close() {
462         if tx.done {
463                 panic("double close") // internal error
464         }
465         tx.done = true
466         tx.db.putConn(tx.ci, nil)
467         tx.ci = nil
468         tx.txi = nil
469 }
470
471 func (tx *Tx) grabConn() (driver.Conn, error) {
472         if tx.done {
473                 return nil, ErrTxDone
474         }
475         tx.cimu.Lock()
476         return tx.ci, nil
477 }
478
479 func (tx *Tx) releaseConn() {
480         tx.cimu.Unlock()
481 }
482
483 // Commit commits the transaction.
484 func (tx *Tx) Commit() error {
485         if tx.done {
486                 return ErrTxDone
487         }
488         defer tx.close()
489         return tx.txi.Commit()
490 }
491
492 // Rollback aborts the transaction.
493 func (tx *Tx) Rollback() error {
494         if tx.done {
495                 return ErrTxDone
496         }
497         defer tx.close()
498         return tx.txi.Rollback()
499 }
500
501 // Prepare creates a prepared statement for use within a transaction.
502 //
503 // The returned statement operates within the transaction and can no longer
504 // be used once the transaction has been committed or rolled back.
505 //
506 // To use an existing prepared statement on this transaction, see Tx.Stmt.
507 func (tx *Tx) Prepare(query string) (*Stmt, error) {
508         // TODO(bradfitz): We could be more efficient here and either
509         // provide a method to take an existing Stmt (created on
510         // perhaps a different Conn), and re-create it on this Conn if
511         // necessary. Or, better: keep a map in DB of query string to
512         // Stmts, and have Stmt.Execute do the right thing and
513         // re-prepare if the Conn in use doesn't have that prepared
514         // statement.  But we'll want to avoid caching the statement
515         // in the case where we only call conn.Prepare implicitly
516         // (such as in db.Exec or tx.Exec), but the caller package
517         // can't be holding a reference to the returned statement.
518         // Perhaps just looking at the reference count (by noting
519         // Stmt.Close) would be enough. We might also want a finalizer
520         // on Stmt to drop the reference count.
521         ci, err := tx.grabConn()
522         if err != nil {
523                 return nil, err
524         }
525         defer tx.releaseConn()
526
527         si, err := ci.Prepare(query)
528         if err != nil {
529                 return nil, err
530         }
531
532         stmt := &Stmt{
533                 db:    tx.db,
534                 tx:    tx,
535                 txsi:  si,
536                 query: query,
537         }
538         return stmt, nil
539 }
540
541 // Stmt returns a transaction-specific prepared statement from
542 // an existing statement.
543 //
544 // Example:
545 //  updateMoney, err := db.Prepare("UPDATE balance SET money=money+? WHERE id=?")
546 //  ...
547 //  tx, err := db.Begin()
548 //  ...
549 //  res, err := tx.Stmt(updateMoney).Exec(123.45, 98293203)
550 func (tx *Tx) Stmt(stmt *Stmt) *Stmt {
551         // TODO(bradfitz): optimize this. Currently this re-prepares
552         // each time.  This is fine for now to illustrate the API but
553         // we should really cache already-prepared statements
554         // per-Conn. See also the big comment in Tx.Prepare.
555
556         if tx.db != stmt.db {
557                 return &Stmt{stickyErr: errors.New("sql: Tx.Stmt: statement from different database used")}
558         }
559         ci, err := tx.grabConn()
560         if err != nil {
561                 return &Stmt{stickyErr: err}
562         }
563         defer tx.releaseConn()
564         si, err := ci.Prepare(stmt.query)
565         return &Stmt{
566                 db:        tx.db,
567                 tx:        tx,
568                 txsi:      si,
569                 query:     stmt.query,
570                 stickyErr: err,
571         }
572 }
573
574 // Exec executes a query that doesn't return rows.
575 // For example: an INSERT and UPDATE.
576 func (tx *Tx) Exec(query string, args ...interface{}) (Result, error) {
577         ci, err := tx.grabConn()
578         if err != nil {
579                 return nil, err
580         }
581         defer tx.releaseConn()
582
583         if execer, ok := ci.(driver.Execer); ok {
584                 dargs, err := driverArgs(nil, args)
585                 if err != nil {
586                         return nil, err
587                 }
588                 resi, err := execer.Exec(query, dargs)
589                 if err == nil {
590                         return result{resi}, nil
591                 }
592                 if err != driver.ErrSkip {
593                         return nil, err
594                 }
595         }
596
597         sti, err := ci.Prepare(query)
598         if err != nil {
599                 return nil, err
600         }
601         defer sti.Close()
602
603         return resultFromStatement(sti, args...)
604 }
605
606 // Query executes a query that returns rows, typically a SELECT.
607 func (tx *Tx) Query(query string, args ...interface{}) (*Rows, error) {
608         if tx.done {
609                 return nil, ErrTxDone
610         }
611         stmt, err := tx.Prepare(query)
612         if err != nil {
613                 return nil, err
614         }
615         rows, err := stmt.Query(args...)
616         if err != nil {
617                 stmt.Close()
618                 return nil, err
619         }
620         rows.closeStmt = stmt
621         return rows, err
622 }
623
624 // QueryRow executes a query that is expected to return at most one row.
625 // QueryRow always return a non-nil value. Errors are deferred until
626 // Row's Scan method is called.
627 func (tx *Tx) QueryRow(query string, args ...interface{}) *Row {
628         rows, err := tx.Query(query, args...)
629         return &Row{rows: rows, err: err}
630 }
631
632 // connStmt is a prepared statement on a particular connection.
633 type connStmt struct {
634         ci driver.Conn
635         si driver.Stmt
636 }
637
638 // Stmt is a prepared statement. Stmt is safe for concurrent use by multiple goroutines.
639 type Stmt struct {
640         // Immutable:
641         db        *DB    // where we came from
642         query     string // that created the Stmt
643         stickyErr error  // if non-nil, this error is returned for all operations
644
645         // If in a transaction, else both nil:
646         tx   *Tx
647         txsi driver.Stmt
648
649         mu     sync.Mutex // protects the rest of the fields
650         closed bool
651
652         // css is a list of underlying driver statement interfaces
653         // that are valid on particular connections.  This is only
654         // used if tx == nil and one is found that has idle
655         // connections.  If tx != nil, txsi is always used.
656         css []connStmt
657 }
658
659 // Exec executes a prepared statement with the given arguments and
660 // returns a Result summarizing the effect of the statement.
661 func (s *Stmt) Exec(args ...interface{}) (Result, error) {
662         _, releaseConn, si, err := s.connStmt()
663         if err != nil {
664                 return nil, err
665         }
666         defer releaseConn(nil)
667
668         return resultFromStatement(si, args...)
669 }
670
671 func resultFromStatement(si driver.Stmt, args ...interface{}) (Result, error) {
672         // -1 means the driver doesn't know how to count the number of
673         // placeholders, so we won't sanity check input here and instead let the
674         // driver deal with errors.
675         if want := si.NumInput(); want != -1 && len(args) != want {
676                 return nil, fmt.Errorf("sql: expected %d arguments, got %d", want, len(args))
677         }
678
679         dargs, err := driverArgs(si, args)
680         if err != nil {
681                 return nil, err
682         }
683
684         resi, err := si.Exec(dargs)
685         if err != nil {
686                 return nil, err
687         }
688         return result{resi}, nil
689 }
690
691 // connStmt returns a free driver connection on which to execute the
692 // statement, a function to call to release the connection, and a
693 // statement bound to that connection.
694 func (s *Stmt) connStmt() (ci driver.Conn, releaseConn func(error), si driver.Stmt, err error) {
695         if err = s.stickyErr; err != nil {
696                 return
697         }
698         s.mu.Lock()
699         if s.closed {
700                 s.mu.Unlock()
701                 err = errors.New("sql: statement is closed")
702                 return
703         }
704
705         // In a transaction, we always use the connection that the
706         // transaction was created on.
707         if s.tx != nil {
708                 s.mu.Unlock()
709                 ci, err = s.tx.grabConn() // blocks, waiting for the connection.
710                 if err != nil {
711                         return
712                 }
713                 releaseConn = func(error) { s.tx.releaseConn() }
714                 return ci, releaseConn, s.txsi, nil
715         }
716
717         var cs connStmt
718         match := false
719         for _, v := range s.css {
720                 // TODO(bradfitz): lazily clean up entries in this
721                 // list with dead conns while enumerating
722                 if _, match = s.db.connIfFree(v.ci); match {
723                         cs = v
724                         break
725                 }
726         }
727         s.mu.Unlock()
728
729         // Make a new conn if all are busy.
730         // TODO(bradfitz): or wait for one? make configurable later?
731         if !match {
732                 for i := 0; ; i++ {
733                         ci, err := s.db.conn()
734                         if err != nil {
735                                 return nil, nil, nil, err
736                         }
737                         si, err := ci.Prepare(s.query)
738                         if err == driver.ErrBadConn && i < 10 {
739                                 continue
740                         }
741                         if err != nil {
742                                 return nil, nil, nil, err
743                         }
744                         s.mu.Lock()
745                         cs = connStmt{ci, si}
746                         s.css = append(s.css, cs)
747                         s.mu.Unlock()
748                         break
749                 }
750         }
751
752         conn := cs.ci
753         releaseConn = func(err error) { s.db.putConn(conn, err) }
754         return conn, releaseConn, cs.si, nil
755 }
756
757 // Query executes a prepared query statement with the given arguments
758 // and returns the query results as a *Rows.
759 func (s *Stmt) Query(args ...interface{}) (*Rows, error) {
760         ci, releaseConn, si, err := s.connStmt()
761         if err != nil {
762                 return nil, err
763         }
764
765         // -1 means the driver doesn't know how to count the number of
766         // placeholders, so we won't sanity check input here and instead let the
767         // driver deal with errors.
768         if want := si.NumInput(); want != -1 && len(args) != want {
769                 return nil, fmt.Errorf("sql: statement expects %d inputs; got %d", si.NumInput(), len(args))
770         }
771
772         dargs, err := driverArgs(si, args)
773         if err != nil {
774                 return nil, err
775         }
776
777         rowsi, err := si.Query(dargs)
778         if err != nil {
779                 releaseConn(err)
780                 return nil, err
781         }
782         // Note: ownership of ci passes to the *Rows, to be freed
783         // with releaseConn.
784         rows := &Rows{
785                 db:          s.db,
786                 ci:          ci,
787                 releaseConn: releaseConn,
788                 rowsi:       rowsi,
789         }
790         return rows, nil
791 }
792
793 // QueryRow executes a prepared query statement with the given arguments.
794 // If an error occurs during the execution of the statement, that error will
795 // be returned by a call to Scan on the returned *Row, which is always non-nil.
796 // If the query selects no rows, the *Row's Scan will return ErrNoRows.
797 // Otherwise, the *Row's Scan scans the first selected row and discards
798 // the rest.
799 //
800 // Example usage:
801 //
802 //  var name string
803 //  err := nameByUseridStmt.QueryRow(id).Scan(&name)
804 func (s *Stmt) QueryRow(args ...interface{}) *Row {
805         rows, err := s.Query(args...)
806         if err != nil {
807                 return &Row{err: err}
808         }
809         return &Row{rows: rows}
810 }
811
812 // Close closes the statement.
813 func (s *Stmt) Close() error {
814         if s.stickyErr != nil {
815                 return s.stickyErr
816         }
817         s.mu.Lock()
818         defer s.mu.Unlock()
819         if s.closed {
820                 return nil
821         }
822         s.closed = true
823
824         if s.tx != nil {
825                 s.txsi.Close()
826         } else {
827                 for _, v := range s.css {
828                         if ci, match := s.db.connIfFree(v.ci); match {
829                                 v.si.Close()
830                                 s.db.putConn(ci, nil)
831                         } else {
832                                 // TODO(bradfitz): care that we can't close
833                                 // this statement because the statement's
834                                 // connection is in use?
835                         }
836                 }
837         }
838         return nil
839 }
840
841 // Rows is the result of a query. Its cursor starts before the first row
842 // of the result set. Use Next to advance through the rows:
843 //
844 //     rows, err := db.Query("SELECT ...")
845 //     ...
846 //     for rows.Next() {
847 //         var id int
848 //         var name string
849 //         err = rows.Scan(&id, &name)
850 //         ...
851 //     }
852 //     err = rows.Err() // get any error encountered during iteration
853 //     ...
854 type Rows struct {
855         db          *DB
856         ci          driver.Conn // owned; must call putconn when closed to release
857         releaseConn func(error)
858         rowsi       driver.Rows
859
860         closed    bool
861         lastcols  []driver.Value
862         lasterr   error
863         closeStmt *Stmt // if non-nil, statement to Close on close
864 }
865
866 // Next prepares the next result row for reading with the Scan method.
867 // It returns true on success, false if there is no next result row.
868 // Every call to Scan, even the first one, must be preceded by a call
869 // to Next.
870 func (rs *Rows) Next() bool {
871         if rs.closed {
872                 return false
873         }
874         if rs.lasterr != nil {
875                 return false
876         }
877         if rs.lastcols == nil {
878                 rs.lastcols = make([]driver.Value, len(rs.rowsi.Columns()))
879         }
880         rs.lasterr = rs.rowsi.Next(rs.lastcols)
881         if rs.lasterr == io.EOF {
882                 rs.Close()
883         }
884         return rs.lasterr == nil
885 }
886
887 // Err returns the error, if any, that was encountered during iteration.
888 func (rs *Rows) Err() error {
889         if rs.lasterr == io.EOF {
890                 return nil
891         }
892         return rs.lasterr
893 }
894
895 // Columns returns the column names.
896 // Columns returns an error if the rows are closed, or if the rows
897 // are from QueryRow and there was a deferred error.
898 func (rs *Rows) Columns() ([]string, error) {
899         if rs.closed {
900                 return nil, errors.New("sql: Rows are closed")
901         }
902         if rs.rowsi == nil {
903                 return nil, errors.New("sql: no Rows available")
904         }
905         return rs.rowsi.Columns(), nil
906 }
907
908 // Scan copies the columns in the current row into the values pointed
909 // at by dest.
910 //
911 // If an argument has type *[]byte, Scan saves in that argument a copy
912 // of the corresponding data. The copy is owned by the caller and can
913 // be modified and held indefinitely. The copy can be avoided by using
914 // an argument of type *RawBytes instead; see the documentation for
915 // RawBytes for restrictions on its use.
916 //
917 // If an argument has type *interface{}, Scan copies the value
918 // provided by the underlying driver without conversion. If the value
919 // is of type []byte, a copy is made and the caller owns the result.
920 func (rs *Rows) Scan(dest ...interface{}) error {
921         if rs.closed {
922                 return errors.New("sql: Rows closed")
923         }
924         if rs.lasterr != nil {
925                 return rs.lasterr
926         }
927         if rs.lastcols == nil {
928                 return errors.New("sql: Scan called without calling Next")
929         }
930         if len(dest) != len(rs.lastcols) {
931                 return fmt.Errorf("sql: expected %d destination arguments in Scan, not %d", len(rs.lastcols), len(dest))
932         }
933         for i, sv := range rs.lastcols {
934                 err := convertAssign(dest[i], sv)
935                 if err != nil {
936                         return fmt.Errorf("sql: Scan error on column index %d: %v", i, err)
937                 }
938         }
939         for _, dp := range dest {
940                 b, ok := dp.(*[]byte)
941                 if !ok {
942                         continue
943                 }
944                 if *b == nil {
945                         // If the []byte is now nil (for a NULL value),
946                         // don't fall through to below which would
947                         // turn it into a non-nil 0-length byte slice
948                         continue
949                 }
950                 if _, ok = dp.(*RawBytes); ok {
951                         continue
952                 }
953                 clone := make([]byte, len(*b))
954                 copy(clone, *b)
955                 *b = clone
956         }
957         return nil
958 }
959
960 // Close closes the Rows, preventing further enumeration. If the
961 // end is encountered, the Rows are closed automatically. Close
962 // is idempotent.
963 func (rs *Rows) Close() error {
964         if rs.closed {
965                 return nil
966         }
967         rs.closed = true
968         err := rs.rowsi.Close()
969         rs.releaseConn(err)
970         if rs.closeStmt != nil {
971                 rs.closeStmt.Close()
972         }
973         return err
974 }
975
976 // Row is the result of calling QueryRow to select a single row.
977 type Row struct {
978         // One of these two will be non-nil:
979         err  error // deferred error for easy chaining
980         rows *Rows
981 }
982
983 // Scan copies the columns from the matched row into the values
984 // pointed at by dest.  If more than one row matches the query,
985 // Scan uses the first row and discards the rest.  If no row matches
986 // the query, Scan returns ErrNoRows.
987 func (r *Row) Scan(dest ...interface{}) error {
988         if r.err != nil {
989                 return r.err
990         }
991
992         // TODO(bradfitz): for now we need to defensively clone all
993         // []byte that the driver returned (not permitting
994         // *RawBytes in Rows.Scan), since we're about to close
995         // the Rows in our defer, when we return from this function.
996         // the contract with the driver.Next(...) interface is that it
997         // can return slices into read-only temporary memory that's
998         // only valid until the next Scan/Close.  But the TODO is that
999         // for a lot of drivers, this copy will be unnecessary.  We
1000         // should provide an optional interface for drivers to
1001         // implement to say, "don't worry, the []bytes that I return
1002         // from Next will not be modified again." (for instance, if
1003         // they were obtained from the network anyway) But for now we
1004         // don't care.
1005         for _, dp := range dest {
1006                 if _, ok := dp.(*RawBytes); ok {
1007                         return errors.New("sql: RawBytes isn't allowed on Row.Scan")
1008                 }
1009         }
1010
1011         defer r.rows.Close()
1012         if !r.rows.Next() {
1013                 return ErrNoRows
1014         }
1015         err := r.rows.Scan(dest...)
1016         if err != nil {
1017                 return err
1018         }
1019
1020         return nil
1021 }
1022
1023 // A Result summarizes an executed SQL command.
1024 type Result interface {
1025         LastInsertId() (int64, error)
1026         RowsAffected() (int64, error)
1027 }
1028
1029 type result struct {
1030         driver.Result
1031 }