OpenCores
URL https://opencores.org/ocsvn/openrisc/openrisc/trunk

Subversion Repositories openrisc

[/] [openrisc/] [trunk/] [gnu-dev/] [or1k-gcc/] [libgo/] [go/] [database/] [sql/] [sql.go] - Blame information for rev 774

Go to most recent revision | Details | Compare with Previous | View Log

Line No. Rev Author Line
1 747 jeremybenn
// 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 sql provides a generic interface around SQL (or SQL-like)
6
// databases.
7
package sql
8
 
9
import (
10
        "database/sql/driver"
11
        "errors"
12
        "fmt"
13
        "io"
14
        "sync"
15
)
16
 
17
var drivers = make(map[string]driver.Driver)
18
 
19
// Register makes a database driver available by the provided name.
20
// If Register is called twice with the same name or if driver is nil,
21
// it panics.
22
func Register(name string, driver driver.Driver) {
23
        if driver == nil {
24
                panic("sql: Register driver is nil")
25
        }
26
        if _, dup := drivers[name]; dup {
27
                panic("sql: Register called twice for driver " + name)
28
        }
29
        drivers[name] = driver
30
}
31
 
32
// RawBytes is a byte slice that holds a reference to memory owned by
33
// the database itself. After a Scan into a RawBytes, the slice is only
34
// valid until the next call to Next, Scan, or Close.
35
type RawBytes []byte
36
 
37
// NullString represents a string that may be null.
38
// NullString implements the ScannerInto interface so
39
// it can be used as a scan destination:
40
//
41
//  var s NullString
42
//  err := db.QueryRow("SELECT name FROM foo WHERE id=?", id).Scan(&s)
43
//  ...
44
//  if s.Valid {
45
//     // use s.String
46
//  } else {
47
//     // NULL value
48
//  }
49
//
50
type NullString struct {
51
        String string
52
        Valid  bool // Valid is true if String is not NULL
53
}
54
 
55
// ScanInto implements the ScannerInto interface.
56
func (ns *NullString) ScanInto(value interface{}) error {
57
        if value == nil {
58
                ns.String, ns.Valid = "", false
59
                return nil
60
        }
61
        ns.Valid = true
62
        return convertAssign(&ns.String, value)
63
}
64
 
65
// SubsetValue implements the driver SubsetValuer interface.
66
func (ns NullString) SubsetValue() (interface{}, error) {
67
        if !ns.Valid {
68
                return nil, nil
69
        }
70
        return ns.String, nil
71
}
72
 
73
// NullInt64 represents an int64 that may be null.
74
// NullInt64 implements the ScannerInto interface so
75
// it can be used as a scan destination, similar to NullString.
76
type NullInt64 struct {
77
        Int64 int64
78
        Valid bool // Valid is true if Int64 is not NULL
79
}
80
 
81
// ScanInto implements the ScannerInto interface.
82
func (n *NullInt64) ScanInto(value interface{}) error {
83
        if value == nil {
84
                n.Int64, n.Valid = 0, false
85
                return nil
86
        }
87
        n.Valid = true
88
        return convertAssign(&n.Int64, value)
89
}
90
 
91
// SubsetValue implements the driver SubsetValuer interface.
92
func (n NullInt64) SubsetValue() (interface{}, error) {
93
        if !n.Valid {
94
                return nil, nil
95
        }
96
        return n.Int64, nil
97
}
98
 
99
// NullFloat64 represents a float64 that may be null.
100
// NullFloat64 implements the ScannerInto interface so
101
// it can be used as a scan destination, similar to NullString.
102
type NullFloat64 struct {
103
        Float64 float64
104
        Valid   bool // Valid is true if Float64 is not NULL
105
}
106
 
107
// ScanInto implements the ScannerInto interface.
108
func (n *NullFloat64) ScanInto(value interface{}) error {
109
        if value == nil {
110
                n.Float64, n.Valid = 0, false
111
                return nil
112
        }
113
        n.Valid = true
114
        return convertAssign(&n.Float64, value)
115
}
116
 
117
// SubsetValue implements the driver SubsetValuer interface.
118
func (n NullFloat64) SubsetValue() (interface{}, error) {
119
        if !n.Valid {
120
                return nil, nil
121
        }
122
        return n.Float64, nil
123
}
124
 
