-
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathstmt.go
More file actions
500 lines (443 loc) · 11.2 KB
/
stmt.go
File metadata and controls
500 lines (443 loc) · 11.2 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
// Copyright 2025 The Sqlite Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package sqlite // import "modernc.org/sqlite"
import (
"context"
"database/sql/driver"
"sync/atomic"
"unsafe"
"modernc.org/libc"
sqlite3 "modernc.org/sqlite/lib"
)
type stmt struct {
c *conn
psql uintptr
pstmt uintptr // The cached SQLite statement handle
}
func newStmt(c *conn, sql string) (*stmt, error) {
p, err := libc.CString(sql)
if err != nil {
return nil, err
}
s := &stmt{c: c, psql: p}
// Attempt to prepare the statement immediately
// We make a copy of the pointer because prepareV2 advances it
psql := p
pstmt, err := c.prepareV2(&psql)
if err != nil {
c.free(p)
return nil, err
}
// Check if there is trailing SQL (indicating a script/multi-statement)
// If *psql (the tail) is 0, we consumed the whole string.
hasTail := *(*byte)(unsafe.Pointer(psql)) != 0
if pstmt != 0 && !hasTail {
// Optimization: Single statement. Cache it.
s.pstmt = pstmt
return s, nil
}
// It is either a script (hasTail) or a comment-only string (pstmt==0).
// For scripts: Finalize now. We will re-parse iteratively in Exec/Query
// to handle the multiple statements correctly using the existing loop logic.
if pstmt != 0 {
if err := c.finalize(pstmt); err != nil {
c.free(p)
return nil, err
}
}
return s, nil
}
// Close closes the statement.
//
// As of Go 1.1, a Stmt will not be closed if it's in use by any queries.
func (s *stmt) Close() (err error) {
if s.pstmt != 0 {
if e := s.c.finalize(s.pstmt); e != nil {
err = e
}
s.pstmt = 0
}
if s.psql != 0 {
s.c.free(s.psql)
s.psql = 0
}
return err
}
// Exec executes a query that doesn't return rows, such as an INSERT or UPDATE.
//
// Deprecated: Drivers should implement StmtExecContext instead (or
// additionally).
func (s *stmt) Exec(args []driver.Value) (driver.Result, error) { //TODO StmtExecContext
return s.exec(context.Background(), toNamedValues(args))
}
// toNamedValues converts []driver.Value to []driver.NamedValue
func toNamedValues(vals []driver.Value) (r []driver.NamedValue) {
r = make([]driver.NamedValue, len(vals))
for i, val := range vals {
r[i] = driver.NamedValue{Value: val, Ordinal: i + 1}
}
return r
}
func (s *stmt) exec(ctx context.Context, args []driver.NamedValue) (r driver.Result, err error) {
var pstmt uintptr
var done int32
if ctx != nil {
if ctxDone := ctx.Done(); ctxDone != nil {
select {
case <-ctxDone:
return nil, ctx.Err()
default:
}
defer interruptOnDone(ctx, s.c, &done)()
}
}
defer func() {
if ctx != nil && atomic.LoadInt32(&done) != 0 {
r, err = nil, ctx.Err()
}
if pstmt != 0 {
// ensure stmt finalized.
e := s.c.finalize(pstmt)
if err == nil && e != nil {
// prioritize original
// returned error.
err = e
}
}
}()
// OPTIMIZED PATH: Single Cached Statement
if s.pstmt != 0 {
err = func() error {
// Bind
n, err := s.c.bindParameterCount(s.pstmt)
if err != nil {
return err
}
if n != 0 {
allocs, err := s.c.bind(s.pstmt, n, args)
if err != nil {
return err
}
// Free allocations after step
if len(allocs) != 0 {
defer func() { s.c.freeAllocs(allocs) }()
}
}
// Step
rc, err := s.c.step(s.pstmt)
if err != nil {
return err
}
// Handle Result
switch rc & 0xff {
case sqlite3.SQLITE_DONE:
r, err = newResult(s.c)
case sqlite3.SQLITE_ROW:
// Step to completion, matching C sqlite3_exec()
// semantics. Required for DML RETURNING correctness;
// also drains SELECT results if passed to Exec.
for rc&0xff == sqlite3.SQLITE_ROW {
if atomic.LoadInt32(&done) != 0 {
return ctx.Err()
}
rc, err = s.c.step(s.pstmt)
if err != nil {
return err
}
}
if rc&0xff != sqlite3.SQLITE_DONE {
return s.c.errstr(int32(rc))
}
r, err = newResult(s.c)
default:
return s.c.errstr(int32(rc))
}
return err
}()
// RESET (Crucial: Do not finalize)
// We must reset the VM to allow reuse.
// We also clear bindings to prevent leaking memory or state to next call.
if resetErr := s.c.reset(s.pstmt); resetErr != nil && err == nil {
err = resetErr
}
if clearErr := s.c.clearBindings(s.pstmt); clearErr != nil && err == nil {
err = clearErr
}
return r, err
}
// FALLBACK PATH: Multi-statement script
for psql := s.psql; *(*byte)(unsafe.Pointer(psql)) != 0 && atomic.LoadInt32(&done) == 0; {
if pstmt, err = s.c.prepareV2(&psql); err != nil {
return nil, err
}
if pstmt == 0 {
continue
}
err = func() error {
n, err := s.c.bindParameterCount(pstmt)
if err != nil {
return err
}
if n != 0 {
allocs, err := s.c.bind(pstmt, n, args)
if err != nil {
return err
}
if len(allocs) != 0 {
defer func() { s.c.freeAllocs(allocs) }()
}
}
rc, err := s.c.step(pstmt)
if err != nil {
return err
}
switch rc & 0xff {
case sqlite3.SQLITE_DONE:
r, err = newResult(s.c)
case sqlite3.SQLITE_ROW:
// Step to completion, matching C sqlite3_exec()
// semantics. Required for DML RETURNING correctness;
// also drains SELECT results if passed to Exec.
for rc&0xff == sqlite3.SQLITE_ROW {
if atomic.LoadInt32(&done) != 0 {
return ctx.Err()
}
rc, err = s.c.step(pstmt)
if err != nil {
return err
}
}
if rc&0xff != sqlite3.SQLITE_DONE {
return s.c.errstr(int32(rc))
}
r, err = newResult(s.c)
default:
return s.c.errstr(int32(rc))
}
return err
}()
e := s.c.finalize(pstmt)
pstmt = 0 // done with
if err == nil && e != nil {
// prioritize original
// returned error.
err = e
}
if err != nil {
return nil, err
}
}
return r, err
}
// NumInput returns the number of placeholder parameters.
//
// If NumInput returns >= 0, the sql package will sanity check argument counts
// from callers and return errors to the caller before the statement's Exec or
// Query methods are called.
//
// NumInput may also return -1, if the driver doesn't know its number of
// placeholders. In that case, the sql package will not sanity check Exec or
// Query argument counts.
func (s *stmt) NumInput() (n int) {
return -1
}
// Query executes a query that may return rows, such as a
// SELECT.
//
// Deprecated: Drivers should implement StmtQueryContext instead (or
// additionally).
func (s *stmt) Query(args []driver.Value) (driver.Rows, error) { //TODO StmtQueryContext
return s.query(context.Background(), toNamedValues(args))
}
func (s *stmt) query(ctx context.Context, args []driver.NamedValue) (r driver.Rows, err error) {
var pstmt uintptr
var done int32
if ctx != nil {
if ctxDone := ctx.Done(); ctxDone != nil {
select {
case <-ctxDone:
return nil, ctx.Err()
default:
}
defer interruptOnDone(ctx, s.c, &done)()
}
}
defer func() {
if ctx != nil && atomic.LoadInt32(&done) != 0 {
if r != nil {
r.Close()
}
r, err = nil, ctx.Err()
} else if r == nil && err == nil {
r, err = newRows(s.c, pstmt, nil, true)
}
if pstmt != 0 {
// ensure stmt finalized.
e := s.c.finalize(pstmt)
if err == nil && e != nil {
// prioritize original
// returned error.
err = e
}
}
}()
// OPTIMIZED PATH: Single Cached Statement
if s.pstmt != 0 {
var allocs []uintptr
// Bind
n, err := s.c.bindParameterCount(s.pstmt)
if err != nil {
return nil, err
}
if n != 0 {
if allocs, err = s.c.bind(s.pstmt, n, args); err != nil {
return nil, err
}
}
// Step
rc, err := s.c.step(s.pstmt)
if err != nil {
// On error, we must free allocs manually because 'newRows' won't take ownership
s.c.freeAllocs(allocs)
s.c.reset(s.pstmt)
s.c.clearBindings(s.pstmt)
return nil, err
}
// Handle Result
switch rc & 0xff {
case sqlite3.SQLITE_ROW:
// Pass reuseStmt=true
if r, err = newRows(s.c, s.pstmt, &allocs, false); err != nil {
s.c.reset(s.pstmt)
s.c.clearBindings(s.pstmt)
return nil, err
}
r.(*rows).reuseStmt = true
return r, nil
case sqlite3.SQLITE_DONE:
// No rows. Reset immediately.
// We still return a rows object (empty), but we can reset the stmt now
// because the empty rows object won't call step() again.
// However, standard newRows behavior expects a valid stmt to get columns.
// Let's rely on newRows to read columns, then it returns.
// Actually, if we pass reuseStmt=true to an empty set,
// rows.Close() will eventually reset it.
if r, err = newRows(s.c, s.pstmt, &allocs, true); err != nil {
s.c.reset(s.pstmt)
s.c.clearBindings(s.pstmt)
return nil, err
}
r.(*rows).reuseStmt = true
return r, nil
default:
// Error case
s.c.freeAllocs(allocs)
s.c.reset(s.pstmt)
s.c.clearBindings(s.pstmt)
return nil, s.c.errstr(int32(rc))
}
}
// FALLBACK PATH: Multi-statement script
for psql := s.psql; *(*byte)(unsafe.Pointer(psql)) != 0 && atomic.LoadInt32(&done) == 0; {
if pstmt, err = s.c.prepareV2(&psql); err != nil {
if r != nil {
r.Close()
}
return nil, err
}
if pstmt == 0 {
continue
}
err = func() (err error) {
var allocs []uintptr
defer func() { s.c.freeAllocs(allocs) }()
n, err := s.c.bindParameterCount(pstmt)
if err != nil {
return err
}
if n != 0 {
if allocs, err = s.c.bind(pstmt, n, args); err != nil {
return err
}
}
rc, err := s.c.step(pstmt)
if err != nil {
return err
}
switch rc & 0xff {
case sqlite3.SQLITE_ROW:
if r != nil {
r.Close()
}
if r, err = newRows(s.c, pstmt, &allocs, false); err != nil {
return err
}
pstmt = 0
return nil
case sqlite3.SQLITE_DONE:
if r == nil {
if r, err = newRows(s.c, pstmt, &allocs, true); err != nil {
return err
}
pstmt = 0
return nil
}
// nop
default:
return s.c.errstr(int32(rc))
}
if *(*byte)(unsafe.Pointer(psql)) == 0 {
if r != nil {
r.Close()
}
if r, err = newRows(s.c, pstmt, &allocs, true); err != nil {
return err
}
pstmt = 0
}
return nil
}()
e := s.c.finalize(pstmt)
pstmt = 0 // done with
if err == nil && e != nil {
// prioritize original
// returned error.
err = e
}
if err != nil {
if r != nil {
r.Close() // r is from a previous iteration; clean up since we won't return it
}
return nil, err
}
}
return r, err
}
// ExecContext implements driver.StmtExecContext
func (s *stmt) ExecContext(ctx context.Context, args []driver.NamedValue) (dr driver.Result, err error) {
if dmesgs {
defer func() {
dmesg("stmt %p, ctx %p, args %v: (driver.Result %p, err %v)", s, ctx, args, dr, err)
}()
}
return s.exec(ctx, args)
}
// QueryContext implements driver.StmtQueryContext
func (s *stmt) QueryContext(ctx context.Context, args []driver.NamedValue) (dr driver.Rows, err error) {
if dmesgs {
defer func() {
dmesg("stmt %p, ctx %p, args %v: (driver.Rows %p, err %v)", s, ctx, args, dr, err)
}()
}
return s.query(ctx, args)
}
// C documentation
//
// int sqlite3_clear_bindings(sqlite3_stmt*);
func (c *conn) clearBindings(pstmt uintptr) error {
if rc := sqlite3.Xsqlite3_clear_bindings(c.tls, pstmt); rc != sqlite3.SQLITE_OK {
return c.errstr(rc)
}
return nil
}