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.
5 // Package sql provides a generic interface around SQL (or SQL-like)
17 var drivers = make(map[string]driver.Driver)
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,
22 func Register(name string, driver driver.Driver) {
24 panic("sql: Register driver is nil")
26 if _, dup := drivers[name]; dup {
27 panic("sql: Register called twice for driver " + name)
29 drivers[name] = driver
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.
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:
42 // err := db.QueryRow("SELECT name FROM foo WHERE id=?", id).Scan(&s)
50 type NullString struct {
52 Valid bool // Valid is true if String is not NULL
55 // Scan implements the Scanner interface.
56 func (ns *NullString) Scan(value interface{}) error {
58 ns.String, ns.Valid = "", false
62 return convertAssign(&ns.String, value)
65 // Value implements the driver Valuer interface.
66 func (ns NullString) Value() (driver.Value, error) {
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 {
78 Valid bool // Valid is true if Int64 is not NULL
81 // Scan implements the Scanner interface.
82 func (n *NullInt64) Scan(value interface{}) error {
84 n.Int64, n.Valid = 0, false
88 return convertAssign(&n.Int64, value)
91 // Value implements the driver Valuer interface.
92 func (n NullInt64) Value() (driver.Value, error) {
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 {
104 Valid bool // Valid is true if Float64 is not NULL
107 // Scan implements the Scanner interface.
108 func (n *NullFloat64) Scan(value interface{}) error {
110 n.Float64, n.Valid = 0, false
114 return convertAssign(&n.Float64, value)
117 // Value implements the driver Valuer interface.
118 func (n NullFloat64) Value() (driver.Value, error) {
122 return n.Float64, nil
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 {
130 Valid bool // Valid is true if Bool is not NULL
133 // Scan implements the Scanner interface.
134 func (n *NullBool) Scan(value interface{}) error {
136 n.Bool, n.Valid = false, false
140 return convertAssign(&n.Bool, value)
143 // Value implements the driver Valuer interface.
144 func (n NullBool) Value() (driver.Value, error) {
151 // Scanner is an interface used by Scan.
152 type Scanner interface {
153 // Scan assigns a value from a database driver.
155 // The src value will be of one of the following restricted
164 // nil - for NULL values
166 // An error should be returned if the value can not be stored
167 // without loss of information.
168 Scan(src interface{}) error
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")
176 // DB is a database handle. It's safe for concurrent use by multiple
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.
192 mu sync.Mutex // protects freeConn and closed
193 freeConn []driver.Conn
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.
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]
206 return nil, fmt.Errorf("sql: unknown driver %q (forgotten import?)", driverName)
208 return &DB{driver: driver, dsn: dataSourceName}, nil
211 // Close closes the database, releasing any open resources.
212 func (db *DB) Close() error {
216 for _, c := range db.freeConn {
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
234 // conn returns a newly-opened or cached driver.Conn
235 func (db *DB) conn() (driver.Conn, error) {
239 return nil, errors.New("sql: database is closed")
241 if n := len(db.freeConn); n > 0 {
242 conn := db.freeConn[n-1]
243 db.freeConn = db.freeConn[:n-1]
248 return db.driver.Open(db.dsn)
251 func (db *DB) connIfFree(wanted driver.Conn) (conn driver.Conn, ok bool) {
254 for i, conn := range db.freeConn {
258 db.freeConn[i] = db.freeConn[len(db.freeConn)-1]
259 db.freeConn = db.freeConn[:len(db.freeConn)-1]
265 // putConnHook is a hook for testing.
266 var putConnHook func(*DB, driver.Conn)
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.
276 if putConnHook != nil {
279 if n := len(db.freeConn); !db.closed && n < db.maxIdleConns() {
280 db.freeConn = append(db.freeConn, c)
284 // TODO: check to see if we need this Conn for any prepared
285 // statements which are still active?
290 // Prepare creates a prepared statement for later execution.
291 func (db *DB) Prepare(query string) (*Stmt, error) {
294 for i := 0; i < 10; i++ {
295 stmt, err = db.prepare(query)
296 if err != driver.ErrBadConn {
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.
318 si, err := ci.Prepare(query)
325 css: []connStmt{{ci, si}},
330 // Exec executes a query without returning any rows.
331 func (db *DB) Exec(query string, args ...interface{}) (Result, error) {
334 for i := 0; i < 10; i++ {
335 res, err = db.exec(query, args)
336 if err != driver.ErrBadConn {
343 func (db *DB) exec(query string, args []interface{}) (res Result, err error) {
352 if execer, ok := ci.(driver.Execer); ok {
353 dargs, err := driverArgs(nil, args)
357 resi, err := execer.Exec(query, dargs)
358 if err != driver.ErrSkip {
362 return result{resi}, nil
366 sti, err := ci.Prepare(query)
372 return resultFromStatement(sti, args...)
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)
382 rows, err := stmt.Query(args...)
387 rows.closeStmt = stmt
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}
399 // Begin starts a transaction. The isolation level is dependent on
401 func (db *DB) Begin() (*Tx, error) {
404 for i := 0; i < 10; i++ {
406 if err != driver.ErrBadConn {
413 func (db *DB) begin() (tx *Tx, err error) {
418 txi, err := ci.Begin()
430 // Driver returns the database's underlying driver.
431 func (db *DB) Driver() driver.Driver {
435 // Tx is an in-progress database transaction.
437 // A transaction must end with a call to Commit or Rollback.
439 // After a call to Commit or Rollback, all operations on the
440 // transaction fail with ErrTxDone.
444 // ci is owned exclusively until Commit or Rollback, at which point
445 // it's returned with putConn.
449 // cimu is held while somebody is using ci (between grabConn
453 // done transitions from false to true exactly once, on Commit
454 // or Rollback. once done, all operations fail with
459 var ErrTxDone = errors.New("sql: Transaction has already been committed or rolled back")
461 func (tx *Tx) close() {
463 panic("double close") // internal error
466 tx.db.putConn(tx.ci, nil)
471 func (tx *Tx) grabConn() (driver.Conn, error) {
473 return nil, ErrTxDone
479 func (tx *Tx) releaseConn() {
483 // Commit commits the transaction.
484 func (tx *Tx) Commit() error {
489 return tx.txi.Commit()
492 // Rollback aborts the transaction.
493 func (tx *Tx) Rollback() error {
498 return tx.txi.Rollback()
501 // Prepare creates a prepared statement for use within a transaction.
503 // The returned statement operates within the transaction and can no longer
504 // be used once the transaction has been committed or rolled back.
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()
525 defer tx.releaseConn()
527 si, err := ci.Prepare(query)
541 // Stmt returns a transaction-specific prepared statement from
542 // an existing statement.
545 // updateMoney, err := db.Prepare("UPDATE balance SET money=money+? WHERE id=?")
547 // tx, err := db.Begin()
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.
556 if tx.db != stmt.db {
557 return &Stmt{stickyErr: errors.New("sql: Tx.Stmt: statement from different database used")}
559 ci, err := tx.grabConn()
561 return &Stmt{stickyErr: err}
563 defer tx.releaseConn()
564 si, err := ci.Prepare(stmt.query)
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()
581 defer tx.releaseConn()
583 if execer, ok := ci.(driver.Execer); ok {
584 dargs, err := driverArgs(nil, args)
588 resi, err := execer.Exec(query, dargs)
590 return result{resi}, nil
592 if err != driver.ErrSkip {
597 sti, err := ci.Prepare(query)
603 return resultFromStatement(sti, args...)
606 // Query executes a query that returns rows, typically a SELECT.
607 func (tx *Tx) Query(query string, args ...interface{}) (*Rows, error) {
609 return nil, ErrTxDone
611 stmt, err := tx.Prepare(query)
615 rows, err := stmt.Query(args...)
620 rows.closeStmt = stmt
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}
632 // connStmt is a prepared statement on a particular connection.
633 type connStmt struct {
638 // Stmt is a prepared statement. Stmt is safe for concurrent use by multiple goroutines.
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
645 // If in a transaction, else both nil:
649 mu sync.Mutex // protects the rest of the fields
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.
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()
666 defer releaseConn(nil)
668 return resultFromStatement(si, args...)
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))
679 dargs, err := driverArgs(si, args)
684 resi, err := si.Exec(dargs)
688 return result{resi}, nil
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 {
701 err = errors.New("sql: statement is closed")
705 // In a transaction, we always use the connection that the
706 // transaction was created on.
709 ci, err = s.tx.grabConn() // blocks, waiting for the connection.
713 releaseConn = func(error) { s.tx.releaseConn() }
714 return ci, releaseConn, s.txsi, nil
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 {
729 // Make a new conn if all are busy.
730 // TODO(bradfitz): or wait for one? make configurable later?
733 ci, err := s.db.conn()
735 return nil, nil, nil, err
737 si, err := ci.Prepare(s.query)
738 if err == driver.ErrBadConn && i < 10 {
742 return nil, nil, nil, err
745 cs = connStmt{ci, si}
746 s.css = append(s.css, cs)
753 releaseConn = func(err error) { s.db.putConn(conn, err) }
754 return conn, releaseConn, cs.si, nil
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()
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))
772 dargs, err := driverArgs(si, args)
777 rowsi, err := si.Query(dargs)
782 // Note: ownership of ci passes to the *Rows, to be freed
787 releaseConn: releaseConn,
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
803 // err := nameByUseridStmt.QueryRow(id).Scan(&name)
804 func (s *Stmt) QueryRow(args ...interface{}) *Row {
805 rows, err := s.Query(args...)
807 return &Row{err: err}
809 return &Row{rows: rows}
812 // Close closes the statement.
813 func (s *Stmt) Close() error {
814 if s.stickyErr != nil {
827 for _, v := range s.css {
828 if ci, match := s.db.connIfFree(v.ci); match {
830 s.db.putConn(ci, nil)
832 // TODO(bradfitz): care that we can't close
833 // this statement because the statement's
834 // connection is in use?
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:
844 // rows, err := db.Query("SELECT ...")
849 // err = rows.Scan(&id, &name)
852 // err = rows.Err() // get any error encountered during iteration
856 ci driver.Conn // owned; must call putconn when closed to release
857 releaseConn func(error)
861 lastcols []driver.Value
863 closeStmt *Stmt // if non-nil, statement to Close on close
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
870 func (rs *Rows) Next() bool {
874 if rs.lasterr != nil {
877 if rs.lastcols == nil {
878 rs.lastcols = make([]driver.Value, len(rs.rowsi.Columns()))
880 rs.lasterr = rs.rowsi.Next(rs.lastcols)
881 if rs.lasterr == io.EOF {
884 return rs.lasterr == nil
887 // Err returns the error, if any, that was encountered during iteration.
888 func (rs *Rows) Err() error {
889 if rs.lasterr == io.EOF {
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) {
900 return nil, errors.New("sql: Rows are closed")
903 return nil, errors.New("sql: no Rows available")
905 return rs.rowsi.Columns(), nil
908 // Scan copies the columns in the current row into the values pointed
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.
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 {
922 return errors.New("sql: Rows closed")
924 if rs.lasterr != nil {
927 if rs.lastcols == nil {
928 return errors.New("sql: Scan called without calling Next")
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))
933 for i, sv := range rs.lastcols {
934 err := convertAssign(dest[i], sv)
936 return fmt.Errorf("sql: Scan error on column index %d: %v", i, err)
939 for _, dp := range dest {
940 b, ok := dp.(*[]byte)
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
950 if _, ok = dp.(*RawBytes); ok {
953 clone := make([]byte, len(*b))
960 // Close closes the Rows, preventing further enumeration. If the
961 // end is encountered, the Rows are closed automatically. Close
963 func (rs *Rows) Close() error {
968 err := rs.rowsi.Close()
970 if rs.closeStmt != nil {
976 // Row is the result of calling QueryRow to select a single row.
978 // One of these two will be non-nil:
979 err error // deferred error for easy chaining
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 {
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
1005 for _, dp := range dest {
1006 if _, ok := dp.(*RawBytes); ok {
1007 return errors.New("sql: RawBytes isn't allowed on Row.Scan")
1011 defer r.rows.Close()
1015 err := r.rows.Scan(dest...)
1023 // A Result summarizes an executed SQL command.
1024 type Result interface {
1025 LastInsertId() (int64, error)
1026 RowsAffected() (int64, error)
1029 type result struct {