Repository navigation
Expand file tree
/
Copy pathquery_cache_test.go
More file actions
613 lines (585 loc) · 19.4 KB
/
Copy pathquery_cache_test.go
File metadata and controls
613 lines (585 loc) · 19.4 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
// 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/driver"
"fmt"
"math"
"path/filepath"
"strings"
"testing"
)
func TestQueryReusesStatement(t *testing.T) {
c := memConn(t)
mustExec(t, c, `CREATE TABLE t(id INTEGER PRIMARY KEY, v TEXT); INSERT INTO t VALUES (1, 'a'), (2, 'b')`)
const q = `SELECT v FROM t WHERE id = ?`
r := openRows(t, c, q, int64(1))
first := r.s
if got := drain(t, r); fmt.Sprint(got) != "[a]" {
t.Fatalf("got %v", got)
}
r.Close()
r = openRows(t, c, q, int64(2))
if r.s != first {
t.Error("the query was prepared again")
}
if got := drain(t, r); fmt.Sprint(got) != "[b]" {
t.Fatalf("got %v", got)
}
r.Close()
}
func TestQuerySameSQLWhileOpen(t *testing.T) {
c := memConn(t)
mustExec(t, c, `CREATE TABLE t(id INTEGER PRIMARY KEY); INSERT INTO t VALUES (1), (2), (3)`)
const q = `SELECT id FROM t WHERE id >= ? ORDER BY id`
queryOne(t, c, q, int64(1)) // the statement is cached now
outer := openRows(t, c, q, int64(1))
dest := make([]driver.Value, 1)
var got []string
for outer.Next(dest) == nil {
got = append(got, fmt.Sprintf("%v%v", dest[0], queryOne(t, c, q, dest[0])))
}
outer.Close()
if want := "[1[1 2 3] 2[2 3] 3[3]]"; fmt.Sprint(got) != want {
t.Fatalf("got %v, want %s", got, want)
}
if got := queryOne(t, c, q, int64(2)); fmt.Sprint(got) != "[2 3]" {
t.Fatalf("got %v", got)
}
}
func TestQueryCacheSkipsPragma(t *testing.T) {
c := memConn(t)
for _, ms := range []int64{100, 200} {
mustExec(t, c, fmt.Sprintf("PRAGMA busy_timeout = %d", ms))
if got := queryOne(t, c, `PRAGMA busy_timeout`); fmt.Sprint(got) != fmt.Sprint([]driver.Value{ms}) {
t.Fatalf("busy_timeout is %v, want %d", got, ms)
}
}
if len(c.queries) != 0 {
t.Errorf("%d statements cached", len(c.queries))
}
}
func TestQueryCacheFollowsSchema(t *testing.T) {
c := memConn(t)
mustExec(t, c, `CREATE TABLE t(a); INSERT INTO t VALUES (1)`)
const q = `SELECT * FROM t`
queryOne(t, c, q)
mustExec(t, c, `ALTER TABLE t ADD COLUMN b`)
r := openRows(t, c, q)
if n := len(r.Columns()); n != 2 {
t.Errorf("%d columns after ALTER TABLE, want 2", n)
}
r.Close()
mustExec(t, c, `DROP TABLE t`)
if _, err := c.QueryContext(context.Background(), q, nil); err == nil {
t.Fatal("query of a dropped table ran")
}
mustExec(t, c, `CREATE TABLE t(x); INSERT INTO t VALUES ('again')`)
if got := queryOne(t, c, q); fmt.Sprint(got) != "[again]" {
t.Fatalf("got %v", got)
}
}
func TestQueryCacheBounded(t *testing.T) {
c := memConn(t)
for i := range 3 * maxQueries {
queryOne(t, c, fmt.Sprintf("SELECT %d", i))
}
if n := len(c.queries); n != maxQueries {
t.Errorf("%d statements cached, want %d", n, maxQueries)
}
// The one used last stays.
last := fmt.Sprintf("SELECT %d", 3*maxQueries-1)
if c.queries[last] == nil {
t.Errorf("%q was dropped", last)
}
}
func TestQueryCacheClose(t *testing.T) {
cn, err := (&Driver{}).Open(":memory:")
if err != nil {
t.Fatal(err)
}
c := cn.(*conn)
queryOne(t, c, `SELECT 1`)
if err := c.Close(); err != nil {
t.Fatal(err)
}
}
func TestQueryCacheSkipsExplain(t *testing.T) {
name := filepath.Join(t.TempDir(), "x.db")
a, b := fileConn(t, name), fileConn(t, name)
mustExec(t, a, `CREATE TABLE t(a, b)`)
const q = `EXPLAIN QUERY PLAN SELECT b FROM t WHERE a = 1`
if got := fmt.Sprint(planOf(t, a, q)); !strings.Contains(got, "SCAN") {
t.Fatalf("plan %s, want a scan", got)
}
mustExec(t, b, `CREATE INDEX ta ON t(a, b)`)
queryOne(t, a, `SELECT count(*) FROM t`) // a reads the new schema
if got := fmt.Sprint(planOf(t, a, q)); !strings.Contains(got, "INDEX ta") {
t.Fatalf("plan %s after CREATE INDEX, want ta", got)
}
if a.queries[q] != nil {
t.Error("the EXPLAIN was cached")
}
}
func planOf(t *testing.T, c *conn, q string) []driver.Value {
t.Helper()
r := openRows(t, c, q)
defer r.Close()
var out []driver.Value
dest := make([]driver.Value, len(r.Columns()))
for r.Next(dest) == nil {
out = append(out, dest[3])
}
return out
}
func TestQueryCacheEmptiedByChange(t *testing.T) {
c := memConn(t)
mustExec(t, c, `CREATE TABLE t(a)`)
queryOne(t, c, `SELECT a FROM t`)
open := openRows(t, c, `SELECT 1 UNION ALL SELECT 2`) // kept, and busy
queryOne(t, c, `SELECT count(*) FROM t`)
if n := len(c.queries); n != 3 {
t.Fatalf("%d statements cached, want 3", n)
}
s, err := c.PrepareContext(context.Background(), `PRAGMA reverse_unordered_selects = 1`)
if err != nil {
t.Fatal(err)
}
s.Close()
if n := len(c.queries); n != 0 {
t.Errorf("%d statements cached after a PRAGMA, want 0", n)
}
if got := drain(t, open); fmt.Sprint(got) != "[1 2]" {
t.Fatalf("open rows gave %v", got)
}
open.Close()
if n := len(c.queries); n != 0 {
t.Errorf("%d statements cached after the open rows closed, want 0", n)
}
}
func TestQueryCacheSkipsWrites(t *testing.T) {
c := memConn(t)
mustExec(t, c, `CREATE TABLE t(a)`)
queryOne(t, c, `INSERT INTO t VALUES (1) RETURNING a`)
if n := len(c.queries); n != 0 {
t.Errorf("%d statements cached", n)
}
}
// A read of the temp database or of an attached one is not kept: what such a
// name means belongs to the connection.
func TestQueryCacheSkipsOtherSchemas(t *testing.T) {
c := memConn(t)
mustExec(t, c, `ATTACH ':memory:' AS aux; CREATE TABLE aux.u(x); CREATE TEMP TABLE tt(x); CREATE TABLE m(x)`)
for _, q := range []string{`SELECT x FROM aux.u`, `SELECT x FROM tt`, `SELECT x FROM temp.tt`} {
queryOne(t, c, q)
if c.queries[q] != nil {
t.Errorf("%s was kept", q)
}
}
queryOne(t, c, `SELECT x FROM m`)
if len(c.queries) != 1 {
t.Errorf("%d statements kept, want only the read of main", len(c.queries))
}
}
// A statement that fails is not kept, whether it fails at its first step or
// after rows, and the next query of the same SQL prepares a new one.
func TestQueryCacheDropsFailed(t *testing.T) {
c := memConn(t)
const first = `SELECT abs(?)`
if _, err := c.QueryContext(context.Background(), first, []driver.NamedValue{{Ordinal: 1, Value: int64(math.MinInt64)}}); err == nil {
t.Fatal("abs of the least int64 gave no error")
}
if c.queries[first] != nil {
t.Error("a statement that failed at its first step was kept")
}
if got := queryOne(t, c, first, int64(-2)); fmt.Sprint(got) != "[2]" {
t.Fatalf("got %v", got)
}
const later = `SELECT abs(x) FROM (SELECT 1 AS x UNION ALL SELECT ?)`
r := openRows(t, c, later, int64(math.MinInt64))
dest := make([]driver.Value, 1)
if err := r.Next(dest); err != nil {
t.Fatal(err)
}
if err := r.Next(dest); err == nil {
t.Fatal("abs of the least int64 gave no error")
}
r.Close()
if c.queries[later] != nil {
t.Error("a statement that failed after a row was kept")
}
}
// When every statement kept has open rows, a new one is not kept and the
// open ones stay. Once rows close, their statement is the one let go.
func TestQueryCacheFullOfOpenRows(t *testing.T) {
c := memConn(t)
open := make([]*rows, maxQueries)
for i := range open {
open[i] = openRows(t, c, fmt.Sprintf("SELECT %d UNION ALL SELECT 0", i))
}
if got := queryOne(t, c, `SELECT 'new'`); fmt.Sprint(got) != "[new]" {
t.Fatalf("got %v", got)
}
if c.queries[`SELECT 'new'`] != nil || len(c.queries) != maxQueries {
t.Fatalf("a statement was kept with every one in use: %d kept", len(c.queries))
}
open[5].Close()
queryOne(t, c, `SELECT 'new'`)
if c.queries[`SELECT 'new'`] == nil || c.queries[`SELECT 5 UNION ALL SELECT 0`] != nil {
t.Fatal("the statement with closed rows was not the one let go")
}
for i, r := range open {
if i == 5 {
continue
}
if got := drain(t, r); fmt.Sprint(got) != fmt.Sprintf("[%d 0]", i) {
t.Fatalf("rows %d gave %v", i, got)
}
r.Close()
}
}
// SQLite asks the authorizer about no column of a table named only in USING,
// so a read of an attached database there is kept. That is safe: ATTACH and
// DETACH empty the cache, so a kept statement never reads a database that
// another one replaced.
func TestQueryCacheJoinOfAttached(t *testing.T) {
c := memConn(t)
mustExec(t, c, `CREATE TABLE m(x); INSERT INTO m VALUES (1), (2); ATTACH ':memory:' AS aux; CREATE TABLE aux.u(x); INSERT INTO aux.u VALUES (1)`)
const q = `SELECT x FROM m JOIN aux.u USING (x)`
if got := queryOne(t, c, q); fmt.Sprint(got) != "[1]" {
t.Fatalf("got %v", got)
}
mustExec(t, c, `DETACH aux; ATTACH ':memory:' AS aux; CREATE TABLE aux.u(x); INSERT INTO aux.u VALUES (2)`)
if got := queryOne(t, c, q); fmt.Sprint(got) != "[2]" {
t.Fatalf("got %v after aux was attached again", got)
}
}
// SQLite marks a parameter whose value its plan looked at, such as one
// compared with = when the WHERE clause or ORDER BY leaves a choice of
// plans, and prepares the statement again when a new value calls for
// another plan. sqlite3_clear_bindings prepares it again at its next step
// whatever the values are, so a kept query is not cleared before it runs
// again, and is kept.
func TestQueryKeptWhenPlanLooksAtArgument(t *testing.T) {
c := memConn(t)
mustExec(t, c, `CREATE TABLE t(k TEXT, v); INSERT INTO t VALUES ('a', 2), ('a', 1), ('b', 3)`)
for _, q := range []string{
`SELECT v FROM t WHERE k = ? ORDER BY v`,
`SELECT min(v) FROM t WHERE k = ?`,
} {
r := openRows(t, c, q, "a")
first := r.s
drain(t, r)
r.Close()
for _, k := range []string{"b", "a", "a"} {
r := openRows(t, c, q, k)
if r.s != first {
t.Fatalf("%s: prepared again", q)
}
drain(t, r)
r.Close()
}
if n := first.s.Reprepares(); n != 0 {
t.Errorf("%s: SQLite prepared it again %d times", q, n)
}
}
}
// A statement of the program's own that runs again is not prepared again
// for its arguments.
func TestStmtNotPreparedAgainForArguments(t *testing.T) {
c := memConn(t)
mustExec(t, c, `CREATE TABLE t(k TEXT, v); INSERT INTO t VALUES ('a', 2), ('a', 1), ('b', 3)`)
ds, err := c.PrepareContext(context.Background(), `SELECT v FROM t WHERE k = ? ORDER BY v`)
if err != nil {
t.Fatal(err)
}
defer ds.Close()
s := ds.(*stmt)
for _, k := range []string{"a", "b", "a"} {
dr, err := s.QueryContext(context.Background(), []driver.NamedValue{{Ordinal: 1, Value: k}})
if err != nil {
t.Fatal(err)
}
drain(t, dr.(*rows))
dr.Close()
}
if n := s.s.Reprepares(); n != 0 {
t.Errorf("SQLite prepared it again %d times", n)
}
}
// A kept query lets go of its text and BLOB arguments as its rows close,
// and stays kept.
func TestQueryKeptLetsArgumentsGo(t *testing.T) {
c := memConn(t)
mustExec(t, c, `CREATE TABLE t(k TEXT, b BLOB, v)`)
const q = `SELECT v FROM t WHERE k = ? OR b = ? OR v = ? ORDER BY v`
r := openRows(t, c, q, "a", []byte("b"), int64(1))
s := r.s
drain(t, r)
r.Close()
if c.queries[q] != s {
t.Fatal("not kept")
}
before := s.s.MemUsed()
const n = 1 << 20
r = openRows(t, c, q, strings.Repeat("a", n), make([]byte, n), int64(1))
if r.s != s {
t.Fatal("prepared again")
}
if held := s.s.MemUsed(); held < before+2*n {
t.Fatalf("%d bytes held with the rows open, %d before: MemUsed does not count the arguments", held, before)
}
drain(t, r)
r.Close()
if c.queries[q] != s {
t.Fatal("not kept")
}
if after := s.s.MemUsed(); after > before+n/2 {
t.Errorf("%d bytes held after the rows closed, %d before", after, before)
}
}
// A plan that holds only for the value of an argument, such as one that
// uses a partial index or the prefix of a LIKE pattern, is made again by
// SQLite when the value changes, also for a kept statement that was not
// cleared: each run gives the rows of its own arguments.
func TestQueryPlanOfArgumentFollowsValue(t *testing.T) {
c := memConn(t)
mustExec(t, c, `PRAGMA case_sensitive_like = ON;
CREATE TABLE t(k TEXT, v INTEGER);
CREATE INDEX t_a ON t(v) WHERE k = 'a';
CREATE INDEX t_k ON t(k);
INSERT INTO t VALUES ('a', 1), ('a', 2), ('b', 3), ('ab', 4), ('ba', 5)`)
for _, tc := range []struct {
q string
args []any
want string
}{
{`SELECT v FROM t WHERE k = ? AND v > 0 ORDER BY v`, []any{"a"}, "[1 2]"},
{`SELECT v FROM t WHERE k = ? AND v > 0 ORDER BY v`, []any{"b"}, "[3]"},
{`SELECT v FROM t WHERE k = ? AND v > 0 ORDER BY v`, []any{"a"}, "[1 2]"},
{`SELECT v FROM t WHERE k = ? AND v > 0 ORDER BY v`, []any{int64(1)}, "[]"},
{`SELECT v FROM t WHERE k LIKE ? ORDER BY v`, []any{"a%"}, "[1 2 4]"},
{`SELECT v FROM t WHERE k LIKE ? ORDER BY v`, []any{"b%"}, "[3 5]"},
{`SELECT v FROM t WHERE k LIKE ? ORDER BY v`, []any{"%a"}, "[1 2 5]"},
{`SELECT v FROM t WHERE k LIKE ? ORDER BY v`, []any{"a%"}, "[1 2 4]"},
} {
r := openRows(t, c, tc.q, tc.args...)
got := fmt.Sprint(drain(t, r))
r.Close()
if got != tc.want {
t.Errorf("%s with %v: got %s, want %s", tc.q, tc.args, got, tc.want)
}
}
}
// prepStmt prepares query as a statement of the program's own.
func prepStmt(t *testing.T, c *conn, query string) *stmt {
t.Helper()
ds, err := c.PrepareContext(context.Background(), query)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { ds.Close() })
return ds.(*stmt)
}
func namedArgs(args []any) []driver.NamedValue {
nv := make([]driver.NamedValue, len(args))
for i, a := range args {
nv[i] = driver.NamedValue{Ordinal: i + 1, Value: a}
}
return nv
}
// stmtRows runs s with args and gives the first column of its rows.
func stmtRows(t *testing.T, s *stmt, args ...any) string {
t.Helper()
dr, err := s.QueryContext(context.Background(), namedArgs(args))
if err != nil {
t.Fatal(err)
}
r := dr.(*rows)
defer r.Close()
return fmt.Sprint(drain(t, r))
}
// As SQLite 3.54.1 prepares a statement again, it gives the new program the
// marks of the old one that say a parameter matters only as 0 or 1, also
// for a parameter the new plan depends on wholly. A new value bound over
// such a mark then runs the plan made for the old value: a partial index
// that holds none of its rows. A statement SQLite prepared again is cleared
// before it is bound, as SQLite prepares it again then, so that each run
// gives the rows of its own arguments: the program's own statement, and a
// statement of the batch cache as runOne runs it.
func TestStmtPreparedAgainFollowsArguments(t *testing.T) {
t.Run("partial index of two parameters", func(t *testing.T) {
c := memConn(t)
mustExec(t, c, `CREATE TABLE t(k INTEGER, j TEXT, v INTEGER);
CREATE INDEX p ON t(v) WHERE k = 5 AND j = 'x';
INSERT INTO t VALUES (5, 'x', 1), (5, 'x', 2), (5, 'y', 3), (6, 'y', 4)`)
s := prepStmt(t, c, `SELECT v FROM t WHERE k = ? AND j = ? ORDER BY v`)
for _, tc := range []struct {
k int64
j string
want string
}{{5, "x", "[1 2]"}, {5, "y", "[3]"}, {5, "x", "[1 2]"}, {5, "y", "[3]"}} {
if got := stmtRows(t, s, tc.k, tc.j); got != tc.want {
t.Errorf("(%d, %s): got %s, want %s", tc.k, tc.j, got, tc.want)
}
}
})
t.Run("partial index made after the prepare", func(t *testing.T) {
c := memConn(t)
mustExec(t, c, `CREATE TABLE t(k TEXT, v INTEGER); INSERT INTO t VALUES ('a', 1), ('a', 2), ('b', 3)`)
s := prepStmt(t, c, `SELECT v FROM t WHERE k = ? ORDER BY v`)
if got := stmtRows(t, s, "a"); got != "[1 2]" {
t.Fatalf("got %s", got)
}
mustExec(t, c, `CREATE INDEX p ON t(v) WHERE k = 'a'`)
for _, tc := range []struct{ k, want string }{{"a", "[1 2]"}, {"b", "[3]"}, {"a", "[1 2]"}, {"b", "[3]"}} {
if got := stmtRows(t, s, tc.k); got != tc.want {
t.Errorf("%s: got %s, want %s", tc.k, got, tc.want)
}
}
})
for _, q := range []string{
`UPDATE t SET n = n + 1 WHERE rowid IN (SELECT rowid FROM t WHERE k = ? AND j = ? ORDER BY v LIMIT 100)`,
`UPDATE t SET n = n + 1 WHERE k = ? AND j = ? AND v = (SELECT min(v) FROM t WHERE k = ?1 AND j = ?2)`,
} {
for _, batch := range []bool{false, true} {
c := memConn(t)
mustExec(t, c, `CREATE TABLE t(k INTEGER, j TEXT, v INTEGER, n INTEGER DEFAULT 0);
CREATE INDEX p ON t(v) WHERE k = 5 AND j = 'x';
INSERT INTO t(k, j, v) VALUES (5, 'x', 1), (5, 'x', 2), (5, 'y', 3), (6, 'y', 4)`)
var own *stmt
if !batch {
own = prepStmt(t, c, q)
}
for _, j := range []string{"x", "y", "x", "y"} {
args := namedArgs([]any{int64(5), j})
var n int64
if batch {
s, err := c.cached(q)
if err != nil {
t.Fatal(err)
}
if err := s.bind(args); err != nil {
t.Fatal(err)
}
r, _, err := s.step(context.Background())
if err != nil {
t.Fatal(err)
}
n = r.n
} else {
r, err := own.ExecContext(context.Background(), args)
if err != nil {
t.Fatal(err)
}
n, _ = r.RowsAffected()
}
want := map[string]int64{"x": 2, "y": 1}[j]
if strings.Contains(q, "min(v)") {
want = 1
}
if n != want {
t.Errorf("batch %v, %s with (5, %s): %d rows, want %d", batch, q, j, n, want)
}
}
}
}
}
// A statement of the program's own lets go of the text and BLOB of its last
// run as it binds the next, also when a number takes its place.
func TestStmtLetsGoOfTextBoundOver(t *testing.T) {
c := memConn(t)
mustExec(t, c, `CREATE TABLE t(x)`)
s := prepStmt(t, c, `INSERT INTO t VALUES (?)`)
exec := func(v any) {
t.Helper()
if _, err := s.ExecContext(context.Background(), namedArgs([]any{v})); err != nil {
t.Fatal(err)
}
}
exec(int64(1))
before := s.s.MemUsed()
exec(strings.Repeat("a", 1<<20))
exec(int64(2))
if after := s.s.MemUsed(); after > before+1<<19 {
t.Errorf("%d bytes held after a number took the place of the text, %d before", after, before)
}
}
// Exec of a statement whose rows are open is refused, as a second Query of
// it is: it would step the statement under its rows and reset it, and the
// rows would start again from the first.
func TestStmtExecWhileRowsOpen(t *testing.T) {
c := memConn(t)
mustExec(t, c, `CREATE TABLE t(v); INSERT INTO t VALUES (1), (2), (3)`)
s := prepStmt(t, c, `SELECT v FROM t ORDER BY v`)
dr, err := s.QueryContext(context.Background(), nil)
if err != nil {
t.Fatal(err)
}
r := dr.(*rows)
defer r.Close()
row := make([]driver.Value, 1)
if err := r.Next(row); err != nil {
t.Fatal(err)
}
got := []driver.Value{row[0]}
if _, err := s.ExecContext(context.Background(), nil); err == nil {
t.Error("Exec ran while the rows of its statement were open")
}
got = append(got, drain(t, r)...)
if fmt.Sprint(got) != "[1 2 3]" {
t.Errorf("rows %v", got)
}
}
// The queries a connection keeps hold at most maxKeptBytes, and one that
// holds more than maxKeptBytes/8 is not kept.
func TestQueryCacheBoundedBytes(t *testing.T) {
c := memConn(t)
mustExec(t, c, `CREATE TABLE t(x)`)
in := func(n int, literal bool) string {
var b strings.Builder
b.WriteString(`SELECT x FROM t WHERE x IN (`)
for i := range n {
if i > 0 {
b.WriteString(`,`)
}
if literal {
fmt.Fprintf(&b, `'v%d'`, i)
} else {
b.WriteString(`?`)
}
}
b.WriteString(`) ORDER BY x`)
return b.String()
}
big := in(5000, true)
queryOne(t, c, big)
if c.queries[big] != nil {
t.Error("a query of 5000 values is kept")
}
for n := 200; n < 200+maxQueries; n++ {
args := make([]any, n)
for i := range args {
args[i] = int64(i)
}
queryOne(t, c, in(n, false), args...)
}
sum := 0
for _, s := range c.queries {
if s.size > maxKeptBytes/8 {
t.Errorf("a query of %d bytes is kept", s.size)
}
sum += s.size
}
if sum != c.queryBytes || sum > maxKeptBytes || len(c.queries) == maxQueries {
t.Errorf("%d queries kept, %d bytes, counted %d", len(c.queries), sum, c.queryBytes)
}
mustExec(t, c, `PRAGMA case_sensitive_like = ON`)
if len(c.queries) != 0 || c.queryBytes != 0 {
t.Errorf("%d queries, %d bytes after a change", len(c.queries), c.queryBytes)
}
}