driver.go 20 KB

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