Movatterモバイル変換


[0]ホーム

URL:


driver

packagestandard library
go1.25.5Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 2, 2025 License:BSD-3-ClauseImports:6Imported by:32,482

Details

Repository

cs.opensource.google/go/go

Links

Documentation

Overview

Package driver defines interfaces to be implemented by databasedrivers as used by package sql.

Most code should use thedatabase/sql package.

The driver interface has evolved over time. Drivers should implementConnector andDriverContext interfaces.The Connector.Connect and Driver.Open methods should never returnErrBadConn.ErrBadConn should only be returned fromValidator,SessionResetter, ora query method if the connection is already in an invalid (e.g. closed) state.

AllConn implementations should implement the following interfaces:Pinger,SessionResetter, andValidator.

If named parameters or context are supported, the driver'sConn should implement:ExecerContext,QueryerContext,ConnPrepareContext, andConnBeginTx.

To support custom data types, implementNamedValueChecker.NamedValueCheckeralso allows queries to accept per-query options as a parameter by returningErrRemoveArgument from CheckNamedValue.

If multiple result sets are supported,Rows should implementRowsNextResultSet.If the driver knows how to describe the types present in the returned resultit should implement the following interfaces:RowsColumnTypeScanType,RowsColumnTypeDatabaseTypeName,RowsColumnTypeLength,RowsColumnTypeNullable,andRowsColumnTypePrecisionScale. A given row value may also return aRowstype, which may represent a database cursor value.

If aConn implementsValidator, then the IsValid method is calledbefore returning the connection to the connection pool. If an entry in theconnection pool implementsSessionResetter, then ResetSessionis called before reusing the connection for another query. If a connection isnever returned to the connection pool but is immediately reused, thenResetSession is called prior to reuse but IsValid is not called.

Index

Constants

This section is empty.

Variables

View Source
var Bool boolType

Bool is aValueConverter that converts input values to bool.

The conversion rules are:

  • booleans are returned unchanged
  • for integer types,1 is true0 is false,other integers are an error
  • for strings and []byte, same rules asstrconv.ParseBool
  • all other types are an error
View Source
var DefaultParameterConverter defaultConverter

DefaultParameterConverter is the default implementation ofValueConverter that's used when aStmt doesn't implementColumnConverter.

DefaultParameterConverter returns its argument directly ifIsValue(arg). Otherwise, if the argument implementsValuer, itsValue method is used to return aValue. As a fallback, the providedargument's underlying type is used to convert it to aValue:underlying integer types are converted to int64, floats to float64,bool, string, and []byte to themselves. If the argument is a nilpointer, defaultConverter.ConvertValue returns a nilValue.If the argument is a non-nil pointer, it is dereferenced anddefaultConverter.ConvertValue is called recursively. Other typesare an error.

View Source
var ErrBadConn =errors.New("driver: bad connection")

ErrBadConn should be returned by a driver to signal to thedatabase/sqlpackage that a driver.Conn is in a bad state (such as the serverhaving earlier closed the connection) and thedatabase/sql package shouldretry on a new connection.

To prevent duplicate operations, ErrBadConn should NOT be returnedif there's a possibility that the database server might haveperformed the operation. Even if the server sends back an error,you shouldn't return ErrBadConn.

Errors will be checked usingerrors.Is. An error maywrap ErrBadConn or implement the Is(error) bool method.

View Source
var ErrRemoveArgument =errors.New("driver: remove argument from query")

ErrRemoveArgument may be returned fromNamedValueChecker to instruct thedatabase/sql package to not pass the argument to the driver query interface.Return when accepting query specific options or structures that aren'tSQL query arguments.

View Source
var ErrSkip =errors.New("driver: skip fast-path; continue as if unimplemented")

ErrSkip may be returned by some optional interfaces' methods toindicate at runtime that the fast path is unavailable and the sqlpackage should continue as if the optional interface was notimplemented. ErrSkip is only supported where explicitlydocumented.

View Source
var Int32 int32Type

Int32 is aValueConverter that converts input values to int64,respecting the limits of an int32 value.

View Source
var ResultNoRows noRows

ResultNoRows is a pre-definedResult for drivers to return when a DDLcommand (such as a CREATE TABLE) succeeds. It returns an error for bothLastInsertId andRowsAffected.

View Source
var String stringType

