sql

Imports

Imports #

"bytes"
"database/sql/driver"
"errors"
"fmt"
"reflect"
"strconv"
"time"
"unicode"
"unicode/utf8"
_ "unsafe"
"context"
"database/sql/driver"
"errors"
"context"
"database/sql/driver"
"errors"
"fmt"
"io"
"maps"
"math/rand/v2"
"reflect"
"runtime"
"slices"
"strconv"
"sync"
"sync/atomic"
"time"
_ "unsafe"

Constants & Variables

ErrConnDone var #

ErrConnDone is returned by any operation that is performed on a connection that has already been returned to the connection pool.

var ErrConnDone = *ast.CallExpr

ErrNoRows var #

ErrNoRows is returned by [Row.Scan] when [DB.QueryRow] doesn't return a row. In such a case, QueryRow returns a placeholder [*Row] value that defers this error until a Scan.

var ErrNoRows = *ast.CallExpr

ErrTxDone var #

ErrTxDone is returned by any operation that is performed on a transaction that has already been committed or rolled back.

var ErrTxDone = *ast.CallExpr

LevelDefault const #

Various isolation levels that drivers may support in [DB.BeginTx]. If a driver does not support a given isolation level an error may be returned. See https://en.wikipedia.org/wiki/Isolation_(database_systems)#Isolation_levels.

const LevelDefault IsolationLevel = iota

LevelLinearizable const #

Various isolation levels that drivers may support in [DB.BeginTx]. If a driver does not support a given isolation level an error may be returned. See https://en.wikipedia.org/wiki/Isolation_(database_systems)#Isolation_levels.

const LevelLinearizable

LevelReadCommitted const #

Various isolation levels that drivers may support in [DB.BeginTx]. If a driver does not support a given isolation level an error may be returned. See https://en.wikipedia.org/wiki/Isolation_(database_systems)#Isolation_levels.

const LevelReadCommitted

LevelReadUncommitted const #

Various isolation levels that drivers may support in [DB.BeginTx]. If a driver does not support a given isolation level an error may be returned. See https://en.wikipedia.org/wiki/Isolation_(database_systems)#Isolation_levels.

const LevelReadUncommitted

LevelRepeatableRead const #

Various isolation levels that drivers may support in [DB.BeginTx]. If a driver does not support a given isolation level an error may be returned. See https://en.wikipedia.org/wiki/Isolation_(database_systems)#Isolation_levels.

const LevelRepeatableRead

LevelSerializable const #

Various isolation levels that drivers may support in [DB.BeginTx]. If a driver does not support a given isolation level an error may be returned. See https://en.wikipedia.org/wiki/Isolation_(database_systems)#Isolation_levels.

const LevelSerializable

LevelSnapshot const #

Various isolation levels that drivers may support in [DB.BeginTx]. If a driver does not support a given isolation level an error may be returned. See https://en.wikipedia.org/wiki/Isolation_(database_systems)#Isolation_levels.

const LevelSnapshot

LevelWriteCommitted const #

Various isolation levels that drivers may support in [DB.BeginTx]. If a driver does not support a given isolation level an error may be returned. See https://en.wikipedia.org/wiki/Isolation_(database_systems)#Isolation_levels.

const LevelWriteCommitted

_ var #

var _ stmtConnGrabber = *ast.UnaryExpr

_ var #

var _ fmt.Stringer = LevelDefault

_ var #

var _ stmtConnGrabber = *ast.UnaryExpr

alwaysNewConn const #

alwaysNewConn forces a new connection to the database.

const alwaysNewConn connReuseStrategy = iota

bypassRowsAwaitDone var #

bypassRowsAwaitDone is only used for testing. If true, it will not close the Rows automatically from the context.

var bypassRowsAwaitDone = false

cachedOrNewConn const #

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.

const cachedOrNewConn

connectionRequestQueueSize var #

This is the size of the connectionOpener request chan (DB.openerCh). 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 to block until the connectionOpener can satisfy the backlog of requests.

var connectionRequestQueueSize = 1000000

debugGetPut const #

debugGetPut determines whether getConn & putConn calls' stack traces are returned for more verbose crashes.

const debugGetPut = false

defaultMaxIdleConns const #

const defaultMaxIdleConns = 2

drivers var #

drivers should be an internal detail, but widely used packages access it using linkname. (It is extra wrong that they linkname drivers but not driversMu.) Notable members of the hall of shame include: - github.com/instana/go-sensor Do not remove or change the type signature. See go.dev/issue/67401. go:linkname drivers

var drivers = *ast.CallExpr

driversMu var #

var driversMu sync.RWMutex

errDBClosed var #

var errDBClosed = *ast.CallExpr

errNilPtr var #

var errNilPtr = *ast.CallExpr

errNoRows var #

var errNoRows = *ast.CallExpr

errRowsClosed var #

var errRowsClosed = *ast.CallExpr

hookTxGrabConn var #

hookTxGrabConn specifies an optional hook to be called on a successful call to (*Tx).grabConn. For tests.

var hookTxGrabConn func()

maxBadConnRetries const #

maxBadConnRetries is the number of maximum retries if the driver returns driver.ErrBadConn to signal a broken connection before forcing a new connection to be opened.

const maxBadConnRetries = 2

nowFunc var #

nowFunc returns the current time; it's overridden in tests.

var nowFunc = time.Now

putConnHook var #

