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.
5 // Package driver defines interfaces to be implemented by database
6 // drivers as used by package sql.
8 // Most code should use package sql.
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:
26 type Value
interface{}
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.
33 // Name will not have a symbol prefix.
36 // Ordinal position of the parameter starting from one and is always set.
39 // Value is the parameter value.
43 // Driver is the interface that must be implemented by a database
45 type Driver
interface {
46 // Open returns a new connection to the database.
47 // The name is a string in a driver-specific format.
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.
53 // The returned connection is only used by one goroutine at a
55 Open(name
string) (Conn
, error
)
58 // ErrSkip may be returned by some optional interfaces' methods to
59 // indicate at runtime that the fast path is unavailable and the sql
60 // package should continue as if the optional interface was not
61 // implemented. ErrSkip is only supported where explicitly
63 var ErrSkip
= errors
.New("driver: skip fast-path; continue as if unimplemented")
65 // ErrBadConn should be returned by a driver to signal to the sql
66 // package that a driver.Conn is in a bad state (such as the server
67 // having earlier closed the connection) and the sql package should
68 // retry on a new connection.
70 // To prevent duplicate operations, ErrBadConn should NOT be returned
71 // if there's a possibility that the database server might have
72 // performed the operation. Even if the server sends back an error,
73 // you shouldn't return ErrBadConn.
74 var ErrBadConn
= errors
.New("driver: bad connection")
76 // Pinger is an optional interface that may be implemented by a Conn.
78 // If a Conn does not implement Pinger, the sql package's DB.Ping and
79 // DB.PingContext will check if there is at least one Conn available.
81 // If Conn.Ping returns ErrBadConn, DB.Ping and DB.PingContext will remove
82 // the Conn from pool.
83 type Pinger
interface {
84 Ping(ctx context
.Context
) error
87 // Execer is an optional interface that may be implemented by a Conn.
89 // If a Conn does not implement Execer, the sql package's DB.Exec will
90 // first prepare a query, execute the statement, and then close the
93 // Exec may return ErrSkip.
95 // Deprecated: Drivers should implement ExecerContext instead (or additionally).
96 type Execer
interface {
97 Exec(query
string, args
[]Value
) (Result
, error
)
100 // ExecerContext is an optional interface that may be implemented by a Conn.
102 // If a Conn does not implement ExecerContext, the sql package's DB.Exec will
103 // first prepare a query, execute the statement, and then close the
106 // ExecerContext may return ErrSkip.
108 // ExecerContext must honor the context timeout and return when the context is canceled.
109 type ExecerContext
interface {
110 ExecContext(ctx context
.Context
, query
string, args
[]NamedValue
) (Result
, error
)
113 // Queryer is an optional interface that may be implemented by a Conn.
115 // If a Conn does not implement Queryer, the sql package's DB.Query will
116 // first prepare a query, execute the statement, and then close the
119 // Query may return ErrSkip.
121 // Deprecated: Drivers should implement QueryerContext instead (or additionally).
122 type Queryer
interface {
123 Query(query
string, args
[]Value
) (Rows
, error
)
126 // QueryerContext is an optional interface that may be implemented by a Conn.
128 // If a Conn does not implement QueryerContext, the sql package's DB.Query will
129 // first prepare a query, execute the statement, and then close the
132 // QueryerContext may return ErrSkip.
134 // QueryerContext must honor the context timeout and return when the context is canceled.
135 type QueryerContext
interface {
136 QueryContext(ctx context
.Context
, query
string, args
[]NamedValue
) (Rows
, error
)
139 // Conn is a connection to a database. It is not used concurrently
140 // by multiple goroutines.
142 // Conn is assumed to be stateful.
143 type Conn
interface {
144 // Prepare returns a prepared statement, bound to this connection.
145 Prepare(query
string) (Stmt
, error
)
147 // Close invalidates and potentially stops any current
148 // prepared statements and transactions, marking this
149 // connection as no longer in use.
151 // Because the sql package maintains a free pool of
152 // connections and only calls Close when there's a surplus of
153 // idle connections, it shouldn't be necessary for drivers to
154 // do their own connection caching.
157 // Begin starts and returns a new transaction.
159 // Deprecated: Drivers should implement ConnBeginTx instead (or additionally).
163 // ConnPrepareContext enhances the Conn interface with context.
164 type ConnPrepareContext
interface {
165 // PrepareContext returns a prepared statement, bound to this connection.
166 // context is for the preparation of the statement,
167 // it must not store the context within the statement itself.
168 PrepareContext(ctx context
.Context
, query
string) (Stmt
, error
)
171 // IsolationLevel is the transaction isolation level stored in TxOptions.
173 // This type should be considered identical to sql.IsolationLevel along
174 // with any values defined on it.
175 type IsolationLevel
int
177 // TxOptions holds the transaction options.
179 // This type should be considered identical to sql.TxOptions.
180 type TxOptions
struct {
181 Isolation IsolationLevel
185 // ConnBeginTx enhances the Conn interface with context and TxOptions.
186 type ConnBeginTx
interface {
187 // BeginTx starts and returns a new transaction.
188 // If the context is canceled by the user the sql package will
189 // call Tx.Rollback before discarding and closing the connection.
191 // This must check opts.Isolation to determine if there is a set
192 // isolation level. If the driver does not support a non-default
193 // level and one is set or if there is a non-default isolation level
194 // that is not supported, an error must be returned.
196 // This must also check opts.ReadOnly to determine if the read-only
197 // value is true to either set the read-only transaction property if supported
198 // or return an error if it is not supported.
199 BeginTx(ctx context
.Context
, opts TxOptions
) (Tx
, error
)
202 // Result is the result of a query execution.
203 type Result
interface {
204 // LastInsertId returns the database's auto-generated ID
205 // after, for example, an INSERT into a table with primary
207 LastInsertId() (int64, error
)
209 // RowsAffected returns the number of rows affected by the
211 RowsAffected() (int64, error
)
214 // Stmt is a prepared statement. It is bound to a Conn and not
215 // used by multiple goroutines concurrently.
216 type Stmt
interface {
217 // Close closes the statement.
219 // As of Go 1.1, a Stmt will not be closed if it's in use
223 // NumInput returns the number of placeholder parameters.
225 // If NumInput returns >= 0, the sql package will sanity check
226 // argument counts from callers and return errors to the caller
227 // before the statement's Exec or Query methods are called.
229 // NumInput may also return -1, if the driver doesn't know
230 // its number of placeholders. In that case, the sql package
231 // will not sanity check Exec or Query argument counts.
234 // Exec executes a query that doesn't return rows, such
235 // as an INSERT or UPDATE.
237 // Deprecated: Drivers should implement StmtExecContext instead (or additionally).
238 Exec(args
[]Value
) (Result
, error
)
240 // Query executes a query that may return rows, such as a
243 // Deprecated: Drivers should implement StmtQueryContext instead (or additionally).
244 Query(args
[]Value
) (Rows
, error
)
247 // StmtExecContext enhances the Stmt interface by providing Exec with context.
248 type StmtExecContext
interface {
249 // ExecContext executes a query that doesn't return rows, such
250 // as an INSERT or UPDATE.
252 // ExecContext must honor the context timeout and return when it is canceled.
253 ExecContext(ctx context
.Context
, args
[]NamedValue
) (Result
, error
)
256 // StmtQueryContext enhances the Stmt interface by providing Query with context.
257 type StmtQueryContext
interface {
258 // QueryContext executes a query that may return rows, such as a
261 // QueryContext must honor the context timeout and return when it is canceled.
262 QueryContext(ctx context
.Context
, args
[]NamedValue
) (Rows
, error
)
265 // ErrRemoveArgument may be returned from NamedValueChecker to instruct the
266 // sql package to not pass the argument to the driver query interface.
267 // Return when accepting query specific options or structures that aren't
268 // SQL query arguments.
269 var ErrRemoveArgument
= errors
.New("driver: remove argument from query")
271 // NamedValueChecker may be optionally implemented by Conn or Stmt. It provides
272 // the driver more control to handle Go and database types beyond the default
273 // Values types allowed.
275 // The sql package checks for value checkers in the following order,
276 // stopping at the first found match: Stmt.NamedValueChecker, Conn.NamedValueChecker,
277 // Stmt.ColumnConverter, DefaultParameterConverter.
279 // If CheckNamedValue returns ErrRemoveArgument, the NamedValue will not be included in
280 // the final query arguments. This may be used to pass special options to
283 // If ErrSkip is returned the column converter error checking
284 // path is used for the argument. Drivers may wish to return ErrSkip after
285 // they have exhausted their own special cases.
286 type NamedValueChecker
interface {
287 // CheckNamedValue is called before passing arguments to the driver
288 // and is called in place of any ColumnConverter. CheckNamedValue must do type
289 // validation and conversion as appropriate for the driver.
290 CheckNamedValue(*NamedValue
) error
293 // ColumnConverter may be optionally implemented by Stmt if the
294 // statement is aware of its own columns' types and can convert from
295 // any type to a driver Value.
297 // Deprecated: Drivers should implement NamedValueChecker.
298 type ColumnConverter
interface {
299 // ColumnConverter returns a ValueConverter for the provided
300 // column index. If the type of a specific column isn't known
301 // or shouldn't be handled specially, DefaultValueConverter
303 ColumnConverter(idx
int) ValueConverter
306 // Rows is an iterator over an executed query's results.
307 type Rows
interface {
308 // Columns returns the names of the columns. The number of
309 // columns of the result is inferred from the length of the
310 // slice. If a particular column name isn't known, an empty
311 // string should be returned for that entry.
314 // Close closes the rows iterator.
317 // Next is called to populate the next row of data into
318 // the provided slice. The provided slice will be the same
319 // size as the Columns() are wide.
321 // Next should return io.EOF when there are no more rows.
322 Next(dest
[]Value
) error
325 // RowsNextResultSet extends the Rows interface by providing a way to signal
326 // the driver to advance to the next result set.
327 type RowsNextResultSet
interface {
330 // HasNextResultSet is called at the end of the current result set and
331 // reports whether there is another result set after the current one.
332 HasNextResultSet() bool
334 // NextResultSet advances the driver to the next result set even
335 // if there are remaining rows in the current result set.
337 // NextResultSet should return io.EOF when there are no more result sets.
338 NextResultSet() error
341 // RowsColumnTypeScanType may be implemented by Rows. It should return
342 // the value type that can be used to scan types into. For example, the database
343 // column type "bigint" this should return "reflect.TypeOf(int64(0))".
344 type RowsColumnTypeScanType
interface {
346 ColumnTypeScanType(index
int) reflect
.Type
349 // RowsColumnTypeDatabaseTypeName may be implemented by Rows. It should return the
350 // database system type name without the length. Type names should be uppercase.
351 // Examples of returned types: "VARCHAR", "NVARCHAR", "VARCHAR2", "CHAR", "TEXT",
352 // "DECIMAL", "SMALLINT", "INT", "BIGINT", "BOOL", "[]BIGINT", "JSONB", "XML",
354 type RowsColumnTypeDatabaseTypeName
interface {
356 ColumnTypeDatabaseTypeName(index
int) string
359 // RowsColumnTypeLength may be implemented by Rows. It should return the length
360 // of the column type if the column is a variable length type. If the column is
361 // not a variable length type ok should return false.
362 // If length is not limited other than system limits, it should return math.MaxInt64.
363 // The following are examples of returned values for various types:
364 // TEXT (math.MaxInt64, true)
365 // varchar(10) (10, true)
366 // nvarchar(10) (10, true)
367 // decimal (0, false)
369 // bytea(30) (30, true)
370 type RowsColumnTypeLength
interface {
372 ColumnTypeLength(index
int) (length
int64, ok
bool)
375 // RowsColumnTypeNullable may be implemented by Rows. The nullable value should
376 // be true if it is known the column may be null, or false if the column is known
377 // to be not nullable.
378 // If the column nullability is unknown, ok should be false.
379 type RowsColumnTypeNullable
interface {
381 ColumnTypeNullable(index
int) (nullable
, ok
bool)
384 // RowsColumnTypePrecisionScale may be implemented by Rows. It should return
385 // the precision and scale for decimal types. If not applicable, ok should be false.
386 // The following are examples of returned values for various types:
387 // decimal(38, 4) (38, 4, true)
389 // decimal (math.MaxInt64, math.MaxInt64, true)
390 type RowsColumnTypePrecisionScale
interface {
392 ColumnTypePrecisionScale(index
int) (precision
, scale
int64, ok
bool)
395 // Tx is a transaction.
401 // RowsAffected implements Result for an INSERT or UPDATE operation
402 // which mutates a number of rows.
403 type RowsAffected
int64
405 var _ Result
= RowsAffected(0)
407 func (RowsAffected
) LastInsertId() (int64, error
) {
408 return 0, errors
.New("no LastInsertId available")
411 func (v RowsAffected
) RowsAffected() (int64, error
) {
415 // ResultNoRows is a pre-defined Result for drivers to return when a DDL
416 // command (such as a CREATE TABLE) succeeds. It returns an error for both
417 // LastInsertId and RowsAffected.
418 var ResultNoRows noRows
422 var _ Result
= noRows
{}
424 func (noRows
) LastInsertId() (int64, error
) {
425 return 0, errors
.New("no LastInsertId available after DDL statement")
428 func (noRows
) RowsAffected() (int64, error
) {
429 return 0, errors
.New("no RowsAffected available after DDL statement")