Debian Codegraph @

sqlite3.go

raw
1 // Copyright (C) 2019 Yasuhiro Matsumoto <[email protected]>.
2 // Copyright (C) 2018 G.J.R. Timmer <[email protected]>.
3 //
4 // Use of this source code is governed by an MIT-style
5 // license that can be found in the LICENSE file.
6
7 //go:build cgo
8 // +build cgo
9
10 package sqlite3
11
12 /*
13 #cgo CFLAGS: -std=gnu99
14 #cgo CFLAGS: -DSQLITE_ENABLE_RTREE
15 #cgo CFLAGS: -DSQLITE_THREADSAFE=1
16 #cgo CFLAGS: -DHAVE_USLEEP=1
17 #cgo CFLAGS: -DSQLITE_ENABLE_FTS3
18 #cgo CFLAGS: -DSQLITE_ENABLE_FTS3_PARENTHESIS
19 #cgo CFLAGS: -DSQLITE_TRACE_SIZE_LIMIT=15
20 #cgo CFLAGS: -DSQLITE_OMIT_DEPRECATED
21 #cgo CFLAGS: -DSQLITE_DEFAULT_WAL_SYNCHRONOUS=1
22 #cgo CFLAGS: -DSQLITE_ENABLE_UPDATE_DELETE_LIMIT
23 #cgo CFLAGS: -Wno-deprecated-declarations
24 #cgo openbsd CFLAGS: -I/usr/local/include
25 #cgo openbsd LDFLAGS: -L/usr/local/lib
26 #ifndef USE_LIBSQLITE3
27 #include "sqlite3-binding.h"
28 #else
29 #include <sqlite3.h>
30 #endif
31 #include <stdlib.h>
32 #include <string.h>
33
34 #ifdef __CYGWIN__
35 # include <errno.h>
36 #endif
37
38 #ifndef SQLITE_OPEN_READWRITE
39 # define SQLITE_OPEN_READWRITE 0
40 #endif
41
42 #ifndef SQLITE_OPEN_FULLMUTEX
43 # define SQLITE_OPEN_FULLMUTEX 0
44 #endif
45
46 #ifndef SQLITE_DETERMINISTIC
47 # define SQLITE_DETERMINISTIC 0
48 #endif
49
50 #if defined(HAVE_PREAD64) && defined(HAVE_PWRITE64)
51 # undef USE_PREAD
52 # undef USE_PWRITE
53 # define USE_PREAD64 1
54 # define USE_PWRITE64 1
55 #elif defined(HAVE_PREAD) && defined(HAVE_PWRITE)
56 # undef USE_PREAD
57 # undef USE_PWRITE
58 # define USE_PREAD64 1
59 # define USE_PWRITE64 1
60 #endif
61
62 static int
63 _sqlite3_open_v2(const char *filename, sqlite3 **ppDb, int flags, const char *zVfs) {
64 #ifdef SQLITE_OPEN_URI
65 return sqlite3_open_v2(filename, ppDb, flags | SQLITE_OPEN_URI, zVfs);
66 #else
67 return sqlite3_open_v2(filename, ppDb, flags, zVfs);
68 #endif
69 }
70
71 static int
72 _sqlite3_bind_text(sqlite3_stmt *stmt, int n, char *p, sqlite3_uint64 np) {
73 return sqlite3_bind_text64(stmt, n, p, np, SQLITE_TRANSIENT, SQLITE_UTF8);
74 }
75
76 static int
77 _sqlite3_bind_blob(sqlite3_stmt *stmt, int n, void *p, sqlite3_uint64 np) {
78 return sqlite3_bind_blob64(stmt, n, p, np, SQLITE_TRANSIENT);
79 }
80
81 typedef struct {
82 int typ;
83 sqlite3_int64 i64;
84 double f64;
85 const void *ptr;
86 int n;
87 } sqlite3_go_col;
88
89 static void
90 _sqlite3_column_values(sqlite3_stmt *stmt, int ncol, sqlite3_go_col *cols) {
91 for (int i = 0; i < ncol; i++) {
92 sqlite3_go_col *col = &cols[i];
93 col->typ = sqlite3_column_type(stmt, i);
94 col->ptr = 0;
95 col->n = 0;
96 switch (col->typ) {
97 case SQLITE_INTEGER:
98 col->i64 = sqlite3_column_int64(stmt, i);
99 break;
100 case SQLITE_FLOAT:
101 col->f64 = sqlite3_column_double(stmt, i);
102 break;
103 case SQLITE_BLOB:
104 col->ptr = sqlite3_column_blob(stmt, i);
105 col->n = sqlite3_column_bytes(stmt, i);
106 break;
107 case SQLITE_TEXT:
108 col->ptr = sqlite3_column_text(stmt, i);
109 col->n = sqlite3_column_bytes(stmt, i);
110 break;
111 default:
112 break;
113 }
114 }
115 }
116
117 #include <stdio.h>
118 #include <stdint.h>
119
120 static int
121 _sqlite3_exec(sqlite3* db, const char* pcmd, long long* rowid, long long* changes)
122 {
123 int rv = sqlite3_exec(db, pcmd, 0, 0, 0);
124 *rowid = (long long) sqlite3_last_insert_rowid(db);
125 *changes = (long long) sqlite3_changes(db);
126 return rv;
127 }
128
129 // Combined reset + clear_bindings in a single C call to reduce CGO crossings.
130 static int
131 _sqlite3_reset_clear(sqlite3_stmt* stmt)
132 {
133 int rv = sqlite3_reset(stmt);
134 sqlite3_clear_bindings(stmt);
135 return rv;
136 }
137
138 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
139 extern int _sqlite3_step_blocking(sqlite3_stmt *stmt);
140 extern int _sqlite3_step_row_blocking(sqlite3_stmt* stmt, long long* rowid, long long* changes);
141 extern int _sqlite3_prepare_v2_blocking(sqlite3 *db, const char *zSql, int nBytes, sqlite3_stmt **ppStmt, const char **pzTail);
142 #endif
143
144 // Combined prepare+step+finalize for simple exec without parameters.
145 // Reduces CGO crossings from ~6 to 1 for the common no-args exec case.
146 static int
147 _sqlite3_exec_no_args(sqlite3* db, const char* zSql, int nBytes, long long* rowid, long long* changes, const char** pzTail)
148 {
149 sqlite3_stmt *stmt = 0;
150 const char *tail = 0;
151 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
152 int rv = _sqlite3_prepare_v2_blocking(db, zSql, nBytes, &stmt, &tail);
153 #else
154 int rv = sqlite3_prepare_v2(db, zSql, nBytes, &stmt, &tail);
155 #endif
156 if (rv != SQLITE_OK) {
157 *pzTail = 0;
158 return rv;
159 }
160 if (stmt == 0) {
161 // Empty statement
162 *rowid = 0;
163 *changes = 0;
164 *pzTail = tail;
165 return SQLITE_OK;
166 }
167 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
168 rv = _sqlite3_step_row_blocking(stmt, rowid, changes);
169 #else
170 rv = sqlite3_step(stmt);
171 *rowid = (long long) sqlite3_last_insert_rowid(db);
172 *changes = (long long) sqlite3_changes(db);
173 #endif
174 sqlite3_finalize(stmt);
175 *pzTail = tail;
176 return rv;
177 }
178
179 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
180
181 static int
182 _sqlite3_step_internal(sqlite3_stmt *stmt)
183 {
184 return _sqlite3_step_blocking(stmt);
185 }
186
187 static int
188 _sqlite3_step_row_internal(sqlite3_stmt* stmt, long long* rowid, long long* changes)
189 {
190 return _sqlite3_step_row_blocking(stmt, rowid, changes);
191 }
192
193 static int
194 _sqlite3_prepare_v2_internal(sqlite3 *db, const char *zSql, int nBytes, sqlite3_stmt **ppStmt, const char **pzTail)
195 {
196 return _sqlite3_prepare_v2_blocking(db, zSql, nBytes, ppStmt, pzTail);
197 }
198
199 #else
200 static int
201 _sqlite3_step_internal(sqlite3_stmt *stmt)
202 {
203 return sqlite3_step(stmt);
204 }
205
206 static int
207 _sqlite3_step_row_internal(sqlite3_stmt* stmt, long long* rowid, long long* changes)
208 {
209 int rv = sqlite3_step(stmt);
210 sqlite3* db = sqlite3_db_handle(stmt);
211 *rowid = (long long) sqlite3_last_insert_rowid(db);
212 *changes = (long long) sqlite3_changes(db);
213 return rv;
214 }
215
216 static int
217 _sqlite3_prepare_v2_internal(sqlite3 *db, const char *zSql, int nBytes, sqlite3_stmt **ppStmt, const char **pzTail)
218 {
219 return sqlite3_prepare_v2(db, zSql, nBytes, ppStmt, pzTail);
220 }
221 #endif
222
223 // Steps a statement once and reports the post-step column count and the
224 // cumulative re-prepare count, in a single CGO crossing. Used for the
225 // eager first step of cached statements: only after the first step is an
226 // expired statement guaranteed to have been re-prepared following a
227 // schema change, so only then do the column count and metadata describe
228 // the current schema.
229 static int
230 _sqlite3_step_columns(sqlite3_stmt* stmt, int* ncol, int* repreps)
231 {
232 int rv = _sqlite3_step_internal(stmt);
233 *ncol = sqlite3_column_count(stmt);
234 #ifdef SQLITE_STMTSTATUS_REPREPARE
235 *repreps = sqlite3_stmt_status(stmt, SQLITE_STMTSTATUS_REPREPARE, 0);
236 #else
237 *repreps = -1;
238 #endif
239 return rv;
240 }
241
242 void _sqlite3_result_text(sqlite3_context* ctx, const char* s, int n) {
243 sqlite3_result_text(ctx, s, n, &free);
244 }
245
246 void _sqlite3_result_blob(sqlite3_context* ctx, const void* b, int l) {
247 sqlite3_result_blob(ctx, b, l, SQLITE_TRANSIENT);
248 }
249
250
251 int _sqlite3_create_function(
252 sqlite3 *db,
253 const char *zFunctionName,
254 int nArg,
255 int eTextRep,
256 uintptr_t pApp,
257 void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
258 void (*xStep)(sqlite3_context*,int,sqlite3_value**),
259 void (*xFinal)(sqlite3_context*)
260 ) {
261 return sqlite3_create_function(db, zFunctionName, nArg, eTextRep, (void*) pApp, xFunc, xStep, xFinal);
262 }
263
264 void callbackTrampoline(sqlite3_context*, int, sqlite3_value**);
265 void stepTrampoline(sqlite3_context*, int, sqlite3_value**);
266 void doneTrampoline(sqlite3_context*);
267
268 int compareTrampoline(void*, int, char*, int, char*);
269 int commitHookTrampoline(void*);
270 void rollbackHookTrampoline(void*);
271 void updateHookTrampoline(void*, int, char*, char*, sqlite3_int64);
272
273 int authorizerTrampoline(void*, int, char*, char*, char*, char*);
274
275 #ifdef SQLITE_LIMIT_WORKER_THREADS
276 # define _SQLITE_HAS_LIMIT
277 # define SQLITE_LIMIT_LENGTH 0
278 # define SQLITE_LIMIT_SQL_LENGTH 1
279 # define SQLITE_LIMIT_COLUMN 2
280 # define SQLITE_LIMIT_EXPR_DEPTH 3
281 # define SQLITE_LIMIT_COMPOUND_SELECT 4
282 # define SQLITE_LIMIT_VDBE_OP 5
283 # define SQLITE_LIMIT_FUNCTION_ARG 6
284 # define SQLITE_LIMIT_ATTACHED 7
285 # define SQLITE_LIMIT_LIKE_PATTERN_LENGTH 8
286 # define SQLITE_LIMIT_VARIABLE_NUMBER 9
287 # define SQLITE_LIMIT_TRIGGER_DEPTH 10
288 # define SQLITE_LIMIT_WORKER_THREADS 11
289 # else
290 # define SQLITE_LIMIT_WORKER_THREADS 11
291 #endif
292
293 static int _sqlite3_limit(sqlite3* db, int limitId, int newLimit) {
294 #ifndef _SQLITE_HAS_LIMIT
295 return -1;
296 #else
297 return sqlite3_limit(db, limitId, newLimit);
298 #endif
299 }
300
301 #if SQLITE_VERSION_NUMBER < 3012000
302 static int sqlite3_system_errno(sqlite3 *db) {
303 return 0;
304 }
305 #endif
306 */
307 import "C"
308 import (
309 "context"
310 "database/sql"
311 "database/sql/driver"
312 "errors"
313 "fmt"
314 "io"
315 "math"
316 "net/url"
317 "reflect"
318 "runtime"
319 "strconv"
320 "strings"
321 "sync"
322 "syscall"
323 "time"
324 "unsafe"
325 )
326
327 // SQLiteTimestampFormats is timestamp formats understood by both this module
328 // and SQLite. The first format in the slice will be used when saving time
329 // values into the database. When parsing a string from a timestamp or datetime
330 // column, the formats are tried in order.
331 var SQLiteTimestampFormats = []string{
332 // By default, store timestamps with whatever timezone they come with.
333 // When parsed, they will be returned with the same timezone.
334 "2006-01-02 15:04:05.999999999-07:00",
335 "2006-01-02T15:04:05.999999999-07:00",
336 "2006-01-02 15:04:05.999999999",
337 "2006-01-02T15:04:05.999999999",
338 "2006-01-02 15:04:05",
339 "2006-01-02T15:04:05",
340 "2006-01-02 15:04",
341 "2006-01-02T15:04",
342 "2006-01-02",
343 }
344
345 const (
346 columnDate string = "date"
347 columnDatetime string = "datetime"
348 columnTimestamp string = "timestamp"
349 )
350
351 // This variable can be replaced with -ldflags like below:
352 // go build -ldflags="-X 'github.com/mattn/go-sqlite3.driverName=my-sqlite3'"
353 var driverName = "sqlite3"
354
355 func init() {
356 if driverName != "" {
357 sql.Register(driverName, &SQLiteDriver{})
358 }
359 }
360
361 // Version returns SQLite library version information.
362 func Version() (libVersion string, libVersionNumber int, sourceID string) {
363 libVersion = C.GoString(C.sqlite3_libversion())
364 libVersionNumber = int(C.sqlite3_libversion_number())
365 sourceID = C.GoString(C.sqlite3_sourceid())
366 return libVersion, libVersionNumber, sourceID
367 }
368
369 const (
370 // used by authorizer and pre_update_hook
371 SQLITE_DELETE = C.SQLITE_DELETE
372 SQLITE_INSERT = C.SQLITE_INSERT
373 SQLITE_UPDATE = C.SQLITE_UPDATE
374
375 // used by authorzier - as return value
376 SQLITE_OK = C.SQLITE_OK
377 SQLITE_IGNORE = C.SQLITE_IGNORE
378 SQLITE_DENY = C.SQLITE_DENY
379
380 // different actions query tries to do - passed as argument to authorizer
381 SQLITE_CREATE_INDEX = C.SQLITE_CREATE_INDEX
382 SQLITE_CREATE_TABLE = C.SQLITE_CREATE_TABLE
383 SQLITE_CREATE_TEMP_INDEX = C.SQLITE_CREATE_TEMP_INDEX
384 SQLITE_CREATE_TEMP_TABLE = C.SQLITE_CREATE_TEMP_TABLE
385 SQLITE_CREATE_TEMP_TRIGGER = C.SQLITE_CREATE_TEMP_TRIGGER
386 SQLITE_CREATE_TEMP_VIEW = C.SQLITE_CREATE_TEMP_VIEW
387 SQLITE_CREATE_TRIGGER = C.SQLITE_CREATE_TRIGGER
388 SQLITE_CREATE_VIEW = C.SQLITE_CREATE_VIEW
389 SQLITE_CREATE_VTABLE = C.SQLITE_CREATE_VTABLE
390 SQLITE_DROP_INDEX = C.SQLITE_DROP_INDEX
391 SQLITE_DROP_TABLE = C.SQLITE_DROP_TABLE
392 SQLITE_DROP_TEMP_INDEX = C.SQLITE_DROP_TEMP_INDEX
393 SQLITE_DROP_TEMP_TABLE = C.SQLITE_DROP_TEMP_TABLE
394 SQLITE_DROP_TEMP_TRIGGER = C.SQLITE_DROP_TEMP_TRIGGER
395 SQLITE_DROP_TEMP_VIEW = C.SQLITE_DROP_TEMP_VIEW
396 SQLITE_DROP_TRIGGER = C.SQLITE_DROP_TRIGGER
397 SQLITE_DROP_VIEW = C.SQLITE_DROP_VIEW
398 SQLITE_DROP_VTABLE = C.SQLITE_DROP_VTABLE
399 SQLITE_PRAGMA = C.SQLITE_PRAGMA
400 SQLITE_READ = C.SQLITE_READ
401 SQLITE_SELECT = C.SQLITE_SELECT
402 SQLITE_TRANSACTION = C.SQLITE_TRANSACTION
403 SQLITE_ATTACH = C.SQLITE_ATTACH
404 SQLITE_DETACH = C.SQLITE_DETACH
405 SQLITE_ALTER_TABLE = C.SQLITE_ALTER_TABLE
406 SQLITE_REINDEX = C.SQLITE_REINDEX
407 SQLITE_ANALYZE = C.SQLITE_ANALYZE
408 SQLITE_FUNCTION = C.SQLITE_FUNCTION
409 SQLITE_SAVEPOINT = C.SQLITE_SAVEPOINT
410 SQLITE_COPY = C.SQLITE_COPY
411 /*SQLITE_RECURSIVE = C.SQLITE_RECURSIVE*/
412 )
413
414 // Standard File Control Opcodes
415 // See: https://www.sqlite.org/c3ref/c_fcntl_begin_atomic_write.html
416 const (
417 SQLITE_FCNTL_LOCKSTATE = int(1)
418 SQLITE_FCNTL_GET_LOCKPROXYFILE = int(2)
419 SQLITE_FCNTL_SET_LOCKPROXYFILE = int(3)
420 SQLITE_FCNTL_LAST_ERRNO = int(4)
421 SQLITE_FCNTL_SIZE_HINT = int(5)
422 SQLITE_FCNTL_CHUNK_SIZE = int(6)
423 SQLITE_FCNTL_FILE_POINTER = int(7)
424 SQLITE_FCNTL_SYNC_OMITTED = int(8)
425 SQLITE_FCNTL_WIN32_AV_RETRY = int(9)
426 SQLITE_FCNTL_PERSIST_WAL = int(10)
427 SQLITE_FCNTL_OVERWRITE = int(11)
428 SQLITE_FCNTL_VFSNAME = int(12)
429 SQLITE_FCNTL_POWERSAFE_OVERWRITE = int(13)
430 SQLITE_FCNTL_PRAGMA = int(14)
431 SQLITE_FCNTL_BUSYHANDLER = int(15)
432 SQLITE_FCNTL_TEMPFILENAME = int(16)
433 SQLITE_FCNTL_MMAP_SIZE = int(18)
434 SQLITE_FCNTL_TRACE = int(19)
435 SQLITE_FCNTL_HAS_MOVED = int(20)
436 SQLITE_FCNTL_SYNC = int(21)
437 SQLITE_FCNTL_COMMIT_PHASETWO = int(22)
438 SQLITE_FCNTL_WIN32_SET_HANDLE = int(23)
439 SQLITE_FCNTL_WAL_BLOCK = int(24)
440 SQLITE_FCNTL_ZIPVFS = int(25)
441 SQLITE_FCNTL_RBU = int(26)
442 SQLITE_FCNTL_VFS_POINTER = int(27)
443 SQLITE_FCNTL_JOURNAL_POINTER = int(28)
444 SQLITE_FCNTL_WIN32_GET_HANDLE = int(29)
445 SQLITE_FCNTL_PDB = int(30)
446 SQLITE_FCNTL_BEGIN_ATOMIC_WRITE = int(31)
447 SQLITE_FCNTL_COMMIT_ATOMIC_WRITE = int(32)
448 SQLITE_FCNTL_ROLLBACK_ATOMIC_WRITE = int(33)
449 SQLITE_FCNTL_LOCK_TIMEOUT = int(34)
450 SQLITE_FCNTL_DATA_VERSION = int(35)
451 SQLITE_FCNTL_SIZE_LIMIT = int(36)
452 SQLITE_FCNTL_CKPT_DONE = int(37)
453 SQLITE_FCNTL_RESERVE_BYTES = int(38)
454 SQLITE_FCNTL_CKPT_START = int(39)
455 SQLITE_FCNTL_EXTERNAL_READER = int(40)
456 SQLITE_FCNTL_CKSM_FILE = int(41)
457 )
458
459 // SQLiteDriver implements driver.Driver.
460 type SQLiteDriver struct {
461 Extensions []string
462 ConnectHook func(*SQLiteConn) error
463 }
464
465 // SQLiteConn implements driver.Conn.
466 type SQLiteConn struct {
467 mu sync.Mutex
468 db *C.sqlite3
469 // activeRows identifies the cancellable Rows currently calling sqlite3_step.
470 // It is guarded by mu so a stale cancellation cannot interrupt later work.
471 activeRows *SQLiteRows
472 loc *time.Location
473 txlock string
474 funcs []*functionInfo
475 aggregators []*aggInfo
476 // Prepared-statement cache. The slice is allocated at Open with a
477 // fixed capacity equal to the configured cache size; cap bounds the
478 // cache, len is the live count, and entries are ordered LRU-first
479 // (index 0 is the oldest, the tail is most recently put). Access
480 // requires mu; stmtCacheEnabled is immutable after Open and is the
481 // only field safe to read without the lock.
482 stmtCache []*SQLiteStmt
483 stmtCacheEnabled bool
484 }
485
486 // SQLiteTx implements driver.Tx.
487 type SQLiteTx struct {
488 c *SQLiteConn
489 }
490
491 // SQLiteStmt implements driver.Stmt.
492 type SQLiteStmt struct {
493 mu sync.Mutex
494 c *SQLiteConn
495 s *C.sqlite3_stmt
496 t string
497 closed bool
498 cls bool // True if the statement was created by SQLiteConn.Query
499 namedParams map[string][3]int
500 cacheKey string
501 metadata *sqliteStmtMetadata
502 // repreps is the statement's cumulative re-prepare count observed
503 // at the last eager first step; a change means SQLite re-prepared
504 // the statement after a schema change and metadata must be rebuilt.
505 repreps C.int
506 }
507
508 type sqliteStmtMetadata struct {
509 cols []string
510 decltype []string
511 }
512
513 // SQLiteResult implements sql.Result.
514 type SQLiteResult struct {
515 id int64
516 changes int64
517 }
518
519 // SQLiteRows implements driver.Rows.
520 type SQLiteRows struct {
521 s *SQLiteStmt
522 nc int32 // Number of columns
523 cls bool // True if we need to close the parent statement in Close
524 cols []string
525 decltype []string
526 colvals *C.sqlite3_go_col
527 ctx context.Context // no better alternative to pass context into Next() method
528 stopCancellation func() bool
529 // pendingStep buffers the result of the eager first step taken for
530 // cached statements in query(); -1 when no step is buffered.
531 pendingStep C.int
532 closemu sync.Mutex
533 }
534
535 type functionInfo struct {
536 f reflect.Value
537 argConverters []callbackArgConverter
538 variadicConverter callbackArgConverter
539 retConverter callbackRetConverter
540 }
541
542 func (fi *functionInfo) Call(ctx *C.sqlite3_context, argv []*C.sqlite3_value) {
543 args, err := callbackConvertArgs(argv, fi.argConverters, fi.variadicConverter)
544 if err != nil {
545 callbackError(ctx, err)
546 return
547 }
548
549 ret := fi.f.Call(args)
550
551 if len(ret) == 2 && ret[1].Interface() != nil {
552 callbackError(ctx, ret[1].Interface().(error))
553 return
554 }
555
556 err = fi.retConverter(ctx, ret[0])
557 if err != nil {
558 callbackError(ctx, err)
559 return
560 }
561 }
562
563 type aggInfo struct {
564 constructor reflect.Value
565
566 // Active aggregator objects for aggregations in flight. The
567 // aggregators are indexed by a counter stored in the aggregation
568 // user data space provided by sqlite.
569 active map[int64]reflect.Value
570 next int64
571
572 stepArgConverters []callbackArgConverter
573 stepVariadicConverter callbackArgConverter
574
575 doneRetConverter callbackRetConverter
576 }
577
578 func (ai *aggInfo) agg(ctx *C.sqlite3_context) (int64, reflect.Value, error) {
579 aggIdx := (*int64)(C.sqlite3_aggregate_context(ctx, C.int(8)))
580 if *aggIdx == 0 {
581 *aggIdx = ai.next
582 ret := ai.constructor.Call(nil)
583 if len(ret) == 2 && ret[1].Interface() != nil {
584 return 0, reflect.Value{}, ret[1].Interface().(error)
585 }
586 if ret[0].IsNil() {
587 return 0, reflect.Value{}, errors.New("aggregator constructor returned nil state")
588 }
589 ai.next++
590 ai.active[*aggIdx] = ret[0]
591 }
592 return *aggIdx, ai.active[*aggIdx], nil
593 }
594
595 func (ai *aggInfo) Step(ctx *C.sqlite3_context, argv []*C.sqlite3_value) {
596 _, agg, err := ai.agg(ctx)
597 if err != nil {
598 callbackError(ctx, err)
599 return
600 }
601
602 args, err := callbackConvertArgs(argv, ai.stepArgConverters, ai.stepVariadicConverter)
603 if err != nil {
604 callbackError(ctx, err)
605 return
606 }
607
608 ret := agg.MethodByName("Step").Call(args)
609 if len(ret) == 1 && ret[0].Interface() != nil {
610 callbackError(ctx, ret[0].Interface().(error))
611 return
612 }
613 }
614
615 func (ai *aggInfo) Done(ctx *C.sqlite3_context) {
616 idx, agg, err := ai.agg(ctx)
617 if err != nil {
618 callbackError(ctx, err)
619 return
620 }
621 defer func() { delete(ai.active, idx) }()
622
623 ret := agg.MethodByName("Done").Call(nil)
624 if len(ret) == 2 && ret[1].Interface() != nil {
625 callbackError(ctx, ret[1].Interface().(error))
626 return
627 }
628
629 err = ai.doneRetConverter(ctx, ret[0])
630 if err != nil {
631 callbackError(ctx, err)
632 return
633 }
634 }
635
636 // Commit transaction.
637 func (tx *SQLiteTx) Commit() error {
638 _, err := tx.c.exec(context.Background(), "COMMIT", nil)
639 if err != nil {
640 // sqlite3 may leave the transaction open in this scenario.
641 // However, database/sql considers the transaction complete once we
642 // return from Commit() - we must clean up to honour its semantics.
643 // We don't know if the ROLLBACK is strictly necessary, but according
644 // to sqlite's docs, there is no harm in calling ROLLBACK unnecessarily.
645 tx.c.exec(context.Background(), "ROLLBACK", nil)
646 }
647 return err
648 }
649
650 // Rollback transaction.
651 func (tx *SQLiteTx) Rollback() error {
652 _, err := tx.c.exec(context.Background(), "ROLLBACK", nil)
653 return err
654 }
655
656 // RegisterCollation makes a Go function available as a collation.
657 //
658 // cmp receives two UTF-8 strings, a and b. The result should be 0 if
659 // a==b, -1 if a < b, and +1 if a > b.
660 //
661 // cmp must always return the same result given the same
662 // inputs. Additionally, it must have the following properties for all
663 // strings A, B and C: if A==B then B==A; if A==B and B==C then A==C;
664 // if A<B then B>A; if A<B and B<C then A<C.
665 //
666 // If cmp does not obey these constraints, sqlite3's behavior is
667 // undefined when the collation is used.
668 func (c *SQLiteConn) RegisterCollation(name string, cmp func(string, string) int) error {
669 handle := newHandle(c, cmp)
670 cname := C.CString(name)
671 defer C.free(unsafe.Pointer(cname))
672 rv := C.sqlite3_create_collation(c.db, cname, C.SQLITE_UTF8, handle, (*[0]byte)(unsafe.Pointer(C.compareTrampoline)))
673 if rv != C.SQLITE_OK {
674 return c.lastError()
675 }
676 return nil
677 }
678
679 // RegisterCommitHook sets the commit hook for a connection.
680 //
681 // If the callback returns non-zero the transaction will become a rollback.
682 //
683 // If there is an existing commit hook for this connection, it will be
684 // removed. If callback is nil the existing hook (if any) will be removed
685 // without creating a new one.
686 func (c *SQLiteConn) RegisterCommitHook(callback func() int) {
687 if callback == nil {
688 C.sqlite3_commit_hook(c.db, nil, nil)
689 } else {
690 C.sqlite3_commit_hook(c.db, (*[0]byte)(C.commitHookTrampoline), newHandle(c, callback))
691 }
692 }
693
694 // RegisterRollbackHook sets the rollback hook for a connection.
695 //
696 // If there is an existing rollback hook for this connection, it will be
697 // removed. If callback is nil the existing hook (if any) will be removed
698 // without creating a new one.
699 func (c *SQLiteConn) RegisterRollbackHook(callback func()) {
700 if callback == nil {
701 C.sqlite3_rollback_hook(c.db, nil, nil)
702 } else {
703 C.sqlite3_rollback_hook(c.db, (*[0]byte)(C.rollbackHookTrampoline), newHandle(c, callback))
704 }
705 }
706
707 // RegisterUpdateHook sets the update hook for a connection.
708 //
709 // The parameters to the callback are the operation (one of the constants
710 // SQLITE_INSERT, SQLITE_DELETE, or SQLITE_UPDATE), the database name, the
711 // table name, and the rowid.
712 //
713 // If there is an existing update hook for this connection, it will be
714 // removed. If callback is nil the existing hook (if any) will be removed
715 // without creating a new one.
716 func (c *SQLiteConn) RegisterUpdateHook(callback func(int, string, string, int64)) {
717 if callback == nil {
718 C.sqlite3_update_hook(c.db, nil, nil)
719 } else {
720 C.sqlite3_update_hook(c.db, (*[0]byte)(C.updateHookTrampoline), newHandle(c, callback))
721 }
722 }
723
724 // RegisterAuthorizer sets the authorizer for connection.
725 //
726 // The parameters to the callback are the operation (one of the constants
727 // SQLITE_INSERT, SQLITE_DELETE, or SQLITE_UPDATE), and 1 to 3 arguments,
728 // depending on operation. More details see:
729 // https://www.sqlite.org/c3ref/c_alter_table.html
730 func (c *SQLiteConn) RegisterAuthorizer(callback func(int, string, string, string) int) {
731 if callback == nil {
732 C.sqlite3_set_authorizer(c.db, nil, nil)
733 } else {
734 C.sqlite3_set_authorizer(c.db, (*[0]byte)(C.authorizerTrampoline), newHandle(c, callback))
735 }
736 }
737
738 // RegisterFunc makes a Go function available as a SQLite function.
739 //
740 // The Go function can have arguments of the following types: any
741 // numeric type except complex, bool, []byte, string and any.
742 // any arguments are given the direct translation of the SQLite data type:
743 // int64 for INTEGER, float64 for FLOAT, []byte for BLOB, string for TEXT.
744 //
745 // The function can additionally be variadic, as long as the type of
746 // the variadic argument is one of the above.
747 //
748 // If pure is true. SQLite will assume that the function's return
749 // value depends only on its inputs, and make more aggressive
750 // optimizations in its queries.
751 //
752 // See _example/go_custom_funcs for a detailed example.
753 func (c *SQLiteConn) RegisterFunc(name string, impl any, pure bool) error {
754 var fi functionInfo
755 fi.f = reflect.ValueOf(impl)
756 t := fi.f.Type()
757 if t.Kind() != reflect.Func {
758 return errors.New("Non-function passed to RegisterFunc")
759 }
760 if t.NumOut() != 1 && t.NumOut() != 2 {
761 return errors.New("SQLite functions must return 1 or 2 values")
762 }
763 if t.NumOut() == 2 && !t.Out(1).Implements(reflect.TypeOf((*error)(nil)).Elem()) {
764 return errors.New("Second return value of SQLite function must be error")
765 }
766
767 numArgs := t.NumIn()
768 if t.IsVariadic() {
769 numArgs--
770 }
771
772 for i := 0; i < numArgs; i++ {
773 conv, err := callbackArg(t.In(i))
774 if err != nil {
775 return err
776 }
777 fi.argConverters = append(fi.argConverters, conv)
778 }
779
780 if t.IsVariadic() {
781 conv, err := callbackArg(t.In(numArgs).Elem())
782 if err != nil {
783 return err
784 }
785 fi.variadicConverter = conv
786 // Pass -1 to sqlite so that it allows any number of
787 // arguments. The call helper verifies that the minimum number
788 // of arguments is present for variadic functions.
789 numArgs = -1
790 }
791
792 conv, err := callbackRet(t.Out(0))
793 if err != nil {
794 return err
795 }
796 fi.retConverter = conv
797
798 // fi must outlast the database connection, or we'll have dangling pointers.
799 c.funcs = append(c.funcs, &fi)
800
801 cname := C.CString(name)
802 defer C.free(unsafe.Pointer(cname))
803 opts := C.SQLITE_UTF8
804 if pure {
805 opts |= C.SQLITE_DETERMINISTIC
806 }
807 rv := sqlite3CreateFunction(c.db, cname, C.int(numArgs), C.int(opts), newHandle(c, &fi), C.callbackTrampoline, nil, nil)
808 if rv != C.SQLITE_OK {
809 return c.lastError()
810 }
811 return nil
812 }
813
814 func sqlite3CreateFunction(db *C.sqlite3, zFunctionName *C.char, nArg C.int, eTextRep C.int, pApp unsafe.Pointer, xFunc unsafe.Pointer, xStep unsafe.Pointer, xFinal unsafe.Pointer) C.int {
815 return C._sqlite3_create_function(db, zFunctionName, nArg, eTextRep, C.uintptr_t(uintptr(pApp)), (*[0]byte)(xFunc), (*[0]byte)(xStep), (*[0]byte)(xFinal))
816 }
817
818 // RegisterAggregator makes a Go type available as a SQLite aggregation function.
819 //
820 // Because aggregation is incremental, it's implemented in Go with a
821 // type that has 2 methods: func Step(values) accumulates one row of
822 // data into the accumulator, and func Done() ret finalizes and
823 // returns the aggregate value. "values" and "ret" may be any type
824 // supported by RegisterFunc.
825 //
826 // RegisterAggregator takes as implementation a constructor function
827 // that constructs an instance of the aggregator type each time an
828 // aggregation begins. The constructor must return a pointer to a
829 // type, or an interface that implements Step() and Done().
830 //
831 // The constructor function and the Step/Done methods may optionally
832 // return an error in addition to their other return values.
833 //
834 // See _example/go_custom_funcs for a detailed example.
835 func (c *SQLiteConn) RegisterAggregator(name string, impl any, pure bool) error {
836 var ai aggInfo
837 ai.constructor = reflect.ValueOf(impl)
838 t := ai.constructor.Type()
839 if t.Kind() != reflect.Func {
840 return errors.New("non-function passed to RegisterAggregator")
841 }
842 if t.NumOut() != 1 && t.NumOut() != 2 {
843 return errors.New("SQLite aggregator constructors must return 1 or 2 values")
844 }
845 if t.NumOut() == 2 && !t.Out(1).Implements(reflect.TypeOf((*error)(nil)).Elem()) {
846 return errors.New("Second return value of SQLite function must be error")
847 }
848 if t.NumIn() != 0 {
849 return errors.New("SQLite aggregator constructors must not have arguments")
850 }
851
852 agg := t.Out(0)
853 switch agg.Kind() {
854 case reflect.Ptr, reflect.Interface:
855 default:
856 return errors.New("SQlite aggregator constructor must return a pointer object")
857 }
858 stepFn, found := agg.MethodByName("Step")
859 if !found {
860 return errors.New("SQlite aggregator doesn't have a Step() function")
861 }
862 step := stepFn.Type
863 if step.NumOut() != 0 && step.NumOut() != 1 {
864 return errors.New("SQlite aggregator Step() function must return 0 or 1 values")
865 }
866 if step.NumOut() == 1 && !step.Out(0).Implements(reflect.TypeOf((*error)(nil)).Elem()) {
867 return errors.New("type of SQlite aggregator Step() return value must be error")
868 }
869
870 stepNArgs := step.NumIn()
871 start := 0
872 if agg.Kind() == reflect.Ptr {
873 // Skip over the method receiver
874 stepNArgs--
875 start++
876 }
877 if step.IsVariadic() {
878 stepNArgs--
879 }
880 for i := start; i < start+stepNArgs; i++ {
881 conv, err := callbackArg(step.In(i))
882 if err != nil {
883 return err
884 }
885 ai.stepArgConverters = append(ai.stepArgConverters, conv)
886 }
887 if step.IsVariadic() {
888 conv, err := callbackArg(step.In(start + stepNArgs).Elem())
889 if err != nil {
890 return err
891 }
892 ai.stepVariadicConverter = conv
893 // Pass -1 to sqlite so that it allows any number of
894 // arguments. The call helper verifies that the minimum number
895 // of arguments is present for variadic functions.
896 stepNArgs = -1
897 }
898
899 doneFn, found := agg.MethodByName("Done")
900 if !found {
901 return errors.New("SQlite aggregator doesn't have a Done() function")
902 }
903 done := doneFn.Type
904 doneNArgs := done.NumIn()
905 if agg.Kind() == reflect.Ptr {
906 // Skip over the method receiver
907 doneNArgs--
908 }
909 if doneNArgs != 0 {
910 return errors.New("SQlite aggregator Done() function must have no arguments")
911 }
912 if done.NumOut() != 1 && done.NumOut() != 2 {
913 return errors.New("SQLite aggregator Done() function must return 1 or 2 values")
914 }
915 if done.NumOut() == 2 && !done.Out(1).Implements(reflect.TypeOf((*error)(nil)).Elem()) {
916 return errors.New("second return value of SQLite aggregator Done() function must be error")
917 }
918
919 conv, err := callbackRet(done.Out(0))
920 if err != nil {
921 return err
922 }
923 ai.doneRetConverter = conv
924 ai.active = make(map[int64]reflect.Value)
925 ai.next = 1
926
927 // ai must outlast the database connection, or we'll have dangling pointers.
928 c.aggregators = append(c.aggregators, &ai)
929
930 cname := C.CString(name)
931 defer C.free(unsafe.Pointer(cname))
932 opts := C.SQLITE_UTF8
933 if pure {
934 opts |= C.SQLITE_DETERMINISTIC
935 }
936 rv := sqlite3CreateFunction(c.db, cname, C.int(stepNArgs), C.int(opts), newHandle(c, &ai), nil, C.stepTrampoline, C.doneTrampoline)
937 if rv != C.SQLITE_OK {
938 return c.lastError()
939 }
940 return nil
941 }
942
943 // AutoCommit return which currently auto commit or not.
944 func (c *SQLiteConn) AutoCommit() bool {
945 c.mu.Lock()
946 defer c.mu.Unlock()
947 return int(C.sqlite3_get_autocommit(c.db)) != 0
948 }
949
950 func (c *SQLiteConn) lastError() error {
951 return lastError(c.db)
952 }
953
954 // Note: may be called with db == nil
955 func lastError(db *C.sqlite3) error {
956 rv := C.sqlite3_errcode(db) // returns SQLITE_NOMEM if db == nil
957 if rv == C.SQLITE_OK {
958 return nil
959 }
960 extrv := C.sqlite3_extended_errcode(db) // returns SQLITE_NOMEM if db == nil
961 errStr := C.GoString(C.sqlite3_errmsg(db)) // returns "out of memory" if db == nil
962
963 // https://www.sqlite.org/c3ref/system_errno.html
964 // sqlite3_system_errno is only meaningful if the error code was SQLITE_CANTOPEN,
965 // or it was SQLITE_IOERR and the extended code was not SQLITE_IOERR_NOMEM
966 var systemErrno syscall.Errno
967 if rv == C.SQLITE_CANTOPEN || (rv == C.SQLITE_IOERR && extrv != C.SQLITE_IOERR_NOMEM) {
968 systemErrno = syscall.Errno(C.sqlite3_system_errno(db))
969 }
970
971 return Error{
972 Code: ErrNo(rv),
973 ExtendedCode: ErrNoExtended(extrv),
974 SystemErrno: systemErrno,
975 err: errStr,
976 }
977 }
978
979 // Exec implements Execer.
980 func (c *SQLiteConn) Exec(query string, args []driver.Value) (driver.Result, error) {
981 return c.exec(context.Background(), query, valueToNamedValue(args))
982 }
983
984 func (c *SQLiteConn) exec(ctx context.Context, query string, args []driver.NamedValue) (driver.Result, error) {
985 // Fast path: no args, no context cancellation → single CGO call per statement
986 if len(args) == 0 && ctx.Done() == nil {
987 return c.execNoArgs(query)
988 }
989
990 start := 0
991 for {
992 s, err := c.prepareWithCache(ctx, query)
993 if err != nil {
994 return nil, err
995 }
996 var res driver.Result
997 if s.(*SQLiteStmt).s != nil {
998 na := s.NumInput()
999 if len(args)-start < na {
1000 s.Close()
1001 return nil, fmt.Errorf("not enough args to execute query: want %d got %d", na, len(args)-start)
1002 }
1003 stmtArgs := stmtArgs(args, start, na)
1004 res, err = s.(*SQLiteStmt).exec(ctx, stmtArgs)
1005 if err != nil && err != driver.ErrSkip {
1006 s.Close()
1007 return nil, err
1008 }
1009 start += na
1010 }
1011 tail := s.(*SQLiteStmt).t
1012 s.Close()
1013 if tail == "" {
1014 if res == nil {
1015 // https://github.com/mattn/go-sqlite3/issues/963
1016 res = &SQLiteResult{0, 0}
1017 }
1018 return res, nil
1019 }
1020 query = tail
1021 }
1022 }
1023
1024 // execNoArgs executes a query with no parameters in a single CGO call per statement.
1025 func (c *SQLiteConn) execNoArgs(query string) (driver.Result, error) {
1026 var res *SQLiteResult
1027 for len(query) > 0 {
1028 var rowid, changes C.longlong
1029 var tail *C.char
1030 pquery := C.CString(query)
1031 rv := C._sqlite3_exec_no_args(c.db, pquery, C.int(len(query)), &rowid, &changes, &tail)
1032 if tail != nil && *tail != '\000' {
1033 query = strings.TrimSpace(C.GoString(tail))
1034 } else {
1035 query = ""
1036 }
1037 C.free(unsafe.Pointer(pquery))
1038 if rv != C.SQLITE_ROW && rv != C.SQLITE_OK && rv != C.SQLITE_DONE {
1039 return nil, c.lastError()
1040 }
1041 res = &SQLiteResult{id: int64(rowid), changes: int64(changes)}
1042 }
1043 if res == nil {
1044 res = &SQLiteResult{0, 0}
1045 }
1046 return res, nil
1047 }
1048
1049 // Query implements Queryer.
1050 func (c *SQLiteConn) Query(query string, args []driver.Value) (driver.Rows, error) {
1051 return c.query(context.Background(), query, valueToNamedValue(args))
1052 }
1053
1054 func (c *SQLiteConn) query(ctx context.Context, query string, args []driver.NamedValue) (driver.Rows, error) {
1055 start := 0
1056 for {
1057 s, err := c.prepareWithCache(ctx, query)
1058 if err != nil {
1059 return nil, err
1060 }
1061 ss := s.(*SQLiteStmt)
1062 ss.cls = true
1063 // sqlite3_prepare_v2 returns SQLITE_OK with a NULL statement handle
1064 // when the input is empty or contains only whitespace/comments.
1065 if ss.s == nil {
1066 tail := ss.t
1067 ss.Close()
1068 if tail == "" {
1069 return &SQLiteRows{cls: true, ctx: ctx}, nil
1070 }
1071 query = tail
1072 continue
1073 }
1074 na := s.NumInput()
1075 if len(args)-start < na {
1076 ss.Close()
1077 return nil, fmt.Errorf("not enough args to execute query: want %d got %d", na, len(args)-start)
1078 }
1079 stmtArgs := stmtArgs(args, start, na)
1080 rows, err := ss.query(ctx, stmtArgs)
1081 if err != nil && err != driver.ErrSkip {
1082 ss.Close()
1083 return rows, err
1084 }
1085 start += na
1086 tail := ss.t
1087 if tail == "" {
1088 return rows, nil
1089 }
1090 rows.Close()
1091 ss.Close()
1092 query = tail
1093 }
1094 }
1095
1096 // Begin transaction.
1097 func (c *SQLiteConn) Begin() (driver.Tx, error) {
1098 return c.begin(context.Background())
1099 }
1100
1101 func (c *SQLiteConn) begin(ctx context.Context) (driver.Tx, error) {
1102 if _, err := c.exec(ctx, c.txlock, nil); err != nil {
1103 return nil, err
1104 }
1105 return &SQLiteTx{c}, nil
1106 }
1107
1108 // Open database and return a new connection.
1109 //
1110 // A pragma can take either zero or one argument.
1111 // The argument is may be either in parentheses or it may be separated from
1112 // the pragma name by an equal sign. The two syntaxes yield identical results.
1113 // In many pragmas, the argument is a boolean. The boolean can be one of:
1114 //
1115 // 1 yes true on
1116 // 0 no false off
1117 //
1118 // You can specify a DSN string using a URI as the filename.
1119 //
1120 // test.db
1121 // file:test.db?cache=shared&mode=memory
1122 // :memory:
1123 // file::memory:
1124 //
1125 // mode
1126 // Access mode of the database.
1127 // https://www.sqlite.org/c3ref/open.html
1128 // Values:
1129 // - ro
1130 // - rw
1131 // - rwc
1132 // - memory
1133 //
1134 // cache
1135 // SQLite Shared-Cache Mode
1136 // https://www.sqlite.org/sharedcache.html
1137 // Values:
1138 // - shared
1139 // - private
1140 //
1141 // immutable=Boolean
1142 // The immutable parameter is a boolean query parameter that indicates
1143 // that the database file is stored on read-only media. When immutable is set,
1144 // SQLite assumes that the database file cannot be changed,
1145 // even by a process with higher privilege,
1146 // and so the database is opened read-only and all locking and change detection is disabled.
1147 // Caution: Setting the immutable property on a database file that
1148 // does in fact change can result in incorrect query results and/or SQLITE_CORRUPT errors.
1149 //
1150 // go-sqlite3 adds the following query parameters to those used by SQLite:
1151 //
1152 // _loc=XXX
1153 // Specify location of time format. It's possible to specify "auto".
1154 //
1155 // _mutex=XXX
1156 // Specify mutex mode. XXX can be "no", "full".
1157 //
1158 // _txlock=XXX
1159 // Specify locking behavior for transactions. XXX can be "immediate",
1160 // "deferred", "exclusive".
1161 //
1162 // _auto_vacuum=X | _vacuum=X
1163 // 0 | none - Auto Vacuum disabled
1164 // 1 | full - Auto Vacuum FULL
1165 // 2 | incremental - Auto Vacuum Incremental
1166 //
1167 // _busy_timeout=XXX"| _timeout=XXX
1168 // Specify value for sqlite3_busy_timeout.
1169 //
1170 // _case_sensitive_like=Boolean | _cslike=Boolean
1171 // https://www.sqlite.org/pragma.html#pragma_case_sensitive_like
1172 // Default or disabled the LIKE operation is case-insensitive.
1173 // When enabling this options behaviour of LIKE will become case-sensitive.
1174 //
1175 // _defer_foreign_keys=Boolean | _defer_fk=Boolean
1176 // Defer Foreign Keys until outermost transaction is committed.
1177 //
1178 // _foreign_keys=Boolean | _fk=Boolean
1179 // Enable or disable enforcement of foreign keys.
1180 //
1181 // _ignore_check_constraints=Boolean
1182 // This pragma enables or disables the enforcement of CHECK constraints.
1183 // The default setting is off, meaning that CHECK constraints are enforced by default.
1184 //
1185 // _journal_mode=MODE | _journal=MODE
1186 // Set journal mode for the databases associated with the current connection.
1187 // https://www.sqlite.org/pragma.html#pragma_journal_mode
1188 //
1189 // _locking_mode=X | _locking=X
1190 // Sets the database connection locking-mode.
1191 // The locking-mode is either NORMAL or EXCLUSIVE.
1192 // https://www.sqlite.org/pragma.html#pragma_locking_mode
1193 //
1194 // _query_only=Boolean
1195 // The query_only pragma prevents all changes to database files when enabled.
1196 //
1197 // _recursive_triggers=Boolean | _rt=Boolean
1198 // Enable or disable recursive triggers.
1199 //
1200 // _secure_delete=Boolean|FAST
1201 // When secure_delete is on, SQLite overwrites deleted content with zeros.
1202 // https://www.sqlite.org/pragma.html#pragma_secure_delete
1203 //
1204 // _synchronous=X | _sync=X
1205 // Change the setting of the "synchronous" flag.
1206 // https://www.sqlite.org/pragma.html#pragma_synchronous
1207 //
1208 // _writable_schema=Boolean
1209 // When this pragma is on, the SQLITE_MASTER tables in which database
1210 // can be changed using ordinary UPDATE, INSERT, and DELETE statements.
1211 // Warning: misuse of this pragma can easily result in a corrupt database file.
1212 func (d *SQLiteDriver) Open(dsn string) (driver.Conn, error) {
1213 if C.sqlite3_threadsafe() == 0 {
1214 return nil, errors.New("sqlite library was not compiled for thread-safe operation")
1215 }
1216
1217 var pkey string
1218
1219 // Options
1220 var loc *time.Location
1221 authCreate := false
1222 authUser := ""
1223 authPass := ""
1224 authCrypt := ""
1225 authSalt := ""
1226 mutex := C.int(C.SQLITE_OPEN_FULLMUTEX)
1227 txlock := "BEGIN"
1228
1229 // PRAGMA's
1230 autoVacuum := -1
1231 busyTimeout := 5000
1232 caseSensitiveLike := -1
1233 deferForeignKeys := -1
1234 foreignKeys := -1
1235 ignoreCheckConstraints := -1
1236 var journalMode string
1237 lockingMode := "NORMAL"
1238 queryOnly := -1
1239 recursiveTriggers := -1
1240 secureDelete := "DEFAULT"
1241 synchronousMode := "NORMAL"
1242 writableSchema := -1
1243 vfsName := ""
1244 var cacheSize *int64
1245 stmtCacheSize := 0
1246
1247 pos := strings.IndexRune(dsn, '?')
1248 if pos >= 1 {
1249 params, err := url.ParseQuery(dsn[pos+1:])
1250 if err != nil {
1251 return nil, err
1252 }
1253
1254 // Authentication
1255 if _, ok := params["_auth"]; ok {
1256 authCreate = true
1257 }
1258 if val := params.Get("_auth_user"); val != "" {
1259 authUser = val
1260 }
1261 if val := params.Get("_auth_pass"); val != "" {
1262 authPass = val
1263 }
1264 if val := params.Get("_auth_crypt"); val != "" {
1265 authCrypt = val
1266 }
1267 if val := params.Get("_auth_salt"); val != "" {
1268 authSalt = val
1269 }
1270
1271 // _loc
1272 if val := params.Get("_loc"); val != "" {
1273 switch strings.ToLower(val) {
1274 case "auto":
1275 loc = time.Local
1276 default:
1277 loc, err = time.LoadLocation(val)
1278 if err != nil {
1279 return nil, fmt.Errorf("Invalid _loc: %v: %v", val, err)
1280 }
1281 }
1282 }
1283
1284 // _mutex
1285 if val := params.Get("_mutex"); val != "" {
1286 switch strings.ToLower(val) {
1287 case "no":
1288 mutex = C.SQLITE_OPEN_NOMUTEX
1289 case "full":
1290 mutex = C.SQLITE_OPEN_FULLMUTEX
1291 default:
1292 return nil, fmt.Errorf("Invalid _mutex: %v", val)
1293 }
1294 }
1295
1296 // _txlock
1297 if val := params.Get("_txlock"); val != "" {
1298 switch strings.ToLower(val) {
1299 case "immediate":
1300 txlock = "BEGIN IMMEDIATE"
1301 case "exclusive":
1302 txlock = "BEGIN EXCLUSIVE"
1303 case "deferred":
1304 txlock = "BEGIN"
1305 default:
1306 return nil, fmt.Errorf("Invalid _txlock: %v", val)
1307 }
1308 }
1309
1310 // Auto Vacuum (_vacuum)
1311 //
1312 // https://www.sqlite.org/pragma.html#pragma_auto_vacuum
1313 //
1314 pkey = "" // Reset pkey
1315 if _, ok := params["_auto_vacuum"]; ok {
1316 pkey = "_auto_vacuum"
1317 }
1318 if _, ok := params["_vacuum"]; ok {
1319 pkey = "_vacuum"
1320 }
1321 if val := params.Get(pkey); val != "" {
1322 switch strings.ToLower(val) {
1323 case "0", "none":
1324 autoVacuum = 0
1325 case "1", "full":
1326 autoVacuum = 1
1327 case "2", "incremental":
1328 autoVacuum = 2
1329 default:
1330 return nil, fmt.Errorf("Invalid _auto_vacuum: %v, expecting value of '0 NONE 1 FULL 2 INCREMENTAL'", val)
1331 }
1332 }
1333
1334 // Busy Timeout (_busy_timeout)
1335 //
1336 // https://www.sqlite.org/pragma.html#pragma_busy_timeout
1337 //
1338 pkey = "" // Reset pkey
1339 if _, ok := params["_busy_timeout"]; ok {
1340 pkey = "_busy_timeout"
1341 }
1342 if _, ok := params["_timeout"]; ok {
1343 pkey = "_timeout"
1344 }
1345 if val := params.Get(pkey); val != "" {
1346 iv, err := strconv.ParseInt(val, 10, 64)
1347 if err != nil {
1348 return nil, fmt.Errorf("Invalid _busy_timeout: %v: %v", val, err)
1349 }
1350 busyTimeout = int(iv)
1351 }
1352
1353 // Case Sensitive Like (_cslike)
1354 //
1355 // https://www.sqlite.org/pragma.html#pragma_case_sensitive_like
1356 //
1357 pkey = "" // Reset pkey
1358 if _, ok := params["_case_sensitive_like"]; ok {
1359 pkey = "_case_sensitive_like"
1360 }
1361 if _, ok := params["_cslike"]; ok {
1362 pkey = "_cslike"
1363 }
1364 if val := params.Get(pkey); val != "" {
1365 switch strings.ToLower(val) {
1366 case "0", "no", "false", "off":
1367 caseSensitiveLike = 0
1368 case "1", "yes", "true", "on":
1369 caseSensitiveLike = 1
1370 default:
1371 return nil, fmt.Errorf("Invalid _case_sensitive_like: %v, expecting boolean value of '0 1 false true no yes off on'", val)
1372 }
1373 }
1374
1375 // Defer Foreign Keys (_defer_foreign_keys | _defer_fk)
1376 //
1377 // https://www.sqlite.org/pragma.html#pragma_defer_foreign_keys
1378 //
1379 pkey = "" // Reset pkey
1380 if _, ok := params["_defer_foreign_keys"]; ok {
1381 pkey = "_defer_foreign_keys"
1382 }
1383 if _, ok := params["_defer_fk"]; ok {
1384 pkey = "_defer_fk"
1385 }
1386 if val := params.Get(pkey); val != "" {
1387 switch strings.ToLower(val) {
1388 case "0", "no", "false", "off":
1389 deferForeignKeys = 0
1390 case "1", "yes", "true", "on":
1391 deferForeignKeys = 1
1392 default:
1393 return nil, fmt.Errorf("Invalid _defer_foreign_keys: %v, expecting boolean value of '0 1 false true no yes off on'", val)
1394 }
1395 }
1396
1397 // Foreign Keys (_foreign_keys | _fk)
1398 //
1399 // https://www.sqlite.org/pragma.html#pragma_foreign_keys
1400 //
1401 pkey = "" // Reset pkey
1402 if _, ok := params["_foreign_keys"]; ok {
1403 pkey = "_foreign_keys"
1404 }
1405 if _, ok := params["_fk"]; ok {
1406 pkey = "_fk"
1407 }
1408 if val := params.Get(pkey); val != "" {
1409 switch strings.ToLower(val) {
1410 case "0", "no", "false", "off":
1411 foreignKeys = 0
1412 case "1", "yes", "true", "on":
1413 foreignKeys = 1
1414 default:
1415 return nil, fmt.Errorf("Invalid _foreign_keys: %v, expecting boolean value of '0 1 false true no yes off on'", val)
1416 }
1417 }
1418
1419 // Ignore CHECK Constrains (_ignore_check_constraints)
1420 //
1421 // https://www.sqlite.org/pragma.html#pragma_ignore_check_constraints
1422 //
1423 if val := params.Get("_ignore_check_constraints"); val != "" {
1424 switch strings.ToLower(val) {
1425 case "0", "no", "false", "off":
1426 ignoreCheckConstraints = 0
1427 case "1", "yes", "true", "on":
1428 ignoreCheckConstraints = 1
1429 default:
1430 return nil, fmt.Errorf("Invalid _ignore_check_constraints: %v, expecting boolean value of '0 1 false true no yes off on'", val)
1431 }
1432 }
1433
1434 // Journal Mode (_journal_mode | _journal)
1435 //
1436 // https://www.sqlite.org/pragma.html#pragma_journal_mode
1437 //
1438 pkey = "" // Reset pkey
1439 if _, ok := params["_journal_mode"]; ok {
1440 pkey = "_journal_mode"
1441 }
1442 if _, ok := params["_journal"]; ok {
1443 pkey = "_journal"
1444 }
1445 if val := params.Get(pkey); val != "" {
1446 switch strings.ToUpper(val) {
1447 case "DELETE", "TRUNCATE", "PERSIST", "MEMORY", "OFF":
1448 journalMode = strings.ToUpper(val)
1449 case "WAL":
1450 journalMode = strings.ToUpper(val)
1451
1452 // For WAL Mode set Synchronous Mode to 'NORMAL'
1453 // See https://www.sqlite.org/pragma.html#pragma_synchronous
1454 synchronousMode = "NORMAL"
1455 default:
1456 return nil, fmt.Errorf("Invalid _journal: %v, expecting value of 'DELETE TRUNCATE PERSIST MEMORY WAL OFF'", val)
1457 }
1458 }
1459
1460 // Locking Mode (_locking)
1461 //
1462 // https://www.sqlite.org/pragma.html#pragma_locking_mode
1463 //
1464 pkey = "" // Reset pkey
1465 if _, ok := params["_locking_mode"]; ok {
1466 pkey = "_locking_mode"
1467 }
1468 if _, ok := params["_locking"]; ok {
1469 pkey = "_locking"
1470 }
1471 if val := params.Get(pkey); val != "" {
1472 switch strings.ToUpper(val) {
1473 case "NORMAL", "EXCLUSIVE":
1474 lockingMode = strings.ToUpper(val)
1475 default:
1476 return nil, fmt.Errorf("Invalid _locking_mode: %v, expecting value of 'NORMAL EXCLUSIVE", val)
1477 }
1478 }
1479
1480 // Query Only (_query_only)
1481 //
1482 // https://www.sqlite.org/pragma.html#pragma_query_only
1483 //
1484 if val := params.Get("_query_only"); val != "" {
1485 switch strings.ToLower(val) {
1486 case "0", "no", "false", "off":
1487 queryOnly = 0
1488 case "1", "yes", "true", "on":
1489 queryOnly = 1
1490 default:
1491 return nil, fmt.Errorf("Invalid _query_only: %v, expecting boolean value of '0 1 false true no yes off on'", val)
1492 }
1493 }
1494
1495 // Recursive Triggers (_recursive_triggers)
1496 //
1497 // https://www.sqlite.org/pragma.html#pragma_recursive_triggers
1498 //
1499 pkey = "" // Reset pkey
1500 if _, ok := params["_recursive_triggers"]; ok {
1501 pkey = "_recursive_triggers"
1502 }
1503 if _, ok := params["_rt"]; ok {
1504 pkey = "_rt"
1505 }
1506 if val := params.Get(pkey); val != "" {
1507 switch strings.ToLower(val) {
1508 case "0", "no", "false", "off":
1509 recursiveTriggers = 0
1510 case "1", "yes", "true", "on":
1511 recursiveTriggers = 1
1512 default:
1513 return nil, fmt.Errorf("Invalid _recursive_triggers: %v, expecting boolean value of '0 1 false true no yes off on'", val)
1514 }
1515 }
1516
1517 // Secure Delete (_secure_delete)
1518 //
1519 // https://www.sqlite.org/pragma.html#pragma_secure_delete
1520 //
1521 if val := params.Get("_secure_delete"); val != "" {
1522 switch strings.ToLower(val) {
1523 case "0", "no", "false", "off":
1524 secureDelete = "OFF"
1525 case "1", "yes", "true", "on":
1526 secureDelete = "ON"
1527 case "fast":
1528 secureDelete = "FAST"
1529 default:
1530 return nil, fmt.Errorf("Invalid _secure_delete: %v, expecting boolean value of '0 1 false true no yes off on fast'", val)
1531 }
1532 }
1533
1534 // Synchronous Mode (_synchronous | _sync)
1535 //
1536 // https://www.sqlite.org/pragma.html#pragma_synchronous
1537 //
1538 pkey = "" // Reset pkey
1539 if _, ok := params["_synchronous"]; ok {
1540 pkey = "_synchronous"
1541 }
1542 if _, ok := params["_sync"]; ok {
1543 pkey = "_sync"
1544 }
1545 if val := params.Get(pkey); val != "" {
1546 switch strings.ToUpper(val) {
1547 case "0", "OFF", "1", "NORMAL", "2", "FULL", "3", "EXTRA":
1548 synchronousMode = strings.ToUpper(val)
1549 default:
1550 return nil, fmt.Errorf("Invalid _synchronous: %v, expecting value of '0 OFF 1 NORMAL 2 FULL 3 EXTRA'", val)
1551 }
1552 }
1553
1554 // Writable Schema (_writeable_schema)
1555 //
1556 // https://www.sqlite.org/pragma.html#pragma_writeable_schema
1557 //
1558 if val := params.Get("_writable_schema"); val != "" {
1559 switch strings.ToLower(val) {
1560 case "0", "no", "false", "off":
1561 writableSchema = 0
1562 case "1", "yes", "true", "on":
1563 writableSchema = 1
1564 default:
1565 return nil, fmt.Errorf("Invalid _writable_schema: %v, expecting boolean value of '0 1 false true no yes off on'", val)
1566 }
1567 }
1568
1569 // Cache size (_cache_size)
1570 //
1571 // https://sqlite.org/pragma.html#pragma_cache_size
1572 //
1573 if val := params.Get("_cache_size"); val != "" {
1574 iv, err := strconv.ParseInt(val, 10, 64)
1575 if err != nil {
1576 return nil, fmt.Errorf("Invalid _cache_size: %v: %v", val, err)
1577 }
1578 cacheSize = &iv
1579 }
1580
1581 // _stmt_cache_size sets the maximum number of prepared statements
1582 // cached per connection. Note that sql.DB is a connection pool, so
1583 // each connection maintains its own independent cache.
1584 if val := params.Get("_stmt_cache_size"); val != "" {
1585 iv, err := strconv.Atoi(val)
1586 if err != nil {
1587 return nil, fmt.Errorf("Invalid _stmt_cache_size: %v: %v", val, err)
1588 }
1589 if iv < 0 {
1590 return nil, fmt.Errorf("Invalid _stmt_cache_size: %v, expecting non-negative integer", val)
1591 }
1592 stmtCacheSize = iv
1593 }
1594
1595 if val := params.Get("vfs"); val != "" {
1596 vfsName = val
1597 }
1598
1599 if !strings.HasPrefix(dsn, "file:") {
1600 dsn = dsn[:pos]
1601 }
1602 }
1603
1604 var db *C.sqlite3
1605 name := C.CString(dsn)
1606 defer C.free(unsafe.Pointer(name))
1607 var vfs *C.char
1608 if vfsName != "" {
1609 vfs = C.CString(vfsName)
1610 defer C.free(unsafe.Pointer(vfs))
1611 }
1612 rv := C._sqlite3_open_v2(name, &db,
1613 mutex|C.SQLITE_OPEN_READWRITE|C.SQLITE_OPEN_CREATE,
1614 vfs)
1615 if rv != 0 {
1616 // Save off the error _before_ closing the database.
1617 // This is safe even if db is nil.
1618 err := lastError(db)
1619 if db != nil {
1620 C.sqlite3_close_v2(db)
1621 }
1622 return nil, err
1623 }
1624 if db == nil {
1625 return nil, errors.New("sqlite succeeded without returning a database")
1626 }
1627
1628 // Create connection to SQLite
1629 conn := &SQLiteConn{db: db, loc: loc, txlock: txlock}
1630 if stmtCacheSize > 0 {
1631 conn.stmtCache = make([]*SQLiteStmt, 0, stmtCacheSize)
1632 conn.stmtCacheEnabled = true
1633 }
1634
1635 // fail closes the connection so no error path leaks the database
1636 // handle or any callback handles registered on it.
1637 fail := func(err error) (driver.Conn, error) {
1638 conn.Close()
1639 return nil, err
1640 }
1641
1642 if conn.stmtCacheEnabled && int(C.sqlite3_libversion_number()) < 3020000 {
1643 // Schema-change detection for cached statements relies on
1644 // SQLITE_STMTSTATUS_REPREPARE (3.20.0); with an older runtime
1645 // library run without the cache rather than risk serving
1646 // statements whose metadata a schema change has expired. The
1647 // compile-time check in _sqlite3_step_columns is not enough:
1648 // with USE_LIBSQLITE3 the header and the runtime library can
1649 // differ.
1650 conn.stmtCache = nil
1651 conn.stmtCacheEnabled = false
1652 }
1653
1654 exec := func(s string) error {
1655 cs := C.CString(s)
1656 rv := C.sqlite3_exec(db, cs, nil, nil, nil)
1657 C.free(unsafe.Pointer(cs))
1658 if rv != C.SQLITE_OK {
1659 return lastError(db)
1660 }
1661 return nil
1662 }
1663
1664 // Busy timeout
1665 if err := exec(fmt.Sprintf("PRAGMA busy_timeout = %d;", busyTimeout)); err != nil {
1666 return fail(err)
1667 }
1668
1669 // USER AUTHENTICATION
1670 //
1671 // User Authentication is always performed even when
1672 // sqlite_userauth is not compiled in, because without user authentication
1673 // the authentication is a no-op.
1674 //
1675 // Workflow
1676 // - Authenticate
1677 // ON::SUCCESS => Continue
1678 // ON::SQLITE_AUTH => Return error and exit Open(...)
1679 //
1680 // - Activate User Authentication
1681 // Check if the user wants to activate User Authentication.
1682 // If so then first create a temporary AuthConn to the database
1683 // This is possible because we are already successfully authenticated.
1684 //
1685 // - Check if `sqlite_user`` table exists
1686 // YES => Add the provided user from DSN as Admin User and
1687 // activate user authentication.
1688 // NO => Continue
1689 //
1690
1691 // Password Cipher has to be registered before authentication
1692 if len(authCrypt) > 0 {
1693 switch strings.ToUpper(authCrypt) {
1694 case "SHA1":
1695 if err := conn.RegisterFunc("sqlite_crypt", CryptEncoderSHA1, true); err != nil {
1696 return fail(fmt.Errorf("CryptEncoderSHA1: %s", err))
1697 }
1698 case "SSHA1":
1699 if len(authSalt) == 0 {
1700 return fail(fmt.Errorf("_auth_crypt=ssha1, requires _auth_salt"))
1701 }
1702 if err := conn.RegisterFunc("sqlite_crypt", CryptEncoderSSHA1(authSalt), true); err != nil {
1703 return fail(fmt.Errorf("CryptEncoderSSHA1: %s", err))
1704 }
1705 case "SHA256":
1706 if err := conn.RegisterFunc("sqlite_crypt", CryptEncoderSHA256, true); err != nil {
1707 return fail(fmt.Errorf("CryptEncoderSHA256: %s", err))
1708 }
1709 case "SSHA256":
1710 if len(authSalt) == 0 {
1711 return fail(fmt.Errorf("_auth_crypt=ssha256, requires _auth_salt"))
1712 }
1713 if err := conn.RegisterFunc("sqlite_crypt", CryptEncoderSSHA256(authSalt), true); err != nil {
1714 return fail(fmt.Errorf("CryptEncoderSSHA256: %s", err))
1715 }
1716 case "SHA384":
1717 if err := conn.RegisterFunc("sqlite_crypt", CryptEncoderSHA384, true); err != nil {
1718 return fail(fmt.Errorf("CryptEncoderSHA384: %s", err))
1719 }
1720 case "SSHA384":
1721 if len(authSalt) == 0 {
1722 return fail(fmt.Errorf("_auth_crypt=ssha384, requires _auth_salt"))
1723 }
1724 if err := conn.RegisterFunc("sqlite_crypt", CryptEncoderSSHA384(authSalt), true); err != nil {
1725 return fail(fmt.Errorf("CryptEncoderSSHA384: %s", err))
1726 }
1727 case "SHA512":
1728 if err := conn.RegisterFunc("sqlite_crypt", CryptEncoderSHA512, true); err != nil {
1729 return fail(fmt.Errorf("CryptEncoderSHA512: %s", err))
1730 }
1731 case "SSHA512":
1732 if len(authSalt) == 0 {
1733 return fail(fmt.Errorf("_auth_crypt=ssha512, requires _auth_salt"))
1734 }
1735 if err := conn.RegisterFunc("sqlite_crypt", CryptEncoderSSHA512(authSalt), true); err != nil {
1736 return fail(fmt.Errorf("CryptEncoderSSHA512: %s", err))
1737 }
1738 }
1739 }
1740
1741 // Preform Authentication
1742 if err := conn.Authenticate(authUser, authPass); err != nil {
1743 return fail(err)
1744 }
1745
1746 // Register: authenticate
1747 // Authenticate will perform an authentication of the provided username
1748 // and password against the database.
1749 //
1750 // If a database contains the SQLITE_USER table, then the
1751 // call to Authenticate must be invoked with an
1752 // appropriate username and password prior to enable read and write
1753 //access to the database.
1754 //
1755 // Return SQLITE_OK on success or SQLITE_ERROR if the username/password
1756 // combination is incorrect or unknown.
1757 //
1758 // If the SQLITE_USER table is not present in the database file, then
1759 // this interface is a harmless no-op returnning SQLITE_OK.
1760 if err := conn.RegisterFunc("authenticate", conn.authenticate, true); err != nil {
1761 return fail(err)
1762 }
1763 //
1764 // Register: auth_user_add
1765 // auth_user_add can be used (by an admin user only)
1766 // to create a new user. When called on a no-authentication-required
1767 // database, this routine converts the database into an authentication-
1768 // required database, automatically makes the added user an
1769 // administrator, and logs in the current connection as that user.
1770 // The AuthUserAdd only works for the "main" database, not
1771 // for any ATTACH-ed databases. Any call to AuthUserAdd by a
1772 // non-admin user results in an error.
1773 if err := conn.RegisterFunc("auth_user_add", conn.authUserAdd, true); err != nil {
1774 return fail(err)
1775 }
1776 //
1777 // Register: auth_user_change
1778 // auth_user_change can be used to change a users
1779 // login credentials or admin privilege. Any user can change their own
1780 // login credentials. Only an admin user can change another users login
1781 // credentials or admin privilege setting. No user may change their own
1782 // admin privilege setting.
1783 if err := conn.RegisterFunc("auth_user_change", conn.authUserChange, true); err != nil {
1784 return fail(err)
1785 }
1786 //
1787 // Register: auth_user_delete
1788 // auth_user_delete can be used (by an admin user only)
1789 // to delete a user. The currently logged-in user cannot be deleted,
1790 // which guarantees that there is always an admin user and hence that
1791 // the database cannot be converted into a no-authentication-required
1792 // database.
1793 if err := conn.RegisterFunc("auth_user_delete", conn.authUserDelete, true); err != nil {
1794 return fail(err)
1795 }
1796
1797 // Register: auth_enabled
1798 // auth_enabled can be used to check if user authentication is enabled
1799 if err := conn.RegisterFunc("auth_enabled", conn.authEnabled, true); err != nil {
1800 return fail(err)
1801 }
1802
1803 // Auto Vacuum
1804 // Moved auto_vacuum command, the user preference for auto_vacuum needs to be implemented directly after
1805 // the authentication and before the sqlite_user table gets created if the user
1806 // decides to activate User Authentication because
1807 // auto_vacuum needs to be set before any tables are created
1808 // and activating user authentication creates the internal table `sqlite_user`.
1809 if autoVacuum > -1 {
1810 if err := exec(fmt.Sprintf("PRAGMA auto_vacuum = %d;", autoVacuum)); err != nil {
1811 return fail(err)
1812 }
1813 }
1814
1815 // Check if user wants to activate User Authentication
1816 if authCreate {
1817 // Before going any further, we need to check that the user
1818 // has provided an username and password within the DSN.
1819 // We are not allowed to continue.
1820 if len(authUser) == 0 {
1821 return fail(fmt.Errorf("Missing '_auth_user' while user authentication was requested with '_auth'"))
1822 }
1823 if len(authPass) == 0 {
1824 return fail(fmt.Errorf("Missing '_auth_pass' while user authentication was requested with '_auth'"))
1825 }
1826
1827 // Check if User Authentication is Enabled
1828 authExists := conn.AuthEnabled()
1829 if !authExists {
1830 if err := conn.AuthUserAdd(authUser, authPass, true); err != nil {
1831 return fail(err)
1832 }
1833 }
1834 }
1835
1836 // Case Sensitive LIKE
1837 if caseSensitiveLike > -1 {
1838 if err := exec(fmt.Sprintf("PRAGMA case_sensitive_like = %d;", caseSensitiveLike)); err != nil {
1839 return fail(err)
1840 }
1841 }
1842
1843 // Defer Foreign Keys
1844 if deferForeignKeys > -1 {
1845 if err := exec(fmt.Sprintf("PRAGMA defer_foreign_keys = %d;", deferForeignKeys)); err != nil {
1846 return fail(err)
1847 }
1848 }
1849
1850 // Foreign Keys
1851 if foreignKeys > -1 {
1852 if err := exec(fmt.Sprintf("PRAGMA foreign_keys = %d;", foreignKeys)); err != nil {
1853 return fail(err)
1854 }
1855 }
1856
1857 // Ignore CHECK Constraints
1858 if ignoreCheckConstraints > -1 {
1859 if err := exec(fmt.Sprintf("PRAGMA ignore_check_constraints = %d;", ignoreCheckConstraints)); err != nil {
1860 return fail(err)
1861 }
1862 }
1863
1864 // Journal Mode
1865 if journalMode != "" {
1866 if err := exec(fmt.Sprintf("PRAGMA journal_mode = %s;", journalMode)); err != nil {
1867 return fail(err)
1868 }
1869 }
1870
1871 // Locking Mode
1872 // Because the default is NORMAL and this is not changed in this package
1873 // by using the compile time SQLITE_DEFAULT_LOCKING_MODE this PRAGMA can always be executed
1874 if err := exec(fmt.Sprintf("PRAGMA locking_mode = %s;", lockingMode)); err != nil {
1875 return fail(err)
1876 }
1877
1878 // Query Only
1879 if queryOnly > -1 {
1880 if err := exec(fmt.Sprintf("PRAGMA query_only = %d;", queryOnly)); err != nil {
1881 return fail(err)
1882 }
1883 }
1884
1885 // Recursive Triggers
1886 if recursiveTriggers > -1 {
1887 if err := exec(fmt.Sprintf("PRAGMA recursive_triggers = %d;", recursiveTriggers)); err != nil {
1888 return fail(err)
1889 }
1890 }
1891
1892 // Secure Delete
1893 //
1894 // Because this package can set the compile time flag SQLITE_SECURE_DELETE with a build tag
1895 // the default value for secureDelete var is 'DEFAULT' this way
1896 // you can compile with secure_delete 'ON' and disable it for a specific database connection.
1897 if secureDelete != "DEFAULT" {
1898 if err := exec(fmt.Sprintf("PRAGMA secure_delete = %s;", secureDelete)); err != nil {
1899 return fail(err)
1900 }
1901 }
1902
1903 // Synchronous Mode
1904 //
1905 // Because default is NORMAL this statement is always executed
1906 if err := exec(fmt.Sprintf("PRAGMA synchronous = %s;", synchronousMode)); err != nil {
1907 return fail(err)
1908 }
1909
1910 // Writable Schema
1911 if writableSchema > -1 {
1912 if err := exec(fmt.Sprintf("PRAGMA writable_schema = %d;", writableSchema)); err != nil {
1913 return fail(err)
1914 }
1915 }
1916
1917 // Cache Size
1918 if cacheSize != nil {
1919 if err := exec(fmt.Sprintf("PRAGMA cache_size = %d;", *cacheSize)); err != nil {
1920 return fail(err)
1921 }
1922 }
1923
1924 if len(d.Extensions) > 0 {
1925 if err := conn.loadExtensions(d.Extensions); err != nil {
1926 return fail(err)
1927 }
1928 }
1929
1930 if d.ConnectHook != nil {
1931 if err := d.ConnectHook(conn); err != nil {
1932 return fail(err)
1933 }
1934 }
1935 runtime.SetFinalizer(conn, (*SQLiteConn).Close)
1936 return conn, nil
1937 }
1938
1939 // Close the connection.
1940 func (c *SQLiteConn) Close() error {
1941 c.mu.Lock()
1942 defer c.mu.Unlock()
1943 if c.db == nil {
1944 return nil
1945 }
1946 runtime.SetFinalizer(c, nil)
1947 c.closeCachedStmtsLocked()
1948 rv := C.sqlite3_close_v2(c.db)
1949 if rv != C.SQLITE_OK {
1950 return lastError(c.db)
1951 }
1952 deleteHandles(c)
1953 c.db = nil
1954 return nil
1955 }
1956
1957 func (c *SQLiteConn) dbConnOpen() bool {
1958 if c == nil {
1959 return false
1960 }
1961 c.mu.Lock()
1962 defer c.mu.Unlock()
1963 return c.db != nil
1964 }
1965
1966 func (c *SQLiteConn) takeCachedStmt(query string) *SQLiteStmt {
1967 if c == nil || query == "" || !c.stmtCacheEnabled {
1968 return nil
1969 }
1970
1971 c.mu.Lock()
1972 defer c.mu.Unlock()
1973
1974 if c.db == nil {
1975 return nil
1976 }
1977 // Scan from the MRU end (tail) so that a stmt put just before is
1978 // found immediately.
1979 for i := len(c.stmtCache) - 1; i >= 0; i-- {
1980 s := c.stmtCache[i]
1981 if s.cacheKey != query {
1982 continue
1983 }
1984 n := len(c.stmtCache)
1985 copy(c.stmtCache[i:n-1], c.stmtCache[i+1:n])
1986 c.stmtCache[n-1] = nil
1987 c.stmtCache = c.stmtCache[:n-1]
1988 // The stmt was marked closed by Close before being cached, and
1989 // cls may have been set if Query opened it; reset both so the
1990 // caller gets a stmt equivalent to a fresh Prepare.
1991 s.closed = false
1992 s.cls = false
1993 return s
1994 }
1995 return nil
1996 }
1997
1998 func (c *SQLiteConn) putCachedStmt(s *SQLiteStmt) bool {
1999 if c == nil || s == nil || s.s == nil || s.cacheKey == "" {
2000 return false
2001 }
2002
2003 c.mu.Lock()
2004 defer c.mu.Unlock()
2005
2006 return c.putCachedStmtLocked(s)
2007 }
2008
2009 func (c *SQLiteConn) putCachedStmtLocked(s *SQLiteStmt) bool {
2010 if c.db == nil {
2011 return false
2012 }
2013 rv := C._sqlite3_reset_clear(s.s)
2014 if rv != C.SQLITE_ROW && rv != C.SQLITE_OK && rv != C.SQLITE_DONE {
2015 return false
2016 }
2017 // If full, finalize the LRU entry at index 0 and shift left; the
2018 // freed tail slot is immediately reused by the append below.
2019 if len(c.stmtCache) == cap(c.stmtCache) {
2020 finalizeCachedStmt(c.stmtCache[0])
2021 copy(c.stmtCache, c.stmtCache[1:])
2022 c.stmtCache = c.stmtCache[:len(c.stmtCache)-1]
2023 }
2024 c.stmtCache = append(c.stmtCache, s)
2025 return true
2026 }
2027
2028 func (c *SQLiteConn) closeCachedStmtsLocked() {
2029 for i, s := range c.stmtCache {
2030 c.stmtCache[i] = nil
2031 finalizeCachedStmt(s)
2032 }
2033 c.stmtCache = c.stmtCache[:0]
2034 }
2035
2036 // finalizeCachedStmt tears down a stmt that was sitting in the connection's
2037 // stmt cache. The caller must hold c.mu. It is safe to pass a nil stmt or a
2038 // stmt whose handle has already been released.
2039 func finalizeCachedStmt(s *SQLiteStmt) {
2040 if s == nil {
2041 return
2042 }
2043 runtime.SetFinalizer(s, nil)
2044 if s.s != nil {
2045 C.sqlite3_finalize(s.s)
2046 s.s = nil
2047 }
2048 s.c = nil
2049 s.closed = true
2050 }
2051
2052 // Prepare the query string. Return a new statement.
2053 func (c *SQLiteConn) Prepare(query string) (driver.Stmt, error) {
2054 return c.prepare(context.Background(), query)
2055 }
2056
2057 func (c *SQLiteConn) prepare(ctx context.Context, query string) (driver.Stmt, error) {
2058 pquery := C.CString(query)
2059 defer C.free(unsafe.Pointer(pquery))
2060 var s *C.sqlite3_stmt
2061 var tail *C.char
2062 rv := C._sqlite3_prepare_v2_internal(c.db, pquery, C.int(len(query)), &s, &tail)
2063 if rv != C.SQLITE_OK {
2064 return nil, c.lastError()
2065 }
2066 var t string
2067 if tail != nil && *tail != '\000' {
2068 t = strings.TrimSpace(C.GoString(tail))
2069 }
2070 ss := &SQLiteStmt{c: c, s: s, t: t}
2071 runtime.SetFinalizer(ss, (*SQLiteStmt).Close)
2072 return ss, nil
2073 }
2074
2075 func (c *SQLiteConn) prepareWithCache(ctx context.Context, query string) (driver.Stmt, error) {
2076 if stmt := c.takeCachedStmt(query); stmt != nil {
2077 return stmt, nil
2078 }
2079 stmt, err := c.prepare(ctx, query)
2080 if err != nil {
2081 return nil, err
2082 }
2083 ss := stmt.(*SQLiteStmt)
2084 if ss.t == "" && c.stmtCacheEnabled {
2085 ss.cacheKey = query
2086 }
2087 return ss, nil
2088 }
2089
2090 // Run-Time Limit Categories.
2091 // See: http://www.sqlite.org/c3ref/c_limit_attached.html
2092 const (
2093 SQLITE_LIMIT_LENGTH = C.SQLITE_LIMIT_LENGTH
2094 SQLITE_LIMIT_SQL_LENGTH = C.SQLITE_LIMIT_SQL_LENGTH
2095 SQLITE_LIMIT_COLUMN = C.SQLITE_LIMIT_COLUMN
2096 SQLITE_LIMIT_EXPR_DEPTH = C.SQLITE_LIMIT_EXPR_DEPTH
2097 SQLITE_LIMIT_COMPOUND_SELECT = C.SQLITE_LIMIT_COMPOUND_SELECT
2098 SQLITE_LIMIT_VDBE_OP = C.SQLITE_LIMIT_VDBE_OP
2099 SQLITE_LIMIT_FUNCTION_ARG = C.SQLITE_LIMIT_FUNCTION_ARG
2100 SQLITE_LIMIT_ATTACHED = C.SQLITE_LIMIT_ATTACHED
2101 SQLITE_LIMIT_LIKE_PATTERN_LENGTH = C.SQLITE_LIMIT_LIKE_PATTERN_LENGTH
2102 SQLITE_LIMIT_VARIABLE_NUMBER = C.SQLITE_LIMIT_VARIABLE_NUMBER
2103 SQLITE_LIMIT_TRIGGER_DEPTH = C.SQLITE_LIMIT_TRIGGER_DEPTH
2104 SQLITE_LIMIT_WORKER_THREADS = C.SQLITE_LIMIT_WORKER_THREADS
2105 )
2106
2107 // GetFilename returns the absolute path to the file containing
2108 // the requested schema. When passed an empty string, it will
2109 // instead use the database's default schema: "main".
2110 // See: sqlite3_db_filename, https://www.sqlite.org/c3ref/db_filename.html
2111 func (c *SQLiteConn) GetFilename(schemaName string) string {
2112 if schemaName == "" {
2113 schemaName = "main"
2114 }
2115 cSchema := C.CString(schemaName)
2116 defer C.free(unsafe.Pointer(cSchema))
2117 return C.GoString(C.sqlite3_db_filename(c.db, cSchema))
2118 }
2119
2120 // GetLimit returns the current value of a run-time limit.
2121 // See: sqlite3_limit, http://www.sqlite.org/c3ref/limit.html
2122 func (c *SQLiteConn) GetLimit(id int) int {
2123 return int(C._sqlite3_limit(c.db, C.int(id), C.int(-1)))
2124 }
2125
2126 // SetLimit changes the value of a run-time limits.
2127 // Then this method returns the prior value of the limit.
2128 // See: sqlite3_limit, http://www.sqlite.org/c3ref/limit.html
2129 func (c *SQLiteConn) SetLimit(id int, newVal int) int {
2130 return int(C._sqlite3_limit(c.db, C.int(id), C.int(newVal)))
2131 }
2132
2133 // SetFileControlInt invokes the xFileControl method on a given database. The
2134 // dbName is the name of the database. It will default to "main" if left blank.
2135 // The op is one of the opcodes prefixed by "SQLITE_FCNTL_". The arg argument
2136 // and return code are both opcode-specific. Please see the SQLite documentation.
2137 //
2138 // This method is not thread-safe as the returned error code can be changed by
2139 // another call if invoked concurrently.
2140 //
2141 // Use SetFileControlInt64 instead if the argument for the opcode is documented
2142 // as a pointer to a sqlite3_int64.
2143 //
2144 // See: sqlite3_file_control, https://www.sqlite.org/c3ref/file_control.html
2145 func (c *SQLiteConn) SetFileControlInt(dbName string, op int, arg int) error {
2146 if dbName == "" {
2147 dbName = "main"
2148 }
2149
2150 cDBName := C.CString(dbName)
2151 defer C.free(unsafe.Pointer(cDBName))
2152
2153 cArg := C.int(arg)
2154 rv := C.sqlite3_file_control(c.db, cDBName, C.int(op), unsafe.Pointer(&cArg))
2155 if rv != C.SQLITE_OK {
2156 return c.lastError()
2157 }
2158 return nil
2159 }
2160
2161 // SetFileControlInt64 invokes the xFileControl method on a given database. The
2162 // dbName is the name of the database. It will default to "main" if left blank.
2163 // The op is one of the opcodes prefixed by "SQLITE_FCNTL_". The arg argument
2164 // and return code are both opcode-specific. Please see the SQLite documentation.
2165 //
2166 // This method is not thread-safe as the returned error code can be changed by
2167 // another call if invoked concurrently.
2168 //
2169 // Only use this method if the argument for the opcode is documented as a pointer
2170 // to a sqlite3_int64.
2171 //
2172 // See: sqlite3_file_control, https://www.sqlite.org/c3ref/file_control.html
2173 func (c *SQLiteConn) SetFileControlInt64(dbName string, op int, arg int64) error {
2174 if dbName == "" {
2175 dbName = "main"
2176 }
2177
2178 cDBName := C.CString(dbName)
2179 defer C.free(unsafe.Pointer(cDBName))
2180
2181 cArg := C.sqlite3_int64(arg)
2182 rv := C.sqlite3_file_control(c.db, cDBName, C.int(op), unsafe.Pointer(&cArg))
2183 if rv != C.SQLITE_OK {
2184 return c.lastError()
2185 }
2186 return nil
2187 }
2188
2189 // Close the statement.
2190 func (s *SQLiteStmt) Close() error {
2191 s.mu.Lock()
2192 defer s.mu.Unlock()
2193 if s.closed {
2194 return nil
2195 }
2196 s.closed = true
2197 runtime.SetFinalizer(s, nil)
2198 conn := s.c
2199 stmt := s.s
2200 if stmt == nil {
2201 s.c = nil
2202 return nil
2203 }
2204 if s.cacheKey != "" {
2205 conn.mu.Lock()
2206 if conn.db == nil {
2207 conn.mu.Unlock()
2208 return errors.New("sqlite statement with already closed database connection")
2209 }
2210 if conn.putCachedStmtLocked(s) {
2211 conn.mu.Unlock()
2212 return nil
2213 }
2214 conn.mu.Unlock()
2215 } else if !conn.dbConnOpen() {
2216 return errors.New("sqlite statement with already closed database connection")
2217 }
2218 s.s = nil
2219 s.c = nil
2220 rv := C.sqlite3_finalize(stmt)
2221 if rv != C.SQLITE_OK {
2222 return conn.lastError()
2223 }
2224 return nil
2225 }
2226
2227 // NumInput return a number of parameters.
2228 func (s *SQLiteStmt) NumInput() int {
2229 return int(C.sqlite3_bind_parameter_count(s.s))
2230 }
2231
2232 var placeHolder = []byte{0}
2233
2234 func bindText(s *C.sqlite3_stmt, n C.int, v string) C.int {
2235 if len(v) == 0 {
2236 return C._sqlite3_bind_text(s, n, (*C.char)(unsafe.Pointer(&placeHolder[0])), C.sqlite3_uint64(0))
2237 }
2238 return C._sqlite3_bind_text(s, n, (*C.char)(unsafe.Pointer(unsafe.StringData(v))), C.sqlite3_uint64(len(v)))
2239 }
2240
2241 func bindValue(s *C.sqlite3_stmt, n C.int, value driver.Value) C.int {
2242 switch v := value.(type) {
2243 case nil:
2244 return C.sqlite3_bind_null(s, n)
2245 case string:
2246 return bindText(s, n, v)
2247 case int64:
2248 return C.sqlite3_bind_int64(s, n, C.sqlite3_int64(v))
2249 case bool:
2250 if v {
2251 return C.sqlite3_bind_int(s, n, 1)
2252 }
2253 return C.sqlite3_bind_int(s, n, 0)
2254 case float64:
2255 return C.sqlite3_bind_double(s, n, C.double(v))
2256 case []byte:
2257 if v == nil {
2258 return C.sqlite3_bind_null(s, n)
2259 }
2260 ln := len(v)
2261 if ln == 0 {
2262 v = placeHolder
2263 }
2264 return C._sqlite3_bind_blob(s, n, unsafe.Pointer(&v[0]), C.sqlite3_uint64(ln))
2265 case time.Time:
2266 var buf [64]byte
2267 b := v.AppendFormat(buf[:0], SQLiteTimestampFormats[0])
2268 if len(b) == 0 {
2269 return C._sqlite3_bind_text(s, n, (*C.char)(unsafe.Pointer(&placeHolder[0])), C.sqlite3_uint64(0))
2270 }
2271 return C._sqlite3_bind_text(s, n, (*C.char)(unsafe.Pointer(&b[0])), C.sqlite3_uint64(len(b)))
2272 default:
2273 return C.SQLITE_MISUSE
2274 }
2275 }
2276
2277 func (s *SQLiteStmt) bindNamedIndices(name string) [3]int {
2278 if s.namedParams == nil {
2279 s.namedParams = make(map[string][3]int)
2280 } else if indices, ok := s.namedParams[name]; ok {
2281 return indices
2282 }
2283
2284 // Build ":name\0" once and rewrite prefix byte to avoid 3 C.CString allocs.
2285 buf := make([]byte, 1+len(name)+1) // prefix + name + null terminator
2286 copy(buf[1:], name)
2287 buf[len(buf)-1] = 0
2288 cname := (*C.char)(unsafe.Pointer(&buf[0]))
2289
2290 var indices [3]int
2291 prefixes := [3]byte{':', '@', '$'}
2292 for i, p := range prefixes {
2293 buf[0] = p
2294 indices[i] = int(C.sqlite3_bind_parameter_index(s.s, cname))
2295 }
2296 s.namedParams[name] = indices
2297 return indices
2298 }
2299
2300 func stmtArgs(args []driver.NamedValue, start, na int) []driver.NamedValue {
2301 if na == 0 {
2302 return nil
2303 }
2304
2305 end := start + na
2306 hasNamedOutside := false
2307 for i := range args {
2308 if args[i].Name != "" && (i < start || i >= end) {
2309 hasNamedOutside = true
2310 break
2311 }
2312 }
2313 if start == 0 && !hasNamedOutside {
2314 return args[start:end]
2315 }
2316
2317 stmtArgs := make([]driver.NamedValue, 0, len(args))
2318 stmtArgs = append(stmtArgs, args[start:end]...)
2319 for i := range args {
2320 if args[i].Name != "" && (i < start || i >= end) {
2321 stmtArgs = append(stmtArgs, args[i])
2322 }
2323 }
2324 for i := range stmtArgs {
2325 stmtArgs[i].Ordinal = i + 1
2326 }
2327 return stmtArgs
2328 }
2329
2330 // bindError converts a non-OK return code from bindValue into an error.
2331 // The synthetic SQLITE_MISUSE returned for unsupported Go types is never
2332 // recorded in the database handle, so lastError may report no error; fall
2333 // back to an explicit message instead of silently ignoring the failure.
2334 func (s *SQLiteStmt) bindError(v driver.Value) error {
2335 if err := s.c.lastError(); err != nil {
2336 return err
2337 }
2338 return fmt.Errorf("sqlite3: unsupported bind type %T", v)
2339 }
2340
2341 func (s *SQLiteStmt) bind(args []driver.NamedValue) error {
2342 rv := C._sqlite3_reset_clear(s.s)
2343 if rv != C.SQLITE_ROW && rv != C.SQLITE_OK && rv != C.SQLITE_DONE {
2344 return s.c.lastError()
2345 }
2346
2347 hasNamed := false
2348 for i := range args {
2349 if args[i].Name != "" {
2350 hasNamed = true
2351 break
2352 }
2353 }
2354
2355 if !hasNamed {
2356 for _, arg := range args {
2357 n := C.int(arg.Ordinal)
2358 rv = bindValue(s.s, n, arg.Value)
2359 if rv != C.SQLITE_OK {
2360 return s.bindError(arg.Value)
2361 }
2362 }
2363 return nil
2364 }
2365
2366 for _, arg := range args {
2367 if arg.Name == "" {
2368 rv = bindValue(s.s, C.int(arg.Ordinal), arg.Value)
2369 if rv != C.SQLITE_OK {
2370 return s.bindError(arg.Value)
2371 }
2372 continue
2373 }
2374 indices := s.bindNamedIndices(arg.Name)
2375 for _, idx := range indices {
2376 if idx == 0 {
2377 continue
2378 }
2379 rv = bindValue(s.s, C.int(idx), arg.Value)
2380 if rv != C.SQLITE_OK {
2381 return s.bindError(arg.Value)
2382 }
2383 }
2384 }
2385 return nil
2386 }
2387
2388 // Query the statement with arguments. Return records.
2389 func (s *SQLiteStmt) Query(args []driver.Value) (driver.Rows, error) {
2390 return s.query(context.Background(), valueToNamedValue(args))
2391 }
2392
2393 func (s *SQLiteStmt) query(ctx context.Context, args []driver.NamedValue) (driver.Rows, error) {
2394 if err := s.bind(args); err != nil {
2395 return nil, err
2396 }
2397
2398 rows := &SQLiteRows{
2399 s: s,
2400 cls: s.cls,
2401 ctx: ctx,
2402 pendingStep: -1,
2403 }
2404 if s.cacheKey != "" {
2405 // A schema change expires cached statements and SQLite only
2406 // re-prepares them on their next step, so the column count and
2407 // metadata read before stepping could describe the old schema.
2408 // Take the query's first step eagerly (it was going to run at
2409 // the first Next anyway) and read them afterwards.
2410 rv, err := rows.eagerFirstStepLocked()
2411 if err != nil {
2412 return nil, err
2413 }
2414 rows.pendingStep = rv
2415 } else {
2416 rows.nc = int32(C.sqlite3_column_count(s.s))
2417 }
2418 if rows.nc > 0 {
2419 rows.colvals = (*C.sqlite3_go_col)(C.malloc(C.size_t(rows.nc) * C.size_t(unsafe.Sizeof(C.sqlite3_go_col{}))))
2420 if rows.colvals == nil {
2421 return nil, errors.New("sqlite3: failed to allocate row buffer")
2422 }
2423 }
2424
2425 return rows, nil
2426 }
2427
2428 // LastInsertId return last inserted ID.
2429 func (r *SQLiteResult) LastInsertId() (int64, error) {
2430 return r.id, nil
2431 }
2432
2433 // RowsAffected return how many rows affected.
2434 func (r *SQLiteResult) RowsAffected() (int64, error) {
2435 return r.changes, nil
2436 }
2437
2438 // Exec execute the statement with arguments. Return result object.
2439 func (s *SQLiteStmt) Exec(args []driver.Value) (driver.Result, error) {
2440 return s.exec(context.Background(), valueToNamedValue(args))
2441 }
2442
2443 func valueToNamedValue(args []driver.Value) []driver.NamedValue {
2444 list := make([]driver.NamedValue, len(args))
2445 for i, v := range args {
2446 list[i] = driver.NamedValue{
2447 Ordinal: i + 1,
2448 Value: v,
2449 }
2450 }
2451 return list
2452 }
2453
2454 func isInterruptErr(err error) bool {
2455 sqliteErr, ok := err.(Error)
2456 if ok {
2457 return sqliteErr.Code == ErrInterrupt
2458 }
2459 return false
2460 }
2461
2462 // exec executes a query that doesn't return rows. Attempts to honor context timeout.
2463 func (s *SQLiteStmt) exec(ctx context.Context, args []driver.NamedValue) (driver.Result, error) {
2464 if ctx.Done() == nil {
2465 return s.execSync(args)
2466 }
2467
2468 sema := make(chan struct{})
2469 var r driver.Result
2470 var err error
2471 go func() {
2472 r, err = s.execSync(args)
2473 close(sema)
2474 }()
2475 select {
2476 case <-sema:
2477 return r, err
2478 case <-ctx.Done():
2479 select {
2480 case <-sema: // no need to interrupt, operation completed in db
2481 return r, err
2482 default:
2483 // this is still racy and can be no-op if executed between sqlite3_* calls in execSync.
2484 C.sqlite3_interrupt(s.c.db)
2485 <-sema // wait for goroutine completed
2486 if isInterruptErr(err) {
2487 return nil, ctx.Err()
2488 }
2489 return r, err
2490 }
2491 }
2492 }
2493
2494 func (s *SQLiteStmt) execSync(args []driver.NamedValue) (driver.Result, error) {
2495 if err := s.bind(args); err != nil {
2496 C._sqlite3_reset_clear(s.s)
2497 return nil, err
2498 }
2499
2500 var rowid, changes C.longlong
2501 rv := C._sqlite3_step_row_internal(s.s, &rowid, &changes)
2502 if rv != C.SQLITE_ROW && rv != C.SQLITE_OK && rv != C.SQLITE_DONE {
2503 err := s.c.lastError()
2504 C._sqlite3_reset_clear(s.s)
2505 return nil, err
2506 }
2507
2508 return &SQLiteResult{id: int64(rowid), changes: int64(changes)}, nil
2509 }
2510
2511 // Readonly reports if this statement is considered readonly by SQLite.
2512 //
2513 // See: https://sqlite.org/c3ref/stmt_readonly.html
2514 func (s *SQLiteStmt) Readonly() bool {
2515 return C.sqlite3_stmt_readonly(s.s) == 1
2516 }
2517
2518 // Close the rows.
2519 func (rc *SQLiteRows) Close() error {
2520 rc.closemu.Lock()
2521 defer rc.closemu.Unlock()
2522 rc.stopWatchingCancellation()
2523 s := rc.s
2524 if s == nil {
2525 if rc.colvals != nil {
2526 C.free(unsafe.Pointer(rc.colvals))
2527 rc.colvals = nil
2528 }
2529 return nil
2530 }
2531 rc.s = nil // remove reference to SQLiteStmt
2532 if rc.colvals != nil {
2533 C.free(unsafe.Pointer(rc.colvals))
2534 rc.colvals = nil
2535 }
2536 s.mu.Lock()
2537 if s.closed {
2538 s.mu.Unlock()
2539 return nil
2540 }
2541 if rc.cls {
2542 s.mu.Unlock()
2543 return s.Close()
2544 }
2545 rv := C.sqlite3_reset(s.s)
2546 if rv != C.SQLITE_OK {
2547 s.mu.Unlock()
2548 return s.c.lastError()
2549 }
2550 s.mu.Unlock()
2551 return nil
2552 }
2553
2554 func (c *SQLiteConn) interruptActiveRows(rows *SQLiteRows) {
2555 c.mu.Lock()
2556 defer c.mu.Unlock()
2557 if c.activeRows == rows && c.db != nil {
2558 C.sqlite3_interrupt(c.db)
2559 }
2560 }
2561
2562 func (rc *SQLiteRows) stopWatchingCancellation() {
2563 if rc.stopCancellation == nil {
2564 return
2565 }
2566 // A false return is harmless: a callback already in progress can interrupt
2567 // only while rc owns conn.activeRows, which is guarded by conn.mu.
2568 rc.stopCancellation()
2569 rc.stopCancellation = nil
2570 }
2571
2572 func (rc *SQLiteRows) startStepping() {
2573 conn := rc.s.c
2574 conn.mu.Lock()
2575 conn.activeRows = rc
2576 conn.mu.Unlock()
2577 }
2578
2579 func (rc *SQLiteRows) finishStepping() {
2580 conn := rc.s.c
2581 conn.mu.Lock()
2582 if conn.activeRows == rc {
2583 conn.activeRows = nil
2584 }
2585 conn.mu.Unlock()
2586 }
2587
2588 func (s *SQLiteStmt) cacheMetadata() bool {
2589 return !s.cls || s.cacheKey != ""
2590 }
2591
2592 func (s *SQLiteStmt) columnNamesLocked(n int) []string {
2593 if s.metadata == nil {
2594 s.metadata = &sqliteStmtMetadata{}
2595 }
2596 if len(s.metadata.cols) != n {
2597 s.metadata.cols = make([]string, n)
2598 for i := range s.metadata.cols {
2599 s.metadata.cols[i] = C.GoString(C.sqlite3_column_name(s.s, C.int(i)))
2600 }
2601 }
2602 return s.metadata.cols
2603 }
2604
2605 func (s *SQLiteStmt) declTypesLocked(n int) []string {
2606 if s.metadata == nil {
2607 s.metadata = &sqliteStmtMetadata{}
2608 }
2609 if len(s.metadata.decltype) != n {
2610 s.metadata.decltype = make([]string, n)
2611 for i := range s.metadata.decltype {
2612 s.metadata.decltype[i] = strings.ToLower(C.GoString(C.sqlite3_column_decltype(s.s, C.int(i))))
2613 }
2614 }
2615 return s.metadata.decltype
2616 }
2617
2618 // Columns return column names.
2619 func (rc *SQLiteRows) Columns() []string {
2620 if rc.s == nil {
2621 return rc.cols
2622 }
2623 rc.s.mu.Lock()
2624 defer rc.s.mu.Unlock()
2625 if rc.s.s != nil && int(rc.nc) != len(rc.cols) {
2626 if rc.s.cacheMetadata() {
2627 rc.cols = rc.s.columnNamesLocked(int(rc.nc))
2628 } else {
2629 rc.cols = make([]string, rc.nc)
2630 for i := range rc.cols {
2631 rc.cols[i] = C.GoString(C.sqlite3_column_name(rc.s.s, C.int(i)))
2632 }
2633 }
2634 }
2635 return rc.cols
2636 }
2637
2638 func (rc *SQLiteRows) declTypes() []string {
2639 if rc.s.s != nil && rc.decltype == nil {
2640 if rc.s.cacheMetadata() {
2641 rc.decltype = rc.s.declTypesLocked(int(rc.nc))
2642 } else {
2643 rc.decltype = make([]string, rc.nc)
2644 for i := range rc.decltype {
2645 rc.decltype[i] = strings.ToLower(C.GoString(C.sqlite3_column_decltype(rc.s.s, C.int(i))))
2646 }
2647 }
2648 }
2649 return rc.decltype
2650 }
2651
2652 // DeclTypes return column types.
2653 func (rc *SQLiteRows) DeclTypes() []string {
2654 if rc.s == nil {
2655 return rc.decltype
2656 }
2657 rc.s.mu.Lock()
2658 defer rc.s.mu.Unlock()
2659 return rc.declTypes()
2660 }
2661
2662 // Next move cursor to next. Attempts to honor context timeout from QueryContext call.
2663 func (rc *SQLiteRows) Next(dest []driver.Value) error {
2664 if rc.s == nil {
2665 return io.EOF
2666 }
2667 rc.s.mu.Lock()
2668 defer rc.s.mu.Unlock()
2669
2670 if rc.s.closed {
2671 return io.EOF
2672 }
2673
2674 if rv := rc.pendingStep; rv >= 0 {
2675 rc.pendingStep = -1
2676 return rc.readStepResultLocked(dest, rv)
2677 }
2678
2679 if rc.stopCancellation == nil {
2680 if rc.ctx.Done() == nil {
2681 rv := C._sqlite3_step_internal(rc.s.s)
2682 return rc.readStepResultLocked(dest, rv)
2683 }
2684 conn := rc.s.c
2685 rc.stopCancellation = context.AfterFunc(rc.ctx, func() {
2686 conn.interruptActiveRows(rc)
2687 })
2688 }
2689 if err := rc.ctx.Err(); err != nil {
2690 return err
2691 }
2692 rv := rc.stepCancellableLocked()
2693 err := rc.readStepResultLocked(dest, rv)
2694 if ctxErr := rc.ctx.Err(); ctxErr != nil {
2695 return ctxErr
2696 }
2697 return err
2698 }
2699
2700 // eagerFirstStepLocked performs the first step of a cached statement
2701 // under the same cancellation rules as Next, records the post-step
2702 // column count, and drops the statement's cached metadata when SQLite
2703 // re-prepared it after a schema change. Note that this runs the first
2704 // step at query time, so a data-modifying statement issued through
2705 // Query executes even if Next is never called.
2706 func (rc *SQLiteRows) eagerFirstStepLocked() (C.int, error) {
2707 s := rc.s
2708 s.mu.Lock()
2709 defer s.mu.Unlock()
2710
2711 if rc.ctx.Done() != nil && rc.stopCancellation == nil {
2712 conn := s.c
2713 rc.stopCancellation = context.AfterFunc(rc.ctx, func() {
2714 conn.interruptActiveRows(rc)
2715 })
2716 }
2717 if err := rc.ctx.Err(); err != nil {
2718 rc.stopWatchingCancellation()
2719 return 0, err
2720 }
2721 var ncol, repreps C.int
2722 var rv C.int
2723 if rc.ctx.Done() == nil {
2724 rv = C._sqlite3_step_columns(s.s, &ncol, &repreps)
2725 } else {
2726 rc.startStepping()
2727 rv = C._sqlite3_step_columns(s.s, &ncol, &repreps)
2728 rc.finishStepping()
2729 }
2730 if err := rc.ctx.Err(); err != nil {
2731 rc.stopWatchingCancellation()
2732 C._sqlite3_reset_clear(s.s)
2733 return 0, err
2734 }
2735 if rv != C.SQLITE_ROW && rv != C.SQLITE_DONE {
2736 rc.stopWatchingCancellation()
2737 err := s.c.lastError()
2738 C._sqlite3_reset_clear(s.s)
2739 return 0, err
2740 }
2741 rc.nc = int32(ncol)
2742 if repreps != s.repreps {
2743 s.repreps = repreps
2744 s.metadata = nil
2745 }
2746 return rv, nil
2747 }
2748
2749 func (rc *SQLiteRows) stepCancellableLocked() C.int {
2750 rc.startStepping()
2751 defer rc.finishStepping()
2752 return C._sqlite3_step_internal(rc.s.s)
2753 }
2754
2755 func (rc *SQLiteRows) readStepResultLocked(dest []driver.Value, rv C.int) error {
2756 if rv == C.SQLITE_DONE {
2757 return io.EOF
2758 }
2759 if rv != C.SQLITE_ROW {
2760 rv = C.sqlite3_reset(rc.s.s)
2761 if rv != C.SQLITE_OK {
2762 return rc.s.c.lastError()
2763 }
2764 return nil
2765 }
2766
2767 rc.declTypes()
2768 if len(dest) == 0 {
2769 return nil
2770 }
2771 C._sqlite3_column_values(rc.s.s, C.int(len(dest)), rc.colvals)
2772 colvals := (*[(math.MaxInt32 - 1) / unsafe.Sizeof(C.sqlite3_go_col{})]C.sqlite3_go_col)(unsafe.Pointer(rc.colvals))[:len(dest):len(dest)]
2773
2774 decltype := rc.decltype
2775 _ = decltype[len(dest)-1]
2776 for i := range dest {
2777 col := &colvals[i]
2778 switch col.typ {
2779 case C.SQLITE_INTEGER:
2780 val := int64(col.i64)
2781 switch decltype[i] {
2782 case columnTimestamp, columnDatetime, columnDate:
2783 var t time.Time
2784 // Assume a millisecond unix timestamp if it's 13 digits -- too
2785 // large to be a reasonable timestamp in seconds.
2786 if val > 1e12 || val < -1e12 {
2787 val *= int64(time.Millisecond) // convert ms to nsec
2788 t = time.Unix(0, val)
2789 } else {
2790 t = time.Unix(val, 0)
2791 }
2792 t = t.UTC()
2793 if rc.s.c.loc != nil {
2794 t = t.In(rc.s.c.loc)
2795 }
2796 dest[i] = t
2797 case "boolean":
2798 dest[i] = val > 0
2799 default:
2800 dest[i] = val
2801 }
2802 case C.SQLITE_FLOAT:
2803 dest[i] = float64(col.f64)
2804 case C.SQLITE_BLOB:
2805 p := col.ptr
2806 if p == nil {
2807 dest[i] = []byte{}
2808 continue
2809 }
2810 n := col.n
2811 dest[i] = C.GoBytes(p, n)
2812 case C.SQLITE_NULL:
2813 dest[i] = nil
2814 case C.SQLITE_TEXT:
2815 var err error
2816 var timeVal time.Time
2817
2818 n := int(col.n)
2819 s := C.GoStringN((*C.char)(unsafe.Pointer(col.ptr)), C.int(n))
2820
2821 switch decltype[i] {
2822 case columnTimestamp, columnDatetime, columnDate:
2823 var t time.Time
2824 s = strings.TrimSuffix(s, "Z")
2825 for _, format := range SQLiteTimestampFormats {
2826 if timeVal, err = time.ParseInLocation(format, s, time.UTC); err == nil {
2827 t = timeVal
2828 break
2829 }
2830 }
2831 if err != nil {
2832 // The column is a time value, so return the zero time on parse failure.
2833 t = time.Time{}
2834 }
2835 if rc.s.c.loc != nil {
2836 t = t.In(rc.s.c.loc)
2837 }
2838 dest[i] = t
2839 default:
2840 dest[i] = s
2841 }
2842 }
2843 }
2844 return nil
2845 }