putConnHook is a hook for testing.

var putConnHook func(*DB, *driverConn)

rollbackHook var #

var rollbackHook func()

rowsCloseHook var #

rowsCloseHook returns a function so tests may install the hook through a test only mutex.

var rowsCloseHook = *ast.FuncLit

valuerReflectType var #

var valuerReflectType = *ast.CallExpr

Type Aliases

IsolationLevel type #

IsolationLevel is the transaction isolation level used in [TxOptions].

type IsolationLevel int

RawBytes type #

RawBytes is a byte slice that holds a reference to memory owned by the database itself. After a [Rows.Scan] into a RawBytes, the slice is only valid until the next call to [Rows.Next], [Rows.Scan], or [Rows.Close].

type RawBytes []byte

connReuseStrategy type #

connReuseStrategy determines how (*DB).conn returns database connections.

type connReuseStrategy uint8

depSet type #

depSet is a finalCloser's outstanding dependencies

type depSet map[any]bool

releaseConn type #

type releaseConn func(error)

Interfaces

Result interface #

A Result summarizes an executed SQL command.

type Result interface {
LastInsertId() (int64, error)
RowsAffected() (int64, error)
}

Scanner interface #

Scanner is an interface used by [Rows.Scan].

type Scanner interface {
Scan(src any) error
}

decimal interface #

decimal composes or decomposes a decimal value to and from individual parts. There are four parts: a boolean negative flag, a form byte with three possible states (finite=0, infinite=1, NaN=2), a base-2 big-endian integer coefficient (also known as a significand) as a []byte, and an int32 exponent. These are composed into a final value as "decimal = (neg) (form=finite) coefficient * 10 ^ exponent". A zero length coefficient is a zero value. The big-endian integer coefficient stores the most significant byte first (at coefficient[0]). If the form is not finite the coefficient and exponent should be ignored. The negative parameter may be set to true for any form, although implementations are not required to respect the negative parameter in the non-finite form. Implementations may choose to set the negative parameter to true on a zero or NaN value, but implementations that do not differentiate between negative and positive zero or NaN values should ignore the negative parameter without error. If an implementation does not support Infinity it may be converted into a NaN without error. If a value is set that is larger than what is supported by an implementation, an error must be returned. Implementations must return an error if a NaN or Infinity is attempted to be set while neither are supported. NOTE(kardianos): This is an experimental interface. See https://golang.org/issue/30870

type decimal interface {
decimalDecompose
decimalCompose
}

decimalCompose interface #

type decimalCompose interface {
Compose(form byte, negative bool, coefficient []byte, exponent int32) error
}

decimalDecompose interface #

type decimalDecompose interface {
Decompose(buf []byte) (form byte, negative bool, coefficient []byte, exponent int32)
}

finalCloser interface #

The finalCloser interface is used by (*DB).addDep and related dependency reference counting.

type finalCloser interface {
finalClose() error
}

stmtConnGrabber interface #

stmtConnGrabber represents a Tx or Conn that will return the underlying driverConn and release function.

type stmtConnGrabber interface {
grabConn(context.Context) (*driverConn, releaseConn, error)
txCtx() context.Context
}

Structs

ColumnType struct #

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
}

Conn struct #

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. A Conn must call [Conn.Close] to return the connection to the database pool and may do so concurrently with a running query. After a call to [Conn.Close], all operations on the connection fail with [ErrConnDone].

type Conn struct {
db *DB
closemu sync.RWMutex
dc *driverConn
done atomic.Bool
releaseConnOnce sync.Once
releaseConnCache releaseConn
}

DB struct #

DB is a database handle representing a pool of zero or more underlying connections. It's safe for concurrent use by multiple goroutines. The sql package creates and frees connections automatically; it also maintains a free pool of idle connections. If the database has 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 returned [Tx] is bound to a single connection. Once [Tx.Commit] or [Tx.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 [DB.SetMaxIdleConns].

type DB struct {
waitDuration atomic.Int64
connector driver.Connector
numClosed atomic.Uint64
mu sync.Mutex
freeConn []*driverConn
connRequests connRequestSet
numOpen int
openerCh chan struct{...}
closed bool
dep map[finalCloser]depSet
lastPut map[*driverConn]string
maxIdleCount int
maxOpen int
maxLifetime time.Duration
maxIdleTime time.Duration
cleanerCh chan struct{...}
waitCount int64
maxIdleClosed int64
maxIdleTimeClosed int64
maxLifetimeClosed int64
stop func()
}

DBStats struct #

DBStats contains database statistics.

type DBStats struct {
MaxOpenConnections int
OpenConnections int
InUse int
Idle int
WaitCount int64
WaitDuration time.Duration
MaxIdleClosed int64
MaxIdleTimeClosed int64
MaxLifetimeClosed int64
}

NamedArg struct #

