OSDN Git Service

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