125
// NullBool represents a bool that may be null.
126
// NullBool implements the ScannerInto interface so
127
// it can be used as a scan destination, similar to NullString.
128
type NullBool struct {
129
        Bool  bool
130
        Valid bool // Valid is true if Bool is not NULL
131
}
132
 
133
// ScanInto implements the ScannerInto interface.
134
func (n *NullBool) ScanInto(value interface{}) error {
135
        if value == nil {
136
                n.Bool, n.Valid = false, false
137
                return nil
138
        }
139
        n.Valid = true
140
        return convertAssign(&n.Bool, value)
141
}
142
 
143
// SubsetValue implements the driver SubsetValuer interface.
144
func (n NullBool) SubsetValue() (interface{}, error) {
145
        if !n.Valid {
146
                return nil, nil
147
        }
148
        return n.Bool, nil
149
}
150
 
151
// ScannerInto is an interface used by Scan.
152
type ScannerInto interface {
153
        // ScanInto assigns a value from a database driver.
154
        //
155
        // The value will be of one of the following restricted
156
        // set of types:
157
        //
158
        //    int64
159
        //    float64
160
        //    bool
161
        //    []byte
162
        //    nil - for NULL values
163
        //
164
        // An error should be returned if the value can not be stored
165
        // without loss of information.
166
        ScanInto(value interface{}) error
167
}
168
 
169
// ErrNoRows is returned by Scan when QueryRow doesn't return a
170
// row. In such a case, QueryRow returns a placeholder *Row value that
171
// defers this error until a Scan.
172
var ErrNoRows = errors.New("sql: no rows in result set")
173
 
174
// DB is a database handle. It's safe for concurrent use by multiple
175
// goroutines.
176
type DB struct {
177
        driver driver.Driver
178
        dsn    string
179
 
180
        mu       sync.Mutex // protects freeConn and closed
181
        freeConn []driver.Conn
182
        closed   bool
183
}
184
 
185
// Open opens a database specified by its database driver name and a
186
// driver-specific data source name, usually consisting of at least a
187
// database name and connection information.
188
//
189
// Most users will open a database via a driver-specific connection
190
// helper function that returns a *DB.
191
func Open(driverName, dataSourceName string) (*DB, error) {
192
        driver, ok := drivers[driverName]
193
        if !ok {
194
                return nil, fmt.Errorf("sql: unknown driver %q (forgotten import?)", driverName)
195
        }
196
        return &DB{driver: driver, dsn: dataSourceName}, nil
197
}
198
 
199
// Close closes the database, releasing any open resources.
200
func (db *DB) Close() error {
201
        db.mu.Lock()
202
        defer db.mu.Unlock()
203
        var err error
204
        for _, c := range db.freeConn {
205
                err1 := c.Close()
206
                if err1 != nil {
207
                        err = err1
208
                }
209
        }
210
        db.freeConn = nil
211
        db.closed = true
212
        return err
213
}
214
 
215
func (db *DB) maxIdleConns() int {
216
        const defaultMaxIdleConns = 2
217
        // TODO(bradfitz): ask driver, if supported, for its default preference
218
        // TODO(bradfitz): let users override?
219
        return defaultMaxIdleConns
220
}
221
 
222
// conn returns a newly-opened or cached driver.Conn
223
func (db *DB) conn() (driver.Conn, error) {
224
        db.mu.Lock()
225
        if db.closed {
226
                db.mu.Unlock()
227
                return nil, errors.New("sql: database is closed")
228
        }
229
        if n := len(db.freeConn); n > 0 {
230
                conn := db.freeConn[n-1]
231
                db.freeConn = db.freeConn[:n-1]
232
                db.mu.Unlock()
233
                return conn, nil
234
        }
235
        db.mu.Unlock()
236
        return db.driver.Open(db.dsn)
237
}
238
 
239
func (db *DB) connIfFree(wanted driver.Conn) (conn driver.Conn, ok bool) {
240
        db.mu.Lock()
241
        defer db.mu.Unlock()
242
        for n, conn := range db.freeConn {
243
                if conn == wanted {
244
                        db.freeConn[n] = db.freeConn[len(db.freeConn)-1]
245
                        db.freeConn = db.freeConn[:len(db.freeConn)-1]
246
                        return wanted, true
247
                }
248
        }
249
        return nil, false
250
}
251
 
