Black Lives Matter. Support the Equal Justice Initiative.

Source file src/database/sql/driver/driver.go

Documentation: database/sql/driver

     1  // Copyright 2011 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Package driver defines interfaces to be implemented by database
     6  // drivers as used by package sql.
     7  //
     8  // Most code should use package sql.
     9  //
    10  // The driver interface has evolved over time. Drivers should implement
    11  // Connector and DriverContext interfaces.
    12  // The Connector.Connect and Driver.Open methods should never return ErrBadConn.
    13  // ErrBadConn should only be returned from Validator, SessionResetter, or
    14  // a query method if the connection is already in an invalid (e.g. closed) state.
    15  //
    16  // All Conn implementations should implement the following interfaces:
    17  // Pinger, SessionResetter, and Validator.
    18  //
    19  // If named parameters or context are supported, the driver's Conn should implement:
    20  // ExecerContext, QueryerContext, ConnPrepareContext, and ConnBeginTx.
    21  //
    22  // To support custom data types, implement NamedValueChecker. NamedValueChecker
    23  // also allows queries to accept per-query options as a parameter by returning
    24  // ErrRemoveArgument from CheckNamedValue.
    25  //
    26  // If multiple result sets are supported, Rows should implement RowsNextResultSet.
    27  // If the driver knows how to describe the types present in the returned result
    28  // it should implement the following interfaces: RowsColumnTypeScanType,
    29  // RowsColumnTypeDatabaseTypeName, RowsColumnTypeLength, RowsColumnTypeNullable,
    30  // and RowsColumnTypePrecisionScale. A given row value may also return a Rows
    31  // type, which may represent a database cursor value.
    32  //
    33  // Before a connection is returned to the connection pool after use, IsValid is
    34  // called if implemented. Before a connection is reused for another query,
    35  // ResetSession is called if implemented. If a connection is never returned to the
    36  // connection pool but immediately reused, then ResetSession is called prior to
    37  // reuse but IsValid is not called.
    38  package driver
    39  
    40  import (
    41  	"context"
    42  	"errors"
    43  	"reflect"
    44  )
    45  
    46  // Value is a value that drivers must be able to handle.
    47  // It is either nil, a type handled by a database driver's NamedValueChecker
    48  // interface, or an instance of one of these types:
    49  //
    50  //   int64
    51  //   float64
    52  //   bool
    53  //   []byte
    54  //   string
    55  //   time.Time
    56  //
    57  // If the driver supports cursors, a returned Value may also implement the Rows interface
    58  // in this package. This is used, for example, when a user selects a cursor
    59  // such as "select cursor(select * from my_table) from dual". If the Rows
    60  // from the select is closed, the cursor Rows will also be closed.
    61  type Value interface{}
    62  
    63  // NamedValue holds both the value name and value.
    64  type NamedValue struct {
    65  	// If the Name is not empty it should be used for the parameter identifier and
    66  	// not the ordinal position.
    67  	//
    68  	// Name will not have a symbol prefix.
    69  	Name string
    70  
    71  	// Ordinal position of the parameter starting from one and is always set.
    72  	Ordinal int
    73  
    74  	// Value is the parameter value.
    75  	Value Value
    76  }
    77  
    78  // Driver is the interface that must be implemented by a database
    79  // driver.
    80  //
    81  // Database drivers may implement DriverContext for access
    82  // to contexts and to parse the name only once for a pool of connections,
    83  // instead of once per connection.
    84  type Driver interface {
    85  	// Open returns a new connection to the database.
    86  	// The name is a string in a driver-specific format.
    87  	//
    88  	// Open may return a cached connection (one previously
    89  	// closed), but doing so is unnecessary; the sql package
    90  	// maintains a pool of idle connections for efficient re-use.
    91  	//
    92  	// The returned connection is only used by one goroutine at a
    93  	// time.
    94  	Open(name string) (Conn, error)
    95  }
    96  
    97  // If a Driver implements DriverContext, then sql.DB will call
    98  // OpenConnector to obtain a Connector and then invoke
    99  // that Connector's Connect method to obtain each needed connection,
   100  // instead of invoking the Driver's Open method for each connection.
   101  // The two-step sequence allows drivers to parse the name just once
   102  // and also provides access to per-Conn contexts.
   103  type DriverContext interface {
   104  	// OpenConnector must parse the name in the same format that Driver.Open
   105  	// parses the name parameter.
   106  	OpenConnector(name string) (Connector, error)
   107  }
   108  
   109  // A Connector represents a driver in a fixed configuration
   110  // and can create any number of equivalent Conns for use
   111  // by multiple goroutines.
   112  //
   113  // A Connector can be passed to sql.OpenDB, to allow drivers
   114  // to implement their own sql.DB constructors, or returned by
   115  // DriverContext's OpenConnector method, to allow drivers
   116  // access to context and to avoid repeated parsing of driver
   117  // configuration.
   118  type Connector interface {
   119  	// Connect returns a connection to the database.
   120  	// Connect may return a cached connection (one previously
   121  	// closed), but doing so is unnecessary; the sql package
   122  	// maintains a pool of idle connections for efficient re-use.
   123  	//
   124  	// The provided context.Context is for dialing purposes only
   125  	// (see net.DialContext) and should not be stored or used for
   126  	// other purposes. A default timeout should still be used
   127  	// when dialing as a connection pool may call Connect
   128  	// asynchronously to any query.
   129  	//
   130  	// The returned connection is only used by one goroutine at a
   131  	// time.
   132  	Connect(context.Context) (Conn, error)
   133  
   134  	// Driver returns the underlying Driver of the Connector,
   135  	// mainly to maintain compatibility with the Driver method
   136  	// on sql.DB.
   137  	Driver() Driver
   138  }
   139  
   140  // ErrSkip may be returned by some optional interfaces' methods to
   141  // indicate at runtime that the fast path is unavailable and the sql
   142  // package should continue as if the optional interface was not
   143  // implemented. ErrSkip is only supported where explicitly
   144  // documented.
   145  var ErrSkip = errors.New("driver: skip fast-path; continue as if unimplemented")
   146  
   147  // ErrBadConn should be returned by a driver to signal to the sql
   148  // package that a driver.Conn is in a bad state (such as the server
   149  // having earlier closed the connection) and the sql package should
   150  // retry on a new connection.
   151  //
   152  // To prevent duplicate operations, ErrBadConn should NOT be returned
   153  // if there's a possibility that the database server might have
   154  // performed the operation. Even if the server sends back an error,
   155  // you shouldn't return ErrBadConn.
   156  var ErrBadConn = errors.New("driver: bad connection")
   157  
   158  // Pinger is an optional interface that may be implemented by a Conn.
   159  //
   160  // If a Conn does not implement Pinger, the sql package's DB.Ping and
   161  // DB.PingContext will check if there is at least one Conn available.
   162  //
   163  // If Conn.Ping returns ErrBadConn, DB.Ping and DB.PingContext will remove
   164  // the Conn from pool.
   165  type Pinger interface {
   166  	Ping(ctx context.Context) error
   167  }
   168  
   169  // Execer is an optional interface that may be implemented by a Conn.
   170  //
   171  // If a Conn implements neither ExecerContext nor Execer,
   172  // the sql package's DB.Exec will first prepare a query, execute the statement,
   173  // and then close the statement.
   174  //
   175  // Exec may return ErrSkip.
   176  //
   177  // Deprecated: Drivers should implement ExecerContext instead.
   178  type Execer interface {
   179  	Exec(query string, args []Value) (Result, error)
   180  }
   181  
   182  // ExecerContext is an optional interface that may be implemented by a Conn.
   183  //
   184  // If a Conn does not implement ExecerContext, the sql package's DB.Exec
   185  // will fall back to Execer; if the Conn does not implement Execer either,
   186  // DB.Exec will first prepare a query, execute the statement, and then
   187  // close the statement.
   188  //
   189  // ExecerContext may return ErrSkip.
   190  //
   191  // ExecerContext must honor the context timeout and return when the context is canceled.
   192  type ExecerContext interface {
   193  	ExecContext(ctx context.Context, query string, args []NamedValue) (Result, error)
   194  }
   195  
   196  // Queryer is an optional interface that may be implemented by a Conn.
   197  //
   198  // If a Conn implements neither QueryerContext nor Queryer,
   199  // the sql package's DB.Query will first prepare a query, execute the statement,
   200  // and then close the statement.
   201  //
   202  // Query may return ErrSkip.
   203  //
   204  // Deprecated: Drivers should implement QueryerContext instead.
   205  type Queryer interface {
   206  	Query(query string, args []Value) (Rows, error)
   207  }
   208  
   209  // QueryerContext is an optional interface that may be implemented by a Conn.
   210  //
   211  // If a Conn does not implement QueryerContext, the sql package's DB.Query
   212  // will fall back to Queryer; if the Conn does not implement Queryer either,
   213  // DB.Query will first prepare a query, execute the statement, and then
   214  // close the statement.
   215  //
   216  // QueryerContext may return ErrSkip.
   217  //
   218  // QueryerContext must honor the context timeout and return when the context is canceled.
   219  type QueryerContext interface {
   220  	QueryContext(ctx context.Context, query string, args []NamedValue) (Rows, error)
   221  }
   222  
   223  // Conn is a connection to a database. It is not used concurrently
   224  // by multiple goroutines.
   225  //
   226  // Conn is assumed to be stateful.
   227  type Conn interface {
   228  	// Prepare returns a prepared statement, bound to this connection.
   229  	Prepare(query string) (Stmt, error)
   230  
   231  	// Close invalidates and potentially stops any current
   232  	// prepared statements and transactions, marking this
   233  	// connection as no longer in use.
   234  	//
   235  	// Because the sql package maintains a free pool of
   236  	// connections and only calls Close when there's a surplus of
   237  	// idle connections, it shouldn't be necessary for drivers to
   238  	// do their own connection caching.
   239  	//
   240  	// Drivers must ensure all network calls made by Close
   241  	// do not block indefinitely (e.g. apply a timeout).
   242  	Close() error
   243  
   244  	// Begin starts and returns a new transaction.
   245  	//
   246  	// Deprecated: Drivers should implement ConnBeginTx instead (or additionally).
   247  	Begin() (Tx, error)
   248  }
   249  
   250  // ConnPrepareContext enhances the Conn interface with context.
   251  type ConnPrepareContext interface {
   252  	// PrepareContext returns a prepared statement, bound to this connection.
   253  	// context is for the preparation of the statement,
   254  	// it must not store the context within the statement itself.
   255  	PrepareContext(ctx context.Context, query string) (Stmt, error)
   256  }
   257  
   258  // IsolationLevel is the transaction isolation level stored in TxOptions.
   259  //
   260  // This type should be considered identical to sql.IsolationLevel along
   261  // with any values defined on it.
   262  type IsolationLevel int
   263  
   264  // TxOptions holds the transaction options.
   265  //
   266  // This type should be considered identical to sql.TxOptions.
   267  type TxOptions struct {
   268  	Isolation IsolationLevel
   269  	ReadOnly  bool
   270  }
   271  
   272  // ConnBeginTx enhances the Conn interface with context and TxOptions.
   273  type ConnBeginTx interface {
   274  	// BeginTx starts and returns a new transaction.
   275  	// If the context is canceled by the user the sql package will
   276  	// call Tx.Rollback before discarding and closing the connection.
   277  	//
   278  	// This must check opts.Isolation to determine if there is a set
   279  	// isolation level. If the driver does not support a non-default
   280  	// level and one is set or if there is a non-default isolation level
   281  	// that is not supported, an error must be returned.
   282  	//
   283  	// This must also check opts.ReadOnly to determine if the read-only
   284  	// value is true to either set the read-only transaction property if supported
   285  	// or return an error if it is not supported.
   286  	BeginTx(ctx context.Context, opts TxOptions) (Tx, error)
   287  }
   288  
   289  // SessionResetter may be implemented by Conn to allow drivers to reset the
   290  // session state associated with the connection and to signal a bad connection.
   291  type SessionResetter interface {
   292  	// ResetSession is called prior to executing a query on the connection
   293  	// if the connection has been used before. If the driver returns ErrBadConn
   294  	// the connection is discarded.
   295  	ResetSession(ctx context.Context) error
   296  }
   297  
   298  // Validator may be implemented by Conn to allow drivers to
   299  // signal if a connection is valid or if it should be discarded.
   300  //
   301  // If implemented, drivers may return the underlying error from queries,
   302  // even if the connection should be discarded by the connection pool.
   303  type Validator interface {
   304  	// IsValid is called prior to placing the connection into the
   305  	// connection pool. The connection will be discarded if false is returned.
   306  	IsValid() bool
   307  }
   308  
   309  // Result is the result of a query execution.
   310  type Result interface {
   311  	// LastInsertId returns the database's auto-generated ID
   312  	// after, for example, an INSERT into a table with primary
   313  	// key.
   314  	LastInsertId() (int64, error)
   315  
   316  	// RowsAffected returns the number of rows affected by the
   317  	// query.
   318  	RowsAffected() (int64, error)
   319  }
   320  
   321  // Stmt is a prepared statement. It is bound to a Conn and not
   322  // used by multiple goroutines concurrently.
   323  type Stmt interface {
   324  	// Close closes the statement.
   325  	//
   326  	// As of Go 1.1, a Stmt will not be closed if it's in use
   327  	// by any queries.
   328  	//
   329  	// Drivers must ensure all network calls made by Close
   330  	// do not block indefinitely (e.g. apply a timeout).
   331  	Close() error
   332  
   333  	// NumInput returns the number of placeholder parameters.
   334  	//
   335  	// If NumInput returns >= 0, the sql package will sanity check
   336  	// argument counts from callers and return errors to the caller
   337  	// before the statement's Exec or Query methods are called.
   338  	//
   339  	// NumInput may also return -1, if the driver doesn't know
   340  	// its number of placeholders. In that case, the sql package
   341  	// will not sanity check Exec or Query argument counts.
   342  	NumInput() int
   343  
   344  	// Exec executes a query that doesn't return rows, such
   345  	// as an INSERT or UPDATE.
   346  	//
   347  	// Deprecated: Drivers should implement StmtExecContext instead (or additionally).
   348  	Exec(args []Value) (Result, error)
   349  
   350  	// Query executes a query that may return rows, such as a
   351  	// SELECT.
   352  	//
   353  	// Deprecated: Drivers should implement StmtQueryContext instead (or additionally).
   354  	Query(args []Value) (Rows, error)
   355  }
   356  
   357  // StmtExecContext enhances the Stmt interface by providing Exec with context.
   358  type StmtExecContext interface {
   359  	// ExecContext executes a query that doesn't return rows, such
   360  	// as an INSERT or UPDATE.
   361  	//
   362  	// ExecContext must honor the context timeout and return when it is canceled.
   363  	ExecContext(ctx context.Context, args []NamedValue) (Result, error)
   364  }
   365  
   366  // StmtQueryContext enhances the Stmt interface by providing Query with context.
   367  type StmtQueryContext interface {
   368  	// QueryContext executes a query that may return rows, such as a
   369  	// SELECT.
   370  	//
   371  	// QueryContext must honor the context timeout and return when it is canceled.
   372  	QueryContext(ctx context.Context, args []NamedValue) (Rows, error)
   373  }
   374  
   375  // ErrRemoveArgument may be returned from NamedValueChecker to instruct the
   376  // sql package to not pass the argument to the driver query interface.
   377  // Return when accepting query specific options or structures that aren't
   378  // SQL query arguments.
   379  var ErrRemoveArgument = errors.New("driver: remove argument from query")
   380  
   381  // NamedValueChecker may be optionally implemented by Conn or Stmt. It provides
   382  // the driver more control to handle Go and database types beyond the default
   383  // Values types allowed.
   384  //
   385  // The sql package checks for value checkers in the following order,
   386  // stopping at the first found match: Stmt.NamedValueChecker, Conn.NamedValueChecker,
   387  // Stmt.ColumnConverter, DefaultParameterConverter.
   388  //
   389  // If CheckNamedValue returns ErrRemoveArgument, the NamedValue will not be included in
   390  // the final query arguments. This may be used to pass special options to
   391  // the query itself.
   392  //
   393  // If ErrSkip is returned the column converter error checking
   394  // path is used for the argument. Drivers may wish to return ErrSkip after
   395  // they have exhausted their own special cases.
   396  type NamedValueChecker interface {
   397  	// CheckNamedValue is called before passing arguments to the driver
   398  	// and is called in place of any ColumnConverter. CheckNamedValue must do type
   399  	// validation and conversion as appropriate for the driver.
   400  	CheckNamedValue(*NamedValue) error
   401  }
   402  
   403  // ColumnConverter may be optionally implemented by Stmt if the
   404  // statement is aware of its own columns' types and can convert from
   405  // any type to a driver Value.
   406  //
   407  // Deprecated: Drivers should implement NamedValueChecker.
   408  type ColumnConverter interface {
   409  	// ColumnConverter returns a ValueConverter for the provided
   410  	// column index. If the type of a specific column isn't known
   411  	// or shouldn't be handled specially, DefaultValueConverter
   412  	// can be returned.
   413  	ColumnConverter(idx int) ValueConverter
   414  }
   415  
   416  // Rows is an iterator over an executed query's results.
   417  type Rows interface {
   418  	// Columns returns the names of the columns. The number of
   419  	// columns of the result is inferred from the length of the
   420  	// slice. If a particular column name isn't known, an empty
   421  	// string should be returned for that entry.
   422  	Columns() []string
   423  
   424  	// Close closes the rows iterator.
   425  	Close() error
   426  
   427  	// Next is called to populate the next row of data into
   428  	// the provided slice. The provided slice will be the same
   429  	// size as the Columns() are wide.
   430  	//
   431  	// Next should return io.EOF when there are no more rows.
   432  	//
   433  	// The dest should not be written to outside of Next. Care
   434  	// should be taken when closing Rows not to modify
   435  	// a buffer held in dest.
   436  	Next(dest []Value) error
   437  }
   438  
   439  // RowsNextResultSet extends the Rows interface by providing a way to signal
   440  // the driver to advance to the next result set.
   441  type RowsNextResultSet interface {
   442  	Rows
   443  
   444  	// HasNextResultSet is called at the end of the current result set and
   445  	// reports whether there is another result set after the current one.
   446  	HasNextResultSet() bool
   447  
   448  	// NextResultSet advances the driver to the next result set even
   449  	// if there are remaining rows in the current result set.
   450  	//
   451  	// NextResultSet should return io.EOF when there are no more result sets.
   452  	NextResultSet() error
   453  }
   454  
   455  // RowsColumnTypeScanType may be implemented by Rows. It should return
   456  // the value type that can be used to scan types into. For example, the database
   457  // column type "bigint" this should return "reflect.TypeOf(int64(0))".
   458  type RowsColumnTypeScanType interface {
   459  	Rows
   460  	ColumnTypeScanType(index int) reflect.Type
   461  }
   462  
   463  // RowsColumnTypeDatabaseTypeName may be implemented by Rows. It should return the
   464  // database system type name without the length. Type names should be uppercase.
   465  // Examples of returned types: "VARCHAR", "NVARCHAR", "VARCHAR2", "CHAR", "TEXT",
   466  // "DECIMAL", "SMALLINT", "INT", "BIGINT", "BOOL", "[]BIGINT", "JSONB", "XML",
   467  // "TIMESTAMP".
   468  type RowsColumnTypeDatabaseTypeName interface {
   469  	Rows
   470  	ColumnTypeDatabaseTypeName(index int) string
   471  }
   472  
   473  // RowsColumnTypeLength may be implemented by Rows. It should return the length
   474  // of the column type if the column is a variable length type. If the column is
   475  // not a variable length type ok should return false.
   476  // If length is not limited other than system limits, it should return math.MaxInt64.
   477  // The following are examples of returned values for various types:
   478  //   TEXT          (math.MaxInt64, true)
   479  //   varchar(10)   (10, true)
   480  //   nvarchar(10)  (10, true)
   481  //   decimal       (0, false)
   482  //   int           (0, false)
   483  //   bytea(30)     (30, true)
   484  type RowsColumnTypeLength interface {
   485  	Rows
   486  	ColumnTypeLength(index int) (length int64, ok bool)
   487  }
   488  
   489  // RowsColumnTypeNullable may be implemented by Rows. The nullable value should
   490  // be true if it is known the column may be null, or false if the column is known
   491  // to be not nullable.
   492  // If the column nullability is unknown, ok should be false.
   493  type RowsColumnTypeNullable interface {
   494  	Rows
   495  	ColumnTypeNullable(index int) (nullable, ok bool)
   496  }
   497  
   498  // RowsColumnTypePrecisionScale may be implemented by Rows. It should return
   499  // the precision and scale for decimal types. If not applicable, ok should be false.
   500  // The following are examples of returned values for various types:
   501  //   decimal(38, 4)    (38, 4, true)
   502  //   int               (0, 0, false)
   503  //   decimal           (math.MaxInt64, math.MaxInt64, true)
   504  type RowsColumnTypePrecisionScale interface {
   505  	Rows
   506  	ColumnTypePrecisionScale(index int) (precision, scale int64, ok bool)
   507  }
   508  
   509  // Tx is a transaction.
   510  type Tx interface {
   511  	Commit() error
   512  	Rollback() error
   513  }
   514  
   515  // RowsAffected implements Result for an INSERT or UPDATE operation
   516  // which mutates a number of rows.
   517  type RowsAffected int64
   518  
   519  var _ Result = RowsAffected(0)
   520  
   521  func (RowsAffected) LastInsertId() (int64, error) {
   522  	return 0, errors.New("LastInsertId is not supported by this driver")
   523  }
   524  
   525  func (v RowsAffected) RowsAffected() (int64, error) {
   526  	return int64(v), nil
   527  }
   528  
   529  // ResultNoRows is a pre-defined Result for drivers to return when a DDL
   530  // command (such as a CREATE TABLE) succeeds. It returns an error for both
   531  // LastInsertId and RowsAffected.
   532  var ResultNoRows noRows
   533  
   534  type noRows struct{}
   535  
   536  var _ Result = noRows{}
   537  
   538  func (noRows) LastInsertId() (int64, error) {
   539  	return 0, errors.New("no LastInsertId available after DDL statement")
   540  }
   541  
   542  func (noRows) RowsAffected() (int64, error) {
   543  	return 0, errors.New("no RowsAffected available after DDL statement")
   544  }
   545  

View as plain text