A NamedArg is a named argument. NamedArg values may be used as arguments to [DB.Query] or [DB.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.

type NamedArg struct {
_NamedFieldsRequired struct{...}
Name string
Value any
}

Null struct #

Null represents a value that may be null. Null implements the [Scanner] interface so it can be used as a scan destination: var s Null[string] err := db.QueryRow("SELECT name FROM foo WHERE id=?", id).Scan(&s) ... if s.Valid { // use s.V } else { // NULL value } T should be one of the types accepted by [driver.Value].

type Null struct {
V T
Valid bool
}

NullBool struct #

NullBool represents a bool that may be null. NullBool implements the [Scanner] interface so it can be used as a scan destination, similar to [NullString].

type NullBool struct {
Bool bool
Valid bool
}

NullByte struct #

NullByte represents a byte that may be null. NullByte implements the [Scanner] interface so it can be used as a scan destination, similar to [NullString].

type NullByte struct {
Byte byte
Valid bool
}

NullFloat64 struct #

NullFloat64 represents a float64 that may be null. NullFloat64 implements the [Scanner] interface so it can be used as a scan destination, similar to [NullString].

type NullFloat64 struct {
Float64 float64
Valid bool
}

NullInt16 struct #

NullInt16 represents an int16 that may be null. NullInt16 implements the [Scanner] interface so it can be used as a scan destination, similar to [NullString].

type NullInt16 struct {
Int16 int16
Valid bool
}

NullInt32 struct #

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
}

NullInt64 struct #

NullInt64 represents an int64 that may be null. NullInt64 implements the [Scanner] interface so it can be used as a scan destination, similar to [NullString].

type NullInt64 struct {
Int64 int64
Valid bool
}

NullString struct #

NullString represents a string that may be null. NullString implements the [Scanner] interface so it can be used as a scan destination: var s NullString err := db.QueryRow("SELECT name FROM foo WHERE id=?", id).Scan(&s) ... if s.Valid { // use s.String } else { // NULL value }

type NullString struct {
String string
Valid bool
}

NullTime struct #

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
}

Out struct #

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 _, err := db.ExecContext(ctx, "ProcName", sql.Named("Arg1", sql.Out{Dest: &outArg}))

type Out struct {
_NamedFieldsRequired struct{...}
Dest any
In bool
}

Row struct #

Row is the result of calling [DB.QueryRow] to select a single row.

type Row struct {
err error
rows *Rows
}

Rows struct #

Rows is the result of a query. Its cursor starts before the first row of the result set. Use [Rows.Next] to advance from row to row.

type Rows struct {
dc *driverConn
releaseConn func(error)
rowsi driver.Rows
cancel func()
closeStmt *driverStmt
contextDone *ast.IndexExpr
closemu sync.RWMutex
lasterr error
closed bool
closemuScanHold bool
hitEOF bool
lastcols []driver.Value
raw []byte
}

Stmt struct #

Stmt is a prepared statement. A Stmt is safe for concurrent use by multiple goroutines. 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.

type Stmt struct {
db *DB
query string
stickyErr error
closemu sync.RWMutex
cg stmtConnGrabber
cgds *driverStmt
parentStmt *Stmt
mu sync.Mutex
closed bool
css []connStmt
lastNumClosed uint64
}

Tx struct #

Tx is an in-progress database transaction. A transaction must end with a call to [Tx.Commit] or [Tx.Rollback]. After a call to [Tx.Commit] or [Tx.Rollback], all operations on the transaction fail with [ErrTxDone]. The statements prepared for a transaction by calling the transaction's [Tx.Prepare] or [Tx.Stmt] methods are closed by the call to [Tx.Commit] or [Tx.Rollback].

type Tx struct {
db *DB
closemu sync.RWMutex
dc *driverConn
txi driver.Tx
releaseConn func(error)
done atomic.Bool
keepConnOnRollback bool
stmts struct{...}
cancel func()
ctx context.Context
}

TxOptions struct #

TxOptions holds the transaction options to be used in [DB.BeginTx].

type TxOptions struct {
Isolation IsolationLevel
ReadOnly bool
}

ccChecker struct #

ccChecker wraps the driver.ColumnConverter and allows it to be used as if it were a NamedValueChecker. If the driver ColumnConverter is not present then the NamedValueChecker will return driver.ErrSkip.

type ccChecker struct {
cci driver.ColumnConverter
want int
}

connRequest struct #

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.

type connRequest struct {
conn *driverConn
err error
}

connRequestAndIndex struct #

type connRequestAndIndex struct {
req chan connRequest
curIdx *int
}

connRequestDelHandle struct #

connRequestDelHandle is an opaque handle to delete an item from calling Add.

type connRequestDelHandle struct {
idx *int
}

connRequestSet struct #

connRequestSet is a set of chan connRequest that's optimized for: - adding an element - removing an element (only by the caller who added it) - taking (get + delete) a random element We previously used a map for this but the take of a random element was expensive, making mapiters. This type avoids a map entirely and just uses a slice.

type connRequestSet struct {
s []connRequestAndIndex
}

connStmt struct #

connStmt is a prepared statement on a particular connection.

type connStmt struct {
dc *driverConn
ds *driverStmt
}

driverConn struct #

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 {
db *DB
createdAt time.Time
sync.Mutex
ci driver.Conn
needReset bool
closed bool
finalClosed bool
openStmt map[*driverStmt]bool
inUse bool
dbmuClosed bool
returnedAt time.Time
onPut []func()
}

driverResult struct #

type driverResult struct {
sync.Locker
resi driver.Result
}

driverStmt struct #

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
si driver.Stmt
closed bool
closeErr error
}

dsnConnector struct #

type dsnConnector struct {
dsn string
driver driver.Driver
}

Functions

Add method #

Add adds v to the set of waiting requests. The returned connRequestDelHandle can be used to remove the item from the set.

func (s *connRequestSet) Add(v chan connRequest) connRequestDelHandle