252
func (db *DB) putConn(c driver.Conn) {
253
        db.mu.Lock()
254
        defer db.mu.Unlock()
255
        if n := len(db.freeConn); !db.closed && n < db.maxIdleConns() {
256
                db.freeConn = append(db.freeConn, c)
257
                return
258
        }
259
        db.closeConn(c) // TODO(bradfitz): release lock before calling this?
260
}
261
 
262
func (db *DB) closeConn(c driver.Conn) {
263
        // TODO: check to see if we need this Conn for any prepared statements
264
        // that are active.
265
        c.Close()
266
}
267
 
268
// Prepare creates a prepared statement for later execution.
269
func (db *DB) Prepare(query string) (*Stmt, error) {
270
        // TODO: check if db.driver supports an optional
271
        // driver.Preparer interface and call that instead, if so,
272
        // otherwise we make a prepared statement that's bound
273
        // to a connection, and to execute this prepared statement
274
        // we either need to use this connection (if it's free), else
275
        // get a new connection + re-prepare + execute on that one.
276
        ci, err := db.conn()
277
        if err != nil {
278
                return nil, err
279
        }
280
        defer db.putConn(ci)
281
        si, err := ci.Prepare(query)
282
        if err != nil {
283
                return nil, err
284
        }
285
        stmt := &Stmt{
286
                db:    db,
287
                query: query,
288
                css:   []connStmt{{ci, si}},
289
        }
290
        return stmt, nil
291
}
292
 
293
// Exec executes a query without returning any rows.
294
func (db *DB) Exec(query string, args ...interface{}) (Result, error) {
295
        sargs, err := subsetTypeArgs(args)
296
        if err != nil {
297
                return nil, err
298
        }
299
 
300
        ci, err := db.conn()
301
        if err != nil {
302
                return nil, err
303
        }
304
        defer db.putConn(ci)
305
 
306
        if execer, ok := ci.(driver.Execer); ok {
307
                resi, err := execer.Exec(query, sargs)
308
                if err != driver.ErrSkip {
309
                        if err != nil {
310
                                return nil, err
311
                        }
312
                        return result{resi}, nil
313
                }
314
        }
315
 
316
        sti, err := ci.Prepare(query)
317
        if err != nil {
318
                return nil, err
319
        }
320
        defer sti.Close()
321
 
322
        resi, err := sti.Exec(sargs)
323
        if err != nil {
324
                return nil, err
325
        }
326
        return result{resi}, nil
327
}
328
 
329
// Query executes a query that returns rows, typically a SELECT.
330
func (db *DB) Query(query string, args ...interface{}) (*Rows, error) {
331
        stmt, err := db.Prepare(query)
332
        if err != nil {
333
                return nil, err
334
        }
335
        rows, err := stmt.Query(args...)
336
        if err != nil {
337
                stmt.Close()
338
                return nil, err
339
        }
340
        rows.closeStmt = stmt
341
        return rows, nil
342
}
343
 
344
// QueryRow executes a query that is expected to return at most one row.
345
// QueryRow always return a non-nil value. Errors are deferred until
346
// Row's Scan method is called.
347
func (db *DB) QueryRow(query string, args ...interface{}) *Row {
348
        rows, err := db.Query(query, args...)
349
        return &Row{rows: rows, err: err}
350
}
351
 
352
// Begin starts a transaction. The isolation level is dependent on
353
// the driver.
354
func (db *DB) Begin() (*Tx, error) {
355
        ci, err := db.conn()
356
        if err != nil {
357
                return nil, err
358
        }
359
        txi, err := ci.Begin()
360
        if err != nil {
361
                db.putConn(ci)
362
                return nil, fmt.Errorf("sql: failed to Begin transaction: %v", err)
363
        }
364
        return &Tx{
365
                db:  db,
366
                ci:  ci,
367
                txi: txi,
368
        }, nil
369
}
370
 
371
// DriverDatabase returns the database's underlying driver.
372
func (db *DB) Driver() driver.Driver {
373
        return db.driver
374
}
375
 
