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

View as plain text