1// Copyright (C) 2019 Yasuhiro Matsumoto <mattn.jp@gmail.com>.
2// Copyright (C) 2018 G.J.R. Timmer <gjr.timmer@gmail.com>.
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// +build cgo
8
9package sqlite3
10
11/*
12#cgo CFLAGS: -std=gnu99
13#cgo CFLAGS: -DSQLITE_ENABLE_RTREE
14#cgo CFLAGS: -DSQLITE_THREADSAFE=1
15#cgo CFLAGS: -DHAVE_USLEEP=1
16#cgo CFLAGS: -DSQLITE_ENABLE_FTS3
17#cgo CFLAGS: -DSQLITE_ENABLE_FTS3_PARENTHESIS
18#cgo CFLAGS: -DSQLITE_ENABLE_FTS4_UNICODE61
19#cgo CFLAGS: -DSQLITE_TRACE_SIZE_LIMIT=15
20#cgo CFLAGS: -DSQLITE_OMIT_DEPRECATED
21#cgo CFLAGS: -DSQLITE_DISABLE_INTRINSIC
22#cgo CFLAGS: -DSQLITE_DEFAULT_WAL_SYNCHRONOUS=1
23#cgo CFLAGS: -DSQLITE_ENABLE_UPDATE_DELETE_LIMIT
24#cgo CFLAGS: -Wno-deprecated-declarations
25#cgo linux,!android CFLAGS: -DHAVE_PREAD64=1 -DHAVE_PWRITE64=1
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
50static int
51_sqlite3_open_v2(const char *filename, sqlite3 **ppDb, int flags, const char *zVfs) {
52#ifdef SQLITE_OPEN_URI
53  return sqlite3_open_v2(filename, ppDb, flags | SQLITE_OPEN_URI, zVfs);
54#else
55  return sqlite3_open_v2(filename, ppDb, flags, zVfs);
56#endif
57}
58
59static int
60_sqlite3_bind_text(sqlite3_stmt *stmt, int n, char *p, int np) {
61  return sqlite3_bind_text(stmt, n, p, np, SQLITE_TRANSIENT);
62}
63
64static int
65_sqlite3_bind_blob(sqlite3_stmt *stmt, int n, void *p, int np) {
66  return sqlite3_bind_blob(stmt, n, p, np, SQLITE_TRANSIENT);
67}
68
69#include <stdio.h>
70#include <stdint.h>
71
72static int
73_sqlite3_exec(sqlite3* db, const char* pcmd, long long* rowid, long long* changes)
74{
75  int rv = sqlite3_exec(db, pcmd, 0, 0, 0);
76  *rowid = (long long) sqlite3_last_insert_rowid(db);
77  *changes = (long long) sqlite3_changes(db);
78  return rv;
79}
80
81#ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
82extern int _sqlite3_step_blocking(sqlite3_stmt *stmt);
83extern int _sqlite3_step_row_blocking(sqlite3_stmt* stmt, long long* rowid, long long* changes);
84extern int _sqlite3_prepare_v2_blocking(sqlite3 *db, const char *zSql, int nBytes, sqlite3_stmt **ppStmt, const char **pzTail);
85
86static int
87_sqlite3_step_internal(sqlite3_stmt *stmt)
88{
89  return _sqlite3_step_blocking(stmt);
90}
91
92static int
93_sqlite3_step_row_internal(sqlite3_stmt* stmt, long long* rowid, long long* changes)
94{
95  return _sqlite3_step_row_blocking(stmt, rowid, changes);
96}
97
98static int
99_sqlite3_prepare_v2_internal(sqlite3 *db, const char *zSql, int nBytes, sqlite3_stmt **ppStmt, const char **pzTail)
100{
101  return _sqlite3_prepare_v2_blocking(db, zSql, nBytes, ppStmt, pzTail);
102}
103
104#else
105static int
106_sqlite3_step_internal(sqlite3_stmt *stmt)
107{
108  return sqlite3_step(stmt);
109}
110
111static int
112_sqlite3_step_row_internal(sqlite3_stmt* stmt, long long* rowid, long long* changes)
113{
114  int rv = sqlite3_step(stmt);
115  sqlite3* db = sqlite3_db_handle(stmt);
116  *rowid = (long long) sqlite3_last_insert_rowid(db);
117  *changes = (long long) sqlite3_changes(db);
118  return rv;
119}
120
121static int
122_sqlite3_prepare_v2_internal(sqlite3 *db, const char *zSql, int nBytes, sqlite3_stmt **ppStmt, const char **pzTail)
123{
124  return sqlite3_prepare_v2(db, zSql, nBytes, ppStmt, pzTail);
125}
126#endif
127
128void _sqlite3_result_text(sqlite3_context* ctx, const char* s) {
129  sqlite3_result_text(ctx, s, -1, &free);
130}
131
132void _sqlite3_result_blob(sqlite3_context* ctx, const void* b, int l) {
133  sqlite3_result_blob(ctx, b, l, SQLITE_TRANSIENT);
134}
135
136
137int _sqlite3_create_function(
138  sqlite3 *db,
139  const char *zFunctionName,
140  int nArg,
141  int eTextRep,
142  uintptr_t pApp,
143  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
144  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
145  void (*xFinal)(sqlite3_context*)
146) {
147  return sqlite3_create_function(db, zFunctionName, nArg, eTextRep, (void*) pApp, xFunc, xStep, xFinal);
148}
149
150void callbackTrampoline(sqlite3_context*, int, sqlite3_value**);
151void stepTrampoline(sqlite3_context*, int, sqlite3_value**);
152void doneTrampoline(sqlite3_context*);
153
154int compareTrampoline(void*, int, char*, int, char*);
155int commitHookTrampoline(void*);
156void rollbackHookTrampoline(void*);
157void updateHookTrampoline(void*, int, char*, char*, sqlite3_int64);
158
159int authorizerTrampoline(void*, int, char*, char*, char*, char*);
160
161#ifdef SQLITE_LIMIT_WORKER_THREADS
162# define _SQLITE_HAS_LIMIT
163# define SQLITE_LIMIT_LENGTH                    0
164# define SQLITE_LIMIT_SQL_LENGTH                1
165# define SQLITE_LIMIT_COLUMN                    2
166# define SQLITE_LIMIT_EXPR_DEPTH                3
167# define SQLITE_LIMIT_COMPOUND_SELECT           4
168# define SQLITE_LIMIT_VDBE_OP                   5
169# define SQLITE_LIMIT_FUNCTION_ARG              6
170# define SQLITE_LIMIT_ATTACHED                  7
171# define SQLITE_LIMIT_LIKE_PATTERN_LENGTH       8
172# define SQLITE_LIMIT_VARIABLE_NUMBER           9
173# define SQLITE_LIMIT_TRIGGER_DEPTH            10
174# define SQLITE_LIMIT_WORKER_THREADS           11
175# else
176# define SQLITE_LIMIT_WORKER_THREADS           11
177#endif
178
179static int _sqlite3_limit(sqlite3* db, int limitId, int newLimit) {
180#ifndef _SQLITE_HAS_LIMIT
181  return -1;
182#else
183  return sqlite3_limit(db, limitId, newLimit);
184#endif
185}
186
187#if SQLITE_VERSION_NUMBER < 3012000
188static int sqlite3_system_errno(sqlite3 *db) {
189  return 0;
190}
191#endif
192*/
193import "C"
194import (
195	"context"
196	"database/sql"
197	"database/sql/driver"
198	"errors"
199	"fmt"
200	"io"
201	"net/url"
202	"reflect"
203	"runtime"
204	"strconv"
205	"strings"
206	"sync"
207	"syscall"
208	"time"
209	"unsafe"
210)
211
212// SQLiteTimestampFormats is timestamp formats understood by both this module
213// and SQLite.  The first format in the slice will be used when saving time
214// values into the database. When parsing a string from a timestamp or datetime
215// column, the formats are tried in order.
216var SQLiteTimestampFormats = []string{
217	// By default, store timestamps with whatever timezone they come with.
218	// When parsed, they will be returned with the same timezone.
219	"2006-01-02 15:04:05.999999999-07:00",
220	"2006-01-02T15:04:05.999999999-07:00",
221	"2006-01-02 15:04:05.999999999",
222	"2006-01-02T15:04:05.999999999",
223	"2006-01-02 15:04:05",
224	"2006-01-02T15:04:05",
225	"2006-01-02 15:04",
226	"2006-01-02T15:04",
227	"2006-01-02",
228}
229
230const (
231	columnDate      string = "date"
232	columnDatetime  string = "datetime"
233	columnTimestamp string = "timestamp"
234)
235
236func init() {
237	sql.Register("sqlite3", &SQLiteDriver{})
238}
239
240// Version returns SQLite library version information.
241func Version() (libVersion string, libVersionNumber int, sourceID string) {
242	libVersion = C.GoString(C.sqlite3_libversion())
243	libVersionNumber = int(C.sqlite3_libversion_number())
244	sourceID = C.GoString(C.sqlite3_sourceid())
245	return libVersion, libVersionNumber, sourceID
246}
247
248const (
249	// used by authorizer and pre_update_hook
250	SQLITE_DELETE = C.SQLITE_DELETE
251	SQLITE_INSERT = C.SQLITE_INSERT
252	SQLITE_UPDATE = C.SQLITE_UPDATE
253
254	// used by authorzier - as return value
255	SQLITE_OK     = C.SQLITE_OK
256	SQLITE_IGNORE = C.SQLITE_IGNORE
257	SQLITE_DENY   = C.SQLITE_DENY
258
259	// different actions query tries to do - passed as argument to authorizer
260	SQLITE_CREATE_INDEX        = C.SQLITE_CREATE_INDEX
261	SQLITE_CREATE_TABLE        = C.SQLITE_CREATE_TABLE
262	SQLITE_CREATE_TEMP_INDEX   = C.SQLITE_CREATE_TEMP_INDEX
263	SQLITE_CREATE_TEMP_TABLE   = C.SQLITE_CREATE_TEMP_TABLE
264	SQLITE_CREATE_TEMP_TRIGGER = C.SQLITE_CREATE_TEMP_TRIGGER
265	SQLITE_CREATE_TEMP_VIEW    = C.SQLITE_CREATE_TEMP_VIEW
266	SQLITE_CREATE_TRIGGER      = C.SQLITE_CREATE_TRIGGER
267	SQLITE_CREATE_VIEW         = C.SQLITE_CREATE_VIEW
268	SQLITE_CREATE_VTABLE       = C.SQLITE_CREATE_VTABLE
269	SQLITE_DROP_INDEX          = C.SQLITE_DROP_INDEX
270	SQLITE_DROP_TABLE          = C.SQLITE_DROP_TABLE
271	SQLITE_DROP_TEMP_INDEX     = C.SQLITE_DROP_TEMP_INDEX
272	SQLITE_DROP_TEMP_TABLE     = C.SQLITE_DROP_TEMP_TABLE
273	SQLITE_DROP_TEMP_TRIGGER   = C.SQLITE_DROP_TEMP_TRIGGER
274	SQLITE_DROP_TEMP_VIEW      = C.SQLITE_DROP_TEMP_VIEW
275	SQLITE_DROP_TRIGGER        = C.SQLITE_DROP_TRIGGER
276	SQLITE_DROP_VIEW           = C.SQLITE_DROP_VIEW
277	SQLITE_DROP_VTABLE         = C.SQLITE_DROP_VTABLE
278	SQLITE_PRAGMA              = C.SQLITE_PRAGMA
279	SQLITE_READ                = C.SQLITE_READ
280	SQLITE_SELECT              = C.SQLITE_SELECT
281	SQLITE_TRANSACTION         = C.SQLITE_TRANSACTION
282	SQLITE_ATTACH              = C.SQLITE_ATTACH
283	SQLITE_DETACH              = C.SQLITE_DETACH
284	SQLITE_ALTER_TABLE         = C.SQLITE_ALTER_TABLE
285	SQLITE_REINDEX             = C.SQLITE_REINDEX
286	SQLITE_ANALYZE             = C.SQLITE_ANALYZE
287	SQLITE_FUNCTION            = C.SQLITE_FUNCTION
288	SQLITE_SAVEPOINT           = C.SQLITE_SAVEPOINT
289	SQLITE_COPY                = C.SQLITE_COPY
290	/*SQLITE_RECURSIVE           = C.SQLITE_RECURSIVE*/
291)
292
293// SQLiteDriver implements driver.Driver.
294type SQLiteDriver struct {
295	Extensions  []string
296	ConnectHook func(*SQLiteConn) error
297}
298
299// SQLiteConn implements driver.Conn.
300type SQLiteConn struct {
301	mu          sync.Mutex
302	db          *C.sqlite3
303	loc         *time.Location
304	txlock      string
305	funcs       []*functionInfo
306	aggregators []*aggInfo
307}
308
309// SQLiteTx implements driver.Tx.
310type SQLiteTx struct {
311	c *SQLiteConn
312}
313
314// SQLiteStmt implements driver.Stmt.
315type SQLiteStmt struct {
316	mu     sync.Mutex
317	c      *SQLiteConn
318	s      *C.sqlite3_stmt
319	t      string
320	closed bool
321	cls    bool
322}
323
324// SQLiteResult implements sql.Result.
325type SQLiteResult struct {
326	id      int64
327	changes int64
328}
329
330// SQLiteRows implements driver.Rows.
331type SQLiteRows struct {
332	s        *SQLiteStmt
333	nc       int
334	cols     []string
335	decltype []string
336	cls      bool
337	closed   bool
338	ctx      context.Context // no better alternative to pass context into Next() method
339}
340
341type functionInfo struct {
342	f                 reflect.Value
343	argConverters     []callbackArgConverter
344	variadicConverter callbackArgConverter
345	retConverter      callbackRetConverter
346}
347
348func (fi *functionInfo) Call(ctx *C.sqlite3_context, argv []*C.sqlite3_value) {
349	args, err := callbackConvertArgs(argv, fi.argConverters, fi.variadicConverter)
350	if err != nil {
351		callbackError(ctx, err)
352		return
353	}
354
355	ret := fi.f.Call(args)
356
357	if len(ret) == 2 && ret[1].Interface() != nil {
358		callbackError(ctx, ret[1].Interface().(error))
359		return
360	}
361
362	err = fi.retConverter(ctx, ret[0])
363	if err != nil {
364		callbackError(ctx, err)
365		return
366	}
367}
368
369type aggInfo struct {
370	constructor reflect.Value
371
372	// Active aggregator objects for aggregations in flight. The
373	// aggregators are indexed by a counter stored in the aggregation
374	// user data space provided by sqlite.
375	active map[int64]reflect.Value
376	next   int64
377
378	stepArgConverters     []callbackArgConverter
379	stepVariadicConverter callbackArgConverter
380
381	doneRetConverter callbackRetConverter
382}
383
384func (ai *aggInfo) agg(ctx *C.sqlite3_context) (int64, reflect.Value, error) {
385	aggIdx := (*int64)(C.sqlite3_aggregate_context(ctx, C.int(8)))
386	if *aggIdx == 0 {
387		*aggIdx = ai.next
388		ret := ai.constructor.Call(nil)
389		if len(ret) == 2 && ret[1].Interface() != nil {
390			return 0, reflect.Value{}, ret[1].Interface().(error)
391		}
392		if ret[0].IsNil() {
393			return 0, reflect.Value{}, errors.New("aggregator constructor returned nil state")
394		}
395		ai.next++
396		ai.active[*aggIdx] = ret[0]
397	}
398	return *aggIdx, ai.active[*aggIdx], nil
399}
400
401func (ai *aggInfo) Step(ctx *C.sqlite3_context, argv []*C.sqlite3_value) {
402	_, agg, err := ai.agg(ctx)
403	if err != nil {
404		callbackError(ctx, err)
405		return
406	}
407
408	args, err := callbackConvertArgs(argv, ai.stepArgConverters, ai.stepVariadicConverter)
409	if err != nil {
410		callbackError(ctx, err)
411		return
412	}
413
414	ret := agg.MethodByName("Step").Call(args)
415	if len(ret) == 1 && ret[0].Interface() != nil {
416		callbackError(ctx, ret[0].Interface().(error))
417		return
418	}
419}
420
421func (ai *aggInfo) Done(ctx *C.sqlite3_context) {
422	idx, agg, err := ai.agg(ctx)
423	if err != nil {
424		callbackError(ctx, err)
425		return
426	}
427	defer func() { delete(ai.active, idx) }()
428
429	ret := agg.MethodByName("Done").Call(nil)
430	if len(ret) == 2 && ret[1].Interface() != nil {
431		callbackError(ctx, ret[1].Interface().(error))
432		return
433	}
434
435	err = ai.doneRetConverter(ctx, ret[0])
436	if err != nil {
437		callbackError(ctx, err)
438		return
439	}
440}
441
442// Commit transaction.
443func (tx *SQLiteTx) Commit() error {
444	_, err := tx.c.exec(context.Background(), "COMMIT", nil)
445	if err != nil && err.(Error).Code == C.SQLITE_BUSY {
446		// sqlite3 will leave the transaction open in this scenario.
447		// However, database/sql considers the transaction complete once we
448		// return from Commit() - we must clean up to honour its semantics.
449		tx.c.exec(context.Background(), "ROLLBACK", nil)
450	}
451	return err
452}
453
454// Rollback transaction.
455func (tx *SQLiteTx) Rollback() error {
456	_, err := tx.c.exec(context.Background(), "ROLLBACK", nil)
457	return err
458}
459
460// RegisterCollation makes a Go function available as a collation.
461//
462// cmp receives two UTF-8 strings, a and b. The result should be 0 if
463// a==b, -1 if a < b, and +1 if a > b.
464//
465// cmp must always return the same result given the same
466// inputs. Additionally, it must have the following properties for all
467// strings A, B and C: if A==B then B==A; if A==B and B==C then A==C;
468// if A<B then B>A; if A<B and B<C then A<C.
469//
470// If cmp does not obey these constraints, sqlite3's behavior is
471// undefined when the collation is used.
472func (c *SQLiteConn) RegisterCollation(name string, cmp func(string, string) int) error {
473	handle := newHandle(c, cmp)
474	cname := C.CString(name)
475	defer C.free(unsafe.Pointer(cname))
476	rv := C.sqlite3_create_collation(c.db, cname, C.SQLITE_UTF8, unsafe.Pointer(handle), (*[0]byte)(unsafe.Pointer(C.compareTrampoline)))
477	if rv != C.SQLITE_OK {
478		return c.lastError()
479	}
480	return nil
481}
482
483// RegisterCommitHook sets the commit hook for a connection.
484//
485// If the callback returns non-zero the transaction will become a rollback.
486//
487// If there is an existing commit hook for this connection, it will be
488// removed. If callback is nil the existing hook (if any) will be removed
489// without creating a new one.
490func (c *SQLiteConn) RegisterCommitHook(callback func() int) {
491	if callback == nil {
492		C.sqlite3_commit_hook(c.db, nil, nil)
493	} else {
494		C.sqlite3_commit_hook(c.db, (*[0]byte)(C.commitHookTrampoline), unsafe.Pointer(newHandle(c, callback)))
495	}
496}
497
498// RegisterRollbackHook sets the rollback hook for a connection.
499//
500// If there is an existing rollback hook for this connection, it will be
501// removed. If callback is nil the existing hook (if any) will be removed
502// without creating a new one.
503func (c *SQLiteConn) RegisterRollbackHook(callback func()) {
504	if callback == nil {
505		C.sqlite3_rollback_hook(c.db, nil, nil)
506	} else {
507		C.sqlite3_rollback_hook(c.db, (*[0]byte)(C.rollbackHookTrampoline), unsafe.Pointer(newHandle(c, callback)))
508	}
509}
510
511// RegisterUpdateHook sets the update hook for a connection.
512//
513// The parameters to the callback are the operation (one of the constants
514// SQLITE_INSERT, SQLITE_DELETE, or SQLITE_UPDATE), the database name, the
515// table name, and the rowid.
516//
517// If there is an existing update hook for this connection, it will be
518// removed. If callback is nil the existing hook (if any) will be removed
519// without creating a new one.
520func (c *SQLiteConn) RegisterUpdateHook(callback func(int, string, string, int64)) {
521	if callback == nil {
522		C.sqlite3_update_hook(c.db, nil, nil)
523	} else {
524		C.sqlite3_update_hook(c.db, (*[0]byte)(C.updateHookTrampoline), unsafe.Pointer(newHandle(c, callback)))
525	}
526}
527
528// RegisterAuthorizer sets the authorizer for connection.
529//
530// The parameters to the callback are the operation (one of the constants
531// SQLITE_INSERT, SQLITE_DELETE, or SQLITE_UPDATE), and 1 to 3 arguments,
532// depending on operation. More details see:
533// https://www.sqlite.org/c3ref/c_alter_table.html
534func (c *SQLiteConn) RegisterAuthorizer(callback func(int, string, string, string) int) {
535	if callback == nil {
536		C.sqlite3_set_authorizer(c.db, nil, nil)
537	} else {
538		C.sqlite3_set_authorizer(c.db, (*[0]byte)(C.authorizerTrampoline), unsafe.Pointer(newHandle(c, callback)))
539	}
540}
541
542// RegisterFunc makes a Go function available as a SQLite function.
543//
544// The Go function can have arguments of the following types: any
545// numeric type except complex, bool, []byte, string and
546// interface{}. interface{} arguments are given the direct translation
547// of the SQLite data type: int64 for INTEGER, float64 for FLOAT,
548// []byte for BLOB, string for TEXT.
549//
550// The function can additionally be variadic, as long as the type of
551// the variadic argument is one of the above.
552//
553// If pure is true. SQLite will assume that the function's return
554// value depends only on its inputs, and make more aggressive
555// optimizations in its queries.
556//
557// See _example/go_custom_funcs for a detailed example.
558func (c *SQLiteConn) RegisterFunc(name string, impl interface{}, pure bool) error {
559	var fi functionInfo
560	fi.f = reflect.ValueOf(impl)
561	t := fi.f.Type()
562	if t.Kind() != reflect.Func {
563		return errors.New("Non-function passed to RegisterFunc")
564	}
565	if t.NumOut() != 1 && t.NumOut() != 2 {
566		return errors.New("SQLite functions must return 1 or 2 values")
567	}
568	if t.NumOut() == 2 && !t.Out(1).Implements(reflect.TypeOf((*error)(nil)).Elem()) {
569		return errors.New("Second return value of SQLite function must be error")
570	}
571
572	numArgs := t.NumIn()
573	if t.IsVariadic() {
574		numArgs--
575	}
576
577	for i := 0; i < numArgs; i++ {
578		conv, err := callbackArg(t.In(i))
579		if err != nil {
580			return err
581		}
582		fi.argConverters = append(fi.argConverters, conv)
583	}
584
585	if t.IsVariadic() {
586		conv, err := callbackArg(t.In(numArgs).Elem())
587		if err != nil {
588			return err
589		}
590		fi.variadicConverter = conv
591		// Pass -1 to sqlite so that it allows any number of
592		// arguments. The call helper verifies that the minimum number
593		// of arguments is present for variadic functions.
594		numArgs = -1
595	}
596
597	conv, err := callbackRet(t.Out(0))
598	if err != nil {
599		return err
600	}
601	fi.retConverter = conv
602
603	// fi must outlast the database connection, or we'll have dangling pointers.
604	c.funcs = append(c.funcs, &fi)
605
606	cname := C.CString(name)
607	defer C.free(unsafe.Pointer(cname))
608	opts := C.SQLITE_UTF8
609	if pure {
610		opts |= C.SQLITE_DETERMINISTIC
611	}
612	rv := sqlite3CreateFunction(c.db, cname, C.int(numArgs), C.int(opts), newHandle(c, &fi), C.callbackTrampoline, nil, nil)
613	if rv != C.SQLITE_OK {
614		return c.lastError()
615	}
616	return nil
617}
618
619func sqlite3CreateFunction(db *C.sqlite3, zFunctionName *C.char, nArg C.int, eTextRep C.int, pApp uintptr, xFunc unsafe.Pointer, xStep unsafe.Pointer, xFinal unsafe.Pointer) C.int {
620	return C._sqlite3_create_function(db, zFunctionName, nArg, eTextRep, C.uintptr_t(pApp), (*[0]byte)(xFunc), (*[0]byte)(xStep), (*[0]byte)(xFinal))
621}
622
623// RegisterAggregator makes a Go type available as a SQLite aggregation function.
624//
625// Because aggregation is incremental, it's implemented in Go with a
626// type that has 2 methods: func Step(values) accumulates one row of
627// data into the accumulator, and func Done() ret finalizes and
628// returns the aggregate value. "values" and "ret" may be any type
629// supported by RegisterFunc.
630//
631// RegisterAggregator takes as implementation a constructor function
632// that constructs an instance of the aggregator type each time an
633// aggregation begins. The constructor must return a pointer to a
634// type, or an interface that implements Step() and Done().
635//
636// The constructor function and the Step/Done methods may optionally
637// return an error in addition to their other return values.
638//
639// See _example/go_custom_funcs for a detailed example.
640func (c *SQLiteConn) RegisterAggregator(name string, impl interface{}, pure bool) error {
641	var ai aggInfo
642	ai.constructor = reflect.ValueOf(impl)
643	t := ai.constructor.Type()
644	if t.Kind() != reflect.Func {
645		return errors.New("non-function passed to RegisterAggregator")
646	}
647	if t.NumOut() != 1 && t.NumOut() != 2 {
648		return errors.New("SQLite aggregator constructors must return 1 or 2 values")
649	}
650	if t.NumOut() == 2 && !t.Out(1).Implements(reflect.TypeOf((*error)(nil)).Elem()) {
651		return errors.New("Second return value of SQLite function must be error")
652	}
653	if t.NumIn() != 0 {
654		return errors.New("SQLite aggregator constructors must not have arguments")
655	}
656
657	agg := t.Out(0)
658	switch agg.Kind() {
659	case reflect.Ptr, reflect.Interface:
660	default:
661		return errors.New("SQlite aggregator constructor must return a pointer object")
662	}
663	stepFn, found := agg.MethodByName("Step")
664	if !found {
665		return errors.New("SQlite aggregator doesn't have a Step() function")
666	}
667	step := stepFn.Type
668	if step.NumOut() != 0 && step.NumOut() != 1 {
669		return errors.New("SQlite aggregator Step() function must return 0 or 1 values")
670	}
671	if step.NumOut() == 1 && !step.Out(0).Implements(reflect.TypeOf((*error)(nil)).Elem()) {
672		return errors.New("type of SQlite aggregator Step() return value must be error")
673	}
674
675	stepNArgs := step.NumIn()
676	start := 0
677	if agg.Kind() == reflect.Ptr {
678		// Skip over the method receiver
679		stepNArgs--
680		start++
681	}
682	if step.IsVariadic() {
683		stepNArgs--
684	}
685	for i := start; i < start+stepNArgs; i++ {
686		conv, err := callbackArg(step.In(i))
687		if err != nil {
688			return err
689		}
690		ai.stepArgConverters = append(ai.stepArgConverters, conv)
691	}
692	if step.IsVariadic() {
693		conv, err := callbackArg(step.In(start + stepNArgs).Elem())
694		if err != nil {
695			return err
696		}
697		ai.stepVariadicConverter = conv
698		// Pass -1 to sqlite so that it allows any number of
699		// arguments. The call helper verifies that the minimum number
700		// of arguments is present for variadic functions.
701		stepNArgs = -1
702	}
703
704	doneFn, found := agg.MethodByName("Done")
705	if !found {
706		return errors.New("SQlite aggregator doesn't have a Done() function")
707	}
708	done := doneFn.Type
709	doneNArgs := done.NumIn()
710	if agg.Kind() == reflect.Ptr {
711		// Skip over the method receiver
712		doneNArgs--
713	}
714	if doneNArgs != 0 {
715		return errors.New("SQlite aggregator Done() function must have no arguments")
716	}
717	if done.NumOut() != 1 && done.NumOut() != 2 {
718		return errors.New("SQLite aggregator Done() function must return 1 or 2 values")
719	}
720	if done.NumOut() == 2 && !done.Out(1).Implements(reflect.TypeOf((*error)(nil)).Elem()) {
721		return errors.New("second return value of SQLite aggregator Done() function must be error")
722	}
723
724	conv, err := callbackRet(done.Out(0))
725	if err != nil {
726		return err
727	}
728	ai.doneRetConverter = conv
729	ai.active = make(map[int64]reflect.Value)
730	ai.next = 1
731
732	// ai must outlast the database connection, or we'll have dangling pointers.
733	c.aggregators = append(c.aggregators, &ai)
734
735	cname := C.CString(name)
736	defer C.free(unsafe.Pointer(cname))
737	opts := C.SQLITE_UTF8
738	if pure {
739		opts |= C.SQLITE_DETERMINISTIC
740	}
741	rv := sqlite3CreateFunction(c.db, cname, C.int(stepNArgs), C.int(opts), newHandle(c, &ai), nil, C.stepTrampoline, C.doneTrampoline)
742	if rv != C.SQLITE_OK {
743		return c.lastError()
744	}
745	return nil
746}
747
748// AutoCommit return which currently auto commit or not.
749func (c *SQLiteConn) AutoCommit() bool {
750	c.mu.Lock()
751	defer c.mu.Unlock()
752	return int(C.sqlite3_get_autocommit(c.db)) != 0
753}
754
755func (c *SQLiteConn) lastError() error {
756	return lastError(c.db)
757}
758
759// Note: may be called with db == nil
760func lastError(db *C.sqlite3) error {
761	rv := C.sqlite3_errcode(db) // returns SQLITE_NOMEM if db == nil
762	if rv == C.SQLITE_OK {
763		return nil
764	}
765	extrv := C.sqlite3_extended_errcode(db)    // returns SQLITE_NOMEM if db == nil
766	errStr := C.GoString(C.sqlite3_errmsg(db)) // returns "out of memory" if db == nil
767
768	// https://www.sqlite.org/c3ref/system_errno.html
769	// sqlite3_system_errno is only meaningful if the error code was SQLITE_CANTOPEN,
770	// or it was SQLITE_IOERR and the extended code was not SQLITE_IOERR_NOMEM
771	var systemErrno syscall.Errno
772	if rv == C.SQLITE_CANTOPEN || (rv == C.SQLITE_IOERR && extrv != C.SQLITE_IOERR_NOMEM) {
773		systemErrno = syscall.Errno(C.sqlite3_system_errno(db))
774	}
775
776	return Error{
777		Code:         ErrNo(rv),
778		ExtendedCode: ErrNoExtended(extrv),
779		SystemErrno:  systemErrno,
780		err:          errStr,
781	}
782}
783
784// Exec implements Execer.
785func (c *SQLiteConn) Exec(query string, args []driver.Value) (driver.Result, error) {
786	list := make([]namedValue, len(args))
787	for i, v := range args {
788		list[i] = namedValue{
789			Ordinal: i + 1,
790			Value:   v,
791		}
792	}
793	return c.exec(context.Background(), query, list)
794}
795
796func (c *SQLiteConn) exec(ctx context.Context, query string, args []namedValue) (driver.Result, error) {
797	start := 0
798	for {
799		s, err := c.prepare(ctx, query)
800		if err != nil {
801			return nil, err
802		}
803		var res driver.Result
804		if s.(*SQLiteStmt).s != nil {
805			na := s.NumInput()
806			if len(args) < na {
807				s.Close()
808				return nil, fmt.Errorf("not enough args to execute query: want %d got %d", na, len(args))
809			}
810			for i := 0; i < na; i++ {
811				args[i].Ordinal -= start
812			}
813			res, err = s.(*SQLiteStmt).exec(ctx, args[:na])
814			if err != nil && err != driver.ErrSkip {
815				s.Close()
816				return nil, err
817			}
818			args = args[na:]
819			start += na
820		}
821		tail := s.(*SQLiteStmt).t
822		s.Close()
823		if tail == "" {
824			return res, nil
825		}
826		query = tail
827	}
828}
829
830type namedValue struct {
831	Name    string
832	Ordinal int
833	Value   driver.Value
834}
835
836// Query implements Queryer.
837func (c *SQLiteConn) Query(query string, args []driver.Value) (driver.Rows, error) {
838	list := make([]namedValue, len(args))
839	for i, v := range args {
840		list[i] = namedValue{
841			Ordinal: i + 1,
842			Value:   v,
843		}
844	}
845	return c.query(context.Background(), query, list)
846}
847
848func (c *SQLiteConn) query(ctx context.Context, query string, args []namedValue) (driver.Rows, error) {
849	start := 0
850	for {
851		s, err := c.prepare(ctx, query)
852		if err != nil {
853			return nil, err
854		}
855		s.(*SQLiteStmt).cls = true
856		na := s.NumInput()
857		if len(args) < na {
858			return nil, fmt.Errorf("not enough args to execute query: want %d got %d", na, len(args))
859		}
860		for i := 0; i < na; i++ {
861			args[i].Ordinal -= start
862		}
863		rows, err := s.(*SQLiteStmt).query(ctx, args[:na])
864		if err != nil && err != driver.ErrSkip {
865			s.Close()
866			return rows, err
867		}
868		args = args[na:]
869		start += na
870		tail := s.(*SQLiteStmt).t
871		if tail == "" {
872			return rows, nil
873		}
874		rows.Close()
875		s.Close()
876		query = tail
877	}
878}
879
880// Begin transaction.
881func (c *SQLiteConn) Begin() (driver.Tx, error) {
882	return c.begin(context.Background())
883}
884
885func (c *SQLiteConn) begin(ctx context.Context) (driver.Tx, error) {
886	if _, err := c.exec(ctx, c.txlock, nil); err != nil {
887		return nil, err
888	}
889	return &SQLiteTx{c}, nil
890}
891
892// Open database and return a new connection.
893//
894// A pragma can take either zero or one argument.
895// The argument is may be either in parentheses or it may be separated from
896// the pragma name by an equal sign. The two syntaxes yield identical results.
897// In many pragmas, the argument is a boolean. The boolean can be one of:
898//    1 yes true on
899//    0 no false off
900//
901// You can specify a DSN string using a URI as the filename.
902//   test.db
903//   file:test.db?cache=shared&mode=memory
904//   :memory:
905//   file::memory:
906//
907//   mode
908//     Access mode of the database.
909//     https://www.sqlite.org/c3ref/open.html
910//     Values:
911//      - ro
912//      - rw
913//      - rwc
914//      - memory
915//
916//   cache
917//     SQLite Shared-Cache Mode
918//     https://www.sqlite.org/sharedcache.html
919//     Values:
920//       - shared
921//       - private
922//
923//   immutable=Boolean
924//     The immutable parameter is a boolean query parameter that indicates
925//     that the database file is stored on read-only media. When immutable is set,
926//     SQLite assumes that the database file cannot be changed,
927//     even by a process with higher privilege,
928//     and so the database is opened read-only and all locking and change detection is disabled.
929//     Caution: Setting the immutable property on a database file that
930//     does in fact change can result in incorrect query results and/or SQLITE_CORRUPT errors.
931//
932// go-sqlite3 adds the following query parameters to those used by SQLite:
933//   _loc=XXX
934//     Specify location of time format. It's possible to specify "auto".
935//
936//   _mutex=XXX
937//     Specify mutex mode. XXX can be "no", "full".
938//
939//   _txlock=XXX
940//     Specify locking behavior for transactions.  XXX can be "immediate",
941//     "deferred", "exclusive".
942//
943//   _auto_vacuum=X | _vacuum=X
944//     0 | none - Auto Vacuum disabled
945//     1 | full - Auto Vacuum FULL
946//     2 | incremental - Auto Vacuum Incremental
947//
948//   _busy_timeout=XXX"| _timeout=XXX
949//     Specify value for sqlite3_busy_timeout.
950//
951//   _case_sensitive_like=Boolean | _cslike=Boolean
952//     https://www.sqlite.org/pragma.html#pragma_case_sensitive_like
953//     Default or disabled the LIKE operation is case-insensitive.
954//     When enabling this options behaviour of LIKE will become case-sensitive.
955//
956//   _defer_foreign_keys=Boolean | _defer_fk=Boolean
957//     Defer Foreign Keys until outermost transaction is committed.
958//
959//   _foreign_keys=Boolean | _fk=Boolean
960//     Enable or disable enforcement of foreign keys.
961//
962//   _ignore_check_constraints=Boolean
963//     This pragma enables or disables the enforcement of CHECK constraints.
964//     The default setting is off, meaning that CHECK constraints are enforced by default.
965//
966//   _journal_mode=MODE | _journal=MODE
967//     Set journal mode for the databases associated with the current connection.
968//     https://www.sqlite.org/pragma.html#pragma_journal_mode
969//
970//   _locking_mode=X | _locking=X
971//     Sets the database connection locking-mode.
972//     The locking-mode is either NORMAL or EXCLUSIVE.
973//     https://www.sqlite.org/pragma.html#pragma_locking_mode
974//
975//   _query_only=Boolean
976//     The query_only pragma prevents all changes to database files when enabled.
977//
978//   _recursive_triggers=Boolean | _rt=Boolean
979//     Enable or disable recursive triggers.
980//
981//   _secure_delete=Boolean|FAST
982//     When secure_delete is on, SQLite overwrites deleted content with zeros.
983//     https://www.sqlite.org/pragma.html#pragma_secure_delete
984//
985//   _synchronous=X | _sync=X
986//     Change the setting of the "synchronous" flag.
987//     https://www.sqlite.org/pragma.html#pragma_synchronous
988//
989//   _writable_schema=Boolean
990//     When this pragma is on, the SQLITE_MASTER tables in which database
991//     can be changed using ordinary UPDATE, INSERT, and DELETE statements.
992//     Warning: misuse of this pragma can easily result in a corrupt database file.
993//
994//
995func (d *SQLiteDriver) Open(dsn string) (driver.Conn, error) {
996	if C.sqlite3_threadsafe() == 0 {
997		return nil, errors.New("sqlite library was not compiled for thread-safe operation")
998	}
999
1000	var pkey string
1001
1002	// Options
1003	var loc *time.Location
1004	authCreate := false
1005	authUser := ""
1006	authPass := ""
1007	authCrypt := ""
1008	authSalt := ""
1009	mutex := C.int(C.SQLITE_OPEN_FULLMUTEX)
1010	txlock := "BEGIN"
1011
1012	// PRAGMA's
1013	autoVacuum := -1
1014	busyTimeout := 5000
1015	caseSensitiveLike := -1
1016	deferForeignKeys := -1
1017	foreignKeys := -1
1018	ignoreCheckConstraints := -1
1019	var journalMode string
1020	lockingMode := "NORMAL"
1021	queryOnly := -1
1022	recursiveTriggers := -1
1023	secureDelete := "DEFAULT"
1024	synchronousMode := "NORMAL"
1025	writableSchema := -1
1026
1027	pos := strings.IndexRune(dsn, '?')
1028	if pos >= 1 {
1029		params, err := url.ParseQuery(dsn[pos+1:])
1030		if err != nil {
1031			return nil, err
1032		}
1033
1034		// Authentication
1035		if _, ok := params["_auth"]; ok {
1036			authCreate = true
1037		}
1038		if val := params.Get("_auth_user"); val != "" {
1039			authUser = val
1040		}
1041		if val := params.Get("_auth_pass"); val != "" {
1042			authPass = val
1043		}
1044		if val := params.Get("_auth_crypt"); val != "" {
1045			authCrypt = val
1046		}
1047		if val := params.Get("_auth_salt"); val != "" {
1048			authSalt = val
1049		}
1050
1051		// _loc
1052		if val := params.Get("_loc"); val != "" {
1053			switch strings.ToLower(val) {
1054			case "auto":
1055				loc = time.Local
1056			default:
1057				loc, err = time.LoadLocation(val)
1058				if err != nil {
1059					return nil, fmt.Errorf("Invalid _loc: %v: %v", val, err)
1060				}
1061			}
1062		}
1063
1064		// _mutex
1065		if val := params.Get("_mutex"); val != "" {
1066			switch strings.ToLower(val) {
1067			case "no":
1068				mutex = C.SQLITE_OPEN_NOMUTEX
1069			case "full":
1070				mutex = C.SQLITE_OPEN_FULLMUTEX
1071			default:
1072				return nil, fmt.Errorf("Invalid _mutex: %v", val)
1073			}
1074		}
1075
1076		// _txlock
1077		if val := params.Get("_txlock"); val != "" {
1078			switch strings.ToLower(val) {
1079			case "immediate":
1080				txlock = "BEGIN IMMEDIATE"
1081			case "exclusive":
1082				txlock = "BEGIN EXCLUSIVE"
1083			case "deferred":
1084				txlock = "BEGIN"
1085			default:
1086				return nil, fmt.Errorf("Invalid _txlock: %v", val)
1087			}
1088		}
1089
1090		// Auto Vacuum (_vacuum)
1091		//
1092		// https://www.sqlite.org/pragma.html#pragma_auto_vacuum
1093		//
1094		pkey = "" // Reset pkey
1095		if _, ok := params["_auto_vacuum"]; ok {
1096			pkey = "_auto_vacuum"
1097		}
1098		if _, ok := params["_vacuum"]; ok {
1099			pkey = "_vacuum"
1100		}
1101		if val := params.Get(pkey); val != "" {
1102			switch strings.ToLower(val) {
1103			case "0", "none":
1104				autoVacuum = 0
1105			case "1", "full":
1106				autoVacuum = 1
1107			case "2", "incremental":
1108				autoVacuum = 2
1109			default:
1110				return nil, fmt.Errorf("Invalid _auto_vacuum: %v, expecting value of '0 NONE 1 FULL 2 INCREMENTAL'", val)
1111			}
1112		}
1113
1114		// Busy Timeout (_busy_timeout)
1115		//
1116		// https://www.sqlite.org/pragma.html#pragma_busy_timeout
1117		//
1118		pkey = "" // Reset pkey
1119		if _, ok := params["_busy_timeout"]; ok {
1120			pkey = "_busy_timeout"
1121		}
1122		if _, ok := params["_timeout"]; ok {
1123			pkey = "_timeout"
1124		}
1125		if val := params.Get(pkey); val != "" {
1126			iv, err := strconv.ParseInt(val, 10, 64)
1127			if err != nil {
1128				return nil, fmt.Errorf("Invalid _busy_timeout: %v: %v", val, err)
1129			}
1130			busyTimeout = int(iv)
1131		}
1132
1133		// Case Sensitive Like (_cslike)
1134		//
1135		// https://www.sqlite.org/pragma.html#pragma_case_sensitive_like
1136		//
1137		pkey = "" // Reset pkey
1138		if _, ok := params["_case_sensitive_like"]; ok {
1139			pkey = "_case_sensitive_like"
1140		}
1141		if _, ok := params["_cslike"]; ok {
1142			pkey = "_cslike"
1143		}
1144		if val := params.Get(pkey); val != "" {
1145			switch strings.ToLower(val) {
1146			case "0", "no", "false", "off":
1147				caseSensitiveLike = 0
1148			case "1", "yes", "true", "on":
1149				caseSensitiveLike = 1
1150			default:
1151				return nil, fmt.Errorf("Invalid _case_sensitive_like: %v, expecting boolean value of '0 1 false true no yes off on'", val)
1152			}
1153		}
1154
1155		// Defer Foreign Keys (_defer_foreign_keys | _defer_fk)
1156		//
1157		// https://www.sqlite.org/pragma.html#pragma_defer_foreign_keys
1158		//
1159		pkey = "" // Reset pkey
1160		if _, ok := params["_defer_foreign_keys"]; ok {
1161			pkey = "_defer_foreign_keys"
1162		}
1163		if _, ok := params["_defer_fk"]; ok {
1164			pkey = "_defer_fk"
1165		}
1166		if val := params.Get(pkey); val != "" {
1167			switch strings.ToLower(val) {
1168			case "0", "no", "false", "off":
1169				deferForeignKeys = 0
1170			case "1", "yes", "true", "on":
1171				deferForeignKeys = 1
1172			default:
1173				return nil, fmt.Errorf("Invalid _defer_foreign_keys: %v, expecting boolean value of '0 1 false true no yes off on'", val)
1174			}
1175		}
1176
1177		// Foreign Keys (_foreign_keys | _fk)
1178		//
1179		// https://www.sqlite.org/pragma.html#pragma_foreign_keys
1180		//
1181		pkey = "" // Reset pkey
1182		if _, ok := params["_foreign_keys"]; ok {
1183			pkey = "_foreign_keys"
1184		}
1185		if _, ok := params["_fk"]; ok {
1186			pkey = "_fk"
1187		}
1188		if val := params.Get(pkey); val != "" {
1189			switch strings.ToLower(val) {
1190			case "0", "no", "false", "off":
1191				foreignKeys = 0
1192			case "1", "yes", "true", "on":
1193				foreignKeys = 1
1194			default:
1195				return nil, fmt.Errorf("Invalid _foreign_keys: %v, expecting boolean value of '0 1 false true no yes off on'", val)
1196			}
1197		}
1198
1199		// Ignore CHECK Constrains (_ignore_check_constraints)
1200		//
1201		// https://www.sqlite.org/pragma.html#pragma_ignore_check_constraints
1202		//
1203		if val := params.Get("_ignore_check_constraints"); val != "" {
1204			switch strings.ToLower(val) {
1205			case "0", "no", "false", "off":
1206				ignoreCheckConstraints = 0
1207			case "1", "yes", "true", "on":
1208				ignoreCheckConstraints = 1
1209			default:
1210				return nil, fmt.Errorf("Invalid _ignore_check_constraints: %v, expecting boolean value of '0 1 false true no yes off on'", val)
1211			}
1212		}
1213
1214		// Journal Mode (_journal_mode | _journal)
1215		//
1216		// https://www.sqlite.org/pragma.html#pragma_journal_mode
1217		//
1218		pkey = "" // Reset pkey
1219		if _, ok := params["_journal_mode"]; ok {
1220			pkey = "_journal_mode"
1221		}
1222		if _, ok := params["_journal"]; ok {
1223			pkey = "_journal"
1224		}
1225		if val := params.Get(pkey); val != "" {
1226			switch strings.ToUpper(val) {
1227			case "DELETE", "TRUNCATE", "PERSIST", "MEMORY", "OFF":
1228				journalMode = strings.ToUpper(val)
1229			case "WAL":
1230				journalMode = strings.ToUpper(val)
1231
1232				// For WAL Mode set Synchronous Mode to 'NORMAL'
1233				// See https://www.sqlite.org/pragma.html#pragma_synchronous
1234				synchronousMode = "NORMAL"
1235			default:
1236				return nil, fmt.Errorf("Invalid _journal: %v, expecting value of 'DELETE TRUNCATE PERSIST MEMORY WAL OFF'", val)
1237			}
1238		}
1239
1240		// Locking Mode (_locking)
1241		//
1242		// https://www.sqlite.org/pragma.html#pragma_locking_mode
1243		//
1244		pkey = "" // Reset pkey
1245		if _, ok := params["_locking_mode"]; ok {
1246			pkey = "_locking_mode"
1247		}
1248		if _, ok := params["_locking"]; ok {
1249			pkey = "_locking"
1250		}
1251		if val := params.Get(pkey); val != "" {
1252			switch strings.ToUpper(val) {
1253			case "NORMAL", "EXCLUSIVE":
1254				lockingMode = strings.ToUpper(val)
1255			default:
1256				return nil, fmt.Errorf("Invalid _locking_mode: %v, expecting value of 'NORMAL EXCLUSIVE", val)
1257			}
1258		}
1259
1260		// Query Only (_query_only)
1261		//
1262		// https://www.sqlite.org/pragma.html#pragma_query_only
1263		//
1264		if val := params.Get("_query_only"); val != "" {
1265			switch strings.ToLower(val) {
1266			case "0", "no", "false", "off":
1267				queryOnly = 0
1268			case "1", "yes", "true", "on":
1269				queryOnly = 1
1270			default:
1271				return nil, fmt.Errorf("Invalid _query_only: %v, expecting boolean value of '0 1 false true no yes off on'", val)
1272			}
1273		}
1274
1275		// Recursive Triggers (_recursive_triggers)
1276		//
1277		// https://www.sqlite.org/pragma.html#pragma_recursive_triggers
1278		//
1279		pkey = "" // Reset pkey
1280		if _, ok := params["_recursive_triggers"]; ok {
1281			pkey = "_recursive_triggers"
1282		}
1283		if _, ok := params["_rt"]; ok {
1284			pkey = "_rt"
1285		}
1286		if val := params.Get(pkey); val != "" {
1287			switch strings.ToLower(val) {
1288			case "0", "no", "false", "off":
1289				recursiveTriggers = 0
1290			case "1", "yes", "true", "on":
1291				recursiveTriggers = 1
1292			default:
1293				return nil, fmt.Errorf("Invalid _recursive_triggers: %v, expecting boolean value of '0 1 false true no yes off on'", val)
1294			}
1295		}
1296
1297		// Secure Delete (_secure_delete)
1298		//
1299		// https://www.sqlite.org/pragma.html#pragma_secure_delete
1300		//
1301		if val := params.Get("_secure_delete"); val != "" {
1302			switch strings.ToLower(val) {
1303			case "0", "no", "false", "off":
1304				secureDelete = "OFF"
1305			case "1", "yes", "true", "on":
1306				secureDelete = "ON"
1307			case "fast":
1308				secureDelete = "FAST"
1309			default:
1310				return nil, fmt.Errorf("Invalid _secure_delete: %v, expecting boolean value of '0 1 false true no yes off on fast'", val)
1311			}
1312		}
1313
1314		// Synchronous Mode (_synchronous | _sync)
1315		//
1316		// https://www.sqlite.org/pragma.html#pragma_synchronous
1317		//
1318		pkey = "" // Reset pkey
1319		if _, ok := params["_synchronous"]; ok {
1320			pkey = "_synchronous"
1321		}
1322		if _, ok := params["_sync"]; ok {
1323			pkey = "_sync"
1324		}
1325		if val := params.Get(pkey); val != "" {
1326			switch strings.ToUpper(val) {
1327			case "0", "OFF", "1", "NORMAL", "2", "FULL", "3", "EXTRA":
1328				synchronousMode = strings.ToUpper(val)
1329			default:
1330				return nil, fmt.Errorf("Invalid _synchronous: %v, expecting value of '0 OFF 1 NORMAL 2 FULL 3 EXTRA'", val)
1331			}
1332		}
1333
1334		// Writable Schema (_writeable_schema)
1335		//
1336		// https://www.sqlite.org/pragma.html#pragma_writeable_schema
1337		//
1338		if val := params.Get("_writable_schema"); val != "" {
1339			switch strings.ToLower(val) {
1340			case "0", "no", "false", "off":
1341				writableSchema = 0
1342			case "1", "yes", "true", "on":
1343				writableSchema = 1
1344			default:
1345				return nil, fmt.Errorf("Invalid _writable_schema: %v, expecting boolean value of '0 1 false true no yes off on'", val)
1346			}
1347		}
1348
1349		if !strings.HasPrefix(dsn, "file:") {
1350			dsn = dsn[:pos]
1351		}
1352	}
1353
1354	var db *C.sqlite3
1355	name := C.CString(dsn)
1356	defer C.free(unsafe.Pointer(name))
1357	rv := C._sqlite3_open_v2(name, &db,
1358		mutex|C.SQLITE_OPEN_READWRITE|C.SQLITE_OPEN_CREATE,
1359		nil)
1360	if rv != 0 {
1361		// Save off the error _before_ closing the database.
1362		// This is safe even if db is nil.
1363		err := lastError(db)
1364		if db != nil {
1365			C.sqlite3_close_v2(db)
1366		}
1367		return nil, err
1368	}
1369	if db == nil {
1370		return nil, errors.New("sqlite succeeded without returning a database")
1371	}
1372
1373	rv = C.sqlite3_busy_timeout(db, C.int(busyTimeout))
1374	if rv != C.SQLITE_OK {
1375		C.sqlite3_close_v2(db)
1376		return nil, Error{Code: ErrNo(rv)}
1377	}
1378
1379	exec := func(s string) error {
1380		cs := C.CString(s)
1381		rv := C.sqlite3_exec(db, cs, nil, nil, nil)
1382		C.free(unsafe.Pointer(cs))
1383		if rv != C.SQLITE_OK {
1384			return lastError(db)
1385		}
1386		return nil
1387	}
1388
1389	// USER AUTHENTICATION
1390	//
1391	// User Authentication is always performed even when
1392	// sqlite_userauth is not compiled in, because without user authentication
1393	// the authentication is a no-op.
1394	//
1395	// Workflow
1396	//	- Authenticate
1397	//		ON::SUCCESS		=> Continue
1398	//		ON::SQLITE_AUTH => Return error and exit Open(...)
1399	//
1400	//  - Activate User Authentication
1401	//		Check if the user wants to activate User Authentication.
1402	//		If so then first create a temporary AuthConn to the database
1403	//		This is possible because we are already successfully authenticated.
1404	//
1405	//	- Check if `sqlite_user`` table exists
1406	//		YES				=> Add the provided user from DSN as Admin User and
1407	//						   activate user authentication.
1408	//		NO				=> Continue
1409	//
1410
1411	// Create connection to SQLite
1412	conn := &SQLiteConn{db: db, loc: loc, txlock: txlock}
1413
1414	// Password Cipher has to be registered before authentication
1415	if len(authCrypt) > 0 {
1416		switch strings.ToUpper(authCrypt) {
1417		case "SHA1":
1418			if err := conn.RegisterFunc("sqlite_crypt", CryptEncoderSHA1, true); err != nil {
1419				return nil, fmt.Errorf("CryptEncoderSHA1: %s", err)
1420			}
1421		case "SSHA1":
1422			if len(authSalt) == 0 {
1423				return nil, fmt.Errorf("_auth_crypt=ssha1, requires _auth_salt")
1424			}
1425			if err := conn.RegisterFunc("sqlite_crypt", CryptEncoderSSHA1(authSalt), true); err != nil {
1426				return nil, fmt.Errorf("CryptEncoderSSHA1: %s", err)
1427			}
1428		case "SHA256":
1429			if err := conn.RegisterFunc("sqlite_crypt", CryptEncoderSHA256, true); err != nil {
1430				return nil, fmt.Errorf("CryptEncoderSHA256: %s", err)
1431			}
1432		case "SSHA256":
1433			if len(authSalt) == 0 {
1434				return nil, fmt.Errorf("_auth_crypt=ssha256, requires _auth_salt")
1435			}
1436			if err := conn.RegisterFunc("sqlite_crypt", CryptEncoderSSHA256(authSalt), true); err != nil {
1437				return nil, fmt.Errorf("CryptEncoderSSHA256: %s", err)
1438			}
1439		case "SHA384":
1440			if err := conn.RegisterFunc("sqlite_crypt", CryptEncoderSHA384, true); err != nil {
1441				return nil, fmt.Errorf("CryptEncoderSHA384: %s", err)
1442			}
1443		case "SSHA384":
1444			if len(authSalt) == 0 {
1445				return nil, fmt.Errorf("_auth_crypt=ssha384, requires _auth_salt")
1446			}
1447			if err := conn.RegisterFunc("sqlite_crypt", CryptEncoderSSHA384(authSalt), true); err != nil {
1448				return nil, fmt.Errorf("CryptEncoderSSHA384: %s", err)
1449			}
1450		case "SHA512":
1451			if err := conn.RegisterFunc("sqlite_crypt", CryptEncoderSHA512, true); err != nil {
1452				return nil, fmt.Errorf("CryptEncoderSHA512: %s", err)
1453			}
1454		case "SSHA512":
1455			if len(authSalt) == 0 {
1456				return nil, fmt.Errorf("_auth_crypt=ssha512, requires _auth_salt")
1457			}
1458			if err := conn.RegisterFunc("sqlite_crypt", CryptEncoderSSHA512(authSalt), true); err != nil {
1459				return nil, fmt.Errorf("CryptEncoderSSHA512: %s", err)
1460			}
1461		}
1462	}
1463
1464	// Preform Authentication
1465	if err := conn.Authenticate(authUser, authPass); err != nil {
1466		return nil, err
1467	}
1468
1469	// Register: authenticate
1470	// Authenticate will perform an authentication of the provided username
1471	// and password against the database.
1472	//
1473	// If a database contains the SQLITE_USER table, then the
1474	// call to Authenticate must be invoked with an
1475	// appropriate username and password prior to enable read and write
1476	//access to the database.
1477	//
1478	// Return SQLITE_OK on success or SQLITE_ERROR if the username/password
1479	// combination is incorrect or unknown.
1480	//
1481	// If the SQLITE_USER table is not present in the database file, then
1482	// this interface is a harmless no-op returnning SQLITE_OK.
1483	if err := conn.RegisterFunc("authenticate", conn.authenticate, true); err != nil {
1484		return nil, err
1485	}
1486	//
1487	// Register: auth_user_add
1488	// auth_user_add can be used (by an admin user only)
1489	// to create a new user. When called on a no-authentication-required
1490	// database, this routine converts the database into an authentication-
1491	// required database, automatically makes the added user an
1492	// administrator, and logs in the current connection as that user.
1493	// The AuthUserAdd only works for the "main" database, not
1494	// for any ATTACH-ed databases. Any call to AuthUserAdd by a
1495	// non-admin user results in an error.
1496	if err := conn.RegisterFunc("auth_user_add", conn.authUserAdd, true); err != nil {
1497		return nil, err
1498	}
1499	//
1500	// Register: auth_user_change
1501	// auth_user_change can be used to change a users
1502	// login credentials or admin privilege.  Any user can change their own
1503	// login credentials. Only an admin user can change another users login
1504	// credentials or admin privilege setting. No user may change their own
1505	// admin privilege setting.
1506	if err := conn.RegisterFunc("auth_user_change", conn.authUserChange, true); err != nil {
1507		return nil, err
1508	}
1509	//
1510	// Register: auth_user_delete
1511	// auth_user_delete can be used (by an admin user only)
1512	// to delete a user. The currently logged-in user cannot be deleted,
1513	// which guarantees that there is always an admin user and hence that
1514	// the database cannot be converted into a no-authentication-required
1515	// database.
1516	if err := conn.RegisterFunc("auth_user_delete", conn.authUserDelete, true); err != nil {
1517		return nil, err
1518	}
1519
1520	// Register: auth_enabled
1521	// auth_enabled can be used to check if user authentication is enabled
1522	if err := conn.RegisterFunc("auth_enabled", conn.authEnabled, true); err != nil {
1523		return nil, err
1524	}
1525
1526	// Auto Vacuum
1527	// Moved auto_vacuum command, the user preference for auto_vacuum needs to be implemented directly after
1528	// the authentication and before the sqlite_user table gets created if the user
1529	// decides to activate User Authentication because
1530	// auto_vacuum needs to be set before any tables are created
1531	// and activating user authentication creates the internal table `sqlite_user`.
1532	if autoVacuum > -1 {
1533		if err := exec(fmt.Sprintf("PRAGMA auto_vacuum = %d;", autoVacuum)); err != nil {
1534			C.sqlite3_close_v2(db)
1535			return nil, err
1536		}
1537	}
1538
1539	// Check if user wants to activate User Authentication
1540	if authCreate {
1541		// Before going any further, we need to check that the user
1542		// has provided an username and password within the DSN.
1543		// We are not allowed to continue.
1544		if len(authUser) == 0 {
1545			return nil, fmt.Errorf("Missing '_auth_user' while user authentication was requested with '_auth'")
1546		}
1547		if len(authPass) == 0 {
1548			return nil, fmt.Errorf("Missing '_auth_pass' while user authentication was requested with '_auth'")
1549		}
1550
1551		// Check if User Authentication is Enabled
1552		authExists := conn.AuthEnabled()
1553		if !authExists {
1554			if err := conn.AuthUserAdd(authUser, authPass, true); err != nil {
1555				return nil, err
1556			}
1557		}
1558	}
1559
1560	// Case Sensitive LIKE
1561	if caseSensitiveLike > -1 {
1562		if err := exec(fmt.Sprintf("PRAGMA case_sensitive_like = %d;", caseSensitiveLike)); err != nil {
1563			C.sqlite3_close_v2(db)
1564			return nil, err
1565		}
1566	}
1567
1568	// Defer Foreign Keys
1569	if deferForeignKeys > -1 {
1570		if err := exec(fmt.Sprintf("PRAGMA defer_foreign_keys = %d;", deferForeignKeys)); err != nil {
1571			C.sqlite3_close_v2(db)
1572			return nil, err
1573		}
1574	}
1575
1576	// Forgein Keys
1577	if foreignKeys > -1 {
1578		if err := exec(fmt.Sprintf("PRAGMA foreign_keys = %d;", foreignKeys)); err != nil {
1579			C.sqlite3_close_v2(db)
1580			return nil, err
1581		}
1582	}
1583
1584	// Ignore CHECK Constraints
1585	if ignoreCheckConstraints > -1 {
1586		if err := exec(fmt.Sprintf("PRAGMA ignore_check_constraints = %d;", ignoreCheckConstraints)); err != nil {
1587			C.sqlite3_close_v2(db)
1588			return nil, err
1589		}
1590	}
1591
1592	// Journal Mode
1593	if journalMode != "" {
1594		if err := exec(fmt.Sprintf("PRAGMA journal_mode = %s;", journalMode)); err != nil {
1595			C.sqlite3_close_v2(db)
1596			return nil, err
1597		}
1598	}
1599
1600	// Locking Mode
1601	// Because the default is NORMAL and this is not changed in this package
1602	// by using the compile time SQLITE_DEFAULT_LOCKING_MODE this PRAGMA can always be executed
1603	if err := exec(fmt.Sprintf("PRAGMA locking_mode = %s;", lockingMode)); err != nil {
1604		C.sqlite3_close_v2(db)
1605		return nil, err
1606	}
1607
1608	// Query Only
1609	if queryOnly > -1 {
1610		if err := exec(fmt.Sprintf("PRAGMA query_only = %d;", queryOnly)); err != nil {
1611			C.sqlite3_close_v2(db)
1612			return nil, err
1613		}
1614	}
1615
1616	// Recursive Triggers
1617	if recursiveTriggers > -1 {
1618		if err := exec(fmt.Sprintf("PRAGMA recursive_triggers = %d;", recursiveTriggers)); err != nil {
1619			C.sqlite3_close_v2(db)
1620			return nil, err
1621		}
1622	}
1623
1624	// Secure Delete
1625	//
1626	// Because this package can set the compile time flag SQLITE_SECURE_DELETE with a build tag
1627	// the default value for secureDelete var is 'DEFAULT' this way
1628	// you can compile with secure_delete 'ON' and disable it for a specific database connection.
1629	if secureDelete != "DEFAULT" {
1630		if err := exec(fmt.Sprintf("PRAGMA secure_delete = %s;", secureDelete)); err != nil {
1631			C.sqlite3_close_v2(db)
1632			return nil, err
1633		}
1634	}
1635
1636	// Synchronous Mode
1637	//
1638	// Because default is NORMAL this statement is always executed
1639	if err := exec(fmt.Sprintf("PRAGMA synchronous = %s;", synchronousMode)); err != nil {
1640		C.sqlite3_close_v2(db)
1641		return nil, err
1642	}
1643
1644	// Writable Schema
1645	if writableSchema > -1 {
1646		if err := exec(fmt.Sprintf("PRAGMA writable_schema = %d;", writableSchema)); err != nil {
1647			C.sqlite3_close_v2(db)
1648			return nil, err
1649		}
1650	}
1651
1652	if len(d.Extensions) > 0 {
1653		if err := conn.loadExtensions(d.Extensions); err != nil {
1654			conn.Close()
1655			return nil, err
1656		}
1657	}
1658
1659	if d.ConnectHook != nil {
1660		if err := d.ConnectHook(conn); err != nil {
1661			conn.Close()
1662			return nil, err
1663		}
1664	}
1665	runtime.SetFinalizer(conn, (*SQLiteConn).Close)
1666	return conn, nil
1667}
1668
1669// Close the connection.
1670func (c *SQLiteConn) Close() error {
1671	rv := C.sqlite3_close_v2(c.db)
1672	if rv != C.SQLITE_OK {
1673		return c.lastError()
1674	}
1675	deleteHandles(c)
1676	c.mu.Lock()
1677	c.db = nil
1678	c.mu.Unlock()
1679	runtime.SetFinalizer(c, nil)
1680	return nil
1681}
1682
1683func (c *SQLiteConn) dbConnOpen() bool {
1684	if c == nil {
1685		return false
1686	}
1687	c.mu.Lock()
1688	defer c.mu.Unlock()
1689	return c.db != nil
1690}
1691
1692// Prepare the query string. Return a new statement.
1693func (c *SQLiteConn) Prepare(query string) (driver.Stmt, error) {
1694	return c.prepare(context.Background(), query)
1695}
1696
1697func (c *SQLiteConn) prepare(ctx context.Context, query string) (driver.Stmt, error) {
1698	pquery := C.CString(query)
1699	defer C.free(unsafe.Pointer(pquery))
1700	var s *C.sqlite3_stmt
1701	var tail *C.char
1702	rv := C._sqlite3_prepare_v2_internal(c.db, pquery, C.int(-1), &s, &tail)
1703	if rv != C.SQLITE_OK {
1704		return nil, c.lastError()
1705	}
1706	var t string
1707	if tail != nil && *tail != '\000' {
1708		t = strings.TrimSpace(C.GoString(tail))
1709	}
1710	ss := &SQLiteStmt{c: c, s: s, t: t}
1711	runtime.SetFinalizer(ss, (*SQLiteStmt).Close)
1712	return ss, nil
1713}
1714
1715// Run-Time Limit Categories.
1716// See: http://www.sqlite.org/c3ref/c_limit_attached.html
1717const (
1718	SQLITE_LIMIT_LENGTH              = C.SQLITE_LIMIT_LENGTH
1719	SQLITE_LIMIT_SQL_LENGTH          = C.SQLITE_LIMIT_SQL_LENGTH
1720	SQLITE_LIMIT_COLUMN              = C.SQLITE_LIMIT_COLUMN
1721	SQLITE_LIMIT_EXPR_DEPTH          = C.SQLITE_LIMIT_EXPR_DEPTH
1722	SQLITE_LIMIT_COMPOUND_SELECT     = C.SQLITE_LIMIT_COMPOUND_SELECT
1723	SQLITE_LIMIT_VDBE_OP             = C.SQLITE_LIMIT_VDBE_OP
1724	SQLITE_LIMIT_FUNCTION_ARG        = C.SQLITE_LIMIT_FUNCTION_ARG
1725	SQLITE_LIMIT_ATTACHED            = C.SQLITE_LIMIT_ATTACHED
1726	SQLITE_LIMIT_LIKE_PATTERN_LENGTH = C.SQLITE_LIMIT_LIKE_PATTERN_LENGTH
1727	SQLITE_LIMIT_VARIABLE_NUMBER     = C.SQLITE_LIMIT_VARIABLE_NUMBER
1728	SQLITE_LIMIT_TRIGGER_DEPTH       = C.SQLITE_LIMIT_TRIGGER_DEPTH
1729	SQLITE_LIMIT_WORKER_THREADS      = C.SQLITE_LIMIT_WORKER_THREADS
1730)
1731
1732// GetFilename returns the absolute path to the file containing
1733// the requested schema. When passed an empty string, it will
1734// instead use the database's default schema: "main".
1735// See: sqlite3_db_filename, https://www.sqlite.org/c3ref/db_filename.html
1736func (c *SQLiteConn) GetFilename(schemaName string) string {
1737	if schemaName == "" {
1738		schemaName = "main"
1739	}
1740	return C.GoString(C.sqlite3_db_filename(c.db, C.CString(schemaName)))
1741}
1742
1743// GetLimit returns the current value of a run-time limit.
1744// See: sqlite3_limit, http://www.sqlite.org/c3ref/limit.html
1745func (c *SQLiteConn) GetLimit(id int) int {
1746	return int(C._sqlite3_limit(c.db, C.int(id), C.int(-1)))
1747}
1748
1749// SetLimit changes the value of a run-time limits.
1750// Then this method returns the prior value of the limit.
1751// See: sqlite3_limit, http://www.sqlite.org/c3ref/limit.html
1752func (c *SQLiteConn) SetLimit(id int, newVal int) int {
1753	return int(C._sqlite3_limit(c.db, C.int(id), C.int(newVal)))
1754}
1755
1756// Close the statement.
1757func (s *SQLiteStmt) Close() error {
1758	s.mu.Lock()
1759	defer s.mu.Unlock()
1760	if s.closed {
1761		return nil
1762	}
1763	s.closed = true
1764	if !s.c.dbConnOpen() {
1765		return errors.New("sqlite statement with already closed database connection")
1766	}
1767	rv := C.sqlite3_finalize(s.s)
1768	s.s = nil
1769	if rv != C.SQLITE_OK {
1770		return s.c.lastError()
1771	}
1772	runtime.SetFinalizer(s, nil)
1773	return nil
1774}
1775
1776// NumInput return a number of parameters.
1777func (s *SQLiteStmt) NumInput() int {
1778	return int(C.sqlite3_bind_parameter_count(s.s))
1779}
1780
1781type bindArg struct {
1782	n int
1783	v driver.Value
1784}
1785
1786var placeHolder = []byte{0}
1787
1788func (s *SQLiteStmt) bind(args []namedValue) error {
1789	rv := C.sqlite3_reset(s.s)
1790	if rv != C.SQLITE_ROW && rv != C.SQLITE_OK && rv != C.SQLITE_DONE {
1791		return s.c.lastError()
1792	}
1793
1794	for i, v := range args {
1795		if v.Name != "" {
1796			cname := C.CString(":" + v.Name)
1797			args[i].Ordinal = int(C.sqlite3_bind_parameter_index(s.s, cname))
1798			C.free(unsafe.Pointer(cname))
1799		}
1800	}
1801
1802	for _, arg := range args {
1803		n := C.int(arg.Ordinal)
1804		switch v := arg.Value.(type) {
1805		case nil:
1806			rv = C.sqlite3_bind_null(s.s, n)
1807		case string:
1808			if len(v) == 0 {
1809				rv = C._sqlite3_bind_text(s.s, n, (*C.char)(unsafe.Pointer(&placeHolder[0])), C.int(0))
1810			} else {
1811				b := []byte(v)
1812				rv = C._sqlite3_bind_text(s.s, n, (*C.char)(unsafe.Pointer(&b[0])), C.int(len(b)))
1813			}
1814		case int64:
1815			rv = C.sqlite3_bind_int64(s.s, n, C.sqlite3_int64(v))
1816		case bool:
1817			if v {
1818				rv = C.sqlite3_bind_int(s.s, n, 1)
1819			} else {
1820				rv = C.sqlite3_bind_int(s.s, n, 0)
1821			}
1822		case float64:
1823			rv = C.sqlite3_bind_double(s.s, n, C.double(v))
1824		case []byte:
1825			if v == nil {
1826				rv = C.sqlite3_bind_null(s.s, n)
1827			} else {
1828				ln := len(v)
1829				if ln == 0 {
1830					v = placeHolder
1831				}
1832				rv = C._sqlite3_bind_blob(s.s, n, unsafe.Pointer(&v[0]), C.int(ln))
1833			}
1834		case time.Time:
1835			b := []byte(v.Format(SQLiteTimestampFormats[0]))
1836			rv = C._sqlite3_bind_text(s.s, n, (*C.char)(unsafe.Pointer(&b[0])), C.int(len(b)))
1837		}
1838		if rv != C.SQLITE_OK {
1839			return s.c.lastError()
1840		}
1841	}
1842	return nil
1843}
1844
1845// Query the statement with arguments. Return records.
1846func (s *SQLiteStmt) Query(args []driver.Value) (driver.Rows, error) {
1847	list := make([]namedValue, len(args))
1848	for i, v := range args {
1849		list[i] = namedValue{
1850			Ordinal: i + 1,
1851			Value:   v,
1852		}
1853	}
1854	return s.query(context.Background(), list)
1855}
1856
1857func (s *SQLiteStmt) query(ctx context.Context, args []namedValue) (driver.Rows, error) {
1858	if err := s.bind(args); err != nil {
1859		return nil, err
1860	}
1861
1862	rows := &SQLiteRows{
1863		s:        s,
1864		nc:       int(C.sqlite3_column_count(s.s)),
1865		cols:     nil,
1866		decltype: nil,
1867		cls:      s.cls,
1868		closed:   false,
1869		ctx:      ctx,
1870	}
1871
1872	return rows, nil
1873}
1874
1875// LastInsertId return last inserted ID.
1876func (r *SQLiteResult) LastInsertId() (int64, error) {
1877	return r.id, nil
1878}
1879
1880// RowsAffected return how many rows affected.
1881func (r *SQLiteResult) RowsAffected() (int64, error) {
1882	return r.changes, nil
1883}
1884
1885// Exec execute the statement with arguments. Return result object.
1886func (s *SQLiteStmt) Exec(args []driver.Value) (driver.Result, error) {
1887	list := make([]namedValue, len(args))
1888	for i, v := range args {
1889		list[i] = namedValue{
1890			Ordinal: i + 1,
1891			Value:   v,
1892		}
1893	}
1894	return s.exec(context.Background(), list)
1895}
1896
1897// exec executes a query that doesn't return rows. Attempts to honor context timeout.
1898func (s *SQLiteStmt) exec(ctx context.Context, args []namedValue) (driver.Result, error) {
1899	if ctx.Done() == nil {
1900		return s.execSync(args)
1901	}
1902
1903	type result struct {
1904		r   driver.Result
1905		err error
1906	}
1907	resultCh := make(chan result)
1908	go func() {
1909		r, err := s.execSync(args)
1910		resultCh <- result{r, err}
1911	}()
1912	select {
1913	case rv := <-resultCh:
1914		return rv.r, rv.err
1915	case <-ctx.Done():
1916		select {
1917		case <-resultCh: // no need to interrupt
1918		default:
1919			// this is still racy and can be no-op if executed between sqlite3_* calls in execSync.
1920			C.sqlite3_interrupt(s.c.db)
1921			<-resultCh // ensure goroutine completed
1922		}
1923		return nil, ctx.Err()
1924	}
1925}
1926
1927func (s *SQLiteStmt) execSync(args []namedValue) (driver.Result, error) {
1928	if err := s.bind(args); err != nil {
1929		C.sqlite3_reset(s.s)
1930		C.sqlite3_clear_bindings(s.s)
1931		return nil, err
1932	}
1933
1934	var rowid, changes C.longlong
1935	rv := C._sqlite3_step_row_internal(s.s, &rowid, &changes)
1936	if rv != C.SQLITE_ROW && rv != C.SQLITE_OK && rv != C.SQLITE_DONE {
1937		err := s.c.lastError()
1938		C.sqlite3_reset(s.s)
1939		C.sqlite3_clear_bindings(s.s)
1940		return nil, err
1941	}
1942
1943	return &SQLiteResult{id: int64(rowid), changes: int64(changes)}, nil
1944}
1945
1946// Close the rows.
1947func (rc *SQLiteRows) Close() error {
1948	rc.s.mu.Lock()
1949	if rc.s.closed || rc.closed {
1950		rc.s.mu.Unlock()
1951		return nil
1952	}
1953	rc.closed = true
1954	if rc.cls {
1955		rc.s.mu.Unlock()
1956		return rc.s.Close()
1957	}
1958	rv := C.sqlite3_reset(rc.s.s)
1959	if rv != C.SQLITE_OK {
1960		rc.s.mu.Unlock()
1961		return rc.s.c.lastError()
1962	}
1963	rc.s.mu.Unlock()
1964	return nil
1965}
1966
1967// Columns return column names.
1968func (rc *SQLiteRows) Columns() []string {
1969	rc.s.mu.Lock()
1970	defer rc.s.mu.Unlock()
1971	if rc.s.s != nil && rc.nc != len(rc.cols) {
1972		rc.cols = make([]string, rc.nc)
1973		for i := 0; i < rc.nc; i++ {
1974			rc.cols[i] = C.GoString(C.sqlite3_column_name(rc.s.s, C.int(i)))
1975		}
1976	}
1977	return rc.cols
1978}
1979
1980func (rc *SQLiteRows) declTypes() []string {
1981	if rc.s.s != nil && rc.decltype == nil {
1982		rc.decltype = make([]string, rc.nc)
1983		for i := 0; i < rc.nc; i++ {
1984			rc.decltype[i] = strings.ToLower(C.GoString(C.sqlite3_column_decltype(rc.s.s, C.int(i))))
1985		}
1986	}
1987	return rc.decltype
1988}
1989
1990// DeclTypes return column types.
1991func (rc *SQLiteRows) DeclTypes() []string {
1992	rc.s.mu.Lock()
1993	defer rc.s.mu.Unlock()
1994	return rc.declTypes()
1995}
1996
1997// Next move cursor to next. Attempts to honor context timeout from QueryContext call.
1998func (rc *SQLiteRows) Next(dest []driver.Value) error {
1999	rc.s.mu.Lock()
2000	defer rc.s.mu.Unlock()
2001
2002	if rc.s.closed {
2003		return io.EOF
2004	}
2005
2006	if rc.ctx.Done() == nil {
2007		return rc.nextSyncLocked(dest)
2008	}
2009	resultCh := make(chan error)
2010	go func() {
2011		resultCh <- rc.nextSyncLocked(dest)
2012	}()
2013	select {
2014	case err := <-resultCh:
2015		return err
2016	case <-rc.ctx.Done():
2017		select {
2018		case <-resultCh: // no need to interrupt
2019		default:
2020			// this is still racy and can be no-op if executed between sqlite3_* calls in nextSyncLocked.
2021			C.sqlite3_interrupt(rc.s.c.db)
2022			<-resultCh // ensure goroutine completed
2023		}
2024		return rc.ctx.Err()
2025	}
2026}
2027
2028// nextSyncLocked moves cursor to next; must be called with locked mutex.
2029func (rc *SQLiteRows) nextSyncLocked(dest []driver.Value) error {
2030	rv := C._sqlite3_step_internal(rc.s.s)
2031	if rv == C.SQLITE_DONE {
2032		return io.EOF
2033	}
2034	if rv != C.SQLITE_ROW {
2035		rv = C.sqlite3_reset(rc.s.s)
2036		if rv != C.SQLITE_OK {
2037			return rc.s.c.lastError()
2038		}
2039		return nil
2040	}
2041
2042	rc.declTypes()
2043
2044	for i := range dest {
2045		switch C.sqlite3_column_type(rc.s.s, C.int(i)) {
2046		case C.SQLITE_INTEGER:
2047			val := int64(C.sqlite3_column_int64(rc.s.s, C.int(i)))
2048			switch rc.decltype[i] {
2049			case columnTimestamp, columnDatetime, columnDate:
2050				var t time.Time
2051				// Assume a millisecond unix timestamp if it's 13 digits -- too
2052				// large to be a reasonable timestamp in seconds.
2053				if val > 1e12 || val < -1e12 {
2054					val *= int64(time.Millisecond) // convert ms to nsec
2055					t = time.Unix(0, val)
2056				} else {
2057					t = time.Unix(val, 0)
2058				}
2059				t = t.UTC()
2060				if rc.s.c.loc != nil {
2061					t = t.In(rc.s.c.loc)
2062				}
2063				dest[i] = t
2064			case "boolean":
2065				dest[i] = val > 0
2066			default:
2067				dest[i] = val
2068			}
2069		case C.SQLITE_FLOAT:
2070			dest[i] = float64(C.sqlite3_column_double(rc.s.s, C.int(i)))
2071		case C.SQLITE_BLOB:
2072			p := C.sqlite3_column_blob(rc.s.s, C.int(i))
2073			if p == nil {
2074				dest[i] = []byte{}
2075				continue
2076			}
2077			n := C.sqlite3_column_bytes(rc.s.s, C.int(i))
2078			dest[i] = C.GoBytes(p, n)
2079		case C.SQLITE_NULL:
2080			dest[i] = nil
2081		case C.SQLITE_TEXT:
2082			var err error
2083			var timeVal time.Time
2084
2085			n := int(C.sqlite3_column_bytes(rc.s.s, C.int(i)))
2086			s := C.GoStringN((*C.char)(unsafe.Pointer(C.sqlite3_column_text(rc.s.s, C.int(i)))), C.int(n))
2087
2088			switch rc.decltype[i] {
2089			case columnTimestamp, columnDatetime, columnDate:
2090				var t time.Time
2091				s = strings.TrimSuffix(s, "Z")
2092				for _, format := range SQLiteTimestampFormats {
2093					if timeVal, err = time.ParseInLocation(format, s, time.UTC); err == nil {
2094						t = timeVal
2095						break
2096					}
2097				}
2098				if err != nil {
2099					// The column is a time value, so return the zero time on parse failure.
2100					t = time.Time{}
2101				}
2102				if rc.s.c.loc != nil {
2103					t = t.In(rc.s.c.loc)
2104				}
2105				dest[i] = t
2106			default:
2107				dest[i] = s
2108			}
2109		}
2110	}
2111	return nil
2112}
2113