376
// Tx is an in-progress database transaction.
377
//
378
// A transaction must end with a call to Commit or Rollback.
379
//
380
// After a call to Commit or Rollback, all operations on the
381
// transaction fail with ErrTransactionFinished.
382
type Tx struct {
383
        db *DB
384
 
385
        // ci is owned exclusively until Commit or Rollback, at which point
386
        // it's returned with putConn.
387
        ci  driver.Conn
388
        txi driver.Tx
389
 
390
        // cimu is held while somebody is using ci (between grabConn
391
        // and releaseConn)
392
        cimu sync.Mutex
393
 
394
        // done transitions from false to true exactly once, on Commit
395
        // or Rollback. once done, all operations fail with
396
        // ErrTransactionFinished.
397
        done bool
398
}
399
 
400
var ErrTransactionFinished = errors.New("sql: Transaction has already been committed or rolled back")
401
 
402
func (tx *Tx) close() {
403
        if tx.done {
404
                panic("double close") // internal error
405
        }
406
        tx.done = true
407
        tx.db.putConn(tx.ci)
408
        tx.ci = nil
409
        tx.txi = nil
410
}
411
 
412
func (tx *Tx) grabConn() (driver.Conn, error) {
413
        if tx.done {
414
                return nil, ErrTransactionFinished
415
        }
416
        tx.cimu.Lock()
417
        return tx.ci, nil
418
}
419
 
420
func (tx *Tx) releaseConn() {
421
        tx.cimu.Unlock()
422
}
423
 
424
// Commit commits the transaction.
425
func (tx *Tx) Commit() error {
426
        if tx.done {
427
                return ErrTransactionFinished
428
        }
429
        defer tx.close()
430
        return tx.txi.Commit()
431
}
432
 
433
// Rollback aborts the transaction.
434
func (tx *Tx) Rollback() error {
435
        if tx.done {
436
                return ErrTransactionFinished
437
        }
438
        defer tx.close()
439
        return tx.txi.Rollback()
440
}
441
 
442
// Prepare creates a prepared statement for use within a transaction.
443
//
444
// The returned statement operates within the transaction and can no longer
445
// be used once the transaction has been committed or rolled back.
446
//
447
// To use an existing prepared statement on this transaction, see Tx.Stmt.
448
func (tx *Tx) Prepare(query string) (*Stmt, error) {
449
        // TODO(bradfitz): We could be more efficient here and either
450
        // provide a method to take an existing Stmt (created on
451
        // perhaps a different Conn), and re-create it on this Conn if
452
        // necessary. Or, better: keep a map in DB of query string to
453
        // Stmts, and have Stmt.Execute do the right thing and
454
        // re-prepare if the Conn in use doesn't have that prepared
455
        // statement.  But we'll want to avoid caching the statement
456
        // in the case where we only call conn.Prepare implicitly
457
        // (such as in db.Exec or tx.Exec), but the caller package
458
        // can't be holding a reference to the returned statement.
459
        // Perhaps just looking at the reference count (by noting
460
        // Stmt.Close) would be enough. We might also want a finalizer
461
        // on Stmt to drop the reference count.
462
        ci, err := tx.grabConn()
463
        if err != nil {
464
                return nil, err
465
        }
466
        defer tx.releaseConn()
467
 
468
        si, err := ci.Prepare(query)
469
        if err != nil {
470
                return nil, err
471
        }
472
 
473
        stmt := &Stmt{
474
                db:    tx.db,
475
                tx:    tx,
476
                txsi:  si,
477
                query: query,
478
        }
479
        return stmt, nil
480
}
481
 
482
// Stmt returns a transaction-specific prepared statement from
483
// an existing statement.
484
//
485
// Example:
486
//  updateMoney, err := db.Prepare("UPDATE balance SET money=money+? WHERE id=?")
487
//  ...
488
//  tx, err := db.Begin()
489
//  ...
490
//  res, err := tx.Stmt(updateMoney).Exec(123.45, 98293203)
491
func (tx *Tx) Stmt(stmt *Stmt) *Stmt {
492
        // TODO(bradfitz): optimize this. Currently this re-prepares
493
        // each time.  This is fine for now to illustrate the API but
494
        // we should really cache already-prepared statements
495
        // per-Conn. See also the big comment in Tx.Prepare.
496
 
497
        if tx.db != stmt.db {
498
                return &Stmt{stickyErr: errors.New("sql: Tx.Stmt: statement from different database used")}
499
        }
500
        ci, err := tx.grabConn()
501
        if err != nil {
502
                return &Stmt{stickyErr: err}
503
        }
504
        defer tx.releaseConn()
505
        si, err := ci.Prepare(stmt.query)
506
        return &Stmt{
507
                db:        tx.db,
508
                tx:        tx,
509
                txsi:      si,
510
                query:     stmt.query,
511
                stickyErr: err,
512
        }
513
}
514
 