String is aValueConverter that converts its input to a string.If the value is already a string or []byte, it's unchanged.If the value is of another type, conversion to string is donewith fmt.Sprintf("%v", v).

Functions

funcIsScanValue

func IsScanValue(vany)bool

IsScanValue is equivalent toIsValue.It exists for compatibility.

funcIsValue

func IsValue(vany)bool

IsValue reports whether v is a validValue parameter type.

Types

typeColumnConverterdeprecated

type ColumnConverter interface {// ColumnConverter returns a ValueConverter for the provided// column index. If the type of a specific column isn't known// or shouldn't be handled specially, [DefaultParameterConverter]// can be returned.ColumnConverter(idxint)ValueConverter}

ColumnConverter may be optionally implemented byStmt if thestatement is aware of its own columns' types and can convert fromany type to a driverValue.

Deprecated: Drivers should implementNamedValueChecker.

typeConn

type Conn interface {// Prepare returns a prepared statement, bound to this connection.Prepare(querystring) (Stmt,error)// Close invalidates and potentially stops any current// prepared statements and transactions, marking this// connection as no longer in use.//// Because the sql package maintains a free pool of// connections and only calls Close when there's a surplus of// idle connections, it shouldn't be necessary for drivers to// do their own connection caching.//// Drivers must ensure all network calls made by Close// do not block indefinitely (e.g. apply a timeout).Close()error// Begin starts and returns a new transaction.//// Deprecated: Drivers should implement ConnBeginTx instead (or additionally).Begin() (Tx,error)}

Conn is a connection to a database. It is not used concurrentlyby multiple goroutines.

Conn is assumed to be stateful.

typeConnBeginTxadded ingo1.8

type ConnBeginTx interface {// BeginTx starts and returns a new transaction.// If the context is canceled by the user the sql package will// call Tx.Rollback before discarding and closing the connection.//// This must check opts.Isolation to determine if there is a set// isolation level. If the driver does not support a non-default// level and one is set or if there is a non-default isolation level// that is not supported, an error must be returned.//// This must also check opts.ReadOnly to determine if the read-only// value is true to either set the read-only transaction property if supported// or return an error if it is not supported.BeginTx(ctxcontext.Context, optsTxOptions) (Tx,error)}

ConnBeginTx enhances theConn interface with context andTxOptions.

typeConnPrepareContextadded ingo1.8

type ConnPrepareContext interface {// PrepareContext returns a prepared statement, bound to this connection.// context is for the preparation of the statement,// it must not store the context within the statement itself.PrepareContext(ctxcontext.Context, querystring) (Stmt,error)}

ConnPrepareContext enhances theConn interface with context.

typeConnectoradded ingo1.10

type Connector interface {// Connect returns a connection to the database.// Connect may return a cached connection (one previously// closed), but doing so is unnecessary; the sql package// maintains a pool of idle connections for efficient re-use.//// The provided context.Context is for dialing purposes only// (see net.DialContext) and should not be stored or used for// other purposes. A default timeout should still be used// when dialing as a connection pool may call Connect// asynchronously to any query.//// The returned connection is only used by one goroutine at a// time.Connect(context.Context) (Conn,error)// Driver returns the underlying Driver of the Connector,// mainly to maintain compatibility with the Driver method// on sql.DB.Driver()Driver}

A Connector represents a driver in a fixed configurationand can create any number of equivalent Conns for useby multiple goroutines.

A Connector can be passed todatabase/sql.OpenDB, to allow driversto implement their owndatabase/sql.DB constructors, or returned byDriverContext's OpenConnector method, to allow driversaccess to context and to avoid repeated parsing of driverconfiguration.

If a Connector implementsio.Closer, thedatabase/sql.DB.Closemethod will call the Close method and return error (if any).

typeDriver

type Driver interface {// Open returns a new connection to the database.// The name is a string in a driver-specific format.//// Open may return a cached connection (one previously// closed), but doing so is unnecessary; the sql package// maintains a pool of idle connections for efficient re-use.//// The returned connection is only used by one goroutine at a// time.Open(namestring) (Conn,error)}

Driver is the interface that must be implemented by a databasedriver.

Database drivers may implementDriverContext for accessto contexts and to parse the name only once for a pool of connections,instead of once per connection.

typeDriverContextadded ingo1.10

type DriverContext interface {// OpenConnector must parse the name in the same format that Driver.Open// parses the name parameter.OpenConnector(namestring) (Connector,error)}

If aDriver implements DriverContext, thendatabase/sql.DB will callOpenConnector to obtain aConnector and then invokethatConnector's Connect method to obtain each needed connection,instead of invoking theDriver's Open method for each connection.The two-step sequence allows drivers to parse the name just onceand also provides access to per-Conn contexts.

typeExecerdeprecated

type Execer interface {Exec(querystring, args []Value) (Result,error)}

Execer is an optional interface that may be implemented by aConn.

If aConn implements neitherExecerContext norExecer,thedatabase/sql.DB.Exec will first prepare a query, execute the statement,and then close the statement.

Exec may returnErrSkip.

Deprecated: Drivers should implementExecerContext instead.

typeExecerContextadded ingo1.8

type ExecerContext interface {ExecContext(ctxcontext.Context, querystring, args []NamedValue) (Result,error)}

ExecerContext is an optional interface that may be implemented by aConn.

If aConn does not implementExecerContext, thedatabase/sql.DB.Execwill fall back toExecer; if the Conn does not implement Execer either,database/sql.DB.Exec will first prepare a query, execute the statement, and thenclose the statement.

ExecContext may returnErrSkip.

ExecContext must honor the context timeout and return when the context is canceled.

typeIsolationLeveladded ingo1.8

type IsolationLevelint

IsolationLevel is the transaction isolation level stored inTxOptions.

This type should be considered identical todatabase/sql.IsolationLevel alongwith any values defined on it.

typeNamedValueadded ingo1.8

type NamedValue struct {// If the Name is not empty it should be used for the parameter identifier and// not the ordinal position.//// Name will not have a symbol prefix.Namestring// Ordinal position of the parameter starting from one and is always set.Ordinalint// Value is the parameter value.ValueValue}

NamedValue holds both the value name and value.

typeNamedValueCheckeradded ingo1.9

type NamedValueChecker interface {// CheckNamedValue is called before passing arguments to the driver// and is called in place of any ColumnConverter. CheckNamedValue must do type// validation and conversion as appropriate for the driver.CheckNamedValue(*NamedValue)error}

NamedValueChecker may be optionally implemented byConn orStmt. It providesthe driver more control to handle Go and database types beyond the defaultValue types allowed.

Thedatabase/sql package checks for value checkers in the following order,stopping at the first found match: Stmt.NamedValueChecker, Conn.NamedValueChecker,Stmt.ColumnConverter,DefaultParameterConverter.

If CheckNamedValue returnsErrRemoveArgument, theNamedValue will not be included inthe final query arguments. This may be used to pass special options tothe query itself.

IfErrSkip is returned the column converter error checkingpath is used for the argument. Drivers may wish to returnErrSkip afterthey have exhausted their own special cases.

typeNotNull

type NotNull struct {ConverterValueConverter}

NotNull is a type that implementsValueConverter by disallowing nilvalues but otherwise delegating to anotherValueConverter.

func (NotNull)ConvertValue

func (nNotNull) ConvertValue(vany) (Value,error)

typeNull

type Null struct {ConverterValueConverter}

Null is a type that implementsValueConverter by allowing nilvalues but otherwise delegating to anotherValueConverter.

func (Null)ConvertValue

func (nNull) ConvertValue(vany) (Value,error)

typePingeradded ingo1.8

type Pinger interface {Ping(ctxcontext.Context)error}

Pinger is an optional interface that may be implemented by aConn.

If aConn does not implement Pinger, thedatabase/sql.DB.Ping anddatabase/sql.DB.PingContext will check if there is at least oneConn available.

If Conn.Ping returnsErrBadConn,database/sql.DB.Ping anddatabase/sql.DB.PingContext will removetheConn from pool.

typeQueryerdeprecatedadded ingo1.1

type Queryer interface {Query(querystring, args []Value) (Rows,error)}

Queryer is an optional interface that may be implemented by aConn.

If aConn implements neitherQueryerContext norQueryer,thedatabase/sql.DB.Query will first prepare a query, execute the statement,and then close the statement.

Query may returnErrSkip.

Deprecated: Drivers should implementQueryerContext instead.

typeQueryerContextadded ingo1.8

type QueryerContext interface {QueryContext(ctxcontext.Context, querystring, args []NamedValue) (Rows,error)}

QueryerContext is an optional interface that may be implemented by aConn.

If aConn does not implement QueryerContext, thedatabase/sql.DB.Querywill fall back toQueryer; if theConn does not implementQueryer either,database/sql.DB.Query will first prepare a query, execute the statement, and thenclose the statement.

QueryContext may returnErrSkip.

QueryContext must honor the context timeout and return when the context is canceled.

typeResult

type Result interface {// LastInsertId returns the database's auto-generated ID// after, for example, an INSERT into a table with primary// key.LastInsertId() (int64,error)// RowsAffected returns the number of rows affected by the// query.RowsAffected() (int64,error)}

Result is the result of a query execution.

typeRows

type Rows interface {// Columns returns the names of the columns. The number of// columns of the result is inferred from the length of the// slice. If a particular column name isn't known, an empty// string should be returned for that entry.Columns() []string// Close closes the rows iterator.Close()error// Next is called to populate the next row of data into// the provided slice. The provided slice will be the same// size as the Columns() are wide.//// Next should return io.EOF when there are no more rows.//// The dest should not be written to outside of Next. Care// should be taken when closing Rows not to modify// a buffer held in dest.Next(dest []Value)error}

Rows is an iterator over an executed query's results.

typeRowsAffected

type RowsAffectedint64

RowsAffected implementsResult for an INSERT or UPDATE operationwhich mutates a number of rows.

func (RowsAffected)LastInsertId

func (RowsAffected) LastInsertId() (int64,error)

func (RowsAffected)RowsAffected

func (vRowsAffected) RowsAffected() (int64,error)

typeRowsColumnTypeDatabaseTypeNameadded ingo1.8

type RowsColumnTypeDatabaseTypeName interface {RowsColumnTypeDatabaseTypeName(indexint)string}

RowsColumnTypeDatabaseTypeName may be implemented byRows. It should return thedatabase 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","TIMESTAMP".

typeRowsColumnTypeLengthadded ingo1.8

type RowsColumnTypeLength interface {RowsColumnTypeLength(indexint) (lengthint64, okbool)}

RowsColumnTypeLength may be implemented byRows. It should return the lengthof the column type if the column is a variable length type. If the column isnot a variable length type ok should return false.If length is not limited other than system limits, it should returnmath.MaxInt64.The following are examples of returned values for various types:

TEXT          (math.MaxInt64, true)varchar(10)   (10, true)nvarchar(10)  (10, true)decimal       (0, false)int           (0, false)bytea(30)     (30, true)

typeRowsColumnTypeNullableadded ingo1.8

type RowsColumnTypeNullable interface {RowsColumnTypeNullable(indexint) (nullable, okbool)}

RowsColumnTypeNullable may be implemented byRows. The nullable value shouldbe true if it is known the column may be null, or false if the column is knownto be not nullable.If the column nullability is unknown, ok should be false.

typeRowsColumnTypePrecisionScaleadded ingo1.8

type RowsColumnTypePrecisionScale interface {RowsColumnTypePrecisionScale(indexint) (precision, scaleint64, okbool)}

RowsColumnTypePrecisionScale may be implemented byRows. It should returnthe precision and scale for decimal types. If not applicable, ok should be false.The following are examples of returned values for various types:

decimal(38, 4)    (38, 4, true)int               (0, 0, false)decimal           (math.MaxInt64, math.MaxInt64, true)

typeRowsColumnTypeScanTypeadded ingo1.8

type RowsColumnTypeScanType interface {RowsColumnTypeScanType(indexint)reflect.Type}

RowsColumnTypeScanType may be implemented byRows. It should returnthe value type that can be used to scan types into. For example, the databasecolumn type "bigint" this should return "reflect.TypeOf(int64(0))".

typeRowsNextResultSetadded ingo1.8

type RowsNextResultSet interface {Rows// HasNextResultSet is called at the end of the current result set and// reports whether there is another result set after the current one.HasNextResultSet()bool// NextResultSet advances the driver to the next result set even// if there are remaining rows in the current result set.//// NextResultSet should return io.EOF when there are no more result sets.NextResultSet()error}

RowsNextResultSet extends theRows interface by providing a way to signalthe driver to advance to the next result set.

typeSessionResetteradded ingo1.10

type SessionResetter interface {// ResetSession is called prior to executing a query on the connection// if the connection has been used before. If the driver returns ErrBadConn// the connection is discarded.ResetSession(ctxcontext.Context)error}

SessionResetter may be implemented byConn to allow drivers to reset thesession state associated with the connection and to signal a bad connection.

typeStmt

type Stmt interface {// Close closes the statement.//// As of Go 1.1, a Stmt will not be closed if it's in use// by any queries.//// Drivers must ensure all network calls made by Close// do not block indefinitely (e.g. apply a timeout).Close()error// NumInput returns the number of placeholder parameters.//// If NumInput returns >= 0, the sql package will sanity check// argument counts from callers and return errors to the caller// before the statement's Exec or Query methods are called.//// NumInput may also return -1, if the driver doesn't know// its number of placeholders. In that case, the sql package// will not sanity check Exec or Query argument counts.NumInput()int// Exec executes a query that doesn't return rows, such// as an INSERT or UPDATE.//// Deprecated: Drivers should implement StmtExecContext instead (or additionally).Exec(args []Value) (Result,error)// Query executes a query that may return rows, such as a// SELECT.//// Deprecated: Drivers should implement StmtQueryContext instead (or additionally).Query(args []Value) (Rows,error)}

Stmt is a prepared statement. It is bound to aConn and notused by multiple goroutines concurrently.

typeStmtExecContextadded ingo1.8

type StmtExecContext interface {// ExecContext executes a query that doesn't return rows, such// as an INSERT or UPDATE.//// ExecContext must honor the context timeout and return when it is canceled.ExecContext(ctxcontext.Context, args []NamedValue) (Result,error)}

StmtExecContext enhances theStmt interface by providing Exec with context.

typeStmtQueryContextadded ingo1.8

type StmtQueryContext interface {// QueryContext executes a query that may return rows, such as a// SELECT.//// QueryContext must honor the context timeout and return when it is canceled.QueryContext(ctxcontext.Context, args []NamedValue) (Rows,error)}

StmtQueryContext enhances theStmt interface by providing Query with context.

typeTx

type Tx interface {Commit()errorRollback()error}

Tx is a transaction.

typeTxOptionsadded ingo1.8

type TxOptions struct {IsolationIsolationLevelReadOnlybool}

TxOptions holds the transaction options.

This type should be considered identical todatabase/sql.TxOptions.

typeValidatoradded ingo1.15

type Validator interface {// IsValid is called prior to placing the connection into the// connection pool. The connection will be discarded if false is returned.IsValid()bool}

Validator may be implemented byConn to allow drivers tosignal if a connection is valid or if it should be discarded.

If implemented, drivers may return the underlying error from queries,even if the connection should be discarded by the connection pool.

typeValue

type Valueany

Value is a value that drivers must be able to handle.It is either nil, a type handled by a database driver'sNamedValueCheckerinterface, or an instance of one of these types:

int64float64bool[]bytestringtime.Time

If the driver supports cursors, a returned Value may also implement theRows interfacein this package. This is used, for example, when a user selects a cursorsuch as "select cursor(select * from my_table) from dual". If theRowsfrom the select is closed, the cursorRows will also be closed.

typeValueConverter

type ValueConverter interface {// ConvertValue converts a value to a driver Value.ConvertValue(vany) (Value,error)}

ValueConverter is the interface providing the ConvertValue method.

Various implementations of ValueConverter are provided by thedriver package to provide consistent implementations of conversionsbetween drivers. The ValueConverters have several uses:

  • converting from theValue types as provided by the sql packageinto a database table's specific column type and making sure itfits, such as making sure a particular int64 fits in atable's uint16 column.

  • converting a value as given from the database into one of thedriverValue types.

  • by thedatabase/sql package, for converting from a driver'sValue typeto a user's type in a scan.

typeValuer

type Valuer interface {// Value returns a driver Value.// Value must not panic.Value() (Value,error)}

Valuer is the interface providing the Value method.

Errors returned by theValue method are wrapped by the database/sql package.This allows callers to useerrors.Is for precise error handling after operationslikedatabase/sql.Query,database/sql.Exec, ordatabase/sql.QueryRow.

Types implementing Valuer interface are able to convertthemselves to a driverValue.

Source Files

View all Source files

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f orF : Jump to
y orY : Canonical URL
go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic.Learn more.

[8]ページ先頭

©2009-2025 Movatter.jp