github.com/mattn/go@v0.0.0-20171011075504-07f7db3ea99f/src/database/sql/driver/driver.go (about)

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