515
// Exec executes a query that doesn't return rows.
516
// For example: an INSERT and UPDATE.
517
func (tx *Tx) Exec(query string, args ...interface{}) (Result, error) {
518
        ci, err := tx.grabConn()
519
        if err != nil {
520
                return nil, err
521
        }
522
        defer tx.releaseConn()
523
 
524
        if execer, ok := ci.(driver.Execer); ok {
525
                resi, err := execer.Exec(query, args)
526
                if err != nil {
527
                        return nil, err
528
                }
529
                return result{resi}, nil
530
        }
531
 
532
        sti, err := ci.Prepare(query)
533
        if err != nil {
534
                return nil, err
535
        }
536
        defer sti.Close()
537
 
538
        sargs, err := subsetTypeArgs(args)
539
        if err != nil {
540
                return nil, err
541
        }
542
 
543
        resi, err := sti.Exec(sargs)
544
        if err != nil {
545
                return nil, err
546
        }
547
        return result{resi}, nil
548
}
549
 
550
// Query executes a query that returns rows, typically a SELECT.
551
func (tx *Tx) Query(query string, args ...interface{}) (*Rows, error) {
552
        if tx.done {
553
                return nil, ErrTransactionFinished
554
        }
555
        stmt, err := tx.Prepare(query)
556
        if err != nil {
557
                return nil, err
558
        }
559
        rows, err := stmt.Query(args...)
560
        if err == nil {
561
                rows.closeStmt = stmt
562
        }
563
        return rows, err
564
}
565
 
566
// QueryRow executes a query that is expected to return at most one row.
567
// QueryRow always return a non-nil value. Errors are deferred until
568
// Row's Scan method is called.
569
func (tx *Tx) QueryRow(query string, args ...interface{}) *Row {
570
        rows, err := tx.Query(query, args...)
571
        return &Row{rows: rows, err: err}
572
}
573
 
574
// connStmt is a prepared statement on a particular connection.
575
type connStmt struct {
576
        ci driver.Conn
577
        si driver.Stmt
578
}
579
 
580
// Stmt is a prepared statement. Stmt is safe for concurrent use by multiple goroutines.
581
type Stmt struct {
582
        // Immutable:
583
        db        *DB    // where we came from
584
        query     string // that created the Stmt
585
        stickyErr error  // if non-nil, this error is returned for all operations
586
 
587
        // If in a transaction, else both nil:
588
        tx   *Tx
589
        txsi driver.Stmt
590
 
591
        mu     sync.Mutex // protects the rest of the fields
592
        closed bool
593
 
594
        // css is a list of underlying driver statement interfaces
595
        // that are valid on particular connections.  This is only
596
        // used if tx == nil and one is found that has idle
597
        // connections.  If tx != nil, txsi is always used.
598
        css []connStmt
599
}
600
 
