github.com/goproxy0/go@v0.0.0-20171111080102-49cc0c489d2c/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 // ResetSessioner may be implemented by Conn to allow drivers to reset the 226 // session state associated with the connection and to signal a bad connection. 227 type ResetSessioner interface { 228 // ResetSession is called while a connection is in the connection 229 // pool. No queries will run on this connection until this method returns. 230 // 231 // If the connection is bad this should return driver.ErrBadConn to prevent 232 // the connection from being returned to the connection pool. Any other 233 // error will be discarded. 234 ResetSession(ctx context.Context) error 235 } 236 237 // Result is the result of a query execution. 238 type Result interface { 239 // LastInsertId returns the database's auto-generated ID 240 // after, for example, an INSERT into a table with primary 241 // key. 242 LastInsertId() (int64, error) 243 244 // RowsAffected returns the number of rows affected by the 245 // query. 246 RowsAffected() (int64, error) 247 } 248 249 // Stmt is a prepared statement. It is bound to a Conn and not 250 // used by multiple goroutines concurrently. 251 type Stmt interface { 252 // Close closes the statement. 253 // 254 // As of Go 1.1, a Stmt will not be closed if it's in use 255 // by any queries. 256 Close() error 257 258 // NumInput returns the number of placeholder parameters. 259 // 260 // If NumInput returns >= 0, the sql package will sanity check 261 // argument counts from callers and return errors to the caller 262 // before the statement's Exec or Query methods are called. 263 // 264 // NumInput may also return -1, if the driver doesn't know 265 // its number of placeholders. In that case, the sql package 266 // will not sanity check Exec or Query argument counts. 267 NumInput() int 268 269 // Exec executes a query that doesn't return rows, such 270 // as an INSERT or UPDATE. 271 // 272 // Deprecated: Drivers should implement StmtExecContext instead (or additionally). 273 Exec(args []Value) (Result, error) 274 275 // Query executes a query that may return rows, such as a 276 // SELECT. 277 // 278 // Deprecated: Drivers should implement StmtQueryContext instead (or additionally). 279 Query(args []Value) (Rows, error) 280 } 281 282 // StmtExecContext enhances the Stmt interface by providing Exec with context. 283 type StmtExecContext interface { 284 // ExecContext executes a query that doesn't return rows, such 285 // as an INSERT or UPDATE. 286 // 287 // ExecContext must honor the context timeout and return when it is canceled. 288 ExecContext(ctx context.Context, args []NamedValue) (Result, error) 289 } 290 291 // StmtQueryContext enhances the Stmt interface by providing Query with context. 292 type StmtQueryContext interface { 293 // QueryContext executes a query that may return rows, such as a 294 // SELECT. 295 // 296 // QueryContext must honor the context timeout and return when it is canceled. 297 QueryContext(ctx context.Context, args []NamedValue) (Rows, error) 298 } 299 300 // ErrRemoveArgument may be returned from NamedValueChecker to instruct the 301 // sql package to not pass the argument to the driver query interface. 302 // Return when accepting query specific options or structures that aren't 303 // SQL query arguments. 304 var ErrRemoveArgument = errors.New("driver: remove argument from query") 305 306 // NamedValueChecker may be optionally implemented by Conn or Stmt. It provides 307 // the driver more control to handle Go and database types beyond the default 308 // Values types allowed. 309 // 310 // The sql package checks for value checkers in the following order, 311 // stopping at the first found match: Stmt.NamedValueChecker, Conn.NamedValueChecker, 312 // Stmt.ColumnConverter, DefaultParameterConverter. 313 // 314 // If CheckNamedValue returns ErrRemoveArgument, the NamedValue will not be included in 315 // the final query arguments. This may be used to pass special options to 316 // the query itself. 317 // 318 // If ErrSkip is returned the column converter error checking 319 // path is used for the argument. Drivers may wish to return ErrSkip after 320 // they have exhausted their own special cases. 321 type NamedValueChecker interface { 322 // CheckNamedValue is called before passing arguments to the driver 323 // and is called in place of any ColumnConverter. CheckNamedValue must do type 324 // validation and conversion as appropriate for the driver. 325 CheckNamedValue(*NamedValue) error 326 } 327 328 // ColumnConverter may be optionally implemented by Stmt if the 329 // statement is aware of its own columns' types and can convert from 330 // any type to a driver Value. 331 // 332 // Deprecated: Drivers should implement NamedValueChecker. 333 type ColumnConverter interface { 334 // ColumnConverter returns a ValueConverter for the provided 335 // column index. If the type of a specific column isn't known 336 // or shouldn't be handled specially, DefaultValueConverter 337 // can be returned. 338 ColumnConverter(idx int) ValueConverter 339 } 340 341 // Rows is an iterator over an executed query's results. 342 type Rows interface { 343 // Columns returns the names of the columns. The number of 344 // columns of the result is inferred from the length of the 345 // slice. If a particular column name isn't known, an empty 346 // string should be returned for that entry. 347 Columns() []string 348 349 // Close closes the rows iterator. 350 Close() error 351 352 // Next is called to populate the next row of data into 353 // the provided slice. The provided slice will be the same 354 // size as the Columns() are wide. 355 // 356 // Next should return io.EOF when there are no more rows. 357 Next(dest []Value) error 358 } 359 360 // RowsNextResultSet extends the Rows interface by providing a way to signal 361 // the driver to advance to the next result set. 362 type RowsNextResultSet interface { 363 Rows 364 365 // HasNextResultSet is called at the end of the current result set and 366 // reports whether there is another result set after the current one. 367 HasNextResultSet() bool 368 369 // NextResultSet advances the driver to the next result set even 370 // if there are remaining rows in the current result set. 371 // 372 // NextResultSet should return io.EOF when there are no more result sets. 373 NextResultSet() error 374 } 375 376 // RowsColumnTypeScanType may be implemented by Rows. It should return 377 // the value type that can be used to scan types into. For example, the database 378 // column type "bigint" this should return "reflect.TypeOf(int64(0))". 379 type RowsColumnTypeScanType interface { 380 Rows 381 ColumnTypeScanType(index int) reflect.Type 382 } 383 384 // RowsColumnTypeDatabaseTypeName may be implemented by Rows. It should return the 385 // database system type name without the length. Type names should be uppercase. 386 // Examples of returned types: "VARCHAR", "NVARCHAR", "VARCHAR2", "CHAR", "TEXT", 387 // "DECIMAL", "SMALLINT", "INT", "BIGINT", "BOOL", "[]BIGINT", "JSONB", "XML", 388 // "TIMESTAMP". 389 type RowsColumnTypeDatabaseTypeName interface { 390 Rows 391 ColumnTypeDatabaseTypeName(index int) string 392 } 393 394 // RowsColumnTypeLength may be implemented by Rows. It should return the length 395 // of the column type if the column is a variable length type. If the column is 396 // not a variable length type ok should return false. 397 // If length is not limited other than system limits, it should return math.MaxInt64. 398 // The following are examples of returned values for various types: 399 // TEXT (math.MaxInt64, true) 400 // varchar(10) (10, true) 401 // nvarchar(10) (10, true) 402 // decimal (0, false) 403 // int (0, false) 404 // bytea(30) (30, true) 405 type RowsColumnTypeLength interface { 406 Rows 407 ColumnTypeLength(index int) (length int64, ok bool) 408 } 409 410 // RowsColumnTypeNullable may be implemented by Rows. The nullable value should 411 // be true if it is known the column may be null, or false if the column is known 412 // to be not nullable. 413 // If the column nullability is unknown, ok should be false. 414 type RowsColumnTypeNullable interface { 415 Rows 416 ColumnTypeNullable(index int) (nullable, ok bool) 417 } 418 419 // RowsColumnTypePrecisionScale may be implemented by Rows. It should return 420 // the precision and scale for decimal types. If not applicable, ok should be false. 421 // The following are examples of returned values for various types: 422 // decimal(38, 4) (38, 4, true) 423 // int (0, 0, false) 424 // decimal (math.MaxInt64, math.MaxInt64, true) 425 type RowsColumnTypePrecisionScale interface { 426 Rows 427 ColumnTypePrecisionScale(index int) (precision, scale int64, ok bool) 428 } 429 430 // Tx is a transaction. 431 type Tx interface { 432 Commit() error 433 Rollback() error 434 } 435 436 // RowsAffected implements Result for an INSERT or UPDATE operation 437 // which mutates a number of rows. 438 type RowsAffected int64 439 440 var _ Result = RowsAffected(0) 441 442 func (RowsAffected) LastInsertId() (int64, error) { 443 return 0, errors.New("no LastInsertId available") 444 } 445 446 func (v RowsAffected) RowsAffected() (int64, error) { 447 return int64(v), nil 448 } 449 450 // ResultNoRows is a pre-defined Result for drivers to return when a DDL 451 // command (such as a CREATE TABLE) succeeds. It returns an error for both 452 // LastInsertId and RowsAffected. 453 var ResultNoRows noRows 454 455 type noRows struct{} 456 457 var _ Result = noRows{} 458 459 func (noRows) LastInsertId() (int64, error) { 460 return 0, errors.New("no LastInsertId available after DDL statement") 461 } 462 463 func (noRows) RowsAffected() (int64, error) { 464 return 0, errors.New("no RowsAffected available after DDL statement") 465 }