// Most code should use package sql.
//
// The driver interface has evolved over time. Drivers should implement
-// Connector and DriverContext interfaces.
-// The Connector.Connect and Driver.Open methods should never return ErrBadConn.
-// ErrBadConn should only be returned from Validator, SessionResetter, or
+// [Connector] and [DriverContext] interfaces.
+// The Connector.Connect and Driver.Open methods should never return [ErrBadConn].
+// [ErrBadConn] should only be returned from [Validator], [SessionResetter], or
// a query method if the connection is already in an invalid (e.g. closed) state.
//
-// All Conn implementations should implement the following interfaces:
-// Pinger, SessionResetter, and Validator.
+// All [Conn] implementations should implement the following interfaces:
+// [Pinger], [SessionResetter], and [Validator].
//
-// If named parameters or context are supported, the driver's Conn should implement:
-// ExecerContext, QueryerContext, ConnPrepareContext, and ConnBeginTx.
+// If named parameters or context are supported, the driver's [Conn] should implement:
+// [ExecerContext], [QueryerContext], [ConnPrepareContext], and [ConnBeginTx].
//
-// To support custom data types, implement NamedValueChecker. NamedValueChecker
+// To support custom data types, implement [NamedValueChecker]. [NamedValueChecker]
// also allows queries to accept per-query options as a parameter by returning
-// ErrRemoveArgument from CheckNamedValue.
+// [ErrRemoveArgument] from CheckNamedValue.
//
-// If multiple result sets are supported, Rows should implement RowsNextResultSet.
+// If multiple result sets are supported, [Rows] should implement [RowsNextResultSet].
// If the driver knows how to describe the types present in the returned result
-// it should implement the following interfaces: RowsColumnTypeScanType,
-// RowsColumnTypeDatabaseTypeName, RowsColumnTypeLength, RowsColumnTypeNullable,
-// and RowsColumnTypePrecisionScale. A given row value may also return a Rows
+// it should implement the following interfaces: [RowsColumnTypeScanType],
+// [RowsColumnTypeDatabaseTypeName], [RowsColumnTypeLength], [RowsColumnTypeNullable],
+// and [RowsColumnTypePrecisionScale]. A given row value may also return a [Rows]
// type, which may represent a database cursor value.
//
// Before a connection is returned to the connection pool after use, IsValid is
)
// Value is a value that drivers must be able to handle.
-// It is either nil, a type handled by a database driver's NamedValueChecker
+// It is either nil, a type handled by a database driver's [NamedValueChecker]
// interface, or an instance of one of these types:
//
// int64
// string
// time.Time
//
-// If the driver supports cursors, a returned Value may also implement the Rows interface
+// If the driver supports cursors, a returned Value may also implement the [Rows] interface
// in this package. This is used, for example, when a user selects a cursor
-// such as "select cursor(select * from my_table) from dual". If the Rows
-// from the select is closed, the cursor Rows will also be closed.
+// such as "select cursor(select * from my_table) from dual". If the [Rows]
+// from the select is closed, the cursor [Rows] will also be closed.
type Value any
// NamedValue holds both the value name and value.
// Driver is the interface that must be implemented by a database
// driver.
//
-// Database drivers may implement DriverContext for access
+// Database drivers may implement [DriverContext] for access
// to contexts and to parse the name only once for a pool of connections,
// instead of once per connection.
type Driver interface {
Open(name string) (Conn, error)
}
-// If a Driver implements DriverContext, then sql.DB will call
-// OpenConnector to obtain a Connector and then invoke
-// that Connector's Connect method to obtain each needed connection,
-// instead of invoking the Driver's Open method for each connection.
+// If a [Driver] implements [DriverContext], then sql.DB will call
+// OpenConnector to obtain a [Connector] and then invoke
+// that [Connector]'s Connect method to obtain each needed connection,
+// instead of invoking the [Driver]'s Open method for each connection.
// The two-step sequence allows drivers to parse the name just once
// and also provides access to per-Conn contexts.
type DriverContext interface {
// and can create any number of equivalent Conns for use
// by multiple goroutines.
//
-// A Connector can be passed to sql.OpenDB, to allow drivers
+// A Connector can be passed to [database/sql.OpenDB], to allow drivers
// to implement their own sql.DB constructors, or returned by
-// DriverContext's OpenConnector method, to allow drivers
+// [DriverContext]'s OpenConnector method, to allow drivers
// access to context and to avoid repeated parsing of driver
// configuration.
//
-// If a Connector implements io.Closer, the sql package's DB.Close
+// If a Connector implements [io.Closer], the [database/sql.DB.Close]
// method will call Close and return error (if any).
type Connector interface {
// Connect returns a connection to the database.
var ErrSkip = errors.New("driver: skip fast-path; continue as if unimplemented")
// ErrBadConn should be returned by a driver to signal to the sql
-// package that a driver.Conn is in a bad state (such as the server
+// package that a [driver.Conn] is in a bad state (such as the server
// having earlier closed the connection) and the sql package should
// retry on a new connection.
//
// wrap ErrBadConn or implement the Is(error) bool method.
var ErrBadConn = errors.New("driver: bad connection")
-// Pinger is an optional interface that may be implemented by a Conn.
+// Pinger is an optional interface that may be implemented by a [Conn].
//
-// If a Conn does not implement Pinger, the sql package's DB.Ping and
-// DB.PingContext will check if there is at least one Conn available.
+// If a [Conn] does not implement Pinger, the [database/sql.DB.Ping] and
+// [database/sql.DB.PingContext] will check if there is at least one [Conn] available.
//
-// If Conn.Ping returns ErrBadConn, DB.Ping and DB.PingContext will remove
-// the Conn from pool.
+// If Conn.Ping returns [ErrBadConn], [database/sql.DB.Ping] and [database/sql.DB.PingContext] will remove
+// the [Conn] from pool.
type Pinger interface {
Ping(ctx context.Context) error
}
// Execer is an optional interface that may be implemented by a Conn.
//
-// If a Conn implements neither ExecerContext nor Execer,
-// the sql package's DB.Exec will first prepare a query, execute the statement,
+// If a [Conn] implements neither [ExecerContext] nor Execer,
+// the [database/sql.DB.Exec] will first prepare a query, execute the statement,
// and then close the statement.
//
-// Exec may return ErrSkip.
+// Exec may return [ErrSkip].
//
-// Deprecated: Drivers should implement ExecerContext instead.
+// Deprecated: Drivers should implement [ExecerContext] instead.
type Execer interface {
Exec(query string, args []Value) (Result, error)
}
-// ExecerContext is an optional interface that may be implemented by a Conn.
+// ExecerContext is an optional interface that may be implemented by a [Conn].
//
-// If a Conn does not implement ExecerContext, the sql package's DB.Exec
-// will fall back to Execer; if the Conn does not implement Execer either,
-// DB.Exec will first prepare a query, execute the statement, and then
+// If a Conn does not implement ExecerContext, the [database/sql.DB.Exec]
+// will fall back to [Execer]; if the Conn does not implement Execer either,
+// [database/sql.DB.Exec] will first prepare a query, execute the statement, and then
// close the statement.
//
-// ExecContext may return ErrSkip.
+// ExecContext may return [ErrSkip].
//
// ExecContext must honor the context timeout and return when the context is canceled.
type ExecerContext interface {
ExecContext(ctx context.Context, query string, args []NamedValue) (Result, error)
}
-// Queryer is an optional interface that may be implemented by a Conn.
+// Queryer is an optional interface that may be implemented by a [Conn].
//
-// If a Conn implements neither QueryerContext nor Queryer,
-// the sql package's DB.Query will first prepare a query, execute the statement,
+// If a Conn implements neither [QueryerContext] nor Queryer,
+// the [database/sql.DB.Query] will first prepare a query, execute the statement,
// and then close the statement.
//
-// Query may return ErrSkip.
+// Query may return [ErrSkip].
//
-// Deprecated: Drivers should implement QueryerContext instead.
+// Deprecated: Drivers should implement [QueryerContext] instead.
type Queryer interface {
Query(query string, args []Value) (Rows, error)
}
// QueryerContext is an optional interface that may be implemented by a Conn.
//
-// If a Conn does not implement QueryerContext, the sql package's DB.Query
-// will fall back to Queryer; if the Conn does not implement Queryer either,
-// DB.Query will first prepare a query, execute the statement, and then
+// If a [Conn] does not implement QueryerContext, the [database/sql.DB.Query]
+// will fall back to [Queryer]; if the [Conn] does not implement [Queryer] either,
+// [database/sql.DB.Query] will first prepare a query, execute the statement, and then
// close the statement.
//
-// QueryContext may return ErrSkip.
+// QueryContext may return [ErrSkip].
//
// QueryContext must honor the context timeout and return when the context is canceled.
type QueryerContext interface {
Begin() (Tx, error)
}
-// ConnPrepareContext enhances the Conn interface with context.
+// ConnPrepareContext enhances the [Conn] interface with context.
type ConnPrepareContext interface {
// PrepareContext returns a prepared statement, bound to this connection.
// context is for the preparation of the statement,
PrepareContext(ctx context.Context, query string) (Stmt, error)
}
-// IsolationLevel is the transaction isolation level stored in TxOptions.
+// IsolationLevel is the transaction isolation level stored in [TxOptions].
//
// This type should be considered identical to sql.IsolationLevel along
// with any values defined on it.
// TxOptions holds the transaction options.
//
-// This type should be considered identical to sql.TxOptions.
+// This type should be considered identical to [database/sql.TxOptions].
type TxOptions struct {
Isolation IsolationLevel
ReadOnly bool
}
-// ConnBeginTx enhances the Conn interface with context and TxOptions.
+// ConnBeginTx enhances the [Conn] interface with context and [TxOptions].
type ConnBeginTx interface {
// BeginTx starts and returns a new transaction.
// If the context is canceled by the user the sql package will
BeginTx(ctx context.Context, opts TxOptions) (Tx, error)
}
-// SessionResetter may be implemented by Conn to allow drivers to reset the
+// SessionResetter may be implemented by [Conn] to allow drivers to reset the
// session state associated with the connection and to signal a bad connection.
type SessionResetter interface {
// ResetSession is called prior to executing a query on the connection
ResetSession(ctx context.Context) error
}
-// Validator may be implemented by Conn to allow drivers to
+// Validator may be implemented by [Conn] to allow drivers to
// signal if a connection is valid or if it should be discarded.
//
// If implemented, drivers may return the underlying error from queries,
RowsAffected() (int64, error)
}
-// Stmt is a prepared statement. It is bound to a Conn and not
+// Stmt is a prepared statement. It is bound to a [Conn] and not
// used by multiple goroutines concurrently.
type Stmt interface {
// Close closes the statement.
Query(args []Value) (Rows, error)
}
-// StmtExecContext enhances the Stmt interface by providing Exec with context.
+// StmtExecContext enhances the [Stmt] interface by providing Exec with context.
type StmtExecContext interface {
// ExecContext executes a query that doesn't return rows, such
// as an INSERT or UPDATE.
ExecContext(ctx context.Context, args []NamedValue) (Result, error)
}
-// StmtQueryContext enhances the Stmt interface by providing Query with context.
+// StmtQueryContext enhances the [Stmt] interface by providing Query with context.
type StmtQueryContext interface {
// QueryContext executes a query that may return rows, such as a
// SELECT.
QueryContext(ctx context.Context, args []NamedValue) (Rows, error)
}
-// ErrRemoveArgument may be returned from NamedValueChecker to instruct the
+// ErrRemoveArgument may be returned from [NamedValueChecker] to instruct the
// sql package to not pass the argument to the driver query interface.
// Return when accepting query specific options or structures that aren't
// SQL query arguments.
var ErrRemoveArgument = errors.New("driver: remove argument from query")
-// NamedValueChecker may be optionally implemented by Conn or Stmt. It provides
+// NamedValueChecker may be optionally implemented by [Conn] or [Stmt]. It provides
// the driver more control to handle Go and database types beyond the default
// Values types allowed.
//
// The sql package checks for value checkers in the following order,
-// stopping at the first found match: Stmt.NamedValueChecker, Conn.NamedValueChecker,
-// Stmt.ColumnConverter, DefaultParameterConverter.
+// stopping at the first found match: [database/sql.Stmt.NamedValueChecker],
+// Conn.NamedValueChecker, [database/sql.Stmt.ColumnConverter], [DefaultParameterConverter].
//
-// If CheckNamedValue returns ErrRemoveArgument, the NamedValue will not be included in
+// If CheckNamedValue returns [ErrRemoveArgument], the [NamedValue] will not be included in
// the final query arguments. This may be used to pass special options to
// the query itself.
//
-// If ErrSkip is returned the column converter error checking
-// path is used for the argument. Drivers may wish to return ErrSkip after
+// If [ErrSkip] is returned the column converter error checking
+// path is used for the argument. Drivers may wish to return [ErrSkip] after
// they have exhausted their own special cases.
type NamedValueChecker interface {
// CheckNamedValue is called before passing arguments to the driver
CheckNamedValue(*NamedValue) error
}
-// ColumnConverter may be optionally implemented by Stmt if the
+// ColumnConverter may be optionally implemented by [Stmt] if the
// statement is aware of its own columns' types and can convert from
-// any type to a driver Value.
+// any type to a driver [Value].
//
-// Deprecated: Drivers should implement NamedValueChecker.
+// Deprecated: Drivers should implement [NamedValueChecker].
type ColumnConverter interface {
// ColumnConverter returns a ValueConverter for the provided
// column index. If the type of a specific column isn't known
Next(dest []Value) error
}
-// RowsNextResultSet extends the Rows interface by providing a way to signal
+// RowsNextResultSet extends the [Rows] interface by providing a way to signal
// the driver to advance to the next result set.
type RowsNextResultSet interface {
Rows
NextResultSet() error
}
-// RowsColumnTypeScanType may be implemented by Rows. It should return
+// RowsColumnTypeScanType may be implemented by [Rows]. It should return
// the value type that can be used to scan types into. For example, the database
-// column type "bigint" this should return "reflect.TypeOf(int64(0))".
+// column type "bigint" this should return "[reflect.TypeOf](int64(0))".
type RowsColumnTypeScanType interface {
Rows
ColumnTypeScanType(index int) reflect.Type
}
-// RowsColumnTypeDatabaseTypeName may be implemented by Rows. It should return the
+// RowsColumnTypeDatabaseTypeName may be implemented by [Rows]. It should return the
// database system type name without the length. Type names should be uppercase.
// Examples of returned types: "VARCHAR", "NVARCHAR", "VARCHAR2", "CHAR", "TEXT",
// "DECIMAL", "SMALLINT", "INT", "BIGINT", "BOOL", "[]BIGINT", "JSONB", "XML",
ColumnTypeDatabaseTypeName(index int) string
}
-// RowsColumnTypeLength may be implemented by Rows. It should return the length
+// RowsColumnTypeLength may be implemented by [Rows]. It should return the length
// of the column type if the column is a variable length type. If the column is
// not a variable length type ok should return false.
// If length is not limited other than system limits, it should return math.MaxInt64.
ColumnTypeLength(index int) (length int64, ok bool)
}
-// RowsColumnTypeNullable may be implemented by Rows. The nullable value should
+// RowsColumnTypeNullable may be implemented by [Rows]. The nullable value should
// be true if it is known the column may be null, or false if the column is known
// to be not nullable.
// If the column nullability is unknown, ok should be false.
ColumnTypeNullable(index int) (nullable, ok bool)
}
-// RowsColumnTypePrecisionScale may be implemented by Rows. It should return
+// RowsColumnTypePrecisionScale may be implemented by [Rows]. It should return
// the precision and scale for decimal types. If not applicable, ok should be false.
// The following are examples of returned values for various types:
//
Rollback() error
}
-// RowsAffected implements Result for an INSERT or UPDATE operation
+// RowsAffected implements [Result] for an INSERT or UPDATE operation
// which mutates a number of rows.
type RowsAffected int64
return int64(v), nil
}
-// ResultNoRows is a pre-defined Result for drivers to return when a DDL
+// ResultNoRows is a pre-defined [Result] for drivers to return when a DDL
// command (such as a CREATE TABLE) succeeds. It returns an error for both
-// LastInsertId and RowsAffected.
+// LastInsertId and [RowsAffected].
var ResultNoRows noRows
type noRows struct{}
// parameter in the SQL statement.
//
// For a more concise way to create NamedArg values, see
-// the Named function.
+// the [Named] function.
type NamedArg struct {
_NamedFieldsRequired struct{}
Value any
}
-// Named provides a more concise way to create NamedArg values.
+// Named provides a more concise way to create [NamedArg] values.
//
// Example usage:
//
return NamedArg{Name: name, Value: value}
}
-// IsolationLevel is the transaction isolation level used in TxOptions.
+// IsolationLevel is the transaction isolation level used in [TxOptions].
type IsolationLevel int
// Various isolation levels that drivers may support in BeginTx.
var _ fmt.Stringer = LevelDefault
-// TxOptions holds the transaction options to be used in DB.BeginTx.
+// TxOptions holds the transaction options to be used in [DB.BeginTx].
type TxOptions struct {
// Isolation is the transaction isolation level.
// If zero, the driver or database's default level is used.
type RawBytes []byte
// NullString represents a string that may be null.
-// NullString implements the Scanner interface so
+// NullString implements the [Scanner] interface so
// it can be used as a scan destination:
//
// var s NullString
Valid bool // Valid is true if String is not NULL
}
-// Scan implements the Scanner interface.
+// Scan implements the [Scanner] interface.
func (ns *NullString) Scan(value any) error {
if value == nil {
ns.String, ns.Valid = "", false
return convertAssign(&ns.String, value)
}
-// Value implements the driver Valuer interface.
+// Value implements the [driver.Valuer] interface.
func (ns NullString) Value() (driver.Value, error) {
if !ns.Valid {
return nil, nil
}
// 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.
+// NullInt64 implements the [Scanner] interface so
+// it can be used as a scan destination, similar to [NullString].
type NullInt64 struct {
Int64 int64
Valid bool // Valid is true if Int64 is not NULL
}
-// Scan implements the Scanner interface.
+// Scan implements the [Scanner] interface.
func (n *NullInt64) Scan(value any) error {
if value == nil {
n.Int64, n.Valid = 0, false
return convertAssign(&n.Int64, value)
}
-// Value implements the driver Valuer interface.
+// Value implements the [driver.Valuer] interface.
func (n NullInt64) Value() (driver.Value, error) {
if !n.Valid {
return nil, nil
}
// 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.
+// NullInt32 implements the [Scanner] interface so
+// it can be used as a scan destination, similar to [NullString].
type NullInt32 struct {
Int32 int32
Valid bool // Valid is true if Int32 is not NULL
}
-// Scan implements the Scanner interface.
+// Scan implements the [Scanner] interface.
func (n *NullInt32) Scan(value any) error {
if value == nil {
n.Int32, n.Valid = 0, false
return convertAssign(&n.Int32, value)
}
-// Value implements the driver Valuer interface.
+// Value implements the [driver.Valuer] interface.
func (n NullInt32) Value() (driver.Value, error) {
if !n.Valid {
return nil, nil
}
// 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.
+// NullInt16 implements the [Scanner] interface so
+// it can be used as a scan destination, similar to [NullString].
type NullInt16 struct {
Int16 int16
Valid bool // Valid is true if Int16 is not NULL
}
-// Scan implements the Scanner interface.
+// Scan implements the [Scanner] interface.
func (n *NullInt16) Scan(value any) error {
if value == nil {
n.Int16, n.Valid = 0, false
return err
}
-// Value implements the driver Valuer interface.
+// Value implements the [driver.Valuer] interface.
func (n NullInt16) Value() (driver.Value, error) {
if !n.Valid {
return nil, nil
}
// 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.
+// NullByte implements the [Scanner] interface so
+// it can be used as a scan destination, similar to [NullString].
type NullByte struct {
Byte byte
Valid bool // Valid is true if Byte is not NULL
}
-// Scan implements the Scanner interface.
+// Scan implements the [Scanner] interface.
func (n *NullByte) Scan(value any) error {
if value == nil {
n.Byte, n.Valid = 0, false
return err
}
-// Value implements the driver Valuer interface.
+// Value implements the [driver.Valuer] interface.
func (n NullByte) Value() (driver.Value, error) {
if !n.Valid {
return nil, nil
}
// 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.
+// NullFloat64 implements the [Scanner] interface so
+// it can be used as a scan destination, similar to [NullString].
type NullFloat64 struct {
Float64 float64
Valid bool // Valid is true if Float64 is not NULL
}
-// Scan implements the Scanner interface.
+// Scan implements the [Scanner] interface.
func (n *NullFloat64) Scan(value any) error {
if value == nil {
n.Float64, n.Valid = 0, false
return convertAssign(&n.Float64, value)
}
-// Value implements the driver Valuer interface.
+// Value implements the [driver.Valuer] interface.
func (n NullFloat64) Value() (driver.Value, error) {
if !n.Valid {
return nil, nil
}
// 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.
+// NullBool implements the [Scanner] interface so
+// it can be used as a scan destination, similar to [NullString].
type NullBool struct {
Bool bool
Valid bool // Valid is true if Bool is not NULL
}
-// Scan implements the Scanner interface.
+// Scan implements the [Scanner] interface.
func (n *NullBool) Scan(value any) error {
if value == nil {
n.Bool, n.Valid = false, false
return convertAssign(&n.Bool, value)
}
-// Value implements the driver Valuer interface.
+// Value implements the [driver.Valuer] interface.
func (n NullBool) Value() (driver.Value, error) {
if !n.Valid {
return nil, nil
return n.Bool, nil
}
-// 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.
+// NullTime represents a [time.Time] that may be null.
+// NullTime implements the [Scanner] interface so
+// it can be used as a scan destination, similar to [NullString].
type NullTime struct {
Time time.Time
Valid bool // Valid is true if Time is not NULL
}
-// Scan implements the Scanner interface.
+// Scan implements the [Scanner] interface.
func (n *NullTime) Scan(value any) error {
if value == nil {
n.Time, n.Valid = time.Time{}, false
return convertAssign(&n.Time, value)
}
-// Value implements the driver Valuer interface.
+// Value implements the [driver.Valuer] interface.
func (n NullTime) Value() (driver.Value, error) {
if !n.Valid {
return nil, nil
}
// Null represents a value that may be null.
-// Null implements the Scanner interface so
+// Null implements the [Scanner] interface so
// it can be used as a scan destination:
//
// var s Null[string]
return n.V, nil
}
-// Scanner is an interface used by Scan.
+// Scanner is an interface used by [Scan].
type Scanner interface {
// Scan assigns a value from a database driver.
//
}
// ErrNoRows is returned by Scan when QueryRow doesn't return a
-// row. In such a case, QueryRow returns a placeholder *Row value that
+// row. In such a case, QueryRow returns a placeholder *[Row] value that
// defers this error until a Scan.
var ErrNoRows = errors.New("sql: no rows in result set")
// 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 Commit or
+// within a transaction ([Tx]) or connection ([Conn]). Once [DB.Begin] is called, the
+// returned [Tx] is bound to a single connection. Once Commit or
// Rollback is called on the transaction, that transaction's
-// connection is returned to DB's idle connection pool. The pool size
+// connection is returned to [DB]'s idle connection pool. The pool size
// can be controlled with SetMaxIdleConns.
type DB struct {
// Total time waited for new connections.
// 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
+// 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.
//
// to the database. To verify that the data source name is valid, call
// Ping.
//
-// The returned DB is safe for concurrent use by multiple goroutines
+// 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.
+// close a [DB].
func OpenDB(c driver.Connector) *DB {
ctx, cancel := context.WithCancel(context.Background())
db := &DB{
// 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
+// 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.
//
// to the database. To verify that the data source name is valid, call
// Ping.
//
-// The returned DB is safe for concurrent use by multiple goroutines
+// 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.
+// close a [DB].
func Open(driverName, dataSourceName string) (*DB, error) {
driversMu.RLock()
driveri, ok := drivers[driverName]
// 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
-// PingContext.
+// Ping uses [context.Background] internally; to specify the context, use
+// [PingContext].
func (db *DB) Ping() error {
return db.PingContext(context.Background())
}
// 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
+// 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 {
db.mu.Lock()
// PrepareContext creates a prepared statement for later queries or executions.
// Multiple queries or executions may be run concurrently from the
// returned statement.
-// The caller must call the statement's Close method
+// The caller must call the statement's [DB.Close] method
// when the statement is no longer needed.
//
// The provided context is used for the preparation of the statement, not for the
// The caller must call the statement's Close method
// when the statement is no longer needed.
//
-// Prepare uses context.Background internally; to specify the context, use
-// PrepareContext.
+// Prepare uses [context.Background] internally; to specify the context, use
+// [DB.PrepareContext].
func (db *DB) Prepare(query string) (*Stmt, error) {
return db.PrepareContext(context.Background(), query)
}
// 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
-// ExecContext.
+// Exec uses [context.Background] internally; to specify the context, use
+// [DB.ExecContext].
func (db *DB) Exec(query string, args ...any) (Result, error) {
return db.ExecContext(context.Background(), query, args...)
}
// 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
-// QueryContext.
+// Query uses [context.Background] internally; to specify the context, use
+// [DB.QueryContext].
func (db *DB) Query(query string, args ...any) (*Rows, error) {
return db.QueryContext(context.Background(), query, args...)
}
// 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's Scan will return ErrNoRows.
-// Otherwise, the *Row's Scan scans the first selected row and discards
+// [Row]'s Scan method is called.
+// If the query selects no rows, the *[Row]'s Scan will return [ErrNoRows].
+// Otherwise, the *[Row]'s Scan scans the first selected row and discards
// the rest.
func (db *DB) QueryRowContext(ctx context.Context, query string, args ...any) *Row {
rows, err := db.QueryContext(ctx, query, args...)
// 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's Scan will return ErrNoRows.
-// Otherwise, the *Row's Scan scans the first selected row and discards
+// [Row]'s Scan method is called.
+// If the query selects no rows, the *[Row]'s Scan will return [ErrNoRows].
+// Otherwise, the *[Row]'s Scan scans the first selected row and discards
// the rest.
//
-// QueryRow uses context.Background internally; to specify the context, use
-// QueryRowContext.
+// QueryRow uses [context.Background] internally; to specify the context, use
+// [DB.QueryRowContext].
func (db *DB) QueryRow(query string, args ...any) *Row {
return db.QueryRowContext(context.Background(), query, args...)
}
//
// 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
+// 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.
+// 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) {
// Begin starts a transaction. The default isolation level is dependent on
// the driver.
//
-// Begin uses context.Background internally; to specify the context, use
-// BeginTx.
+// Begin uses [context.Background] internally; to specify the context, use
+// [DB.BeginTx].
func (db *DB) Begin() (*Tx, error) {
return db.BeginTx(context.Background(), nil)
}
// 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.
+// calling [Conn.Close].
func (db *DB) Conn(ctx context.Context) (*Conn, error) {
var dc *driverConn
var err error
type releaseConn func(error)
// Conn represents a single database connection rather than a pool of database
-// connections. Prefer running queries from DB unless there is a specific
+// connections. Prefer running queries from [DB] unless there is a specific
// need for a continuous single database connection.
//
-// A Conn must call Close to return the connection to the database pool
+// 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 Close, all operations on the
-// connection fail with ErrConnDone.
+// After a call to [Conn.Close], all operations on the
+// connection fail with [ErrConnDone].
type Conn struct {
db *DB
// 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's Scan will return ErrNoRows.
-// Otherwise, the *Row's Scan scans the first selected row and discards
+// [Row]'s Scan method is called.
+// If the query selects no rows, the *[Row]'s Scan will return [ErrNoRows].
+// Otherwise, the *[Row]'s Scan scans the first selected row and discards
// the rest.
func (c *Conn) QueryRowContext(ctx context.Context, query string, args ...any) *Row {
rows, err := c.QueryContext(ctx, query, args...)
// PrepareContext creates a prepared statement for later queries or executions.
// Multiple queries or executions may be run concurrently from the
// returned statement.
-// The caller must call the statement's Close method
+// The caller must call the statement's [Conn.Close] method
// when the statement is no longer needed.
//
// The provided context is used for the preparation of the statement, not for the
// 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.
+// 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) {
var dc *driverConn
var release releaseConn
//
// 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
+// 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.
+// 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) {
}
// Close returns the connection to the connection pool.
-// All operations after a Close will return with ErrConnDone.
+// 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.
// Tx is an in-progress database transaction.
//
-// A transaction must end with a call to Commit or Rollback.
+// A transaction must end with a call to [Tx.Commit] or [Tx.Rollback].
//
-// After a call to Commit or Rollback, all operations on the
-// transaction fail with ErrTxDone.
+// 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 Prepare or Stmt methods are closed
-// by the call to Commit or Rollback.
+// 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
// 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.
+// 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
// 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.
+// To use an existing prepared statement on this transaction, see [Tx.Stmt].
//
-// Prepare uses context.Background internally; to specify the context, use
-// PrepareContext.
+// Prepare uses [context.Background] internally; to specify the context, use
+// [Tx.PrepareContext].
func (tx *Tx) Prepare(query string) (*Stmt, error) {
return tx.PrepareContext(context.Background(), query)
}
// 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
-// StmtContext.
+// Stmt uses [context.Background] internally; to specify the context, use
+// [Tx.StmtContext].
func (tx *Tx) Stmt(stmt *Stmt) *Stmt {
return tx.StmtContext(context.Background(), stmt)
}
// 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
-// ExecContext.
+// Exec uses [context.Background] internally; to specify the context, use
+// [Tx.ExecContext].
func (tx *Tx) Exec(query string, args ...any) (Result, error) {
return tx.ExecContext(context.Background(), query, args...)
}
// Query executes a query that returns rows, typically a SELECT.
//
-// Query uses context.Background internally; to specify the context, use
-// QueryContext.
+// Query uses [context.Background] internally; to specify the context, use
+// [Tx.QueryContext].
func (tx *Tx) Query(query string, args ...any) (*Rows, error) {
return tx.QueryContext(context.Background(), query, args...)
}
// 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's Scan will return ErrNoRows.
-// Otherwise, the *Row's Scan scans the first selected row and discards
+// [Row]'s Scan method is called.
+// If the query selects no rows, the *[Row]'s Scan will return [ErrNoRows].
+// Otherwise, the *[Row]'s Scan scans the first selected row and discards
// the rest.
func (tx *Tx) QueryRowContext(ctx context.Context, query string, args ...any) *Row {
rows, err := tx.QueryContext(ctx, query, args...)
// 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's Scan will return ErrNoRows.
-// Otherwise, the *Row's Scan scans the first selected row and discards
+// [Row]'s Scan method is called.
+// If the query selects no rows, the *[Row]'s Scan will return [ErrNoRows].
+// Otherwise, the *[Row]'s Scan scans the first selected row and discards
// the rest.
//
-// QueryRow uses context.Background internally; to specify the context, use
-// QueryRowContext.
+// QueryRow uses [context.Background] internally; to specify the context, use
+// [Tx.QueryRowContext].
func (tx *Tx) QueryRow(query string, args ...any) *Row {
return tx.QueryRowContext(context.Background(), query, args...)
}
// 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
+// 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
+// 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 {
// Immutable:
}
// ExecContext executes a prepared statement with the given arguments and
-// returns a Result summarizing the effect of the statement.
+// returns a [Result] summarizing the effect of the statement.
func (s *Stmt) ExecContext(ctx context.Context, args ...any) (Result, error) {
s.closemu.RLock()
defer s.closemu.RUnlock()
}
// Exec executes a prepared statement with the given arguments and
-// returns a Result summarizing the effect of the statement.
+// returns a [Result] summarizing the effect of the statement.
//
-// Exec uses context.Background internally; to specify the context, use
-// ExecContext.
+// Exec uses [context.Background] internally; to specify the context, use
+// [Stmt.ExecContext].
func (s *Stmt) Exec(args ...any) (Result, error) {
return s.ExecContext(context.Background(), args...)
}
}
// QueryContext executes a prepared query statement with the given arguments
-// and returns the query results as a *Rows.
+// and returns the query results as a *[Rows].
func (s *Stmt) QueryContext(ctx context.Context, args ...any) (*Rows, error) {
s.closemu.RLock()
defer s.closemu.RUnlock()
// 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
-// QueryContext.
+// Query uses [context.Background] internally; to specify the context, use
+// [Stmt.QueryContext].
func (s *Stmt) Query(args ...any) (*Rows, error) {
return s.QueryContext(context.Background(), args...)
}
// 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's Scan will return ErrNoRows.
-// Otherwise, the *Row's Scan scans the first selected row and discards
+// be returned by a call to Scan on the returned *[Row], which is always non-nil.
+// If the query selects no rows, the *[Row]'s Scan will return [ErrNoRows].
+// Otherwise, the *[Row]'s Scan scans the first selected row and discards
// the rest.
func (s *Stmt) QueryRowContext(ctx context.Context, args ...any) *Row {
rows, err := s.QueryContext(ctx, args...)
// QueryRow executes a prepared query statement with the given arguments.
// If an error occurs during the execution of the statement, that error will
-// be returned by a call to Scan on the returned *Row, which is always non-nil.
-// If the query selects no rows, the *Row's Scan will return ErrNoRows.
-// Otherwise, the *Row's Scan scans the first selected row and discards
+// be returned by a call to Scan on the returned *[Row], which is always non-nil.
+// If the query selects no rows, the *[Row]'s Scan will return [ErrNoRows].
+// Otherwise, the *[Row]'s Scan scans the first selected row and discards
// the rest.
//
// Example usage:
// var name string
// err := nameByUseridStmt.QueryRow(id).Scan(&name)
//
-// QueryRow uses context.Background internally; to specify the context, use
-// QueryRowContext.
+// QueryRow uses [context.Background] internally; to specify the context, use
+// [Stmt.QueryRowContext].
func (s *Stmt) QueryRow(args ...any) *Row {
return s.QueryRowContext(context.Background(), args...)
}
}
// Rows is the result of a query. Its cursor starts before the first row
-// of the result set. Use Next to advance from row to row.
+// of the result set. Use [Rows.Next] to advance from row to row.
type Rows struct {
dc *driverConn // owned; must call releaseConn when closed to release
releaseConn func(error)
rs.close(ctx.Err())
}
-// Next prepares the next result row for reading with the Scan method. It
+// 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. Err should be consulted to distinguish between
+// happened while preparing it. [Rows.Err] should be consulted to distinguish between
// the two cases.
//
-// Every call to Scan, even the first one, must be preceded by a call to Next.
+// Every call to [Rows.Scan], even the first one, must be preceded by a call to [Rows.Next].
func (rs *Rows) Next() bool {
// If the user's calling Next, they're done with their previous row's Scan
// results (any RawBytes memory), so we can release the read lock that would
// 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 Err method should be consulted
+// 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 Next method should always be called before
+// 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 {
}
// Err returns the error, if any, that was encountered during iteration.
-// Err may be called after an explicit or implicit Close.
+// Err may be called after an explicit or implicit [Rows.Close].
func (rs *Rows) Err() error {
// Return any context error that might've happened during row iteration,
// but only if we haven't reported the final Next() = false after rows
// 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).
+// be [math.MaxInt64] (any database limits will still apply).
// If the column type is not variable length, such as an int, or if not supported
// by the driver ok is false.
func (ci *ColumnType) Length() (length int64, ok bool) {
return ci.precision, ci.scale, ci.hasPrecisionScale
}
-// ScanType returns a Go type suitable for scanning into using Rows.Scan.
+// 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 {
// 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. Length specifiers
+// 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".
// 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.
+// 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:
// *bool
// *float32, *float64
// *interface{}
-// *RawBytes
-// *Rows (cursor value)
-// any type implementing Scanner (see Scanner docs)
+// *[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,
// 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.
+// 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
// the latter two, time.RFC3339Nano is used.
//
// Source values of type bool may be scanned into types *bool,
-// *interface{}, *string, *[]byte, or *RawBytes.
+// *interface{}, *string, *[]byte, or *[RawBytes].
//
// For scanning into *bool, the source may be true, false, 1, 0, or
-// string inputs parseable by strconv.ParseBool.
+// 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.
+// *[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,
+// 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 {
if rs.closemuScanHold {
// hook through a test only mutex.
var rowsCloseHook = func() func(*Rows, *error) { return nil }
-// Close closes the Rows, preventing further enumeration. If Next is called
+// 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 Err. Close is idempotent and does not affect the result of Err.
+// 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 {
// If the user's calling Close, they're done with their previous row's Scan
// results (any RawBytes memory), so we can release the read lock that would
}
// Scan copies the columns from the matched row into the values
-// pointed at by dest. See the documentation on Rows.Scan for details.
+// 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.
+// the query, Scan returns [ErrNoRows].
func (r *Row) Scan(dest ...any) error {
if r.err != nil {
return r.err
}
// Err provides a way for wrapping packages to check for
-// query errors without calling Scan.
+// 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 Scan.
+// If this error is not nil, this error will also be returned from [Row.Scan].
func (r *Row) Err() error {
return r.err
}