601
// Exec executes a prepared statement with the given arguments and
602
// returns a Result summarizing the effect of the statement.
603
func (s *Stmt) Exec(args ...interface{}) (Result, error) {
604
        _, releaseConn, si, err := s.connStmt()
605
        if err != nil {
606
                return nil, err
607
        }
608
        defer releaseConn()
609
 
610
        // -1 means the driver doesn't know how to count the number of
611
        // placeholders, so we won't sanity check input here and instead let the
612
        // driver deal with errors.
613
        if want := si.NumInput(); want != -1 && len(args) != want {
614
                return nil, fmt.Errorf("sql: expected %d arguments, got %d", want, len(args))
615
        }
616
 
617
        // Convert args to subset types.
618
        if cc, ok := si.(driver.ColumnConverter); ok {
619
                for n, arg := range args {
620
                        // First, see if the value itself knows how to convert
621
                        // itself to a driver type.  For example, a NullString
622
                        // struct changing into a string or nil.
623
                        if svi, ok := arg.(driver.SubsetValuer); ok {
624
                                sv, err := svi.SubsetValue()
625
                                if err != nil {
626
                                        return nil, fmt.Errorf("sql: argument index %d from SubsetValue: %v", n, err)
627
                                }
628
                                if !driver.IsParameterSubsetType(sv) {
629
                                        return nil, fmt.Errorf("sql: argument index %d: non-subset type %T returned from SubsetValue", n, sv)
630
                                }
631
                                arg = sv
632
                        }
633
 
634
                        // Second, ask the column to sanity check itself. For
635
                        // example, drivers might use this to make sure that
636
                        // an int64 values being inserted into a 16-bit
637
                        // integer field is in range (before getting
638
                        // truncated), or that a nil can't go into a NOT NULL
639
                        // column before going across the network to get the
640
                        // same error.
641
                        args[n], err = cc.ColumnConverter(n).ConvertValue(arg)
642
                        if err != nil {
643
                                return nil, fmt.Errorf("sql: converting Exec argument #%d's type: %v", n, err)
644
                        }
645
                        if !driver.IsParameterSubsetType(args[n]) {
646
                                return nil, fmt.Errorf("sql: driver ColumnConverter error converted %T to unsupported type %T",
647
                                        arg, args[n])
648
                        }
649
                }
650
        } else {
651
                for n, arg := range args {
652
                        args[n], err = driver.DefaultParameterConverter.ConvertValue(arg)
653
                        if err != nil {
654
                                return nil, fmt.Errorf("sql: converting Exec argument #%d's type: %v", n, err)
655
                        }
656
                }
657
        }
658
 
659
        resi, err := si.Exec(args)
660
        if err != nil {
661
                return nil, err
662
        }
663
        return result{resi}, nil
664
}
665
 
666
// connStmt returns a free driver connection on which to execute the
667
// statement, a function to call to release the connection, and a
668
// statement bound to that connection.
669
func (s *Stmt) connStmt() (ci driver.Conn, releaseConn func(), si driver.Stmt, err error) {
670
        if err = s.stickyErr; err != nil {
671
                return
672
        }
673
        s.mu.Lock()
674
        if s.closed {
675
                s.mu.Unlock()
676
                err = errors.New("sql: statement is closed")
677
                return
678
        }
679
 
680
        // In a transaction, we always use the connection that the
681
        // transaction was created on.
682
        if s.tx != nil {
683
                s.mu.Unlock()
684
                ci, err = s.tx.grabConn() // blocks, waiting for the connection.
685
                if err != nil {
686
                        return
687
                }
688
                releaseConn = func() { s.tx.releaseConn() }
689
                return ci, releaseConn, s.txsi, nil
690
        }
691
 
692
        var cs connStmt
693
        match := false
694
        for _, v := range s.css {
695
                // TODO(bradfitz): lazily clean up entries in this
696
                // list with dead conns while enumerating
697
                if _, match = s.db.connIfFree(cs.ci); match {
698
                        cs = v
699
                        break
700
                }
701
        }
702
        s.mu.Unlock()
703
 
704
        // Make a new conn if all are busy.
705
        // TODO(bradfitz): or wait for one? make configurable later?
706
        if !match {
707
                ci, err := s.db.conn()
708
                if err != nil {
709
                        return nil, nil, nil, err
710
                }
711
                si, err := ci.Prepare(s.query)
712
                if err != nil {
713
                        return nil, nil, nil, err
714
                }
715
                s.mu.Lock()
716
                cs = connStmt{ci, si}
717
                s.css = append(s.css, cs)
718
                s.mu.Unlock()
719
        }
720
 
721
        conn := cs.ci
722
        releaseConn = func() { s.db.putConn(conn) }
723
        return conn, releaseConn, cs.si, nil
724
}
725
 
726
// Query executes a prepared query statement with the given arguments
727
// and returns the query results as a *Rows.
728
func (s *Stmt) Query(args ...interface{}) (*Rows, error) {
729
        ci, releaseConn, si, err := s.connStmt()
730
        if err != nil {
731
                return nil, err
732
        }
733
 
734
        // -1 means the driver doesn't know how to count the number of
735
        // placeholders, so we won't sanity check input here and instead let the
736
        // driver deal with errors.
737
        if want := si.NumInput(); want != -1 && len(args) != want {
738
                return nil, fmt.Errorf("sql: statement expects %d inputs; got %d", si.NumInput(), len(args))
739
        }
740
        sargs, err := subsetTypeArgs(args)
741
        if err != nil {
742
                return nil, err
743
        }
744
        rowsi, err := si.Query(sargs)
745
        if err != nil {
746
                s.db.putConn(ci)
747
                return nil, err
748
        }
749
        // Note: ownership of ci passes to the *Rows, to be freed
750
        // with releaseConn.
751
        rows := &Rows{
752
                db:          s.db,
753
                ci:          ci,
754
                releaseConn: releaseConn,
755
                rowsi:       rowsi,
756
        }
757
        return rows, nil
758
}
759
 
