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