Imported Upstream version 4.8.1
[platform/upstream/gcc48.git] / libgo / go / database / sql / sql_test.go
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 sql
6
7 import (
8         "database/sql/driver"
9         "fmt"
10         "reflect"
11         "runtime"
12         "strings"
13         "testing"
14         "time"
15 )
16
17 func init() {
18         type dbConn struct {
19                 db *DB
20                 c  driver.Conn
21         }
22         freedFrom := make(map[dbConn]string)
23         putConnHook = func(db *DB, c driver.Conn) {
24                 for _, oc := range db.freeConn {
25                         if oc == c {
26                                 // print before panic, as panic may get lost due to conflicting panic
27                                 // (all goroutines asleep) elsewhere, since we might not unlock
28                                 // the mutex in freeConn here.
29                                 println("double free of conn. conflicts are:\nA) " + freedFrom[dbConn{db, c}] + "\n\nand\nB) " + stack())
30                                 panic("double free of conn.")
31                         }
32                 }
33                 freedFrom[dbConn{db, c}] = stack()
34         }
35 }
36
37 const fakeDBName = "foo"
38
39 var chrisBirthday = time.Unix(123456789, 0)
40
41 func newTestDB(t *testing.T, name string) *DB {
42         db, err := Open("test", fakeDBName)
43         if err != nil {
44                 t.Fatalf("Open: %v", err)
45         }
46         if _, err := db.Exec("WIPE"); err != nil {
47                 t.Fatalf("exec wipe: %v", err)
48         }
49         if name == "people" {
50                 exec(t, db, "CREATE|people|name=string,age=int32,photo=blob,dead=bool,bdate=datetime")
51                 exec(t, db, "INSERT|people|name=Alice,age=?,photo=APHOTO", 1)
52                 exec(t, db, "INSERT|people|name=Bob,age=?,photo=BPHOTO", 2)
53                 exec(t, db, "INSERT|people|name=Chris,age=?,photo=CPHOTO,bdate=?", 3, chrisBirthday)
54         }
55         return db
56 }
57
58 func exec(t *testing.T, db *DB, query string, args ...interface{}) {
59         _, err := db.Exec(query, args...)
60         if err != nil {
61                 t.Fatalf("Exec of %q: %v", query, err)
62         }
63 }
64
65 func closeDB(t *testing.T, db *DB) {
66         err := db.Close()
67         if err != nil {
68                 t.Fatalf("error closing DB: %v", err)
69         }
70 }
71
72 // numPrepares assumes that db has exactly 1 idle conn and returns
73 // its count of calls to Prepare
74 func numPrepares(t *testing.T, db *DB) int {
75         if n := len(db.freeConn); n != 1 {
76                 t.Fatalf("free conns = %d; want 1", n)
77         }
78         return db.freeConn[0].(*fakeConn).numPrepare
79 }
80
81 func TestQuery(t *testing.T) {
82         db := newTestDB(t, "people")
83         defer closeDB(t, db)
84         prepares0 := numPrepares(t, db)
85         rows, err := db.Query("SELECT|people|age,name|")
86         if err != nil {
87                 t.Fatalf("Query: %v", err)
88         }
89         type row struct {
90                 age  int
91                 name string
92         }
93         got := []row{}
94         for rows.Next() {
95                 var r row
96                 err = rows.Scan(&r.age, &r.name)
97                 if err != nil {
98                         t.Fatalf("Scan: %v", err)
99                 }
100                 got = append(got, r)
101         }
102         err = rows.Err()
103         if err != nil {
104                 t.Fatalf("Err: %v", err)
105         }
106         want := []row{
107                 {age: 1, name: "Alice"},
108                 {age: 2, name: "Bob"},
109                 {age: 3, name: "Chris"},
110         }
111         if !reflect.DeepEqual(got, want) {
112                 t.Errorf("mismatch.\n got: %#v\nwant: %#v", got, want)
113         }
114
115         // And verify that the final rows.Next() call, which hit EOF,
116         // also closed the rows connection.
117         if n := len(db.freeConn); n != 1 {
118                 t.Fatalf("free conns after query hitting EOF = %d; want 1", n)
119         }
120         if prepares := numPrepares(t, db) - prepares0; prepares != 1 {
121                 t.Errorf("executed %d Prepare statements; want 1", prepares)
122         }
123 }
124
125 func TestByteOwnership(t *testing.T) {
126         db := newTestDB(t, "people")
127         defer closeDB(t, db)
128         rows, err := db.Query("SELECT|people|name,photo|")
129         if err != nil {
130                 t.Fatalf("Query: %v", err)
131         }
132         type row struct {
133                 name  []byte
134                 photo RawBytes
135         }
136         got := []row{}
137         for rows.Next() {
138                 var r row
139                 err = rows.Scan(&r.name, &r.photo)
140                 if err != nil {
141                         t.Fatalf("Scan: %v", err)
142                 }
143                 got = append(got, r)
144         }
145         corruptMemory := []byte("\xffPHOTO")
146         want := []row{
147                 {name: []byte("Alice"), photo: corruptMemory},
148                 {name: []byte("Bob"), photo: corruptMemory},
149                 {name: []byte("Chris"), photo: corruptMemory},
150         }
151         if !reflect.DeepEqual(got, want) {
152                 t.Errorf("mismatch.\n got: %#v\nwant: %#v", got, want)
153         }
154
155         var photo RawBytes
156         err = db.QueryRow("SELECT|people|photo|name=?", "Alice").Scan(&photo)
157         if err == nil {
158                 t.Error("want error scanning into RawBytes from QueryRow")
159         }
160 }
161
162 func TestRowsColumns(t *testing.T) {
163         db := newTestDB(t, "people")
164         defer closeDB(t, db)
165         rows, err := db.Query("SELECT|people|age,name|")
166         if err != nil {
167                 t.Fatalf("Query: %v", err)
168         }
169         cols, err := rows.Columns()
170         if err != nil {
171                 t.Fatalf("Columns: %v", err)
172         }
173         want := []string{"age", "name"}
174         if !reflect.DeepEqual(cols, want) {
175                 t.Errorf("got %#v; want %#v", cols, want)
176         }
177 }
178
179 func TestQueryRow(t *testing.T) {
180         db := newTestDB(t, "people")
181         defer closeDB(t, db)
182         var name string
183         var age int
184         var birthday time.Time
185
186         err := db.QueryRow("SELECT|people|age,name|age=?", 3).Scan(&age)
187         if err == nil || !strings.Contains(err.Error(), "expected 2 destination arguments") {
188                 t.Errorf("expected error from wrong number of arguments; actually got: %v", err)
189         }
190
191         err = db.QueryRow("SELECT|people|bdate|age=?", 3).Scan(&birthday)
192         if err != nil || !birthday.Equal(chrisBirthday) {
193                 t.Errorf("chris birthday = %v, err = %v; want %v", birthday, err, chrisBirthday)
194         }
195
196         err = db.QueryRow("SELECT|people|age,name|age=?", 2).Scan(&age, &name)
197         if err != nil {
198                 t.Fatalf("age QueryRow+Scan: %v", err)
199         }
200         if name != "Bob" {
201                 t.Errorf("expected name Bob, got %q", name)
202         }
203         if age != 2 {
204                 t.Errorf("expected age 2, got %d", age)
205         }
206
207         err = db.QueryRow("SELECT|people|age,name|name=?", "Alice").Scan(&age, &name)
208         if err != nil {
209                 t.Fatalf("name QueryRow+Scan: %v", err)
210         }
211         if name != "Alice" {
212                 t.Errorf("expected name Alice, got %q", name)
213         }
214         if age != 1 {
215                 t.Errorf("expected age 1, got %d", age)
216         }
217
218         var photo []byte
219         err = db.QueryRow("SELECT|people|photo|name=?", "Alice").Scan(&photo)
220         if err != nil {
221                 t.Fatalf("photo QueryRow+Scan: %v", err)
222         }
223         want := []byte("APHOTO")
224         if !reflect.DeepEqual(photo, want) {
225                 t.Errorf("photo = %q; want %q", photo, want)
226         }
227 }
228
229 func TestStatementErrorAfterClose(t *testing.T) {
230         db := newTestDB(t, "people")
231         defer closeDB(t, db)
232         stmt, err := db.Prepare("SELECT|people|age|name=?")
233         if err != nil {
234                 t.Fatalf("Prepare: %v", err)
235         }
236         err = stmt.Close()
237         if err != nil {
238                 t.Fatalf("Close: %v", err)
239         }
240         var name string
241         err = stmt.QueryRow("foo").Scan(&name)
242         if err == nil {
243                 t.Errorf("expected error from QueryRow.Scan after Stmt.Close")
244         }
245 }
246
247 func TestStatementQueryRow(t *testing.T) {
248         db := newTestDB(t, "people")
249         defer closeDB(t, db)
250         stmt, err := db.Prepare("SELECT|people|age|name=?")
251         if err != nil {
252                 t.Fatalf("Prepare: %v", err)
253         }
254         defer stmt.Close()
255         var age int
256         for n, tt := range []struct {
257                 name string
258                 want int
259         }{
260                 {"Alice", 1},
261                 {"Bob", 2},
262                 {"Chris", 3},
263         } {
264                 if err := stmt.QueryRow(tt.name).Scan(&age); err != nil {
265                         t.Errorf("%d: on %q, QueryRow/Scan: %v", n, tt.name, err)
266                 } else if age != tt.want {
267                         t.Errorf("%d: age=%d, want %d", n, age, tt.want)
268                 }
269         }
270
271 }
272
273 // just a test of fakedb itself
274 func TestBogusPreboundParameters(t *testing.T) {
275         db := newTestDB(t, "foo")
276         defer closeDB(t, db)
277         exec(t, db, "CREATE|t1|name=string,age=int32,dead=bool")
278         _, err := db.Prepare("INSERT|t1|name=?,age=bogusconversion")
279         if err == nil {
280                 t.Fatalf("expected error")
281         }
282         if err.Error() != `fakedb: invalid conversion to int32 from "bogusconversion"` {
283                 t.Errorf("unexpected error: %v", err)
284         }
285 }
286
287 func TestExec(t *testing.T) {
288         db := newTestDB(t, "foo")
289         defer closeDB(t, db)
290         exec(t, db, "CREATE|t1|name=string,age=int32,dead=bool")
291         stmt, err := db.Prepare("INSERT|t1|name=?,age=?")
292         if err != nil {
293                 t.Errorf("Stmt, err = %v, %v", stmt, err)
294         }
295         defer stmt.Close()
296
297         type execTest struct {
298                 args    []interface{}
299                 wantErr string
300         }
301         execTests := []execTest{
302                 // Okay:
303                 {[]interface{}{"Brad", 31}, ""},
304                 {[]interface{}{"Brad", int64(31)}, ""},
305                 {[]interface{}{"Bob", "32"}, ""},
306                 {[]interface{}{7, 9}, ""},
307
308                 // Invalid conversions:
309                 {[]interface{}{"Brad", int64(0xFFFFFFFF)}, "sql: converting argument #1's type: sql/driver: value 4294967295 overflows int32"},
310                 {[]interface{}{"Brad", "strconv fail"}, "sql: converting argument #1's type: sql/driver: value \"strconv fail\" can't be converted to int32"},
311
312                 // Wrong number of args:
313                 {[]interface{}{}, "sql: expected 2 arguments, got 0"},
314                 {[]interface{}{1, 2, 3}, "sql: expected 2 arguments, got 3"},
315         }
316         for n, et := range execTests {
317                 _, err := stmt.Exec(et.args...)
318                 errStr := ""
319                 if err != nil {
320                         errStr = err.Error()
321                 }
322                 if errStr != et.wantErr {
323                         t.Errorf("stmt.Execute #%d: for %v, got error %q, want error %q",
324                                 n, et.args, errStr, et.wantErr)
325                 }
326         }
327 }
328
329 func TestTxStmt(t *testing.T) {
330         db := newTestDB(t, "")
331         defer closeDB(t, db)
332         exec(t, db, "CREATE|t1|name=string,age=int32,dead=bool")
333         stmt, err := db.Prepare("INSERT|t1|name=?,age=?")
334         if err != nil {
335                 t.Fatalf("Stmt, err = %v, %v", stmt, err)
336         }
337         defer stmt.Close()
338         tx, err := db.Begin()
339         if err != nil {
340                 t.Fatalf("Begin = %v", err)
341         }
342         txs := tx.Stmt(stmt)
343         defer txs.Close()
344         _, err = txs.Exec("Bobby", 7)
345         if err != nil {
346                 t.Fatalf("Exec = %v", err)
347         }
348         err = tx.Commit()
349         if err != nil {
350                 t.Fatalf("Commit = %v", err)
351         }
352 }
353
354 // Issue: http://golang.org/issue/2784
355 // This test didn't fail before because we got luckly with the fakedb driver.
356 // It was failing, and now not, in github.com/bradfitz/go-sql-test
357 func TestTxQuery(t *testing.T) {
358         db := newTestDB(t, "")
359         defer closeDB(t, db)
360         exec(t, db, "CREATE|t1|name=string,age=int32,dead=bool")
361         exec(t, db, "INSERT|t1|name=Alice")
362
363         tx, err := db.Begin()
364         if err != nil {
365                 t.Fatal(err)
366         }
367         defer tx.Rollback()
368
369         r, err := tx.Query("SELECT|t1|name|")
370         if err != nil {
371                 t.Fatal(err)
372         }
373         defer r.Close()
374
375         if !r.Next() {
376                 if r.Err() != nil {
377                         t.Fatal(r.Err())
378                 }
379                 t.Fatal("expected one row")
380         }
381
382         var x string
383         err = r.Scan(&x)
384         if err != nil {
385                 t.Fatal(err)
386         }
387 }
388
389 func TestTxQueryInvalid(t *testing.T) {
390         db := newTestDB(t, "")
391         defer closeDB(t, db)
392
393         tx, err := db.Begin()
394         if err != nil {
395                 t.Fatal(err)
396         }
397         defer tx.Rollback()
398
399         _, err = tx.Query("SELECT|t1|name|")
400         if err == nil {
401                 t.Fatal("Error expected")
402         }
403 }
404
405 // Tests fix for issue 4433, that retries in Begin happen when
406 // conn.Begin() returns ErrBadConn
407 func TestTxErrBadConn(t *testing.T) {
408         db, err := Open("test", fakeDBName+";badConn")
409         if err != nil {
410                 t.Fatalf("Open: %v", err)
411         }
412         if _, err := db.Exec("WIPE"); err != nil {
413                 t.Fatalf("exec wipe: %v", err)
414         }
415         defer closeDB(t, db)
416         exec(t, db, "CREATE|t1|name=string,age=int32,dead=bool")
417         stmt, err := db.Prepare("INSERT|t1|name=?,age=?")
418         if err != nil {
419                 t.Fatalf("Stmt, err = %v, %v", stmt, err)
420         }
421         defer stmt.Close()
422         tx, err := db.Begin()
423         if err != nil {
424                 t.Fatalf("Begin = %v", err)
425         }
426         txs := tx.Stmt(stmt)
427         defer txs.Close()
428         _, err = txs.Exec("Bobby", 7)
429         if err != nil {
430                 t.Fatalf("Exec = %v", err)
431         }
432         err = tx.Commit()
433         if err != nil {
434                 t.Fatalf("Commit = %v", err)
435         }
436 }
437
438 // Tests fix for issue 2542, that we release a lock when querying on
439 // a closed connection.
440 func TestIssue2542Deadlock(t *testing.T) {
441         db := newTestDB(t, "people")
442         closeDB(t, db)
443         for i := 0; i < 2; i++ {
444                 _, err := db.Query("SELECT|people|age,name|")
445                 if err == nil {
446                         t.Fatalf("expected error")
447                 }
448         }
449 }
450
451 // Tests fix for issue 2788, that we bind nil to a []byte if the
452 // value in the column is sql null
453 func TestNullByteSlice(t *testing.T) {
454         db := newTestDB(t, "")
455         defer closeDB(t, db)
456         exec(t, db, "CREATE|t|id=int32,name=nullstring")
457         exec(t, db, "INSERT|t|id=10,name=?", nil)
458
459         var name []byte
460
461         err := db.QueryRow("SELECT|t|name|id=?", 10).Scan(&name)
462         if err != nil {
463                 t.Fatal(err)
464         }
465         if name != nil {
466                 t.Fatalf("name []byte should be nil for null column value, got: %#v", name)
467         }
468
469         exec(t, db, "INSERT|t|id=11,name=?", "bob")
470         err = db.QueryRow("SELECT|t|name|id=?", 11).Scan(&name)
471         if err != nil {
472                 t.Fatal(err)
473         }
474         if string(name) != "bob" {
475                 t.Fatalf("name []byte should be bob, got: %q", string(name))
476         }
477 }
478
479 func TestPointerParamsAndScans(t *testing.T) {
480         db := newTestDB(t, "")
481         defer closeDB(t, db)
482         exec(t, db, "CREATE|t|id=int32,name=nullstring")
483
484         bob := "bob"
485         var name *string
486
487         name = &bob
488         exec(t, db, "INSERT|t|id=10,name=?", name)
489         name = nil
490         exec(t, db, "INSERT|t|id=20,name=?", name)
491
492         err := db.QueryRow("SELECT|t|name|id=?", 10).Scan(&name)
493         if err != nil {
494                 t.Fatalf("querying id 10: %v", err)
495         }
496         if name == nil {
497                 t.Errorf("id 10's name = nil; want bob")
498         } else if *name != "bob" {
499                 t.Errorf("id 10's name = %q; want bob", *name)
500         }
501
502         err = db.QueryRow("SELECT|t|name|id=?", 20).Scan(&name)
503         if err != nil {
504                 t.Fatalf("querying id 20: %v", err)
505         }
506         if name != nil {
507                 t.Errorf("id 20 = %q; want nil", *name)
508         }
509 }
510
511 func TestQueryRowClosingStmt(t *testing.T) {
512         db := newTestDB(t, "people")
513         defer closeDB(t, db)
514         var name string
515         var age int
516         err := db.QueryRow("SELECT|people|age,name|age=?", 3).Scan(&age, &name)
517         if err != nil {
518                 t.Fatal(err)
519         }
520         if len(db.freeConn) != 1 {
521                 t.Fatalf("expected 1 free conn")
522         }
523         fakeConn := db.freeConn[0].(*fakeConn)
524         if made, closed := fakeConn.stmtsMade, fakeConn.stmtsClosed; made != closed {
525                 t.Errorf("statement close mismatch: made %d, closed %d", made, closed)
526         }
527 }
528
529 type nullTestRow struct {
530         nullParam    interface{}
531         notNullParam interface{}
532         scanNullVal  interface{}
533 }
534
535 type nullTestSpec struct {
536         nullType    string
537         notNullType string
538         rows        [6]nullTestRow
539 }
540
541 func TestNullStringParam(t *testing.T) {
542         spec := nullTestSpec{"nullstring", "string", [6]nullTestRow{
543                 {NullString{"aqua", true}, "", NullString{"aqua", true}},
544                 {NullString{"brown", false}, "", NullString{"", false}},
545                 {"chartreuse", "", NullString{"chartreuse", true}},
546                 {NullString{"darkred", true}, "", NullString{"darkred", true}},
547                 {NullString{"eel", false}, "", NullString{"", false}},
548                 {"foo", NullString{"black", false}, nil},
549         }}
550         nullTestRun(t, spec)
551 }
552
553 func TestNullInt64Param(t *testing.T) {
554         spec := nullTestSpec{"nullint64", "int64", [6]nullTestRow{
555                 {NullInt64{31, true}, 1, NullInt64{31, true}},
556                 {NullInt64{-22, false}, 1, NullInt64{0, false}},
557                 {22, 1, NullInt64{22, true}},
558                 {NullInt64{33, true}, 1, NullInt64{33, true}},
559                 {NullInt64{222, false}, 1, NullInt64{0, false}},
560                 {0, NullInt64{31, false}, nil},
561         }}
562         nullTestRun(t, spec)
563 }
564
565 func TestNullFloat64Param(t *testing.T) {
566         spec := nullTestSpec{"nullfloat64", "float64", [6]nullTestRow{
567                 {NullFloat64{31.2, true}, 1, NullFloat64{31.2, true}},
568                 {NullFloat64{13.1, false}, 1, NullFloat64{0, false}},
569                 {-22.9, 1, NullFloat64{-22.9, true}},
570                 {NullFloat64{33.81, true}, 1, NullFloat64{33.81, true}},
571                 {NullFloat64{222, false}, 1, NullFloat64{0, false}},
572                 {10, NullFloat64{31.2, false}, nil},
573         }}
574         nullTestRun(t, spec)
575 }
576
577 func TestNullBoolParam(t *testing.T) {
578         spec := nullTestSpec{"nullbool", "bool", [6]nullTestRow{
579                 {NullBool{false, true}, true, NullBool{false, true}},
580                 {NullBool{true, false}, false, NullBool{false, false}},
581                 {true, true, NullBool{true, true}},
582                 {NullBool{true, true}, false, NullBool{true, true}},
583                 {NullBool{true, false}, true, NullBool{false, false}},
584                 {true, NullBool{true, false}, nil},
585         }}
586         nullTestRun(t, spec)
587 }
588
589 func nullTestRun(t *testing.T, spec nullTestSpec) {
590         db := newTestDB(t, "")
591         defer closeDB(t, db)
592         exec(t, db, fmt.Sprintf("CREATE|t|id=int32,name=string,nullf=%s,notnullf=%s", spec.nullType, spec.notNullType))
593
594         // Inserts with db.Exec:
595         exec(t, db, "INSERT|t|id=?,name=?,nullf=?,notnullf=?", 1, "alice", spec.rows[0].nullParam, spec.rows[0].notNullParam)
596         exec(t, db, "INSERT|t|id=?,name=?,nullf=?,notnullf=?", 2, "bob", spec.rows[1].nullParam, spec.rows[1].notNullParam)
597
598         // Inserts with a prepared statement:
599         stmt, err := db.Prepare("INSERT|t|id=?,name=?,nullf=?,notnullf=?")
600         if err != nil {
601                 t.Fatalf("prepare: %v", err)
602         }
603         defer stmt.Close()
604         if _, err := stmt.Exec(3, "chris", spec.rows[2].nullParam, spec.rows[2].notNullParam); err != nil {
605                 t.Errorf("exec insert chris: %v", err)
606         }
607         if _, err := stmt.Exec(4, "dave", spec.rows[3].nullParam, spec.rows[3].notNullParam); err != nil {
608                 t.Errorf("exec insert dave: %v", err)
609         }
610         if _, err := stmt.Exec(5, "eleanor", spec.rows[4].nullParam, spec.rows[4].notNullParam); err != nil {
611                 t.Errorf("exec insert eleanor: %v", err)
612         }
613
614         // Can't put null val into non-null col
615         if _, err := stmt.Exec(6, "bob", spec.rows[5].nullParam, spec.rows[5].notNullParam); err == nil {
616                 t.Errorf("expected error inserting nil val with prepared statement Exec")
617         }
618
619         _, err = db.Exec("INSERT|t|id=?,name=?,nullf=?", 999, nil, nil)
620         if err == nil {
621                 // TODO: this test fails, but it's just because
622                 // fakeConn implements the optional Execer interface,
623                 // so arguably this is the correct behavior.  But
624                 // maybe I should flesh out the fakeConn.Exec
625                 // implementation so this properly fails.
626                 // t.Errorf("expected error inserting nil name with Exec")
627         }
628
629         paramtype := reflect.TypeOf(spec.rows[0].nullParam)
630         bindVal := reflect.New(paramtype).Interface()
631
632         for i := 0; i < 5; i++ {
633                 id := i + 1
634                 if err := db.QueryRow("SELECT|t|nullf|id=?", id).Scan(bindVal); err != nil {
635                         t.Errorf("id=%d Scan: %v", id, err)
636                 }
637                 bindValDeref := reflect.ValueOf(bindVal).Elem().Interface()
638                 if !reflect.DeepEqual(bindValDeref, spec.rows[i].scanNullVal) {
639                         t.Errorf("id=%d got %#v, want %#v", id, bindValDeref, spec.rows[i].scanNullVal)
640                 }
641         }
642 }
643
644 func stack() string {
645         buf := make([]byte, 1024)
646         return string(buf[:runtime.Stack(buf, false)])
647 }