760
// QueryRow executes a prepared query statement with the given arguments.
761
// If an error occurs during the execution of the statement, that error will
762
// be returned by a call to Scan on the returned *Row, which is always non-nil.
763
// If the query selects no rows, the *Row's Scan will return ErrNoRows.
764
// Otherwise, the *Row's Scan scans the first selected row and discards
765
// the rest.
766
//
767
// Example usage:
768
//
769
//  var name string
770
//  err := nameByUseridStmt.QueryRow(id).Scan(&s)
771
func (s *Stmt) QueryRow(args ...interface{}) *Row {
772
        rows, err := s.Query(args...)
773
        if err != nil {
774
                return &Row{err: err}
775
        }
776
        return &Row{rows: rows}
777
}
778
 
779
// Close closes the statement.
780
func (s *Stmt) Close() error {
781
        if s.stickyErr != nil {
782
                return s.stickyErr
783
        }
784
        s.mu.Lock()
785
        defer s.mu.Unlock()
786
        if s.closed {
787
                return nil
788
        }
789
        s.closed = true
790
 
791
        if s.tx != nil {
792
                s.txsi.Close()
793
        } else {
794
                for _, v := range s.css {
795
                        if ci, match := s.db.connIfFree(v.ci); match {
796
                                v.si.Close()
797
                                s.db.putConn(ci)
798
                        } else {
799
                                // TODO(bradfitz): care that we can't close
800
                                // this statement because the statement's
801
                                // connection is in use?
802
                        }
803
                }
804
        }
805
        return nil
806
}
807
 
808
// Rows is the result of a query. Its cursor starts before the first row
809
// of the result set. Use Next to advance through the rows:
810
//
811
//     rows, err := db.Query("SELECT ...")
812
//     ...
813
//     for rows.Next() {
814
//         var id int
815
//         var name string
816
//         err = rows.Scan(&id, &name)
817
//         ...
818
//     }
819
//     err = rows.Err() // get any error encountered during iteration
820
//     ...
821
type Rows struct {
822
        db          *DB
823
        ci          driver.Conn // owned; must call putconn when closed to release
824
        releaseConn func()
825
        rowsi       driver.Rows
826
 
827
        closed    bool
828
        lastcols  []interface{}
829
        lasterr   error
830
        closeStmt *Stmt // if non-nil, statement to Close on close
831
}
832
 
833
// Next prepares the next result row for reading with the Scan method.
834
// It returns true on success, false if there is no next result row.
835
// Every call to Scan, even the first one, must be preceded by a call
836
// to Next.
837
func (rs *Rows) Next() bool {
838
        if rs.closed {
839
                return false
840
        }
841
        if rs.lasterr != nil {
842
                return false
843
        }
844
        if rs.lastcols == nil {
845
                rs.lastcols = make([]interface{}, len(rs.rowsi.Columns()))
846
        }
847
        rs.lasterr = rs.rowsi.Next(rs.lastcols)
848
        if rs.lasterr == io.EOF {
849
                rs.Close()
850
        }
851
        return rs.lasterr == nil
852
}
853
 
854
// Err returns the error, if any, that was encountered during iteration.
855
func (rs *Rows) Err() error {
856
        if rs.lasterr == io.EOF {
857
                return nil
858
        }
859
        return rs.lasterr
860
}
861
 
862
// Columns returns the column names.
863
// Columns returns an error if the rows are closed, or if the rows
864
// are from QueryRow and there was a deferred error.
865
func (rs *Rows) Columns() ([]string, error) {
866
        if rs.closed {
867
                return nil, errors.New("sql: Rows are closed")
868
        }
869
        if rs.rowsi == nil {
870
                return nil, errors.New("sql: no Rows available")
871
        }
872
        return rs.rowsi.Columns(), nil
873
}
874
 
