Repository navigation
Expand file tree
/
Copy pathstmt.go
More file actions
657 lines (618 loc) · 17.5 KB
/
Copy pathstmt.go
File metadata and controls
657 lines (618 loc) · 17.5 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
// 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"
"errors"
"fmt"
"io"
"slices"
"strconv"
"strings"
"time"
"github.com/liustack/sqlite/internal/csqlite"
"github.com/liustack/sqlite/internal/queuehook"
)
type stmt struct {
c *conn
s *csqlite.Stmt
sql string
nparams int
// readOnly says the statement writes nothing (sqlite3_stmt_readonly).
readOnly bool
// changesConn says the statement changes its connection (a PRAGMA that
// sets something, ATTACH, a temporary object).
changesConn bool
// explain says the statement is an EXPLAIN: see prepareAgain.
explain bool
// once is a statement of conn.QueryContext, or one closed with its rows
// open: its rows finalize it.
once bool
// kept is the query a statement of conn.QueryContext is cached for. used
// is when a statement of the query or write cache last ran, and keptAt
// its Reprepares when it was kept (cache.go).
kept string
used uint64
keptAt int
// size is what a kept query or write holds, its SQL counted (cache.go).
size int
// rows are the open rows of the statement, nil when it has none.
rows *rows
// prev and next link the statements of the connection that are not
// finalized (conn.live), so that Close can end them.
prev, next *stmt
// cols, decl and isTime describe the columns of its rows. They are read
// again when SQLite has prepared the statement again after a change of
// the schema (prepared counts those).
cols []string
decl []string
isTime []bool
prepared int
// held are the parameters the last bind gave text or a BLOB, of which
// SQLite keeps a copy until the parameter is bound again (letGo).
held []int
}
// columns reads the names and declared types of the columns, once for each
// time SQLite prepared the statement.
func (s *stmt) columns() {
p := s.s.Reprepares()
if s.cols != nil && p == s.prepared {
return
}
s.prepared = p
n := s.s.ColumnCount()
s.cols = make([]string, n)
s.decl = make([]string, n)
s.isTime = make([]bool, n)
for i := range n {
s.cols[i] = s.s.ColumnName(i)
s.decl[i] = strings.ToUpper(s.s.ColumnDeclType(i))
switch s.decl[i] {
case "DATE", "DATETIME", "TIMESTAMP":
s.isTime[i] = true
}
}
}
var (
_ driver.Stmt = (*stmt)(nil)
_ driver.StmtExecContext = (*stmt)(nil)
_ driver.StmtQueryContext = (*stmt)(nil)
)
// Close finalizes the statement. database/sql closes a statement prepared
// on a sql.Conn when the program does, also with its rows still open: those
// rows go on, and finalize it when they are closed.
func (s *stmt) Close() error {
if s.s == nil {
return nil
}
if s.rows != nil {
s.once = true
return nil
}
err := s.s.Finalize()
s.s = nil
s.c.unlink(s)
return err
}
func (s *stmt) NumInput() int { return -1 }
func (s *stmt) Exec(args []driver.Value) (driver.Result, error) {
return s.ExecContext(context.Background(), named(args))
}
func (s *stmt) Query(args []driver.Value) (driver.Rows, error) {
return s.QueryContext(context.Background(), named(args))
}
func named(args []driver.Value) []driver.NamedValue {
n := make([]driver.NamedValue, len(args))
for i, v := range args {
n[i] = driver.NamedValue{Ordinal: i + 1, Value: v}
}
return n
}
func (s *stmt) ExecContext(ctx context.Context, args []driver.NamedValue) (driver.Result, error) {
defer s.c.unmark()
r, err := s.exec(ctx, args)
if err != nil {
return nil, s.c.noteErr(err)
}
return r, nil
}
func (s *stmt) exec(ctx context.Context, args []driver.NamedValue) (*result, error) {
c := s.c
if s.s == nil {
return nil, errStmtClosed
}
if c.retired() {
return nil, c.refusal()
}
if err := c.txEnded(); err != nil {
return nil, err
}
if s.rows != nil {
// Stepped under its rows and reset, it would start them again.
return nil, errors.New("sqlite: the rows of the statement are still open")
}
if err := s.prepareAgain(); err != nil {
return nil, err
}
// A connection with a query not done keeps the snapshot it read, which the
// connection running a batch would not have.
if c.wl != nil && !c.writing && !c.private() && c.c.AutoCommit() && !c.c.InTx() && s.s.Mergeable() {
return c.wl.submit(ctx, c, s, args)
}
// The time of a statement that may commit, for Stats: a write that takes
// the write lock itself, and a COMMIT run while the connection holds it
// (countCommit). The writes of a transaction are not timed.
timed := c.wl != nil && (!c.writing && !s.readOnly || c.writing && s.readOnly)
if err := c.beginWrite(ctx, s.readOnly); err != nil {
return nil, err
}
var start time.Time
if timed {
start = time.Now()
}
r, err := s.run(ctx, args)
if timed {
c.runTime = time.Since(start)
}
c.endWrite()
if s.changesConn {
// DETACH changes the connection too: settings are read after it.
if aerr := c.syncAttached(); err == nil {
err = aerr
}
c.changed()
}
if err != nil {
return nil, err
}
return r, nil
}
// prepareAgain prepares an EXPLAIN again before it runs. SQLite runs EXPLAIN
// without checking the schema, so one prepared before a change of the
// schema would list the plan of the old schema, and the names of tables it
// freed.
func (s *stmt) prepareAgain() error {
if !s.explain {
return nil
}
if s.rows != nil {
return errors.New("sqlite: the rows of the statement are still open")
}
p, _, err := s.c.prepareOne(context.Background(), s.sql)
if err != nil {
return err
}
s.s.Finalize()
s.s, s.cols = p, nil
return nil
}
// changed reads what the driver keeps of the settings of c, once c is set
// up and after each statement that changes the connection, failed or not:
// busy_timeout, as the file's write lock waits as long as SQLite would, and
// who runs the automatic checkpoints (checkpoint.go). It reads fields of
// the connection and runs no statement, which SQLite may refuse after one
// that failed.
func (c *conn) changed() {
// PRAGMA busy_timeout puts SQLite's own busy handler back.
c.c.InstallBusy()
if ms, ok := c.c.BusyTimeoutNow(); ok {
c.busyTimeout = time.Duration(ms) * time.Millisecond
}
c.takeCheckpoints()
}
// run binds args and steps the statement once, with the write lock held if
// it writes. A context done before the step stops it: SQLite forgets an
// interrupt that comes before a statement starts.
func (s *stmt) run(ctx context.Context, args []driver.NamedValue) (*result, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
if err := s.bind(args); err != nil {
return nil, err
}
res, _, err := s.step(ctx)
return res, ctxErr(ctx, err)
}
// step steps the bound statement once and resets it. stepped says it did
// step: it does not when ctx is done already (watch). The error is SQLite's,
// as an interrupt: ctxErr makes it the error of ctx.
func (s *stmt) step(ctx context.Context) (res *result, stepped bool, err error) {
stop, err := s.c.watch(ctx)
if err != nil {
return nil, false, err
}
_, err = s.s.Step()
stop()
if rerr := s.s.Reset(); err == nil {
err = rerr
}
if err != nil {
return nil, true, err
}
return &result{id: s.c.c.LastInsertRowID(), n: s.c.c.Changes()}, true, nil
}
func (s *stmt) QueryContext(ctx context.Context, args []driver.NamedValue) (driver.Rows, error) {
defer s.c.unmark()
r, err := s.query(ctx, args)
if err != nil {
return nil, s.c.noteErr(err)
}
return r, nil
}
// query runs the statement to its first row, so that its columns are the
// ones of the schema it runs on (SQLite prepares it again at its first step
// after a change of the schema), and a context done before then stops it.
func (s *stmt) query(ctx context.Context, args []driver.NamedValue) (*rows, error) {
c := s.c
if s.s == nil {
return nil, errStmtClosed
}
if c.retired() {
return nil, c.refusal()
}
if err := c.txEnded(); err != nil {
return nil, err
}
if s.rows != nil {
return nil, errors.New("sqlite: the rows of the statement are still open")
}
if err := s.prepareAgain(); err != nil {
return nil, err
}
if err := ctx.Err(); err != nil {
return nil, err
}
if err := s.bind(args); err != nil {
return nil, err
}
if err := c.beginWrite(ctx, s.readOnly); err != nil {
return nil, err
}
stop, err := c.watch(ctx)
if err != nil {
c.endWrite()
return nil, err
}
row, err := s.s.Step()
// Also when it failed: SQLite prepares a PRAGMA again as it steps it,
// and sets the value as it does.
if s.changesConn {
if err != nil || !row {
// An ATTACH has no row: it is done, and DETACH may run.
s.s.Reset()
if aerr := c.syncAttached(); err == nil {
err = aerr
}
}
c.changed()
}
if err != nil {
stop()
s.s.Reset()
c.endWrite()
return nil, ctxErr(ctx, err)
}
s.columns()
r := &rows{s: s, ctx: ctx, stop: stop, first: true, done: !row}
s.rows = r
if !row {
r.end()
}
return r, nil
}
// bind gives each parameter of the statement its argument, and refuses
// arguments that leave one out, so that the statement runs with the values
// of this call alone. A bind that fails leaves some parameters with the
// values of before, and the statement does not run.
//
// A statement SQLite never prepared again is not cleared first: in SQLite
// 3.54.1 sqlite3_clear_bindings makes SQLite prepare the statement again at
// its next step whenever its plan looked at the value of a parameter, even
// for the same values, where binding a parameter does that only when the new
// value calls for another plan. It first lets go of the text and BLOB of the
// last bind (letGo), which binding a number over them would keep.
//
// A statement SQLite prepared again is cleared first. 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, such as one a partial index compares (fixed in
// SQLite after 3.54.1, check-in 836eec040f). Binding a new value over such a
// mark would run the plan made for the old value. Clearing makes SQLite
// prepare it again for the new values, as it did before.
func (s *stmt) bind(args []driver.NamedValue) error {
if s.s.PreparedAgain() {
if err := s.s.ClearBindings(); err != nil {
return err
}
s.held = s.held[:0]
} else if err := s.letGo(); err != nil {
return err
}
named := false
for _, a := range args {
named = named || a.Name != ""
}
if !named && len(args) < s.nparams {
// SQLite would read the parameters left over as NULL.
return fmt.Errorf("sqlite: %d arguments for %d parameters", len(args), s.nparams)
}
// bound marks what the arguments bind when some have names: SQLite would
// read a parameter left out as NULL, and keep the last of two arguments
// for one parameter. Without names each argument has a number of its
// own.
var small [64]bool
var bound []bool
if named {
bound = small[:]
if s.nparams > len(small) {
bound = make([]bool, s.nparams)
}
}
for _, a := range args {
i := a.Ordinal
if a.Name != "" {
i = s.paramIndex(a.Name)
if i == 0 {
return fmt.Errorf("sqlite: no parameter named %s", a.Name)
}
} else if i > s.nparams {
return fmt.Errorf("sqlite: %d arguments for %d parameters", len(args), s.nparams)
}
if bound != nil {
if bound[i-1] {
return fmt.Errorf("sqlite: two arguments for parameter %s", s.param(i))
}
bound[i-1] = true
}
var err error
switch v := a.Value.(type) {
case nil:
err = s.s.BindNull(i)
case int64:
err = s.s.BindInt64(i, v)
case float64:
err = s.s.BindDouble(i, v)
case bool:
var n int64
if v {
n = 1
}
err = s.s.BindInt64(i, n)
case []byte:
if v == nil {
err = s.s.BindNull(i) // as mattn/go-sqlite3 does
} else {
s.held = append(s.held, i)
err = s.s.BindBlob(i, v)
}
case string:
s.held = append(s.held, i)
err = s.s.BindText(i, v)
case time.Time:
s.held = append(s.held, i)
err = s.s.BindText(i, v.Format(timeFormat))
default:
return fmt.Errorf("sqlite: cannot bind %T", v)
}
if err != nil {
return err
}
}
if bound != nil {
return s.allBound(bound)
}
return nil
}
// param names parameter i in an error: by its name, or its number.
func (s *stmt) param(i int) string {
if n := s.s.ParamName(i); n != "" {
return n
}
return strconv.Itoa(i)
}
// allBound says each parameter has an argument, given what bound marks. One
// name used twice in the SQL is one parameter. A number up to the largest
// needs an argument even when the SQL skips it (1 in "SELECT ?2, :x"), as
// it does with no names.
func (s *stmt) allBound(bound []bool) error {
for i := range s.nparams {
if !bound[i] {
return fmt.Errorf("sqlite: no argument for parameter %s", s.param(i+1))
}
}
return nil
}
// paramIndex finds the parameter of a name given without its prefix.
func (s *stmt) paramIndex(name string) int {
for i := 1; i <= s.nparams; i++ {
n := s.s.ParamName(i)
if len(n) > 1 && n[1:] == name {
return i
}
}
return 0
}
// watch interrupts the statement of the connection when ctx is done, until
// stop is called. stop waits for an interrupt that has started, so that it
// never reaches a connection that is closed or runs another statement.
// When ctx is already done it gives the error of ctx, and the statement must
// not step: SQLite forgets an interrupt that comes before a statement starts.
// A cancel that comes while the step starts may still let the statement
// finish, as sqlite3_interrupt says.
//
// A ctx with the mark of queuehook.NoInterrupt (a statement of the queue)
// still stops the statement before it starts, and nothing after.
func (c *conn) watch(ctx context.Context) (func(), error) {
if ctx.Done() == nil {
return func() {}, nil
}
if err := ctx.Err(); err != nil {
return nil, err
}
if queuehook.Uninterrupted(ctx) {
return func() {}, nil
}
done := make(chan struct{})
stop := context.AfterFunc(ctx, func() {
c.c.Interrupt()
close(done)
})
return func() {
if !stop() {
<-done
}
}, nil
}
// ctxErr is the error of the context when it ended the statement, or its
// wait for a lock: SQLite then says the file is locked.
func ctxErr(ctx context.Context, err error) error {
var e *csqlite.Error
// SQLITE_INTERRUPT, and SQLITE_BUSY itself: SQLITE_BUSY_SNAPSHOT and
// the like are not the end of a wait.
if errors.As(err, &e) && (e.Code() == 9 || e.ExtendedCode() == 5) && ctx.Err() != nil {
return ctx.Err()
}
return err
}
type result struct{ id, n int64 }
func (r *result) LastInsertId() (int64, error) { return r.id, nil }
func (r *result) RowsAffected() (int64, error) { return r.n, nil }
type rows struct {
s *stmt
ctx context.Context
stop func()
// first says query stepped to the first row and NextRow has not yet
// given it.
first bool
done bool
close bool
}
// end stops watching the context once the statement has ended, so that no
// interrupt reaches a later statement of the connection.
func (r *rows) end() {
r.done = true
r.stop()
r.stop = func() {}
}
// What a statement and rows answer once they are closed, by their own Close
// or by that of their connection.
var (
errStmtClosed = errors.New("sqlite: the statement is closed")
errRowsClosed = errors.New("sqlite: the rows are closed")
)
var (
_ driver.Rows = (*rows)(nil)
_ driver.RowsColumnTypeDatabaseTypeName = (*rows)(nil)
)
// Columns gives a copy: database/sql hands the slice to its caller, and the
// statement keeps its own for its next rows.
func (r *rows) Columns() []string { return slices.Clone(r.s.cols) }
func (r *rows) ColumnTypeDatabaseTypeName(i int) string { return r.s.decl[i] }
func (r *rows) Close() error {
if r.close {
return nil
}
r.close = true
r.stop()
r.s.rows = nil
err := r.s.s.Reset()
r.s.c.endWrite()
if r.s.once {
if ferr := r.s.Close(); err == nil {
err = ferr
}
} else if r.s.kept != "" {
if kerr := r.s.c.keepQuery(r.s, err); err == nil {
err = kerr
}
}
if r.done {
return nil // Next already gave the error of the statement
}
return r.s.c.noteErr(err)
}
// NextRow steps to the next row.
func (r *rows) NextRow() error {
if r.close {
return errRowsClosed
}
if r.first {
r.first = false
if r.done {
return io.EOF
}
return nil
}
if r.done {
return io.EOF
}
row, err := r.s.s.Step()
if err != nil {
r.end()
return r.s.c.noteErr(ctxErr(r.ctx, err))
}
if !row {
r.end()
return io.EOF
}
return nil
}
// Next is NextRow and the values of the row, for database/sql before Go
// 1.27 calls ScanColumn.
func (r *rows) Next(dest []driver.Value) error {
if err := r.NextRow(); err != nil {
return err
}
for i := range dest {
v, err := r.value(i)
if err != nil {
return err
}
dest[i] = v
}
return nil
}
// value is column i of the row as a driver.Value. It fails when SQLite has
// no memory to give a text or a blob.
func (r *rows) value(i int) (driver.Value, error) {
if r.close {
return nil, errRowsClosed
}
s := r.s.s
switch s.ColumnType(i) {
case csqlite.TypeInteger:
v := s.ColumnInt64(i)
if r.isTime(i) {
return time.Unix(v, 0).UTC(), nil
}
return v, nil
case csqlite.TypeFloat:
return s.ColumnDouble(i), nil
case csqlite.TypeText:
v, err := s.ColumnText(i)
if err != nil {
return nil, r.s.c.noteErr(err)
}
if r.isTime(i) {
if t, ok := parseTime(v); ok {
return t, nil
}
}
return v, nil
case csqlite.TypeBlob:
b, err := s.ColumnBlob(i)
if err != nil {
return nil, r.s.c.noteErr(err)
}
if b == nil {
b = []byte{}
}
return b, nil
}
return nil, nil
}
func (r *rows) isTime(i int) bool { return r.s.isTime[i] }