Debian Codegraph @

sqlite3_test.go

raw
1 // Copyright (C) 2019 Yasuhiro Matsumoto <[email protected]>.
2 //
3 // Use of this source code is governed by an MIT-style
4 // license that can be found in the LICENSE file.
5
6 //go:build cgo
7 // +build cgo
8
9 package sqlite3
10
11 import (
12 "bytes"
13 "database/sql"
14 "database/sql/driver"
15 "errors"
16 "fmt"
17 "io/ioutil"
18 "math/rand"
19 "net/url"
20 "os"
21 "reflect"
22 "regexp"
23 "runtime"
24 "strconv"
25 "strings"
26 "sync"
27 "testing"
28 "time"
29 )
30
31 func TempFilename(t testing.TB) string {
32 f, err := ioutil.TempFile("", "go-sqlite3-test-")
33 if err != nil {
34 t.Fatal(err)
35 }
36 f.Close()
37 return f.Name()
38 }
39
40 func doTestOpen(t *testing.T, option string) (string, error) {
41 tempFilename := TempFilename(t)
42 url := tempFilename + option
43
44 defer func() {
45 err := os.Remove(tempFilename)
46 if err != nil {
47 t.Error("temp file remove error:", err)
48 }
49 }()
50
51 db, err := sql.Open("sqlite3", url)
52 if err != nil {
53 return "Failed to open database:", err
54 }
55
56 defer func() {
57 err = db.Close()
58 if err != nil {
59 t.Error("db close error:", err)
60 }
61 }()
62
63 err = db.Ping()
64 if err != nil {
65 return "ping error:", err
66 }
67
68 _, err = db.Exec("drop table foo")
69 _, err = db.Exec("create table foo (id integer)")
70 if err != nil {
71 return "Failed to create table:", err
72 }
73
74 if stat, err := os.Stat(tempFilename); err != nil || stat.IsDir() {
75 return "Failed to create ./foo.db", nil
76 }
77
78 return "", nil
79 }
80
81 func TestOpen(t *testing.T) {
82 cases := map[string]bool{
83 "": true,
84 "?_txlock=immediate": true,
85 "?_txlock=deferred": true,
86 "?_txlock=exclusive": true,
87 "?_txlock=bogus": false,
88 }
89 for option, expectedPass := range cases {
90 result, err := doTestOpen(t, option)
91 if result == "" {
92 if !expectedPass {
93 errmsg := fmt.Sprintf("_txlock error not caught at dbOpen with option: %s", option)
94 t.Fatal(errmsg)
95 }
96 } else if expectedPass {
97 if err == nil {
98 t.Fatal(result)
99 } else {
100 t.Fatal(result, err)
101 }
102 }
103 }
104 }
105
106 func TestOpenWithVFS(t *testing.T) {
107 filename := t.Name() + ".sqlite"
108
109 if err := os.Remove(filename); err != nil && !os.IsNotExist(err) {
110 t.Fatal(err)
111 }
112 defer os.Remove(filename)
113
114 db, err := sql.Open("sqlite3", fmt.Sprintf("file:%s?vfs=hello", filename))
115 if err != nil {
116 t.Fatal("Failed to open", err)
117 }
118 err = db.Ping()
119 if err == nil {
120 t.Fatal("Failed to open", err)
121 }
122 db.Close()
123
124 defer os.Remove(filename)
125
126 var vfs string
127 if runtime.GOOS == "windows" {
128 vfs = "win32-none"
129 } else {
130 vfs = "unix-none"
131 }
132 db, err = sql.Open("sqlite3", fmt.Sprintf("file:%s?vfs=%s", filename, vfs))
133 if err != nil {
134 t.Fatal("Failed to open", err)
135 }
136 err = db.Ping()
137 if err != nil {
138 t.Fatal("Failed to ping", err)
139 }
140 db.Close()
141 }
142
143 func TestOpenNoCreate(t *testing.T) {
144 filename := t.Name() + ".sqlite"
145
146 if err := os.Remove(filename); err != nil && !os.IsNotExist(err) {
147 t.Fatal(err)
148 }
149 defer os.Remove(filename)
150
151 // https://golang.org/pkg/database/sql/#Open
152 // "Open may just validate its arguments without creating a connection
153 // to the database. To verify that the data source name is valid, call Ping."
154 db, err := sql.Open("sqlite3", fmt.Sprintf("file:%s?mode=rw", filename))
155 if err == nil {
156 defer db.Close()
157
158 err = db.Ping()
159 if err == nil {
160 t.Fatal("expected error from Open or Ping")
161 }
162 }
163
164 sqlErr, ok := err.(Error)
165 if !ok {
166 t.Fatalf("expected sqlite3.Error, but got %T", err)
167 }
168
169 if sqlErr.Code != ErrCantOpen {
170 t.Fatalf("expected SQLITE_CANTOPEN, but got %v", sqlErr)
171 }
172
173 // make sure database file truly was not created
174 if _, err := os.Stat(filename); !os.IsNotExist(err) {
175 if err != nil {
176 t.Fatal(err)
177 }
178 t.Fatal("expected database file to not exist")
179 }
180
181 // verify that it works if the mode is "rwc" instead
182 db, err = sql.Open("sqlite3", fmt.Sprintf("file:%s?mode=rwc", filename))
183 if err != nil {
184 t.Fatal(err)
185 }
186 defer db.Close()
187
188 if err := db.Ping(); err != nil {
189 t.Fatal(err)
190 }
191
192 // make sure database file truly was created
193 if _, err := os.Stat(filename); err != nil {
194 if !os.IsNotExist(err) {
195 t.Fatal(err)
196 }
197 t.Fatal("expected database file to exist")
198 }
199 }
200
201 func TestReadonly(t *testing.T) {
202 tempFilename := TempFilename(t)
203 defer os.Remove(tempFilename)
204
205 db1, err := sql.Open("sqlite3", "file:"+tempFilename)
206 if err != nil {
207 t.Fatal(err)
208 }
209 db1.Exec("CREATE TABLE test (x int, y float)")
210
211 db2, err := sql.Open("sqlite3", "file:"+tempFilename+"?mode=ro")
212 if err != nil {
213 t.Fatal(err)
214 }
215 _ = db2
216 _, err = db2.Exec("INSERT INTO test VALUES (1, 3.14)")
217 if err == nil {
218 t.Fatal("didn't expect INSERT into read-only database to work")
219 }
220 }
221
222 func TestForeignKeys(t *testing.T) {
223 cases := map[string]bool{
224 "?_foreign_keys=1": true,
225 "?_foreign_keys=0": false,
226 }
227 for option, want := range cases {
228 fname := TempFilename(t)
229 uri := "file:" + fname + option
230 db, err := sql.Open("sqlite3", uri)
231 if err != nil {
232 os.Remove(fname)
233 t.Errorf("sql.Open(\"sqlite3\", %q): %v", uri, err)
234 continue
235 }
236 var enabled bool
237 err = db.QueryRow("PRAGMA foreign_keys;").Scan(&enabled)
238 db.Close()
239 os.Remove(fname)
240 if err != nil {
241 t.Errorf("query foreign_keys for %s: %v", uri, err)
242 continue
243 }
244 if enabled != want {
245 t.Errorf("\"PRAGMA foreign_keys;\" for %q = %t; want %t", uri, enabled, want)
246 continue
247 }
248 }
249 }
250
251 func TestDeferredForeignKey(t *testing.T) {
252 fname := TempFilename(t)
253 uri := "file:" + fname + "?_foreign_keys=1"
254 db, err := sql.Open("sqlite3", uri)
255 if err != nil {
256 os.Remove(fname)
257 t.Errorf("sql.Open(\"sqlite3\", %q): %v", uri, err)
258 }
259 _, err = db.Exec("CREATE TABLE bar (id INTEGER PRIMARY KEY)")
260 if err != nil {
261 t.Errorf("failed creating tables: %v", err)
262 }
263 _, err = db.Exec("CREATE TABLE foo (bar_id INTEGER, FOREIGN KEY(bar_id) REFERENCES bar(id) DEFERRABLE INITIALLY DEFERRED)")
264 if err != nil {
265 t.Errorf("failed creating tables: %v", err)
266 }
267 tx, err := db.Begin()
268 if err != nil {
269 t.Errorf("Failed to begin transaction: %v", err)
270 }
271 _, err = tx.Exec("INSERT INTO foo (bar_id) VALUES (123)")
272 if err != nil {
273 t.Errorf("Failed to insert row: %v", err)
274 }
275 err = tx.Commit()
276 if err == nil {
277 t.Errorf("Expected an error: %v", err)
278 }
279 _, err = db.Begin()
280 if err != nil {
281 t.Errorf("Failed to begin transaction: %v", err)
282 }
283
284 db.Close()
285 os.Remove(fname)
286 }
287
288 func TestRecursiveTriggers(t *testing.T) {
289 cases := map[string]bool{
290 "?_recursive_triggers=1": true,
291 "?_recursive_triggers=0": false,
292 }
293 for option, want := range cases {
294 fname := TempFilename(t)
295 uri := "file:" + fname + option
296 db, err := sql.Open("sqlite3", uri)
297 if err != nil {
298 os.Remove(fname)
299 t.Errorf("sql.Open(\"sqlite3\", %q): %v", uri, err)
300 continue
301 }
302 var enabled bool
303 err = db.QueryRow("PRAGMA recursive_triggers;").Scan(&enabled)
304 db.Close()
305 os.Remove(fname)
306 if err != nil {
307 t.Errorf("query recursive_triggers for %s: %v", uri, err)
308 continue
309 }
310 if enabled != want {
311 t.Errorf("\"PRAGMA recursive_triggers;\" for %q = %t; want %t", uri, enabled, want)
312 continue
313 }
314 }
315 }
316
317 func TestClose(t *testing.T) {
318 tempFilename := TempFilename(t)
319 defer os.Remove(tempFilename)
320 db, err := sql.Open("sqlite3", tempFilename)
321 if err != nil {
322 t.Fatal("Failed to open database:", err)
323 }
324
325 _, err = db.Exec("drop table foo")
326 _, err = db.Exec("create table foo (id integer)")
327 if err != nil {
328 t.Fatal("Failed to create table:", err)
329 }
330
331 stmt, err := db.Prepare("select id from foo where id = ?")
332 if err != nil {
333 t.Fatal("Failed to select records:", err)
334 }
335
336 db.Close()
337 _, err = stmt.Exec(1)
338 if err == nil {
339 t.Fatal("Failed to operate closed statement")
340 }
341 }
342
343 func TestInsert(t *testing.T) {
344 tempFilename := TempFilename(t)
345 defer os.Remove(tempFilename)
346 db, err := sql.Open("sqlite3", tempFilename)
347 if err != nil {
348 t.Fatal("Failed to open database:", err)
349 }
350 defer db.Close()
351
352 _, err = db.Exec("drop table foo")
353 _, err = db.Exec("create table foo (id integer)")
354 if err != nil {
355 t.Fatal("Failed to create table:", err)
356 }
357
358 res, err := db.Exec("insert into foo(id) values(123)")
359 if err != nil {
360 t.Fatal("Failed to insert record:", err)
361 }
362 affected, _ := res.RowsAffected()
363 if affected != 1 {
364 t.Fatalf("Expected %d for affected rows, but %d:", 1, affected)
365 }
366
367 rows, err := db.Query("select id from foo")
368 if err != nil {
369 t.Fatal("Failed to select records:", err)
370 }
371 defer rows.Close()
372
373 rows.Next()
374
375 var result int
376 rows.Scan(&result)
377 if result != 123 {
378 t.Errorf("Expected %d for fetched result, but %d:", 123, result)
379 }
380 }
381
382 func TestUpsert(t *testing.T) {
383 _, n, _ := Version()
384 if n < 3024000 {
385 t.Skip("UPSERT requires sqlite3 >= 3.24.0")
386 }
387 tempFilename := TempFilename(t)
388 defer os.Remove(tempFilename)
389 db, err := sql.Open("sqlite3", tempFilename)
390 if err != nil {
391 t.Fatal("Failed to open database:", err)
392 }
393 defer db.Close()
394
395 _, err = db.Exec("drop table foo")
396 _, err = db.Exec("create table foo (name string primary key, counter integer)")
397 if err != nil {
398 t.Fatal("Failed to create table:", err)
399 }
400
401 for i := 0; i < 10; i++ {
402 res, err := db.Exec("insert into foo(name, counter) values('key', 1) on conflict (name) do update set counter=counter+1")
403 if err != nil {
404 t.Fatal("Failed to upsert record:", err)
405 }
406 affected, _ := res.RowsAffected()
407 if affected != 1 {
408 t.Fatalf("Expected %d for affected rows, but %d:", 1, affected)
409 }
410 }
411 rows, err := db.Query("select name, counter from foo")
412 if err != nil {
413 t.Fatal("Failed to select records:", err)
414 }
415 defer rows.Close()
416
417 rows.Next()
418
419 var resultName string
420 var resultCounter int
421 rows.Scan(&resultName, &resultCounter)
422 if resultName != "key" {
423 t.Errorf("Expected %s for fetched result, but %s:", "key", resultName)
424 }
425 if resultCounter != 10 {
426 t.Errorf("Expected %d for fetched result, but %d:", 10, resultCounter)
427 }
428
429 }
430
431 func TestUpdate(t *testing.T) {
432 tempFilename := TempFilename(t)
433 defer os.Remove(tempFilename)
434 db, err := sql.Open("sqlite3", tempFilename)
435 if err != nil {
436 t.Fatal("Failed to open database:", err)
437 }
438 defer db.Close()
439
440 _, err = db.Exec("drop table foo")
441 _, err = db.Exec("create table foo (id integer)")
442 if err != nil {
443 t.Fatal("Failed to create table:", err)
444 }
445
446 res, err := db.Exec("insert into foo(id) values(123)")
447 if err != nil {
448 t.Fatal("Failed to insert record:", err)
449 }
450 expected, err := res.LastInsertId()
451 if err != nil {
452 t.Fatal("Failed to get LastInsertId:", err)
453 }
454 affected, _ := res.RowsAffected()
455 if err != nil {
456 t.Fatal("Failed to get RowsAffected:", err)
457 }
458 if affected != 1 {
459 t.Fatalf("Expected %d for affected rows, but %d:", 1, affected)
460 }
461
462 res, err = db.Exec("update foo set id = 234")
463 if err != nil {
464 t.Fatal("Failed to update record:", err)
465 }
466 lastID, err := res.LastInsertId()
467 if err != nil {
468 t.Fatal("Failed to get LastInsertId:", err)
469 }
470 if expected != lastID {
471 t.Errorf("Expected %q for last Id, but %q:", expected, lastID)
472 }
473 affected, _ = res.RowsAffected()
474 if err != nil {
475 t.Fatal("Failed to get RowsAffected:", err)
476 }
477 if affected != 1 {
478 t.Fatalf("Expected %d for affected rows, but %d:", 1, affected)
479 }
480
481 rows, err := db.Query("select id from foo")
482 if err != nil {
483 t.Fatal("Failed to select records:", err)
484 }
485 defer rows.Close()
486
487 rows.Next()
488
489 var result int
490 rows.Scan(&result)
491 if result != 234 {
492 t.Errorf("Expected %d for fetched result, but %d:", 234, result)
493 }
494 }
495
496 func TestDelete(t *testing.T) {
497 tempFilename := TempFilename(t)
498 defer os.Remove(tempFilename)
499 db, err := sql.Open("sqlite3", tempFilename)
500 if err != nil {
501 t.Fatal("Failed to open database:", err)
502 }
503 defer db.Close()
504
505 _, err = db.Exec("drop table foo")
506 _, err = db.Exec("create table foo (id integer)")
507 if err != nil {
508 t.Fatal("Failed to create table:", err)
509 }
510
511 res, err := db.Exec("insert into foo(id) values(123)")
512 if err != nil {
513 t.Fatal("Failed to insert record:", err)
514 }
515 expected, err := res.LastInsertId()
516 if err != nil {
517 t.Fatal("Failed to get LastInsertId:", err)
518 }
519 affected, err := res.RowsAffected()
520 if err != nil {
521 t.Fatal("Failed to get RowsAffected:", err)
522 }
523 if affected != 1 {
524 t.Errorf("Expected %d for cout of affected rows, but %q:", 1, affected)
525 }
526
527 res, err = db.Exec("delete from foo where id = 123")
528 if err != nil {
529 t.Fatal("Failed to delete record:", err)
530 }
531 lastID, err := res.LastInsertId()
532 if err != nil {
533 t.Fatal("Failed to get LastInsertId:", err)
534 }
535 if expected != lastID {
536 t.Errorf("Expected %q for last Id, but %q:", expected, lastID)
537 }
538 affected, err = res.RowsAffected()
539 if err != nil {
540 t.Fatal("Failed to get RowsAffected:", err)
541 }
542 if affected != 1 {
543 t.Errorf("Expected %d for cout of affected rows, but %q:", 1, affected)
544 }
545
546 rows, err := db.Query("select id from foo")
547 if err != nil {
548 t.Fatal("Failed to select records:", err)
549 }
550 defer rows.Close()
551
552 if rows.Next() {
553 t.Error("Fetched row but expected not rows")
554 }
555 }
556
557 func TestBooleanRoundtrip(t *testing.T) {
558 tempFilename := TempFilename(t)
559 defer os.Remove(tempFilename)
560 db, err := sql.Open("sqlite3", tempFilename)
561 if err != nil {
562 t.Fatal("Failed to open database:", err)
563 }
564 defer db.Close()
565
566 _, err = db.Exec("DROP TABLE foo")
567 _, err = db.Exec("CREATE TABLE foo(id INTEGER, value BOOL)")
568 if err != nil {
569 t.Fatal("Failed to create table:", err)
570 }
571
572 _, err = db.Exec("INSERT INTO foo(id, value) VALUES(1, ?)", true)
573 if err != nil {
574 t.Fatal("Failed to insert true value:", err)
575 }
576
577 _, err = db.Exec("INSERT INTO foo(id, value) VALUES(2, ?)", false)
578 if err != nil {
579 t.Fatal("Failed to insert false value:", err)
580 }
581
582 rows, err := db.Query("SELECT id, value FROM foo")
583 if err != nil {
584 t.Fatal("Unable to query foo table:", err)
585 }
586 defer rows.Close()
587
588 for rows.Next() {
589 var id int
590 var value bool
591
592 if err := rows.Scan(&id, &value); err != nil {
593 t.Error("Unable to scan results:", err)
594 continue
595 }
596
597 if id == 1 && !value {
598 t.Error("Value for id 1 should be true, not false")
599
600 } else if id == 2 && value {
601 t.Error("Value for id 2 should be false, not true")
602 }
603 }
604 }
605
606 func timezone(t time.Time) string { return t.Format("-07:00") }
607
608 func TestTimestamp(t *testing.T) {
609 tempFilename := TempFilename(t)
610 defer os.Remove(tempFilename)
611 db, err := sql.Open("sqlite3", tempFilename)
612 if err != nil {
613 t.Fatal("Failed to open database:", err)
614 }
615 defer db.Close()
616
617 _, err = db.Exec("DROP TABLE foo")
618 _, err = db.Exec("CREATE TABLE foo(id INTEGER, ts timeSTAMP, dt DATETIME)")
619 if err != nil {
620 t.Fatal("Failed to create table:", err)
621 }
622
623 timestamp1 := time.Date(2012, time.April, 6, 22, 50, 0, 0, time.UTC)
624 timestamp2 := time.Date(2006, time.January, 2, 15, 4, 5, 123456789, time.UTC)
625 timestamp3 := time.Date(2012, time.November, 4, 0, 0, 0, 0, time.UTC)
626 tzTest := time.FixedZone("TEST", -9*3600-13*60)
627 tests := []struct {
628 value any
629 expected time.Time
630 }{
631 {"nonsense", time.Time{}},
632 {"0000-00-00 00:00:00", time.Time{}},
633 {time.Time{}.Unix(), time.Time{}},
634 {timestamp1, timestamp1},
635 {timestamp2.Unix(), timestamp2.Truncate(time.Second)},
636 {timestamp2.UnixNano() / int64(time.Millisecond), timestamp2.Truncate(time.Millisecond)},
637 {timestamp1.In(tzTest), timestamp1.In(tzTest)},
638 {timestamp1.Format("2006-01-02 15:04:05.000"), timestamp1},
639 {timestamp1.Format("2006-01-02T15:04:05.000"), timestamp1},
640 {timestamp1.Format("2006-01-02 15:04:05"), timestamp1},
641 {timestamp1.Format("2006-01-02T15:04:05"), timestamp1},
642 {timestamp2, timestamp2},
643 {"2006-01-02 15:04:05.123456789", timestamp2},
644 {"2006-01-02T15:04:05.123456789", timestamp2},
645 {"2006-01-02T05:51:05.123456789-09:13", timestamp2.In(tzTest)},
646 {"2012-11-04", timestamp3},
647 {"2012-11-04 00:00", timestamp3},
648 {"2012-11-04 00:00:00", timestamp3},
649 {"2012-11-04 00:00:00.000", timestamp3},
650 {"2012-11-04T00:00", timestamp3},
651 {"2012-11-04T00:00:00", timestamp3},
652 {"2012-11-04T00:00:00.000", timestamp3},
653 {"2006-01-02T15:04:05.123456789Z", timestamp2},
654 {"2012-11-04Z", timestamp3},
655 {"2012-11-04 00:00Z", timestamp3},
656 {"2012-11-04 00:00:00Z", timestamp3},
657 {"2012-11-04 00:00:00.000Z", timestamp3},
658 {"2012-11-04T00:00Z", timestamp3},
659 {"2012-11-04T00:00:00Z", timestamp3},
660 {"2012-11-04T00:00:00.000Z", timestamp3},
661 }
662 for i := range tests {
663 _, err = db.Exec("INSERT INTO foo(id, ts, dt) VALUES(?, ?, ?)", i, tests[i].value, tests[i].value)
664 if err != nil {
665 t.Fatal("Failed to insert timestamp:", err)
666 }
667 }
668
669 rows, err := db.Query("SELECT id, ts, dt FROM foo ORDER BY id ASC")
670 if err != nil {
671 t.Fatal("Unable to query foo table:", err)
672 }
673 defer rows.Close()
674
675 seen := 0
676 for rows.Next() {
677 var id int
678 var ts, dt time.Time
679
680 if err := rows.Scan(&id, &ts, &dt); err != nil {
681 t.Error("Unable to scan results:", err)
682 continue
683 }
684 if id < 0 || id >= len(tests) {
685 t.Error("Bad row id: ", id)
686 continue
687 }
688 seen++
689 if !tests[id].expected.Equal(ts) {
690 t.Errorf("Timestamp value for id %v (%v) should be %v, not %v", id, tests[id].value, tests[id].expected, dt)
691 }
692 if !tests[id].expected.Equal(dt) {
693 t.Errorf("Datetime value for id %v (%v) should be %v, not %v", id, tests[id].value, tests[id].expected, dt)
694 }
695 if timezone(tests[id].expected) != timezone(ts) {
696 t.Errorf("Timezone for id %v (%v) should be %v, not %v", id, tests[id].value,
697 timezone(tests[id].expected), timezone(ts))
698 }
699 if timezone(tests[id].expected) != timezone(dt) {
700 t.Errorf("Timezone for id %v (%v) should be %v, not %v", id, tests[id].value,
701 timezone(tests[id].expected), timezone(dt))
702 }
703 }
704
705 if seen != len(tests) {
706 t.Errorf("Expected to see %d rows", len(tests))
707 }
708 }
709
710 func TestBoolean(t *testing.T) {
711 tempFilename := TempFilename(t)
712 defer os.Remove(tempFilename)
713 db, err := sql.Open("sqlite3", tempFilename)
714 if err != nil {
715 t.Fatal("Failed to open database:", err)
716 }
717
718 defer db.Close()
719
720 _, err = db.Exec("CREATE TABLE foo(id INTEGER, fbool BOOLEAN)")
721 if err != nil {
722 t.Fatal("Failed to create table:", err)
723 }
724
725 bool1 := true
726 _, err = db.Exec("INSERT INTO foo(id, fbool) VALUES(1, ?)", bool1)
727 if err != nil {
728 t.Fatal("Failed to insert boolean:", err)
729 }
730
731 bool2 := false
732 _, err = db.Exec("INSERT INTO foo(id, fbool) VALUES(2, ?)", bool2)
733 if err != nil {
734 t.Fatal("Failed to insert boolean:", err)
735 }
736
737 bool3 := "nonsense"
738 _, err = db.Exec("INSERT INTO foo(id, fbool) VALUES(3, ?)", bool3)
739 if err != nil {
740 t.Fatal("Failed to insert nonsense:", err)
741 }
742
743 rows, err := db.Query("SELECT id, fbool FROM foo where fbool = ?", bool1)
744 if err != nil {
745 t.Fatal("Unable to query foo table:", err)
746 }
747 counter := 0
748
749 var id int
750 var fbool bool
751
752 for rows.Next() {
753 if err := rows.Scan(&id, &fbool); err != nil {
754 t.Fatal("Unable to scan results:", err)
755 }
756 counter++
757 }
758
759 if counter != 1 {
760 t.Fatalf("Expected 1 row but %v", counter)
761 }
762
763 if id != 1 && !fbool {
764 t.Fatalf("Value for id 1 should be %v, not %v", bool1, fbool)
765 }
766
767 rows, err = db.Query("SELECT id, fbool FROM foo where fbool = ?", bool2)
768 if err != nil {
769 t.Fatal("Unable to query foo table:", err)
770 }
771
772 counter = 0
773
774 for rows.Next() {
775 if err := rows.Scan(&id, &fbool); err != nil {
776 t.Fatal("Unable to scan results:", err)
777 }
778 counter++
779 }
780
781 if counter != 1 {
782 t.Fatalf("Expected 1 row but %v", counter)
783 }
784
785 if id != 2 && fbool {
786 t.Fatalf("Value for id 2 should be %v, not %v", bool2, fbool)
787 }
788
789 // make sure "nonsense" triggered an error
790 rows, err = db.Query("SELECT id, fbool FROM foo where id=?;", 3)
791 if err != nil {
792 t.Fatal("Unable to query foo table:", err)
793 }
794
795 rows.Next()
796 err = rows.Scan(&id, &fbool)
797 if err == nil {
798 t.Error("Expected error from \"nonsense\" bool")
799 }
800 }
801
802 func TestFloat32(t *testing.T) {
803 tempFilename := TempFilename(t)
804 defer os.Remove(tempFilename)
805 db, err := sql.Open("sqlite3", tempFilename)
806 if err != nil {
807 t.Fatal("Failed to open database:", err)
808 }
809 defer db.Close()
810
811 _, err = db.Exec("CREATE TABLE foo(id INTEGER)")
812 if err != nil {
813 t.Fatal("Failed to create table:", err)
814 }
815
816 _, err = db.Exec("INSERT INTO foo(id) VALUES(null)")
817 if err != nil {
818 t.Fatal("Failed to insert null:", err)
819 }
820
821 rows, err := db.Query("SELECT id FROM foo")
822 if err != nil {
823 t.Fatal("Unable to query foo table:", err)
824 }
825
826 if !rows.Next() {
827 t.Fatal("Unable to query results:", err)
828 }
829
830 var id any
831 if err := rows.Scan(&id); err != nil {
832 t.Fatal("Unable to scan results:", err)
833 }
834 if id != nil {
835 t.Error("Expected nil but not")
836 }
837 }
838
839 func TestNull(t *testing.T) {
840 tempFilename := TempFilename(t)
841 defer os.Remove(tempFilename)
842 db, err := sql.Open("sqlite3", tempFilename)
843 if err != nil {
844 t.Fatal("Failed to open database:", err)
845 }
846 defer db.Close()
847
848 rows, err := db.Query("SELECT 3.141592")
849 if err != nil {
850 t.Fatal("Unable to query foo table:", err)
851 }
852
853 if !rows.Next() {
854 t.Fatal("Unable to query results:", err)
855 }
856
857 var v any
858 if err := rows.Scan(&v); err != nil {
859 t.Fatal("Unable to scan results:", err)
860 }
861 f, ok := v.(float64)
862 if !ok {
863 t.Error("Expected float but not")
864 }
865 if f != 3.141592 {
866 t.Error("Expected 3.141592 but not")
867 }
868 }
869
870 func TestTransaction(t *testing.T) {
871 tempFilename := TempFilename(t)
872 defer os.Remove(tempFilename)
873 db, err := sql.Open("sqlite3", tempFilename)
874 if err != nil {
875 t.Fatal("Failed to open database:", err)
876 }
877 defer db.Close()
878
879 _, err = db.Exec("CREATE TABLE foo(id INTEGER)")
880 if err != nil {
881 t.Fatal("Failed to create table:", err)
882 }
883
884 tx, err := db.Begin()
885 if err != nil {
886 t.Fatal("Failed to begin transaction:", err)
887 }
888
889 _, err = tx.Exec("INSERT INTO foo(id) VALUES(1)")
890 if err != nil {
891 t.Fatal("Failed to insert null:", err)
892 }
893
894 rows, err := tx.Query("SELECT id from foo")
895 if err != nil {
896 t.Fatal("Unable to query foo table:", err)
897 }
898
899 err = tx.Rollback()
900 if err != nil {
901 t.Fatal("Failed to rollback transaction:", err)
902 }
903
904 if rows.Next() {
905 t.Fatal("Unable to query results:", err)
906 }
907
908 tx, err = db.Begin()
909 if err != nil {
910 t.Fatal("Failed to begin transaction:", err)
911 }
912
913 _, err = tx.Exec("INSERT INTO foo(id) VALUES(1)")
914 if err != nil {
915 t.Fatal("Failed to insert null:", err)
916 }
917
918 err = tx.Commit()
919 if err != nil {
920 t.Fatal("Failed to commit transaction:", err)
921 }
922
923 rows, err = tx.Query("SELECT id from foo")
924 if err == nil {
925 t.Fatal("Expected failure to query")
926 }
927 }
928
929 func TestWAL(t *testing.T) {
930 tempFilename := TempFilename(t)
931 defer os.Remove(tempFilename)
932 db, err := sql.Open("sqlite3", tempFilename)
933 if err != nil {
934 t.Fatal("Failed to open database:", err)
935 }
936 defer db.Close()
937
938 if _, err = db.Exec("PRAGMA journal_mode=WAL;"); err != nil {
939 t.Fatal("Failed to Exec PRAGMA journal_mode:", err)
940 }
941 if _, err = db.Exec("PRAGMA locking_mode=EXCLUSIVE;"); err != nil {
942 t.Fatal("Failed to Exec PRAGMA locking_mode:", err)
943 }
944 if _, err = db.Exec("CREATE TABLE test (id SERIAL, user TEXT NOT NULL, name TEXT NOT NULL);"); err != nil {
945 t.Fatal("Failed to Exec CREATE TABLE:", err)
946 }
947 if _, err = db.Exec("INSERT INTO test (user, name) VALUES ('user','name');"); err != nil {
948 t.Fatal("Failed to Exec INSERT:", err)
949 }
950
951 trans, err := db.Begin()
952 if err != nil {
953 t.Fatal("Failed to Begin:", err)
954 }
955 s, err := trans.Prepare("INSERT INTO test (user, name) VALUES (?, ?);")
956 if err != nil {
957 t.Fatal("Failed to Prepare:", err)
958 }
959
960 var count int
961 if err = trans.QueryRow("SELECT count(user) FROM test;").Scan(&count); err != nil {
962 t.Fatal("Failed to QueryRow:", err)
963 }
964 if _, err = s.Exec("bbbb", "aaaa"); err != nil {
965 t.Fatal("Failed to Exec prepared statement:", err)
966 }
967 if err = s.Close(); err != nil {
968 t.Fatal("Failed to Close prepared statement:", err)
969 }
970 if err = trans.Commit(); err != nil {
971 t.Fatal("Failed to Commit:", err)
972 }
973 }
974
975 func TestTimezoneConversion(t *testing.T) {
976 zones := []string{"UTC", "US/Central", "US/Pacific", "Local"}
977 for _, tz := range zones {
978 tempFilename := TempFilename(t)
979 defer os.Remove(tempFilename)
980 db, err := sql.Open("sqlite3", tempFilename+"?_loc="+url.QueryEscape(tz))
981 if err != nil {
982 t.Fatal("Failed to open database:", err)
983 }
984 defer db.Close()
985
986 _, err = db.Exec("DROP TABLE foo")
987 _, err = db.Exec("CREATE TABLE foo(id INTEGER, ts TIMESTAMP, dt DATETIME)")
988 if err != nil {
989 t.Fatal("Failed to create table:", err)
990 }
991
992 loc, err := time.LoadLocation(tz)
993 if err != nil {
994 t.Fatal("Failed to load location:", err)
995 }
996
997 timestamp1 := time.Date(2012, time.April, 6, 22, 50, 0, 0, time.UTC)
998 timestamp2 := time.Date(2006, time.January, 2, 15, 4, 5, 123456789, time.UTC)
999 timestamp3 := time.Date(2012, time.November, 4, 0, 0, 0, 0, time.UTC)
1000 tests := []struct {
1001 value any
1002 expected time.Time
1003 }{
1004 {"nonsense", time.Time{}.In(loc)},
1005 {"0000-00-00 00:00:00", time.Time{}.In(loc)},
1006 {timestamp1, timestamp1.In(loc)},
1007 {timestamp1.Unix(), timestamp1.In(loc)},
1008 {timestamp1.In(time.FixedZone("TEST", -7*3600)), timestamp1.In(loc)},
1009 {timestamp1.Format("2006-01-02 15:04:05.000"), timestamp1.In(loc)},
1010 {timestamp1.Format("2006-01-02T15:04:05.000"), timestamp1.In(loc)},
1011 {timestamp1.Format("2006-01-02 15:04:05"), timestamp1.In(loc)},
1012 {timestamp1.Format("2006-01-02T15:04:05"), timestamp1.In(loc)},
1013 {timestamp2, timestamp2.In(loc)},
1014 {"2006-01-02 15:04:05.123456789", timestamp2.In(loc)},
1015 {"2006-01-02T15:04:05.123456789", timestamp2.In(loc)},
1016 {"2012-11-04", timestamp3.In(loc)},
1017 {"2012-11-04 00:00", timestamp3.In(loc)},
1018 {"2012-11-04 00:00:00", timestamp3.In(loc)},
1019 {"2012-11-04 00:00:00.000", timestamp3.In(loc)},
1020 {"2012-11-04T00:00", timestamp3.In(loc)},
1021 {"2012-11-04T00:00:00", timestamp3.In(loc)},
1022 {"2012-11-04T00:00:00.000", timestamp3.In(loc)},
1023 }
1024 for i := range tests {
1025 _, err = db.Exec("INSERT INTO foo(id, ts, dt) VALUES(?, ?, ?)", i, tests[i].value, tests[i].value)
1026 if err != nil {
1027 t.Fatal("Failed to insert timestamp:", err)
1028 }
1029 }
1030
1031 rows, err := db.Query("SELECT id, ts, dt FROM foo ORDER BY id ASC")
1032 if err != nil {
1033 t.Fatal("Unable to query foo table:", err)
1034 }
1035 defer rows.Close()
1036
1037 seen := 0
1038 for rows.Next() {
1039 var id int
1040 var ts, dt time.Time
1041
1042 if err := rows.Scan(&id, &ts, &dt); err != nil {
1043 t.Error("Unable to scan results:", err)
1044 continue
1045 }
1046 if id < 0 || id >= len(tests) {
1047 t.Error("Bad row id: ", id)
1048 continue
1049 }
1050 seen++
1051 if !tests[id].expected.Equal(ts) {
1052 t.Errorf("Timestamp value for id %v (%v) should be %v, not %v", id, tests[id].value, tests[id].expected, ts)
1053 }
1054 if !tests[id].expected.Equal(dt) {
1055 t.Errorf("Datetime value for id %v (%v) should be %v, not %v", id, tests[id].value, tests[id].expected, dt)
1056 }
1057 if tests[id].expected.Location().String() != ts.Location().String() {
1058 t.Errorf("Location for id %v (%v) should be %v, not %v", id, tests[id].value, tests[id].expected.Location().String(), ts.Location().String())
1059 }
1060 if tests[id].expected.Location().String() != dt.Location().String() {
1061 t.Errorf("Location for id %v (%v) should be %v, not %v", id, tests[id].value, tests[id].expected.Location().String(), dt.Location().String())
1062 }
1063 }
1064
1065 if seen != len(tests) {
1066 t.Errorf("Expected to see %d rows", len(tests))
1067 }
1068 }
1069 }
1070
1071 // TODO: Execer & Queryer currently disabled
1072 // https://github.com/mattn/go-sqlite3/issues/82
1073 func TestExecer(t *testing.T) {
1074 tempFilename := TempFilename(t)
1075 defer os.Remove(tempFilename)
1076 db, err := sql.Open("sqlite3", tempFilename)
1077 if err != nil {
1078 t.Fatal("Failed to open database:", err)
1079 }
1080 defer db.Close()
1081
1082 _, err = db.Exec(`
1083 create table foo (id integer); -- one comment
1084 insert into foo(id) values(?);
1085 insert into foo(id) values(?);
1086 insert into foo(id) values(?); -- another comment
1087 `, 1, 2, 3)
1088 if err != nil {
1089 t.Error("Failed to call db.Exec:", err)
1090 }
1091 }
1092
1093 func TestQueryer(t *testing.T) {
1094 tempFilename := TempFilename(t)
1095 defer os.Remove(tempFilename)
1096 db, err := sql.Open("sqlite3", tempFilename)
1097 if err != nil {
1098 t.Fatal("Failed to open database:", err)
1099 }
1100 defer db.Close()
1101
1102 _, err = db.Exec(`
1103 create table foo (id integer);
1104 `)
1105 if err != nil {
1106 t.Error("Failed to call db.Query:", err)
1107 }
1108
1109 _, err = db.Exec(`
1110 insert into foo(id) values(?);
1111 insert into foo(id) values(?);
1112 insert into foo(id) values(?);
1113 `, 3, 2, 1)
1114 if err != nil {
1115 t.Error("Failed to call db.Exec:", err)
1116 }
1117 rows, err := db.Query(`
1118 select id from foo order by id;
1119 `)
1120 if err != nil {
1121 t.Error("Failed to call db.Query:", err)
1122 }
1123 defer rows.Close()
1124 n := 0
1125 for rows.Next() {
1126 var id int
1127 err = rows.Scan(&id)
1128 if err != nil {
1129 t.Error("Failed to db.Query:", err)
1130 }
1131 if id != n+1 {
1132 t.Error("Failed to db.Query: not matched results")
1133 }
1134 n = n + 1
1135 }
1136 if err := rows.Err(); err != nil {
1137 t.Errorf("Post-scan failed: %v\n", err)
1138 }
1139 if n != 3 {
1140 t.Errorf("Expected 3 rows but retrieved %v", n)
1141 }
1142 }
1143
1144 func TestStress(t *testing.T) {
1145 tempFilename := TempFilename(t)
1146 defer os.Remove(tempFilename)
1147 db, err := sql.Open("sqlite3", tempFilename)
1148 if err != nil {
1149 t.Fatal("Failed to open database:", err)
1150 }
1151 db.Exec("CREATE TABLE foo (id int);")
1152 db.Exec("INSERT INTO foo VALUES(1);")
1153 db.Exec("INSERT INTO foo VALUES(2);")
1154 db.Close()
1155
1156 for i := 0; i < 10000; i++ {
1157 db, err := sql.Open("sqlite3", tempFilename)
1158 if err != nil {
1159 t.Fatal("Failed to open database:", err)
1160 }
1161
1162 for j := 0; j < 3; j++ {
1163 rows, err := db.Query("select * from foo where id=1;")
1164 if err != nil {
1165 t.Error("Failed to call db.Query:", err)
1166 }
1167 for rows.Next() {
1168 var i int
1169 if err := rows.Scan(&i); err != nil {
1170 t.Errorf("Scan failed: %v\n", err)
1171 }
1172 }
1173 if err := rows.Err(); err != nil {
1174 t.Errorf("Post-scan failed: %v\n", err)
1175 }
1176 rows.Close()
1177 }
1178 db.Close()
1179 }
1180 }
1181
1182 func TestDateTimeLocal(t *testing.T) {
1183 zone := "Asia/Tokyo"
1184 tempFilename := TempFilename(t)
1185 defer os.Remove(tempFilename)
1186 db, err := sql.Open("sqlite3", tempFilename+"?_loc="+zone)
1187 if err != nil {
1188 t.Fatal("Failed to open database:", err)
1189 }
1190 db.Exec("CREATE TABLE foo (dt datetime);")
1191 db.Exec("INSERT INTO foo VALUES('2015-03-05 15:16:17');")
1192
1193 row := db.QueryRow("select * from foo")
1194 var d time.Time
1195 err = row.Scan(&d)
1196 if err != nil {
1197 t.Fatal("Failed to scan datetime:", err)
1198 }
1199 if d.Hour() == 15 || !strings.Contains(d.String(), "JST") {
1200 t.Fatal("Result should have timezone", d)
1201 }
1202 db.Close()
1203
1204 db, err = sql.Open("sqlite3", tempFilename)
1205 if err != nil {
1206 t.Fatal("Failed to open database:", err)
1207 }
1208
1209 row = db.QueryRow("select * from foo")
1210 err = row.Scan(&d)
1211 if err != nil {
1212 t.Fatal("Failed to scan datetime:", err)
1213 }
1214 if d.UTC().Hour() != 15 || !strings.Contains(d.String(), "UTC") {
1215 t.Fatalf("Result should not have timezone %v %v", zone, d.String())
1216 }
1217
1218 _, err = db.Exec("DELETE FROM foo")
1219 if err != nil {
1220 t.Fatal("Failed to delete table:", err)
1221 }
1222 dt, err := time.Parse("2006/1/2 15/4/5 -0700 MST", "2015/3/5 15/16/17 +0900 JST")
1223 if err != nil {
1224 t.Fatal("Failed to parse datetime:", err)
1225 }
1226 db.Exec("INSERT INTO foo VALUES(?);", dt)
1227
1228 db.Close()
1229 db, err = sql.Open("sqlite3", tempFilename+"?_loc="+zone)
1230 if err != nil {
1231 t.Fatal("Failed to open database:", err)
1232 }
1233
1234 row = db.QueryRow("select * from foo")
1235 err = row.Scan(&d)
1236 if err != nil {
1237 t.Fatal("Failed to scan datetime:", err)
1238 }
1239 if d.Hour() != 15 || !strings.Contains(d.String(), "JST") {
1240 t.Fatalf("Result should have timezone %v %v", zone, d.String())
1241 }
1242 }
1243
1244 func TestVersion(t *testing.T) {
1245 s, n, id := Version()
1246 if s == "" || n == 0 || id == "" {
1247 t.Errorf("Version failed %q, %d, %q\n", s, n, id)
1248 }
1249 }
1250
1251 func TestStringContainingZero(t *testing.T) {
1252 tempFilename := TempFilename(t)
1253 defer os.Remove(tempFilename)
1254 db, err := sql.Open("sqlite3", tempFilename)
1255 if err != nil {
1256 t.Fatal("Failed to open database:", err)
1257 }
1258 defer db.Close()
1259
1260 _, err = db.Exec(`
1261 create table foo (id integer, name, extra text);
1262 `)
1263 if err != nil {
1264 t.Error("Failed to call db.Query:", err)
1265 }
1266
1267 const text = "foo\x00bar"
1268
1269 _, err = db.Exec(`insert into foo(id, name, extra) values($1, $2, $2)`, 1, text)
1270 if err != nil {
1271 t.Error("Failed to call db.Exec:", err)
1272 }
1273
1274 row := db.QueryRow(`select id, extra from foo where id = $1 and extra = $2`, 1, text)
1275 if row == nil {
1276 t.Error("Failed to call db.QueryRow")
1277 }
1278
1279 var id int
1280 var extra string
1281 err = row.Scan(&id, &extra)
1282 if err != nil {
1283 t.Error("Failed to db.Scan:", err)
1284 }
1285 if id != 1 || extra != text {
1286 t.Error("Failed to db.QueryRow: not matched results")
1287 }
1288 }
1289
1290 const CurrentTimeStamp = "2006-01-02 15:04:05"
1291
1292 type TimeStamp struct{ *time.Time }
1293
1294 func (t TimeStamp) Scan(value any) error {
1295 var err error
1296 switch v := value.(type) {
1297 case string:
1298 *t.Time, err = time.Parse(CurrentTimeStamp, v)
1299 case []byte:
1300 *t.Time, err = time.Parse(CurrentTimeStamp, string(v))
1301 default:
1302 err = errors.New("invalid type for current_timestamp")
1303 }
1304 return err
1305 }
1306
1307 func (t TimeStamp) Value() (driver.Value, error) {
1308 return t.Time.Format(CurrentTimeStamp), nil
1309 }
1310
1311 func TestDateTimeNow(t *testing.T) {
1312 tempFilename := TempFilename(t)
1313 defer os.Remove(tempFilename)
1314 db, err := sql.Open("sqlite3", tempFilename)
1315 if err != nil {
1316 t.Fatal("Failed to open database:", err)
1317 }
1318 defer db.Close()
1319
1320 var d time.Time
1321 err = db.QueryRow("SELECT datetime('now')").Scan(TimeStamp{&d})
1322 if err != nil {
1323 t.Fatal("Failed to scan datetime:", err)
1324 }
1325 }
1326
1327 func TestBindErrorPaths(t *testing.T) {
1328 d := &SQLiteDriver{}
1329 conn, err := d.Open(":memory:")
1330 if err != nil {
1331 t.Fatal("Failed to open database:", err)
1332 }
1333 defer conn.Close()
1334 c := conn.(*SQLiteConn)
1335
1336 if _, err := c.Exec("CREATE TABLE t (v)", nil); err != nil {
1337 t.Fatal("Failed to create table:", err)
1338 }
1339
1340 // An unsupported Go type must report an explicit error instead of
1341 // silently binding NULL: positional parameter.
1342 _, err = c.Exec("INSERT INTO t VALUES (?)", []driver.Value{int32(1)})
1343 if err == nil || !strings.Contains(err.Error(), "unsupported bind type int32") {
1344 t.Errorf("positional bind of unsupported type: got %v, want unsupported bind type error", err)
1345 }
1346
1347 // The same for a named parameter.
1348 stmt, err := c.Prepare("INSERT INTO t VALUES (:x)")
1349 if err != nil {
1350 t.Fatal("Failed to prepare:", err)
1351 }
1352 err = stmt.(*SQLiteStmt).bind([]driver.NamedValue{{Name: "x", Ordinal: 1, Value: int32(1)}})
1353 if err == nil || !strings.Contains(err.Error(), "unsupported bind type int32") {
1354 t.Errorf("named bind of unsupported type: got %v, want unsupported bind type error", err)
1355 }
1356 stmt.Close()
1357
1358 // A genuine SQLite bind failure must preserve the recorded error.
1359 stmt, err = c.Prepare("INSERT INTO t VALUES (?)")
1360 if err != nil {
1361 t.Fatal("Failed to prepare:", err)
1362 }
1363 err = stmt.(*SQLiteStmt).bind([]driver.NamedValue{{Ordinal: 2, Value: int64(1)}})
1364 var serr Error
1365 if !errors.As(err, &serr) || serr.Code != ErrRange {
1366 t.Errorf("out-of-range bind: got %v, want SQLITE_RANGE error", err)
1367 }
1368 stmt.Close()
1369 }
1370
1371 func TestFunctionRegistration(t *testing.T) {
1372 addi8_16_32 := func(a int8, b int16) int32 { return int32(a) + int32(b) }
1373 addi64 := func(a, b int64) int64 { return a + b }
1374 addu8_16_32 := func(a uint8, b uint16) uint32 { return uint32(a) + uint32(b) }
1375 addu64 := func(a, b uint64) uint64 { return a + b }
1376 addiu := func(a int, b uint) int64 { return int64(a) + int64(b) }
1377 addf32_64 := func(a float32, b float64) float64 { return float64(a) + b }
1378 not := func(a bool) bool { return !a }
1379 regex := func(re, s string) (bool, error) {
1380 return regexp.MatchString(re, s)
1381 }
1382 generic := func(a any) int64 {
1383 switch a.(type) {
1384 case int64:
1385 return 1
1386 case float64:
1387 return 2
1388 case []byte:
1389 return 3
1390 case string:
1391 return 4
1392 default:
1393 panic("unreachable")
1394 }
1395 }
1396 variadic := func(a, b int64, c ...int64) int64 {
1397 ret := a + b
1398 for _, d := range c {
1399 ret += d
1400 }
1401 return ret
1402 }
1403 variadicGeneric := func(a ...any) int64 {
1404 return int64(len(a))
1405 }
1406
1407 sql.Register("sqlite3_FunctionRegistration", &SQLiteDriver{
1408 ConnectHook: func(conn *SQLiteConn) error {
1409 if err := conn.RegisterFunc("addi8_16_32", addi8_16_32, true); err != nil {
1410 return err
1411 }
1412 if err := conn.RegisterFunc("addi64", addi64, true); err != nil {
1413 return err
1414 }
1415 if err := conn.RegisterFunc("addu8_16_32", addu8_16_32, true); err != nil {
1416 return err
1417 }
1418 if err := conn.RegisterFunc("addu64", addu64, true); err != nil {
1419 return err
1420 }
1421 if err := conn.RegisterFunc("addiu", addiu, true); err != nil {
1422 return err
1423 }
1424 if err := conn.RegisterFunc("addf32_64", addf32_64, true); err != nil {
1425 return err
1426 }
1427 if err := conn.RegisterFunc("not", not, true); err != nil {
1428 return err
1429 }
1430 if err := conn.RegisterFunc("regex", regex, true); err != nil {
1431 return err
1432 }
1433 if err := conn.RegisterFunc("generic", generic, true); err != nil {
1434 return err
1435 }
1436 if err := conn.RegisterFunc("variadic", variadic, true); err != nil {
1437 return err
1438 }
1439 if err := conn.RegisterFunc("variadicGeneric", variadicGeneric, true); err != nil {
1440 return err
1441 }
1442 return nil
1443 },
1444 })
1445 db, err := sql.Open("sqlite3_FunctionRegistration", ":memory:")
1446 if err != nil {
1447 t.Fatal("Failed to open database:", err)
1448 }
1449 defer db.Close()
1450
1451 ops := []struct {
1452 query string
1453 expected any
1454 }{
1455 {"SELECT addi8_16_32(1,2)", int32(3)},
1456 {"SELECT addi64(1,2)", int64(3)},
1457 {"SELECT addu8_16_32(1,2)", uint32(3)},
1458 {"SELECT addu64(1,2)", uint64(3)},
1459 {"SELECT addiu(1,2)", int64(3)},
1460 {"SELECT addf32_64(1.5,1.5)", float64(3)},
1461 {"SELECT not(1)", false},
1462 {"SELECT not(0)", true},
1463 {`SELECT regex('^foo.*', 'foobar')`, true},
1464 {`SELECT regex('^foo.*', 'barfoobar')`, false},
1465 {"SELECT generic(1)", int64(1)},
1466 {"SELECT generic(1.1)", int64(2)},
1467 {`SELECT generic(NULL)`, int64(3)},
1468 {`SELECT generic('foo')`, int64(4)},
1469 {"SELECT variadic(1,2)", int64(3)},
1470 {"SELECT variadic(1,2,3,4)", int64(10)},
1471 {"SELECT variadic(1,1,1,1,1,1,1,1,1,1)", int64(10)},
1472 {`SELECT variadicGeneric(1,'foo',2.3, NULL)`, int64(4)},
1473 }
1474
1475 for _, op := range ops {
1476 ret := reflect.New(reflect.TypeOf(op.expected))
1477 err = db.QueryRow(op.query).Scan(ret.Interface())
1478 if err != nil {
1479 t.Errorf("Query %q failed: %s", op.query, err)
1480 } else if !reflect.DeepEqual(ret.Elem().Interface(), op.expected) {
1481 t.Errorf("Query %q returned wrong value: got %v (%T), want %v (%T)", op.query, ret.Elem().Interface(), ret.Elem().Interface(), op.expected, op.expected)
1482 }
1483 }
1484 }
1485
1486 func TestFunctionRegistrationNamedTypes(t *testing.T) {
1487 type NInt int64
1488 type NFloat float64
1489 type NString string
1490 type NBlob []byte
1491 type NBool bool
1492
1493 dur := func(n int64) time.Duration { return time.Duration(n) }
1494 nint := func(a, b NInt) NInt { return a + b }
1495 nfloat := func(a, b NFloat) NFloat { return a + b }
1496 nstring := func(s NString) NString { return s + "!" }
1497 nblob := func(s string) NBlob { return NBlob(s) }
1498 nbool := func(b NBool) NBool { return !b }
1499
1500 sql.Register("sqlite3_FunctionRegistrationNamedTypes", &SQLiteDriver{
1501 ConnectHook: func(conn *SQLiteConn) error {
1502 if err := conn.RegisterFunc("dur", dur, true); err != nil {
1503 return err
1504 }
1505 if err := conn.RegisterFunc("nint", nint, true); err != nil {
1506 return err
1507 }
1508 if err := conn.RegisterFunc("nfloat", nfloat, true); err != nil {
1509 return err
1510 }
1511 if err := conn.RegisterFunc("nstring", nstring, true); err != nil {
1512 return err
1513 }
1514 if err := conn.RegisterFunc("nblob", nblob, true); err != nil {
1515 return err
1516 }
1517 return conn.RegisterFunc("nbool", nbool, true)
1518 },
1519 })
1520 db, err := sql.Open("sqlite3_FunctionRegistrationNamedTypes", ":memory:")
1521 if err != nil {
1522 t.Fatal("Failed to open database:", err)
1523 }
1524 defer db.Close()
1525
1526 ops := []struct {
1527 query string
1528 expected any
1529 }{
1530 {"SELECT dur(42)", int64(42)},
1531 {"SELECT nint(1,2)", int64(3)},
1532 {"SELECT nfloat(1.5,1.5)", float64(3)},
1533 {`SELECT nstring('foo')`, "foo!"},
1534 {`SELECT nblob('xy')`, []byte("xy")},
1535 // An empty blob result is mapped to SQL NULL.
1536 {`SELECT nblob('') IS NULL`, true},
1537 {"SELECT nbool(0)", true},
1538 }
1539
1540 for _, op := range ops {
1541 ret := reflect.New(reflect.TypeOf(op.expected))
1542 err = db.QueryRow(op.query).Scan(ret.Interface())
1543 if err != nil {
1544 t.Errorf("Query %q failed: %s", op.query, err)
1545 } else if !reflect.DeepEqual(ret.Elem().Interface(), op.expected) {
1546 t.Errorf("Query %q returned wrong value: got %v (%T), want %v (%T)", op.query, ret.Elem().Interface(), ret.Elem().Interface(), op.expected, op.expected)
1547 }
1548 }
1549 }
1550
1551 func TestFunctionArgStringContainingZero(t *testing.T) {
1552 sql.Register("sqlite3_FunctionArgZero", &SQLiteDriver{
1553 ConnectHook: func(conn *SQLiteConn) error {
1554 // arglen reports how many bytes of the text argument reached the
1555 // Go side; echo returns the string result verbatim.
1556 if err := conn.RegisterFunc("arglen", func(s string) int64 { return int64(len(s)) }, true); err != nil {
1557 return err
1558 }
1559 return conn.RegisterFunc("echo", func(s string) string { return s }, true)
1560 },
1561 })
1562 db, err := sql.Open("sqlite3_FunctionArgZero", ":memory:")
1563 if err != nil {
1564 t.Fatal("Failed to open database:", err)
1565 }
1566 defer db.Close()
1567
1568 const text = "foo\x00bar"
1569
1570 var n int64
1571 if err := db.QueryRow("SELECT arglen(?)", text).Scan(&n); err != nil {
1572 t.Fatal("Failed to call db.QueryRow:", err)
1573 }
1574 if n != int64(len(text)) {
1575 t.Errorf("text argument truncated at embedded NUL: got len %d, want %d", n, len(text))
1576 }
1577
1578 var got string
1579 if err := db.QueryRow("SELECT echo(?)", text).Scan(&got); err != nil {
1580 t.Fatal("Failed to call db.QueryRow:", err)
1581 }
1582 if got != text {
1583 t.Errorf("text result truncated at embedded NUL: got %q (len %d), want %q (len %d)", got, len(got), text, len(text))
1584 }
1585 }
1586
1587 type sumAggregator int64
1588
1589 func (s *sumAggregator) Step(x int64) {
1590 *s += sumAggregator(x)
1591 }
1592
1593 func (s *sumAggregator) Done() int64 {
1594 return int64(*s)
1595 }
1596
1597 func TestAggregatorRegistration(t *testing.T) {
1598 customSum := func() *sumAggregator {
1599 var ret sumAggregator
1600 return &ret
1601 }
1602
1603 sql.Register("sqlite3_AggregatorRegistration", &SQLiteDriver{
1604 ConnectHook: func(conn *SQLiteConn) error {
1605 return conn.RegisterAggregator("customSum", customSum, true)
1606 },
1607 })
1608 db, err := sql.Open("sqlite3_AggregatorRegistration", ":memory:")
1609 if err != nil {
1610 t.Fatal("Failed to open database:", err)
1611 }
1612 defer db.Close()
1613
1614 _, err = db.Exec("create table foo (department integer, profits integer)")
1615 if err != nil {
1616 // trace feature is not implemented
1617 t.Skip("Failed to create table:", err)
1618 }
1619
1620 _, err = db.Exec("insert into foo values (1, 10), (1, 20), (2, 42)")
1621 if err != nil {
1622 t.Fatal("Failed to insert records:", err)
1623 }
1624
1625 tests := []struct {
1626 dept, sum int64
1627 }{
1628 {1, 30},
1629 {2, 42},
1630 }
1631
1632 for _, test := range tests {
1633 var ret int64
1634 err = db.QueryRow("select customSum(profits) from foo where department = $1 group by department", test.dept).Scan(&ret)
1635 if err != nil {
1636 t.Fatal("Query failed:", err)
1637 }
1638 if ret != test.sum {
1639 t.Fatalf("Custom sum returned wrong value, got %d, want %d", ret, test.sum)
1640 }
1641 }
1642 }
1643
1644 type mode struct {
1645 counts map[any]int
1646 top any
1647 topCount int
1648 }
1649
1650 func newMode() *mode {
1651 return &mode{
1652 counts: map[any]int{},
1653 }
1654 }
1655
1656 func (m *mode) Step(x any) {
1657 m.counts[x]++
1658 c := m.counts[x]
1659 if c > m.topCount {
1660 m.top = x
1661 m.topCount = c
1662 }
1663 }
1664
1665 func (m *mode) Done() any {
1666 return m.top
1667 }
1668
1669 func TestAggregatorRegistration_GenericReturn(t *testing.T) {
1670 sql.Register("sqlite3_AggregatorRegistration_GenericReturn", &SQLiteDriver{
1671 ConnectHook: func(conn *SQLiteConn) error {
1672 return conn.RegisterAggregator("mode", newMode, true)
1673 },
1674 })
1675 db, err := sql.Open("sqlite3_AggregatorRegistration_GenericReturn", ":memory:")
1676 if err != nil {
1677 t.Fatal("Failed to open database:", err)
1678 }
1679 defer db.Close()
1680
1681 _, err = db.Exec("create table foo (department integer, profits integer)")
1682 if err != nil {
1683 t.Fatal("Failed to create table:", err)
1684 }
1685 _, err = db.Exec("insert into foo values (1, 10), (1, 20), (1, 45), (2, 42), (2, 115), (2, 20)")
1686 if err != nil {
1687 t.Fatal("Failed to insert records:", err)
1688 }
1689
1690 var mode int
1691 err = db.QueryRow("select mode(profits) from foo").Scan(&mode)
1692 if err != nil {
1693 t.Fatal("MODE query error:", err)
1694 }
1695
1696 if mode != 20 {
1697 t.Fatal("Got incorrect mode. Wanted 20, got: ", mode)
1698 }
1699 }
1700
1701 func rot13(r rune) rune {
1702 switch {
1703 case r >= 'A' && r <= 'Z':
1704 return 'A' + (r-'A'+13)%26
1705 case r >= 'a' && r <= 'z':
1706 return 'a' + (r-'a'+13)%26
1707 }
1708 return r
1709 }
1710
1711 func TestCollationRegistration(t *testing.T) {
1712 collateRot13 := func(a, b string) int {
1713 ra, rb := strings.Map(rot13, a), strings.Map(rot13, b)
1714 return strings.Compare(ra, rb)
1715 }
1716 collateRot13Reverse := func(a, b string) int {
1717 return collateRot13(b, a)
1718 }
1719
1720 sql.Register("sqlite3_CollationRegistration", &SQLiteDriver{
1721 ConnectHook: func(conn *SQLiteConn) error {
1722 if err := conn.RegisterCollation("rot13", collateRot13); err != nil {
1723 return err
1724 }
1725 if err := conn.RegisterCollation("rot13reverse", collateRot13Reverse); err != nil {
1726 return err
1727 }
1728 return nil
1729 },
1730 })
1731
1732 db, err := sql.Open("sqlite3_CollationRegistration", ":memory:")
1733 if err != nil {
1734 t.Fatal("Failed to open database:", err)
1735 }
1736 defer db.Close()
1737
1738 populate := []string{
1739 `CREATE TABLE test (s TEXT)`,
1740 `INSERT INTO test VALUES ('aaaa')`,
1741 `INSERT INTO test VALUES ('ffff')`,
1742 `INSERT INTO test VALUES ('qqqq')`,
1743 `INSERT INTO test VALUES ('tttt')`,
1744 `INSERT INTO test VALUES ('zzzz')`,
1745 }
1746 for _, stmt := range populate {
1747 if _, err := db.Exec(stmt); err != nil {
1748 t.Fatal("Failed to populate test DB:", err)
1749 }
1750 }
1751
1752 ops := []struct {
1753 query string
1754 want []string
1755 }{
1756 {
1757 "SELECT * FROM test ORDER BY s COLLATE rot13 ASC",
1758 []string{
1759 "qqqq",
1760 "tttt",
1761 "zzzz",
1762 "aaaa",
1763 "ffff",
1764 },
1765 },
1766 {
1767 "SELECT * FROM test ORDER BY s COLLATE rot13 DESC",
1768 []string{
1769 "ffff",
1770 "aaaa",
1771 "zzzz",
1772 "tttt",
1773 "qqqq",
1774 },
1775 },
1776 {
1777 "SELECT * FROM test ORDER BY s COLLATE rot13reverse ASC",
1778 []string{
1779 "ffff",
1780 "aaaa",
1781 "zzzz",
1782 "tttt",
1783 "qqqq",
1784 },
1785 },
1786 {
1787 "SELECT * FROM test ORDER BY s COLLATE rot13reverse DESC",
1788 []string{
1789 "qqqq",
1790 "tttt",
1791 "zzzz",
1792 "aaaa",
1793 "ffff",
1794 },
1795 },
1796 }
1797
1798 for _, op := range ops {
1799 rows, err := db.Query(op.query)
1800 if err != nil {
1801 t.Fatalf("Query %q failed: %s", op.query, err)
1802 }
1803 got := []string{}
1804 defer rows.Close()
1805 for rows.Next() {
1806 var s string
1807 if err = rows.Scan(&s); err != nil {
1808 t.Fatalf("Reading row for %q: %s", op.query, err)
1809 }
1810 got = append(got, s)
1811 }
1812 if err = rows.Err(); err != nil {
1813 t.Fatalf("Reading rows for %q: %s", op.query, err)
1814 }
1815
1816 if !reflect.DeepEqual(got, op.want) {
1817 t.Fatalf("Unexpected output from %q\ngot:\n%s\n\nwant:\n%s", op.query, strings.Join(got, "\n"), strings.Join(op.want, "\n"))
1818 }
1819 }
1820 }
1821
1822 func TestDeclTypes(t *testing.T) {
1823
1824 d := SQLiteDriver{}
1825
1826 conn, err := d.Open(":memory:")
1827 if err != nil {
1828 t.Fatal("Failed to begin transaction:", err)
1829 }
1830 defer conn.Close()
1831
1832 sqlite3conn := conn.(*SQLiteConn)
1833
1834 _, err = sqlite3conn.Exec("create table foo (id integer not null primary key, name text)", nil)
1835 if err != nil {
1836 t.Fatal("Failed to create table:", err)
1837 }
1838
1839 _, err = sqlite3conn.Exec("insert into foo(name) values('bar')", nil)
1840 if err != nil {
1841 t.Fatal("Failed to insert:", err)
1842 }
1843
1844 rs, err := sqlite3conn.Query("select * from foo", nil)
1845 if err != nil {
1846 t.Fatal("Failed to select:", err)
1847 }
1848 defer rs.Close()
1849
1850 declTypes := rs.(*SQLiteRows).DeclTypes()
1851
1852 if !reflect.DeepEqual(declTypes, []string{"integer", "text"}) {
1853 t.Fatal("Unexpected declTypes:", declTypes)
1854 }
1855 }
1856
1857 func TestPinger(t *testing.T) {
1858 db, err := sql.Open("sqlite3", ":memory:")
1859 if err != nil {
1860 t.Fatal(err)
1861 }
1862 err = db.Ping()
1863 if err != nil {
1864 t.Fatal(err)
1865 }
1866 db.Close()
1867 err = db.Ping()
1868 if err == nil {
1869 t.Fatal("Should be closed")
1870 }
1871 }
1872
1873 func TestUpdateAndTransactionHooks(t *testing.T) {
1874 var events []string
1875 var commitHookReturn = 0
1876
1877 sql.Register("sqlite3_UpdateHook", &SQLiteDriver{
1878 ConnectHook: func(conn *SQLiteConn) error {
1879 conn.RegisterCommitHook(func() int {
1880 events = append(events, "commit")
1881 return commitHookReturn
1882 })
1883 conn.RegisterRollbackHook(func() {
1884 events = append(events, "rollback")
1885 })
1886 conn.RegisterUpdateHook(func(op int, db string, table string, rowid int64) {
1887 events = append(events, fmt.Sprintf("update(op=%v db=%v table=%v rowid=%v)", op, db, table, rowid))
1888 })
1889 return nil
1890 },
1891 })
1892 db, err := sql.Open("sqlite3_UpdateHook", ":memory:")
1893 if err != nil {
1894 t.Fatal("Failed to open database:", err)
1895 }
1896 defer db.Close()
1897
1898 statements := []string{
1899 "create table foo (id integer primary key)",
1900 "insert into foo values (9)",
1901 "update foo set id = 99 where id = 9",
1902 "delete from foo where id = 99",
1903 }
1904 for _, statement := range statements {
1905 _, err = db.Exec(statement)
1906 if err != nil {
1907 t.Fatalf("Unable to prepare test data [%v]: %v", statement, err)
1908 }
1909 }
1910
1911 commitHookReturn = 1
1912 _, err = db.Exec("insert into foo values (5)")
1913 if err == nil {
1914 t.Error("Commit hook failed to rollback transaction")
1915 }
1916
1917 var expected = []string{
1918 "commit",
1919 fmt.Sprintf("update(op=%v db=main table=foo rowid=9)", SQLITE_INSERT),
1920 "commit",
1921 fmt.Sprintf("update(op=%v db=main table=foo rowid=99)", SQLITE_UPDATE),
1922 "commit",
1923 fmt.Sprintf("update(op=%v db=main table=foo rowid=99)", SQLITE_DELETE),
1924 "commit",
1925 fmt.Sprintf("update(op=%v db=main table=foo rowid=5)", SQLITE_INSERT),
1926 "commit",
1927 "rollback",
1928 }
1929 if !reflect.DeepEqual(events, expected) {
1930 t.Errorf("Expected notifications %v but got %v", expected, events)
1931 }
1932 }
1933
1934 func TestAuthorizer(t *testing.T) {
1935 var authorizerReturn = 0
1936
1937 sql.Register("sqlite3_Authorizer", &SQLiteDriver{
1938 ConnectHook: func(conn *SQLiteConn) error {
1939 conn.RegisterAuthorizer(func(op int, arg1, arg2, arg3 string) int {
1940 return authorizerReturn
1941 })
1942 return nil
1943 },
1944 })
1945 db, err := sql.Open("sqlite3_Authorizer", ":memory:")
1946 if err != nil {
1947 t.Fatal("Failed to open database:", err)
1948 }
1949 defer db.Close()
1950
1951 statements := []string{
1952 "create table foo (id integer primary key, name varchar)",
1953 "insert into foo values (9, 'test9')",
1954 "update foo set name = 'test99' where id = 9",
1955 "select * from foo",
1956 }
1957
1958 authorizerReturn = SQLITE_OK
1959 for _, statement := range statements {
1960 _, err = db.Exec(statement)
1961 if err != nil {
1962 t.Fatalf("No error expected [%v]: %v", statement, err)
1963 }
1964 }
1965
1966 authorizerReturn = SQLITE_DENY
1967 for _, statement := range statements {
1968 _, err = db.Exec(statement)
1969 if err == nil {
1970 t.Fatalf("Authorizer didn't worked - nil received, but error expected: [%v]", statement)
1971 }
1972 }
1973 }
1974
1975 func TestSetFileControlInt(t *testing.T) {
1976 t.Run("PERSIST_WAL", func(t *testing.T) {
1977 tempFilename := TempFilename(t)
1978 defer os.Remove(tempFilename)
1979
1980 sql.Register("sqlite3_FCNTL_PERSIST_WAL", &SQLiteDriver{
1981 ConnectHook: func(conn *SQLiteConn) error {
1982 if err := conn.SetFileControlInt("", SQLITE_FCNTL_PERSIST_WAL, 1); err != nil {
1983 return fmt.Errorf("Unexpected error from SetFileControlInt(): %w", err)
1984 }
1985 return nil
1986 },
1987 })
1988
1989 db, err := sql.Open("sqlite3_FCNTL_PERSIST_WAL", tempFilename)
1990 if err != nil {
1991 t.Fatal("Failed to open database:", err)
1992 }
1993 defer db.Close()
1994
1995 // Set to WAL mode & write a page.
1996 if _, err := db.Exec(`PRAGMA journal_mode = wal`); err != nil {
1997 t.Fatal("Failed to set journal mode:", err)
1998 } else if _, err := db.Exec(`CREATE TABLE t (x)`); err != nil {
1999 t.Fatal("Failed to create table:", err)
2000 }
2001 if err := db.Close(); err != nil {
2002 t.Fatal("Failed to close database", err)
2003 }
2004
2005 // Ensure WAL file persists after close.
2006 if _, err := os.Stat(tempFilename + "-wal"); err != nil {
2007 t.Fatal("Expected WAL file to be persisted after close", err)
2008 }
2009 })
2010 }
2011
2012 func TestSetFileControlInt64(t *testing.T) {
2013 const GiB = 1024 * 1024 * 1024
2014
2015 t.Run("", func(t *testing.T) {
2016
2017 sql.Register("sqlite3_FCNTL_SIZE_LIMIT", &SQLiteDriver{
2018 ConnectHook: func(conn *SQLiteConn) error {
2019 if err := conn.SetFileControlInt64("", SQLITE_FCNTL_SIZE_LIMIT, 4*GiB); err != nil {
2020 return fmt.Errorf("Unexpected error from SetFileControlInt64(): %w", err)
2021 }
2022 return nil
2023 },
2024 })
2025
2026 db, err := sql.Open("sqlite3", "file:/dbname?vfs=memdb")
2027 if err != nil {
2028 t.Fatal("Failed to open database:", err)
2029 }
2030 err = db.Ping()
2031 if err != nil {
2032 t.Fatal("Failed to ping", err)
2033 }
2034 db.Close()
2035 })
2036 }
2037
2038 func TestNonColumnString(t *testing.T) {
2039 db, err := sql.Open("sqlite3", ":memory:")
2040 if err != nil {
2041 t.Fatal(err)
2042 }
2043 defer db.Close()
2044
2045 var x any
2046 if err := db.QueryRow("SELECT 'hello'").Scan(&x); err != nil {
2047 t.Fatal(err)
2048 }
2049 s, ok := x.(string)
2050 if !ok {
2051 t.Fatalf("non-column string must return string but got %T", x)
2052 }
2053 if s != "hello" {
2054 t.Fatalf("non-column string must return %q but got %q", "hello", s)
2055 }
2056 }
2057
2058 func TestNilAndEmptyBytes(t *testing.T) {
2059 db, err := sql.Open("sqlite3", ":memory:")
2060 if err != nil {
2061 t.Fatal(err)
2062 }
2063 defer db.Close()
2064 actualNil := []byte("use this to use an actual nil not a reference to nil")
2065 emptyBytes := []byte{}
2066 for tsti, tst := range []struct {
2067 name string
2068 columnType string
2069 insertBytes []byte
2070 expectedBytes []byte
2071 }{
2072 {"actual nil blob", "blob", actualNil, nil},
2073 {"referenced nil blob", "blob", nil, nil},
2074 {"empty blob", "blob", emptyBytes, emptyBytes},
2075 {"actual nil text", "text", actualNil, nil},
2076 {"referenced nil text", "text", nil, nil},
2077 {"empty text", "text", emptyBytes, emptyBytes},
2078 } {
2079 if _, err = db.Exec(fmt.Sprintf("create table tbl%d (txt %s)", tsti, tst.columnType)); err != nil {
2080 t.Fatal(tst.name, err)
2081 }
2082 if bytes.Equal(tst.insertBytes, actualNil) {
2083 if _, err = db.Exec(fmt.Sprintf("insert into tbl%d (txt) values (?)", tsti), nil); err != nil {
2084 t.Fatal(tst.name, err)
2085 }
2086 } else {
2087 if _, err = db.Exec(fmt.Sprintf("insert into tbl%d (txt) values (?)", tsti), &tst.insertBytes); err != nil {
2088 t.Fatal(tst.name, err)
2089 }
2090 }
2091 rows, err := db.Query(fmt.Sprintf("select txt from tbl%d", tsti))
2092 if err != nil {
2093 t.Fatal(tst.name, err)
2094 }
2095 if !rows.Next() {
2096 t.Fatal(tst.name, "no rows")
2097 }
2098 var scanBytes []byte
2099 if err = rows.Scan(&scanBytes); err != nil {
2100 t.Fatal(tst.name, err)
2101 }
2102 if err = rows.Err(); err != nil {
2103 t.Fatal(tst.name, err)
2104 }
2105 if tst.expectedBytes == nil && scanBytes != nil {
2106 t.Errorf("%s: %#v != %#v", tst.name, scanBytes, tst.expectedBytes)
2107 } else if !bytes.Equal(scanBytes, tst.expectedBytes) {
2108 t.Errorf("%s: %#v != %#v", tst.name, scanBytes, tst.expectedBytes)
2109 }
2110 }
2111 }
2112
2113 func TestInsertNilByteSlice(t *testing.T) {
2114 db, err := sql.Open("sqlite3", ":memory:")
2115 if err != nil {
2116 t.Fatal(err)
2117 }
2118 defer db.Close()
2119 if _, err := db.Exec("create table blob_not_null (b blob not null)"); err != nil {
2120 t.Fatal(err)
2121 }
2122 var nilSlice []byte
2123 if _, err := db.Exec("insert into blob_not_null (b) values (?)", nilSlice); err == nil {
2124 t.Fatal("didn't expect INSERT to 'not null' column with a nil []byte slice to work")
2125 }
2126 zeroLenSlice := []byte{}
2127 if _, err := db.Exec("insert into blob_not_null (b) values (?)", zeroLenSlice); err != nil {
2128 t.Fatal("failed to insert zero-length slice")
2129 }
2130 }
2131
2132 func TestNamedParam(t *testing.T) {
2133 tempFilename := TempFilename(t)
2134 defer os.Remove(tempFilename)
2135 db, err := sql.Open("sqlite3", tempFilename)
2136 if err != nil {
2137 t.Fatal("Failed to open database:", err)
2138 }
2139 defer db.Close()
2140
2141 _, err = db.Exec("drop table foo")
2142 _, err = db.Exec("create table foo (id integer, name text, amount integer)")
2143 if err != nil {
2144 t.Fatal("Failed to create table:", err)
2145 }
2146
2147 _, err = db.Exec("insert into foo(id, name, amount) values(:id, @name, $amount)",
2148 sql.Named("bar", 42), sql.Named("baz", "quux"),
2149 sql.Named("amount", 123), sql.Named("corge", "waldo"),
2150 sql.Named("id", 2), sql.Named("name", "grault"))
2151 if err != nil {
2152 t.Fatal("Failed to insert record with named parameters:", err)
2153 }
2154
2155 rows, err := db.Query("select id, name, amount from foo")
2156 if err != nil {
2157 t.Fatal("Failed to select records:", err)
2158 }
2159 defer rows.Close()
2160
2161 rows.Next()
2162
2163 var id, amount int
2164 var name string
2165 rows.Scan(&id, &name, &amount)
2166 if id != 2 || name != "grault" || amount != 123 {
2167 t.Errorf("Expected %d, %q, %d for fetched result, but got %d, %q, %d:", 2, "grault", 123, id, name, amount)
2168 }
2169 }
2170
2171 func TestNamedParamClearBindings(t *testing.T) {
2172 tempFilename := TempFilename(t)
2173 defer os.Remove(tempFilename)
2174 db, err := sql.Open("sqlite3", tempFilename)
2175 if err != nil {
2176 t.Fatal("Failed to open database:", err)
2177 }
2178 defer db.Close()
2179
2180 _, err = db.Exec("create table foo (x integer, y integer, z text)")
2181 if err != nil {
2182 t.Fatal("Failed to create table:", err)
2183 }
2184
2185 // First insert with all named params specified
2186 _, err = db.Exec("insert into foo(x, y, z) values($x, $y, $z)",
2187 sql.Named("x", 1), sql.Named("y", 2), sql.Named("z", "three"))
2188 if err != nil {
2189 t.Fatal("Failed to insert:", err)
2190 }
2191
2192 // Second insert: $y should be NULL since we pass nil explicitly
2193 _, err = db.Exec("insert into foo(x, y, z) values($x, $y, $z)",
2194 sql.Named("x", 10), sql.Named("y", nil), sql.Named("z", nil))
2195 if err != nil {
2196 t.Fatal("Failed to insert:", err)
2197 }
2198
2199 var x int
2200 var y, z sql.NullInt64
2201 err = db.QueryRow("select x, y, z from foo where x = 10").Scan(&x, &y, &z)
2202 if err != nil {
2203 t.Fatal("Failed to query:", err)
2204 }
2205 if y.Valid {
2206 t.Errorf("Expected y to be NULL, got %d", y.Int64)
2207 }
2208 if z.Valid {
2209 t.Errorf("Expected z to be NULL, got %d", z.Int64)
2210 }
2211 }
2212
2213 // https://github.com/mattn/go-sqlite3/issues/1390
2214 // sqlite3_prepare_v2 returns SQLITE_OK with a NULL statement handle when the
2215 // input contains no SQL (only whitespace or comments). Querying such input
2216 // must not panic.
2217 func TestQueryCommentOnly(t *testing.T) {
2218 db, err := sql.Open("sqlite3", ":memory:")
2219 if err != nil {
2220 t.Fatal(err)
2221 }
2222 defer db.Close()
2223
2224 cases := []string{"", " ", "-- comment", "---- comment\n", "/* block */"}
2225 for _, q := range cases {
2226 var x int
2227 if err := db.QueryRow(q).Scan(&x); err != sql.ErrNoRows {
2228 t.Errorf("QueryRow(%q): expected ErrNoRows, got %v", q, err)
2229 }
2230
2231 rows, err := db.Query(q)
2232 if err != nil {
2233 t.Errorf("Query(%q): unexpected error: %v", q, err)
2234 continue
2235 }
2236 if rows.Next() {
2237 t.Errorf("Query(%q): expected no rows", q)
2238 }
2239 rows.Close()
2240
2241 if _, err := db.Exec(q); err != nil {
2242 t.Errorf("Exec(%q): unexpected error: %v", q, err)
2243 }
2244 }
2245 }
2246
2247 var customFunctionOnce sync.Once
2248
2249 func BenchmarkCustomFunctions(b *testing.B) {
2250 customFunctionOnce.Do(func() {
2251 customAdd := func(a, b int64) int64 {
2252 return a + b
2253 }
2254
2255 sql.Register("sqlite3_BenchmarkCustomFunctions", &SQLiteDriver{
2256 ConnectHook: func(conn *SQLiteConn) error {
2257 // Impure function to force sqlite to reexecute it each time.
2258 return conn.RegisterFunc("custom_add", customAdd, false)
2259 },
2260 })
2261 })
2262
2263 db, err := sql.Open("sqlite3_BenchmarkCustomFunctions", ":memory:")
2264 if err != nil {
2265 b.Fatal("Failed to open database:", err)
2266 }
2267 defer db.Close()
2268
2269 b.ResetTimer()
2270 for i := 0; i < b.N; i++ {
2271 var i int64
2272 err = db.QueryRow("SELECT custom_add(1,2)").Scan(&i)
2273 if err != nil {
2274 b.Fatal("Failed to run custom add:", err)
2275 }
2276 }
2277 }
2278
2279 func TestSuite(t *testing.T) {
2280 initializeTestDB(t)
2281 defer freeTestDB()
2282
2283 for _, test := range tests {
2284 t.Run(test.Name, test.F)
2285 }
2286 }
2287
2288 func BenchmarkSuite(b *testing.B) {
2289 initializeTestDB(b)
2290 defer freeTestDB()
2291
2292 for _, benchmark := range benchmarks {
2293 b.Run(benchmark.Name, benchmark.F)
2294 }
2295 }
2296
2297 // Dialect is a type of dialect of databases.
2298 type Dialect int
2299
2300 // Dialects for databases.
2301 const (
2302 SQLITE Dialect = iota // SQLITE mean SQLite3 dialect
2303 POSTGRESQL // POSTGRESQL mean PostgreSQL dialect
2304 MYSQL // MYSQL mean MySQL dialect
2305 )
2306
2307 // DB provide context for the tests
2308 type TestDB struct {
2309 testing.TB
2310 *sql.DB
2311 dialect Dialect
2312 once sync.Once
2313 tempFilename string
2314 }
2315
2316 var db *TestDB
2317
2318 func initializeTestDB(t testing.TB) {
2319 tempFilename := TempFilename(t)
2320 d, err := sql.Open("sqlite3", tempFilename+"?_busy_timeout=99999")
2321 if err != nil {
2322 os.Remove(tempFilename)
2323 t.Fatal(err)
2324 }
2325
2326 db = &TestDB{t, d, SQLITE, sync.Once{}, tempFilename}
2327 }
2328
2329 func freeTestDB() {
2330 err := db.DB.Close()
2331 if err != nil {
2332 panic(err)
2333 }
2334 err = os.Remove(db.tempFilename)
2335 if err != nil {
2336 panic(err)
2337 }
2338 }
2339
2340 // the following tables will be created and dropped during the test
2341 var testTables = []string{"foo", "bar", "t", "bench"}
2342
2343 var tests = []testing.InternalTest{
2344 {Name: "TestResult", F: testResult},
2345 {Name: "TestBlobs", F: testBlobs},
2346 {Name: "TestMultiBlobs", F: testMultiBlobs},
2347 {Name: "TestNullZeroLengthBlobs", F: testNullZeroLengthBlobs},
2348 {Name: "TestManyQueryRow", F: testManyQueryRow},
2349 {Name: "TestTxQuery", F: testTxQuery},
2350 {Name: "TestPreparedStmt", F: testPreparedStmt},
2351 {Name: "TestExecEmptyQuery", F: testExecEmptyQuery},
2352 }
2353
2354 var benchmarks = []testing.InternalBenchmark{
2355 {Name: "BenchmarkExec", F: benchmarkExec},
2356 {Name: "BenchmarkQuery", F: benchmarkQuery},
2357 {Name: "BenchmarkParams", F: benchmarkParams},
2358 {Name: "BenchmarkStmt", F: benchmarkStmt},
2359 {Name: "BenchmarkRows", F: benchmarkRows},
2360 {Name: "BenchmarkStmtRows", F: benchmarkStmtRows},
2361 {Name: "BenchmarkQueryParallel", F: benchmarkQueryParallel},
2362 }
2363
2364 func (db *TestDB) mustExec(sql string, args ...any) sql.Result {
2365 res, err := db.Exec(sql, args...)
2366 if err != nil {
2367 db.Fatalf("Error running %q: %v", sql, err)
2368 }
2369 return res
2370 }
2371
2372 func (db *TestDB) tearDown() {
2373 for _, tbl := range testTables {
2374 switch db.dialect {
2375 case SQLITE:
2376 db.mustExec("drop table if exists " + tbl)
2377 case MYSQL, POSTGRESQL:
2378 db.mustExec("drop table if exists " + tbl)
2379 default:
2380 db.Fatal("unknown dialect")
2381 }
2382 }
2383 }
2384
2385 // q replaces ? parameters if needed
2386 func (db *TestDB) q(sql string) string {
2387 switch db.dialect {
2388 case POSTGRESQL: // replace with $1, $2, ..
2389 qrx := regexp.MustCompile(`\?`)
2390 n := 0
2391 return qrx.ReplaceAllStringFunc(sql, func(string) string {
2392 n++
2393 return "$" + strconv.Itoa(n)
2394 })
2395 }
2396 return sql
2397 }
2398
2399 func (db *TestDB) blobType(size int) string {
2400 switch db.dialect {
2401 case SQLITE:
2402 return fmt.Sprintf("blob[%d]", size)
2403 case POSTGRESQL:
2404 return "bytea"
2405 case MYSQL:
2406 return fmt.Sprintf("VARBINARY(%d)", size)
2407 }
2408 panic("unknown dialect")
2409 }
2410
2411 func (db *TestDB) serialPK() string {
2412 switch db.dialect {
2413 case SQLITE:
2414 return "integer primary key autoincrement"
2415 case POSTGRESQL:
2416 return "serial primary key"
2417 case MYSQL:
2418 return "integer primary key auto_increment"
2419 }
2420 panic("unknown dialect")
2421 }
2422
2423 func (db *TestDB) now() string {
2424 switch db.dialect {
2425 case SQLITE:
2426 return "datetime('now')"
2427 case POSTGRESQL:
2428 return "now()"
2429 case MYSQL:
2430 return "now()"
2431 }
2432 panic("unknown dialect")
2433 }
2434
2435 func makeBench() {
2436 if _, err := db.Exec("create table bench (n varchar(32), i integer, d double, s varchar(32), t datetime)"); err != nil {
2437 panic(err)
2438 }
2439 st, err := db.Prepare("insert into bench values (?, ?, ?, ?, ?)")
2440 if err != nil {
2441 panic(err)
2442 }
2443 defer st.Close()
2444 for i := 0; i < 100; i++ {
2445 if _, err = st.Exec(nil, i, float64(i), fmt.Sprintf("%d", i), time.Now()); err != nil {
2446 panic(err)
2447 }
2448 }
2449 }
2450
2451 // testResult is test for result
2452 func testResult(t *testing.T) {
2453 db.tearDown()
2454 db.mustExec("create temporary table test (id " + db.serialPK() + ", name varchar(10))")
2455
2456 for i := 1; i < 3; i++ {
2457 r := db.mustExec(db.q("insert into test (name) values (?)"), fmt.Sprintf("row %d", i))
2458 n, err := r.RowsAffected()
2459 if err != nil {
2460 t.Fatal(err)
2461 }
2462 if n != 1 {
2463 t.Errorf("got %v, want %v", n, 1)
2464 }
2465 n, err = r.LastInsertId()
2466 if err != nil {
2467 t.Fatal(err)
2468 }
2469 if n != int64(i) {
2470 t.Errorf("got %v, want %v", n, i)
2471 }
2472 }
2473 if _, err := db.Exec("error!"); err == nil {
2474 t.Fatalf("expected error")
2475 }
2476 }
2477
2478 // testBlobs is test for blobs
2479 func testBlobs(t *testing.T) {
2480 db.tearDown()
2481 var blob = []byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}
2482 db.mustExec("create table foo (id integer primary key, bar " + db.blobType(16) + ")")
2483 db.mustExec(db.q("insert into foo (id, bar) values(?,?)"), 0, blob)
2484
2485 want := fmt.Sprintf("%x", blob)
2486
2487 b := make([]byte, 16)
2488 err := db.QueryRow(db.q("select bar from foo where id = ?"), 0).Scan(&b)
2489 got := fmt.Sprintf("%x", b)
2490 if err != nil {
2491 t.Errorf("[]byte scan: %v", err)
2492 } else if got != want {
2493 t.Errorf("for []byte, got %q; want %q", got, want)
2494 }
2495
2496 err = db.QueryRow(db.q("select bar from foo where id = ?"), 0).Scan(&got)
2497 want = string(blob)
2498 if err != nil {
2499 t.Errorf("string scan: %v", err)
2500 } else if got != want {
2501 t.Errorf("for string, got %q; want %q", got, want)
2502 }
2503 }
2504
2505 func testMultiBlobs(t *testing.T) {
2506 db.tearDown()
2507 db.mustExec("create table foo (id integer primary key, bar " + db.blobType(16) + ")")
2508 var blob0 = []byte{0, 1, 2, 3, 4, 5, 6, 7}
2509 db.mustExec(db.q("insert into foo (id, bar) values(?,?)"), 0, blob0)
2510 var blob1 = []byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}
2511 db.mustExec(db.q("insert into foo (id, bar) values(?,?)"), 1, blob1)
2512
2513 r, err := db.Query(db.q("select bar from foo order by id"))
2514 if err != nil {
2515 t.Fatal(err)
2516 }
2517 defer r.Close()
2518 if !r.Next() {
2519 if r.Err() != nil {
2520 t.Fatal(err)
2521 }
2522 t.Fatal("expected one rows")
2523 }
2524
2525 want0 := fmt.Sprintf("%x", blob0)
2526 b0 := make([]byte, 8)
2527 err = r.Scan(&b0)
2528 if err != nil {
2529 t.Fatal(err)
2530 }
2531 got0 := fmt.Sprintf("%x", b0)
2532
2533 if !r.Next() {
2534 if r.Err() != nil {
2535 t.Fatal(err)
2536 }
2537 t.Fatal("expected one rows")
2538 }
2539
2540 want1 := fmt.Sprintf("%x", blob1)
2541 b1 := make([]byte, 16)
2542 err = r.Scan(&b1)
2543 if err != nil {
2544 t.Fatal(err)
2545 }
2546 got1 := fmt.Sprintf("%x", b1)
2547 if got0 != want0 {
2548 t.Errorf("for []byte, got %q; want %q", got0, want0)
2549 }
2550 if got1 != want1 {
2551 t.Errorf("for []byte, got %q; want %q", got1, want1)
2552 }
2553 }
2554
2555 // testBlobs tests that we distinguish between null and zero-length blobs
2556 func testNullZeroLengthBlobs(t *testing.T) {
2557 db.tearDown()
2558 db.mustExec("create table foo (id integer primary key, bar " + db.blobType(16) + ")")
2559 db.mustExec(db.q("insert into foo (id, bar) values(?,?)"), 0, nil)
2560 db.mustExec(db.q("insert into foo (id, bar) values(?,?)"), 1, []byte{})
2561
2562 r0 := db.QueryRow(db.q("select bar from foo where id=0"))
2563 var b0 []byte
2564 err := r0.Scan(&b0)
2565 if err != nil {
2566 t.Fatal(err)
2567 }
2568 if b0 != nil {
2569 t.Errorf("for id=0, got %x; want nil", b0)
2570 }
2571
2572 r1 := db.QueryRow(db.q("select bar from foo where id=1"))
2573 var b1 []byte
2574 err = r1.Scan(&b1)
2575 if err != nil {
2576 t.Fatal(err)
2577 }
2578 if b1 == nil {
2579 t.Error("for id=1, got nil; want zero-length slice")
2580 } else if len(b1) > 0 {
2581 t.Errorf("for id=1, got %x; want zero-length slice", b1)
2582 }
2583 }
2584
2585 // testManyQueryRow is test for many query row
2586 func testManyQueryRow(t *testing.T) {
2587 if testing.Short() {
2588 t.Log("skipping in short mode")
2589 return
2590 }
2591 db.tearDown()
2592 db.mustExec("create table foo (id integer primary key, name varchar(50))")
2593 db.mustExec(db.q("insert into foo (id, name) values(?,?)"), 1, "bob")
2594 var name string
2595 for i := 0; i < 10000; i++ {
2596 err := db.QueryRow(db.q("select name from foo where id = ?"), 1).Scan(&name)
2597 if err != nil || name != "bob" {
2598 t.Fatalf("on query %d: err=%v, name=%q", i, err, name)
2599 }
2600 }
2601 }
2602
2603 // testTxQuery is test for transactional query
2604 func testTxQuery(t *testing.T) {
2605 db.tearDown()
2606 tx, err := db.Begin()
2607 if err != nil {
2608 t.Fatal(err)
2609 }
2610 defer tx.Rollback()
2611
2612 _, err = tx.Exec("create table foo (id integer primary key, name varchar(50))")
2613 if err != nil {
2614 t.Fatal(err)
2615 }
2616
2617 _, err = tx.Exec(db.q("insert into foo (id, name) values(?,?)"), 1, "bob")
2618 if err != nil {
2619 t.Fatal(err)
2620 }
2621
2622 r, err := tx.Query(db.q("select name from foo where id = ?"), 1)
2623 if err != nil {
2624 t.Fatal(err)
2625 }
2626 defer r.Close()
2627
2628 if !r.Next() {
2629 if r.Err() != nil {
2630 t.Fatal(err)
2631 }
2632 t.Fatal("expected one rows")
2633 }
2634
2635 var name string
2636 err = r.Scan(&name)
2637 if err != nil {
2638 t.Fatal(err)
2639 }
2640 }
2641
2642 // testPreparedStmt is test for prepared statement
2643 func testPreparedStmt(t *testing.T) {
2644 db.tearDown()
2645 db.mustExec("CREATE TABLE t (count INT)")
2646 sel, err := db.Prepare("SELECT count FROM t ORDER BY count DESC")
2647 if err != nil {
2648 t.Fatalf("prepare 1: %v", err)
2649 }
2650 ins, err := db.Prepare(db.q("INSERT INTO t (count) VALUES (?)"))
2651 if err != nil {
2652 t.Fatalf("prepare 2: %v", err)
2653 }
2654
2655 for n := 1; n <= 3; n++ {
2656 if _, err := ins.Exec(n); err != nil {
2657 t.Fatalf("insert(%d) = %v", n, err)
2658 }
2659 }
2660
2661 const nRuns = 10
2662 var wg sync.WaitGroup
2663 for i := 0; i < nRuns; i++ {
2664 wg.Add(1)
2665 go func() {
2666 defer wg.Done()
2667 for j := 0; j < 10; j++ {
2668 count := 0
2669 if err := sel.QueryRow().Scan(&count); err != nil && err != sql.ErrNoRows {
2670 t.Errorf("Query: %v", err)
2671 return
2672 }
2673 if _, err := ins.Exec(rand.Intn(100)); err != nil {
2674 t.Errorf("Insert: %v", err)
2675 return
2676 }
2677 }
2678 }()
2679 }
2680 wg.Wait()
2681 }
2682
2683 // testEmptyQuery is test for validating the API in case of empty query
2684 func testExecEmptyQuery(t *testing.T) {
2685 db.tearDown()
2686 res, err := db.Exec(" -- this is just a comment ")
2687 if err != nil {
2688 t.Fatalf("empty query err: %v", err)
2689 }
2690
2691 _, err = res.LastInsertId()
2692 if err != nil {
2693 t.Fatalf("LastInsertId returned an error: %v", err)
2694 }
2695
2696 _, err = res.RowsAffected()
2697 if err != nil {
2698 t.Fatalf("RowsAffected returned an error: %v", err)
2699 }
2700 }
2701
2702 // Benchmarks need to use panic() since b.Error errors are lost when
2703 // running via testing.Benchmark() I would like to run these via go
2704 // test -bench but calling Benchmark() from a benchmark test
2705 // currently hangs go.
2706
2707 // benchmarkExec is benchmark for exec
2708 func benchmarkExec(b *testing.B) {
2709 for i := 0; i < b.N; i++ {
2710 if _, err := db.Exec("select 1"); err != nil {
2711 panic(err)
2712 }
2713 }
2714 }
2715
2716 // benchmarkQuery is benchmark for query
2717 func benchmarkQuery(b *testing.B) {
2718 for i := 0; i < b.N; i++ {
2719 var n sql.NullString
2720 var i int
2721 var f float64
2722 var s string
2723 // var t time.Time
2724 if err := db.QueryRow("select null, 1, 1.1, 'foo'").Scan(&n, &i, &f, &s); err != nil {
2725 panic(err)
2726 }
2727 }
2728 }
2729
2730 // benchmarkParams is benchmark for params
2731 func benchmarkParams(b *testing.B) {
2732 for i := 0; i < b.N; i++ {
2733 var n sql.NullString
2734 var i int
2735 var f float64
2736 var s string
2737 // var t time.Time
2738 if err := db.QueryRow("select ?, ?, ?, ?", nil, 1, 1.1, "foo").Scan(&n, &i, &f, &s); err != nil {
2739 panic(err)
2740 }
2741 }
2742 }
2743
2744 // benchmarkStmt is benchmark for statement
2745 func benchmarkStmt(b *testing.B) {
2746 st, err := db.Prepare("select ?, ?, ?, ?")
2747 if err != nil {
2748 panic(err)
2749 }
2750 defer st.Close()
2751
2752 for n := 0; n < b.N; n++ {
2753 var n sql.NullString
2754 var i int
2755 var f float64
2756 var s string
2757 // var t time.Time
2758 if err := st.QueryRow(nil, 1, 1.1, "foo").Scan(&n, &i, &f, &s); err != nil {
2759 panic(err)
2760 }
2761 }
2762 }
2763
2764 // benchmarkRows is benchmark for rows
2765 func benchmarkRows(b *testing.B) {
2766 db.once.Do(makeBench)
2767
2768 for n := 0; n < b.N; n++ {
2769 var n sql.NullString
2770 var i int
2771 var f float64
2772 var s string
2773 var t time.Time
2774 r, err := db.Query("select * from bench")
2775 if err != nil {
2776 panic(err)
2777 }
2778 for r.Next() {
2779 if err = r.Scan(&n, &i, &f, &s, &t); err != nil {
2780 panic(err)
2781 }
2782 }
2783 if err = r.Err(); err != nil {
2784 panic(err)
2785 }
2786 }
2787 }
2788
2789 // benchmarkStmtRows is benchmark for statement rows
2790 func benchmarkStmtRows(b *testing.B) {
2791 db.once.Do(makeBench)
2792
2793 st, err := db.Prepare("select * from bench")
2794 if err != nil {
2795 panic(err)
2796 }
2797 defer st.Close()
2798
2799 for n := 0; n < b.N; n++ {
2800 var n sql.NullString
2801 var i int
2802 var f float64
2803 var s string
2804 var t time.Time
2805 r, err := st.Query()
2806 if err != nil {
2807 panic(err)
2808 }
2809 for r.Next() {
2810 if err = r.Scan(&n, &i, &f, &s, &t); err != nil {
2811 panic(err)
2812 }
2813 }
2814 if err = r.Err(); err != nil {
2815 panic(err)
2816 }
2817 }
2818 }
2819
2820 func benchmarkQueryParallel(b *testing.B) {
2821 b.RunParallel(func(pb *testing.PB) {
2822 db, err := sql.Open("sqlite3", ":memory:")
2823 if err != nil {
2824 panic(err)
2825 }
2826 db.SetMaxOpenConns(runtime.NumCPU())
2827 defer db.Close()
2828 var i int64
2829 for pb.Next() {
2830 if err := db.QueryRow("SELECT 1, 2, 3, 4").Scan(&i, &i, &i, &i); err != nil {
2831 panic(err)
2832 }
2833 }
2834 })
2835 }