d557fc8303451e039a9e78df0079ad1e77502181
[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 occured 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         sargs, err := subsetTypeArgs(args)
333         if err != nil {
334                 return nil, err
335         }
336         var res Result
337         for i := 0; i < 10; i++ {
338                 res, err = db.exec(query, sargs)
339                 if err != driver.ErrBadConn {
340                         break
341                 }
342         }
343         return res, err
344 }
345
346 func (db *DB) exec(query string, sargs []driver.Value) (res Result, err error) {
347         ci, err := db.conn()
348         if err != nil {
349                 return nil, err
350         }
351         defer func() {
352                 db.putConn(ci, err)
353         }()
354
355         if execer, ok := ci.(driver.Execer); ok {
356                 resi, err := execer.Exec(query, sargs)
357                 if err != driver.ErrSkip {
358                         if err != nil {
359                                 return nil, err
360                         }
361                         return result{resi}, nil
362                 }
363         }
364
365         sti, err := ci.Prepare(query)
366         if err != nil {
367                 return nil, err
368         }
369         defer sti.Close()
370
371         resi, err := sti.Exec(sargs)
372         if err != nil {
373                 return nil, err
374         }
375         return result{resi}, nil
376 }
377
378 // Query executes a query that returns rows, typically a SELECT.
379 func (db *DB) Query(query string, args ...interface{}) (*Rows, error) {
380         stmt, err := db.Prepare(query)
381         if err != nil {
382                 return nil, err
383         }
384         rows, err := stmt.Query(args...)
385         if err != nil {
386                 stmt.Close()
387                 return nil, err
388         }
389         rows.closeStmt = stmt
390         return rows, nil
391 }
392
393 // QueryRow executes a query that is expected to return at most one row.
394 // QueryRow always return a non-nil value. Errors are deferred until
395 // Row's Scan method is called.
396 func (db *DB) QueryRow(query string, args ...interface{}) *Row {
397         rows, err := db.Query(query, args...)
398         return &Row{rows: rows, err: err}
399 }
400
401 // Begin starts a transaction. The isolation level is dependent on
402 // the driver.
403 func (db *DB) Begin() (*Tx, error) {
404         var tx *Tx
405         var err error
406         for i := 0; i < 10; i++ {
407                 tx, err = db.begin()
408                 if err != driver.ErrBadConn {
409                         break
410                 }
411         }
412         return tx, err
413 }
414
415 func (db *DB) begin() (tx *Tx, err error) {
416         ci, err := db.conn()
417         if err != nil {
418                 return nil, err
419         }
420         txi, err := ci.Begin()
421         if err != nil {
422                 db.putConn(ci, err)
423                 return nil, fmt.Errorf("sql: failed to Begin transaction: %v", err)
424         }
425         return &Tx{
426                 db:  db,
427                 ci:  ci,
428                 txi: txi,
429         }, nil
430 }
431
432 // Driver returns the database's underlying driver.
433 func (db *DB) Driver() driver.Driver {
434         return db.driver
435 }
436
437 // Tx is an in-progress database transaction.
438 //
439 // A transaction must end with a call to Commit or Rollback.
440 //
441 // After a call to Commit or Rollback, all operations on the
442 // transaction fail with ErrTxDone.
443 type Tx struct {
444         db *DB
445
446         // ci is owned exclusively until Commit or Rollback, at which point
447         // it's returned with putConn.
448         ci  driver.Conn
449         txi driver.Tx
450
451         // cimu is held while somebody is using ci (between grabConn
452         // and releaseConn)
453         cimu sync.Mutex
454
455         // done transitions from false to true exactly once, on Commit
456         // or Rollback. once done, all operations fail with
457         // ErrTxDone.
458         done bool
459 }
460
461 var ErrTxDone = errors.New("sql: Transaction has already been committed or rolled back")
462
463 func (tx *Tx) close() {
464         if tx.done {
465                 panic("double close") // internal error
466         }
467         tx.done = true
468         tx.db.putConn(tx.ci, nil)
469         tx.ci = nil
470         tx.txi = nil
471 }
472
473 func (tx *Tx) grabConn() (driver.Conn, error) {
474         if tx.done {
475                 return nil, ErrTxDone
476         }
477         tx.cimu.Lock()
478         return tx.ci, nil
479 }
480
481 func (tx *Tx) releaseConn() {
482         tx.cimu.Unlock()
483 }
484
485 // Commit commits the transaction.
486 func (tx *Tx) Commit() error {
487         if tx.done {
488                 return ErrTxDone
489         }
490         defer tx.close()
491         return tx.txi.Commit()
492 }
493
494 // Rollback aborts the transaction.
495 func (tx *Tx) Rollback() error {
496         if tx.done {
497                 return ErrTxDone
498         }
499         defer tx.close()
500         return tx.txi.Rollback()
501 }
502
503 // Prepare creates a prepared statement for use within a transaction.
504 //
505 // The returned statement operates within the transaction and can no longer
506 // be used once the transaction has been committed or rolled back.
507 //
508 // To use an existing prepared statement on this transaction, see Tx.Stmt.
509 func (tx *Tx) Prepare(query string) (*Stmt, error) {
510         // TODO(bradfitz): We could be more efficient here and either
511         // provide a method to take an existing Stmt (created on
512         // perhaps a different Conn), and re-create it on this Conn if
513         // necessary. Or, better: keep a map in DB of query string to
514         // Stmts, and have Stmt.Execute do the right thing and
515         // re-prepare if the Conn in use doesn't have that prepared
516         // statement.  But we'll want to avoid caching the statement
517         // in the case where we only call conn.Prepare implicitly
518         // (such as in db.Exec or tx.Exec), but the caller package
519         // can't be holding a reference to the returned statement.
520         // Perhaps just looking at the reference count (by noting
521         // Stmt.Close) would be enough. We might also want a finalizer
522         // on Stmt to drop the reference count.
523         ci, err := tx.grabConn()
524         if err != nil {
525                 return nil, err
526         }
527         defer tx.releaseConn()
528
529         si, err := ci.Prepare(query)
530         if err != nil {
531                 return nil, err
532         }
533
534         stmt := &Stmt{
535                 db:    tx.db,
536                 tx:    tx,
537                 txsi:  si,
538                 query: query,
539         }
540         return stmt, nil
541 }
542
543 // Stmt returns a transaction-specific prepared statement from
544 // an existing statement.
545 //
546 // Example:
547 //  updateMoney, err := db.Prepare("UPDATE balance SET money=money+? WHERE id=?")
548 //  ...
549 //  tx, err := db.Begin()
550 //  ...
551 //  res, err := tx.Stmt(updateMoney).Exec(123.45, 98293203)
552 func (tx *Tx) Stmt(stmt *Stmt) *Stmt {
553         // TODO(bradfitz): optimize this. Currently this re-prepares
554         // each time.  This is fine for now to illustrate the API but
555         // we should really cache already-prepared statements
556         // per-Conn. See also the big comment in Tx.Prepare.
557
558         if tx.db != stmt.db {
559                 return &Stmt{stickyErr: errors.New("sql: Tx.Stmt: statement from different database used")}
560         }
561         ci, err := tx.grabConn()
562         if err != nil {
563                 return &Stmt{stickyErr: err}
564         }
565         defer tx.releaseConn()
566         si, err := ci.Prepare(stmt.query)
567         return &Stmt{
568                 db:        tx.db,
569                 tx:        tx,
570                 txsi:      si,
571                 query:     stmt.query,
572                 stickyErr: err,
573         }
574 }
575
576 // Exec executes a query that doesn't return rows.
577 // For example: an INSERT and UPDATE.
578 func (tx *Tx) Exec(query string, args ...interface{}) (Result, error) {
579         ci, err := tx.grabConn()
580         if err != nil {
581                 return nil, err
582         }
583         defer tx.releaseConn()
584
585         sargs, err := subsetTypeArgs(args)
586         if err != nil {
587                 return nil, err
588         }
589
590         if execer, ok := ci.(driver.Execer); ok {
591                 resi, err := execer.Exec(query, sargs)
592                 if err == nil {
593                         return result{resi}, nil
594                 }
595                 if err != driver.ErrSkip {
596                         return nil, err
597                 }
598         }
599
600         sti, err := ci.Prepare(query)
601         if err != nil {
602                 return nil, err
603         }
604         defer sti.Close()
605
606         resi, err := sti.Exec(sargs)
607         if err != nil {
608                 return nil, err
609         }
610         return result{resi}, nil
611 }
612
613 // Query executes a query that returns rows, typically a SELECT.
614 func (tx *Tx) Query(query string, args ...interface{}) (*Rows, error) {
615         if tx.done {
616                 return nil, ErrTxDone
617         }
618         stmt, err := tx.Prepare(query)
619         if err != nil {
620                 return nil, err
621         }
622         rows, err := stmt.Query(args...)
623         if err != nil {
624                 stmt.Close()
625                 return nil, err
626         }
627         rows.closeStmt = stmt
628         return rows, err
629 }
630
631 // QueryRow executes a query that is expected to return at most one row.
632 // QueryRow always return a non-nil value. Errors are deferred until
633 // Row's Scan method is called.
634 func (tx *Tx) QueryRow(query string, args ...interface{}) *Row {
635         rows, err := tx.Query(query, args...)
636         return &Row{rows: rows, err: err}
637 }
638
639 // connStmt is a prepared statement on a particular connection.
640 type connStmt struct {
641         ci driver.Conn
642         si driver.Stmt
643 }
644
645 // Stmt is a prepared statement. Stmt is safe for concurrent use by multiple goroutines.
646 type Stmt struct {
647         // Immutable:
648         db        *DB    // where we came from
649         query     string // that created the Stmt
650         stickyErr error  // if non-nil, this error is returned for all operations
651
652         // If in a transaction, else both nil:
653         tx   *Tx
654         txsi driver.Stmt
655
656         mu     sync.Mutex // protects the rest of the fields
657         closed bool
658
659         // css is a list of underlying driver statement interfaces
660         // that are valid on particular connections.  This is only
661         // used if tx == nil and one is found that has idle
662         // connections.  If tx != nil, txsi is always used.
663         css []connStmt
664 }
665
666 // Exec executes a prepared statement with the given arguments and
667 // returns a Result summarizing the effect of the statement.
668 func (s *Stmt) Exec(args ...interface{}) (Result, error) {
669         _, releaseConn, si, err := s.connStmt()
670         if err != nil {
671                 return nil, err
672         }
673         defer releaseConn(nil)
674
675         // -1 means the driver doesn't know how to count the number of
676         // placeholders, so we won't sanity check input here and instead let the
677         // driver deal with errors.
678         if want := si.NumInput(); want != -1 && len(args) != want {
679                 return nil, fmt.Errorf("sql: expected %d arguments, got %d", want, len(args))
680         }
681
682         sargs := make([]driver.Value, len(args))
683
684         // Convert args to subset types.
685         if cc, ok := si.(driver.ColumnConverter); ok {
686                 for n, arg := range args {
687                         // First, see if the value itself knows how to convert
688                         // itself to a driver type.  For example, a NullString
689                         // struct changing into a string or nil.
690                         if svi, ok := arg.(driver.Valuer); ok {
691                                 sv, err := svi.Value()
692                                 if err != nil {
693                                         return nil, fmt.Errorf("sql: argument index %d from Value: %v", n, err)
694                                 }
695                                 if !driver.IsValue(sv) {
696                                         return nil, fmt.Errorf("sql: argument index %d: non-subset type %T returned from Value", n, sv)
697                                 }
698                                 arg = sv
699                         }
700
701                         // Second, ask the column to sanity check itself. For
702                         // example, drivers might use this to make sure that
703                         // an int64 values being inserted into a 16-bit
704                         // integer field is in range (before getting
705                         // truncated), or that a nil can't go into a NOT NULL
706                         // column before going across the network to get the
707                         // same error.
708                         sargs[n], err = cc.ColumnConverter(n).ConvertValue(arg)
709                         if err != nil {
710                                 return nil, fmt.Errorf("sql: converting Exec argument #%d's type: %v", n, err)
711                         }
712                         if !driver.IsValue(sargs[n]) {
713                                 return nil, fmt.Errorf("sql: driver ColumnConverter error converted %T to unsupported type %T",
714                                         arg, sargs[n])
715                         }
716                 }
717         } else {
718                 for n, arg := range args {
719                         sargs[n], err = driver.DefaultParameterConverter.ConvertValue(arg)
720                         if err != nil {
721                                 return nil, fmt.Errorf("sql: converting Exec argument #%d's type: %v", n, err)
722                         }
723                 }
724         }
725
726         resi, err := si.Exec(sargs)
727         if err != nil {
728                 return nil, err
729         }
730         return result{resi}, nil
731 }
732
733 // connStmt returns a free driver connection on which to execute the
734 // statement, a function to call to release the connection, and a
735 // statement bound to that connection.
736 func (s *Stmt) connStmt() (ci driver.Conn, releaseConn func(error), si driver.Stmt, err error) {
737         if err = s.stickyErr; err != nil {
738                 return
739         }
740         s.mu.Lock()
741         if s.closed {
742                 s.mu.Unlock()
743                 err = errors.New("sql: statement is closed")
744                 return
745         }
746
747         // In a transaction, we always use the connection that the
748         // transaction was created on.
749         if s.tx != nil {
750                 s.mu.Unlock()
751                 ci, err = s.tx.grabConn() // blocks, waiting for the connection.
752                 if err != nil {
753                         return
754                 }
755                 releaseConn = func(error) { s.tx.releaseConn() }
756                 return ci, releaseConn, s.txsi, nil
757         }
758
759         var cs connStmt
760         match := false
761         for _, v := range s.css {
762                 // TODO(bradfitz): lazily clean up entries in this
763                 // list with dead conns while enumerating
764                 if _, match = s.db.connIfFree(v.ci); match {
765                         cs = v
766                         break
767                 }
768         }
769         s.mu.Unlock()
770
771         // Make a new conn if all are busy.
772         // TODO(bradfitz): or wait for one? make configurable later?
773         if !match {
774                 for i := 0; ; i++ {
775                         ci, err := s.db.conn()
776                         if err != nil {
777                                 return nil, nil, nil, err
778                         }
779                         si, err := ci.Prepare(s.query)
780                         if err == driver.ErrBadConn && i < 10 {
781                                 continue
782                         }
783                         if err != nil {
784                                 return nil, nil, nil, err
785                         }
786                         s.mu.Lock()
787                         cs = connStmt{ci, si}
788                         s.css = append(s.css, cs)
789                         s.mu.Unlock()
790                         break
791                 }
792         }
793
794         conn := cs.ci
795         releaseConn = func(err error) { s.db.putConn(conn, err) }
796         return conn, releaseConn, cs.si, nil
797 }
798
799 // Query executes a prepared query statement with the given arguments
800 // and returns the query results as a *Rows.
801 func (s *Stmt) Query(args ...interface{}) (*Rows, error) {
802         ci, releaseConn, si, err := s.connStmt()
803         if err != nil {
804                 return nil, err
805         }
806
807         // -1 means the driver doesn't know how to count the number of
808         // placeholders, so we won't sanity check input here and instead let the
809         // driver deal with errors.
810         if want := si.NumInput(); want != -1 && len(args) != want {
811                 return nil, fmt.Errorf("sql: statement expects %d inputs; got %d", si.NumInput(), len(args))
812         }
813         sargs, err := subsetTypeArgs(args)
814         if err != nil {
815                 return nil, err
816         }
817         rowsi, err := si.Query(sargs)
818         if err != nil {
819                 releaseConn(err)
820                 return nil, err
821         }
822         // Note: ownership of ci passes to the *Rows, to be freed
823         // with releaseConn.
824         rows := &Rows{
825                 db:          s.db,
826                 ci:          ci,
827                 releaseConn: releaseConn,
828                 rowsi:       rowsi,
829         }
830         return rows, nil
831 }
832
833 // QueryRow executes a prepared query statement with the given arguments.
834 // If an error occurs during the execution of the statement, that error will
835 // be returned by a call to Scan on the returned *Row, which is always non-nil.
836 // If the query selects no rows, the *Row's Scan will return ErrNoRows.
837 // Otherwise, the *Row's Scan scans the first selected row and discards
838 // the rest.
839 //
840 // Example usage:
841 //
842 //  var name string
843 //  err := nameByUseridStmt.QueryRow(id).Scan(&name)
844 func (s *Stmt) QueryRow(args ...interface{}) *Row {
845         rows, err := s.Query(args...)
846         if err != nil {
847                 return &Row{err: err}
848         }
849         return &Row{rows: rows}
850 }
851
852 // Close closes the statement.
853 func (s *Stmt) Close() error {
854         if s.stickyErr != nil {
855                 return s.stickyErr
856         }
857         s.mu.Lock()
858         defer s.mu.Unlock()
859         if s.closed {
860                 return nil
861         }
862         s.closed = true
863
864         if s.tx != nil {
865                 s.txsi.Close()
866         } else {
867                 for _, v := range s.css {
868                         if ci, match := s.db.connIfFree(v.ci); match {
869                                 v.si.Close()
870                                 s.db.putConn(ci, nil)
871                         } else {
872                                 // TODO(bradfitz): care that we can't close
873                                 // this statement because the statement's
874                                 // connection is in use?
875                         }
876                 }
877         }
878         return nil
879 }
880
881 // Rows is the result of a query. Its cursor starts before the first row
882 // of the result set. Use Next to advance through the rows:
883 //
884 //     rows, err := db.Query("SELECT ...")
885 //     ...
886 //     for rows.Next() {
887 //         var id int
888 //         var name string
889 //         err = rows.Scan(&id, &name)
890 //         ...
891 //     }
892 //     err = rows.Err() // get any error encountered during iteration
893 //     ...
894 type Rows struct {
895         db          *DB
896         ci          driver.Conn // owned; must call putconn when closed to release
897         releaseConn func(error)
898         rowsi       driver.Rows
899
900         closed    bool
901         lastcols  []driver.Value
902         lasterr   error
903         closeStmt *Stmt // if non-nil, statement to Close on close
904 }
905
906 // Next prepares the next result row for reading with the Scan method.
907 // It returns true on success, false if there is no next result row.
908 // Every call to Scan, even the first one, must be preceded by a call
909 // to Next.
910 func (rs *Rows) Next() bool {
911         if rs.closed {
912                 return false
913         }
914         if rs.lasterr != nil {
915                 return false
916         }
917         if rs.lastcols == nil {
918                 rs.lastcols = make([]driver.Value, len(rs.rowsi.Columns()))
919         }
920         rs.lasterr = rs.rowsi.Next(rs.lastcols)
921         if rs.lasterr == io.EOF {
922                 rs.Close()
923         }
924         return rs.lasterr == nil
925 }
926
927 // Err returns the error, if any, that was encountered during iteration.
928 func (rs *Rows) Err() error {
929         if rs.lasterr == io.EOF {
930                 return nil
931         }
932         return rs.lasterr
933 }
934
935 // Columns returns the column names.
936 // Columns returns an error if the rows are closed, or if the rows
937 // are from QueryRow and there was a deferred error.
938 func (rs *Rows) Columns() ([]string, error) {
939         if rs.closed {
940                 return nil, errors.New("sql: Rows are closed")
941         }
942         if rs.rowsi == nil {
943                 return nil, errors.New("sql: no Rows available")
944         }
945         return rs.rowsi.Columns(), nil
946 }
947
948 // Scan copies the columns in the current row into the values pointed
949 // at by dest.
950 //
951 // If an argument has type *[]byte, Scan saves in that argument a copy
952 // of the corresponding data. The copy is owned by the caller and can
953 // be modified and held indefinitely. The copy can be avoided by using
954 // an argument of type *RawBytes instead; see the documentation for
955 // RawBytes for restrictions on its use.
956 //
957 // If an argument has type *interface{}, Scan copies the value
958 // provided by the underlying driver without conversion. If the value
959 // is of type []byte, a copy is made and the caller owns the result.
960 func (rs *Rows) Scan(dest ...interface{}) error {
961         if rs.closed {
962                 return errors.New("sql: Rows closed")
963         }
964         if rs.lasterr != nil {
965                 return rs.lasterr
966         }
967         if rs.lastcols == nil {
968                 return errors.New("sql: Scan called without calling Next")
969         }
970         if len(dest) != len(rs.lastcols) {
971                 return fmt.Errorf("sql: expected %d destination arguments in Scan, not %d", len(rs.lastcols), len(dest))
972         }
973         for i, sv := range rs.lastcols {
974                 err := convertAssign(dest[i], sv)
975                 if err != nil {
976                         return fmt.Errorf("sql: Scan error on column index %d: %v", i, err)
977                 }
978         }
979         for _, dp := range dest {
980                 b, ok := dp.(*[]byte)
981                 if !ok {
982                         continue
983                 }
984                 if *b == nil {
985                         // If the []byte is now nil (for a NULL value),
986                         // don't fall through to below which would
987                         // turn it into a non-nil 0-length byte slice
988                         continue
989                 }
990                 if _, ok = dp.(*RawBytes); ok {
991                         continue
992                 }
993                 clone := make([]byte, len(*b))
994                 copy(clone, *b)
995                 *b = clone
996         }
997         return nil
998 }
999
1000 // Close closes the Rows, preventing further enumeration. If the
1001 // end is encountered, the Rows are closed automatically. Close
1002 // is idempotent.
1003 func (rs *Rows) Close() error {
1004         if rs.closed {
1005                 return nil
1006         }
1007         rs.closed = true
1008         err := rs.rowsi.Close()
1009         rs.releaseConn(err)
1010         if rs.closeStmt != nil {
1011                 rs.closeStmt.Close()
1012         }
1013         return err
1014 }
1015
1016 // Row is the result of calling QueryRow to select a single row.
1017 type Row struct {
1018         // One of these two will be non-nil:
1019         err  error // deferred error for easy chaining
1020         rows *Rows
1021 }
1022
1023 // Scan copies the columns from the matched row into the values
1024 // pointed at by dest.  If more than one row matches the query,
1025 // Scan uses the first row and discards the rest.  If no row matches
1026 // the query, Scan returns ErrNoRows.
1027 func (r *Row) Scan(dest ...interface{}) error {
1028         if r.err != nil {
1029                 return r.err
1030         }
1031
1032         // TODO(bradfitz): for now we need to defensively clone all
1033         // []byte that the driver returned (not permitting
1034         // *RawBytes in Rows.Scan), since we're about to close
1035         // the Rows in our defer, when we return from this function.
1036         // the contract with the driver.Next(...) interface is that it
1037         // can return slices into read-only temporary memory that's
1038         // only valid until the next Scan/Close.  But the TODO is that
1039         // for a lot of drivers, this copy will be unnecessary.  We
1040         // should provide an optional interface for drivers to
1041         // implement to say, "don't worry, the []bytes that I return
1042         // from Next will not be modified again." (for instance, if
1043         // they were obtained from the network anyway) But for now we
1044         // don't care.
1045         for _, dp := range dest {
1046                 if _, ok := dp.(*RawBytes); ok {
1047                         return errors.New("sql: RawBytes isn't allowed on Row.Scan")
1048                 }
1049         }
1050
1051         defer r.rows.Close()
1052         if !r.rows.Next() {
1053                 return ErrNoRows
1054         }
1055         err := r.rows.Scan(dest...)
1056         if err != nil {
1057                 return err
1058         }
1059
1060         return nil
1061 }
1062
1063 // A Result summarizes an executed SQL command.
1064 type Result interface {
1065         LastInsertId() (int64, error)
1066         RowsAffected() (int64, error)
1067 }
1068
1069 type result struct {
1070         driver.Result
1071 }