Begin method #

Begin starts a transaction. The default isolation level is dependent on the driver. Begin uses [context.Background] internally; to specify the context, use [DB.BeginTx].

func (db *DB) Begin() (*Tx, error)

BeginTx method #

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)

BeginTx method #

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 (db *DB) BeginTx(ctx context.Context, opts *TxOptions) (*Tx, error)

CheckNamedValue method #

func (c ccChecker) CheckNamedValue(nv *driver.NamedValue) error

Close method #

Close closes the statement.

func (s *Stmt) Close() error

Close method #

func (dc *driverConn) Close() error

Close method #

Close closes the [Rows], preventing further enumeration. If [Rows.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 result of [Rows.Err]. Close is idempotent and does not affect the result of [Rows.Err].

func (rs *Rows) Close() error

Close method #

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. It is rare to Close a [DB], as the [DB] handle is meant to be long-lived and shared between many goroutines.

func (db *DB) Close() error

Close method #

Close ensures driver.Stmt is only closed once and always returns the same result.

func (ds *driverStmt) Close() error

Close method #

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

CloseAndRemoveAll method #

CloseAndRemoveAll closes all channels in the set and clears the set.

func (s *connRequestSet) CloseAndRemoveAll()

ColumnTypes method #

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)

Columns method #

Columns returns the column names. Columns returns an error if the rows are closed.

func (rs *Rows) Columns() ([]string, error)

Commit method #

Commit commits the transaction.

func (tx *Tx) Commit() error

Conn method #

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)

Connect method #

func (t dsnConnector) Connect(_ context.Context) (driver.Conn, error)

DatabaseTypeName method #

DatabaseTypeName returns the database system name of the column type. If an empty string is returned, then the driver type name is not supported. Consult your driver documentation for a list of driver data types. [ColumnType.Length] specifiers are not included. Common type names include "VARCHAR", "TEXT", "NVARCHAR", "DECIMAL", "BOOL", "INT", and "BIGINT".

func (ci *ColumnType) DatabaseTypeName() string

DecimalSize method #

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 int64, scale int64, ok bool)

Delete method #

Delete removes an element from the set. It reports whether the element was deleted. (It can return false if a caller of TakeRandom took it meanwhile, or upon the second call to Delete)

func (s *connRequestSet) Delete(h connRequestDelHandle) bool

Driver method #

func (t dsnConnector) Driver() driver.Driver

Driver method #

Driver returns the database's underlying driver.

func (db *DB) Driver() driver.Driver

Drivers function #

Drivers returns a sorted list of the names of the registered drivers.

func Drivers() []string

Err method #

Err returns the error, if any, that was encountered during iteration. Err may be called after an explicit or implicit [Rows.Close].

func (rs *Rows) Err() error

Err method #

Err provides a way for wrapping packages to check for query errors without calling [Row.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 [Row.Scan].

func (r *Row) Err() error

Exec method #

Exec executes a query without returning any rows. The args are for any placeholder parameters in the query. Exec uses [context.Background] internally; to specify the context, use [DB.ExecContext].

func (db *DB) Exec(query string, args ...any) (Result, error)

Exec method #

Exec executes a query that doesn't return rows. For example: an INSERT and UPDATE. Exec uses [context.Background] internally; to specify the context, use [Tx.ExecContext].

func (tx *Tx) Exec(query string, args ...any) (Result, error)

Exec method #

Exec executes a prepared statement with the given arguments and returns a [Result] summarizing the effect of the statement. Exec uses [context.Background] internally; to specify the context, use [Stmt.ExecContext].

func (s *Stmt) Exec(args ...any) (Result, error)

ExecContext method #

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 ...any) (Result, error)

ExecContext method #

ExecContext executes a query without returning any rows. The args are for any placeholder parameters in the query.

func (db *DB) ExecContext(ctx context.Context, query string, args ...any) (Result, error)

ExecContext method #

ExecContext executes a query that doesn't return rows. For example: an INSERT and UPDATE.

func (tx *Tx) ExecContext(ctx context.Context, query string, args ...any) (Result, error)

ExecContext method #

ExecContext executes a prepared statement with the given arguments and returns a [Result] summarizing the effect of the statement.

func (s *Stmt) ExecContext(ctx context.Context, args ...any) (Result, error)

LastInsertId method #

func (dr driverResult) LastInsertId() (int64, error)

Len method #

Len returns the length of the set.

func (s *connRequestSet) Len() int

Length method #

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)

Name method #

Name returns the name or alias of the column.

func (ci *ColumnType) Name() string

Named function #

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 any) NamedArg

Next method #

Next prepares the next result row for reading with the [Rows.Scan] method. It returns true on success, or false if there is no next result row or an error happened while preparing it. [Rows.Err] should be consulted to distinguish between the two cases. Every call to [Rows.Scan], even the first one, must be preceded by a call to [Rows.Next].

func (rs *Rows) Next() bool

NextResultSet method #

NextResultSet prepares the next result set for reading. It reports whether there is further result sets, or false if there is no further result set or if there is an error advancing to it. The [Rows.Err] method should be consulted to distinguish between the two cases. After calling NextResultSet, the [Rows.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

Nullable method #

Nullable reports whether the column may be null. If a driver does not support this property ok will be false.

func (ci *ColumnType) Nullable() (nullable bool, ok bool)

Open function #

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 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. Open may just validate its arguments without creating a connection to the database. To verify that the data source name is valid, call [DB.Ping]. 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].

