Repository navigation
Expand file tree
/
Copy pathfault_test.go
More file actions
735 lines (710 loc) · 23.8 KB
/
Copy pathfault_test.go
File metadata and controls
735 lines (710 loc) · 23.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
// Copyright (c) 2026 The liustack/sqlite Authors.
// SPDX-License-Identifier: MIT
// Use of this source code is governed by the MIT license in LICENSE at the
// root of this repository.
//go:build ((linux || darwin) && (amd64 || arm64)) || (windows && (amd64 || arm64))
package sqlite
import (
"context"
"database/sql"
"database/sql/driver"
"errors"
"fmt"
"slices"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/liustack/sqlite/internal/csqlite"
"github.com/liustack/sqlite/internal/vfs"
)
// failOp has the n-th op on a file whose name ends with suffix fail with
// rc, once, for the rest of the test.
func failOp(t *testing.T, suffix string, op vfs.Op, n int64, rc int) *atomic.Int64 {
var seen, failed atomic.Int64
vfs.SetFault(func(path string, o vfs.Op) int {
if o == op && strings.HasSuffix(path, suffix) && seen.Add(1) == n {
failed.Add(1)
return rc
}
return vfs.OK
})
t.Cleanup(func() { vfs.SetFault(nil) })
return &failed
}
// Merged inserts while one write or sync of the WAL or the database fails:
// every caller told its insert committed finds its row, now and after the
// database is opened again, and the file stays sound.
func TestMergeDiskFails(t *testing.T) {
for _, tc := range []struct {
name, suffix string
op vfs.Op
n int64
rc int
}{
{"wal sync", "-wal", vfs.OpSync, 20, vfs.IOErrFsync},
{"wal write", "-wal", vfs.OpWrite, 20, vfs.IOErrWrite},
{"db sync", ".db", vfs.OpSync, 2, vfs.IOErrFsync},
{"db write", ".db", vfs.OpWrite, 20, vfs.IOErrWrite},
} {
t.Run(tc.name, func(t *testing.T) { mergeDiskFails(t, tc.suffix, tc.op, tc.n, tc.rc) })
}
}
func mergeDiskFails(t *testing.T, suffix string, op vfs.Op, n int64, rc int) {
path := mPath(t)
dsn := "file:" + path + "?_pragma=journal_mode(WAL)&_pragma=synchronous(FULL)&_pragma=wal_autocheckpoint(100)"
db := mOpen(t, dsn)
db.SetMaxOpenConns(32)
db.SetMaxIdleConns(32)
mExec(t, db, `CREATE TABLE t(k TEXT PRIMARY KEY)`)
failed := failOp(t, suffix, op, n, rc)
var (
wg sync.WaitGroup
mu sync.Mutex
ok = map[string]bool{}
errs = map[string]error{}
)
for g := range 32 {
wg.Go(func() {
for i := range 50 {
k := fmt.Sprintf("g%d-%d", g, i)
_, err := db.Exec(`INSERT INTO t VALUES (?)`, k)
mu.Lock()
if err == nil {
ok[k] = true
} else {
errs[k] = err
}
mu.Unlock()
}
})
}
wg.Wait()
vfs.SetFault(nil)
if failed.Load() != 1 {
t.Fatalf("%d syncs failed, want 1", failed.Load())
}
check := func(db interface {
Query(string, ...any) (*sql.Rows, error)
}, when string) {
t.Helper()
have := map[string]bool{}
rows, err := db.Query(`SELECT k FROM t`)
if err != nil {
t.Fatalf("%s: %v", when, err)
}
for rows.Next() {
var k string
rows.Scan(&k)
have[k] = true
}
if err := rows.Err(); err != nil {
t.Fatalf("%s: %v", when, err)
}
lost, ghost := 0, 0
for k := range ok {
if !have[k] {
lost++
}
}
for k := range errs {
if have[k] {
ghost++
}
}
kinds := map[string]int{}
for _, err := range errs {
kinds[err.Error()]++
}
t.Logf("%s: %d committed, %d failed %v, %d rows, %d told committed but missing, %d told failed but present", when, len(ok), len(errs), kinds, len(have), lost, ghost)
if lost > 0 {
t.Errorf("%s: %d rows told committed are missing", when, lost)
}
}
check(db, "after the failure")
db.Close()
db2 := mOpen(t, dsn)
check(db2, "opened again")
var ic string
if err := db2.QueryRow(`PRAGMA integrity_check`).Scan(&ic); err != nil || ic != "ok" {
t.Fatalf("integrity_check: %q %v", ic, err)
}
}
// setControlFault makes execCached fail as f says for the rest of the test.
func setControlFault(t *testing.T, f func(c *conn, sql string) error) {
controlFault = f
t.Cleanup(func() { controlFault = nil })
}
// twoConns opens two connections of one connector on a new database.
func twoConns(t *testing.T) (*conn, *conn) {
t.Helper()
cn, err := NewConnector("file:" + mPath(t) + "?_pragma=journal_mode(WAL)")
if err != nil {
t.Fatal(err)
}
var cs [2]*conn
for i := range cs {
dc, err := cn.Connect(context.Background())
if err != nil {
t.Fatal(err)
}
cs[i] = dc.(*conn)
t.Cleanup(func() { cs[i].Close() })
}
return cs[0], cs[1]
}
var errNoMem = csqlite.NewError(NOMEM, "out of memory", nil)
// failRollback has RELEASE merge and ROLLBACK fail, as they would when the
// connection cannot prepare them: the transaction of the batch stays open.
func failRollback(_ *conn, sql string) error {
if sql == "RELEASE merge" || sql == "ROLLBACK" {
return errNoMem
}
return nil
}
// A batch whose transaction will not roll back keeps the lock on its
// connection, and the requests it did not get to wait in the queue. Closing
// the connection rolls the transaction back, and only then does the lock go
// on.
func TestBatchRollbackFails(t *testing.T) {
c, other := twoConns(t)
mustExec(t, c, `CREATE TABLE t(x)`)
a, b := batchReq(`INSERT INTO t VALUES (1)`), batchReq(`INSERT INTO t VALUES (2)`)
a.key, b.key = c.key, c.key
wl := c.wl
wl.mu.Lock()
wl.held = true
wl.queue = append(wl.queue, a, b)
wl.mu.Unlock()
setControlFault(t, failRollback)
wl.release(c)
if !errors.Is(a.err, errNoMem) {
t.Fatalf("the statement whose RELEASE failed got %v", a.err)
}
if !c.bad || c.c.AutoCommit() || !c.writing {
t.Fatalf("bad %v, autocommit %v, writing %v", c.bad, c.c.AutoCommit(), c.writing)
}
wl.mu.Lock()
held, queued := wl.held, slices.Contains(wl.queue, b)
wl.mu.Unlock()
if !held || !queued || b.handed {
t.Fatalf("held %v, b queued %v, b handed %v", held, queued, b.handed)
}
controlFault = nil
// The committed callback runs as the lock goes on.
var autocommit bool
wl.committed.Store(&[]func(uint32, uint32, int64){func(uint32, uint32, int64) { autocommit = c.c.AutoCommit() }}[0])
if err := c.Close(); err != nil {
t.Fatal(err)
}
if !autocommit {
t.Fatal("the lock went on while the transaction was open")
}
select {
case <-b.done:
default:
t.Fatal("the lock did not go to the queued request")
}
if !b.handed {
t.Fatal("b was answered, not handed the lock")
}
if n := countOf(t, other, `SELECT count(*) FROM t`); n != 0 {
t.Fatalf("%d rows: the batch committed", n)
}
}
// When the ROLLBACK of Close fails too, closing the connection ends its
// transaction, and the lock goes on after: SQLite's own lock is gone when
// the next writer has it.
func TestCloseRollbackFails(t *testing.T) {
c, other := twoConns(t)
mustExec(t, c, `CREATE TABLE t(x)`)
a, b := batchReq(`INSERT INTO t VALUES (1)`), batchReq(`INSERT INTO t VALUES (2)`)
a.key, b.key = c.key, c.key
wl := c.wl
wl.mu.Lock()
wl.held = true
wl.queue = append(wl.queue, a, b)
wl.mu.Unlock()
setControlFault(t, failRollback)
wl.release(c)
if !c.bad || c.c.AutoCommit() || !c.writing {
t.Fatalf("bad %v, autocommit %v, writing %v", c.bad, c.c.AutoCommit(), c.writing)
}
// The fault stays for the ROLLBACK of Close.
if err := c.Close(); err != nil {
t.Fatal(err)
}
select {
case <-b.done:
default:
t.Fatal("the lock did not go to the queued request")
}
if !b.handed {
t.Fatal("b was answered, not handed the lock")
}
// As the request that was handed the lock would: SQLite lets it write.
if err := other.c.Exec(`BEGIN IMMEDIATE; INSERT INTO t VALUES (3); COMMIT`); err != nil {
t.Fatal(err)
}
if n := countOf(t, other, `SELECT count(*) FROM t`); n != 1 {
t.Fatalf("%d rows: the batch committed", n)
}
}
func countOf(t *testing.T, c *conn, q string) int64 {
t.Helper()
got := queryOne(t, c, q)
return got[0].(int64)
}
// A request handed the lock that leads a batch and goes back to its own
// connection must not run there when the batch would not roll back: it
// gets driver.ErrBadConn, having never run.
func TestLeadRollbackFails(t *testing.T) {
c, other := twoConns(t)
mustExec(t, c, `CREATE TABLE t(x)`)
lead := batchReq(`INSERT INTO t VALUES (1); SELECT 1`) // never merges
lead.key, lead.handed = c.key, true
e := batchReq(`INSERT INTO t VALUES (2)`)
e.key = c.key
c.wl.mu.Lock()
c.wl.held = true
c.wl.queue = append(c.wl.queue, e)
c.wl.mu.Unlock()
setControlFault(t, failRollback)
if _, err := c.answered(context.Background(), nil, lead); !errors.Is(err, driver.ErrBadConn) {
t.Fatalf("the leader got %v, want driver.ErrBadConn", err)
}
if !errors.Is(e.err, errNoMem) {
t.Fatalf("the statement whose RELEASE failed got %v", e.err)
}
controlFault = nil
c.Close()
if n := countOf(t, other, `SELECT count(*) FROM t`); n != 0 {
t.Fatalf("%d rows", n)
}
}
// makeBad has c run a batch whose transaction would not roll back: c is
// then bad, and its transaction stays open until c is closed.
func makeBad(t *testing.T, c *conn) {
t.Helper()
a := batchReq(`INSERT INTO t VALUES (1)`)
a.key = c.key
wl := c.wl
wl.mu.Lock()
wl.held = true
wl.queue = append(wl.queue, a)
wl.mu.Unlock()
setControlFault(t, failRollback)
wl.release(c)
controlFault = nil
if !c.bad || c.c.AutoCommit() {
t.Fatalf("bad %v, autocommit %v: the test needs a batch that would not roll back", c.bad, c.c.AutoCommit())
}
}
// A connection whose batch would not roll back keeps the transaction of the
// batch open until it is closed, which rolls it back. Nothing may run in it
// meanwhile: a write there would succeed and then be rolled back, and a read
// would see writes that are not there. Each way in gets driver.ErrBadConn
// and runs nothing.
func TestBadConnRunsNothing(t *testing.T) {
ctx := context.Background()
const write = `INSERT INTO t VALUES (9)`
for _, way := range []struct {
name string
call func(c *conn, prepared, returning *stmt) (driver.Rows, error)
}{
{"Exec", func(c *conn, _, _ *stmt) (driver.Rows, error) {
_, err := c.ExecContext(ctx, write, nil)
return nil, err
}},
{"Exec of a prepared statement", func(_ *conn, p, _ *stmt) (driver.Rows, error) { _, err := p.ExecContext(ctx, nil); return nil, err }},
{"Query", func(c *conn, _, _ *stmt) (driver.Rows, error) { return c.QueryContext(ctx, write+` RETURNING x`, nil) }},
{"Query kept", func(c *conn, _, _ *stmt) (driver.Rows, error) {
return c.QueryContext(ctx, `SELECT count(*) FROM t`, nil)
}},
{"Query of a prepared statement", func(_ *conn, _, r *stmt) (driver.Rows, error) { return r.QueryContext(ctx, nil) }},
{"Prepare", func(c *conn, _, _ *stmt) (driver.Rows, error) {
_, err := c.PrepareContext(ctx, write)
return nil, err
}},
{"BeginTx", func(c *conn, _, _ *stmt) (driver.Rows, error) {
_, err := c.BeginTx(ctx, driver.TxOptions{})
return nil, err
}},
{"Ping", func(c *conn, _, _ *stmt) (driver.Rows, error) { return nil, c.Ping(ctx) }},
{"ResetSession", func(c *conn, _, _ *stmt) (driver.Rows, error) { return nil, c.ResetSession(ctx) }},
} {
// With rows of the connection open the error is another
// (TestBadSQLConnRowsOpen). database/sql asks ResetSession only of a
// connection in its pool, which has no rows open.
for _, open := range []bool{false, true} {
if open && way.name == "ResetSession" {
continue
}
t.Run(fmt.Sprintf("%s/rows open %v", way.name, open), func(t *testing.T) {
c, other := twoConns(t)
mustExec(t, c, `CREATE TABLE t(x)`)
p, err := c.PrepareContext(ctx, write)
if err != nil {
t.Fatal(err)
}
r, err := c.PrepareContext(ctx, write+` RETURNING x`)
if err != nil {
t.Fatal(err)
}
queryOne(t, c, `SELECT count(*) FROM t`) // kept by the connection
want := driver.ErrBadConn
if open {
// At its end already, so c still runs a batch.
kept := openRows(t, c, `SELECT 1 WHERE 0`)
defer kept.Close()
want = errConnHeld
}
makeBad(t, c)
rows, err := way.call(c, p.(*stmt), r.(*stmt))
if err == nil && rows != nil {
rows.Close()
}
if !errors.Is(err, want) || open && errors.Is(err, driver.ErrBadConn) {
t.Errorf("got %v, want %v", err, want)
}
if n := batchCount(t, c, `SELECT count(*) FROM t WHERE x = 9`); n != 0 {
t.Errorf("the write ran in the transaction the close rolls back")
}
c.Close()
if n := countOf(t, other, `SELECT count(*) FROM t`); n != 0 {
t.Fatalf("%d rows after the close", n)
}
})
}
}
}
// A transaction of database/sql on a connection gone bad (a DETACH that
// failed after an ATTACH in it, syncAttached) commits nothing: Commit rolls
// it back and gives driver.ErrBadConn.
func TestBadConnCommitsNothing(t *testing.T) {
ctx := context.Background()
// A sql.Tx begun on a sql.Conn gives the error of Commit to the
// sql.Conn, which database/sql closes on driver.ErrBadConn: with rows of
// the sql.Conn open, the error is another (TestBadSQLConnRowsOpen). While
// the transaction is open, so is a call that does not end it
// (TestSpentSQLConnTxOpen).
for _, open := range []bool{false, true} {
t.Run(fmt.Sprintf("rows open %v", open), func(t *testing.T) {
c, other := twoConns(t)
mustExec(t, c, `CREATE TABLE t(x)`)
want := driver.ErrBadConn
if open {
kept := openRows(t, c, `SELECT 1 WHERE 0`)
defer kept.Close()
want = errConnHeld
}
tx, err := c.BeginTx(ctx, driver.TxOptions{})
if err != nil {
t.Fatal(err)
}
mustExec(t, c, `INSERT INTO t VALUES (9)`)
c.bad = true
if _, err := c.ExecContext(ctx, `INSERT INTO t VALUES (8)`, nil); !errors.Is(err, errConnHeld) || errors.Is(err, driver.ErrBadConn) {
t.Errorf("a statement in the transaction gave %v, want %v", err, errConnHeld)
}
if err := c.Ping(ctx); !errors.Is(err, errConnHeld) || errors.Is(err, driver.ErrBadConn) {
t.Errorf("Ping in the transaction gave %v, want %v", err, errConnHeld)
}
if err := tx.Commit(); !errors.Is(err, want) || open && errors.Is(err, driver.ErrBadConn) {
t.Errorf("Commit gave %v, want %v", err, want)
}
c.Close()
if n := countOf(t, other, `SELECT count(*) FROM t`); n != 0 {
t.Fatalf("%d rows: the transaction of a bad connection committed", n)
}
})
}
}
// How a program meets a bad connection: it keeps a sql.Conn whose write
// gave the lock back to a batch, and the batch would not roll back. Its
// next write must not succeed in that transaction only to be rolled back
// when the connection closes. database/sql closes the sql.Conn on
// driver.ErrBadConn, which rolls the batch back and hands the lock on.
func TestBadSQLConnRefusesWrite(t *testing.T) {
ctx := context.Background()
cn, err := NewConnector("file:" + mPath(t) + "?_pragma=journal_mode(WAL)")
if err != nil {
t.Fatal(err)
}
db := sql.OpenDB(cn)
t.Cleanup(func() { db.Close() })
mExec(t, db, `CREATE TABLE h(x); CREATE TABLE t(x)`)
sc, err := db.Conn(ctx)
if err != nil {
t.Fatal(err)
}
defer sc.Close()
spoil(t, db, sc)
r, err := sc.ExecContext(ctx, `INSERT INTO t VALUES (9)`)
if err == nil {
n, _ := r.RowsAffected()
sc.Close()
t.Fatalf("a write on the bad connection succeeded with %d rows, and %d of them are there after the close", n, mCount(t, db, `SELECT count(*) FROM t WHERE x = 9`))
}
if !errors.Is(err, driver.ErrBadConn) {
t.Fatalf("a write on the bad connection gave %v, want driver.ErrBadConn", err)
}
if err := sc.PingContext(ctx); !errors.Is(err, sql.ErrConnDone) {
t.Errorf("the sql.Conn after driver.ErrBadConn: %v, want sql.ErrConnDone", err)
}
after, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
if _, err := db.ExecContext(after, `INSERT INTO t VALUES (2)`); err != nil {
t.Fatalf("a write once the bad connection closed: %v", err)
}
if n := mCount(t, db, `SELECT count(*) FROM t`); n != 1 {
t.Fatalf("%d rows, want the 1 written after", n)
}
}
// An Exec of several statements whose connection goes bad between two of
// them: its first gives the lock back to a batch of another caller, and the
// batch would not roll back. The first ran and committed, so the error is
// not driver.ErrBadConn, on which database/sql would run them all again on
// another connection, also with rows of the connection open. The next is
// not even prepared: SQLite applies a PRAGMA that sets something as it
// prepares it.
func TestExecCutOnBadConn(t *testing.T) {
for _, open := range []bool{false, true} {
t.Run(fmt.Sprintf("rows open %v", open), func(t *testing.T) {
c, other := twoConns(t)
mustExec(t, c, `CREATE TABLE h(x); CREATE TABLE t(x)`)
if open {
// At its end already, so c still runs a batch.
kept := openRows(t, c, `SELECT 1 WHERE 0`)
defer kept.Close()
}
a := batchReq(`INSERT INTO t VALUES (1)`)
a.key = c.key
wl := c.wl
wl.mu.Lock()
wl.queue = append(wl.queue, a)
wl.mu.Unlock()
setControlFault(t, failRollback)
was := c.busyTimeout
_, err := c.ExecContext(context.Background(), `INSERT INTO h VALUES (1); PRAGMA busy_timeout=123`, nil)
controlFault = nil
if !c.bad {
t.Fatal("the test needs a batch that would not roll back")
}
if !errors.Is(err, errExecCut) {
t.Errorf("got %v, want %v", err, errExecCut)
}
if c.busyTimeout != was || c.c.ChangedItself() {
t.Errorf("busy timeout %v, was %v: the PRAGMA was prepared on the bad connection", c.busyTimeout, was)
}
c.Close()
if n := countOf(t, other, `SELECT count(*) FROM h`); n != 1 {
t.Errorf("%d rows of the first statement, want the 1 it committed", n)
}
if n := countOf(t, other, `SELECT count(*) FROM t`); n != 0 {
t.Errorf("%d rows of the batch that would not roll back", n)
}
})
}
}
// An Exec whose statements all ran succeeds, also when the last of them
// left its connection bad as it gave the lock back: what follows it holds
// no statement, as SQLite reads it, so nothing of the Exec was refused.
func TestExecDoneOnBadConn(t *testing.T) {
for _, tail := range []string{"", ";", " -- done", "/* never closed", " \v", "\x00PRAGMA busy_timeout=123", "\xef\xbb\xbf"} {
t.Run(fmt.Sprintf("%q", tail), func(t *testing.T) {
c, other := twoConns(t)
mustExec(t, c, `CREATE TABLE h(x); CREATE TABLE t(x)`)
a := batchReq(`INSERT INTO t VALUES (1)`)
a.key = c.key
wl := c.wl
wl.mu.Lock()
wl.queue = append(wl.queue, a)
wl.mu.Unlock()
setControlFault(t, failRollback)
was := c.busyTimeout
_, err := c.ExecContext(context.Background(), `INSERT INTO h VALUES (1)`+tail, nil)
controlFault = nil
if !c.bad {
t.Fatal("the test needs a batch that would not roll back")
}
if err != nil {
t.Errorf("the Exec ran and committed, and got %v", err)
}
if c.busyTimeout != was {
t.Errorf("busy timeout %v, was %v", c.busyTimeout, was)
}
c.Close()
if n := countOf(t, other, `SELECT count(*) FROM h`); n != 1 {
t.Errorf("%d rows of the Exec, want the 1 it committed", n)
}
})
}
}
// spoil makes the connection of sc bad as a program meets it: a write of sc
// gives the lock back to a batch of another caller, and the batch would not
// roll back. Tables h and t are there, and empty.
func spoil(t *testing.T, db *sql.DB, sc *sql.Conn) {
t.Helper()
ctx := context.Background()
var bad *conn
sc.Raw(func(dc any) error { bad = dc.(*conn); return nil })
tx, err := sc.BeginTx(ctx, nil)
if err != nil {
t.Fatal(err)
}
mExec(t, tx, `INSERT INTO h VALUES (1)`)
queued := execAsync(ctx, db, `INSERT INTO t VALUES (1)`)
waitFor(t, 1)
setControlFault(t, func(c *conn, sql string) error {
if c == bad && (sql == "RELEASE merge" || sql == "ROLLBACK") {
return errNoMem
}
return nil
})
if err := tx.Commit(); err != nil {
t.Fatal(err)
}
if a := await(t, queued, "the queued write"); !errors.Is(a.err, errNoMem) {
t.Fatalf("the queued write got %v, want the error of its RELEASE", a.err)
}
controlFault = nil
if !bad.bad {
t.Fatal("the test needs a batch that would not roll back")
}
}
// A sql.Conn gone bad with rows of it still open. database/sql closes a
// sql.Conn that gets driver.ErrBadConn before the call returns, and the
// close waits for the rows of the sql.Conn, which a program closes once
// the call returned: the call would never return, and the write lock the
// connection keeps would never go back. So the call gets an error that says
// the rows are open, and the sql.Conn stays open: once its rows are closed,
// the next call gets driver.ErrBadConn and closes it.
func TestBadSQLConnRowsOpen(t *testing.T) {
ctx := context.Background()
const write = `INSERT INTO t VALUES (9)`
for _, way := range []struct {
name string
call func(sc *sql.Conn, st *sql.Stmt) error
}{
{"Exec", func(sc *sql.Conn, _ *sql.Stmt) error {
_, err := sc.ExecContext(ctx, write)
return err
}},
{"Exec of a prepared statement", func(_ *sql.Conn, st *sql.Stmt) error {
_, err := st.ExecContext(ctx)
return err
}},
{"Query", func(sc *sql.Conn, _ *sql.Stmt) error {
rows, err := sc.QueryContext(ctx, `SELECT count(*) FROM t`)
if err == nil {
rows.Close()
}
return err
}},
{"Prepare", func(sc *sql.Conn, _ *sql.Stmt) error {
st, err := sc.PrepareContext(ctx, write)
if err == nil {
st.Close()
}
return err
}},
{"BeginTx", func(sc *sql.Conn, _ *sql.Stmt) error {
tx, err := sc.BeginTx(ctx, nil)
if err == nil {
tx.Rollback()
}
return err
}},
{"Ping", func(sc *sql.Conn, _ *sql.Stmt) error { return sc.PingContext(ctx) }},
} {
t.Run(way.name, func(t *testing.T) {
cn, err := NewConnector("file:" + mPath(t) + "?_pragma=journal_mode(WAL)")
if err != nil {
t.Fatal(err)
}
db := sql.OpenDB(cn)
t.Cleanup(func() { db.Close() })
mExec(t, db, `CREATE TABLE h(x); CREATE TABLE t(x)`)
sc, err := db.Conn(ctx)
if err != nil {
t.Fatal(err)
}
defer sc.Close()
st, err := sc.PrepareContext(ctx, write)
if err != nil {
t.Fatal(err)
}
defer st.Close()
// At its end already, so the connection still runs batches.
rows, err := sc.QueryContext(ctx, `SELECT 1 WHERE 0`)
if err != nil {
t.Fatal(err)
}
defer rows.Close()
spoil(t, db, sc)
done := make(chan error, 1)
go func() { done <- way.call(sc, st) }()
select {
case err = <-done:
case <-time.After(10 * time.Second):
rows.Close() // lets the call return
<-done
t.Fatal("the call on the bad sql.Conn did not return while its rows were open")
}
if !errors.Is(err, errConnHeld) || errors.Is(err, driver.ErrBadConn) {
t.Fatalf("got %v, want an error that the rows of the connection are open", err)
}
if n := mCount(t, db, `SELECT count(*) FROM t WHERE x = 9`); n != 0 {
t.Fatalf("%d rows of the write on the bad connection", n)
}
if err := rows.Close(); err != nil {
t.Fatal(err)
}
if _, err := sc.ExecContext(ctx, write); !errors.Is(err, driver.ErrBadConn) {
t.Fatalf("with its rows closed the sql.Conn got %v, want driver.ErrBadConn", err)
}
if err := sc.PingContext(ctx); !errors.Is(err, sql.ErrConnDone) {
t.Errorf("the sql.Conn after driver.ErrBadConn: %v, want sql.ErrConnDone", err)
}
after, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
if _, err := db.ExecContext(after, `INSERT INTO t VALUES (2)`); err != nil {
t.Fatalf("a write once the bad connection closed: %v", err)
}
if n := mCount(t, db, `SELECT count(*) FROM t`); n != 1 {
t.Fatalf("%d rows, want the 1 written after", n)
}
})
}
}
// When writing a virtual table's index ends the transaction of a batch, the
// statement gets that error, though it had failed alone before, and the
// others get it under SQLITE_ABORT_ROLLBACK.
func TestFlushEndsBatch(t *testing.T) {
c := batchConn(t)
mustExec(t, c, `CREATE VIRTUAL TABLE f USING fts5(x); CREATE TABLE u(x UNIQUE); INSERT INTO u VALUES (1)`)
errFull := csqlite.NewError(FULL, "database or disk is full", nil)
flushes := 0
setControlFault(t, func(c *conn, sql string) error {
if sql != "SAVEPOINT flush" {
return nil
}
if flushes++; flushes < 2 {
return nil
}
c.c.Exec("ROLLBACK") // a full disk as the index is written
return errFull
})
a := batchReq(`INSERT INTO f VALUES ('x')`)
b := batchReq(`INSERT OR FAIL INTO u VALUES (2), (1)`)
c.runBatch([]*request{a, b})
if b.err != errFull {
t.Fatalf("the statement got %v, want what ended the transaction", b.err)
}
var e *Error
if !errors.As(a.err, &e) || e.ExtendedCode() != ABORT_ROLLBACK || errors.Unwrap(a.err) != errFull {
t.Fatalf("the statement before got %v", a.err)
}
}