exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
// Copyright 2011 The Go Authors. All rights reserved.
|
|
|
|
|
// Use of this source code is governed by a BSD-style
|
|
|
|
|
// license that can be found in the LICENSE file.
|
|
|
|
|
|
|
|
|
|
// Package sql provides a generic interface around SQL (or SQL-like)
|
|
|
|
|
// databases.
|
2013-03-25 17:38:51 -07:00
|
|
|
//
|
|
|
|
|
// The sql package must be used in conjunction with a database driver.
|
2015-07-10 17:17:11 -06:00
|
|
|
// See https://golang.org/s/sqldrivers for a list of drivers.
|
2013-10-24 10:13:23 -07:00
|
|
|
//
|
2019-03-28 16:15:14 -07:00
|
|
|
// Drivers that do not support context cancellation will not return until
|
2016-12-08 13:07:35 -08:00
|
|
|
// after the query is completed.
|
|
|
|
|
//
|
|
|
|
|
// For usage examples, see the wiki page at
|
2015-07-10 17:17:11 -06:00
|
|
|
// https://golang.org/s/sqlwiki.
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
package sql
|
|
|
|
|
|
|
|
|
|
import (
|
2016-09-19 11:19:32 -07:00
|
|
|
"context"
|
2012-01-19 16:04:26 -08:00
|
|
|
"database/sql/driver"
|
2011-11-01 22:04:37 -04:00
|
|
|
"errors"
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
"fmt"
|
2011-11-01 22:04:37 -04:00
|
|
|
"io"
|
2016-09-27 13:27:02 -07:00
|
|
|
"reflect"
|
2013-02-20 15:35:27 -08:00
|
|
|
"runtime"
|
2014-10-15 13:10:14 -04:00
|
|
|
"sort"
|
2018-02-06 08:56:53 +03:00
|
|
|
"strconv"
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
"sync"
|
2015-01-23 20:02:37 +09:00
|
|
|
"sync/atomic"
|
2015-03-03 21:27:07 +09:00
|
|
|
"time"
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
)
|
|
|
|
|
|
2015-06-29 17:56:20 -07:00
|
|
|
var (
|
2015-10-22 21:50:06 -04:00
|
|
|
driversMu sync.RWMutex
|
2015-06-29 17:56:20 -07:00
|
|
|
drivers = make(map[string]driver.Driver)
|
|
|
|
|
)
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
|
2015-03-03 21:27:07 +09:00
|
|
|
// nowFunc returns the current time; it's overridden in tests.
|
|
|
|
|
var nowFunc = time.Now
|
|
|
|
|
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
// Register makes a database driver available by the provided name.
|
|
|
|
|
// If Register is called twice with the same name or if driver is nil,
|
|
|
|
|
// it panics.
|
|
|
|
|
func Register(name string, driver driver.Driver) {
|
2015-06-29 17:56:20 -07:00
|
|
|
driversMu.Lock()
|
|
|
|
|
defer driversMu.Unlock()
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
if driver == nil {
|
2011-12-15 10:14:57 -08:00
|
|
|
panic("sql: Register driver is nil")
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
}
|
|
|
|
|
if _, dup := drivers[name]; dup {
|
2011-12-15 10:14:57 -08:00
|
|
|
panic("sql: Register called twice for driver " + name)
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
}
|
|
|
|
|
drivers[name] = driver
|
|
|
|
|
}
|
|
|
|
|
|
2014-10-31 09:49:42 -07:00
|
|
|
func unregisterAllDrivers() {
|
2015-06-29 17:56:20 -07:00
|
|
|
driversMu.Lock()
|
|
|
|
|
defer driversMu.Unlock()
|
2014-10-31 09:49:42 -07:00
|
|
|
// For tests.
|
|
|
|
|
drivers = make(map[string]driver.Driver)
|
|
|
|
|
}
|
|
|
|
|
|
2014-10-15 13:10:14 -04:00
|
|
|
// Drivers returns a sorted list of the names of the registered drivers.
|
|
|
|
|
func Drivers() []string {
|
2015-10-22 21:50:06 -04:00
|
|
|
driversMu.RLock()
|
|
|
|
|
defer driversMu.RUnlock()
|
2019-09-30 00:07:34 +00:00
|
|
|
list := make([]string, 0, len(drivers))
|
2014-10-15 13:10:14 -04:00
|
|
|
for name := range drivers {
|
|
|
|
|
list = append(list, name)
|
|
|
|
|
}
|
|
|
|
|
sort.Strings(list)
|
|
|
|
|
return list
|
|
|
|
|
}
|
|
|
|
|
|
2016-12-09 19:58:11 +00:00
|
|
|
// A NamedArg is a named argument. NamedArg values may be used as
|
|
|
|
|
// arguments to Query or Exec and bind to the corresponding named
|
|
|
|
|
// parameter in the SQL statement.
|
|
|
|
|
//
|
|
|
|
|
// For a more concise way to create NamedArg values, see
|
|
|
|
|
// the Named function.
|
2016-11-29 09:57:17 -08:00
|
|
|
type NamedArg struct {
|
2016-11-24 02:21:20 +00:00
|
|
|
_Named_Fields_Required struct{}
|
|
|
|
|
|
2016-12-09 19:58:11 +00:00
|
|
|
// Name is the name of the parameter placeholder.
|
|
|
|
|
//
|
|
|
|
|
// If empty, the ordinal position in the argument list will be
|
|
|
|
|
// used.
|
2016-11-23 09:10:30 -08:00
|
|
|
//
|
|
|
|
|
// Name must omit any symbol prefix.
|
2016-10-03 09:49:25 -07:00
|
|
|
Name string
|
|
|
|
|
|
2016-12-09 19:58:11 +00:00
|
|
|
// Value is the value of the parameter.
|
|
|
|
|
// It may be assigned the same value types as the query
|
|
|
|
|
// arguments.
|
2016-10-03 09:49:25 -07:00
|
|
|
Value interface{}
|
|
|
|
|
}
|
|
|
|
|
|
2016-11-29 09:57:17 -08:00
|
|
|
// Named provides a more concise way to create NamedArg values.
|
|
|
|
|
//
|
|
|
|
|
// Example usage:
|
|
|
|
|
//
|
|
|
|
|
// db.ExecContext(ctx, `
|
|
|
|
|
// delete from Invoice
|
|
|
|
|
// where
|
|
|
|
|
// TimeCreated < @end
|
|
|
|
|
// and TimeCreated >= @start;`,
|
|
|
|
|
// sql.Named("start", startTime),
|
|
|
|
|
// sql.Named("end", endTime),
|
|
|
|
|
// )
|
|
|
|
|
func Named(name string, value interface{}) NamedArg {
|
2016-10-03 09:49:25 -07:00
|
|
|
// This method exists because the go1compat promise
|
|
|
|
|
// doesn't guarantee that structs don't grow more fields,
|
|
|
|
|
// so unkeyed struct literals are a vet error. Thus, we don't
|
2016-11-29 09:57:17 -08:00
|
|
|
// want to allow sql.NamedArg{name, value}.
|
|
|
|
|
return NamedArg{Name: name, Value: value}
|
2016-10-03 09:49:25 -07:00
|
|
|
}
|
|
|
|
|
|
2016-12-13 07:55:12 -08:00
|
|
|
// IsolationLevel is the transaction isolation level used in TxOptions.
|
2016-10-16 23:11:55 -07:00
|
|
|
type IsolationLevel int
|
|
|
|
|
|
2016-12-13 07:55:12 -08:00
|
|
|
// Various isolation levels that drivers may support in BeginTx.
|
2016-10-16 23:11:55 -07:00
|
|
|
// If a driver does not support a given isolation level an error may be returned.
|
2016-10-31 07:32:19 -07:00
|
|
|
//
|
|
|
|
|
// See https://en.wikipedia.org/wiki/Isolation_(database_systems)#Isolation_levels.
|
2016-10-16 23:11:55 -07:00
|
|
|
const (
|
|
|
|
|
LevelDefault IsolationLevel = iota
|
2016-10-31 07:32:19 -07:00
|
|
|
LevelReadUncommitted
|
|
|
|
|
LevelReadCommitted
|
|
|
|
|
LevelWriteCommitted
|
2016-10-16 23:11:55 -07:00
|
|
|
LevelRepeatableRead
|
|
|
|
|
LevelSnapshot
|
|
|
|
|
LevelSerializable
|
|
|
|
|
LevelLinearizable
|
|
|
|
|
)
|
|
|
|
|
|
2018-11-02 16:56:42 +00:00
|
|
|
// String returns the name of the transaction isolation level.
|
2018-02-06 08:56:53 +03:00
|
|
|
func (i IsolationLevel) String() string {
|
|
|
|
|
switch i {
|
|
|
|
|
case LevelDefault:
|
|
|
|
|
return "Default"
|
|
|
|
|
case LevelReadUncommitted:
|
|
|
|
|
return "Read Uncommitted"
|
|
|
|
|
case LevelReadCommitted:
|
|
|
|
|
return "Read Committed"
|
|
|
|
|
case LevelWriteCommitted:
|
|
|
|
|
return "Write Committed"
|
|
|
|
|
case LevelRepeatableRead:
|
|
|
|
|
return "Repeatable Read"
|
|
|
|
|
case LevelSnapshot:
|
|
|
|
|
return "Snapshot"
|
|
|
|
|
case LevelSerializable:
|
|
|
|
|
return "Serializable"
|
|
|
|
|
case LevelLinearizable:
|
|
|
|
|
return "Linearizable"
|
|
|
|
|
default:
|
|
|
|
|
return "IsolationLevel(" + strconv.Itoa(int(i)) + ")"
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
var _ fmt.Stringer = LevelDefault
|
|
|
|
|
|
2016-12-13 07:55:12 -08:00
|
|
|
// TxOptions holds the transaction options to be used in DB.BeginTx.
|
|
|
|
|
type TxOptions struct {
|
|
|
|
|
// Isolation is the transaction isolation level.
|
|
|
|
|
// If zero, the driver or database's default level is used.
|
|
|
|
|
Isolation IsolationLevel
|
|
|
|
|
ReadOnly bool
|
2016-10-16 23:11:55 -07:00
|
|
|
}
|
|
|
|
|
|
2012-01-17 10:44:35 -08:00
|
|
|
// RawBytes is a byte slice that holds a reference to memory owned by
|
|
|
|
|
// the database itself. After a Scan into a RawBytes, the slice is only
|
|
|
|
|
// valid until the next call to Next, Scan, or Close.
|
|
|
|
|
type RawBytes []byte
|
|
|
|
|
|
2012-01-19 09:27:45 -08:00
|
|
|
// NullString represents a string that may be null.
|
2012-02-10 10:20:49 +11:00
|
|
|
// NullString implements the Scanner interface so
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
// it can be used as a scan destination:
|
|
|
|
|
//
|
2012-01-19 09:27:45 -08:00
|
|
|
// var s NullString
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
// err := db.QueryRow("SELECT name FROM foo WHERE id=?", id).Scan(&s)
|
|
|
|
|
// ...
|
|
|
|
|
// if s.Valid {
|
|
|
|
|
// // use s.String
|
|
|
|
|
// } else {
|
|
|
|
|
// // NULL value
|
|
|
|
|
// }
|
|
|
|
|
//
|
2012-01-19 09:27:45 -08:00
|
|
|
type NullString struct {
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
String string
|
|
|
|
|
Valid bool // Valid is true if String is not NULL
|
|
|
|
|
}
|
|
|
|
|
|
2012-02-10 10:20:49 +11:00
|
|
|
// Scan implements the Scanner interface.
|
|
|
|
|
func (ns *NullString) Scan(value interface{}) error {
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
if value == nil {
|
2012-01-19 09:27:45 -08:00
|
|
|
ns.String, ns.Valid = "", false
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
return nil
|
|
|
|
|
}
|
2012-01-19 09:27:45 -08:00
|
|
|
ns.Valid = true
|
|
|
|
|
return convertAssign(&ns.String, value)
|
|
|
|
|
}
|
|
|
|
|
|
2012-02-20 14:25:28 +11:00
|
|
|
// Value implements the driver Valuer interface.
|
|
|
|
|
func (ns NullString) Value() (driver.Value, error) {
|
2012-01-19 09:27:45 -08:00
|
|
|
if !ns.Valid {
|
|
|
|
|
return nil, nil
|
|
|
|
|
}
|
|
|
|
|
return ns.String, nil
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
}
|
|
|
|
|
|
2012-01-25 17:47:32 -08:00
|
|
|
// NullInt64 represents an int64 that may be null.
|
2012-02-10 10:20:49 +11:00
|
|
|
// NullInt64 implements the Scanner interface so
|
2012-01-25 17:47:32 -08:00
|
|
|
// it can be used as a scan destination, similar to NullString.
|
|
|
|
|
type NullInt64 struct {
|
|
|
|
|
Int64 int64
|
|
|
|
|
Valid bool // Valid is true if Int64 is not NULL
|
|
|
|
|
}
|
|
|
|
|
|
2012-02-10 10:20:49 +11:00
|
|
|
// Scan implements the Scanner interface.
|
|
|
|
|
func (n *NullInt64) Scan(value interface{}) error {
|
2012-01-25 17:47:32 -08:00
|
|
|
if value == nil {
|
|
|
|
|
n.Int64, n.Valid = 0, false
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
n.Valid = true
|
|
|
|
|
return convertAssign(&n.Int64, value)
|
|
|
|
|
}
|
|
|
|
|
|
2012-02-20 14:25:28 +11:00
|
|
|
// Value implements the driver Valuer interface.
|
|
|
|
|
func (n NullInt64) Value() (driver.Value, error) {
|
2012-01-25 17:47:32 -08:00
|
|
|
if !n.Valid {
|
|
|
|
|
return nil, nil
|
|
|
|
|
}
|
|
|
|
|
return n.Int64, nil
|
|
|
|
|
}
|
|
|
|
|
|
2019-04-26 11:46:26 -07:00
|
|
|
// NullInt32 represents an int32 that may be null.
|
|
|
|
|
// NullInt32 implements the Scanner interface so
|
|
|
|
|
// it can be used as a scan destination, similar to NullString.
|
|
|
|
|
type NullInt32 struct {
|
|
|
|
|
Int32 int32
|
|
|
|
|
Valid bool // Valid is true if Int32 is not NULL
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Scan implements the Scanner interface.
|
|
|
|
|
func (n *NullInt32) Scan(value interface{}) error {
|
|
|
|
|
if value == nil {
|
|
|
|
|
n.Int32, n.Valid = 0, false
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
n.Valid = true
|
|
|
|
|
return convertAssign(&n.Int32, value)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Value implements the driver Valuer interface.
|
|
|
|
|
func (n NullInt32) Value() (driver.Value, error) {
|
|
|
|
|
if !n.Valid {
|
|
|
|
|
return nil, nil
|
|
|
|
|
}
|
|
|
|
|
return int64(n.Int32), nil
|
|
|
|
|
}
|
|
|
|
|
|
2012-01-25 17:47:32 -08:00
|
|
|
// NullFloat64 represents a float64 that may be null.
|
2012-02-10 10:20:49 +11:00
|
|
|
// NullFloat64 implements the Scanner interface so
|
2012-01-25 17:47:32 -08:00
|
|
|
// it can be used as a scan destination, similar to NullString.
|
|
|
|
|
type NullFloat64 struct {
|
|
|
|
|
Float64 float64
|
|
|
|
|
Valid bool // Valid is true if Float64 is not NULL
|
|
|
|
|
}
|
|
|
|
|
|
2012-02-10 10:20:49 +11:00
|
|
|
// Scan implements the Scanner interface.
|
|
|
|
|
func (n *NullFloat64) Scan(value interface{}) error {
|
2012-01-25 17:47:32 -08:00
|
|
|
if value == nil {
|
|
|
|
|
n.Float64, n.Valid = 0, false
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
n.Valid = true
|
|
|
|
|
return convertAssign(&n.Float64, value)
|
|
|
|
|
}
|
|
|
|
|
|
2012-02-20 14:25:28 +11:00
|
|
|
// Value implements the driver Valuer interface.
|
|
|
|
|
func (n NullFloat64) Value() (driver.Value, error) {
|
2012-01-25 17:47:32 -08:00
|
|
|
if !n.Valid {
|
|
|
|
|
return nil, nil
|
|
|
|
|
}
|
|
|
|
|
return n.Float64, nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// NullBool represents a bool that may be null.
|
2012-02-10 10:20:49 +11:00
|
|
|
// NullBool implements the Scanner interface so
|
2012-01-25 17:47:32 -08:00
|
|
|
// it can be used as a scan destination, similar to NullString.
|
|
|
|
|
type NullBool struct {
|
|
|
|
|
Bool bool
|
|
|
|
|
Valid bool // Valid is true if Bool is not NULL
|
|
|
|
|
}
|
|
|
|
|
|
2012-02-10 10:20:49 +11:00
|
|
|
// Scan implements the Scanner interface.
|
|
|
|
|
func (n *NullBool) Scan(value interface{}) error {
|
2012-01-25 17:47:32 -08:00
|
|
|
if value == nil {
|
|
|
|
|
n.Bool, n.Valid = false, false
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
n.Valid = true
|
|
|
|
|
return convertAssign(&n.Bool, value)
|
|
|
|
|
}
|
|
|
|
|
|
2012-02-20 14:25:28 +11:00
|
|
|
// Value implements the driver Valuer interface.
|
|
|
|
|
func (n NullBool) Value() (driver.Value, error) {
|
2012-01-25 17:47:32 -08:00
|
|
|
if !n.Valid {
|
|
|
|
|
return nil, nil
|
|
|
|
|
}
|
|
|
|
|
return n.Bool, nil
|
|
|
|
|
}
|
|
|
|
|
|
2019-04-05 10:23:15 -07:00
|
|
|
// NullTime represents a time.Time that may be null.
|
|
|
|
|
// NullTime implements the Scanner interface so
|
|
|
|
|
// it can be used as a scan destination, similar to NullString.
|
|
|
|
|
type NullTime struct {
|
|
|
|
|
Time time.Time
|
|
|
|
|
Valid bool // Valid is true if Time is not NULL
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Scan implements the Scanner interface.
|
|
|
|
|
func (n *NullTime) Scan(value interface{}) error {
|
|
|
|
|
if value == nil {
|
|
|
|
|
n.Time, n.Valid = time.Time{}, false
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
n.Valid = true
|
|
|
|
|
return convertAssign(&n.Time, value)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Value implements the driver Valuer interface.
|
|
|
|
|
func (n NullTime) Value() (driver.Value, error) {
|
|
|
|
|
if !n.Valid {
|
|
|
|
|
return nil, nil
|
|
|
|
|
}
|
|
|
|
|
return n.Time, nil
|
|
|
|
|
}
|
|
|
|
|
|
2012-02-10 10:20:49 +11:00
|
|
|
// Scanner is an interface used by Scan.
|
|
|
|
|
type Scanner interface {
|
|
|
|
|
// Scan assigns a value from a database driver.
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
//
|
2016-01-26 20:58:00 +00:00
|
|
|
// The src value will be of one of the following types:
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
//
|
|
|
|
|
// int64
|
|
|
|
|
// float64
|
|
|
|
|
// bool
|
|
|
|
|
// []byte
|
2012-02-10 10:20:49 +11:00
|
|
|
// string
|
|
|
|
|
// time.Time
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
// nil - for NULL values
|
|
|
|
|
//
|
2016-01-27 12:49:13 -08:00
|
|
|
// An error should be returned if the value cannot be stored
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
// without loss of information.
|
2018-04-20 13:18:09 -07:00
|
|
|
//
|
|
|
|
|
// Reference types such as []byte are only valid until the next call to Scan
|
|
|
|
|
// and should not be retained. Their underlying memory is owned by the driver.
|
|
|
|
|
// If retention is necessary, copy their values before the next call to Scan.
|
2012-02-10 10:20:49 +11:00
|
|
|
Scan(src interface{}) error
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
}
|
|
|
|
|
|
2017-03-23 13:17:59 -07:00
|
|
|
// Out may be used to retrieve OUTPUT value parameters from stored procedures.
|
|
|
|
|
//
|
|
|
|
|
// Not all drivers and databases support OUTPUT value parameters.
|
|
|
|
|
//
|
|
|
|
|
// Example usage:
|
|
|
|
|
//
|
|
|
|
|
// var outArg string
|
2017-10-17 23:11:54 -03:00
|
|
|
// _, err := db.ExecContext(ctx, "ProcName", sql.Named("Arg1", sql.Out{Dest: &outArg}))
|
2017-03-23 13:17:59 -07:00
|
|
|
type Out struct {
|
|
|
|
|
_Named_Fields_Required struct{}
|
|
|
|
|
|
|
|
|
|
// Dest is a pointer to the value that will be set to the result of the
|
|
|
|
|
// stored procedure's OUTPUT parameter.
|
|
|
|
|
Dest interface{}
|
|
|
|
|
|
|
|
|
|
// In is whether the parameter is an INOUT parameter. If so, the input value to the stored
|
|
|
|
|
// procedure is the dereferenced value of Dest's pointer, which is then replaced with
|
|
|
|
|
// the output value.
|
|
|
|
|
In bool
|
|
|
|
|
}
|
|
|
|
|
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
// ErrNoRows is returned by Scan when QueryRow doesn't return a
|
|
|
|
|
// row. In such a case, QueryRow returns a placeholder *Row value that
|
|
|
|
|
// defers this error until a Scan.
|
2011-12-15 10:14:57 -08:00
|
|
|
var ErrNoRows = errors.New("sql: no rows in result set")
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
|
2014-05-19 09:54:47 -07:00
|
|
|
// DB is a database handle representing a pool of zero or more
|
|
|
|
|
// underlying connections. It's safe for concurrent use by multiple
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
// goroutines.
|
2012-03-06 17:44:47 -08:00
|
|
|
//
|
2013-03-18 15:54:22 -07:00
|
|
|
// The sql package creates and frees connections automatically; it
|
|
|
|
|
// also maintains a free pool of idle connections. If the database has
|
2018-06-06 18:01:02 +03:00
|
|
|
// a concept of per-connection state, such state can be reliably observed
|
|
|
|
|
// within a transaction (Tx) or connection (Conn). Once DB.Begin is called, the
|
2013-03-18 15:54:22 -07:00
|
|
|
// returned Tx is bound to a single connection. Once Commit or
|
|
|
|
|
// Rollback is called on the transaction, that transaction's
|
|
|
|
|
// connection is returned to DB's idle connection pool. The pool size
|
|
|
|
|
// can be controlled with SetMaxIdleConns.
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
type DB struct {
|
2018-04-20 14:22:18 -07:00
|
|
|
// Atomic access only. At top of struct to prevent mis-alignment
|
|
|
|
|
// on 32-bit platforms. Of type time.Duration.
|
|
|
|
|
waitDuration int64 // Total time waited for new connections.
|
|
|
|
|
|
2017-08-05 06:04:19 -04:00
|
|
|
connector driver.Connector
|
2015-01-23 20:02:37 +09:00
|
|
|
// numClosed is an atomic counter which represents a total number of
|
|
|
|
|
// closed connections. Stmt.openStmt checks it before cleaning closed
|
|
|
|
|
// connections in Stmt.css.
|
|
|
|
|
numClosed uint64
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
|
2013-08-30 09:27:33 -07:00
|
|
|
mu sync.Mutex // protects following fields
|
2014-08-28 08:49:56 -07:00
|
|
|
freeConn []*driverConn
|
2017-02-08 10:32:22 -08:00
|
|
|
connRequests map[uint64]chan connRequest
|
|
|
|
|
nextRequest uint64 // Next key to use in connRequests.
|
|
|
|
|
numOpen int // number of opened and pending open connections
|
2013-10-29 16:03:13 -07:00
|
|
|
// Used to signal the need for new connections
|
2013-08-30 09:27:33 -07:00
|
|
|
// a goroutine running connectionOpener() reads on this chan and
|
|
|
|
|
// maybeOpenNewConnections sends on the chan (one send per needed connection)
|
|
|
|
|
// It is closed during db.Close(). The close tells the connectionOpener
|
|
|
|
|
// goroutine to exit.
|
2018-04-20 14:22:18 -07:00
|
|
|
openerCh chan struct{}
|
|
|
|
|
closed bool
|
|
|
|
|
dep map[finalCloser]depSet
|
|
|
|
|
lastPut map[*driverConn]string // stacktrace of last conn's put; debug only
|
2018-10-29 09:09:21 -07:00
|
|
|
maxIdleCount int // zero means defaultMaxIdleConns; negative means 0
|
2018-04-20 14:22:18 -07:00
|
|
|
maxOpen int // <= 0 means unlimited
|
|
|
|
|
maxLifetime time.Duration // maximum amount of time a connection may be reused
|
2018-10-29 09:09:21 -07:00
|
|
|
maxIdleTime time.Duration // maximum amount of time a connection may be idle before being closed
|
2018-04-20 14:22:18 -07:00
|
|
|
cleanerCh chan struct{}
|
|
|
|
|
waitCount int64 // Total number of connections waited for.
|
2018-10-29 09:09:21 -07:00
|
|
|
maxIdleClosed int64 // Total number of connections closed due to idle count.
|
|
|
|
|
maxIdleTimeClosed int64 // Total number of connections closed due to idle time.
|
2018-04-20 14:22:18 -07:00
|
|
|
maxLifetimeClosed int64 // Total number of connections closed due to max free limit.
|
2017-10-02 11:16:53 -07:00
|
|
|
|
|
|
|
|
stop func() // stop cancels the connection opener and the session resetter.
|
2013-03-14 15:01:45 -07:00
|
|
|
}
|
|
|
|
|
|
2015-03-27 19:45:12 +01:00
|
|
|
// connReuseStrategy determines how (*DB).conn returns database connections.
|
|
|
|
|
type connReuseStrategy uint8
|
|
|
|
|
|
|
|
|
|
const (
|
|
|
|
|
// alwaysNewConn forces a new connection to the database.
|
|
|
|
|
alwaysNewConn connReuseStrategy = iota
|
|
|
|
|
// cachedOrNewConn returns a cached connection, if available, else waits
|
|
|
|
|
// for one to become available (if MaxOpenConns has been reached) or
|
|
|
|
|
// creates a new database connection.
|
|
|
|
|
cachedOrNewConn
|
|
|
|
|
)
|
|
|
|
|
|
2013-03-14 15:01:45 -07:00
|
|
|
// driverConn wraps a driver.Conn with a mutex, to
|
|
|
|
|
// be held during all calls into the Conn. (including any calls onto
|
|
|
|
|
// interfaces returned via that Conn, such as calls on Tx, Stmt,
|
|
|
|
|
// Result, Rows)
|
|
|
|
|
type driverConn struct {
|
2015-03-03 21:27:07 +09:00
|
|
|
db *DB
|
|
|
|
|
createdAt time.Time
|
2013-03-25 16:50:27 -07:00
|
|
|
|
database/sql: fix driver Conn refcounting with prepared statements
The refcounting of driver Conns was completedly busted and
would leak (be held open forever) with any reasonable
load. This was a significant regression from Go 1.0.
The core of this patch is removing one line:
s.db.addDep(dc, s)
A database conn (dc) is a resource that be re-created any time
(but cached for speed) should not be held open forever with a
dependency refcount just because the Stmt (s) is alive (which
typically last for long periods of time, like forever).
The meat of the patch is new tests. In fixing the real issue,
a lot of tests then failed due to the fakedb_test.go's paranoia
about closing a fakeConn while it has open fakeStmts on it. I
could've ignored that, but that's been a problem in the past for
other bugs.
Instead, I now track per-Conn open statements and close them
when the the conn closes. The proper way to do this would've
been making *driverStmt a finalCloser and using the dep mechanism,
but it was much more invasive. Added a TODO instead.
I'd like to give a way for drivers to opt-out of caring about
driver.Stmt closes before a driver.Conn close, but that's a TODO
for the future, and that TODO is added in this CL.
I know this is very late for Go 1.1, but database/sql is
currently nearly useless without this.
I'd like to believe all these database/sql bugs in the past
release cycle are the result of increased usage, number of
drivers, and good feedback from increasingly-capable Go
developers, and not the result of me sucking. It's also hard
with all the real drivers being out-of-tree, so I'm having to
add more and more hooks to fakedb_test.go to simulate things
which real drivers end up doing.
Fixes #5323
R=golang-dev, snaury, gwenn.kahz, google, r
CC=golang-dev
https://golang.org/cl/8836045
2013-04-25 14:45:56 -07:00
|
|
|
sync.Mutex // guards following
|
|
|
|
|
ci driver.Conn
|
2019-04-26 14:45:46 -07:00
|
|
|
needReset bool // The connection session should be reset before use if true.
|
database/sql: fix driver Conn refcounting with prepared statements
The refcounting of driver Conns was completedly busted and
would leak (be held open forever) with any reasonable
load. This was a significant regression from Go 1.0.
The core of this patch is removing one line:
s.db.addDep(dc, s)
A database conn (dc) is a resource that be re-created any time
(but cached for speed) should not be held open forever with a
dependency refcount just because the Stmt (s) is alive (which
typically last for long periods of time, like forever).
The meat of the patch is new tests. In fixing the real issue,
a lot of tests then failed due to the fakedb_test.go's paranoia
about closing a fakeConn while it has open fakeStmts on it. I
could've ignored that, but that's been a problem in the past for
other bugs.
Instead, I now track per-Conn open statements and close them
when the the conn closes. The proper way to do this would've
been making *driverStmt a finalCloser and using the dep mechanism,
but it was much more invasive. Added a TODO instead.
I'd like to give a way for drivers to opt-out of caring about
driver.Stmt closes before a driver.Conn close, but that's a TODO
for the future, and that TODO is added in this CL.
I know this is very late for Go 1.1, but database/sql is
currently nearly useless without this.
I'd like to believe all these database/sql bugs in the past
release cycle are the result of increased usage, number of
drivers, and good feedback from increasingly-capable Go
developers, and not the result of me sucking. It's also hard
with all the real drivers being out-of-tree, so I'm having to
add more and more hooks to fakedb_test.go to simulate things
which real drivers end up doing.
Fixes #5323
R=golang-dev, snaury, gwenn.kahz, google, r
CC=golang-dev
https://golang.org/cl/8836045
2013-04-25 14:45:56 -07:00
|
|
|
closed bool
|
|
|
|
|
finalClosed bool // ci.Close has been called
|
2016-11-17 09:33:31 -08:00
|
|
|
openStmt map[*driverStmt]bool
|
2013-04-03 11:13:40 -07:00
|
|
|
|
|
|
|
|
// guarded by db.mu
|
database/sql: fix driver Conn refcounting with prepared statements
The refcounting of driver Conns was completedly busted and
would leak (be held open forever) with any reasonable
load. This was a significant regression from Go 1.0.
The core of this patch is removing one line:
s.db.addDep(dc, s)
A database conn (dc) is a resource that be re-created any time
(but cached for speed) should not be held open forever with a
dependency refcount just because the Stmt (s) is alive (which
typically last for long periods of time, like forever).
The meat of the patch is new tests. In fixing the real issue,
a lot of tests then failed due to the fakedb_test.go's paranoia
about closing a fakeConn while it has open fakeStmts on it. I
could've ignored that, but that's been a problem in the past for
other bugs.
Instead, I now track per-Conn open statements and close them
when the the conn closes. The proper way to do this would've
been making *driverStmt a finalCloser and using the dep mechanism,
but it was much more invasive. Added a TODO instead.
I'd like to give a way for drivers to opt-out of caring about
driver.Stmt closes before a driver.Conn close, but that's a TODO
for the future, and that TODO is added in this CL.
I know this is very late for Go 1.1, but database/sql is
currently nearly useless without this.
I'd like to believe all these database/sql bugs in the past
release cycle are the result of increased usage, number of
drivers, and good feedback from increasingly-capable Go
developers, and not the result of me sucking. It's also hard
with all the real drivers being out-of-tree, so I'm having to
add more and more hooks to fakedb_test.go to simulate things
which real drivers end up doing.
Fixes #5323
R=golang-dev, snaury, gwenn.kahz, google, r
CC=golang-dev
https://golang.org/cl/8836045
2013-04-25 14:45:56 -07:00
|
|
|
inUse bool
|
2018-10-29 09:09:21 -07:00
|
|
|
returnedAt time.Time // Time the connection was created or returned.
|
|
|
|
|
onPut []func() // code (with db.mu held) run when conn is next returned
|
|
|
|
|
dbmuClosed bool // same as closed, but guarded by db.mu, for removeClosedStmtLocked
|
database/sql: fix driver Conn refcounting with prepared statements
The refcounting of driver Conns was completedly busted and
would leak (be held open forever) with any reasonable
load. This was a significant regression from Go 1.0.
The core of this patch is removing one line:
s.db.addDep(dc, s)
A database conn (dc) is a resource that be re-created any time
(but cached for speed) should not be held open forever with a
dependency refcount just because the Stmt (s) is alive (which
typically last for long periods of time, like forever).
The meat of the patch is new tests. In fixing the real issue,
a lot of tests then failed due to the fakedb_test.go's paranoia
about closing a fakeConn while it has open fakeStmts on it. I
could've ignored that, but that's been a problem in the past for
other bugs.
Instead, I now track per-Conn open statements and close them
when the the conn closes. The proper way to do this would've
been making *driverStmt a finalCloser and using the dep mechanism,
but it was much more invasive. Added a TODO instead.
I'd like to give a way for drivers to opt-out of caring about
driver.Stmt closes before a driver.Conn close, but that's a TODO
for the future, and that TODO is added in this CL.
I know this is very late for Go 1.1, but database/sql is
currently nearly useless without this.
I'd like to believe all these database/sql bugs in the past
release cycle are the result of increased usage, number of
drivers, and good feedback from increasingly-capable Go
developers, and not the result of me sucking. It's also hard
with all the real drivers being out-of-tree, so I'm having to
add more and more hooks to fakedb_test.go to simulate things
which real drivers end up doing.
Fixes #5323
R=golang-dev, snaury, gwenn.kahz, google, r
CC=golang-dev
https://golang.org/cl/8836045
2013-04-25 14:45:56 -07:00
|
|
|
}
|
|
|
|
|
|
2013-05-14 16:35:31 -07:00
|
|
|
func (dc *driverConn) releaseConn(err error) {
|
2017-10-02 11:16:53 -07:00
|
|
|
dc.db.putConn(dc, err, true)
|
2013-05-14 16:35:31 -07:00
|
|
|
}
|
|
|
|
|
|
2016-11-17 09:33:31 -08:00
|
|
|
func (dc *driverConn) removeOpenStmt(ds *driverStmt) {
|
database/sql: fix driver Conn refcounting with prepared statements
The refcounting of driver Conns was completedly busted and
would leak (be held open forever) with any reasonable
load. This was a significant regression from Go 1.0.
The core of this patch is removing one line:
s.db.addDep(dc, s)
A database conn (dc) is a resource that be re-created any time
(but cached for speed) should not be held open forever with a
dependency refcount just because the Stmt (s) is alive (which
typically last for long periods of time, like forever).
The meat of the patch is new tests. In fixing the real issue,
a lot of tests then failed due to the fakedb_test.go's paranoia
about closing a fakeConn while it has open fakeStmts on it. I
could've ignored that, but that's been a problem in the past for
other bugs.
Instead, I now track per-Conn open statements and close them
when the the conn closes. The proper way to do this would've
been making *driverStmt a finalCloser and using the dep mechanism,
but it was much more invasive. Added a TODO instead.
I'd like to give a way for drivers to opt-out of caring about
driver.Stmt closes before a driver.Conn close, but that's a TODO
for the future, and that TODO is added in this CL.
I know this is very late for Go 1.1, but database/sql is
currently nearly useless without this.
I'd like to believe all these database/sql bugs in the past
release cycle are the result of increased usage, number of
drivers, and good feedback from increasingly-capable Go
developers, and not the result of me sucking. It's also hard
with all the real drivers being out-of-tree, so I'm having to
add more and more hooks to fakedb_test.go to simulate things
which real drivers end up doing.
Fixes #5323
R=golang-dev, snaury, gwenn.kahz, google, r
CC=golang-dev
https://golang.org/cl/8836045
2013-04-25 14:45:56 -07:00
|
|
|
dc.Lock()
|
|
|
|
|
defer dc.Unlock()
|
2016-11-17 09:33:31 -08:00
|
|
|
delete(dc.openStmt, ds)
|
database/sql: fix driver Conn refcounting with prepared statements
The refcounting of driver Conns was completedly busted and
would leak (be held open forever) with any reasonable
load. This was a significant regression from Go 1.0.
The core of this patch is removing one line:
s.db.addDep(dc, s)
A database conn (dc) is a resource that be re-created any time
(but cached for speed) should not be held open forever with a
dependency refcount just because the Stmt (s) is alive (which
typically last for long periods of time, like forever).
The meat of the patch is new tests. In fixing the real issue,
a lot of tests then failed due to the fakedb_test.go's paranoia
about closing a fakeConn while it has open fakeStmts on it. I
could've ignored that, but that's been a problem in the past for
other bugs.
Instead, I now track per-Conn open statements and close them
when the the conn closes. The proper way to do this would've
been making *driverStmt a finalCloser and using the dep mechanism,
but it was much more invasive. Added a TODO instead.
I'd like to give a way for drivers to opt-out of caring about
driver.Stmt closes before a driver.Conn close, but that's a TODO
for the future, and that TODO is added in this CL.
I know this is very late for Go 1.1, but database/sql is
currently nearly useless without this.
I'd like to believe all these database/sql bugs in the past
release cycle are the result of increased usage, number of
drivers, and good feedback from increasingly-capable Go
developers, and not the result of me sucking. It's also hard
with all the real drivers being out-of-tree, so I'm having to
add more and more hooks to fakedb_test.go to simulate things
which real drivers end up doing.
Fixes #5323
R=golang-dev, snaury, gwenn.kahz, google, r
CC=golang-dev
https://golang.org/cl/8836045
2013-04-25 14:45:56 -07:00
|
|
|
}
|
|
|
|
|
|
2015-03-03 21:27:07 +09:00
|
|
|
func (dc *driverConn) expired(timeout time.Duration) bool {
|
|
|
|
|
if timeout <= 0 {
|
|
|
|
|
return false
|
|
|
|
|
}
|
|
|
|
|
return dc.createdAt.Add(timeout).Before(nowFunc())
|
|
|
|
|
}
|
|
|
|
|
|
2019-04-26 14:45:46 -07:00
|
|
|
// resetSession checks if the driver connection needs the
|
|
|
|
|
// session to be reset and if required, resets it.
|
|
|
|
|
func (dc *driverConn) resetSession(ctx context.Context) error {
|
|
|
|
|
dc.Lock()
|
|
|
|
|
defer dc.Unlock()
|
|
|
|
|
|
|
|
|
|
if !dc.needReset {
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
if cr, ok := dc.ci.(driver.SessionResetter); ok {
|
|
|
|
|
return cr.ResetSession(ctx)
|
|
|
|
|
}
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// validateConnection checks if the connection is valid and can
|
|
|
|
|
// still be used. It also marks the session for reset if required.
|
|
|
|
|
func (dc *driverConn) validateConnection(needsReset bool) bool {
|
|
|
|
|
dc.Lock()
|
|
|
|
|
defer dc.Unlock()
|
|
|
|
|
|
|
|
|
|
if needsReset {
|
|
|
|
|
dc.needReset = true
|
|
|
|
|
}
|
2020-03-18 10:03:51 -07:00
|
|
|
if cv, ok := dc.ci.(driver.Validator); ok {
|
|
|
|
|
return cv.IsValid()
|
2019-04-26 14:45:46 -07:00
|
|
|
}
|
|
|
|
|
return true
|
|
|
|
|
}
|
|
|
|
|
|
2017-06-12 10:46:15 -07:00
|
|
|
// prepareLocked prepares the query on dc. When cg == nil the dc must keep track of
|
|
|
|
|
// the prepared statements in a pool.
|
|
|
|
|
func (dc *driverConn) prepareLocked(ctx context.Context, cg stmtConnGrabber, query string) (*driverStmt, error) {
|
2016-09-19 11:19:32 -07:00
|
|
|
si, err := ctxDriverPrepare(ctx, dc.ci, query)
|
2016-11-17 09:33:31 -08:00
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
database/sql: fix driver Conn refcounting with prepared statements
The refcounting of driver Conns was completedly busted and
would leak (be held open forever) with any reasonable
load. This was a significant regression from Go 1.0.
The core of this patch is removing one line:
s.db.addDep(dc, s)
A database conn (dc) is a resource that be re-created any time
(but cached for speed) should not be held open forever with a
dependency refcount just because the Stmt (s) is alive (which
typically last for long periods of time, like forever).
The meat of the patch is new tests. In fixing the real issue,
a lot of tests then failed due to the fakedb_test.go's paranoia
about closing a fakeConn while it has open fakeStmts on it. I
could've ignored that, but that's been a problem in the past for
other bugs.
Instead, I now track per-Conn open statements and close them
when the the conn closes. The proper way to do this would've
been making *driverStmt a finalCloser and using the dep mechanism,
but it was much more invasive. Added a TODO instead.
I'd like to give a way for drivers to opt-out of caring about
driver.Stmt closes before a driver.Conn close, but that's a TODO
for the future, and that TODO is added in this CL.
I know this is very late for Go 1.1, but database/sql is
currently nearly useless without this.
I'd like to believe all these database/sql bugs in the past
release cycle are the result of increased usage, number of
drivers, and good feedback from increasingly-capable Go
developers, and not the result of me sucking. It's also hard
with all the real drivers being out-of-tree, so I'm having to
add more and more hooks to fakedb_test.go to simulate things
which real drivers end up doing.
Fixes #5323
R=golang-dev, snaury, gwenn.kahz, google, r
CC=golang-dev
https://golang.org/cl/8836045
2013-04-25 14:45:56 -07:00
|
|
|
}
|
2017-06-12 10:46:15 -07:00
|
|
|
ds := &driverStmt{Locker: dc, si: si}
|
|
|
|
|
|
|
|
|
|
// No need to manage open statements if there is a single connection grabber.
|
|
|
|
|
if cg != nil {
|
|
|
|
|
return ds, nil
|
|
|
|
|
}
|
2016-11-17 09:33:31 -08:00
|
|
|
|
|
|
|
|
// Track each driverConn's open statements, so we can close them
|
|
|
|
|
// before closing the conn.
|
|
|
|
|
//
|
|
|
|
|
// Wrap all driver.Stmt is *driverStmt to ensure they are only closed once.
|
|
|
|
|
if dc.openStmt == nil {
|
|
|
|
|
dc.openStmt = make(map[*driverStmt]bool)
|
|
|
|
|
}
|
|
|
|
|
dc.openStmt[ds] = true
|
|
|
|
|
return ds, nil
|
2013-03-25 16:50:27 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// the dc.db's Mutex is held.
|
2013-08-30 09:27:33 -07:00
|
|
|
func (dc *driverConn) closeDBLocked() func() error {
|
2013-03-25 16:50:27 -07:00
|
|
|
dc.Lock()
|
2013-08-30 09:27:33 -07:00
|
|
|
defer dc.Unlock()
|
2013-03-25 16:50:27 -07:00
|
|
|
if dc.closed {
|
2013-08-30 09:27:33 -07:00
|
|
|
return func() error { return errors.New("sql: duplicate driverConn close") }
|
2013-03-25 16:50:27 -07:00
|
|
|
}
|
|
|
|
|
dc.closed = true
|
2013-08-30 09:27:33 -07:00
|
|
|
return dc.db.removeDepLocked(dc, dc)
|
2013-03-25 16:50:27 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (dc *driverConn) Close() error {
|
|
|
|
|
dc.Lock()
|
|
|
|
|
if dc.closed {
|
|
|
|
|
dc.Unlock()
|
|
|
|
|
return errors.New("sql: duplicate driverConn close")
|
|
|
|
|
}
|
|
|
|
|
dc.closed = true
|
|
|
|
|
dc.Unlock() // not defer; removeDep finalClose calls may need to lock
|
database/sql: fix driver Conn refcounting with prepared statements
The refcounting of driver Conns was completedly busted and
would leak (be held open forever) with any reasonable
load. This was a significant regression from Go 1.0.
The core of this patch is removing one line:
s.db.addDep(dc, s)
A database conn (dc) is a resource that be re-created any time
(but cached for speed) should not be held open forever with a
dependency refcount just because the Stmt (s) is alive (which
typically last for long periods of time, like forever).
The meat of the patch is new tests. In fixing the real issue,
a lot of tests then failed due to the fakedb_test.go's paranoia
about closing a fakeConn while it has open fakeStmts on it. I
could've ignored that, but that's been a problem in the past for
other bugs.
Instead, I now track per-Conn open statements and close them
when the the conn closes. The proper way to do this would've
been making *driverStmt a finalCloser and using the dep mechanism,
but it was much more invasive. Added a TODO instead.
I'd like to give a way for drivers to opt-out of caring about
driver.Stmt closes before a driver.Conn close, but that's a TODO
for the future, and that TODO is added in this CL.
I know this is very late for Go 1.1, but database/sql is
currently nearly useless without this.
I'd like to believe all these database/sql bugs in the past
release cycle are the result of increased usage, number of
drivers, and good feedback from increasingly-capable Go
developers, and not the result of me sucking. It's also hard
with all the real drivers being out-of-tree, so I'm having to
add more and more hooks to fakedb_test.go to simulate things
which real drivers end up doing.
Fixes #5323
R=golang-dev, snaury, gwenn.kahz, google, r
CC=golang-dev
https://golang.org/cl/8836045
2013-04-25 14:45:56 -07:00
|
|
|
|
|
|
|
|
// And now updates that require holding dc.mu.Lock.
|
|
|
|
|
dc.db.mu.Lock()
|
|
|
|
|
dc.dbmuClosed = true
|
|
|
|
|
fn := dc.db.removeDepLocked(dc, dc)
|
|
|
|
|
dc.db.mu.Unlock()
|
|
|
|
|
return fn()
|
2013-03-25 16:50:27 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (dc *driverConn) finalClose() error {
|
2016-11-16 11:33:38 -08:00
|
|
|
var err error
|
2016-11-17 09:33:31 -08:00
|
|
|
|
|
|
|
|
// Each *driverStmt has a lock to the dc. Copy the list out of the dc
|
|
|
|
|
// before calling close on each stmt.
|
|
|
|
|
var openStmt []*driverStmt
|
2016-11-16 11:33:38 -08:00
|
|
|
withLock(dc, func() {
|
2016-11-17 09:33:31 -08:00
|
|
|
openStmt = make([]*driverStmt, 0, len(dc.openStmt))
|
|
|
|
|
for ds := range dc.openStmt {
|
|
|
|
|
openStmt = append(openStmt, ds)
|
2016-11-16 11:33:38 -08:00
|
|
|
}
|
2016-11-17 09:33:31 -08:00
|
|
|
dc.openStmt = nil
|
|
|
|
|
})
|
|
|
|
|
for _, ds := range openStmt {
|
|
|
|
|
ds.Close()
|
|
|
|
|
}
|
|
|
|
|
withLock(dc, func() {
|
|
|
|
|
dc.finalClosed = true
|
|
|
|
|
err = dc.ci.Close()
|
|
|
|
|
dc.ci = nil
|
2016-11-16 11:33:38 -08:00
|
|
|
})
|
2013-08-30 09:27:33 -07:00
|
|
|
|
|
|
|
|
dc.db.mu.Lock()
|
|
|
|
|
dc.db.numOpen--
|
|
|
|
|
dc.db.maybeOpenNewConnections()
|
|
|
|
|
dc.db.mu.Unlock()
|
|
|
|
|
|
2015-01-23 20:02:37 +09:00
|
|
|
atomic.AddUint64(&dc.db.numClosed, 1)
|
2013-03-25 16:50:27 -07:00
|
|
|
return err
|
2013-03-14 15:01:45 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// driverStmt associates a driver.Stmt with the
|
|
|
|
|
// *driverConn from which it came, so the driverConn's lock can be
|
|
|
|
|
// held during calls.
|
|
|
|
|
type driverStmt struct {
|
|
|
|
|
sync.Locker // the *driverConn
|
|
|
|
|
si driver.Stmt
|
2016-11-17 09:33:31 -08:00
|
|
|
closed bool
|
|
|
|
|
closeErr error // return value of previous Close call
|
2013-03-14 15:01:45 -07:00
|
|
|
}
|
|
|
|
|
|
2018-07-25 16:36:11 -07:00
|
|
|
// Close ensures driver.Stmt is only closed once and always returns the same
|
2016-11-17 09:33:31 -08:00
|
|
|
// result.
|
2013-03-14 15:01:45 -07:00
|
|
|
func (ds *driverStmt) Close() error {
|
|
|
|
|
ds.Lock()
|
|
|
|
|
defer ds.Unlock()
|
2016-11-17 09:33:31 -08:00
|
|
|
if ds.closed {
|
|
|
|
|
return ds.closeErr
|
|
|
|
|
}
|
|
|
|
|
ds.closed = true
|
|
|
|
|
ds.closeErr = ds.si.Close()
|
|
|
|
|
return ds.closeErr
|
2013-02-20 15:35:27 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// depSet is a finalCloser's outstanding dependencies
|
|
|
|
|
type depSet map[interface{}]bool // set of true bools
|
|
|
|
|
|
database/sql: fix driver Conn refcounting with prepared statements
The refcounting of driver Conns was completedly busted and
would leak (be held open forever) with any reasonable
load. This was a significant regression from Go 1.0.
The core of this patch is removing one line:
s.db.addDep(dc, s)
A database conn (dc) is a resource that be re-created any time
(but cached for speed) should not be held open forever with a
dependency refcount just because the Stmt (s) is alive (which
typically last for long periods of time, like forever).
The meat of the patch is new tests. In fixing the real issue,
a lot of tests then failed due to the fakedb_test.go's paranoia
about closing a fakeConn while it has open fakeStmts on it. I
could've ignored that, but that's been a problem in the past for
other bugs.
Instead, I now track per-Conn open statements and close them
when the the conn closes. The proper way to do this would've
been making *driverStmt a finalCloser and using the dep mechanism,
but it was much more invasive. Added a TODO instead.
I'd like to give a way for drivers to opt-out of caring about
driver.Stmt closes before a driver.Conn close, but that's a TODO
for the future, and that TODO is added in this CL.
I know this is very late for Go 1.1, but database/sql is
currently nearly useless without this.
I'd like to believe all these database/sql bugs in the past
release cycle are the result of increased usage, number of
drivers, and good feedback from increasingly-capable Go
developers, and not the result of me sucking. It's also hard
with all the real drivers being out-of-tree, so I'm having to
add more and more hooks to fakedb_test.go to simulate things
which real drivers end up doing.
Fixes #5323
R=golang-dev, snaury, gwenn.kahz, google, r
CC=golang-dev
https://golang.org/cl/8836045
2013-04-25 14:45:56 -07:00
|
|
|
// The finalCloser interface is used by (*DB).addDep and related
|
|
|
|
|
// dependency reference counting.
|
2013-02-20 15:35:27 -08:00
|
|
|
type finalCloser interface {
|
|
|
|
|
// finalClose is called when the reference count of an object
|
|
|
|
|
// goes to zero. (*DB).mu is not held while calling it.
|
|
|
|
|
finalClose() error
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// addDep notes that x now depends on dep, and x's finalClose won't be
|
|
|
|
|
// called until all of x's dependencies are removed with removeDep.
|
|
|
|
|
func (db *DB) addDep(x finalCloser, dep interface{}) {
|
|
|
|
|
db.mu.Lock()
|
|
|
|
|
defer db.mu.Unlock()
|
2013-03-25 16:50:27 -07:00
|
|
|
db.addDepLocked(x, dep)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (db *DB) addDepLocked(x finalCloser, dep interface{}) {
|
2013-02-20 15:35:27 -08:00
|
|
|
if db.dep == nil {
|
|
|
|
|
db.dep = make(map[finalCloser]depSet)
|
|
|
|
|
}
|
|
|
|
|
xdep := db.dep[x]
|
|
|
|
|
if xdep == nil {
|
|
|
|
|
xdep = make(depSet)
|
|
|
|
|
db.dep[x] = xdep
|
|
|
|
|
}
|
|
|
|
|
xdep[dep] = true
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// removeDep notes that x no longer depends on dep.
|
|
|
|
|
// If x still has dependencies, nil is returned.
|
|
|
|
|
// If x no longer has any dependencies, its finalClose method will be
|
|
|
|
|
// called and its error value will be returned.
|
|
|
|
|
func (db *DB) removeDep(x finalCloser, dep interface{}) error {
|
2013-03-25 16:50:27 -07:00
|
|
|
db.mu.Lock()
|
|
|
|
|
fn := db.removeDepLocked(x, dep)
|
|
|
|
|
db.mu.Unlock()
|
|
|
|
|
return fn()
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (db *DB) removeDepLocked(x finalCloser, dep interface{}) func() error {
|
2013-02-20 15:35:27 -08:00
|
|
|
|
2013-05-21 14:58:08 -07:00
|
|
|
xdep, ok := db.dep[x]
|
|
|
|
|
if !ok {
|
|
|
|
|
panic(fmt.Sprintf("unpaired removeDep: no deps for %T", x))
|
2013-02-20 15:35:27 -08:00
|
|
|
}
|
|
|
|
|
|
2013-05-21 14:58:08 -07:00
|
|
|
l0 := len(xdep)
|
|
|
|
|
delete(xdep, dep)
|
|
|
|
|
|
|
|
|
|
switch len(xdep) {
|
|
|
|
|
case l0:
|
|
|
|
|
// Nothing removed. Shouldn't happen.
|
|
|
|
|
panic(fmt.Sprintf("unpaired removeDep: no %T dep on %T", dep, x))
|
|
|
|
|
case 0:
|
|
|
|
|
// No more dependencies.
|
|
|
|
|
delete(db.dep, x)
|
|
|
|
|
return x.finalClose
|
|
|
|
|
default:
|
|
|
|
|
// Dependencies remain.
|
2013-03-25 16:50:27 -07:00
|
|
|
return func() error { return nil }
|
|
|
|
|
}
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
}
|
|
|
|
|
|
2015-09-14 00:18:22 +00:00
|
|
|
// This is the size of the connectionOpener request chan (DB.openerCh).
|
2013-08-30 09:27:33 -07:00
|
|
|
// This value should be larger than the maximum typical value
|
|
|
|
|
// used for db.maxOpen. If maxOpen is significantly larger than
|
|
|
|
|
// connectionRequestQueueSize then it is possible for ALL calls into the *DB
|
2014-04-29 12:44:40 -04:00
|
|
|
// to block until the connectionOpener can satisfy the backlog of requests.
|
2013-08-30 09:27:33 -07:00
|
|
|
var connectionRequestQueueSize = 1000000
|
|
|
|
|
|
2017-08-05 06:04:19 -04:00
|
|
|
type dsnConnector struct {
|
|
|
|
|
dsn string
|
|
|
|
|
driver driver.Driver
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (t dsnConnector) Connect(_ context.Context) (driver.Conn, error) {
|
|
|
|
|
return t.driver.Open(t.dsn)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (t dsnConnector) Driver() driver.Driver {
|
|
|
|
|
return t.driver
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// OpenDB opens a database using a Connector, allowing drivers to
|
|
|
|
|
// bypass a string based data source name.
|
|
|
|
|
//
|
|
|
|
|
// Most users will open a database via a driver-specific connection
|
|
|
|
|
// helper function that returns a *DB. No database drivers are included
|
|
|
|
|
// in the Go standard library. See https://golang.org/s/sqldrivers for
|
|
|
|
|
// a list of third-party drivers.
|
|
|
|
|
//
|
|
|
|
|
// OpenDB may just validate its arguments without creating a connection
|
|
|
|
|
// to the database. To verify that the data source name is valid, call
|
|
|
|
|
// Ping.
|
|
|
|
|
//
|
|
|
|
|
// The returned DB is safe for concurrent use by multiple goroutines
|
|
|
|
|
// and maintains its own pool of idle connections. Thus, the OpenDB
|
|
|
|
|
// function should be called just once. It is rarely necessary to
|
|
|
|
|
// close a DB.
|
|
|
|
|
func OpenDB(c driver.Connector) *DB {
|
2017-10-02 11:16:53 -07:00
|
|
|
ctx, cancel := context.WithCancel(context.Background())
|
2017-08-05 06:04:19 -04:00
|
|
|
db := &DB{
|
|
|
|
|
connector: c,
|
|
|
|
|
openerCh: make(chan struct{}, connectionRequestQueueSize),
|
|
|
|
|
lastPut: make(map[*driverConn]string),
|
|
|
|
|
connRequests: make(map[uint64]chan connRequest),
|
2017-10-02 11:16:53 -07:00
|
|
|
stop: cancel,
|
2017-08-05 06:04:19 -04:00
|
|
|
}
|
|
|
|
|
|
2017-10-02 11:16:53 -07:00
|
|
|
go db.connectionOpener(ctx)
|
2017-08-05 06:04:19 -04:00
|
|
|
|
|
|
|
|
return db
|
|
|
|
|
}
|
|
|
|
|
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
// Open opens a database specified by its database driver name and a
|
|
|
|
|
// driver-specific data source name, usually consisting of at least a
|
|
|
|
|
// database name and connection information.
|
|
|
|
|
//
|
|
|
|
|
// Most users will open a database via a driver-specific connection
|
2013-03-25 17:38:51 -07:00
|
|
|
// helper function that returns a *DB. No database drivers are included
|
2015-07-10 17:17:11 -06:00
|
|
|
// in the Go standard library. See https://golang.org/s/sqldrivers for
|
2013-03-25 17:38:51 -07:00
|
|
|
// a list of third-party drivers.
|
2013-03-14 14:06:46 -07:00
|
|
|
//
|
|
|
|
|
// Open may just validate its arguments without creating a connection
|
|
|
|
|
// to the database. To verify that the data source name is valid, call
|
|
|
|
|
// Ping.
|
2014-05-19 09:54:47 -07:00
|
|
|
//
|
|
|
|
|
// The returned DB is safe for concurrent use by multiple goroutines
|
|
|
|
|
// and maintains its own pool of idle connections. Thus, the Open
|
|
|
|
|
// function should be called just once. It is rarely necessary to
|
|
|
|
|
// close a DB.
|
2011-11-01 22:04:37 -04:00
|
|
|
func Open(driverName, dataSourceName string) (*DB, error) {
|
2015-10-22 21:50:06 -04:00
|
|
|
driversMu.RLock()
|
2013-02-20 15:35:27 -08:00
|
|
|
driveri, ok := drivers[driverName]
|
2015-10-22 21:50:06 -04:00
|
|
|
driversMu.RUnlock()
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
if !ok {
|
2011-12-15 10:14:57 -08:00
|
|
|
return nil, fmt.Errorf("sql: unknown driver %q (forgotten import?)", driverName)
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
}
|
2017-08-05 06:04:19 -04:00
|
|
|
|
2017-11-14 08:53:56 -08:00
|
|
|
if driverCtx, ok := driveri.(driver.DriverContext); ok {
|
|
|
|
|
connector, err := driverCtx.OpenConnector(dataSourceName)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
return OpenDB(connector), nil
|
|
|
|
|
}
|
|
|
|
|
|
2017-08-05 06:04:19 -04:00
|
|
|
return OpenDB(dsnConnector{dsn: dataSourceName, driver: driveri}), nil
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
}
|
|
|
|
|
|
database/sql: allow using a single connection from the database
Databases have the following concepts: Statement, Batch, and Session.
A statement is often a single line like:
SELECT Amount from Account where ID = 50;
A batch is one or more statements submitted together for the query
to process. It may be a DELETE, INSERT, two UPDATES and a SELECT in
a single query text.
A session is usually represented by a single database connection.
This often is an issue when dealing with scopes in databases.
Temporary tables and variables can have batch, session, or global
scope depending on the syntax, database, and use.
Furthermore, some databases (sybase and derivatives in perticular)
that prevent certain statements from being in the same batch
and may necessitate being in the same session.
By allowing users to extract a Conn from the database they can manage
session on their own without hacking around it by making connection
pools of single connections (a real workaround presented in issue).
It is tempting to just use a transaction, but this isn't always
desirable or an option if running an interactive session or
alter script set that itself starts transactions.
Fixes #18081
Change-Id: I9bdf0796632c48d4bcaef3624c629641984ffaf2
Reviewed-on: https://go-review.googlesource.com/40694
Reviewed-by: Brad Fitzpatrick <bradfitz@golang.org>
2017-04-13 16:04:40 -07:00
|
|
|
func (db *DB) pingDC(ctx context.Context, dc *driverConn, release func(error)) error {
|
|
|
|
|
var err error
|
|
|
|
|
if pinger, ok := dc.ci.(driver.Pinger); ok {
|
|
|
|
|
withLock(dc, func() {
|
|
|
|
|
err = pinger.Ping(ctx)
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
release(err)
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
|
2016-09-19 11:19:32 -07:00
|
|
|
// PingContext verifies a connection to the database is still alive,
|
2013-03-14 14:06:46 -07:00
|
|
|
// establishing a connection if necessary.
|
2016-09-19 11:19:32 -07:00
|
|
|
func (db *DB) PingContext(ctx context.Context) error {
|
2016-10-26 17:11:13 +09:00
|
|
|
var dc *driverConn
|
|
|
|
|
var err error
|
|
|
|
|
|
|
|
|
|
for i := 0; i < maxBadConnRetries; i++ {
|
|
|
|
|
dc, err = db.conn(ctx, cachedOrNewConn)
|
|
|
|
|
if err != driver.ErrBadConn {
|
|
|
|
|
break
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
if err == driver.ErrBadConn {
|
|
|
|
|
dc, err = db.conn(ctx, alwaysNewConn)
|
|
|
|
|
}
|
2013-03-14 14:06:46 -07:00
|
|
|
if err != nil {
|
|
|
|
|
return err
|
|
|
|
|
}
|
2016-10-26 17:11:13 +09:00
|
|
|
|
database/sql: allow using a single connection from the database
Databases have the following concepts: Statement, Batch, and Session.
A statement is often a single line like:
SELECT Amount from Account where ID = 50;
A batch is one or more statements submitted together for the query
to process. It may be a DELETE, INSERT, two UPDATES and a SELECT in
a single query text.
A session is usually represented by a single database connection.
This often is an issue when dealing with scopes in databases.
Temporary tables and variables can have batch, session, or global
scope depending on the syntax, database, and use.
Furthermore, some databases (sybase and derivatives in perticular)
that prevent certain statements from being in the same batch
and may necessitate being in the same session.
By allowing users to extract a Conn from the database they can manage
session on their own without hacking around it by making connection
pools of single connections (a real workaround presented in issue).
It is tempting to just use a transaction, but this isn't always
desirable or an option if running an interactive session or
alter script set that itself starts transactions.
Fixes #18081
Change-Id: I9bdf0796632c48d4bcaef3624c629641984ffaf2
Reviewed-on: https://go-review.googlesource.com/40694
Reviewed-by: Brad Fitzpatrick <bradfitz@golang.org>
2017-04-13 16:04:40 -07:00
|
|
|
return db.pingDC(ctx, dc, dc.releaseConn)
|
2013-03-14 14:06:46 -07:00
|
|
|
}
|
|
|
|
|
|
2016-09-19 11:19:32 -07:00
|
|
|
// Ping verifies a connection to the database is still alive,
|
|
|
|
|
// establishing a connection if necessary.
|
|
|
|
|
func (db *DB) Ping() error {
|
|
|
|
|
return db.PingContext(context.Background())
|
|
|
|
|
}
|
|
|
|
|
|
2018-03-29 10:01:27 -07:00
|
|
|
// Close closes the database and prevents new queries from starting.
|
|
|
|
|
// Close then waits for all queries that have started processing on the server
|
|
|
|
|
// to finish.
|
2014-05-19 09:54:47 -07:00
|
|
|
//
|
|
|
|
|
// It is rare to Close a DB, as the DB handle is meant to be
|
|
|
|
|
// long-lived and shared between many goroutines.
|
2011-11-14 10:48:26 -08:00
|
|
|
func (db *DB) Close() error {
|
|
|
|
|
db.mu.Lock()
|
2013-08-30 09:27:33 -07:00
|
|
|
if db.closed { // Make DB.Close idempotent
|
|
|
|
|
db.mu.Unlock()
|
|
|
|
|
return nil
|
|
|
|
|
}
|
2015-03-03 21:27:07 +09:00
|
|
|
if db.cleanerCh != nil {
|
|
|
|
|
close(db.cleanerCh)
|
|
|
|
|
}
|
2011-11-14 10:48:26 -08:00
|
|
|
var err error
|
2014-08-28 08:49:56 -07:00
|
|
|
fns := make([]func() error, 0, len(db.freeConn))
|
|
|
|
|
for _, dc := range db.freeConn {
|
2013-08-30 09:27:33 -07:00
|
|
|
fns = append(fns, dc.closeDBLocked())
|
|
|
|
|
}
|
2014-08-28 08:49:56 -07:00
|
|
|
db.freeConn = nil
|
2013-08-30 09:27:33 -07:00
|
|
|
db.closed = true
|
2014-08-28 08:49:56 -07:00
|
|
|
for _, req := range db.connRequests {
|
2013-08-30 09:27:33 -07:00
|
|
|
close(req)
|
|
|
|
|
}
|
|
|
|
|
db.mu.Unlock()
|
|
|
|
|
for _, fn := range fns {
|
|
|
|
|
err1 := fn()
|
2011-11-14 10:48:26 -08:00
|
|
|
if err1 != nil {
|
|
|
|
|
err = err1
|
|
|
|
|
}
|
|
|
|
|
}
|
2017-10-02 11:16:53 -07:00
|
|
|
db.stop()
|
2011-11-14 10:48:26 -08:00
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
|
2013-03-18 15:33:04 -07:00
|
|
|
const defaultMaxIdleConns = 2
|
|
|
|
|
|
|
|
|
|
func (db *DB) maxIdleConnsLocked() int {
|
2018-10-29 09:09:21 -07:00
|
|
|
n := db.maxIdleCount
|
2013-03-18 15:33:04 -07:00
|
|
|
switch {
|
|
|
|
|
case n == 0:
|
|
|
|
|
// TODO(bradfitz): ask driver, if supported, for its default preference
|
|
|
|
|
return defaultMaxIdleConns
|
|
|
|
|
case n < 0:
|
|
|
|
|
return 0
|
|
|
|
|
default:
|
|
|
|
|
return n
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2018-10-29 09:09:21 -07:00
|
|
|
func (db *DB) shortestIdleTimeLocked() time.Duration {
|
|
|
|
|
min := db.maxIdleTime
|
|
|
|
|
if min > db.maxLifetime {
|
|
|
|
|
min = db.maxLifetime
|
|
|
|
|
}
|
|
|
|
|
return min
|
|
|
|
|
}
|
|
|
|
|
|
2013-03-18 15:33:04 -07:00
|
|
|
// SetMaxIdleConns sets the maximum number of connections in the idle
|
|
|
|
|
// connection pool.
|
|
|
|
|
//
|
2018-05-01 16:33:27 +03:00
|
|
|
// If MaxOpenConns is greater than 0 but less than the new MaxIdleConns,
|
|
|
|
|
// then the new MaxIdleConns will be reduced to match the MaxOpenConns limit.
|
2013-08-30 09:27:33 -07:00
|
|
|
//
|
2013-03-18 15:33:04 -07:00
|
|
|
// If n <= 0, no idle connections are retained.
|
2018-04-20 14:22:18 -07:00
|
|
|
//
|
|
|
|
|
// The default max idle connections is currently 2. This may change in
|
|
|
|
|
// a future release.
|
2013-03-18 15:33:04 -07:00
|
|
|
func (db *DB) SetMaxIdleConns(n int) {
|
|
|
|
|
db.mu.Lock()
|
|
|
|
|
if n > 0 {
|
2018-10-29 09:09:21 -07:00
|
|
|
db.maxIdleCount = n
|
2013-03-18 15:33:04 -07:00
|
|
|
} else {
|
|
|
|
|
// No idle connections.
|
2018-10-29 09:09:21 -07:00
|
|
|
db.maxIdleCount = -1
|
2013-03-18 15:33:04 -07:00
|
|
|
}
|
2013-08-30 09:27:33 -07:00
|
|
|
// Make sure maxIdle doesn't exceed maxOpen
|
|
|
|
|
if db.maxOpen > 0 && db.maxIdleConnsLocked() > db.maxOpen {
|
2018-10-29 09:09:21 -07:00
|
|
|
db.maxIdleCount = db.maxOpen
|
2013-08-30 09:27:33 -07:00
|
|
|
}
|
2013-10-16 09:17:25 -07:00
|
|
|
var closing []*driverConn
|
2014-08-28 08:49:56 -07:00
|
|
|
idleCount := len(db.freeConn)
|
|
|
|
|
maxIdle := db.maxIdleConnsLocked()
|
|
|
|
|
if idleCount > maxIdle {
|
|
|
|
|
closing = db.freeConn[maxIdle:]
|
|
|
|
|
db.freeConn = db.freeConn[:maxIdle]
|
2013-10-16 09:17:25 -07:00
|
|
|
}
|
2018-04-20 14:22:18 -07:00
|
|
|
db.maxIdleClosed += int64(len(closing))
|
2013-10-16 09:17:25 -07:00
|
|
|
db.mu.Unlock()
|
|
|
|
|
for _, c := range closing {
|
|
|
|
|
c.Close()
|
2013-03-18 15:33:04 -07:00
|
|
|
}
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
}
|
|
|
|
|
|
2013-08-30 09:27:33 -07:00
|
|
|
// SetMaxOpenConns sets the maximum number of open connections to the database.
|
|
|
|
|
//
|
|
|
|
|
// If MaxIdleConns is greater than 0 and the new MaxOpenConns is less than
|
|
|
|
|
// MaxIdleConns, then MaxIdleConns will be reduced to match the new
|
2018-05-01 16:33:27 +03:00
|
|
|
// MaxOpenConns limit.
|
2013-08-30 09:27:33 -07:00
|
|
|
//
|
|
|
|
|
// If n <= 0, then there is no limit on the number of open connections.
|
|
|
|
|
// The default is 0 (unlimited).
|
|
|
|
|
func (db *DB) SetMaxOpenConns(n int) {
|
|
|
|
|
db.mu.Lock()
|
|
|
|
|
db.maxOpen = n
|
|
|
|
|
if n < 0 {
|
|
|
|
|
db.maxOpen = 0
|
|
|
|
|
}
|
|
|
|
|
syncMaxIdle := db.maxOpen > 0 && db.maxIdleConnsLocked() > db.maxOpen
|
|
|
|
|
db.mu.Unlock()
|
|
|
|
|
if syncMaxIdle {
|
|
|
|
|
db.SetMaxIdleConns(n)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2015-03-03 21:27:07 +09:00
|
|
|
// SetConnMaxLifetime sets the maximum amount of time a connection may be reused.
|
|
|
|
|
//
|
|
|
|
|
// Expired connections may be closed lazily before reuse.
|
|
|
|
|
//
|
2018-10-29 09:09:21 -07:00
|
|
|
// If d <= 0, connections are not closed due to a connection's age.
|
2015-03-03 21:27:07 +09:00
|
|
|
func (db *DB) SetConnMaxLifetime(d time.Duration) {
|
|
|
|
|
if d < 0 {
|
|
|
|
|
d = 0
|
|
|
|
|
}
|
|
|
|
|
db.mu.Lock()
|
2018-10-29 09:09:21 -07:00
|
|
|
// Wake cleaner up when lifetime is shortened.
|
2015-03-03 21:27:07 +09:00
|
|
|
if d > 0 && d < db.maxLifetime && db.cleanerCh != nil {
|
|
|
|
|
select {
|
|
|
|
|
case db.cleanerCh <- struct{}{}:
|
|
|
|
|
default:
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
db.maxLifetime = d
|
|
|
|
|
db.startCleanerLocked()
|
|
|
|
|
db.mu.Unlock()
|
|
|
|
|
}
|
|
|
|
|
|
2018-10-29 09:09:21 -07:00
|
|
|
// SetConnMaxIdleTime sets the maximum amount of time a connection may be idle.
|
|
|
|
|
//
|
|
|
|
|
// Expired connections may be closed lazily before reuse.
|
|
|
|
|
//
|
|
|
|
|
// If d <= 0, connections are not closed due to a connection's idle time.
|
|
|
|
|
func (db *DB) SetConnMaxIdleTime(d time.Duration) {
|
|
|
|
|
if d < 0 {
|
|
|
|
|
d = 0
|
|
|
|
|
}
|
|
|
|
|
db.mu.Lock()
|
|
|
|
|
defer db.mu.Unlock()
|
|
|
|
|
|
|
|
|
|
// Wake cleaner up when idle time is shortened.
|
|
|
|
|
if d > 0 && d < db.maxIdleTime && db.cleanerCh != nil {
|
|
|
|
|
select {
|
|
|
|
|
case db.cleanerCh <- struct{}{}:
|
|
|
|
|
default:
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
db.maxIdleTime = d
|
|
|
|
|
db.startCleanerLocked()
|
|
|
|
|
}
|
|
|
|
|
|
2015-03-03 21:27:07 +09:00
|
|
|
// startCleanerLocked starts connectionCleaner if needed.
|
|
|
|
|
func (db *DB) startCleanerLocked() {
|
2018-10-29 09:09:21 -07:00
|
|
|
if (db.maxLifetime > 0 || db.maxIdleTime > 0) && db.numOpen > 0 && db.cleanerCh == nil {
|
2015-03-03 21:27:07 +09:00
|
|
|
db.cleanerCh = make(chan struct{}, 1)
|
2018-10-29 09:09:21 -07:00
|
|
|
go db.connectionCleaner(db.shortestIdleTimeLocked())
|
2015-03-03 21:27:07 +09:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (db *DB) connectionCleaner(d time.Duration) {
|
|
|
|
|
const minInterval = time.Second
|
|
|
|
|
|
|
|
|
|
if d < minInterval {
|
|
|
|
|
d = minInterval
|
|
|
|
|
}
|
|
|
|
|
t := time.NewTimer(d)
|
|
|
|
|
|
|
|
|
|
for {
|
|
|
|
|
select {
|
|
|
|
|
case <-t.C:
|
|
|
|
|
case <-db.cleanerCh: // maxLifetime was changed or db was closed.
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
db.mu.Lock()
|
2018-10-29 09:09:21 -07:00
|
|
|
|
|
|
|
|
d = db.shortestIdleTimeLocked()
|
2015-03-03 21:27:07 +09:00
|
|
|
if db.closed || db.numOpen == 0 || d <= 0 {
|
|
|
|
|
db.cleanerCh = nil
|
|
|
|
|
db.mu.Unlock()
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
2018-10-29 09:09:21 -07:00
|
|
|
closing := db.connectionCleanerRunLocked()
|
|
|
|
|
db.mu.Unlock()
|
|
|
|
|
for _, c := range closing {
|
|
|
|
|
c.Close()
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if d < minInterval {
|
|
|
|
|
d = minInterval
|
|
|
|
|
}
|
|
|
|
|
t.Reset(d)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (db *DB) connectionCleanerRunLocked() (closing []*driverConn) {
|
|
|
|
|
if db.maxLifetime > 0 {
|
|
|
|
|
expiredSince := nowFunc().Add(-db.maxLifetime)
|
2015-03-03 21:27:07 +09:00
|
|
|
for i := 0; i < len(db.freeConn); i++ {
|
|
|
|
|
c := db.freeConn[i]
|
|
|
|
|
if c.createdAt.Before(expiredSince) {
|
|
|
|
|
closing = append(closing, c)
|
|
|
|
|
last := len(db.freeConn) - 1
|
|
|
|
|
db.freeConn[i] = db.freeConn[last]
|
|
|
|
|
db.freeConn[last] = nil
|
|
|
|
|
db.freeConn = db.freeConn[:last]
|
|
|
|
|
i--
|
|
|
|
|
}
|
|
|
|
|
}
|
2018-04-20 14:22:18 -07:00
|
|
|
db.maxLifetimeClosed += int64(len(closing))
|
2018-10-29 09:09:21 -07:00
|
|
|
}
|
2015-03-03 21:27:07 +09:00
|
|
|
|
2018-10-29 09:09:21 -07:00
|
|
|
if db.maxIdleTime > 0 {
|
|
|
|
|
expiredSince := nowFunc().Add(-db.maxIdleTime)
|
|
|
|
|
var expiredCount int64
|
|
|
|
|
for i := 0; i < len(db.freeConn); i++ {
|
|
|
|
|
c := db.freeConn[i]
|
|
|
|
|
if db.maxIdleTime > 0 && c.returnedAt.Before(expiredSince) {
|
|
|
|
|
closing = append(closing, c)
|
|
|
|
|
expiredCount++
|
|
|
|
|
last := len(db.freeConn) - 1
|
|
|
|
|
db.freeConn[i] = db.freeConn[last]
|
|
|
|
|
db.freeConn[last] = nil
|
|
|
|
|
db.freeConn = db.freeConn[:last]
|
|
|
|
|
i--
|
|
|
|
|
}
|
2015-03-03 21:27:07 +09:00
|
|
|
}
|
2018-10-29 09:09:21 -07:00
|
|
|
db.maxIdleTimeClosed += expiredCount
|
2015-03-03 21:27:07 +09:00
|
|
|
}
|
2018-10-29 09:09:21 -07:00
|
|
|
return
|
2015-03-03 21:27:07 +09:00
|
|
|
}
|
|
|
|
|
|
2015-03-23 18:23:53 +03:00
|
|
|
// DBStats contains database statistics.
|
|
|
|
|
type DBStats struct {
|
2018-04-20 14:22:18 -07:00
|
|
|
MaxOpenConnections int // Maximum number of open connections to the database.
|
|
|
|
|
|
|
|
|
|
// Pool Status
|
|
|
|
|
OpenConnections int // The number of established connections both in use and idle.
|
|
|
|
|
InUse int // The number of connections currently in use.
|
|
|
|
|
Idle int // The number of idle connections.
|
|
|
|
|
|
|
|
|
|
// Counters
|
|
|
|
|
WaitCount int64 // The total number of connections waited for.
|
|
|
|
|
WaitDuration time.Duration // The total time blocked waiting for a new connection.
|
|
|
|
|
MaxIdleClosed int64 // The total number of connections closed due to SetMaxIdleConns.
|
2018-10-29 09:09:21 -07:00
|
|
|
MaxIdleTimeClosed int64 // The total number of connections closed due to SetConnMaxIdleTime.
|
2018-04-20 14:22:18 -07:00
|
|
|
MaxLifetimeClosed int64 // The total number of connections closed due to SetConnMaxLifetime.
|
2015-03-23 18:23:53 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Stats returns database statistics.
|
|
|
|
|
func (db *DB) Stats() DBStats {
|
2018-04-20 14:22:18 -07:00
|
|
|
wait := atomic.LoadInt64(&db.waitDuration)
|
|
|
|
|
|
2015-03-23 18:23:53 +03:00
|
|
|
db.mu.Lock()
|
2018-04-20 14:22:18 -07:00
|
|
|
defer db.mu.Unlock()
|
|
|
|
|
|
2015-03-23 18:23:53 +03:00
|
|
|
stats := DBStats{
|
2018-04-20 14:22:18 -07:00
|
|
|
MaxOpenConnections: db.maxOpen,
|
|
|
|
|
|
|
|
|
|
Idle: len(db.freeConn),
|
2015-03-23 18:23:53 +03:00
|
|
|
OpenConnections: db.numOpen,
|
2018-04-20 14:22:18 -07:00
|
|
|
InUse: db.numOpen - len(db.freeConn),
|
|
|
|
|
|
|
|
|
|
WaitCount: db.waitCount,
|
|
|
|
|
WaitDuration: time.Duration(wait),
|
|
|
|
|
MaxIdleClosed: db.maxIdleClosed,
|
2018-10-29 09:09:21 -07:00
|
|
|
MaxIdleTimeClosed: db.maxIdleTimeClosed,
|
2018-04-20 14:22:18 -07:00
|
|
|
MaxLifetimeClosed: db.maxLifetimeClosed,
|
2015-03-23 18:23:53 +03:00
|
|
|
}
|
|
|
|
|
return stats
|
|
|
|
|
}
|
|
|
|
|
|
2013-08-30 09:27:33 -07:00
|
|
|
// Assumes db.mu is locked.
|
|
|
|
|
// If there are connRequests and the connection limit hasn't been reached,
|
|
|
|
|
// then tell the connectionOpener to open new connections.
|
|
|
|
|
func (db *DB) maybeOpenNewConnections() {
|
2015-09-14 03:44:56 -04:00
|
|
|
numRequests := len(db.connRequests)
|
2013-08-30 09:27:33 -07:00
|
|
|
if db.maxOpen > 0 {
|
2015-09-14 03:44:56 -04:00
|
|
|
numCanOpen := db.maxOpen - db.numOpen
|
2013-08-30 09:27:33 -07:00
|
|
|
if numRequests > numCanOpen {
|
|
|
|
|
numRequests = numCanOpen
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
for numRequests > 0 {
|
2015-09-14 03:44:56 -04:00
|
|
|
db.numOpen++ // optimistically
|
2013-08-30 09:27:33 -07:00
|
|
|
numRequests--
|
2016-06-28 12:06:08 -07:00
|
|
|
if db.closed {
|
|
|
|
|
return
|
|
|
|
|
}
|
2013-08-30 09:27:33 -07:00
|
|
|
db.openerCh <- struct{}{}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2013-12-27 08:59:02 -08:00
|
|
|
// Runs in a separate goroutine, opens new connections when requested.
|
2017-10-02 11:16:53 -07:00
|
|
|
func (db *DB) connectionOpener(ctx context.Context) {
|
|
|
|
|
for {
|
|
|
|
|
select {
|
|
|
|
|
case <-ctx.Done():
|
|
|
|
|
return
|
|
|
|
|
case <-db.openerCh:
|
|
|
|
|
db.openNewConnection(ctx)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2013-08-30 09:27:33 -07:00
|
|
|
// Open one new connection
|
2017-10-02 11:16:53 -07:00
|
|
|
func (db *DB) openNewConnection(ctx context.Context) {
|
2015-09-14 03:44:56 -04:00
|
|
|
// maybeOpenNewConnctions has already executed db.numOpen++ before it sent
|
|
|
|
|
// on db.openerCh. This function must execute db.numOpen-- if the
|
|
|
|
|
// connection fails or is closed before returning.
|
2017-10-02 11:16:53 -07:00
|
|
|
ci, err := db.connector.Connect(ctx)
|
2013-08-30 09:27:33 -07:00
|
|
|
db.mu.Lock()
|
|
|
|
|
defer db.mu.Unlock()
|
|
|
|
|
if db.closed {
|
|
|
|
|
if err == nil {
|
|
|
|
|
ci.Close()
|
|
|
|
|
}
|
2015-09-14 03:44:56 -04:00
|
|
|
db.numOpen--
|
2013-08-30 09:27:33 -07:00
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
if err != nil {
|
2015-09-14 03:44:56 -04:00
|
|
|
db.numOpen--
|
2013-08-30 09:27:33 -07:00
|
|
|
db.putConnDBLocked(nil, err)
|
2015-09-14 03:44:56 -04:00
|
|
|
db.maybeOpenNewConnections()
|
2013-08-30 09:27:33 -07:00
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
dc := &driverConn{
|
2018-10-29 09:09:21 -07:00
|
|
|
db: db,
|
|
|
|
|
createdAt: nowFunc(),
|
|
|
|
|
returnedAt: nowFunc(),
|
|
|
|
|
ci: ci,
|
2013-08-30 09:27:33 -07:00
|
|
|
}
|
2013-10-16 09:22:57 -07:00
|
|
|
if db.putConnDBLocked(dc, err) {
|
|
|
|
|
db.addDepLocked(dc, dc)
|
|
|
|
|
} else {
|
2015-09-14 03:44:56 -04:00
|
|
|
db.numOpen--
|
2013-10-16 09:22:57 -07:00
|
|
|
ci.Close()
|
|
|
|
|
}
|
2013-08-30 09:27:33 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// connRequest represents one request for a new connection
|
|
|
|
|
// When there are no idle connections available, DB.conn will create
|
|
|
|
|
// a new connRequest and put it on the db.connRequests list.
|
2014-08-28 08:49:56 -07:00
|
|
|
type connRequest struct {
|
|
|
|
|
conn *driverConn
|
|
|
|
|
err error
|
|
|
|
|
}
|
2013-08-30 09:27:33 -07:00
|
|
|
|
|
|
|
|
var errDBClosed = errors.New("sql: database is closed")
|
|
|
|
|
|
2017-02-08 10:32:22 -08:00
|
|
|
// nextRequestKeyLocked returns the next connection request key.
|
|
|
|
|
// It is assumed that nextRequest will not overflow.
|
|
|
|
|
func (db *DB) nextRequestKeyLocked() uint64 {
|
|
|
|
|
next := db.nextRequest
|
|
|
|
|
db.nextRequest++
|
|
|
|
|
return next
|
|
|
|
|
}
|
|
|
|
|
|
2015-03-27 19:45:12 +01:00
|
|
|
// conn returns a newly-opened or cached *driverConn.
|
2016-09-19 11:19:32 -07:00
|
|
|
func (db *DB) conn(ctx context.Context, strategy connReuseStrategy) (*driverConn, error) {
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
db.mu.Lock()
|
2011-11-14 10:48:26 -08:00
|
|
|
if db.closed {
|
2011-12-12 13:56:56 -08:00
|
|
|
db.mu.Unlock()
|
2013-08-30 09:27:33 -07:00
|
|
|
return nil, errDBClosed
|
|
|
|
|
}
|
2016-09-19 11:19:32 -07:00
|
|
|
// Check if the context is expired.
|
2016-10-28 10:10:46 -07:00
|
|
|
select {
|
|
|
|
|
default:
|
|
|
|
|
case <-ctx.Done():
|
2016-10-19 12:26:55 -07:00
|
|
|
db.mu.Unlock()
|
2016-10-28 10:10:46 -07:00
|
|
|
return nil, ctx.Err()
|
2016-09-19 11:19:32 -07:00
|
|
|
}
|
2015-03-03 21:27:07 +09:00
|
|
|
lifetime := db.maxLifetime
|
2013-08-30 09:27:33 -07:00
|
|
|
|
2015-03-27 19:45:12 +01:00
|
|
|
// Prefer a free connection, if possible.
|
|
|
|
|
numFree := len(db.freeConn)
|
|
|
|
|
if strategy == cachedOrNewConn && numFree > 0 {
|
|
|
|
|
conn := db.freeConn[0]
|
|
|
|
|
copy(db.freeConn, db.freeConn[1:])
|
|
|
|
|
db.freeConn = db.freeConn[:numFree-1]
|
|
|
|
|
conn.inUse = true
|
|
|
|
|
db.mu.Unlock()
|
2015-03-03 21:27:07 +09:00
|
|
|
if conn.expired(lifetime) {
|
|
|
|
|
conn.Close()
|
|
|
|
|
return nil, driver.ErrBadConn
|
|
|
|
|
}
|
2019-04-26 14:45:46 -07:00
|
|
|
|
|
|
|
|
// Reset the session if required.
|
|
|
|
|
if err := conn.resetSession(ctx); err == driver.ErrBadConn {
|
2017-10-02 11:16:53 -07:00
|
|
|
conn.Close()
|
|
|
|
|
return nil, driver.ErrBadConn
|
|
|
|
|
}
|
2019-04-26 14:45:46 -07:00
|
|
|
|
2015-03-27 19:45:12 +01:00
|
|
|
return conn, nil
|
|
|
|
|
}
|
|
|
|
|
|
2016-03-01 23:21:55 +00:00
|
|
|
// Out of free connections or we were asked not to use one. If we're not
|
2015-03-27 19:45:12 +01:00
|
|
|
// allowed to open any more connections, make a request and wait.
|
|
|
|
|
if db.maxOpen > 0 && db.numOpen >= db.maxOpen {
|
2013-08-30 09:27:33 -07:00
|
|
|
// Make the connRequest channel. It's buffered so that the
|
|
|
|
|
// connectionOpener doesn't block while waiting for the req to be read.
|
2014-08-28 11:07:29 -07:00
|
|
|
req := make(chan connRequest, 1)
|
2017-02-08 10:32:22 -08:00
|
|
|
reqKey := db.nextRequestKeyLocked()
|
|
|
|
|
db.connRequests[reqKey] = req
|
2018-04-20 14:22:18 -07:00
|
|
|
db.waitCount++
|
2013-08-30 09:27:33 -07:00
|
|
|
db.mu.Unlock()
|
2016-09-19 11:19:32 -07:00
|
|
|
|
2018-10-29 09:09:21 -07:00
|
|
|
waitStart := nowFunc()
|
2018-04-20 14:22:18 -07:00
|
|
|
|
2016-09-19 11:19:32 -07:00
|
|
|
// Timeout the connection request with the context.
|
|
|
|
|
select {
|
|
|
|
|
case <-ctx.Done():
|
2017-02-08 10:32:22 -08:00
|
|
|
// Remove the connection request and ensure no value has been sent
|
|
|
|
|
// on it after removing.
|
|
|
|
|
db.mu.Lock()
|
|
|
|
|
delete(db.connRequests, reqKey)
|
2017-02-08 21:38:51 -08:00
|
|
|
db.mu.Unlock()
|
2018-04-20 14:22:18 -07:00
|
|
|
|
|
|
|
|
atomic.AddInt64(&db.waitDuration, int64(time.Since(waitStart)))
|
|
|
|
|
|
2017-02-08 10:32:22 -08:00
|
|
|
select {
|
|
|
|
|
default:
|
|
|
|
|
case ret, ok := <-req:
|
2018-03-25 16:58:27 -07:00
|
|
|
if ok && ret.conn != nil {
|
2017-10-02 11:16:53 -07:00
|
|
|
db.putConn(ret.conn, ret.err, false)
|
2017-02-08 10:32:22 -08:00
|
|
|
}
|
|
|
|
|
}
|
2016-09-19 11:19:32 -07:00
|
|
|
return nil, ctx.Err()
|
|
|
|
|
case ret, ok := <-req:
|
2018-04-20 14:22:18 -07:00
|
|
|
atomic.AddInt64(&db.waitDuration, int64(time.Since(waitStart)))
|
|
|
|
|
|
2016-09-19 11:19:32 -07:00
|
|
|
if !ok {
|
|
|
|
|
return nil, errDBClosed
|
|
|
|
|
}
|
|
|
|
|
if ret.err == nil && ret.conn.expired(lifetime) {
|
|
|
|
|
ret.conn.Close()
|
|
|
|
|
return nil, driver.ErrBadConn
|
|
|
|
|
}
|
2017-10-02 11:16:53 -07:00
|
|
|
if ret.conn == nil {
|
|
|
|
|
return nil, ret.err
|
|
|
|
|
}
|
2019-04-26 14:45:46 -07:00
|
|
|
|
|
|
|
|
// Reset the session if required.
|
|
|
|
|
if err := ret.conn.resetSession(ctx); err == driver.ErrBadConn {
|
2017-10-02 11:16:53 -07:00
|
|
|
ret.conn.Close()
|
|
|
|
|
return nil, driver.ErrBadConn
|
|
|
|
|
}
|
2016-09-19 11:19:32 -07:00
|
|
|
return ret.conn, ret.err
|
2015-03-03 21:27:07 +09:00
|
|
|
}
|
2011-11-14 10:48:26 -08:00
|
|
|
}
|
2013-08-30 09:27:33 -07:00
|
|
|
|
2014-05-07 11:54:29 -07:00
|
|
|
db.numOpen++ // optimistically
|
2013-08-30 09:27:33 -07:00
|
|
|
db.mu.Unlock()
|
2017-08-05 06:04:19 -04:00
|
|
|
ci, err := db.connector.Connect(ctx)
|
2013-03-14 15:01:45 -07:00
|
|
|
if err != nil {
|
2014-05-07 11:54:29 -07:00
|
|
|
db.mu.Lock()
|
|
|
|
|
db.numOpen-- // correct for earlier optimism
|
2015-09-14 03:44:56 -04:00
|
|
|
db.maybeOpenNewConnections()
|
2014-05-07 11:54:29 -07:00
|
|
|
db.mu.Unlock()
|
2013-03-14 15:01:45 -07:00
|
|
|
return nil, err
|
2013-02-20 15:35:27 -08:00
|
|
|
}
|
2013-08-30 09:27:33 -07:00
|
|
|
db.mu.Lock()
|
2013-03-25 16:50:27 -07:00
|
|
|
dc := &driverConn{
|
2018-10-29 09:09:21 -07:00
|
|
|
db: db,
|
|
|
|
|
createdAt: nowFunc(),
|
|
|
|
|
returnedAt: nowFunc(),
|
|
|
|
|
ci: ci,
|
|
|
|
|
inUse: true,
|
2013-03-25 16:50:27 -07:00
|
|
|
}
|
|
|
|
|
db.addDepLocked(dc, dc)
|
2013-03-14 15:01:45 -07:00
|
|
|
db.mu.Unlock()
|
|
|
|
|
return dc, nil
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
}
|
|
|
|
|
|
2012-03-10 10:00:02 -08:00
|
|
|
// putConnHook is a hook for testing.
|
2013-03-14 15:01:45 -07:00
|
|
|
var putConnHook func(*DB, *driverConn)
|
2012-03-10 10:00:02 -08:00
|
|
|
|
2016-11-17 09:33:31 -08:00
|
|
|
// noteUnusedDriverStatement notes that ds is no longer used and should
|
2013-02-20 15:35:27 -08:00
|
|
|
// be closed whenever possible (when c is next not in use), unless c is
|
|
|
|
|
// already closed.
|
2016-11-17 09:33:31 -08:00
|
|
|
func (db *DB) noteUnusedDriverStatement(c *driverConn, ds *driverStmt) {
|
2013-02-20 15:35:27 -08:00
|
|
|
db.mu.Lock()
|
|
|
|
|
defer db.mu.Unlock()
|
2013-04-03 11:13:40 -07:00
|
|
|
if c.inUse {
|
|
|
|
|
c.onPut = append(c.onPut, func() {
|
2016-11-17 09:33:31 -08:00
|
|
|
ds.Close()
|
2013-02-20 15:35:27 -08:00
|
|
|
})
|
|
|
|
|
} else {
|
database/sql: fix driver Conn refcounting with prepared statements
The refcounting of driver Conns was completedly busted and
would leak (be held open forever) with any reasonable
load. This was a significant regression from Go 1.0.
The core of this patch is removing one line:
s.db.addDep(dc, s)
A database conn (dc) is a resource that be re-created any time
(but cached for speed) should not be held open forever with a
dependency refcount just because the Stmt (s) is alive (which
typically last for long periods of time, like forever).
The meat of the patch is new tests. In fixing the real issue,
a lot of tests then failed due to the fakedb_test.go's paranoia
about closing a fakeConn while it has open fakeStmts on it. I
could've ignored that, but that's been a problem in the past for
other bugs.
Instead, I now track per-Conn open statements and close them
when the the conn closes. The proper way to do this would've
been making *driverStmt a finalCloser and using the dep mechanism,
but it was much more invasive. Added a TODO instead.
I'd like to give a way for drivers to opt-out of caring about
driver.Stmt closes before a driver.Conn close, but that's a TODO
for the future, and that TODO is added in this CL.
I know this is very late for Go 1.1, but database/sql is
currently nearly useless without this.
I'd like to believe all these database/sql bugs in the past
release cycle are the result of increased usage, number of
drivers, and good feedback from increasingly-capable Go
developers, and not the result of me sucking. It's also hard
with all the real drivers being out-of-tree, so I'm having to
add more and more hooks to fakedb_test.go to simulate things
which real drivers end up doing.
Fixes #5323
R=golang-dev, snaury, gwenn.kahz, google, r
CC=golang-dev
https://golang.org/cl/8836045
2013-04-25 14:45:56 -07:00
|
|
|
c.Lock()
|
2016-11-17 09:33:31 -08:00
|
|
|
fc := c.finalClosed
|
|
|
|
|
c.Unlock()
|
|
|
|
|
if !fc {
|
|
|
|
|
ds.Close()
|
database/sql: fix driver Conn refcounting with prepared statements
The refcounting of driver Conns was completedly busted and
would leak (be held open forever) with any reasonable
load. This was a significant regression from Go 1.0.
The core of this patch is removing one line:
s.db.addDep(dc, s)
A database conn (dc) is a resource that be re-created any time
(but cached for speed) should not be held open forever with a
dependency refcount just because the Stmt (s) is alive (which
typically last for long periods of time, like forever).
The meat of the patch is new tests. In fixing the real issue,
a lot of tests then failed due to the fakedb_test.go's paranoia
about closing a fakeConn while it has open fakeStmts on it. I
could've ignored that, but that's been a problem in the past for
other bugs.
Instead, I now track per-Conn open statements and close them
when the the conn closes. The proper way to do this would've
been making *driverStmt a finalCloser and using the dep mechanism,
but it was much more invasive. Added a TODO instead.
I'd like to give a way for drivers to opt-out of caring about
driver.Stmt closes before a driver.Conn close, but that's a TODO
for the future, and that TODO is added in this CL.
I know this is very late for Go 1.1, but database/sql is
currently nearly useless without this.
I'd like to believe all these database/sql bugs in the past
release cycle are the result of increased usage, number of
drivers, and good feedback from increasingly-capable Go
developers, and not the result of me sucking. It's also hard
with all the real drivers being out-of-tree, so I'm having to
add more and more hooks to fakedb_test.go to simulate things
which real drivers end up doing.
Fixes #5323
R=golang-dev, snaury, gwenn.kahz, google, r
CC=golang-dev
https://golang.org/cl/8836045
2013-04-25 14:45:56 -07:00
|
|
|
}
|
2013-02-20 15:35:27 -08:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// debugGetPut determines whether getConn & putConn calls' stack traces
|
|
|
|
|
// are returned for more verbose crashes.
|
|
|
|
|
const debugGetPut = false
|
|
|
|
|
|
2012-03-08 10:09:52 -08:00
|
|
|
// putConn adds a connection to the db's free pool.
|
2012-12-19 03:04:09 +08:00
|
|
|
// err is optionally the last error that occurred on this connection.
|
2017-10-02 11:16:53 -07:00
|
|
|
func (db *DB) putConn(dc *driverConn, err error, resetSession bool) {
|
2019-04-26 14:45:46 -07:00
|
|
|
if err != driver.ErrBadConn {
|
|
|
|
|
if !dc.validateConnection(resetSession) {
|
|
|
|
|
err = driver.ErrBadConn
|
|
|
|
|
}
|
|
|
|
|
}
|
2013-02-20 15:35:27 -08:00
|
|
|
db.mu.Lock()
|
2013-04-03 11:13:40 -07:00
|
|
|
if !dc.inUse {
|
2013-02-20 15:35:27 -08:00
|
|
|
if debugGetPut {
|
2013-03-14 15:01:45 -07:00
|
|
|
fmt.Printf("putConn(%v) DUPLICATE was: %s\n\nPREVIOUS was: %s", dc, stack(), db.lastPut[dc])
|
2013-02-20 15:35:27 -08:00
|
|
|
}
|
|
|
|
|
panic("sql: connection returned that was never out")
|
|
|
|
|
}
|
|
|
|
|
if debugGetPut {
|
2013-03-14 15:01:45 -07:00
|
|
|
db.lastPut[dc] = stack()
|
2013-02-20 15:35:27 -08:00
|
|
|
}
|
2013-04-03 11:13:40 -07:00
|
|
|
dc.inUse = false
|
2018-10-29 09:09:21 -07:00
|
|
|
dc.returnedAt = nowFunc()
|
2013-02-20 15:35:27 -08:00
|
|
|
|
2013-04-03 11:13:40 -07:00
|
|
|
for _, fn := range dc.onPut {
|
|
|
|
|
fn()
|
2013-02-20 15:35:27 -08:00
|
|
|
}
|
2013-04-03 11:13:40 -07:00
|
|
|
dc.onPut = nil
|
2013-02-20 15:35:27 -08:00
|
|
|
|
2012-03-08 10:09:52 -08:00
|
|
|
if err == driver.ErrBadConn {
|
|
|
|
|
// Don't reuse bad connections.
|
2013-08-30 09:27:33 -07:00
|
|
|
// Since the conn is considered bad and is being discarded, treat it
|
2013-10-16 09:17:25 -07:00
|
|
|
// as closed. Don't decrement the open count here, finalClose will
|
|
|
|
|
// take care of that.
|
2013-08-30 09:27:33 -07:00
|
|
|
db.maybeOpenNewConnections()
|
2013-02-20 15:35:27 -08:00
|
|
|
db.mu.Unlock()
|
2013-08-14 09:27:30 -07:00
|
|
|
dc.Close()
|
2012-03-08 10:09:52 -08:00
|
|
|
return
|
|
|
|
|
}
|
2012-03-10 10:00:02 -08:00
|
|
|
if putConnHook != nil {
|
2013-03-14 15:01:45 -07:00
|
|
|
putConnHook(db, dc)
|
2012-03-10 10:00:02 -08:00
|
|
|
}
|
2013-08-30 09:27:33 -07:00
|
|
|
added := db.putConnDBLocked(dc, nil)
|
2013-08-29 17:26:00 -07:00
|
|
|
db.mu.Unlock()
|
2013-03-14 15:01:45 -07:00
|
|
|
|
2013-08-30 09:27:33 -07:00
|
|
|
if !added {
|
|
|
|
|
dc.Close()
|
2017-10-02 11:16:53 -07:00
|
|
|
return
|
|
|
|
|
}
|
2013-08-30 09:27:33 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Satisfy a connRequest or put the driverConn in the idle pool and return true
|
|
|
|
|
// or return false.
|
|
|
|
|
// putConnDBLocked will satisfy a connRequest if there is one, or it will
|
2013-12-17 14:53:31 -08:00
|
|
|
// return the *driverConn to the freeConn list if err == nil and the idle
|
|
|
|
|
// connection limit will not be exceeded.
|
2013-08-30 09:27:33 -07:00
|
|
|
// If err != nil, the value of dc is ignored.
|
|
|
|
|
// If err == nil, then dc must not equal nil.
|
2014-04-29 12:44:40 -04:00
|
|
|
// If a connRequest was fulfilled or the *driverConn was placed in the
|
2013-08-30 09:27:33 -07:00
|
|
|
// freeConn list, then true is returned, otherwise false is returned.
|
|
|
|
|
func (db *DB) putConnDBLocked(dc *driverConn, err error) bool {
|
2016-06-28 12:06:08 -07:00
|
|
|
if db.closed {
|
|
|
|
|
return false
|
|
|
|
|
}
|
2014-12-30 16:12:50 +08:00
|
|
|
if db.maxOpen > 0 && db.numOpen > db.maxOpen {
|
|
|
|
|
return false
|
|
|
|
|
}
|
2014-08-28 08:49:56 -07:00
|
|
|
if c := len(db.connRequests); c > 0 {
|
2017-02-08 10:32:22 -08:00
|
|
|
var req chan connRequest
|
|
|
|
|
var reqKey uint64
|
|
|
|
|
for reqKey, req = range db.connRequests {
|
|
|
|
|
break
|
|
|
|
|
}
|
|
|
|
|
delete(db.connRequests, reqKey) // Remove from pending requests.
|
2014-08-28 08:49:56 -07:00
|
|
|
if err == nil {
|
2013-08-30 09:27:33 -07:00
|
|
|
dc.inUse = true
|
2014-08-28 08:49:56 -07:00
|
|
|
}
|
2014-08-28 11:07:29 -07:00
|
|
|
req <- connRequest{
|
2014-08-28 08:49:56 -07:00
|
|
|
conn: dc,
|
|
|
|
|
err: err,
|
2013-08-30 09:27:33 -07:00
|
|
|
}
|
|
|
|
|
return true
|
2018-09-29 22:10:43 -07:00
|
|
|
} else if err == nil && !db.closed {
|
|
|
|
|
if db.maxIdleConnsLocked() > len(db.freeConn) {
|
|
|
|
|
db.freeConn = append(db.freeConn, dc)
|
|
|
|
|
db.startCleanerLocked()
|
|
|
|
|
return true
|
|
|
|
|
}
|
2018-04-20 14:22:18 -07:00
|
|
|
db.maxIdleClosed++
|
2013-08-30 09:27:33 -07:00
|
|
|
}
|
|
|
|
|
return false
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
}
|
|
|
|
|
|
2013-12-17 11:57:30 -08:00
|
|
|
// maxBadConnRetries is the number of maximum retries if the driver returns
|
2015-03-27 19:45:12 +01:00
|
|
|
// driver.ErrBadConn to signal a broken connection before forcing a new
|
|
|
|
|
// connection to be opened.
|
|
|
|
|
const maxBadConnRetries = 2
|
2013-12-17 11:57:30 -08:00
|
|
|
|
2016-09-19 11:19:32 -07:00
|
|
|
// PrepareContext creates a prepared statement for later queries or executions.
|
2013-02-20 22:15:36 -08:00
|
|
|
// Multiple queries or executions may be run concurrently from the
|
|
|
|
|
// returned statement.
|
2015-07-14 16:28:28 -04:00
|
|
|
// The caller must call the statement's Close method
|
|
|
|
|
// when the statement is no longer needed.
|
2016-09-28 12:51:39 -07:00
|
|
|
//
|
2016-09-27 13:27:02 -07:00
|
|
|
// The provided context is used for the preparation of the statement, not for the
|
|
|
|
|
// execution of the statement.
|
2016-09-19 11:19:32 -07:00
|
|
|
func (db *DB) PrepareContext(ctx context.Context, query string) (*Stmt, error) {
|
2012-03-08 10:09:52 -08:00
|
|
|
var stmt *Stmt
|
|
|
|
|
var err error
|
2013-12-17 11:57:30 -08:00
|
|
|
for i := 0; i < maxBadConnRetries; i++ {
|
2016-09-19 11:19:32 -07:00
|
|
|
stmt, err = db.prepare(ctx, query, cachedOrNewConn)
|
2012-03-08 10:09:52 -08:00
|
|
|
if err != driver.ErrBadConn {
|
|
|
|
|
break
|
|
|
|
|
}
|
|
|
|
|
}
|
2015-03-27 19:45:12 +01:00
|
|
|
if err == driver.ErrBadConn {
|
2016-09-19 11:19:32 -07:00
|
|
|
return db.prepare(ctx, query, alwaysNewConn)
|
2015-03-27 19:45:12 +01:00
|
|
|
}
|
2012-03-08 10:09:52 -08:00
|
|
|
return stmt, err
|
|
|
|
|
}
|
|
|
|
|
|
2016-09-19 11:19:32 -07:00
|
|
|
// Prepare creates a prepared statement for later queries or executions.
|
|
|
|
|
// Multiple queries or executions may be run concurrently from the
|
|
|
|
|
// returned statement.
|
|
|
|
|
// The caller must call the statement's Close method
|
|
|
|
|
// when the statement is no longer needed.
|
|
|
|
|
func (db *DB) Prepare(query string) (*Stmt, error) {
|
|
|
|
|
return db.PrepareContext(context.Background(), query)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (db *DB) prepare(ctx context.Context, query string, strategy connReuseStrategy) (*Stmt, error) {
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
// TODO: check if db.driver supports an optional
|
|
|
|
|
// driver.Preparer interface and call that instead, if so,
|
|
|
|
|
// otherwise we make a prepared statement that's bound
|
|
|
|
|
// to a connection, and to execute this prepared statement
|
|
|
|
|
// we either need to use this connection (if it's free), else
|
|
|
|
|
// get a new connection + re-prepare + execute on that one.
|
2016-09-19 11:19:32 -07:00
|
|
|
dc, err := db.conn(ctx, strategy)
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
2017-06-12 10:46:15 -07:00
|
|
|
return db.prepareDC(ctx, dc, dc.releaseConn, nil, query)
|
2017-04-04 17:03:10 -07:00
|
|
|
}
|
|
|
|
|
|
2017-06-12 10:46:15 -07:00
|
|
|
// prepareDC prepares a query on the driverConn and calls release before
|
|
|
|
|
// returning. When cg == nil it implies that a connection pool is used, and
|
|
|
|
|
// when cg != nil only a single driver connection is used.
|
|
|
|
|
func (db *DB) prepareDC(ctx context.Context, dc *driverConn, release func(error), cg stmtConnGrabber, query string) (*Stmt, error) {
|
2016-11-17 09:33:31 -08:00
|
|
|
var ds *driverStmt
|
2017-04-04 17:03:10 -07:00
|
|
|
var err error
|
|
|
|
|
defer func() {
|
|
|
|
|
release(err)
|
|
|
|
|
}()
|
2016-05-31 06:58:33 -07:00
|
|
|
withLock(dc, func() {
|
2017-06-12 10:46:15 -07:00
|
|
|
ds, err = dc.prepareLocked(ctx, cg, query)
|
2016-05-31 06:58:33 -07:00
|
|
|
})
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
2013-02-20 15:35:27 -08:00
|
|
|
stmt := &Stmt{
|
2017-06-12 10:46:15 -07:00
|
|
|
db: db,
|
|
|
|
|
query: query,
|
|
|
|
|
cg: cg,
|
|
|
|
|
cgds: ds,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// When cg == nil this statement will need to keep track of various
|
|
|
|
|
// connections they are prepared on and record the stmt dependency on
|
|
|
|
|
// the DB.
|
|
|
|
|
if cg == nil {
|
|
|
|
|
stmt.css = []connStmt{{dc, ds}}
|
|
|
|
|
stmt.lastNumClosed = atomic.LoadUint64(&db.numClosed)
|
|
|
|
|
db.addDep(stmt, stmt)
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
}
|
|
|
|
|
return stmt, nil
|
|
|
|
|
}
|
|
|
|
|
|
2016-09-19 11:19:32 -07:00
|
|
|
// ExecContext executes a query without returning any rows.
|
2013-02-13 15:25:39 -08:00
|
|
|
// The args are for any placeholder parameters in the query.
|
2016-09-19 11:19:32 -07:00
|
|
|
func (db *DB) ExecContext(ctx context.Context, query string, args ...interface{}) (Result, error) {
|
2012-03-08 10:09:52 -08:00
|
|
|
var res Result
|
2012-05-29 11:09:09 -07:00
|
|
|
var err error
|
2013-12-17 11:57:30 -08:00
|
|
|
for i := 0; i < maxBadConnRetries; i++ {
|
2016-09-19 11:19:32 -07:00
|
|
|
res, err = db.exec(ctx, query, args, cachedOrNewConn)
|
2012-03-08 10:09:52 -08:00
|
|
|
if err != driver.ErrBadConn {
|
|
|
|
|
break
|
|
|
|
|
}
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
}
|
2015-03-27 19:45:12 +01:00
|
|
|
if err == driver.ErrBadConn {
|
2016-09-19 11:19:32 -07:00
|
|
|
return db.exec(ctx, query, args, alwaysNewConn)
|
2015-03-27 19:45:12 +01:00
|
|
|
}
|
2012-03-08 10:09:52 -08:00
|
|
|
return res, err
|
|
|
|
|
}
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
|
2016-09-19 11:19:32 -07:00
|
|
|
// Exec executes a query without returning any rows.
|
|
|
|
|
// The args are for any placeholder parameters in the query.
|
|
|
|
|
func (db *DB) Exec(query string, args ...interface{}) (Result, error) {
|
|
|
|
|
return db.ExecContext(context.Background(), query, args...)
|
|
|
|
|
}
|
|
|
|
|
|
2017-04-04 17:03:10 -07:00
|
|
|
func (db *DB) exec(ctx context.Context, query string, args []interface{}, strategy connReuseStrategy) (Result, error) {
|
2016-09-19 11:19:32 -07:00
|
|
|
dc, err := db.conn(ctx, strategy)
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
2017-04-04 17:03:10 -07:00
|
|
|
return db.execDC(ctx, dc, dc.releaseConn, query, args)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (db *DB) execDC(ctx context.Context, dc *driverConn, release func(error), query string, args []interface{}) (res Result, err error) {
|
2012-08-23 19:29:47 -07:00
|
|
|
defer func() {
|
2017-04-04 17:03:10 -07:00
|
|
|
release(err)
|
2012-08-23 19:29:47 -07:00
|
|
|
}()
|
2017-09-23 19:38:32 -07:00
|
|
|
execerCtx, ok := dc.ci.(driver.ExecerContext)
|
|
|
|
|
var execer driver.Execer
|
|
|
|
|
if !ok {
|
|
|
|
|
execer, ok = dc.ci.(driver.Execer)
|
|
|
|
|
}
|
|
|
|
|
if ok {
|
|
|
|
|
var nvdargs []driver.NamedValue
|
2016-05-31 06:58:33 -07:00
|
|
|
var resi driver.Result
|
|
|
|
|
withLock(dc, func() {
|
2017-10-17 15:59:56 -07:00
|
|
|
nvdargs, err = driverArgsConnLocked(dc.ci, nil, args)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return
|
|
|
|
|
}
|
2017-09-23 19:38:32 -07:00
|
|
|
resi, err = ctxDriverExec(ctx, execerCtx, execer, query, nvdargs)
|
2016-05-31 06:58:33 -07:00
|
|
|
})
|
2011-11-14 10:48:26 -08:00
|
|
|
if err != driver.ErrSkip {
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
2013-03-14 15:01:45 -07:00
|
|
|
return driverResult{dc, resi}, nil
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2016-05-31 06:58:33 -07:00
|
|
|
var si driver.Stmt
|
|
|
|
|
withLock(dc, func() {
|
2016-09-19 11:19:32 -07:00
|
|
|
si, err = ctxDriverPrepare(ctx, dc.ci, query)
|
2016-05-31 06:58:33 -07:00
|
|
|
})
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
2016-11-17 09:33:31 -08:00
|
|
|
ds := &driverStmt{Locker: dc, si: si}
|
|
|
|
|
defer ds.Close()
|
2017-03-23 13:17:59 -07:00
|
|
|
return resultFromStatement(ctx, dc.ci, ds, args...)
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
}
|
|
|
|
|
|
2016-09-19 11:19:32 -07:00
|
|
|
// QueryContext executes a query that returns rows, typically a SELECT.
|
2013-01-11 14:46:49 -08:00
|
|
|
// The args are for any placeholder parameters in the query.
|
2016-09-19 11:19:32 -07:00
|
|
|
func (db *DB) QueryContext(ctx context.Context, query string, args ...interface{}) (*Rows, error) {
|
2013-02-13 15:25:39 -08:00
|
|
|
var rows *Rows
|
|
|
|
|
var err error
|
2013-12-17 11:57:30 -08:00
|
|
|
for i := 0; i < maxBadConnRetries; i++ {
|
2016-09-19 11:19:32 -07:00
|
|
|
rows, err = db.query(ctx, query, args, cachedOrNewConn)
|
2013-02-13 15:25:39 -08:00
|
|
|
if err != driver.ErrBadConn {
|
|
|
|
|
break
|
|
|
|
|
}
|
|
|
|
|
}
|
2015-03-27 19:45:12 +01:00
|
|
|
if err == driver.ErrBadConn {
|
2016-09-19 11:19:32 -07:00
|
|
|
return db.query(ctx, query, args, alwaysNewConn)
|
2015-03-27 19:45:12 +01:00
|
|
|
}
|
2013-02-13 15:25:39 -08:00
|
|
|
return rows, err
|
|
|
|
|
}
|
|
|
|
|
|
2016-09-19 11:19:32 -07:00
|
|
|
// Query executes a query that returns rows, typically a SELECT.
|
|
|
|
|
// The args are for any placeholder parameters in the query.
|
|
|
|
|
func (db *DB) Query(query string, args ...interface{}) (*Rows, error) {
|
|
|
|
|
return db.QueryContext(context.Background(), query, args...)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (db *DB) query(ctx context.Context, query string, args []interface{}, strategy connReuseStrategy) (*Rows, error) {
|
2017-04-04 17:03:10 -07:00
|
|
|
dc, err := db.conn(ctx, strategy)
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
2013-02-13 15:25:39 -08:00
|
|
|
|
2017-06-05 09:04:05 -07:00
|
|
|
return db.queryDC(ctx, nil, dc, dc.releaseConn, query, args)
|
2013-02-13 15:25:39 -08:00
|
|
|
}
|
|
|
|
|
|
2017-04-04 17:03:10 -07:00
|
|
|
// queryDC executes a query on the given connection.
|
2013-02-13 15:25:39 -08:00
|
|
|
// The connection gets released by the releaseConn function.
|
2017-06-05 09:04:05 -07:00
|
|
|
// The ctx context is from a query method and the txctx context is from an
|
|
|
|
|
// optional transaction context.
|
|
|
|
|
func (db *DB) queryDC(ctx, txctx context.Context, dc *driverConn, releaseConn func(error), query string, args []interface{}) (*Rows, error) {
|
2017-09-23 19:38:32 -07:00
|
|
|
queryerCtx, ok := dc.ci.(driver.QueryerContext)
|
|
|
|
|
var queryer driver.Queryer
|
|
|
|
|
if !ok {
|
|
|
|
|
queryer, ok = dc.ci.(driver.Queryer)
|
|
|
|
|
}
|
|
|
|
|
if ok {
|
2017-10-17 15:59:56 -07:00
|
|
|
var nvdargs []driver.NamedValue
|
2016-05-31 06:58:33 -07:00
|
|
|
var rowsi driver.Rows
|
2017-10-17 15:59:56 -07:00
|
|
|
var err error
|
2016-05-31 06:58:33 -07:00
|
|
|
withLock(dc, func() {
|
2017-10-17 15:59:56 -07:00
|
|
|
nvdargs, err = driverArgsConnLocked(dc.ci, nil, args)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return
|
|
|
|
|
}
|
2017-09-23 19:38:32 -07:00
|
|
|
rowsi, err = ctxDriverQuery(ctx, queryerCtx, queryer, query, nvdargs)
|
2016-05-31 06:58:33 -07:00
|
|
|
})
|
2013-02-13 15:25:39 -08:00
|
|
|
if err != driver.ErrSkip {
|
|
|
|
|
if err != nil {
|
|
|
|
|
releaseConn(err)
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
2013-03-18 11:39:00 -07:00
|
|
|
// Note: ownership of dc passes to the *Rows, to be freed
|
2013-02-13 15:25:39 -08:00
|
|
|
// with releaseConn.
|
|
|
|
|
rows := &Rows{
|
2013-03-14 15:01:45 -07:00
|
|
|
dc: dc,
|
2013-02-13 15:25:39 -08:00
|
|
|
releaseConn: releaseConn,
|
|
|
|
|
rowsi: rowsi,
|
|
|
|
|
}
|
2017-06-05 09:04:05 -07:00
|
|
|
rows.initContextClose(ctx, txctx)
|
2013-02-13 15:25:39 -08:00
|
|
|
return rows, nil
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2016-05-31 06:58:33 -07:00
|
|
|
var si driver.Stmt
|
|
|
|
|
var err error
|
|
|
|
|
withLock(dc, func() {
|
2016-09-19 11:19:32 -07:00
|
|
|
si, err = ctxDriverPrepare(ctx, dc.ci, query)
|
2016-05-31 06:58:33 -07:00
|
|
|
})
|
2012-01-13 15:25:07 -08:00
|
|
|
if err != nil {
|
2013-02-13 15:25:39 -08:00
|
|
|
releaseConn(err)
|
2012-01-13 15:25:07 -08:00
|
|
|
return nil, err
|
|
|
|
|
}
|
2013-02-13 15:25:39 -08:00
|
|
|
|
2016-11-17 09:33:31 -08:00
|
|
|
ds := &driverStmt{Locker: dc, si: si}
|
2017-03-23 13:17:59 -07:00
|
|
|
rowsi, err := rowsiFromStatement(ctx, dc.ci, ds, args...)
|
2013-02-13 15:25:39 -08:00
|
|
|
if err != nil {
|
2016-11-17 09:33:31 -08:00
|
|
|
ds.Close()
|
2013-07-23 14:09:53 +10:00
|
|
|
releaseConn(err)
|
2013-02-13 15:25:39 -08:00
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Note: ownership of ci passes to the *Rows, to be freed
|
|
|
|
|
// with releaseConn.
|
|
|
|
|
rows := &Rows{
|
2013-03-14 15:01:45 -07:00
|
|
|
dc: dc,
|
2013-02-13 15:25:39 -08:00
|
|
|
releaseConn: releaseConn,
|
|
|
|
|
rowsi: rowsi,
|
2016-11-17 09:33:31 -08:00
|
|
|
closeStmt: ds,
|
2013-02-13 15:25:39 -08:00
|
|
|
}
|
2017-06-05 09:04:05 -07:00
|
|
|
rows.initContextClose(ctx, txctx)
|
2012-01-13 15:25:07 -08:00
|
|
|
return rows, nil
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
}
|
|
|
|
|
|
2016-09-19 11:19:32 -07:00
|
|
|
// QueryRowContext executes a query that is expected to return at most one row.
|
|
|
|
|
// QueryRowContext always returns a non-nil value. Errors are deferred until
|
|
|
|
|
// Row's Scan method is called.
|
2017-06-05 15:45:04 -07:00
|
|
|
// If the query selects no rows, the *Row's Scan will return ErrNoRows.
|
|
|
|
|
// Otherwise, the *Row's Scan scans the first selected row and discards
|
|
|
|
|
// the rest.
|
2016-09-19 11:19:32 -07:00
|
|
|
func (db *DB) QueryRowContext(ctx context.Context, query string, args ...interface{}) *Row {
|
|
|
|
|
rows, err := db.QueryContext(ctx, query, args...)
|
|
|
|
|
return &Row{rows: rows, err: err}
|
|
|
|
|
}
|
|
|
|
|
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
// QueryRow executes a query that is expected to return at most one row.
|
2015-12-30 13:23:11 +13:00
|
|
|
// QueryRow always returns a non-nil value. Errors are deferred until
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
// Row's Scan method is called.
|
2017-06-05 15:45:04 -07:00
|
|
|
// If the query selects no rows, the *Row's Scan will return ErrNoRows.
|
|
|
|
|
// Otherwise, the *Row's Scan scans the first selected row and discards
|
|
|
|
|
// the rest.
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
func (db *DB) QueryRow(query string, args ...interface{}) *Row {
|
2016-09-19 11:19:32 -07:00
|
|
|
return db.QueryRowContext(context.Background(), query, args...)
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
}
|
|
|
|
|
|
2016-12-13 07:55:12 -08:00
|
|
|
// BeginTx starts a transaction.
|
2016-10-16 23:11:55 -07:00
|
|
|
//
|
2016-10-28 10:10:46 -07:00
|
|
|
// The provided context is used until the transaction is committed or rolled back.
|
|
|
|
|
// If the context is canceled, the sql package will roll back
|
|
|
|
|
// the transaction. Tx.Commit will return an error if the context provided to
|
2016-12-13 07:55:12 -08:00
|
|
|
// BeginTx is canceled.
|
2016-10-28 10:10:46 -07:00
|
|
|
//
|
2016-12-13 07:55:12 -08:00
|
|
|
// The provided TxOptions is optional and may be nil if defaults should be used.
|
|
|
|
|
// If a non-default isolation level is used that the driver doesn't support,
|
|
|
|
|
// an error will be returned.
|
|
|
|
|
func (db *DB) BeginTx(ctx context.Context, opts *TxOptions) (*Tx, error) {
|
2012-03-08 10:09:52 -08:00
|
|
|
var tx *Tx
|
|
|
|
|
var err error
|
2013-12-17 11:57:30 -08:00
|
|
|
for i := 0; i < maxBadConnRetries; i++ {
|
2016-12-13 07:55:12 -08:00
|
|
|
tx, err = db.begin(ctx, opts, cachedOrNewConn)
|
2012-03-08 10:09:52 -08:00
|
|
|
if err != driver.ErrBadConn {
|
|
|
|
|
break
|
|
|
|
|
}
|
|
|
|
|
}
|
2015-03-27 19:45:12 +01:00
|
|
|
if err == driver.ErrBadConn {
|
2016-12-13 07:55:12 -08:00
|
|
|
return db.begin(ctx, opts, alwaysNewConn)
|
2015-03-27 19:45:12 +01:00
|
|
|
}
|
2012-03-08 10:09:52 -08:00
|
|
|
return tx, err
|
|
|
|
|
}
|
|
|
|
|
|
2016-09-19 11:19:32 -07:00
|
|
|
// Begin starts a transaction. The default isolation level is dependent on
|
|
|
|
|
// the driver.
|
|
|
|
|
func (db *DB) Begin() (*Tx, error) {
|
2016-12-13 07:55:12 -08:00
|
|
|
return db.BeginTx(context.Background(), nil)
|
2016-09-19 11:19:32 -07:00
|
|
|
}
|
|
|
|
|
|
2016-12-13 07:55:12 -08:00
|
|
|
func (db *DB) begin(ctx context.Context, opts *TxOptions, strategy connReuseStrategy) (tx *Tx, err error) {
|
2016-09-19 11:19:32 -07:00
|
|
|
dc, err := db.conn(ctx, strategy)
|
2011-11-02 11:46:04 -07:00
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
2017-04-04 17:03:10 -07:00
|
|
|
return db.beginDC(ctx, dc, dc.releaseConn, opts)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// beginDC starts a transaction. The provided dc must be valid and ready to use.
|
|
|
|
|
func (db *DB) beginDC(ctx context.Context, dc *driverConn, release func(error), opts *TxOptions) (tx *Tx, err error) {
|
2016-05-31 06:58:33 -07:00
|
|
|
var txi driver.Tx
|
|
|
|
|
withLock(dc, func() {
|
2016-12-13 07:55:12 -08:00
|
|
|
txi, err = ctxDriverBegin(ctx, opts, dc.ci)
|
2016-05-31 06:58:33 -07:00
|
|
|
})
|
2011-11-02 11:46:04 -07:00
|
|
|
if err != nil {
|
2017-04-04 17:03:10 -07:00
|
|
|
release(err)
|
2012-12-12 22:04:55 -08:00
|
|
|
return nil, err
|
2011-11-02 11:46:04 -07:00
|
|
|
}
|
2016-09-19 11:19:32 -07:00
|
|
|
|
|
|
|
|
// Schedule the transaction to rollback when the context is cancelled.
|
|
|
|
|
// The cancel function in Tx will be called after done is set to true.
|
|
|
|
|
ctx, cancel := context.WithCancel(ctx)
|
|
|
|
|
tx = &Tx{
|
2017-04-04 17:03:10 -07:00
|
|
|
db: db,
|
|
|
|
|
dc: dc,
|
|
|
|
|
releaseConn: release,
|
|
|
|
|
txi: txi,
|
|
|
|
|
cancel: cancel,
|
|
|
|
|
ctx: ctx,
|
2016-09-19 11:19:32 -07:00
|
|
|
}
|
2017-01-20 17:12:50 -08:00
|
|
|
go tx.awaitDone()
|
2016-09-19 11:19:32 -07:00
|
|
|
return tx, nil
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
}
|
|
|
|
|
|
2012-02-10 09:12:32 +11:00
|
|
|
// Driver returns the database's underlying driver.
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
func (db *DB) Driver() driver.Driver {
|
2017-08-05 06:04:19 -04:00
|
|
|
return db.connector.Driver()
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
}
|
|
|
|
|
|
database/sql: allow using a single connection from the database
Databases have the following concepts: Statement, Batch, and Session.
A statement is often a single line like:
SELECT Amount from Account where ID = 50;
A batch is one or more statements submitted together for the query
to process. It may be a DELETE, INSERT, two UPDATES and a SELECT in
a single query text.
A session is usually represented by a single database connection.
This often is an issue when dealing with scopes in databases.
Temporary tables and variables can have batch, session, or global
scope depending on the syntax, database, and use.
Furthermore, some databases (sybase and derivatives in perticular)
that prevent certain statements from being in the same batch
and may necessitate being in the same session.
By allowing users to extract a Conn from the database they can manage
session on their own without hacking around it by making connection
pools of single connections (a real workaround presented in issue).
It is tempting to just use a transaction, but this isn't always
desirable or an option if running an interactive session or
alter script set that itself starts transactions.
Fixes #18081
Change-Id: I9bdf0796632c48d4bcaef3624c629641984ffaf2
Reviewed-on: https://go-review.googlesource.com/40694
Reviewed-by: Brad Fitzpatrick <bradfitz@golang.org>
2017-04-13 16:04:40 -07:00
|
|
|
// ErrConnDone is returned by any operation that is performed on a connection
|
2017-09-23 17:04:51 -07:00
|
|
|
// that has already been returned to the connection pool.
|
2018-05-05 07:18:21 -07:00
|
|
|
var ErrConnDone = errors.New("sql: connection is already closed")
|
database/sql: allow using a single connection from the database
Databases have the following concepts: Statement, Batch, and Session.
A statement is often a single line like:
SELECT Amount from Account where ID = 50;
A batch is one or more statements submitted together for the query
to process. It may be a DELETE, INSERT, two UPDATES and a SELECT in
a single query text.
A session is usually represented by a single database connection.
This often is an issue when dealing with scopes in databases.
Temporary tables and variables can have batch, session, or global
scope depending on the syntax, database, and use.
Furthermore, some databases (sybase and derivatives in perticular)
that prevent certain statements from being in the same batch
and may necessitate being in the same session.
By allowing users to extract a Conn from the database they can manage
session on their own without hacking around it by making connection
pools of single connections (a real workaround presented in issue).
It is tempting to just use a transaction, but this isn't always
desirable or an option if running an interactive session or
alter script set that itself starts transactions.
Fixes #18081
Change-Id: I9bdf0796632c48d4bcaef3624c629641984ffaf2
Reviewed-on: https://go-review.googlesource.com/40694
Reviewed-by: Brad Fitzpatrick <bradfitz@golang.org>
2017-04-13 16:04:40 -07:00
|
|
|
|
|
|
|
|
// Conn returns a single connection by either opening a new connection
|
|
|
|
|
// or returning an existing connection from the connection pool. Conn will
|
|
|
|
|
// block until either a connection is returned or ctx is canceled.
|
|
|
|
|
// Queries run on the same Conn will be run in the same database session.
|
|
|
|
|
//
|
|
|
|
|
// Every Conn must be returned to the database pool after use by
|
|
|
|
|
// calling Conn.Close.
|
|
|
|
|
func (db *DB) Conn(ctx context.Context) (*Conn, error) {
|
|
|
|
|
var dc *driverConn
|
|
|
|
|
var err error
|
|
|
|
|
for i := 0; i < maxBadConnRetries; i++ {
|
|
|
|
|
dc, err = db.conn(ctx, cachedOrNewConn)
|
|
|
|
|
if err != driver.ErrBadConn {
|
|
|
|
|
break
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
if err == driver.ErrBadConn {
|
2019-01-11 14:20:41 -08:00
|
|
|
dc, err = db.conn(ctx, alwaysNewConn)
|
database/sql: allow using a single connection from the database
Databases have the following concepts: Statement, Batch, and Session.
A statement is often a single line like:
SELECT Amount from Account where ID = 50;
A batch is one or more statements submitted together for the query
to process. It may be a DELETE, INSERT, two UPDATES and a SELECT in
a single query text.
A session is usually represented by a single database connection.
This often is an issue when dealing with scopes in databases.
Temporary tables and variables can have batch, session, or global
scope depending on the syntax, database, and use.
Furthermore, some databases (sybase and derivatives in perticular)
that prevent certain statements from being in the same batch
and may necessitate being in the same session.
By allowing users to extract a Conn from the database they can manage
session on their own without hacking around it by making connection
pools of single connections (a real workaround presented in issue).
It is tempting to just use a transaction, but this isn't always
desirable or an option if running an interactive session or
alter script set that itself starts transactions.
Fixes #18081
Change-Id: I9bdf0796632c48d4bcaef3624c629641984ffaf2
Reviewed-on: https://go-review.googlesource.com/40694
Reviewed-by: Brad Fitzpatrick <bradfitz@golang.org>
2017-04-13 16:04:40 -07:00
|
|
|
}
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
conn := &Conn{
|
|
|
|
|
db: db,
|
|
|
|
|
dc: dc,
|
|
|
|
|
}
|
|
|
|
|
return conn, nil
|
|
|
|
|
}
|
|
|
|
|
|
2017-06-12 10:46:15 -07:00
|
|
|
type releaseConn func(error)
|
|
|
|
|
|
2017-09-23 17:04:51 -07:00
|
|
|
// Conn represents a single database connection rather than a pool of database
|
|
|
|
|
// connections. Prefer running queries from DB unless there is a specific
|
|
|
|
|
// need for a continuous single database connection.
|
database/sql: allow using a single connection from the database
Databases have the following concepts: Statement, Batch, and Session.
A statement is often a single line like:
SELECT Amount from Account where ID = 50;
A batch is one or more statements submitted together for the query
to process. It may be a DELETE, INSERT, two UPDATES and a SELECT in
a single query text.
A session is usually represented by a single database connection.
This often is an issue when dealing with scopes in databases.
Temporary tables and variables can have batch, session, or global
scope depending on the syntax, database, and use.
Furthermore, some databases (sybase and derivatives in perticular)
that prevent certain statements from being in the same batch
and may necessitate being in the same session.
By allowing users to extract a Conn from the database they can manage
session on their own without hacking around it by making connection
pools of single connections (a real workaround presented in issue).
It is tempting to just use a transaction, but this isn't always
desirable or an option if running an interactive session or
alter script set that itself starts transactions.
Fixes #18081
Change-Id: I9bdf0796632c48d4bcaef3624c629641984ffaf2
Reviewed-on: https://go-review.googlesource.com/40694
Reviewed-by: Brad Fitzpatrick <bradfitz@golang.org>
2017-04-13 16:04:40 -07:00
|
|
|
//
|
|
|
|
|
// A Conn must call Close to return the connection to the database pool
|
|
|
|
|
// and may do so concurrently with a running query.
|
|
|
|
|
//
|
|
|
|
|
// After a call to Close, all operations on the
|
|
|
|
|
// connection fail with ErrConnDone.
|
|
|
|
|
type Conn struct {
|
|
|
|
|
db *DB
|
|
|
|
|
|
|
|
|
|
// closemu prevents the connection from closing while there
|
|
|
|
|
// is an active query. It is held for read during queries
|
|
|
|
|
// and exclusively during close.
|
|
|
|
|
closemu sync.RWMutex
|
|
|
|
|
|
|
|
|
|
// dc is owned until close, at which point
|
|
|
|
|
// it's returned to the connection pool.
|
|
|
|
|
dc *driverConn
|
|
|
|
|
|
|
|
|
|
// done transitions from 0 to 1 exactly once, on close.
|
|
|
|
|
// Once done, all operations fail with ErrConnDone.
|
|
|
|
|
// Use atomic operations on value when checking value.
|
|
|
|
|
done int32
|
|
|
|
|
}
|
|
|
|
|
|
2019-04-26 14:09:07 -07:00
|
|
|
// grabConn takes a context to implement stmtConnGrabber
|
|
|
|
|
// but the context is not used.
|
2017-06-12 10:46:15 -07:00
|
|
|
func (c *Conn) grabConn(context.Context) (*driverConn, releaseConn, error) {
|
database/sql: allow using a single connection from the database
Databases have the following concepts: Statement, Batch, and Session.
A statement is often a single line like:
SELECT Amount from Account where ID = 50;
A batch is one or more statements submitted together for the query
to process. It may be a DELETE, INSERT, two UPDATES and a SELECT in
a single query text.
A session is usually represented by a single database connection.
This often is an issue when dealing with scopes in databases.
Temporary tables and variables can have batch, session, or global
scope depending on the syntax, database, and use.
Furthermore, some databases (sybase and derivatives in perticular)
that prevent certain statements from being in the same batch
and may necessitate being in the same session.
By allowing users to extract a Conn from the database they can manage
session on their own without hacking around it by making connection
pools of single connections (a real workaround presented in issue).
It is tempting to just use a transaction, but this isn't always
desirable or an option if running an interactive session or
alter script set that itself starts transactions.
Fixes #18081
Change-Id: I9bdf0796632c48d4bcaef3624c629641984ffaf2
Reviewed-on: https://go-review.googlesource.com/40694
Reviewed-by: Brad Fitzpatrick <bradfitz@golang.org>
2017-04-13 16:04:40 -07:00
|
|
|
if atomic.LoadInt32(&c.done) != 0 {
|
2017-06-12 10:46:15 -07:00
|
|
|
return nil, nil, ErrConnDone
|
database/sql: allow using a single connection from the database
Databases have the following concepts: Statement, Batch, and Session.
A statement is often a single line like:
SELECT Amount from Account where ID = 50;
A batch is one or more statements submitted together for the query
to process. It may be a DELETE, INSERT, two UPDATES and a SELECT in
a single query text.
A session is usually represented by a single database connection.
This often is an issue when dealing with scopes in databases.
Temporary tables and variables can have batch, session, or global
scope depending on the syntax, database, and use.
Furthermore, some databases (sybase and derivatives in perticular)
that prevent certain statements from being in the same batch
and may necessitate being in the same session.
By allowing users to extract a Conn from the database they can manage
session on their own without hacking around it by making connection
pools of single connections (a real workaround presented in issue).
It is tempting to just use a transaction, but this isn't always
desirable or an option if running an interactive session or
alter script set that itself starts transactions.
Fixes #18081
Change-Id: I9bdf0796632c48d4bcaef3624c629641984ffaf2
Reviewed-on: https://go-review.googlesource.com/40694
Reviewed-by: Brad Fitzpatrick <bradfitz@golang.org>
2017-04-13 16:04:40 -07:00
|
|
|
}
|
2017-06-12 10:46:15 -07:00
|
|
|
c.closemu.RLock()
|
|
|
|
|
return c.dc, c.closemuRUnlockCondReleaseConn, nil
|
database/sql: allow using a single connection from the database
Databases have the following concepts: Statement, Batch, and Session.
A statement is often a single line like:
SELECT Amount from Account where ID = 50;
A batch is one or more statements submitted together for the query
to process. It may be a DELETE, INSERT, two UPDATES and a SELECT in
a single query text.
A session is usually represented by a single database connection.
This often is an issue when dealing with scopes in databases.
Temporary tables and variables can have batch, session, or global
scope depending on the syntax, database, and use.
Furthermore, some databases (sybase and derivatives in perticular)
that prevent certain statements from being in the same batch
and may necessitate being in the same session.
By allowing users to extract a Conn from the database they can manage
session on their own without hacking around it by making connection
pools of single connections (a real workaround presented in issue).
It is tempting to just use a transaction, but this isn't always
desirable or an option if running an interactive session or
alter script set that itself starts transactions.
Fixes #18081
Change-Id: I9bdf0796632c48d4bcaef3624c629641984ffaf2
Reviewed-on: https://go-review.googlesource.com/40694
Reviewed-by: Brad Fitzpatrick <bradfitz@golang.org>
2017-04-13 16:04:40 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// PingContext verifies the connection to the database is still alive.
|
|
|
|
|
func (c *Conn) PingContext(ctx context.Context) error {
|
2017-06-12 10:46:15 -07:00
|
|
|
dc, release, err := c.grabConn(ctx)
|
database/sql: allow using a single connection from the database
Databases have the following concepts: Statement, Batch, and Session.
A statement is often a single line like:
SELECT Amount from Account where ID = 50;
A batch is one or more statements submitted together for the query
to process. It may be a DELETE, INSERT, two UPDATES and a SELECT in
a single query text.
A session is usually represented by a single database connection.
This often is an issue when dealing with scopes in databases.
Temporary tables and variables can have batch, session, or global
scope depending on the syntax, database, and use.
Furthermore, some databases (sybase and derivatives in perticular)
that prevent certain statements from being in the same batch
and may necessitate being in the same session.
By allowing users to extract a Conn from the database they can manage
session on their own without hacking around it by making connection
pools of single connections (a real workaround presented in issue).
It is tempting to just use a transaction, but this isn't always
desirable or an option if running an interactive session or
alter script set that itself starts transactions.
Fixes #18081
Change-Id: I9bdf0796632c48d4bcaef3624c629641984ffaf2
Reviewed-on: https://go-review.googlesource.com/40694
Reviewed-by: Brad Fitzpatrick <bradfitz@golang.org>
2017-04-13 16:04:40 -07:00
|
|
|
if err != nil {
|
|
|
|
|
return err
|
|
|
|
|
}
|
2017-06-12 10:46:15 -07:00
|
|
|
return c.db.pingDC(ctx, dc, release)
|
database/sql: allow using a single connection from the database
Databases have the following concepts: Statement, Batch, and Session.
A statement is often a single line like:
SELECT Amount from Account where ID = 50;
A batch is one or more statements submitted together for the query
to process. It may be a DELETE, INSERT, two UPDATES and a SELECT in
a single query text.
A session is usually represented by a single database connection.
This often is an issue when dealing with scopes in databases.
Temporary tables and variables can have batch, session, or global
scope depending on the syntax, database, and use.
Furthermore, some databases (sybase and derivatives in perticular)
that prevent certain statements from being in the same batch
and may necessitate being in the same session.
By allowing users to extract a Conn from the database they can manage
session on their own without hacking around it by making connection
pools of single connections (a real workaround presented in issue).
It is tempting to just use a transaction, but this isn't always
desirable or an option if running an interactive session or
alter script set that itself starts transactions.
Fixes #18081
Change-Id: I9bdf0796632c48d4bcaef3624c629641984ffaf2
Reviewed-on: https://go-review.googlesource.com/40694
Reviewed-by: Brad Fitzpatrick <bradfitz@golang.org>
2017-04-13 16:04:40 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// ExecContext executes a query without returning any rows.
|
|
|
|
|
// The args are for any placeholder parameters in the query.
|
|
|
|
|
func (c *Conn) ExecContext(ctx context.Context, query string, args ...interface{}) (Result, error) {
|
2017-06-12 10:46:15 -07:00
|
|
|
dc, release, err := c.grabConn(ctx)
|
database/sql: allow using a single connection from the database
Databases have the following concepts: Statement, Batch, and Session.
A statement is often a single line like:
SELECT Amount from Account where ID = 50;
A batch is one or more statements submitted together for the query
to process. It may be a DELETE, INSERT, two UPDATES and a SELECT in
a single query text.
A session is usually represented by a single database connection.
This often is an issue when dealing with scopes in databases.
Temporary tables and variables can have batch, session, or global
scope depending on the syntax, database, and use.
Furthermore, some databases (sybase and derivatives in perticular)
that prevent certain statements from being in the same batch
and may necessitate being in the same session.
By allowing users to extract a Conn from the database they can manage
session on their own without hacking around it by making connection
pools of single connections (a real workaround presented in issue).
It is tempting to just use a transaction, but this isn't always
desirable or an option if running an interactive session or
alter script set that itself starts transactions.
Fixes #18081
Change-Id: I9bdf0796632c48d4bcaef3624c629641984ffaf2
Reviewed-on: https://go-review.googlesource.com/40694
Reviewed-by: Brad Fitzpatrick <bradfitz@golang.org>
2017-04-13 16:04:40 -07:00
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
2017-06-12 10:46:15 -07:00
|
|
|
return c.db.execDC(ctx, dc, release, query, args)
|
database/sql: allow using a single connection from the database
Databases have the following concepts: Statement, Batch, and Session.
A statement is often a single line like:
SELECT Amount from Account where ID = 50;
A batch is one or more statements submitted together for the query
to process. It may be a DELETE, INSERT, two UPDATES and a SELECT in
a single query text.
A session is usually represented by a single database connection.
This often is an issue when dealing with scopes in databases.
Temporary tables and variables can have batch, session, or global
scope depending on the syntax, database, and use.
Furthermore, some databases (sybase and derivatives in perticular)
that prevent certain statements from being in the same batch
and may necessitate being in the same session.
By allowing users to extract a Conn from the database they can manage
session on their own without hacking around it by making connection
pools of single connections (a real workaround presented in issue).
It is tempting to just use a transaction, but this isn't always
desirable or an option if running an interactive session or
alter script set that itself starts transactions.
Fixes #18081
Change-Id: I9bdf0796632c48d4bcaef3624c629641984ffaf2
Reviewed-on: https://go-review.googlesource.com/40694
Reviewed-by: Brad Fitzpatrick <bradfitz@golang.org>
2017-04-13 16:04:40 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// QueryContext executes a query that returns rows, typically a SELECT.
|
|
|
|
|
// The args are for any placeholder parameters in the query.
|
|
|
|
|
func (c *Conn) QueryContext(ctx context.Context, query string, args ...interface{}) (*Rows, error) {
|
2017-06-12 10:46:15 -07:00
|
|
|
dc, release, err := c.grabConn(ctx)
|
database/sql: allow using a single connection from the database
Databases have the following concepts: Statement, Batch, and Session.
A statement is often a single line like:
SELECT Amount from Account where ID = 50;
A batch is one or more statements submitted together for the query
to process. It may be a DELETE, INSERT, two UPDATES and a SELECT in
a single query text.
A session is usually represented by a single database connection.
This often is an issue when dealing with scopes in databases.
Temporary tables and variables can have batch, session, or global
scope depending on the syntax, database, and use.
Furthermore, some databases (sybase and derivatives in perticular)
that prevent certain statements from being in the same batch
and may necessitate being in the same session.
By allowing users to extract a Conn from the database they can manage
session on their own without hacking around it by making connection
pools of single connections (a real workaround presented in issue).
It is tempting to just use a transaction, but this isn't always
desirable or an option if running an interactive session or
alter script set that itself starts transactions.
Fixes #18081
Change-Id: I9bdf0796632c48d4bcaef3624c629641984ffaf2
Reviewed-on: https://go-review.googlesource.com/40694
Reviewed-by: Brad Fitzpatrick <bradfitz@golang.org>
2017-04-13 16:04:40 -07:00
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
2017-06-12 10:46:15 -07:00
|
|
|
return c.db.queryDC(ctx, nil, dc, release, query, args)
|
database/sql: allow using a single connection from the database
Databases have the following concepts: Statement, Batch, and Session.
A statement is often a single line like:
SELECT Amount from Account where ID = 50;
A batch is one or more statements submitted together for the query
to process. It may be a DELETE, INSERT, two UPDATES and a SELECT in
a single query text.
A session is usually represented by a single database connection.
This often is an issue when dealing with scopes in databases.
Temporary tables and variables can have batch, session, or global
scope depending on the syntax, database, and use.
Furthermore, some databases (sybase and derivatives in perticular)
that prevent certain statements from being in the same batch
and may necessitate being in the same session.
By allowing users to extract a Conn from the database they can manage
session on their own without hacking around it by making connection
pools of single connections (a real workaround presented in issue).
It is tempting to just use a transaction, but this isn't always
desirable or an option if running an interactive session or
alter script set that itself starts transactions.
Fixes #18081
Change-Id: I9bdf0796632c48d4bcaef3624c629641984ffaf2
Reviewed-on: https://go-review.googlesource.com/40694
Reviewed-by: Brad Fitzpatrick <bradfitz@golang.org>
2017-04-13 16:04:40 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// QueryRowContext executes a query that is expected to return at most one row.
|
|
|
|
|
// QueryRowContext always returns a non-nil value. Errors are deferred until
|
|
|
|
|
// Row's Scan method is called.
|
2017-06-05 15:45:04 -07:00
|
|
|
// If the query selects no rows, the *Row's Scan will return ErrNoRows.
|
|
|
|
|
// Otherwise, the *Row's Scan scans the first selected row and discards
|
|
|
|
|
// the rest.
|
database/sql: allow using a single connection from the database
Databases have the following concepts: Statement, Batch, and Session.
A statement is often a single line like:
SELECT Amount from Account where ID = 50;
A batch is one or more statements submitted together for the query
to process. It may be a DELETE, INSERT, two UPDATES and a SELECT in
a single query text.
A session is usually represented by a single database connection.
This often is an issue when dealing with scopes in databases.
Temporary tables and variables can have batch, session, or global
scope depending on the syntax, database, and use.
Furthermore, some databases (sybase and derivatives in perticular)
that prevent certain statements from being in the same batch
and may necessitate being in the same session.
By allowing users to extract a Conn from the database they can manage
session on their own without hacking around it by making connection
pools of single connections (a real workaround presented in issue).
It is tempting to just use a transaction, but this isn't always
desirable or an option if running an interactive session or
alter script set that itself starts transactions.
Fixes #18081
Change-Id: I9bdf0796632c48d4bcaef3624c629641984ffaf2
Reviewed-on: https://go-review.googlesource.com/40694
Reviewed-by: Brad Fitzpatrick <bradfitz@golang.org>
2017-04-13 16:04:40 -07:00
|
|
|
func (c *Conn) QueryRowContext(ctx context.Context, query string, args ...interface{}) *Row {
|
|
|
|
|
rows, err := c.QueryContext(ctx, query, args...)
|
|
|
|
|
return &Row{rows: rows, err: err}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// PrepareContext creates a prepared statement for later queries or executions.
|
|
|
|
|
// Multiple queries or executions may be run concurrently from the
|
|
|
|
|
// returned statement.
|
|
|
|
|
// The caller must call the statement's Close method
|
|
|
|
|
// when the statement is no longer needed.
|
|
|
|
|
//
|
|
|
|
|
// The provided context is used for the preparation of the statement, not for the
|
|
|
|
|
// execution of the statement.
|
|
|
|
|
func (c *Conn) PrepareContext(ctx context.Context, query string) (*Stmt, error) {
|
2017-06-12 10:46:15 -07:00
|
|
|
dc, release, err := c.grabConn(ctx)
|
database/sql: allow using a single connection from the database
Databases have the following concepts: Statement, Batch, and Session.
A statement is often a single line like:
SELECT Amount from Account where ID = 50;
A batch is one or more statements submitted together for the query
to process. It may be a DELETE, INSERT, two UPDATES and a SELECT in
a single query text.
A session is usually represented by a single database connection.
This often is an issue when dealing with scopes in databases.
Temporary tables and variables can have batch, session, or global
scope depending on the syntax, database, and use.
Furthermore, some databases (sybase and derivatives in perticular)
that prevent certain statements from being in the same batch
and may necessitate being in the same session.
By allowing users to extract a Conn from the database they can manage
session on their own without hacking around it by making connection
pools of single connections (a real workaround presented in issue).
It is tempting to just use a transaction, but this isn't always
desirable or an option if running an interactive session or
alter script set that itself starts transactions.
Fixes #18081
Change-Id: I9bdf0796632c48d4bcaef3624c629641984ffaf2
Reviewed-on: https://go-review.googlesource.com/40694
Reviewed-by: Brad Fitzpatrick <bradfitz@golang.org>
2017-04-13 16:04:40 -07:00
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
2017-06-12 10:46:15 -07:00
|
|
|
return c.db.prepareDC(ctx, dc, release, c, query)
|
database/sql: allow using a single connection from the database
Databases have the following concepts: Statement, Batch, and Session.
A statement is often a single line like:
SELECT Amount from Account where ID = 50;
A batch is one or more statements submitted together for the query
to process. It may be a DELETE, INSERT, two UPDATES and a SELECT in
a single query text.
A session is usually represented by a single database connection.
This often is an issue when dealing with scopes in databases.
Temporary tables and variables can have batch, session, or global
scope depending on the syntax, database, and use.
Furthermore, some databases (sybase and derivatives in perticular)
that prevent certain statements from being in the same batch
and may necessitate being in the same session.
By allowing users to extract a Conn from the database they can manage
session on their own without hacking around it by making connection
pools of single connections (a real workaround presented in issue).
It is tempting to just use a transaction, but this isn't always
desirable or an option if running an interactive session or
alter script set that itself starts transactions.
Fixes #18081
Change-Id: I9bdf0796632c48d4bcaef3624c629641984ffaf2
Reviewed-on: https://go-review.googlesource.com/40694
Reviewed-by: Brad Fitzpatrick <bradfitz@golang.org>
2017-04-13 16:04:40 -07:00
|
|
|
}
|
|
|
|
|
|
2019-04-26 14:09:07 -07:00
|
|
|
// Raw executes f exposing the underlying driver connection for the
|
|
|
|
|
// duration of f. The driverConn must not be used outside of f.
|
|
|
|
|
//
|
|
|
|
|
// Once f returns and err is nil, the Conn will continue to be usable
|
|
|
|
|
// until Conn.Close is called.
|
|
|
|
|
func (c *Conn) Raw(f func(driverConn interface{}) error) (err error) {
|
|
|
|
|
var dc *driverConn
|
|
|
|
|
var release releaseConn
|
|
|
|
|
|
|
|
|
|
// grabConn takes a context to implement stmtConnGrabber, but the context is not used.
|
|
|
|
|
dc, release, err = c.grabConn(nil)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
fPanic := true
|
|
|
|
|
dc.Mutex.Lock()
|
|
|
|
|
defer func() {
|
|
|
|
|
dc.Mutex.Unlock()
|
|
|
|
|
|
|
|
|
|
// If f panics fPanic will remain true.
|
|
|
|
|
// Ensure an error is passed to release so the connection
|
|
|
|
|
// may be discarded.
|
|
|
|
|
if fPanic {
|
|
|
|
|
err = driver.ErrBadConn
|
|
|
|
|
}
|
|
|
|
|
release(err)
|
|
|
|
|
}()
|
|
|
|
|
err = f(dc.ci)
|
|
|
|
|
fPanic = false
|
|
|
|
|
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
database/sql: allow using a single connection from the database
Databases have the following concepts: Statement, Batch, and Session.
A statement is often a single line like:
SELECT Amount from Account where ID = 50;
A batch is one or more statements submitted together for the query
to process. It may be a DELETE, INSERT, two UPDATES and a SELECT in
a single query text.
A session is usually represented by a single database connection.
This often is an issue when dealing with scopes in databases.
Temporary tables and variables can have batch, session, or global
scope depending on the syntax, database, and use.
Furthermore, some databases (sybase and derivatives in perticular)
that prevent certain statements from being in the same batch
and may necessitate being in the same session.
By allowing users to extract a Conn from the database they can manage
session on their own without hacking around it by making connection
pools of single connections (a real workaround presented in issue).
It is tempting to just use a transaction, but this isn't always
desirable or an option if running an interactive session or
alter script set that itself starts transactions.
Fixes #18081
Change-Id: I9bdf0796632c48d4bcaef3624c629641984ffaf2
Reviewed-on: https://go-review.googlesource.com/40694
Reviewed-by: Brad Fitzpatrick <bradfitz@golang.org>
2017-04-13 16:04:40 -07:00
|
|
|
// BeginTx starts a transaction.
|
|
|
|
|
//
|
|
|
|
|
// The provided context is used until the transaction is committed or rolled back.
|
|
|
|
|
// If the context is canceled, the sql package will roll back
|
|
|
|
|
// the transaction. Tx.Commit will return an error if the context provided to
|
|
|
|
|
// BeginTx is canceled.
|
|
|
|
|
//
|
|
|
|
|
// The provided TxOptions is optional and may be nil if defaults should be used.
|
|
|
|
|
// If a non-default isolation level is used that the driver doesn't support,
|
|
|
|
|
// an error will be returned.
|
|
|
|
|
func (c *Conn) BeginTx(ctx context.Context, opts *TxOptions) (*Tx, error) {
|
2017-06-12 10:46:15 -07:00
|
|
|
dc, release, err := c.grabConn(ctx)
|
database/sql: allow using a single connection from the database
Databases have the following concepts: Statement, Batch, and Session.
A statement is often a single line like:
SELECT Amount from Account where ID = 50;
A batch is one or more statements submitted together for the query
to process. It may be a DELETE, INSERT, two UPDATES and a SELECT in
a single query text.
A session is usually represented by a single database connection.
This often is an issue when dealing with scopes in databases.
Temporary tables and variables can have batch, session, or global
scope depending on the syntax, database, and use.
Furthermore, some databases (sybase and derivatives in perticular)
that prevent certain statements from being in the same batch
and may necessitate being in the same session.
By allowing users to extract a Conn from the database they can manage
session on their own without hacking around it by making connection
pools of single connections (a real workaround presented in issue).
It is tempting to just use a transaction, but this isn't always
desirable or an option if running an interactive session or
alter script set that itself starts transactions.
Fixes #18081
Change-Id: I9bdf0796632c48d4bcaef3624c629641984ffaf2
Reviewed-on: https://go-review.googlesource.com/40694
Reviewed-by: Brad Fitzpatrick <bradfitz@golang.org>
2017-04-13 16:04:40 -07:00
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
2017-06-12 10:46:15 -07:00
|
|
|
return c.db.beginDC(ctx, dc, release, opts)
|
database/sql: allow using a single connection from the database
Databases have the following concepts: Statement, Batch, and Session.
A statement is often a single line like:
SELECT Amount from Account where ID = 50;
A batch is one or more statements submitted together for the query
to process. It may be a DELETE, INSERT, two UPDATES and a SELECT in
a single query text.
A session is usually represented by a single database connection.
This often is an issue when dealing with scopes in databases.
Temporary tables and variables can have batch, session, or global
scope depending on the syntax, database, and use.
Furthermore, some databases (sybase and derivatives in perticular)
that prevent certain statements from being in the same batch
and may necessitate being in the same session.
By allowing users to extract a Conn from the database they can manage
session on their own without hacking around it by making connection
pools of single connections (a real workaround presented in issue).
It is tempting to just use a transaction, but this isn't always
desirable or an option if running an interactive session or
alter script set that itself starts transactions.
Fixes #18081
Change-Id: I9bdf0796632c48d4bcaef3624c629641984ffaf2
Reviewed-on: https://go-review.googlesource.com/40694
Reviewed-by: Brad Fitzpatrick <bradfitz@golang.org>
2017-04-13 16:04:40 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// closemuRUnlockCondReleaseConn read unlocks closemu
|
|
|
|
|
// as the sql operation is done with the dc.
|
|
|
|
|
func (c *Conn) closemuRUnlockCondReleaseConn(err error) {
|
|
|
|
|
c.closemu.RUnlock()
|
|
|
|
|
if err == driver.ErrBadConn {
|
|
|
|
|
c.close(err)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2017-06-12 10:46:15 -07:00
|
|
|
func (c *Conn) txCtx() context.Context {
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
database/sql: allow using a single connection from the database
Databases have the following concepts: Statement, Batch, and Session.
A statement is often a single line like:
SELECT Amount from Account where ID = 50;
A batch is one or more statements submitted together for the query
to process. It may be a DELETE, INSERT, two UPDATES and a SELECT in
a single query text.
A session is usually represented by a single database connection.
This often is an issue when dealing with scopes in databases.
Temporary tables and variables can have batch, session, or global
scope depending on the syntax, database, and use.
Furthermore, some databases (sybase and derivatives in perticular)
that prevent certain statements from being in the same batch
and may necessitate being in the same session.
By allowing users to extract a Conn from the database they can manage
session on their own without hacking around it by making connection
pools of single connections (a real workaround presented in issue).
It is tempting to just use a transaction, but this isn't always
desirable or an option if running an interactive session or
alter script set that itself starts transactions.
Fixes #18081
Change-Id: I9bdf0796632c48d4bcaef3624c629641984ffaf2
Reviewed-on: https://go-review.googlesource.com/40694
Reviewed-by: Brad Fitzpatrick <bradfitz@golang.org>
2017-04-13 16:04:40 -07:00
|
|
|
func (c *Conn) close(err error) error {
|
|
|
|
|
if !atomic.CompareAndSwapInt32(&c.done, 0, 1) {
|
|
|
|
|
return ErrConnDone
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Lock around releasing the driver connection
|
|
|
|
|
// to ensure all queries have been stopped before doing so.
|
|
|
|
|
c.closemu.Lock()
|
|
|
|
|
defer c.closemu.Unlock()
|
|
|
|
|
|
|
|
|
|
c.dc.releaseConn(err)
|
|
|
|
|
c.dc = nil
|
|
|
|
|
c.db = nil
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Close returns the connection to the connection pool.
|
|
|
|
|
// All operations after a Close will return with ErrConnDone.
|
|
|
|
|
// Close is safe to call concurrently with other operations and will
|
|
|
|
|
// block until all other operations finish. It may be useful to first
|
|
|
|
|
// cancel any used context and then call close directly after.
|
|
|
|
|
func (c *Conn) Close() error {
|
|
|
|
|
return c.close(nil)
|
|
|
|
|
}
|
|
|
|
|
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
// Tx is an in-progress database transaction.
|
2011-11-02 11:46:04 -07:00
|
|
|
//
|
|
|
|
|
// A transaction must end with a call to Commit or Rollback.
|
|
|
|
|
//
|
|
|
|
|
// After a call to Commit or Rollback, all operations on the
|
2012-02-10 09:12:32 +11:00
|
|
|
// transaction fail with ErrTxDone.
|
2015-07-14 16:28:28 -04:00
|
|
|
//
|
|
|
|
|
// The statements prepared for a transaction by calling
|
|
|
|
|
// the transaction's Prepare or Stmt methods are closed
|
|
|
|
|
// by the call to Commit or Rollback.
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
type Tx struct {
|
2011-11-02 11:46:04 -07:00
|
|
|
db *DB
|
|
|
|
|
|
2017-01-20 17:12:50 -08:00
|
|
|
// closemu prevents the transaction from closing while there
|
|
|
|
|
// is an active query. It is held for read during queries
|
|
|
|
|
// and exclusively during close.
|
|
|
|
|
closemu sync.RWMutex
|
|
|
|
|
|
2013-03-14 15:01:45 -07:00
|
|
|
// dc is owned exclusively until Commit or Rollback, at which point
|
2011-11-02 11:46:04 -07:00
|
|
|
// it's returned with putConn.
|
2013-03-14 15:01:45 -07:00
|
|
|
dc *driverConn
|
2011-11-02 11:46:04 -07:00
|
|
|
txi driver.Tx
|
|
|
|
|
|
2017-04-04 17:03:10 -07:00
|
|
|
// releaseConn is called once the Tx is closed to release
|
|
|
|
|
// any held driverConn back to the pool.
|
|
|
|
|
releaseConn func(error)
|
|
|
|
|
|
2016-10-28 10:10:46 -07:00
|
|
|
// done transitions from 0 to 1 exactly once, on Commit
|
2011-11-02 11:46:04 -07:00
|
|
|
// or Rollback. once done, all operations fail with
|
2012-02-10 09:12:32 +11:00
|
|
|
// ErrTxDone.
|
2016-10-28 10:10:46 -07:00
|
|
|
// Use atomic operations on value when checking value.
|
|
|
|
|
done int32
|
2014-09-22 09:19:27 -04:00
|
|
|
|
2016-03-01 23:21:55 +00:00
|
|
|
// All Stmts prepared for this transaction. These will be closed after the
|
2014-09-22 09:19:27 -04:00
|
|
|
// transaction has been committed or rolled back.
|
|
|
|
|
stmts struct {
|
|
|
|
|
sync.Mutex
|
|
|
|
|
v []*Stmt
|
|
|
|
|
}
|
2016-09-19 11:19:32 -07:00
|
|
|
|
2017-04-04 17:03:10 -07:00
|
|
|
// cancel is called after done transitions from 0 to 1.
|
2016-09-19 11:19:32 -07:00
|
|
|
cancel func()
|
2016-10-28 10:10:46 -07:00
|
|
|
|
|
|
|
|
// ctx lives for the life of the transaction.
|
|
|
|
|
ctx context.Context
|
|
|
|
|
}
|
|
|
|
|
|
2017-01-20 17:12:50 -08:00
|
|
|
// awaitDone blocks until the context in Tx is canceled and rolls back
|
|
|
|
|
// the transaction if it's not already done.
|
|
|
|
|
func (tx *Tx) awaitDone() {
|
|
|
|
|
// Wait for either the transaction to be committed or rolled
|
|
|
|
|
// back, or for the associated context to be closed.
|
|
|
|
|
<-tx.ctx.Done()
|
|
|
|
|
|
|
|
|
|
// Discard and close the connection used to ensure the
|
|
|
|
|
// transaction is closed and the resources are released. This
|
|
|
|
|
// rollback does nothing if the transaction has already been
|
|
|
|
|
// committed or rolled back.
|
|
|
|
|
tx.rollback(true)
|
|
|
|
|
}
|
|
|
|
|
|
2016-10-28 10:10:46 -07:00
|
|
|
func (tx *Tx) isDone() bool {
|
|
|
|
|
return atomic.LoadInt32(&tx.done) != 0
|
2011-11-02 11:46:04 -07:00
|
|
|
}
|
|
|
|
|
|
2016-09-26 20:23:36 -05:00
|
|
|
// ErrTxDone is returned by any operation that is performed on a transaction
|
|
|
|
|
// that has already been committed or rolled back.
|
2018-05-05 07:18:21 -07:00
|
|
|
var ErrTxDone = errors.New("sql: transaction has already been committed or rolled back")
|
2011-11-02 11:46:04 -07:00
|
|
|
|
2016-12-26 11:33:46 -08:00
|
|
|
// close returns the connection to the pool and
|
|
|
|
|
// must only be called by Tx.rollback or Tx.Commit.
|
2015-08-24 21:48:39 -04:00
|
|
|
func (tx *Tx) close(err error) {
|
2017-06-05 09:04:05 -07:00
|
|
|
tx.cancel()
|
|
|
|
|
|
2017-01-20 17:12:50 -08:00
|
|
|
tx.closemu.Lock()
|
|
|
|
|
defer tx.closemu.Unlock()
|
|
|
|
|
|
2017-04-04 17:03:10 -07:00
|
|
|
tx.releaseConn(err)
|
2013-03-14 15:01:45 -07:00
|
|
|
tx.dc = nil
|
2011-11-02 11:46:04 -07:00
|
|
|
tx.txi = nil
|
|
|
|
|
}
|
|
|
|
|
|
2017-01-20 17:12:50 -08:00
|
|
|
// hookTxGrabConn specifies an optional hook to be called on
|
|
|
|
|
// a successful call to (*Tx).grabConn. For tests.
|
|
|
|
|
var hookTxGrabConn func()
|
|
|
|
|
|
2017-06-12 10:46:15 -07:00
|
|
|
func (tx *Tx) grabConn(ctx context.Context) (*driverConn, releaseConn, error) {
|
2017-01-20 17:12:50 -08:00
|
|
|
select {
|
|
|
|
|
default:
|
|
|
|
|
case <-ctx.Done():
|
2017-06-12 10:46:15 -07:00
|
|
|
return nil, nil, ctx.Err()
|
2017-01-20 17:12:50 -08:00
|
|
|
}
|
2017-06-12 10:46:15 -07:00
|
|
|
|
2019-09-08 19:36:13 +03:00
|
|
|
// closemu.RLock must come before the check for isDone to prevent the Tx from
|
2017-06-12 10:46:15 -07:00
|
|
|
// closing while a query is executing.
|
|
|
|
|
tx.closemu.RLock()
|
2016-10-28 10:10:46 -07:00
|
|
|
if tx.isDone() {
|
2017-06-12 10:46:15 -07:00
|
|
|
tx.closemu.RUnlock()
|
|
|
|
|
return nil, nil, ErrTxDone
|
2011-11-02 11:46:04 -07:00
|
|
|
}
|
2017-01-20 17:12:50 -08:00
|
|
|
if hookTxGrabConn != nil { // test hook
|
|
|
|
|
hookTxGrabConn()
|
|
|
|
|
}
|
2017-06-12 10:46:15 -07:00
|
|
|
return tx.dc, tx.closemuRUnlockRelease, nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (tx *Tx) txCtx() context.Context {
|
|
|
|
|
return tx.ctx
|
2011-11-02 11:46:04 -07:00
|
|
|
}
|
|
|
|
|
|
2017-04-07 12:21:50 -07:00
|
|
|
// closemuRUnlockRelease is used as a func(error) method value in
|
|
|
|
|
// ExecContext and QueryContext. Unlocking in the releaseConn keeps
|
|
|
|
|
// the driver conn from being returned to the connection pool until
|
|
|
|
|
// the Rows has been closed.
|
|
|
|
|
func (tx *Tx) closemuRUnlockRelease(error) {
|
|
|
|
|
tx.closemu.RUnlock()
|
|
|
|
|
}
|
|
|
|
|
|
2014-09-22 09:19:27 -04:00
|
|
|
// Closes all Stmts prepared for this transaction.
|
|
|
|
|
func (tx *Tx) closePrepared() {
|
|
|
|
|
tx.stmts.Lock()
|
2016-05-31 06:58:33 -07:00
|
|
|
defer tx.stmts.Unlock()
|
2014-09-22 09:19:27 -04:00
|
|
|
for _, stmt := range tx.stmts.v {
|
|
|
|
|
stmt.Close()
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
// Commit commits the transaction.
|
2011-11-01 22:04:37 -04:00
|
|
|
func (tx *Tx) Commit() error {
|
2017-12-04 10:53:53 +08:00
|
|
|
// Check context first to avoid transaction leak.
|
2018-03-07 10:20:19 +01:00
|
|
|
// If put it behind tx.done CompareAndSwap statement, we can't ensure
|
2017-12-04 10:53:53 +08:00
|
|
|
// the consistency between tx.done and the real COMMIT operation.
|
2016-10-28 10:10:46 -07:00
|
|
|
select {
|
|
|
|
|
default:
|
|
|
|
|
case <-tx.ctx.Done():
|
2017-12-04 10:53:53 +08:00
|
|
|
if atomic.LoadInt32(&tx.done) == 1 {
|
|
|
|
|
return ErrTxDone
|
|
|
|
|
}
|
2016-10-28 10:10:46 -07:00
|
|
|
return tx.ctx.Err()
|
|
|
|
|
}
|
2017-12-04 10:53:53 +08:00
|
|
|
if !atomic.CompareAndSwapInt32(&tx.done, 0, 1) {
|
|
|
|
|
return ErrTxDone
|
|
|
|
|
}
|
2016-05-31 06:58:33 -07:00
|
|
|
var err error
|
|
|
|
|
withLock(tx.dc, func() {
|
|
|
|
|
err = tx.txi.Commit()
|
|
|
|
|
})
|
2014-09-22 09:19:27 -04:00
|
|
|
if err != driver.ErrBadConn {
|
|
|
|
|
tx.closePrepared()
|
|
|
|
|
}
|
2015-08-24 21:48:39 -04:00
|
|
|
tx.close(err)
|
2014-09-22 09:19:27 -04:00
|
|
|
return err
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
}
|
|
|
|
|
|
2016-10-28 10:10:46 -07:00
|
|
|
// rollback aborts the transaction and optionally forces the pool to discard
|
|
|
|
|
// the connection.
|
|
|
|
|
func (tx *Tx) rollback(discardConn bool) error {
|
2016-12-26 11:33:46 -08:00
|
|
|
if !atomic.CompareAndSwapInt32(&tx.done, 0, 1) {
|
2012-02-10 09:12:32 +11:00
|
|
|
return ErrTxDone
|
2011-11-02 11:46:04 -07:00
|
|
|
}
|
2016-05-31 06:58:33 -07:00
|
|
|
var err error
|
|
|
|
|
withLock(tx.dc, func() {
|
|
|
|
|
err = tx.txi.Rollback()
|
|
|
|
|
})
|
2014-09-22 09:19:27 -04:00
|
|
|
if err != driver.ErrBadConn {
|
|
|
|
|
tx.closePrepared()
|
|
|
|
|
}
|
2016-10-28 10:10:46 -07:00
|
|
|
if discardConn {
|
|
|
|
|
err = driver.ErrBadConn
|
|
|
|
|
}
|
2015-08-24 21:48:39 -04:00
|
|
|
tx.close(err)
|
2014-09-22 09:19:27 -04:00
|
|
|
return err
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
}
|
|
|
|
|
|
2016-10-28 10:10:46 -07:00
|
|
|
// Rollback aborts the transaction.
|
|
|
|
|
func (tx *Tx) Rollback() error {
|
|
|
|
|
return tx.rollback(false)
|
|
|
|
|
}
|
|
|
|
|
|
2017-07-18 07:18:35 +03:00
|
|
|
// PrepareContext creates a prepared statement for use within a transaction.
|
2011-11-02 11:46:04 -07:00
|
|
|
//
|
2016-11-15 17:14:13 -08:00
|
|
|
// The returned statement operates within the transaction and will be closed
|
|
|
|
|
// when the transaction has been committed or rolled back.
|
2011-11-28 11:00:32 -05:00
|
|
|
//
|
|
|
|
|
// To use an existing prepared statement on this transaction, see Tx.Stmt.
|
2016-09-28 12:51:39 -07:00
|
|
|
//
|
|
|
|
|
// The provided context will be used for the preparation of the context, not
|
2016-09-19 11:19:32 -07:00
|
|
|
// for the execution of the returned statement. The returned statement
|
|
|
|
|
// will run in the transaction context.
|
|
|
|
|
func (tx *Tx) PrepareContext(ctx context.Context, query string) (*Stmt, error) {
|
2017-06-12 10:46:15 -07:00
|
|
|
dc, release, err := tx.grabConn(ctx)
|
2011-11-02 11:46:04 -07:00
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
|
2017-06-12 10:46:15 -07:00
|
|
|
stmt, err := tx.db.prepareDC(ctx, dc, release, tx, query)
|
2011-11-02 11:46:04 -07:00
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
2014-09-22 09:19:27 -04:00
|
|
|
tx.stmts.Lock()
|
|
|
|
|
tx.stmts.v = append(tx.stmts.v, stmt)
|
|
|
|
|
tx.stmts.Unlock()
|
2011-11-02 11:46:04 -07:00
|
|
|
return stmt, nil
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
}
|
|
|
|
|
|
2016-09-19 11:19:32 -07:00
|
|
|
// Prepare creates a prepared statement for use within a transaction.
|
|
|
|
|
//
|
|
|
|
|
// The returned statement operates within the transaction and can no longer
|
|
|
|
|
// be used once the transaction has been committed or rolled back.
|
|
|
|
|
//
|
|
|
|
|
// To use an existing prepared statement on this transaction, see Tx.Stmt.
|
|
|
|
|
func (tx *Tx) Prepare(query string) (*Stmt, error) {
|
2017-06-09 18:45:46 +00:00
|
|
|
return tx.PrepareContext(context.Background(), query)
|
2016-09-19 11:19:32 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// StmtContext returns a transaction-specific prepared statement from
|
2011-11-28 11:00:32 -05:00
|
|
|
// an existing statement.
|
|
|
|
|
//
|
|
|
|
|
// Example:
|
|
|
|
|
// updateMoney, err := db.Prepare("UPDATE balance SET money=money+? WHERE id=?")
|
|
|
|
|
// ...
|
|
|
|
|
// tx, err := db.Begin()
|
|
|
|
|
// ...
|
2016-09-19 11:19:32 -07:00
|
|
|
// res, err := tx.StmtContext(ctx, updateMoney).Exec(123.45, 98293203)
|
2015-07-14 16:28:28 -04:00
|
|
|
//
|
2017-09-23 17:04:51 -07:00
|
|
|
// The provided context is used for the preparation of the statement, not for the
|
|
|
|
|
// execution of the statement.
|
|
|
|
|
//
|
2016-11-15 17:14:13 -08:00
|
|
|
// The returned statement operates within the transaction and will be closed
|
|
|
|
|
// when the transaction has been committed or rolled back.
|
2016-09-19 11:19:32 -07:00
|
|
|
func (tx *Tx) StmtContext(ctx context.Context, stmt *Stmt) *Stmt {
|
2017-06-12 10:46:15 -07:00
|
|
|
dc, release, err := tx.grabConn(ctx)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return &Stmt{stickyErr: err}
|
|
|
|
|
}
|
|
|
|
|
defer release(nil)
|
2017-01-20 17:12:50 -08:00
|
|
|
|
2011-11-28 11:00:32 -05:00
|
|
|
if tx.db != stmt.db {
|
|
|
|
|
return &Stmt{stickyErr: errors.New("sql: Tx.Stmt: statement from different database used")}
|
|
|
|
|
}
|
2016-05-31 06:58:33 -07:00
|
|
|
var si driver.Stmt
|
2017-01-19 14:17:10 -08:00
|
|
|
var parentStmt *Stmt
|
|
|
|
|
stmt.mu.Lock()
|
2017-06-12 10:46:15 -07:00
|
|
|
if stmt.closed || stmt.cg != nil {
|
2017-01-19 14:17:10 -08:00
|
|
|
// If the statement has been closed or already belongs to a
|
|
|
|
|
// transaction, we can't reuse it in this connection.
|
|
|
|
|
// Since tx.StmtContext should never need to be called with a
|
|
|
|
|
// Stmt already belonging to tx, we ignore this edge case and
|
|
|
|
|
// re-prepare the statement in this case. No need to add
|
|
|
|
|
// code-complexity for this.
|
|
|
|
|
stmt.mu.Unlock()
|
|
|
|
|
withLock(dc, func() {
|
|
|
|
|
si, err = ctxDriverPrepare(ctx, dc.ci, stmt.query)
|
|
|
|
|
})
|
|
|
|
|
if err != nil {
|
|
|
|
|
return &Stmt{stickyErr: err}
|
|
|
|
|
}
|
|
|
|
|
} else {
|
|
|
|
|
stmt.removeClosedStmtLocked()
|
|
|
|
|
// See if the statement has already been prepared on this connection,
|
|
|
|
|
// and reuse it if possible.
|
|
|
|
|
for _, v := range stmt.css {
|
|
|
|
|
if v.dc == dc {
|
|
|
|
|
si = v.ds.si
|
|
|
|
|
break
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
stmt.mu.Unlock()
|
|
|
|
|
|
|
|
|
|
if si == nil {
|
2017-12-21 09:31:39 -08:00
|
|
|
var ds *driverStmt
|
2017-10-17 15:59:56 -07:00
|
|
|
withLock(dc, func() {
|
|
|
|
|
ds, err = stmt.prepareOnConnLocked(ctx, dc)
|
|
|
|
|
})
|
2017-01-19 14:17:10 -08:00
|
|
|
if err != nil {
|
|
|
|
|
return &Stmt{stickyErr: err}
|
|
|
|
|
}
|
2017-12-21 09:31:39 -08:00
|
|
|
si = ds.si
|
2017-01-19 14:17:10 -08:00
|
|
|
}
|
|
|
|
|
parentStmt = stmt
|
|
|
|
|
}
|
|
|
|
|
|
2014-09-22 09:19:27 -04:00
|
|
|
txs := &Stmt{
|
2013-03-14 15:01:45 -07:00
|
|
|
db: tx.db,
|
2017-06-12 10:46:15 -07:00
|
|
|
cg: tx,
|
|
|
|
|
cgds: &driverStmt{
|
2013-03-14 15:01:45 -07:00
|
|
|
Locker: dc,
|
|
|
|
|
si: si,
|
|
|
|
|
},
|
2017-01-19 14:17:10 -08:00
|
|
|
parentStmt: parentStmt,
|
|
|
|
|
query: stmt.query,
|
|
|
|
|
}
|
|
|
|
|
if parentStmt != nil {
|
|
|
|
|
tx.db.addDep(parentStmt, txs)
|
2011-11-28 11:00:32 -05:00
|
|
|
}
|
2014-09-22 09:19:27 -04:00
|
|
|
tx.stmts.Lock()
|
|
|
|
|
tx.stmts.v = append(tx.stmts.v, txs)
|
|
|
|
|
tx.stmts.Unlock()
|
|
|
|
|
return txs
|
2011-11-28 11:00:32 -05:00
|
|
|
}
|
|
|
|
|
|
2016-09-19 11:19:32 -07:00
|
|
|
// Stmt returns a transaction-specific prepared statement from
|
|
|
|
|
// an existing statement.
|
|
|
|
|
//
|
|
|
|
|
// Example:
|
|
|
|
|
// updateMoney, err := db.Prepare("UPDATE balance SET money=money+? WHERE id=?")
|
|
|
|
|
// ...
|
|
|
|
|
// tx, err := db.Begin()
|
|
|
|
|
// ...
|
|
|
|
|
// res, err := tx.Stmt(updateMoney).Exec(123.45, 98293203)
|
|
|
|
|
//
|
2016-11-15 17:14:13 -08:00
|
|
|
// The returned statement operates within the transaction and will be closed
|
|
|
|
|
// when the transaction has been committed or rolled back.
|
2016-09-19 11:19:32 -07:00
|
|
|
func (tx *Tx) Stmt(stmt *Stmt) *Stmt {
|
2017-06-09 18:45:46 +00:00
|
|
|
return tx.StmtContext(context.Background(), stmt)
|
2016-09-19 11:19:32 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// ExecContext executes a query that doesn't return rows.
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
// For example: an INSERT and UPDATE.
|
2016-09-19 11:19:32 -07:00
|
|
|
func (tx *Tx) ExecContext(ctx context.Context, query string, args ...interface{}) (Result, error) {
|
2017-06-12 10:46:15 -07:00
|
|
|
dc, release, err := tx.grabConn(ctx)
|
2011-11-02 11:46:04 -07:00
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
2017-06-12 10:46:15 -07:00
|
|
|
return tx.db.execDC(ctx, dc, release, query, args)
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
}
|
|
|
|
|
|
2016-09-19 11:19:32 -07:00
|
|
|
// Exec executes a query that doesn't return rows.
|
|
|
|
|
// For example: an INSERT and UPDATE.
|
|
|
|
|
func (tx *Tx) Exec(query string, args ...interface{}) (Result, error) {
|
2017-06-09 18:45:46 +00:00
|
|
|
return tx.ExecContext(context.Background(), query, args...)
|
2016-09-19 11:19:32 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// QueryContext executes a query that returns rows, typically a SELECT.
|
|
|
|
|
func (tx *Tx) QueryContext(ctx context.Context, query string, args ...interface{}) (*Rows, error) {
|
2017-06-12 10:46:15 -07:00
|
|
|
dc, release, err := tx.grabConn(ctx)
|
2012-03-10 15:21:44 -08:00
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
2012-01-25 17:49:30 -08:00
|
|
|
}
|
2017-04-07 12:21:50 -07:00
|
|
|
|
2017-06-12 10:46:15 -07:00
|
|
|
return tx.db.queryDC(ctx, tx.ctx, dc, release, query, args)
|
2016-09-19 11:19:32 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Query executes a query that returns rows, typically a SELECT.
|
|
|
|
|
func (tx *Tx) Query(query string, args ...interface{}) (*Rows, error) {
|
2017-06-09 18:45:46 +00:00
|
|
|
return tx.QueryContext(context.Background(), query, args...)
|
2016-09-19 11:19:32 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// QueryRowContext executes a query that is expected to return at most one row.
|
|
|
|
|
// QueryRowContext always returns a non-nil value. Errors are deferred until
|
|
|
|
|
// Row's Scan method is called.
|
2017-06-05 15:45:04 -07:00
|
|
|
// If the query selects no rows, the *Row's Scan will return ErrNoRows.
|
|
|
|
|
// Otherwise, the *Row's Scan scans the first selected row and discards
|
|
|
|
|
// the rest.
|
2016-09-19 11:19:32 -07:00
|
|
|
func (tx *Tx) QueryRowContext(ctx context.Context, query string, args ...interface{}) *Row {
|
|
|
|
|
rows, err := tx.QueryContext(ctx, query, args...)
|
|
|
|
|
return &Row{rows: rows, err: err}
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// QueryRow executes a query that is expected to return at most one row.
|
2015-12-30 13:23:11 +13:00
|
|
|
// QueryRow always returns a non-nil value. Errors are deferred until
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
// Row's Scan method is called.
|
2017-06-05 15:45:04 -07:00
|
|
|
// If the query selects no rows, the *Row's Scan will return ErrNoRows.
|
|
|
|
|
// Otherwise, the *Row's Scan scans the first selected row and discards
|
|
|
|
|
// the rest.
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
func (tx *Tx) QueryRow(query string, args ...interface{}) *Row {
|
2017-06-09 18:45:46 +00:00
|
|
|
return tx.QueryRowContext(context.Background(), query, args...)
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// connStmt is a prepared statement on a particular connection.
|
|
|
|
|
type connStmt struct {
|
2013-03-14 15:01:45 -07:00
|
|
|
dc *driverConn
|
2016-11-17 09:33:31 -08:00
|
|
|
ds *driverStmt
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
}
|
|
|
|
|
|
2017-06-12 10:46:15 -07:00
|
|
|
// stmtConnGrabber represents a Tx or Conn that will return the underlying
|
|
|
|
|
// driverConn and release function.
|
|
|
|
|
type stmtConnGrabber interface {
|
|
|
|
|
// grabConn returns the driverConn and the associated release function
|
|
|
|
|
// that must be called when the operation completes.
|
|
|
|
|
grabConn(context.Context) (*driverConn, releaseConn, error)
|
|
|
|
|
|
|
|
|
|
// txCtx returns the transaction context if available.
|
|
|
|
|
// The returned context should be selected on along with
|
|
|
|
|
// any query context when awaiting a cancel.
|
|
|
|
|
txCtx() context.Context
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
var (
|
|
|
|
|
_ stmtConnGrabber = &Tx{}
|
|
|
|
|
_ stmtConnGrabber = &Conn{}
|
|
|
|
|
)
|
|
|
|
|
|
2015-07-14 16:28:28 -04:00
|
|
|
// Stmt is a prepared statement.
|
|
|
|
|
// A Stmt is safe for concurrent use by multiple goroutines.
|
2019-01-23 15:15:06 +00:00
|
|
|
//
|
|
|
|
|
// If a Stmt is prepared on a Tx or Conn, it will be bound to a single
|
|
|
|
|
// underlying connection forever. If the Tx or Conn closes, the Stmt will
|
|
|
|
|
// become unusable and all operations will return an error.
|
|
|
|
|
// If a Stmt is prepared on a DB, it will remain usable for the lifetime of the
|
|
|
|
|
// DB. When the Stmt needs to execute on a new underlying connection, it will
|
|
|
|
|
// prepare itself on the new connection automatically.
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
type Stmt struct {
|
|
|
|
|
// Immutable:
|
2011-11-28 11:00:32 -05:00
|
|
|
db *DB // where we came from
|
|
|
|
|
query string // that created the Stmt
|
|
|
|
|
stickyErr error // if non-nil, this error is returned for all operations
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
|
2013-02-20 15:35:27 -08:00
|
|
|
closemu sync.RWMutex // held exclusively during close, for read otherwise.
|
|
|
|
|
|
2017-06-12 10:46:15 -07:00
|
|
|
// If Stmt is prepared on a Tx or Conn then cg is present and will
|
|
|
|
|
// only ever grab a connection from cg.
|
|
|
|
|
// If cg is nil then the Stmt must grab an arbitrary connection
|
|
|
|
|
// from db and determine if it must prepare the stmt again by
|
|
|
|
|
// inspecting css.
|
|
|
|
|
cg stmtConnGrabber
|
|
|
|
|
cgds *driverStmt
|
2011-11-02 11:46:04 -07:00
|
|
|
|
2017-01-19 14:17:10 -08:00
|
|
|
// parentStmt is set when a transaction-specific statement
|
|
|
|
|
// is requested from an identical statement prepared on the same
|
|
|
|
|
// conn. parentStmt is used to track the dependency of this statement
|
|
|
|
|
// on its originating ("parent") statement so that parentStmt may
|
|
|
|
|
// be closed by the user without them having to know whether or not
|
|
|
|
|
// any transactions are still using it.
|
|
|
|
|
parentStmt *Stmt
|
|
|
|
|
|
2011-11-02 11:46:04 -07:00
|
|
|
mu sync.Mutex // protects the rest of the fields
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
closed bool
|
|
|
|
|
|
2011-11-02 11:46:04 -07:00
|
|
|
// css is a list of underlying driver statement interfaces
|
2016-03-01 23:21:55 +00:00
|
|
|
// that are valid on particular connections. This is only
|
2017-06-12 10:46:15 -07:00
|
|
|
// used if cg == nil and one is found that has idle
|
|
|
|
|
// connections. If cg != nil, cgds is always used.
|
2011-11-02 11:46:04 -07:00
|
|
|
css []connStmt
|
2015-01-23 20:02:37 +09:00
|
|
|
|
|
|
|
|
// lastNumClosed is copied from db.numClosed when Stmt is created
|
|
|
|
|
// without tx and closed connections in css are removed.
|
|
|
|
|
lastNumClosed uint64
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
}
|
|
|
|
|
|
2016-09-19 11:19:32 -07:00
|
|
|
// ExecContext executes a prepared statement with the given arguments and
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
// returns a Result summarizing the effect of the statement.
|
2016-09-19 11:19:32 -07:00
|
|
|
func (s *Stmt) ExecContext(ctx context.Context, args ...interface{}) (Result, error) {
|
2013-02-20 15:35:27 -08:00
|
|
|
s.closemu.RLock()
|
|
|
|
|
defer s.closemu.RUnlock()
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
|
2013-12-17 11:57:30 -08:00
|
|
|
var res Result
|
2017-05-21 19:51:46 -07:00
|
|
|
strategy := cachedOrNewConn
|
|
|
|
|
for i := 0; i < maxBadConnRetries+1; i++ {
|
|
|
|
|
if i == maxBadConnRetries {
|
|
|
|
|
strategy = alwaysNewConn
|
|
|
|
|
}
|
|
|
|
|
dc, releaseConn, ds, err := s.connStmt(ctx, strategy)
|
2013-12-17 11:57:30 -08:00
|
|
|
if err != nil {
|
|
|
|
|
if err == driver.ErrBadConn {
|
|
|
|
|
continue
|
|
|
|
|
}
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
|
2017-03-23 13:17:59 -07:00
|
|
|
res, err = resultFromStatement(ctx, dc.ci, ds, args...)
|
2013-12-17 11:57:30 -08:00
|
|
|
releaseConn(err)
|
|
|
|
|
if err != driver.ErrBadConn {
|
|
|
|
|
return res, err
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return nil, driver.ErrBadConn
|
2013-01-11 13:28:33 -08:00
|
|
|
}
|
|
|
|
|
|
2016-09-19 11:19:32 -07:00
|
|
|
// Exec executes a prepared statement with the given arguments and
|
|
|
|
|
// returns a Result summarizing the effect of the statement.
|
|
|
|
|
func (s *Stmt) Exec(args ...interface{}) (Result, error) {
|
|
|
|
|
return s.ExecContext(context.Background(), args...)
|
|
|
|
|
}
|
|
|
|
|
|
2017-03-23 13:17:59 -07:00
|
|
|
func resultFromStatement(ctx context.Context, ci driver.Conn, ds *driverStmt, args ...interface{}) (Result, error) {
|
2017-10-17 15:59:56 -07:00
|
|
|
ds.Lock()
|
|
|
|
|
defer ds.Unlock()
|
|
|
|
|
|
|
|
|
|
dargs, err := driverArgsConnLocked(ci, ds, args)
|
2012-05-29 11:09:09 -07:00
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
}
|
|
|
|
|
|
2016-09-19 11:19:32 -07:00
|
|
|
resi, err := ctxDriverStmtExec(ctx, ds.si, dargs)
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
2013-03-14 15:01:45 -07:00
|
|
|
return driverResult{ds.Locker, resi}, nil
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
}
|
|
|
|
|
|
2015-01-23 20:02:37 +09:00
|
|
|
// removeClosedStmtLocked removes closed conns in s.css.
|
|
|
|
|
//
|
|
|
|
|
// To avoid lock contention on DB.mu, we do it only when
|
|
|
|
|
// s.db.numClosed - s.lastNum is large enough.
|
|
|
|
|
func (s *Stmt) removeClosedStmtLocked() {
|
|
|
|
|
t := len(s.css)/2 + 1
|
|
|
|
|
if t > 10 {
|
|
|
|
|
t = 10
|
|
|
|
|
}
|
|
|
|
|
dbClosed := atomic.LoadUint64(&s.db.numClosed)
|
|
|
|
|
if dbClosed-s.lastNumClosed < uint64(t) {
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
s.db.mu.Lock()
|
|
|
|
|
for i := 0; i < len(s.css); i++ {
|
|
|
|
|
if s.css[i].dc.dbmuClosed {
|
|
|
|
|
s.css[i] = s.css[len(s.css)-1]
|
|
|
|
|
s.css = s.css[:len(s.css)-1]
|
|
|
|
|
i--
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
s.db.mu.Unlock()
|
|
|
|
|
s.lastNumClosed = dbClosed
|
|
|
|
|
}
|
|
|
|
|
|
2011-11-02 11:46:04 -07:00
|
|
|
// connStmt returns a free driver connection on which to execute the
|
|
|
|
|
// statement, a function to call to release the connection, and a
|
|
|
|
|
// statement bound to that connection.
|
2017-06-12 10:46:15 -07:00
|
|
|
func (s *Stmt) connStmt(ctx context.Context, strategy connReuseStrategy) (dc *driverConn, releaseConn func(error), ds *driverStmt, err error) {
|
2012-01-10 12:51:27 -08:00
|
|
|
if err = s.stickyErr; err != nil {
|
|
|
|
|
return
|
2011-11-28 11:00:32 -05:00
|
|
|
}
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
s.mu.Lock()
|
|
|
|
|
if s.closed {
|
2011-11-02 11:46:04 -07:00
|
|
|
s.mu.Unlock()
|
2011-12-15 10:14:57 -08:00
|
|
|
err = errors.New("sql: statement is closed")
|
2011-11-02 11:46:04 -07:00
|
|
|
return
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
}
|
2011-11-02 11:46:04 -07:00
|
|
|
|
2017-06-12 10:46:15 -07:00
|
|
|
// In a transaction or connection, we always use the connection that the
|
2018-02-20 15:10:49 +00:00
|
|
|
// stmt was created on.
|
2017-06-12 10:46:15 -07:00
|
|
|
if s.cg != nil {
|
2011-11-02 11:46:04 -07:00
|
|
|
s.mu.Unlock()
|
2017-06-12 10:46:15 -07:00
|
|
|
dc, releaseConn, err = s.cg.grabConn(ctx) // blocks, waiting for the connection.
|
2011-11-02 11:46:04 -07:00
|
|
|
if err != nil {
|
|
|
|
|
return
|
|
|
|
|
}
|
2017-06-12 10:46:15 -07:00
|
|
|
return dc, releaseConn, s.cgds, nil
|
2011-11-02 11:46:04 -07:00
|
|
|
}
|
|
|
|
|
|
2015-01-23 20:02:37 +09:00
|
|
|
s.removeClosedStmtLocked()
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
s.mu.Unlock()
|
|
|
|
|
|
2017-06-12 10:46:15 -07:00
|
|
|
dc, err = s.db.conn(ctx, strategy)
|
2014-09-02 09:08:41 -07:00
|
|
|
if err != nil {
|
|
|
|
|
return nil, nil, nil, err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
s.mu.Lock()
|
|
|
|
|
for _, v := range s.css {
|
|
|
|
|
if v.dc == dc {
|
|
|
|
|
s.mu.Unlock()
|
2016-11-17 09:33:31 -08:00
|
|
|
return dc, dc.releaseConn, v.ds, nil
|
2013-12-17 11:57:30 -08:00
|
|
|
}
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
}
|
2014-09-02 09:08:41 -07:00
|
|
|
s.mu.Unlock()
|
|
|
|
|
|
|
|
|
|
// No luck; we need to prepare the statement on this connection
|
2016-05-31 06:58:33 -07:00
|
|
|
withLock(dc, func() {
|
2017-01-19 14:17:10 -08:00
|
|
|
ds, err = s.prepareOnConnLocked(ctx, dc)
|
2016-05-31 06:58:33 -07:00
|
|
|
})
|
2014-09-02 09:08:41 -07:00
|
|
|
if err != nil {
|
2017-04-04 17:03:10 -07:00
|
|
|
dc.releaseConn(err)
|
2014-09-02 09:08:41 -07:00
|
|
|
return nil, nil, nil, err
|
|
|
|
|
}
|
2017-01-19 14:17:10 -08:00
|
|
|
|
|
|
|
|
return dc, dc.releaseConn, ds, nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// prepareOnConnLocked prepares the query in Stmt s on dc and adds it to the list of
|
|
|
|
|
// open connStmt on the statement. It assumes the caller is holding the lock on dc.
|
|
|
|
|
func (s *Stmt) prepareOnConnLocked(ctx context.Context, dc *driverConn) (*driverStmt, error) {
|
2017-06-12 10:46:15 -07:00
|
|
|
si, err := dc.prepareLocked(ctx, s.cg, s.query)
|
2017-01-19 14:17:10 -08:00
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
cs := connStmt{dc, si}
|
2014-09-02 09:08:41 -07:00
|
|
|
s.mu.Lock()
|
|
|
|
|
s.css = append(s.css, cs)
|
|
|
|
|
s.mu.Unlock()
|
2017-01-19 14:17:10 -08:00
|
|
|
return cs.ds, nil
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
}
|
|
|
|
|
|
2016-09-19 11:19:32 -07:00
|
|
|
// QueryContext executes a prepared query statement with the given arguments
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
// and returns the query results as a *Rows.
|
2016-09-19 11:19:32 -07:00
|
|
|
func (s *Stmt) QueryContext(ctx context.Context, args ...interface{}) (*Rows, error) {
|
2013-02-20 15:35:27 -08:00
|
|
|
s.closemu.RLock()
|
|
|
|
|
defer s.closemu.RUnlock()
|
|
|
|
|
|
2013-12-17 11:57:30 -08:00
|
|
|
var rowsi driver.Rows
|
2017-05-21 19:51:46 -07:00
|
|
|
strategy := cachedOrNewConn
|
|
|
|
|
for i := 0; i < maxBadConnRetries+1; i++ {
|
|
|
|
|
if i == maxBadConnRetries {
|
|
|
|
|
strategy = alwaysNewConn
|
|
|
|
|
}
|
|
|
|
|
dc, releaseConn, ds, err := s.connStmt(ctx, strategy)
|
2013-12-17 11:57:30 -08:00
|
|
|
if err != nil {
|
|
|
|
|
if err == driver.ErrBadConn {
|
|
|
|
|
continue
|
|
|
|
|
}
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
2011-11-15 16:29:43 -08:00
|
|
|
|
2017-03-23 13:17:59 -07:00
|
|
|
rowsi, err = rowsiFromStatement(ctx, dc.ci, ds, args...)
|
2013-12-17 11:57:30 -08:00
|
|
|
if err == nil {
|
|
|
|
|
// Note: ownership of ci passes to the *Rows, to be freed
|
|
|
|
|
// with releaseConn.
|
|
|
|
|
rows := &Rows{
|
|
|
|
|
dc: dc,
|
|
|
|
|
rowsi: rowsi,
|
|
|
|
|
// releaseConn set below
|
|
|
|
|
}
|
2017-04-28 14:24:31 -07:00
|
|
|
// addDep must be added before initContextClose or it could attempt
|
|
|
|
|
// to removeDep before it has been added.
|
2013-12-17 11:57:30 -08:00
|
|
|
s.db.addDep(s, rows)
|
2017-04-28 14:24:31 -07:00
|
|
|
|
|
|
|
|
// releaseConn must be set before initContextClose or it could
|
|
|
|
|
// release the connection before it is set.
|
2013-12-17 11:57:30 -08:00
|
|
|
rows.releaseConn = func(err error) {
|
|
|
|
|
releaseConn(err)
|
|
|
|
|
s.db.removeDep(s, rows)
|
|
|
|
|
}
|
2017-06-05 09:04:05 -07:00
|
|
|
var txctx context.Context
|
2017-06-12 10:46:15 -07:00
|
|
|
if s.cg != nil {
|
|
|
|
|
txctx = s.cg.txCtx()
|
2017-06-05 09:04:05 -07:00
|
|
|
}
|
|
|
|
|
rows.initContextClose(ctx, txctx)
|
2013-12-17 11:57:30 -08:00
|
|
|
return rows, nil
|
|
|
|
|
}
|
2013-02-13 15:25:39 -08:00
|
|
|
|
2013-02-20 15:35:27 -08:00
|
|
|
releaseConn(err)
|
2013-12-17 11:57:30 -08:00
|
|
|
if err != driver.ErrBadConn {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
2013-02-13 15:25:39 -08:00
|
|
|
}
|
2013-12-17 11:57:30 -08:00
|
|
|
return nil, driver.ErrBadConn
|
2013-02-13 15:25:39 -08:00
|
|
|
}
|
|
|
|
|
|
2016-09-19 11:19:32 -07:00
|
|
|
// Query executes a prepared query statement with the given arguments
|
|
|
|
|
// and returns the query results as a *Rows.
|
|
|
|
|
func (s *Stmt) Query(args ...interface{}) (*Rows, error) {
|
|
|
|
|
return s.QueryContext(context.Background(), args...)
|
|
|
|
|
}
|
|
|
|
|
|
2017-03-23 13:17:59 -07:00
|
|
|
func rowsiFromStatement(ctx context.Context, ci driver.Conn, ds *driverStmt, args ...interface{}) (driver.Rows, error) {
|
2017-10-17 15:59:56 -07:00
|
|
|
ds.Lock()
|
|
|
|
|
defer ds.Unlock()
|
2017-11-09 14:14:44 -08:00
|
|
|
dargs, err := driverArgsConnLocked(ci, ds, args)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
2018-04-11 19:20:10 -07:00
|
|
|
return ctxDriverStmtQuery(ctx, ds.si, dargs)
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
}
|
|
|
|
|
|
2016-09-19 11:19:32 -07:00
|
|
|
// QueryRowContext executes a prepared query statement with the given arguments.
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
// If an error occurs during the execution of the statement, that error will
|
|
|
|
|
// be returned by a call to Scan on the returned *Row, which is always non-nil.
|
|
|
|
|
// If the query selects no rows, the *Row's Scan will return ErrNoRows.
|
|
|
|
|
// Otherwise, the *Row's Scan scans the first selected row and discards
|
|
|
|
|
// the rest.
|
2016-09-19 11:19:32 -07:00
|
|
|
func (s *Stmt) QueryRowContext(ctx context.Context, args ...interface{}) *Row {
|
|
|
|
|
rows, err := s.QueryContext(ctx, args...)
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
if err != nil {
|
|
|
|
|
return &Row{err: err}
|
|
|
|
|
}
|
|
|
|
|
return &Row{rows: rows}
|
|
|
|
|
}
|
|
|
|
|
|
2016-09-19 11:19:32 -07:00
|
|
|
// QueryRow executes a prepared query statement with the given arguments.
|
|
|
|
|
// If an error occurs during the execution of the statement, that error will
|
|
|
|
|
// be returned by a call to Scan on the returned *Row, which is always non-nil.
|
|
|
|
|
// If the query selects no rows, the *Row's Scan will return ErrNoRows.
|
|
|
|
|
// Otherwise, the *Row's Scan scans the first selected row and discards
|
|
|
|
|
// the rest.
|
|
|
|
|
//
|
|
|
|
|
// Example usage:
|
|
|
|
|
//
|
|
|
|
|
// var name string
|
|
|
|
|
// err := nameByUseridStmt.QueryRow(id).Scan(&name)
|
|
|
|
|
func (s *Stmt) QueryRow(args ...interface{}) *Row {
|
|
|
|
|
return s.QueryRowContext(context.Background(), args...)
|
|
|
|
|
}
|
|
|
|
|
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
// Close closes the statement.
|
2011-11-01 22:04:37 -04:00
|
|
|
func (s *Stmt) Close() error {
|
2013-02-20 15:35:27 -08:00
|
|
|
s.closemu.Lock()
|
|
|
|
|
defer s.closemu.Unlock()
|
|
|
|
|
|
2011-11-28 11:00:32 -05:00
|
|
|
if s.stickyErr != nil {
|
|
|
|
|
return s.stickyErr
|
|
|
|
|
}
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
s.mu.Lock()
|
|
|
|
|
if s.closed {
|
2013-08-30 09:27:33 -07:00
|
|
|
s.mu.Unlock()
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
s.closed = true
|
2017-06-12 10:46:15 -07:00
|
|
|
txds := s.cgds
|
|
|
|
|
s.cgds = nil
|
|
|
|
|
|
2016-11-17 09:33:31 -08:00
|
|
|
s.mu.Unlock()
|
2011-11-02 11:46:04 -07:00
|
|
|
|
2017-06-12 10:46:15 -07:00
|
|
|
if s.cg == nil {
|
2017-01-19 14:17:10 -08:00
|
|
|
return s.db.removeDep(s, s)
|
2013-02-20 15:35:27 -08:00
|
|
|
}
|
|
|
|
|
|
2017-01-19 14:17:10 -08:00
|
|
|
if s.parentStmt != nil {
|
|
|
|
|
// If parentStmt is set, we must not close s.txds since it's stored
|
|
|
|
|
// in the css array of the parentStmt.
|
|
|
|
|
return s.db.removeDep(s.parentStmt, s)
|
|
|
|
|
}
|
2017-06-12 10:46:15 -07:00
|
|
|
return txds.Close()
|
2013-02-20 15:35:27 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (s *Stmt) finalClose() error {
|
2013-08-30 09:27:33 -07:00
|
|
|
s.mu.Lock()
|
|
|
|
|
defer s.mu.Unlock()
|
|
|
|
|
if s.css != nil {
|
|
|
|
|
for _, v := range s.css {
|
2016-11-17 09:33:31 -08:00
|
|
|
s.db.noteUnusedDriverStatement(v.dc, v.ds)
|
|
|
|
|
v.dc.removeOpenStmt(v.ds)
|
2013-08-30 09:27:33 -07:00
|
|
|
}
|
|
|
|
|
s.css = nil
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
}
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Rows is the result of a query. Its cursor starts before the first row
|
2018-01-30 19:25:37 -08:00
|
|
|
// of the result set. Use Next to advance from row to row.
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
type Rows struct {
|
2013-03-14 15:01:45 -07:00
|
|
|
dc *driverConn // owned; must call releaseConn when closed to release
|
2012-03-10 10:00:02 -08:00
|
|
|
releaseConn func(error)
|
2011-11-02 11:46:04 -07:00
|
|
|
rowsi driver.Rows
|
2017-02-07 10:19:02 -08:00
|
|
|
cancel func() // called when Rows is closed, may be nil.
|
|
|
|
|
closeStmt *driverStmt // if non-nil, statement to Close on close
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
|
2017-02-07 10:19:02 -08:00
|
|
|
// closemu prevents Rows from closing while there
|
|
|
|
|
// is an active streaming result. It is held for read during non-close operations
|
|
|
|
|
// and exclusively during close.
|
|
|
|
|
//
|
|
|
|
|
// closemu guards lasterr and closed.
|
|
|
|
|
closemu sync.RWMutex
|
|
|
|
|
closed bool
|
|
|
|
|
lasterr error // non-nil only if closed is true
|
|
|
|
|
|
|
|
|
|
// lastcols is only used in Scan, Next, and NextResultSet which are expected
|
2017-02-08 15:31:33 -08:00
|
|
|
// not to be called concurrently.
|
2017-02-07 10:19:02 -08:00
|
|
|
lastcols []driver.Value
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
}
|
|
|
|
|
|
2018-10-27 14:12:52 -07:00
|
|
|
// lasterrOrErrLocked returns either lasterr or the provided err.
|
|
|
|
|
// rs.closemu must be read-locked.
|
|
|
|
|
func (rs *Rows) lasterrOrErrLocked(err error) error {
|
|
|
|
|
if rs.lasterr != nil && rs.lasterr != io.EOF {
|
|
|
|
|
return rs.lasterr
|
|
|
|
|
}
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
|
2017-06-05 09:04:05 -07:00
|
|
|
func (rs *Rows) initContextClose(ctx, txctx context.Context) {
|
2018-03-25 17:19:47 -07:00
|
|
|
if ctx.Done() == nil && (txctx == nil || txctx.Done() == nil) {
|
|
|
|
|
return
|
|
|
|
|
}
|
2017-01-20 17:12:50 -08:00
|
|
|
ctx, rs.cancel = context.WithCancel(ctx)
|
2017-06-05 09:04:05 -07:00
|
|
|
go rs.awaitDone(ctx, txctx)
|
2017-01-20 17:12:50 -08:00
|
|
|
}
|
2016-09-28 12:51:39 -07:00
|
|
|
|
2017-06-05 09:04:05 -07:00
|
|
|
// awaitDone blocks until either ctx or txctx is canceled. The ctx is provided
|
|
|
|
|
// from the query context and is canceled when the query Rows is closed.
|
|
|
|
|
// If the query was issued in a transaction, the transaction's context
|
|
|
|
|
// is also provided in txctx to ensure Rows is closed if the Tx is closed.
|
|
|
|
|
func (rs *Rows) awaitDone(ctx, txctx context.Context) {
|
|
|
|
|
var txctxDone <-chan struct{}
|
|
|
|
|
if txctx != nil {
|
|
|
|
|
txctxDone = txctx.Done()
|
|
|
|
|
}
|
|
|
|
|
select {
|
|
|
|
|
case <-ctx.Done():
|
|
|
|
|
case <-txctxDone:
|
|
|
|
|
}
|
2017-02-07 10:19:02 -08:00
|
|
|
rs.close(ctx.Err())
|
2016-09-28 12:51:39 -07:00
|
|
|
}
|
|
|
|
|
|
2016-03-01 23:21:55 +00:00
|
|
|
// Next prepares the next result row for reading with the Scan method. It
|
2013-12-16 12:48:35 -08:00
|
|
|
// returns true on success, or false if there is no next result row or an error
|
2016-03-01 23:21:55 +00:00
|
|
|
// happened while preparing it. Err should be consulted to distinguish between
|
2013-12-16 12:48:35 -08:00
|
|
|
// the two cases.
|
|
|
|
|
//
|
|
|
|
|
// Every call to Scan, even the first one, must be preceded by a call to Next.
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
func (rs *Rows) Next() bool {
|
2017-02-07 10:19:02 -08:00
|
|
|
var doClose, ok bool
|
|
|
|
|
withLock(rs.closemu.RLocker(), func() {
|
|
|
|
|
doClose, ok = rs.nextLocked()
|
|
|
|
|
})
|
|
|
|
|
if doClose {
|
|
|
|
|
rs.Close()
|
|
|
|
|
}
|
|
|
|
|
return ok
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (rs *Rows) nextLocked() (doClose, ok bool) {
|
|
|
|
|
if rs.closed {
|
|
|
|
|
return false, false
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
}
|
2017-10-17 15:59:56 -07:00
|
|
|
|
|
|
|
|
// Lock the driver connection before calling the driver interface
|
|
|
|
|
// rowsi to prevent a Tx from rolling back the connection at the same time.
|
|
|
|
|
rs.dc.Lock()
|
|
|
|
|
defer rs.dc.Unlock()
|
|
|
|
|
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
if rs.lastcols == nil {
|
2012-02-20 14:25:28 +11:00
|
|
|
rs.lastcols = make([]driver.Value, len(rs.rowsi.Columns()))
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
}
|
2017-10-17 15:59:56 -07:00
|
|
|
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
rs.lasterr = rs.rowsi.Next(rs.lastcols)
|
2016-10-06 11:06:21 -07:00
|
|
|
if rs.lasterr != nil {
|
|
|
|
|
// Close the connection if there is a driver error.
|
|
|
|
|
if rs.lasterr != io.EOF {
|
2017-02-07 10:19:02 -08:00
|
|
|
return true, false
|
2016-10-06 11:06:21 -07:00
|
|
|
}
|
|
|
|
|
nextResultSet, ok := rs.rowsi.(driver.RowsNextResultSet)
|
|
|
|
|
if !ok {
|
2017-02-07 10:19:02 -08:00
|
|
|
return true, false
|
2016-10-06 11:06:21 -07:00
|
|
|
}
|
|
|
|
|
// The driver is at the end of the current result set.
|
|
|
|
|
// Test to see if there is another result set after the current one.
|
2017-01-07 08:23:11 -08:00
|
|
|
// Only close Rows if there is no further result sets to read.
|
2016-10-06 11:06:21 -07:00
|
|
|
if !nextResultSet.HasNextResultSet() {
|
2017-02-07 10:19:02 -08:00
|
|
|
doClose = true
|
2016-10-06 11:06:21 -07:00
|
|
|
}
|
2017-02-07 10:19:02 -08:00
|
|
|
return doClose, false
|
2016-10-06 11:06:21 -07:00
|
|
|
}
|
2017-02-07 10:19:02 -08:00
|
|
|
return false, true
|
2016-10-06 11:06:21 -07:00
|
|
|
}
|
|
|
|
|
|
2018-11-02 15:18:43 +00:00
|
|
|
// NextResultSet prepares the next result set for reading. It reports whether
|
2016-10-06 11:06:21 -07:00
|
|
|
// there is further result sets, or false if there is no further result set
|
|
|
|
|
// or if there is an error advancing to it. The Err method should be consulted
|
|
|
|
|
// to distinguish between the two cases.
|
|
|
|
|
//
|
|
|
|
|
// After calling NextResultSet, the Next method should always be called before
|
|
|
|
|
// scanning. If there are further result sets they may not have rows in the result
|
|
|
|
|
// set.
|
|
|
|
|
func (rs *Rows) NextResultSet() bool {
|
2017-02-07 10:19:02 -08:00
|
|
|
var doClose bool
|
|
|
|
|
defer func() {
|
|
|
|
|
if doClose {
|
|
|
|
|
rs.Close()
|
|
|
|
|
}
|
|
|
|
|
}()
|
|
|
|
|
rs.closemu.RLock()
|
|
|
|
|
defer rs.closemu.RUnlock()
|
|
|
|
|
|
|
|
|
|
if rs.closed {
|
2016-10-06 11:06:21 -07:00
|
|
|
return false
|
|
|
|
|
}
|
2017-02-07 10:19:02 -08:00
|
|
|
|
2016-10-06 11:06:21 -07:00
|
|
|
rs.lastcols = nil
|
|
|
|
|
nextResultSet, ok := rs.rowsi.(driver.RowsNextResultSet)
|
|
|
|
|
if !ok {
|
2017-02-07 10:19:02 -08:00
|
|
|
doClose = true
|
2016-10-06 11:06:21 -07:00
|
|
|
return false
|
|
|
|
|
}
|
2017-10-17 15:59:56 -07:00
|
|
|
|
|
|
|
|
// Lock the driver connection before calling the driver interface
|
|
|
|
|
// rowsi to prevent a Tx from rolling back the connection at the same time.
|
|
|
|
|
rs.dc.Lock()
|
|
|
|
|
defer rs.dc.Unlock()
|
|
|
|
|
|
2016-10-06 11:06:21 -07:00
|
|
|
rs.lasterr = nextResultSet.NextResultSet()
|
2013-08-16 11:23:35 +10:00
|
|
|
if rs.lasterr != nil {
|
2017-02-07 10:19:02 -08:00
|
|
|
doClose = true
|
2013-08-16 11:23:35 +10:00
|
|
|
return false
|
2012-01-10 12:51:27 -08:00
|
|
|
}
|
2013-08-16 11:23:35 +10:00
|
|
|
return true
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
}
|
|
|
|
|
|
2011-11-04 09:50:20 -04:00
|
|
|
// Err returns the error, if any, that was encountered during iteration.
|
2013-08-16 11:23:35 +10:00
|
|
|
// Err may be called after an explicit or implicit Close.
|
2011-11-04 09:50:20 -04:00
|
|
|
func (rs *Rows) Err() error {
|
2017-02-07 10:19:02 -08:00
|
|
|
rs.closemu.RLock()
|
|
|
|
|
defer rs.closemu.RUnlock()
|
2018-10-27 14:12:52 -07:00
|
|
|
return rs.lasterrOrErrLocked(nil)
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
}
|
|
|
|
|
|
2018-10-27 14:12:52 -07:00
|
|
|
var errRowsClosed = errors.New("sql: Rows are closed")
|
|
|
|
|
var errNoRows = errors.New("sql: no Rows available")
|
|
|
|
|
|
2011-12-15 10:14:57 -08:00
|
|
|
// Columns returns the column names.
|
2018-09-03 16:24:12 +00:00
|
|
|
// Columns returns an error if the rows are closed.
|
2011-12-15 10:14:57 -08:00
|
|
|
func (rs *Rows) Columns() ([]string, error) {
|
2017-02-07 10:19:02 -08:00
|
|
|
rs.closemu.RLock()
|
|
|
|
|
defer rs.closemu.RUnlock()
|
|
|
|
|
if rs.closed {
|
2018-10-27 14:12:52 -07:00
|
|
|
return nil, rs.lasterrOrErrLocked(errRowsClosed)
|
2011-12-15 10:14:57 -08:00
|
|
|
}
|
|
|
|
|
if rs.rowsi == nil {
|
2018-10-27 14:12:52 -07:00
|
|
|
return nil, rs.lasterrOrErrLocked(errNoRows)
|
2011-12-15 10:14:57 -08:00
|
|
|
}
|
2017-10-17 15:59:56 -07:00
|
|
|
rs.dc.Lock()
|
|
|
|
|
defer rs.dc.Unlock()
|
|
|
|
|
|
2011-12-15 10:14:57 -08:00
|
|
|
return rs.rowsi.Columns(), nil
|
|
|
|
|
}
|
|
|
|
|
|
2016-09-27 13:27:02 -07:00
|
|
|
// ColumnTypes returns column information such as column type, length,
|
|
|
|
|
// and nullable. Some information may not be available from some drivers.
|
|
|
|
|
func (rs *Rows) ColumnTypes() ([]*ColumnType, error) {
|
2017-02-07 10:19:02 -08:00
|
|
|
rs.closemu.RLock()
|
|
|
|
|
defer rs.closemu.RUnlock()
|
|
|
|
|
if rs.closed {
|
2018-10-27 14:12:52 -07:00
|
|
|
return nil, rs.lasterrOrErrLocked(errRowsClosed)
|
2016-09-27 13:27:02 -07:00
|
|
|
}
|
|
|
|
|
if rs.rowsi == nil {
|
2018-10-27 14:12:52 -07:00
|
|
|
return nil, rs.lasterrOrErrLocked(errNoRows)
|
2016-09-27 13:27:02 -07:00
|
|
|
}
|
2017-10-17 15:59:56 -07:00
|
|
|
rs.dc.Lock()
|
|
|
|
|
defer rs.dc.Unlock()
|
|
|
|
|
|
|
|
|
|
return rowsColumnInfoSetupConnLocked(rs.rowsi), nil
|
2016-09-27 13:27:02 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// ColumnType contains the name and type of a column.
|
|
|
|
|
type ColumnType struct {
|
|
|
|
|
name string
|
|
|
|
|
|
|
|
|
|
hasNullable bool
|
|
|
|
|
hasLength bool
|
|
|
|
|
hasPrecisionScale bool
|
|
|
|
|
|
|
|
|
|
nullable bool
|
|
|
|
|
length int64
|
|
|
|
|
databaseType string
|
|
|
|
|
precision int64
|
|
|
|
|
scale int64
|
|
|
|
|
scanType reflect.Type
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Name returns the name or alias of the column.
|
|
|
|
|
func (ci *ColumnType) Name() string {
|
|
|
|
|
return ci.name
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Length returns the column type length for variable length column types such
|
|
|
|
|
// as text and binary field types. If the type length is unbounded the value will
|
|
|
|
|
// be math.MaxInt64 (any database limits will still apply).
|
|
|
|
|
// If the column type is not variable length, such as an int, or if not supported
|
|
|
|
|
// by the driver ok is false.
|
|
|
|
|
func (ci *ColumnType) Length() (length int64, ok bool) {
|
|
|
|
|
return ci.length, ci.hasLength
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// DecimalSize returns the scale and precision of a decimal type.
|
|
|
|
|
// If not applicable or if not supported ok is false.
|
|
|
|
|
func (ci *ColumnType) DecimalSize() (precision, scale int64, ok bool) {
|
|
|
|
|
return ci.precision, ci.scale, ci.hasPrecisionScale
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// ScanType returns a Go type suitable for scanning into using Rows.Scan.
|
|
|
|
|
// If a driver does not support this property ScanType will return
|
|
|
|
|
// the type of an empty interface.
|
|
|
|
|
func (ci *ColumnType) ScanType() reflect.Type {
|
|
|
|
|
return ci.scanType
|
|
|
|
|
}
|
|
|
|
|
|
2018-11-22 11:46:44 +01:00
|
|
|
// Nullable reports whether the column may be null.
|
2016-09-27 13:27:02 -07:00
|
|
|
// If a driver does not support this property ok will be false.
|
|
|
|
|
func (ci *ColumnType) Nullable() (nullable, ok bool) {
|
|
|
|
|
return ci.nullable, ci.hasNullable
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// DatabaseTypeName returns the database system name of the column type. If an empty
|
|
|
|
|
// string is returned the driver type name is not supported.
|
|
|
|
|
// Consult your driver documentation for a list of driver data types. Length specifiers
|
|
|
|
|
// are not included.
|
|
|
|
|
// Common type include "VARCHAR", "TEXT", "NVARCHAR", "DECIMAL", "BOOL", "INT", "BIGINT".
|
|
|
|
|
func (ci *ColumnType) DatabaseTypeName() string {
|
|
|
|
|
return ci.databaseType
|
|
|
|
|
}
|
|
|
|
|
|
2017-10-17 15:59:56 -07:00
|
|
|
func rowsColumnInfoSetupConnLocked(rowsi driver.Rows) []*ColumnType {
|
2016-09-27 13:27:02 -07:00
|
|
|
names := rowsi.Columns()
|
|
|
|
|
|
|
|
|
|
list := make([]*ColumnType, len(names))
|
|
|
|
|
for i := range list {
|
|
|
|
|
ci := &ColumnType{
|
|
|
|
|
name: names[i],
|
|
|
|
|
}
|
|
|
|
|
list[i] = ci
|
|
|
|
|
|
|
|
|
|
if prop, ok := rowsi.(driver.RowsColumnTypeScanType); ok {
|
|
|
|
|
ci.scanType = prop.ColumnTypeScanType(i)
|
|
|
|
|
} else {
|
|
|
|
|
ci.scanType = reflect.TypeOf(new(interface{})).Elem()
|
|
|
|
|
}
|
|
|
|
|
if prop, ok := rowsi.(driver.RowsColumnTypeDatabaseTypeName); ok {
|
|
|
|
|
ci.databaseType = prop.ColumnTypeDatabaseTypeName(i)
|
|
|
|
|
}
|
|
|
|
|
if prop, ok := rowsi.(driver.RowsColumnTypeLength); ok {
|
|
|
|
|
ci.length, ci.hasLength = prop.ColumnTypeLength(i)
|
|
|
|
|
}
|
|
|
|
|
if prop, ok := rowsi.(driver.RowsColumnTypeNullable); ok {
|
|
|
|
|
ci.nullable, ci.hasNullable = prop.ColumnTypeNullable(i)
|
|
|
|
|
}
|
|
|
|
|
if prop, ok := rowsi.(driver.RowsColumnTypePrecisionScale); ok {
|
|
|
|
|
ci.precision, ci.scale, ci.hasPrecisionScale = prop.ColumnTypePrecisionScale(i)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return list
|
|
|
|
|
}
|
|
|
|
|
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
// Scan copies the columns in the current row into the values pointed
|
2016-01-26 20:58:00 +00:00
|
|
|
// at by dest. The number of values in dest must be the same as the
|
|
|
|
|
// number of columns in Rows.
|
2012-01-17 10:44:35 -08:00
|
|
|
//
|
2016-01-26 20:58:00 +00:00
|
|
|
// Scan converts columns read from the database into the following
|
|
|
|
|
// common Go types and special types provided by the sql package:
|
|
|
|
|
//
|
|
|
|
|
// *string
|
|
|
|
|
// *[]byte
|
|
|
|
|
// *int, *int8, *int16, *int32, *int64
|
|
|
|
|
// *uint, *uint8, *uint16, *uint32, *uint64
|
|
|
|
|
// *bool
|
|
|
|
|
// *float32, *float64
|
|
|
|
|
// *interface{}
|
|
|
|
|
// *RawBytes
|
2018-10-29 16:22:37 -07:00
|
|
|
// *Rows (cursor value)
|
2016-01-26 20:58:00 +00:00
|
|
|
// any type implementing Scanner (see Scanner docs)
|
|
|
|
|
//
|
|
|
|
|
// In the most simple case, if the type of the value from the source
|
|
|
|
|
// column is an integer, bool or string type T and dest is of type *T,
|
|
|
|
|
// Scan simply assigns the value through the pointer.
|
|
|
|
|
//
|
|
|
|
|
// Scan also converts between string and numeric types, as long as no
|
|
|
|
|
// information would be lost. While Scan stringifies all numbers
|
|
|
|
|
// scanned from numeric database columns into *string, scans into
|
|
|
|
|
// numeric types are checked for overflow. For example, a float64 with
|
|
|
|
|
// value 300 or a string with value "300" can scan into a uint16, but
|
|
|
|
|
// not into a uint8, though float64(255) or "255" can scan into a
|
|
|
|
|
// uint8. One exception is that scans of some float64 numbers to
|
|
|
|
|
// strings may lose information when stringifying. In general, scan
|
|
|
|
|
// floating point columns into *float64.
|
|
|
|
|
//
|
|
|
|
|
// If a dest argument has type *[]byte, Scan saves in that argument a
|
|
|
|
|
// copy of the corresponding data. The copy is owned by the caller and
|
|
|
|
|
// can be modified and held indefinitely. The copy can be avoided by
|
|
|
|
|
// using an argument of type *RawBytes instead; see the documentation
|
|
|
|
|
// for RawBytes for restrictions on its use.
|
2012-02-06 10:06:22 -08:00
|
|
|
//
|
|
|
|
|
// If an argument has type *interface{}, Scan copies the value
|
2016-01-26 20:58:00 +00:00
|
|
|
// provided by the underlying driver without conversion. When scanning
|
|
|
|
|
// from a source value of type []byte to *interface{}, a copy of the
|
|
|
|
|
// slice is made and the caller owns the result.
|
|
|
|
|
//
|
|
|
|
|
// Source values of type time.Time may be scanned into values of type
|
|
|
|
|
// *time.Time, *interface{}, *string, or *[]byte. When converting to
|
2018-03-26 18:58:53 -04:00
|
|
|
// the latter two, time.RFC3339Nano is used.
|
2016-01-26 20:58:00 +00:00
|
|
|
//
|
|
|
|
|
// Source values of type bool may be scanned into types *bool,
|
|
|
|
|
// *interface{}, *string, *[]byte, or *RawBytes.
|
|
|
|
|
//
|
|
|
|
|
// For scanning into *bool, the source may be true, false, 1, 0, or
|
|
|
|
|
// string inputs parseable by strconv.ParseBool.
|
2018-10-29 16:22:37 -07:00
|
|
|
//
|
|
|
|
|
// Scan can also convert a cursor returned from a query, such as
|
|
|
|
|
// "select cursor(select * from my_table) from dual", into a
|
|
|
|
|
// *Rows value that can itself be scanned from. The parent
|
|
|
|
|
// select query will close any cursor *Rows if the parent *Rows is closed.
|
2011-11-01 22:04:37 -04:00
|
|
|
func (rs *Rows) Scan(dest ...interface{}) error {
|
2017-02-07 10:19:02 -08:00
|
|
|
rs.closemu.RLock()
|
2018-04-02 22:15:59 -07:00
|
|
|
|
|
|
|
|
if rs.lasterr != nil && rs.lasterr != io.EOF {
|
|
|
|
|
rs.closemu.RUnlock()
|
|
|
|
|
return rs.lasterr
|
|
|
|
|
}
|
2017-02-07 10:19:02 -08:00
|
|
|
if rs.closed {
|
2018-10-27 14:12:52 -07:00
|
|
|
err := rs.lasterrOrErrLocked(errRowsClosed)
|
2017-02-07 10:19:02 -08:00
|
|
|
rs.closemu.RUnlock()
|
2018-10-27 14:12:52 -07:00
|
|
|
return err
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
}
|
2017-02-07 10:19:02 -08:00
|
|
|
rs.closemu.RUnlock()
|
|
|
|
|
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
if rs.lastcols == nil {
|
2011-12-15 10:14:57 -08:00
|
|
|
return errors.New("sql: Scan called without calling Next")
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
}
|
|
|
|
|
if len(dest) != len(rs.lastcols) {
|
2011-12-15 10:14:57 -08:00
|
|
|
return fmt.Errorf("sql: expected %d destination arguments in Scan, not %d", len(rs.lastcols), len(dest))
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
}
|
|
|
|
|
for i, sv := range rs.lastcols {
|
2018-10-29 16:22:37 -07:00
|
|
|
err := convertAssignRows(dest[i], sv, rs)
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
if err != nil {
|
2018-01-07 15:08:59 +01:00
|
|
|
return fmt.Errorf(`sql: Scan error on column index %d, name %q: %v`, i, rs.rowsi.Columns()[i], err)
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
2017-01-20 17:12:50 -08:00
|
|
|
// rowsCloseHook returns a function so tests may install the
|
2017-01-26 13:41:56 -08:00
|
|
|
// hook through a test only mutex.
|
2017-01-20 17:12:50 -08:00
|
|
|
var rowsCloseHook = func() func(*Rows, *error) { return nil }
|
2013-08-13 14:56:40 -07:00
|
|
|
|
2016-10-16 23:11:55 -07:00
|
|
|
// Close closes the Rows, preventing further enumeration. If Next is called
|
|
|
|
|
// and returns false and there are no further result sets,
|
|
|
|
|
// the Rows are closed automatically and it will suffice to check the
|
2013-08-16 11:23:35 +10:00
|
|
|
// result of Err. Close is idempotent and does not affect the result of Err.
|
2011-11-01 22:04:37 -04:00
|
|
|
func (rs *Rows) Close() error {
|
2017-02-07 10:19:02 -08:00
|
|
|
return rs.close(nil)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (rs *Rows) close(err error) error {
|
|
|
|
|
rs.closemu.Lock()
|
|
|
|
|
defer rs.closemu.Unlock()
|
|
|
|
|
|
|
|
|
|
if rs.closed {
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
return nil
|
|
|
|
|
}
|
2017-02-07 10:19:02 -08:00
|
|
|
rs.closed = true
|
|
|
|
|
|
|
|
|
|
if rs.lasterr == nil {
|
|
|
|
|
rs.lasterr = err
|
|
|
|
|
}
|
2017-01-20 17:12:50 -08:00
|
|
|
|
2017-06-10 22:02:53 -07:00
|
|
|
withLock(rs.dc, func() {
|
|
|
|
|
err = rs.rowsi.Close()
|
|
|
|
|
})
|
2017-01-20 17:12:50 -08:00
|
|
|
if fn := rowsCloseHook(); fn != nil {
|
2013-08-13 14:56:40 -07:00
|
|
|
fn(rs, &err)
|
|
|
|
|
}
|
2017-01-20 17:12:50 -08:00
|
|
|
if rs.cancel != nil {
|
|
|
|
|
rs.cancel()
|
|
|
|
|
}
|
|
|
|
|
|
2012-01-13 15:25:07 -08:00
|
|
|
if rs.closeStmt != nil {
|
|
|
|
|
rs.closeStmt.Close()
|
|
|
|
|
}
|
2013-04-15 14:06:41 -07:00
|
|
|
rs.releaseConn(err)
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Row is the result of calling QueryRow to select a single row.
|
|
|
|
|
type Row struct {
|
|
|
|
|
// One of these two will be non-nil:
|
2011-11-01 22:04:37 -04:00
|
|
|
err error // deferred error for easy chaining
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
rows *Rows
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Scan copies the columns from the matched row into the values
|
2016-01-26 20:58:00 +00:00
|
|
|
// pointed at by dest. See the documentation on Rows.Scan for details.
|
|
|
|
|
// If more than one row matches the query,
|
|
|
|
|
// Scan uses the first row and discards the rest. If no row matches
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
// the query, Scan returns ErrNoRows.
|
2011-11-01 22:04:37 -04:00
|
|
|
func (r *Row) Scan(dest ...interface{}) error {
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
if r.err != nil {
|
|
|
|
|
return r.err
|
|
|
|
|
}
|
2012-01-12 11:23:33 -08:00
|
|
|
|
|
|
|
|
// TODO(bradfitz): for now we need to defensively clone all
|
2012-03-10 15:21:44 -08:00
|
|
|
// []byte that the driver returned (not permitting
|
2012-01-26 15:12:48 -08:00
|
|
|
// *RawBytes in Rows.Scan), since we're about to close
|
2012-01-12 11:23:33 -08:00
|
|
|
// the Rows in our defer, when we return from this function.
|
|
|
|
|
// the contract with the driver.Next(...) interface is that it
|
|
|
|
|
// can return slices into read-only temporary memory that's
|
2016-03-01 23:21:55 +00:00
|
|
|
// only valid until the next Scan/Close. But the TODO is that
|
|
|
|
|
// for a lot of drivers, this copy will be unnecessary. We
|
2012-01-12 11:23:33 -08:00
|
|
|
// should provide an optional interface for drivers to
|
|
|
|
|
// implement to say, "don't worry, the []bytes that I return
|
|
|
|
|
// from Next will not be modified again." (for instance, if
|
|
|
|
|
// they were obtained from the network anyway) But for now we
|
|
|
|
|
// don't care.
|
2013-10-16 09:17:25 -07:00
|
|
|
defer r.rows.Close()
|
2012-01-12 11:23:33 -08:00
|
|
|
for _, dp := range dest {
|
2012-01-17 10:44:35 -08:00
|
|
|
if _, ok := dp.(*RawBytes); ok {
|
|
|
|
|
return errors.New("sql: RawBytes isn't allowed on Row.Scan")
|
|
|
|
|
}
|
2012-01-12 11:23:33 -08:00
|
|
|
}
|
2012-01-26 15:12:48 -08:00
|
|
|
|
|
|
|
|
if !r.rows.Next() {
|
2013-12-16 12:48:35 -08:00
|
|
|
if err := r.rows.Err(); err != nil {
|
|
|
|
|
return err
|
|
|
|
|
}
|
2012-01-26 15:12:48 -08:00
|
|
|
return ErrNoRows
|
|
|
|
|
}
|
|
|
|
|
err := r.rows.Scan(dest...)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return err
|
|
|
|
|
}
|
2013-12-16 12:48:35 -08:00
|
|
|
// Make sure the query can be processed to completion with no errors.
|
2018-04-11 19:20:10 -07:00
|
|
|
return r.rows.Close()
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
}
|
|
|
|
|
|
2020-01-10 12:06:53 +02:00
|
|
|
// Err provides a way for wrapping packages to check for
|
|
|
|
|
// query errors without calling Scan.
|
|
|
|
|
// Err returns the error, if any, that was encountered while running the query.
|
|
|
|
|
// If this error is not nil, this error will also be returned from Scan.
|
|
|
|
|
func (r *Row) Err() error {
|
|
|
|
|
return r.err
|
|
|
|
|
}
|
|
|
|
|
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
// A Result summarizes an executed SQL command.
|
|
|
|
|
type Result interface {
|
2013-10-29 17:38:43 -07:00
|
|
|
// LastInsertId returns the integer generated by the database
|
|
|
|
|
// in response to a command. Typically this will be from an
|
|
|
|
|
// "auto increment" column when inserting a new row. Not all
|
|
|
|
|
// databases support this feature, and the syntax of such
|
|
|
|
|
// statements varies.
|
2011-11-01 22:04:37 -04:00
|
|
|
LastInsertId() (int64, error)
|
2013-10-29 17:38:43 -07:00
|
|
|
|
|
|
|
|
// RowsAffected returns the number of rows affected by an
|
|
|
|
|
// update, insert, or delete. Not every database or database
|
|
|
|
|
// driver may support this.
|
2011-11-01 22:04:37 -04:00
|
|
|
RowsAffected() (int64, error)
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
}
|
|
|
|
|
|
2013-03-14 15:01:45 -07:00
|
|
|
type driverResult struct {
|
|
|
|
|
sync.Locker // the *driverConn
|
|
|
|
|
resi driver.Result
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (dr driverResult) LastInsertId() (int64, error) {
|
|
|
|
|
dr.Lock()
|
|
|
|
|
defer dr.Unlock()
|
|
|
|
|
return dr.resi.LastInsertId()
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (dr driverResult) RowsAffected() (int64, error) {
|
|
|
|
|
dr.Lock()
|
|
|
|
|
defer dr.Unlock()
|
|
|
|
|
return dr.resi.RowsAffected()
|
exp/sql{,/driver}: new database packages
R=gustavo, rsc, borman, dave, kevlar, nigeltao, dvyukov, kardianos, fw, r, r, david.crawshaw
CC=golang-dev
https://golang.org/cl/4973055
2011-09-29 16:12:21 -07:00
|
|
|
}
|
2013-02-20 15:35:27 -08:00
|
|
|
|
|
|
|
|
func stack() string {
|
database/sql: fix driver Conn refcounting with prepared statements
The refcounting of driver Conns was completedly busted and
would leak (be held open forever) with any reasonable
load. This was a significant regression from Go 1.0.
The core of this patch is removing one line:
s.db.addDep(dc, s)
A database conn (dc) is a resource that be re-created any time
(but cached for speed) should not be held open forever with a
dependency refcount just because the Stmt (s) is alive (which
typically last for long periods of time, like forever).
The meat of the patch is new tests. In fixing the real issue,
a lot of tests then failed due to the fakedb_test.go's paranoia
about closing a fakeConn while it has open fakeStmts on it. I
could've ignored that, but that's been a problem in the past for
other bugs.
Instead, I now track per-Conn open statements and close them
when the the conn closes. The proper way to do this would've
been making *driverStmt a finalCloser and using the dep mechanism,
but it was much more invasive. Added a TODO instead.
I'd like to give a way for drivers to opt-out of caring about
driver.Stmt closes before a driver.Conn close, but that's a TODO
for the future, and that TODO is added in this CL.
I know this is very late for Go 1.1, but database/sql is
currently nearly useless without this.
I'd like to believe all these database/sql bugs in the past
release cycle are the result of increased usage, number of
drivers, and good feedback from increasingly-capable Go
developers, and not the result of me sucking. It's also hard
with all the real drivers being out-of-tree, so I'm having to
add more and more hooks to fakedb_test.go to simulate things
which real drivers end up doing.
Fixes #5323
R=golang-dev, snaury, gwenn.kahz, google, r
CC=golang-dev
https://golang.org/cl/8836045
2013-04-25 14:45:56 -07:00
|
|
|
var buf [2 << 10]byte
|
2013-02-20 15:35:27 -08:00
|
|
|
return string(buf[:runtime.Stack(buf[:], false)])
|
|
|
|
|
}
|
2013-03-14 15:01:45 -07:00
|
|
|
|
|
|
|
|
// withLock runs while holding lk.
|
|
|
|
|
func withLock(lk sync.Locker, fn func()) {
|
|
|
|
|
lk.Lock()
|
2015-12-18 12:16:05 -05:00
|
|
|
defer lk.Unlock() // in case fn panics
|
2013-03-14 15:01:45 -07:00
|
|
|
fn()
|
|
|
|
|
}
|