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.
22 freedFrom := make(map[dbConn]string)
23 putConnHook = func(db *DB, c driver.Conn) {
24 for _, oc := range db.freeConn {
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.")
33 freedFrom[dbConn{db, c}] = stack()
37 const fakeDBName = "foo"
39 var chrisBirthday = time.Unix(123456789, 0)
41 func newTestDB(t *testing.T, name string) *DB {
42 db, err := Open("test", fakeDBName)
44 t.Fatalf("Open: %v", err)
46 if _, err := db.Exec("WIPE"); err != nil {
47 t.Fatalf("exec wipe: %v", err)
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)
58 func exec(t *testing.T, db *DB, query string, args ...interface{}) {
59 _, err := db.Exec(query, args...)
61 t.Fatalf("Exec of %q: %v", query, err)
65 func closeDB(t *testing.T, db *DB) {
68 t.Fatalf("error closing DB: %v", err)
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)
78 return db.freeConn[0].(*fakeConn).numPrepare
81 func TestQuery(t *testing.T) {
82 db := newTestDB(t, "people")
84 prepares0 := numPrepares(t, db)
85 rows, err := db.Query("SELECT|people|age,name|")
87 t.Fatalf("Query: %v", err)
96 err = rows.Scan(&r.age, &r.name)
98 t.Fatalf("Scan: %v", err)
104 t.Fatalf("Err: %v", err)
107 {age: 1, name: "Alice"},
108 {age: 2, name: "Bob"},
109 {age: 3, name: "Chris"},
111 if !reflect.DeepEqual(got, want) {
112 t.Errorf("mismatch.\n got: %#v\nwant: %#v", got, want)
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)
120 if prepares := numPrepares(t, db) - prepares0; prepares != 1 {
121 t.Errorf("executed %d Prepare statements; want 1", prepares)
125 func TestByteOwnership(t *testing.T) {
126 db := newTestDB(t, "people")
128 rows, err := db.Query("SELECT|people|name,photo|")
130 t.Fatalf("Query: %v", err)
139 err = rows.Scan(&r.name, &r.photo)
141 t.Fatalf("Scan: %v", err)
145 corruptMemory := []byte("\xffPHOTO")
147 {name: []byte("Alice"), photo: corruptMemory},
148 {name: []byte("Bob"), photo: corruptMemory},
149 {name: []byte("Chris"), photo: corruptMemory},
151 if !reflect.DeepEqual(got, want) {
152 t.Errorf("mismatch.\n got: %#v\nwant: %#v", got, want)
156 err = db.QueryRow("SELECT|people|photo|name=?", "Alice").Scan(&photo)
158 t.Error("want error scanning into RawBytes from QueryRow")
162 func TestRowsColumns(t *testing.T) {
163 db := newTestDB(t, "people")
165 rows, err := db.Query("SELECT|people|age,name|")
167 t.Fatalf("Query: %v", err)
169 cols, err := rows.Columns()
171 t.Fatalf("Columns: %v", err)
173 want := []string{"age", "name"}
174 if !reflect.DeepEqual(cols, want) {
175 t.Errorf("got %#v; want %#v", cols, want)
179 func TestQueryRow(t *testing.T) {
180 db := newTestDB(t, "people")
184 var birthday time.Time
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)
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)
196 err = db.QueryRow("SELECT|people|age,name|age=?", 2).Scan(&age, &name)
198 t.Fatalf("age QueryRow+Scan: %v", err)
201 t.Errorf("expected name Bob, got %q", name)
204 t.Errorf("expected age 2, got %d", age)
207 err = db.QueryRow("SELECT|people|age,name|name=?", "Alice").Scan(&age, &name)
209 t.Fatalf("name QueryRow+Scan: %v", err)
212 t.Errorf("expected name Alice, got %q", name)
215 t.Errorf("expected age 1, got %d", age)
219 err = db.QueryRow("SELECT|people|photo|name=?", "Alice").Scan(&photo)
221 t.Fatalf("photo QueryRow+Scan: %v", err)
223 want := []byte("APHOTO")
224 if !reflect.DeepEqual(photo, want) {
225 t.Errorf("photo = %q; want %q", photo, want)
229 func TestStatementErrorAfterClose(t *testing.T) {
230 db := newTestDB(t, "people")
232 stmt, err := db.Prepare("SELECT|people|age|name=?")
234 t.Fatalf("Prepare: %v", err)
238 t.Fatalf("Close: %v", err)
241 err = stmt.QueryRow("foo").Scan(&name)
243 t.Errorf("expected error from QueryRow.Scan after Stmt.Close")
247 func TestStatementQueryRow(t *testing.T) {
248 db := newTestDB(t, "people")
250 stmt, err := db.Prepare("SELECT|people|age|name=?")
252 t.Fatalf("Prepare: %v", err)
256 for n, tt := range []struct {
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)
273 // just a test of fakedb itself
274 func TestBogusPreboundParameters(t *testing.T) {
275 db := newTestDB(t, "foo")
277 exec(t, db, "CREATE|t1|name=string,age=int32,dead=bool")
278 _, err := db.Prepare("INSERT|t1|name=?,age=bogusconversion")
280 t.Fatalf("expected error")
282 if err.Error() != `fakedb: invalid conversion to int32 from "bogusconversion"` {
283 t.Errorf("unexpected error: %v", err)
287 func TestExec(t *testing.T) {
288 db := newTestDB(t, "foo")
290 exec(t, db, "CREATE|t1|name=string,age=int32,dead=bool")
291 stmt, err := db.Prepare("INSERT|t1|name=?,age=?")
293 t.Errorf("Stmt, err = %v, %v", stmt, err)
297 type execTest struct {
301 execTests := []execTest{
303 {[]interface{}{"Brad", 31}, ""},
304 {[]interface{}{"Brad", int64(31)}, ""},
305 {[]interface{}{"Bob", "32"}, ""},
306 {[]interface{}{7, 9}, ""},
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"},
312 // Wrong number of args:
313 {[]interface{}{}, "sql: expected 2 arguments, got 0"},
314 {[]interface{}{1, 2, 3}, "sql: expected 2 arguments, got 3"},
316 for n, et := range execTests {
317 _, err := stmt.Exec(et.args...)
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)
329 func TestTxStmt(t *testing.T) {
330 db := newTestDB(t, "")
332 exec(t, db, "CREATE|t1|name=string,age=int32,dead=bool")
333 stmt, err := db.Prepare("INSERT|t1|name=?,age=?")
335 t.Fatalf("Stmt, err = %v, %v", stmt, err)
338 tx, err := db.Begin()
340 t.Fatalf("Begin = %v", err)
344 _, err = txs.Exec("Bobby", 7)
346 t.Fatalf("Exec = %v", err)
350 t.Fatalf("Commit = %v", err)
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, "")
360 exec(t, db, "CREATE|t1|name=string,age=int32,dead=bool")
361 exec(t, db, "INSERT|t1|name=Alice")
363 tx, err := db.Begin()
369 r, err := tx.Query("SELECT|t1|name|")
379 t.Fatal("expected one row")
389 func TestTxQueryInvalid(t *testing.T) {
390 db := newTestDB(t, "")
393 tx, err := db.Begin()
399 _, err = tx.Query("SELECT|t1|name|")
401 t.Fatal("Error expected")
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")
410 t.Fatalf("Open: %v", err)
412 if _, err := db.Exec("WIPE"); err != nil {
413 t.Fatalf("exec wipe: %v", err)
416 exec(t, db, "CREATE|t1|name=string,age=int32,dead=bool")
417 stmt, err := db.Prepare("INSERT|t1|name=?,age=?")
419 t.Fatalf("Stmt, err = %v, %v", stmt, err)
422 tx, err := db.Begin()
424 t.Fatalf("Begin = %v", err)
428 _, err = txs.Exec("Bobby", 7)
430 t.Fatalf("Exec = %v", err)
434 t.Fatalf("Commit = %v", err)
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")
443 for i := 0; i < 2; i++ {
444 _, err := db.Query("SELECT|people|age,name|")
446 t.Fatalf("expected error")
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, "")
456 exec(t, db, "CREATE|t|id=int32,name=nullstring")
457 exec(t, db, "INSERT|t|id=10,name=?", nil)
461 err := db.QueryRow("SELECT|t|name|id=?", 10).Scan(&name)
466 t.Fatalf("name []byte should be nil for null column value, got: %#v", name)
469 exec(t, db, "INSERT|t|id=11,name=?", "bob")
470 err = db.QueryRow("SELECT|t|name|id=?", 11).Scan(&name)
474 if string(name) != "bob" {
475 t.Fatalf("name []byte should be bob, got: %q", string(name))
479 func TestPointerParamsAndScans(t *testing.T) {
480 db := newTestDB(t, "")
482 exec(t, db, "CREATE|t|id=int32,name=nullstring")
488 exec(t, db, "INSERT|t|id=10,name=?", name)
490 exec(t, db, "INSERT|t|id=20,name=?", name)
492 err := db.QueryRow("SELECT|t|name|id=?", 10).Scan(&name)
494 t.Fatalf("querying id 10: %v", err)
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)
502 err = db.QueryRow("SELECT|t|name|id=?", 20).Scan(&name)
504 t.Fatalf("querying id 20: %v", err)
507 t.Errorf("id 20 = %q; want nil", *name)
511 func TestQueryRowClosingStmt(t *testing.T) {
512 db := newTestDB(t, "people")
516 err := db.QueryRow("SELECT|people|age,name|age=?", 3).Scan(&age, &name)
520 if len(db.freeConn) != 1 {
521 t.Fatalf("expected 1 free conn")
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)
529 type nullTestRow struct {
530 nullParam interface{}
531 notNullParam interface{}
532 scanNullVal interface{}
535 type nullTestSpec struct {
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},
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},
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},
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},
589 func nullTestRun(t *testing.T, spec nullTestSpec) {
590 db := newTestDB(t, "")
592 exec(t, db, fmt.Sprintf("CREATE|t|id=int32,name=string,nullf=%s,notnullf=%s", spec.nullType, spec.notNullType))
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)
598 // Inserts with a prepared statement:
599 stmt, err := db.Prepare("INSERT|t|id=?,name=?,nullf=?,notnullf=?")
601 t.Fatalf("prepare: %v", err)
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)
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)
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)
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")
619 _, err = db.Exec("INSERT|t|id=?,name=?,nullf=?", 999, nil, 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")
629 paramtype := reflect.TypeOf(spec.rows[0].nullParam)
630 bindVal := reflect.New(paramtype).Interface()
632 for i := 0; i < 5; i++ {
634 if err := db.QueryRow("SELECT|t|nullf|id=?", id).Scan(bindVal); err != nil {
635 t.Errorf("id=%d Scan: %v", id, err)
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)
644 func stack() string {
645 buf := make([]byte, 1024)
646 return string(buf[:runtime.Stack(buf, false)])