func Open(driverName string, dataSourceName string) (*DB, error)

OpenDB function #

OpenDB opens a database using a [driver.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 [DB.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

Ping method #

Ping verifies a connection to the database is still alive, establishing a connection if necessary. Ping uses [context.Background] internally; to specify the context, use [DB.PingContext].

func (db *DB) Ping() error

PingContext method #

PingContext verifies the connection to the database is still alive.

func (c *Conn) PingContext(ctx context.Context) error

PingContext method #

PingContext verifies a connection to the database is still alive, establishing a connection if necessary.

func (db *DB) PingContext(ctx context.Context) error

Prepare method #

Prepare creates a prepared statement for use within a transaction. The returned statement operates within the transaction and will be closed when the transaction has been committed or rolled back. To use an existing prepared statement on this transaction, see [Tx.Stmt]. Prepare uses [context.Background] internally; to specify the context, use [Tx.PrepareContext].

func (tx *Tx) Prepare(query string) (*Stmt, error)

Prepare method #

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 [*Stmt.Close] method when the statement is no longer needed. Prepare uses [context.Background] internally; to specify the context, use [DB.PrepareContext].

func (db *DB) Prepare(query string) (*Stmt, error)

PrepareContext method #

PrepareContext creates a prepared statement for use within a transaction. The returned statement operates within the transaction and will be closed when the transaction has been committed or rolled back. To use an existing prepared statement on this transaction, see [Tx.Stmt]. The provided context will be used for the preparation of the context, not 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)

PrepareContext method #

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 [*Stmt.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)

PrepareContext method #

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 [*Stmt.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 (db *DB) PrepareContext(ctx context.Context, query string) (*Stmt, error)

Query method #

Query executes a query that returns rows, typically a SELECT. The args are for any placeholder parameters in the query. Query uses [context.Background] internally; to specify the context, use [DB.QueryContext].

func (db *DB) Query(query string, args ...any) (*Rows, error)

Query method #

Query executes a prepared query statement with the given arguments and returns the query results as a *Rows. Query uses [context.Background] internally; to specify the context, use [Stmt.QueryContext].

func (s *Stmt) Query(args ...any) (*Rows, error)

Query method #

Query executes a query that returns rows, typically a SELECT. Query uses [context.Background] internally; to specify the context, use [Tx.QueryContext].

func (tx *Tx) Query(query string, args ...any) (*Rows, error)

QueryContext method #

QueryContext executes a prepared query statement with the given arguments and returns the query results as a [*Rows].

func (s *Stmt) QueryContext(ctx context.Context, args ...any) (*Rows, error)

QueryContext method #

QueryContext executes a query that returns rows, typically a SELECT.

func (tx *Tx) QueryContext(ctx context.Context, query string, args ...any) (*Rows, error)

QueryContext method #

QueryContext executes a query that returns rows, typically a SELECT. The args are for any placeholder parameters in the query.

func (db *DB) QueryContext(ctx context.Context, query string, args ...any) (*Rows, error)

QueryContext method #

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 ...any) (*Rows, error)

QueryRow method #

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.Scan] will return [ErrNoRows]. Otherwise, the [*Row.Scan] scans the first selected row and discards the rest. Example usage: var name string err := nameByUseridStmt.QueryRow(id).Scan(&name) QueryRow uses [context.Background] internally; to specify the context, use [Stmt.QueryRowContext].

func (s *Stmt) QueryRow(args ...any) *Row

QueryRow method #

QueryRow executes a query that is expected to return at most one row. QueryRow always returns a non-nil value. Errors are deferred until [Row]'s Scan method is called. If the query selects no rows, the [*Row.Scan] will return [ErrNoRows]. Otherwise, [*Row.Scan] scans the first selected row and discards the rest. QueryRow uses [context.Background] internally; to specify the context, use [DB.QueryRowContext].

func (db *DB) QueryRow(query string, args ...any) *Row

QueryRow method #

QueryRow executes a query that is expected to return at most one row. QueryRow always returns a non-nil value. Errors are deferred until [Row]'s Scan method is called. If the query selects no rows, the [*Row.Scan] will return [ErrNoRows]. Otherwise, the [*Row.Scan] scans the first selected row and discards the rest. QueryRow uses [context.Background] internally; to specify the context, use [Tx.QueryRowContext].

func (tx *Tx) QueryRow(query string, args ...any) *Row

QueryRowContext method #

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. If the query selects no rows, the [*Row.Scan] will return [ErrNoRows]. Otherwise, [*Row.Scan] scans the first selected row and discards the rest.

func (db *DB) QueryRowContext(ctx context.Context, query string, args ...any) *Row

QueryRowContext method #

QueryRowContext 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.Scan] will return [ErrNoRows]. Otherwise, the [*Row.Scan] scans the first selected row and discards the rest.

func (s *Stmt) QueryRowContext(ctx context.Context, args ...any) *Row

QueryRowContext method #

QueryRowContext executes a query that is expected to return at most one row. QueryRowContext always returns a non-nil value. Errors are deferred until the [*Row.Scan] method is called. If the query selects no rows, the [*Row.Scan] will return [ErrNoRows]. Otherwise, the [*Row.Scan] scans the first selected row and discards the rest.

func (c *Conn) QueryRowContext(ctx context.Context, query string, args ...any) *Row