875
// Scan copies the columns in the current row into the values pointed
876
// at by dest.
877
//
878
// If an argument has type *[]byte, Scan saves in that argument a copy
879
// of the corresponding data. The copy is owned by the caller and can
880
// be modified and held indefinitely. The copy can be avoided by using
881
// an argument of type *RawBytes instead; see the documentation for
882
// RawBytes for restrictions on its use.
883
//
884
// If an argument has type *interface{}, Scan copies the value
885
// provided by the underlying driver without conversion. If the value
886
// is of type []byte, a copy is made and the caller owns the result.
887
func (rs *Rows) Scan(dest ...interface{}) error {
888
        if rs.closed {
889
                return errors.New("sql: Rows closed")
890
        }
891
        if rs.lasterr != nil {
892
                return rs.lasterr
893
        }
894
        if rs.lastcols == nil {
895
                return errors.New("sql: Scan called without calling Next")
896
        }
897
        if len(dest) != len(rs.lastcols) {
898
                return fmt.Errorf("sql: expected %d destination arguments in Scan, not %d", len(rs.lastcols), len(dest))
899
        }
900
        for i, sv := range rs.lastcols {
901
                err := convertAssign(dest[i], sv)
902
                if err != nil {
903
                        return fmt.Errorf("sql: Scan error on column index %d: %v", i, err)
904
                }
905
        }
906
        for _, dp := range dest {
907
                b, ok := dp.(*[]byte)
908
                if !ok {
909
                        continue
910
                }
911
                if *b == nil {
912
                        // If the []byte is now nil (for a NULL value),
913
                        // don't fall through to below which would
914
                        // turn it into a non-nil 0-length byte slice
915
                        continue
916
                }
917
                if _, ok = dp.(*RawBytes); ok {
918
                        continue
919
                }
920
                clone := make([]byte, len(*b))
921
                copy(clone, *b)
922
                *b = clone
923
        }
924
        return nil
925
}
926
 
927
// Close closes the Rows, preventing further enumeration. If the
928
// end is encountered, the Rows are closed automatically. Close
929
// is idempotent.
930
func (rs *Rows) Close() error {
931
        if rs.closed {
932
                return nil
933
        }
934
        rs.closed = true
935
        err := rs.rowsi.Close()
936
        rs.releaseConn()
937
        if rs.closeStmt != nil {
938
                rs.closeStmt.Close()
939
        }
940
        return err
941
}
942
 
943
// Row is the result of calling QueryRow to select a single row.
944
type Row struct {
945
        // One of these two will be non-nil:
946
        err  error // deferred error for easy chaining
947
        rows *Rows
948
}
949
 
950
// Scan copies the columns from the matched row into the values
951
// pointed at by dest.  If more than one row matches the query,
952
// Scan uses the first row and discards the rest.  If no row matches
953
// the query, Scan returns ErrNoRows.
954
func (r *Row) Scan(dest ...interface{}) error {
955
        if r.err != nil {
956
                return r.err
957
        }
958
 
959
        // TODO(bradfitz): for now we need to defensively clone all
960
        // []byte that the driver returned (not permitting
961
        // *RawBytes in Rows.Scan), since we're about to close
962
        // the Rows in our defer, when we return from this function.
963
        // the contract with the driver.Next(...) interface is that it
964
        // can return slices into read-only temporary memory that's
965
        // only valid until the next Scan/Close.  But the TODO is that
966
        // for a lot of drivers, this copy will be unnecessary.  We
967
        // should provide an optional interface for drivers to
968
        // implement to say, "don't worry, the []bytes that I return
969
        // from Next will not be modified again." (for instance, if
970
        // they were obtained from the network anyway) But for now we
971
        // don't care.
972
        for _, dp := range dest {
973
                if _, ok := dp.(*RawBytes); ok {
974
                        return errors.New("sql: RawBytes isn't allowed on Row.Scan")
975
                }
976
        }
977
 
978
        defer r.rows.Close()
979
        if !r.rows.Next() {
980
                return ErrNoRows
981
        }
982
        err := r.rows.Scan(dest...)
983
        if err != nil {
984
                return err
985
        }
986
 
987
        return nil
988
}
989
 
990
// A Result summarizes an executed SQL command.
991
type Result interface {
992
        LastInsertId() (int64, error)
993
        RowsAffected() (int64, error)
994
}
995
 
996
type result struct {
997
        driver.Result
998
}

powered by: WebSVN 2.1.0

© copyright 1999-2024 OpenCores.org, equivalent to Oliscience, all rights reserved. OpenCores®, registered trademark.