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 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.
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) {
332 sargs, err := subsetTypeArgs(args)
337 for i := 0; i < 10; i++ {
338 res, err = db.exec(query, sargs)
339 if err != driver.ErrBadConn {
346 func (db *DB) exec(query string, sargs []driver.Value) (res Result, err error) {
355 if execer, ok := ci.(driver.Execer); ok {
356 resi, err := execer.Exec(query, sargs)
357 if err != driver.ErrSkip {
361 return result{resi}, nil
365 sti, err := ci.Prepare(query)
371 resi, err := sti.Exec(sargs)
375 return result{resi}, nil
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)
384 rows, err := stmt.Query(args...)
389 rows.closeStmt = stmt
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}
401 // Begin starts a transaction. The isolation level is dependent on
403 func (db *DB) Begin() (*Tx, error) {
406 for i := 0; i < 10; i++ {
408 if err != driver.ErrBadConn {
415 func (db *DB) begin() (tx *Tx, err error) {
420 txi, err := ci.Begin()
423 return nil, fmt.Errorf("sql: failed to Begin transaction: %v", err)
432 // Driver returns the database's underlying driver.
433 func (db *DB) Driver() driver.Driver {
437 // Tx is an in-progress database transaction.
439 // A transaction must end with a call to Commit or Rollback.
441 // After a call to Commit or Rollback, all operations on the
442 // transaction fail with ErrTxDone.
446 // ci is owned exclusively until Commit or Rollback, at which point
447 // it's returned with putConn.
451 // cimu is held while somebody is using ci (between grabConn
455 // done transitions from false to true exactly once, on Commit
456 // or Rollback. once done, all operations fail with
461 var ErrTxDone = errors.New("sql: Transaction has already been committed or rolled back")
463 func (tx *Tx) close() {
465 panic("double close") // internal error
468 tx.db.putConn(tx.ci, nil)
473 func (tx *Tx) grabConn() (driver.Conn, error) {
475 return nil, ErrTxDone
481 func (tx *Tx) releaseConn() {
485 // Commit commits the transaction.
486 func (tx *Tx) Commit() error {
491 return tx.txi.Commit()
494 // Rollback aborts the transaction.
495 func (tx *Tx) Rollback() error {
500 return tx.txi.Rollback()
503 // Prepare creates a prepared statement for use within a transaction.
505 // The returned statement operates within the transaction and can no longer
506 // be used once the transaction has been committed or rolled back.
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()
527 defer tx.releaseConn()
529 si, err := ci.Prepare(query)
543 // Stmt returns a transaction-specific prepared statement from
544 // an existing statement.
547 // updateMoney, err := db.Prepare("UPDATE balance SET money=money+? WHERE id=?")
549 // tx, err := db.Begin()
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.
558 if tx.db != stmt.db {
559 return &Stmt{stickyErr: errors.New("sql: Tx.Stmt: statement from different database used")}
561 ci, err := tx.grabConn()
563 return &Stmt{stickyErr: err}
565 defer tx.releaseConn()
566 si, err := ci.Prepare(stmt.query)
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()
583 defer tx.releaseConn()
585 sargs, err := subsetTypeArgs(args)
590 if execer, ok := ci.(driver.Execer); ok {
591 resi, err := execer.Exec(query, sargs)
593 return result{resi}, nil
595 if err != driver.ErrSkip {
600 sti, err := ci.Prepare(query)
606 resi, err := sti.Exec(sargs)
610 return result{resi}, nil
613 // Query executes a query that returns rows, typically a SELECT.
614 func (tx *Tx) Query(query string, args ...interface{}) (*Rows, error) {
616 return nil, ErrTxDone
618 stmt, err := tx.Prepare(query)
622 rows, err := stmt.Query(args...)
627 rows.closeStmt = stmt
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}
639 // connStmt is a prepared statement on a particular connection.
640 type connStmt struct {
645 // Stmt is a prepared statement. Stmt is safe for concurrent use by multiple goroutines.
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
652 // If in a transaction, else both nil:
656 mu sync.Mutex // protects the rest of the fields
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.
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()
673 defer releaseConn(nil)
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))
682 sargs := make([]driver.Value, len(args))
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()
693 return nil, fmt.Errorf("sql: argument index %d from Value: %v", n, err)
695 if !driver.IsValue(sv) {
696 return nil, fmt.Errorf("sql: argument index %d: non-subset type %T returned from Value", n, sv)
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
708 sargs[n], err = cc.ColumnConverter(n).ConvertValue(arg)
710 return nil, fmt.Errorf("sql: converting Exec argument #%d's type: %v", n, err)
712 if !driver.IsValue(sargs[n]) {
713 return nil, fmt.Errorf("sql: driver ColumnConverter error converted %T to unsupported type %T",
718 for n, arg := range args {
719 sargs[n], err = driver.DefaultParameterConverter.ConvertValue(arg)
721 return nil, fmt.Errorf("sql: converting Exec argument #%d's type: %v", n, err)
726 resi, err := si.Exec(sargs)
730 return result{resi}, nil
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 {
743 err = errors.New("sql: statement is closed")
747 // In a transaction, we always use the connection that the
748 // transaction was created on.
751 ci, err = s.tx.grabConn() // blocks, waiting for the connection.
755 releaseConn = func(error) { s.tx.releaseConn() }
756 return ci, releaseConn, s.txsi, nil
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 {
771 // Make a new conn if all are busy.
772 // TODO(bradfitz): or wait for one? make configurable later?
775 ci, err := s.db.conn()
777 return nil, nil, nil, err
779 si, err := ci.Prepare(s.query)
780 if err == driver.ErrBadConn && i < 10 {
784 return nil, nil, nil, err
787 cs = connStmt{ci, si}
788 s.css = append(s.css, cs)
795 releaseConn = func(err error) { s.db.putConn(conn, err) }
796 return conn, releaseConn, cs.si, nil
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()
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))
813 sargs, err := subsetTypeArgs(args)
817 rowsi, err := si.Query(sargs)
822 // Note: ownership of ci passes to the *Rows, to be freed
827 releaseConn: releaseConn,
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
843 // err := nameByUseridStmt.QueryRow(id).Scan(&name)
844 func (s *Stmt) QueryRow(args ...interface{}) *Row {
845 rows, err := s.Query(args...)
847 return &Row{err: err}
849 return &Row{rows: rows}
852 // Close closes the statement.
853 func (s *Stmt) Close() error {
854 if s.stickyErr != nil {
867 for _, v := range s.css {
868 if ci, match := s.db.connIfFree(v.ci); match {
870 s.db.putConn(ci, nil)
872 // TODO(bradfitz): care that we can't close
873 // this statement because the statement's
874 // connection is in use?
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:
884 // rows, err := db.Query("SELECT ...")
889 // err = rows.Scan(&id, &name)
892 // err = rows.Err() // get any error encountered during iteration
896 ci driver.Conn // owned; must call putconn when closed to release
897 releaseConn func(error)
901 lastcols []driver.Value
903 closeStmt *Stmt // if non-nil, statement to Close on close
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
910 func (rs *Rows) Next() bool {
914 if rs.lasterr != nil {
917 if rs.lastcols == nil {
918 rs.lastcols = make([]driver.Value, len(rs.rowsi.Columns()))
920 rs.lasterr = rs.rowsi.Next(rs.lastcols)
921 if rs.lasterr == io.EOF {
924 return rs.lasterr == nil
927 // Err returns the error, if any, that was encountered during iteration.
928 func (rs *Rows) Err() error {
929 if rs.lasterr == io.EOF {
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) {
940 return nil, errors.New("sql: Rows are closed")
943 return nil, errors.New("sql: no Rows available")
945 return rs.rowsi.Columns(), nil
948 // Scan copies the columns in the current row into the values pointed
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.
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 {
962 return errors.New("sql: Rows closed")
964 if rs.lasterr != nil {
967 if rs.lastcols == nil {
968 return errors.New("sql: Scan called without calling Next")
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))
973 for i, sv := range rs.lastcols {
974 err := convertAssign(dest[i], sv)
976 return fmt.Errorf("sql: Scan error on column index %d: %v", i, err)
979 for _, dp := range dest {
980 b, ok := dp.(*[]byte)
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
990 if _, ok = dp.(*RawBytes); ok {
993 clone := make([]byte, len(*b))
1000 // Close closes the Rows, preventing further enumeration. If the
1001 // end is encountered, the Rows are closed automatically. Close
1003 func (rs *Rows) Close() error {
1008 err := rs.rowsi.Close()
1010 if rs.closeStmt != nil {
1011 rs.closeStmt.Close()
1016 // Row is the result of calling QueryRow to select a single row.
1018 // One of these two will be non-nil:
1019 err error // deferred error for easy chaining
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 {
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
1045 for _, dp := range dest {
1046 if _, ok := dp.(*RawBytes); ok {
1047 return errors.New("sql: RawBytes isn't allowed on Row.Scan")
1051 defer r.rows.Close()
1055 err := r.rows.Scan(dest...)
1063 // A Result summarizes an executed SQL command.
1064 type Result interface {
1065 LastInsertId() (int64, error)
1066 RowsAffected() (int64, error)
1069 type result struct {