QueryRowContext method #

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. If the query selects no rows, the [*Row.Scan] will return [ErrNoRows]. Otherwise, the [*Row.Scan] scans the first selected row and discards the rest.

func (tx *Tx) QueryRowContext(ctx context.Context, query string, args ...any) *Row

Raw method #

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 not [driver.ErrBadConn], the [Conn] will continue to be usable until [Conn.Close] is called.

func (c *Conn) Raw(f func(driverConn any) error) (err error)

Register function #

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)

Rollback method #

Rollback aborts the transaction.

func (tx *Tx) Rollback() error

RowsAffected method #

func (dr driverResult) RowsAffected() (int64, error)

Scan method #

Scan implements the [Scanner] interface.

func (n *NullInt32) Scan(value any) error

Scan method #

Scan implements the [Scanner] interface.

func (n *NullTime) Scan(value any) error

Scan method #

func (n **ast.IndexExpr) Scan(value any) error

Scan method #

Scan implements the [Scanner] interface.

func (n *NullBool) Scan(value any) error

Scan method #

Scan implements the [Scanner] interface.

func (n *NullFloat64) Scan(value any) error

Scan method #

Scan implements the [Scanner] interface.

func (ns *NullString) Scan(value any) error

Scan method #

Scan copies the columns in the current row into the values pointed at by dest. The number of values in dest must be the same as the number of columns in [Rows]. 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 *Rows (cursor value) 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. If an argument has type *interface{}, Scan copies the value 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 the latter two, [time.RFC3339Nano] is used. 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]. 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. If any of the first arguments implementing [Scanner] returns an error, that error will be wrapped in the returned error.

func (rs *Rows) Scan(dest ...any) error

Scan method #

Scan implements the [Scanner] interface.

func (n *NullInt16) Scan(value any) error

Scan method #

Scan implements the [Scanner] interface.

func (n *NullInt64) Scan(value any) error

Scan method #

Scan implements the [Scanner] interface.

func (n *NullByte) Scan(value any) error

Scan method #

Scan copies the columns from the matched row into the values 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 the query, Scan returns [ErrNoRows].

func (r *Row) Scan(dest ...any) error

ScanType method #

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

SetConnMaxIdleTime method #

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)

SetConnMaxLifetime method #

SetConnMaxLifetime sets the maximum amount of time a connection may be reused. Expired connections may be closed lazily before reuse. If d <= 0, connections are not closed due to a connection's age.

func (db *DB) SetConnMaxLifetime(d time.Duration)

SetMaxIdleConns method #

SetMaxIdleConns sets the maximum number of connections in the idle connection pool. If MaxOpenConns is greater than 0 but less than the new MaxIdleConns, then the new MaxIdleConns will be reduced to match the MaxOpenConns limit. If n <= 0, no idle connections are retained. The default max idle connections is currently 2. This may change in a future release.

func (db *DB) SetMaxIdleConns(n int)

SetMaxOpenConns method #

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 MaxOpenConns limit. 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)

Stats method #

Stats returns database statistics.

func (db *DB) Stats() DBStats

Stmt method #

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) The returned statement operates within the transaction and will be closed when the transaction has been committed or rolled back. Stmt uses [context.Background] internally; to specify the context, use [Tx.StmtContext].

func (tx *Tx) Stmt(stmt *Stmt) *Stmt

StmtContext method #

StmtContext 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.StmtContext(ctx, updateMoney).Exec(123.45, 98293203) The provided context is used for the preparation of the statement, not for the execution of the statement. The returned statement operates within the transaction and will be closed when the transaction has been committed or rolled back.

func (tx *Tx) StmtContext(ctx context.Context, stmt *Stmt) *Stmt

String method #

String returns the name of the transaction isolation level.

func (i IsolationLevel) String() string

TakeRandom method #

TakeRandom returns and removes a random element from s and reports whether there was one to take. (It returns ok=false if the set is empty.)

func (s *connRequestSet) TakeRandom() (v chan connRequest, ok bool)

Value method #

Value implements the [driver.Valuer] interface.

func (n NullFloat64) Value() (driver.Value, error)

Value method #

Value implements the [driver.Valuer] interface.

func (n NullByte) Value() (driver.Value, error)

Value method #

Value implements the [driver.Valuer] interface.

func (ns NullString) Value() (driver.Value, error)

Value method #

Value implements the [driver.Valuer] interface.

func (n NullInt32) Value() (driver.Value, error)

Value method #

Value implements the [driver.Valuer] interface.

func (n NullInt16) Value() (driver.Value, error)

Value method #

Value implements the [driver.Valuer] interface.

func (n NullInt64) Value() (driver.Value, error)

Value method #

Value implements the [driver.Valuer] interface.

func (n NullBool) Value() (driver.Value, error)

Value method #

func (n *ast.IndexExpr) Value() (driver.Value, error)

Value method #

Value implements the [driver.Valuer] interface.

func (n NullTime) Value() (driver.Value, error)

addDep method #

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 any)

addDepLocked method #

func (db *DB) addDepLocked(x finalCloser, dep any)

asBytes function #

func asBytes(buf []byte, rv reflect.Value) (b []byte, ok bool)

asString function #

func asString(src any) string

awaitDone method #

awaitDone blocks until ctx, txctx, or closectx is canceled. The ctx is provided from the query context. 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. The closectx is closed by an explicit call to rs.Close.

