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