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