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