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