func (rs *Rows) awaitDone(ctx context.Context, txctx context.Context, closectx context.Context)

awaitDone method #

awaitDone blocks until the context in Tx is canceled and rolls back the transaction if it's not already done.

func (tx *Tx) awaitDone()

begin method #

func (db *DB) begin(ctx context.Context, opts *TxOptions, strategy connReuseStrategy) (tx *Tx, err error)

beginDC method #

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)

callValuerValue function #

callValuerValue returns vr.Value(), with one exception: If vr.Value is an auto-generated method on a pointer type and the pointer is nil, it would panic at runtime in the panicwrap method. Treat it like nil instead. Issue 8415. This is so people can implement driver.Value on value types and still use nil pointers to those types to mean nil/NULL, just like string/*string. This function is mirrored in the database/sql/driver package.

func callValuerValue(vr driver.Valuer) (v driver.Value, err error)

close method #

func (rs *Rows) close(err error) error

close method #

func (c *Conn) close(err error) error

close method #

close returns the connection to the pool and must only be called by Tx.rollback or Tx.Commit while tx is already canceled and won't be executed concurrently.

func (tx *Tx) close(err error)

closeDBLocked method #

the dc.db's Mutex is held.

func (dc *driverConn) closeDBLocked() (func() error)

closePrepared method #

Closes all Stmts prepared for this transaction.

func (tx *Tx) closePrepared()

closemuRUnlockCondReleaseConn method #

closemuRUnlockCondReleaseConn read unlocks closemu as the sql operation is done with the dc.

func (c *Conn) closemuRUnlockCondReleaseConn(err error)

closemuRUnlockIfHeldByScan method #

closemuRUnlockIfHeldByScan releases any closemu.RLock held open by a previous call to Scan with *RawBytes.

func (rs *Rows) closemuRUnlockIfHeldByScan()

closemuRUnlockRelease method #

closemuRUnlockRelease is used as a func(error) method value in [DB.ExecContext] and [DB.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)

conn method #

conn returns a newly-opened or cached *driverConn.

func (db *DB) conn(ctx context.Context, strategy connReuseStrategy) (*driverConn, error)

connStmt method #

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.

func (s *Stmt) connStmt(ctx context.Context, strategy connReuseStrategy) (dc *driverConn, releaseConn func(error), ds *driverStmt, err error)

connectionCleaner method #

func (db *DB) connectionCleaner(d time.Duration)

connectionCleanerRunLocked method #

connectionCleanerRunLocked removes connections that should be closed from freeConn and returns them along side an updated duration to the next check if a quicker check is required to ensure connections are checked appropriately.

func (db *DB) connectionCleanerRunLocked(d time.Duration) (time.Duration, []*driverConn)

connectionOpener method #

Runs in a separate goroutine, opens new connections when requested.

func (db *DB) connectionOpener(ctx context.Context)

convertAssign function #

convertAssign is the same as convertAssignRows, but without the optional rows argument. convertAssign should be an internal detail, but widely used packages access it using linkname. Notable members of the hall of shame include: - ariga.io/entcache Do not remove or change the type signature. See go.dev/issue/67401. go:linkname convertAssign

func convertAssign(dest any, src any) error

convertAssignRows function #

convertAssignRows copies to dest the value in src, converting it if possible. An error is returned if the copy would result in loss of information. dest should be a pointer type. If rows is passed in, the rows will be used as the parent for any cursor values converted from a driver.Rows to a *Rows.

func convertAssignRows(dest any, src any, rows *Rows) error

ctxDriverBegin function #

func ctxDriverBegin(ctx context.Context, opts *TxOptions, ci driver.Conn) (driver.Tx, error)

ctxDriverExec function #

func ctxDriverExec(ctx context.Context, execerCtx driver.ExecerContext, execer driver.Execer, query string, nvdargs []driver.NamedValue) (driver.Result, error)

ctxDriverPrepare function #

func ctxDriverPrepare(ctx context.Context, ci driver.Conn, query string) (driver.Stmt, error)

ctxDriverQuery function #

func ctxDriverQuery(ctx context.Context, queryerCtx driver.QueryerContext, queryer driver.Queryer, query string, nvdargs []driver.NamedValue) (driver.Rows, error)

ctxDriverStmtExec function #

func ctxDriverStmtExec(ctx context.Context, si driver.Stmt, nvdargs []driver.NamedValue) (driver.Result, error)

ctxDriverStmtQuery function #

func ctxDriverStmtQuery(ctx context.Context, si driver.Stmt, nvdargs []driver.NamedValue) (driver.Rows, error)

defaultCheckNamedValue function #

defaultCheckNamedValue wraps the default ColumnConverter to have the same function signature as the CheckNamedValue in the driver.NamedValueChecker interface.

func defaultCheckNamedValue(nv *driver.NamedValue) (err error)

deleteIndex method #

func (s *connRequestSet) deleteIndex(idx int)

describeNamedValue function #

func describeNamedValue(nv *driver.NamedValue) string

driverArgsConnLocked function #

driverArgsConnLocked converts arguments from callers of Stmt.Exec and Stmt.Query into driver Values. The statement ds may be nil, if no statement is available. ci must be locked.

func driverArgsConnLocked(ci driver.Conn, ds *driverStmt, args []any) ([]driver.NamedValue, error)

exec method #

func (db *DB) exec(ctx context.Context, query string, args []any, strategy connReuseStrategy) (Result, error)

execDC method #

func (db *DB) execDC(ctx context.Context, dc *driverConn, release func(error), query string, args []any) (res Result, err error)

expired method #

func (dc *driverConn) expired(timeout time.Duration) bool

finalClose method #

func (dc *driverConn) finalClose() error

finalClose method #

func (s *Stmt) finalClose() error

grabConn method #

func (tx *Tx) grabConn(ctx context.Context) (*driverConn, releaseConn, error)

grabConn method #

grabConn takes a context to implement stmtConnGrabber but the context is not used.

func (c *Conn) grabConn(context.Context) (*driverConn, releaseConn, error)

initContextClose method #

func (rs *Rows) initContextClose(ctx context.Context, txctx context.Context)

isDone method #

func (tx *Tx) isDone() bool

lasterrOrErrLocked method #

lasterrOrErrLocked returns either lasterr or the provided err. rs.closemu must be read-locked.

func (rs *Rows) lasterrOrErrLocked(err error) error

maxIdleConnsLocked method #

func (db *DB) maxIdleConnsLocked() int

maybeOpenNewConnections method #

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()

namedValueToValue function #

func namedValueToValue(named []driver.NamedValue) ([]driver.Value, error)

nextLocked method #

func (rs *Rows) nextLocked() (doClose bool, ok bool)

noteUnusedDriverStatement method #

noteUnusedDriverStatement notes that ds is no longer used and should be closed whenever possible (when c is next not in use), unless c is already closed.

func (db *DB) noteUnusedDriverStatement(c *driverConn, ds *driverStmt)

openNewConnection method #

Open one new connection

func (db *DB) openNewConnection(ctx context.Context)

pingDC method #

func (db *DB) pingDC(ctx context.Context, dc *driverConn, release func(error)) error

prepare method #

func (db *DB) prepare(ctx context.Context, query string, strategy connReuseStrategy) (*Stmt, error)

prepareDC method #

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)

prepareLocked method #

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)

prepareOnConnLocked method #

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)

putConn method #

putConn adds a connection to the db's free pool. err is optionally the last error that occurred on this connection.

func (db *DB) putConn(dc *driverConn, err error, resetSession bool)

putConnDBLocked method #

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 return the *driverConn to the freeConn list if err == nil and the idle connection limit will not be exceeded. If err != nil, the value of dc is ignored. If err == nil, then dc must not equal nil. If a connRequest was fulfilled or the *driverConn was placed in the freeConn list, then true is returned, otherwise false is returned.

func (db *DB) putConnDBLocked(dc *driverConn, err error) bool

query method #

func (db *DB) query(ctx context.Context, query string, args []any, strategy connReuseStrategy) (*Rows, error)

queryDC method #

queryDC executes a query on the given connection. The connection gets released by the releaseConn function. The ctx context is from a query method and the txctx context is from an optional transaction context.

func (db *DB) queryDC(ctx context.Context, txctx context.Context, dc *driverConn, releaseConn func(error), query string, args []any) (*Rows, error)

rawbuf method #

rawbuf returns the buffer to append RawBytes values to. This buffer is reused across calls to Rows.Scan. Usage: rawBytes = rows.setrawbuf(append(rows.rawbuf(), value...))

func (rs *Rows) rawbuf() []byte

releaseConn method #

func (dc *driverConn) releaseConn(err error)

removeClosedStmtLocked method #

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()

removeDep method #

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 any) error

removeDepLocked method #

func (db *DB) removeDepLocked(x finalCloser, dep any) (func() error)

removeOpenStmt method #

func (dc *driverConn) removeOpenStmt(ds *driverStmt)

resetSession method #

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

resultFromStatement function #

func resultFromStatement(ctx context.Context, ci driver.Conn, ds *driverStmt, args ...any) (Result, error)

retry method #

func (db *DB) retry(fn func(strategy connReuseStrategy) error) error

rollback method #

rollback aborts the transaction and optionally forces the pool to discard the connection.

func (tx *Tx) rollback(discardConn bool) error

rowsColumnInfoSetupConnLocked function #

func rowsColumnInfoSetupConnLocked(rowsi driver.Rows) []*ColumnType

rowsiFromStatement function #

func rowsiFromStatement(ctx context.Context, ci driver.Conn, ds *driverStmt, args ...any) (driver.Rows, error)

scanArgsContainRawBytes function #

func scanArgsContainRawBytes(args []any) bool

setrawbuf method #

setrawbuf updates the RawBytes buffer with the result of appending a new value to it. It returns the new value.

func (rs *Rows) setrawbuf(b []byte) RawBytes

shortestIdleTimeLocked method #

func (db *DB) shortestIdleTimeLocked() time.Duration

stack function #

func stack() string

startCleanerLocked method #

startCleanerLocked starts connectionCleaner if needed.

func (db *DB) startCleanerLocked()

strconvErr function #

func strconvErr(err error) error

txCtx method #

func (tx *Tx) txCtx() context.Context

txCtx method #

func (c *Conn) txCtx() context.Context

unregisterAllDrivers function #

func unregisterAllDrivers()

validateConnection method #

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

validateNamedValueName function #

func validateNamedValueName(name string) error

withLock function #

withLock runs while holding lk.

func withLock(lk sync.Locker, fn func())

Generated with Arrow