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

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

View as plain text