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(t.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	return int(C.sqlite3_get_autocommit(c.db)) != 0
744}
745
746func (c *SQLiteConn) lastError() error {
747	return lastError(c.db)
748}
749
750func lastError(db *C.sqlite3) error {
751	rv := C.sqlite3_errcode(db)
752	if rv == C.SQLITE_OK {
753		return nil
754	}
755	return Error{
756		Code:         ErrNo(rv),
757		ExtendedCode: ErrNoExtended(C.sqlite3_extended_errcode(db)),
758		err:          C.GoString(C.sqlite3_errmsg(db)),
759	}
760}
761
762// Exec implements Execer.
763func (c *SQLiteConn) Exec(query string, args []driver.Value) (driver.Result, error) {
764	list := make([]namedValue, len(args))
765	for i, v := range args {
766		list[i] = namedValue{
767			Ordinal: i + 1,
768			Value:   v,
769		}
770	}
771	return c.exec(context.Background(), query, list)
772}
773
774func (c *SQLiteConn) exec(ctx context.Context, query string, args []namedValue) (driver.Result, error) {
775	start := 0
776	for {
777		s, err := c.prepare(ctx, query)
778		if err != nil {
779			return nil, err
780		}
781		var res driver.Result
782		if s.(*SQLiteStmt).s != nil {
783			na := s.NumInput()
784			if len(args) < na {
785				s.Close()
786				return nil, fmt.Errorf("not enough args to execute query: want %d got %d", na, len(args))
787			}
788			for i := 0; i < na; i++ {
789				args[i].Ordinal -= start
790			}
791			res, err = s.(*SQLiteStmt).exec(ctx, args[:na])
792			if err != nil && err != driver.ErrSkip {
793				s.Close()
794				return nil, err
795			}
796			args = args[na:]
797			start += na
798		}
799		tail := s.(*SQLiteStmt).t
800		s.Close()
801		if tail == "" {
802			return res, nil
803		}
804		query = tail
805	}
806}
807
808type namedValue struct {
809	Name    string
810	Ordinal int
811	Value   driver.Value
812}
813
814// Query implements Queryer.
815func (c *SQLiteConn) Query(query string, args []driver.Value) (driver.Rows, error) {
816	list := make([]namedValue, len(args))
817	for i, v := range args {
818		list[i] = namedValue{
819			Ordinal: i + 1,
820			Value:   v,
821		}
822	}
823	return c.query(context.Background(), query, list)
824}
825
826func (c *SQLiteConn) query(ctx context.Context, query string, args []namedValue) (driver.Rows, error) {
827	start := 0
828	for {
829		s, err := c.prepare(ctx, query)
830		if err != nil {
831			return nil, err
832		}
833		s.(*SQLiteStmt).cls = true
834		na := s.NumInput()
835		if len(args) < na {
836			return nil, fmt.Errorf("not enough args to execute query: want %d got %d", na, len(args))
837		}
838		for i := 0; i < na; i++ {
839			args[i].Ordinal -= start
840		}
841		rows, err := s.(*SQLiteStmt).query(ctx, args[:na])
842		if err != nil && err != driver.ErrSkip {
843			s.Close()
844			return rows, err
845		}
846		args = args[na:]
847		start += na
848		tail := s.(*SQLiteStmt).t
849		if tail == "" {
850			return rows, nil
851		}
852		rows.Close()
853		s.Close()
854		query = tail
855	}
856}
857
858// Begin transaction.
859func (c *SQLiteConn) Begin() (driver.Tx, error) {
860	return c.begin(context.Background())
861}
862
863func (c *SQLiteConn) begin(ctx context.Context) (driver.Tx, error) {
864	if _, err := c.exec(ctx, c.txlock, nil); err != nil {
865		return nil, err
866	}
867	return &SQLiteTx{c}, nil
868}
869
870func errorString(err Error) string {
871	return C.GoString(C.sqlite3_errstr(C.int(err.Code)))
872}
873
874// Open database and return a new connection.
875//
876// A pragma can take either zero or one argument.
877// The argument is may be either in parentheses or it may be separated from
878// the pragma name by an equal sign. The two syntaxes yield identical results.
879// In many pragmas, the argument is a boolean. The boolean can be one of:
880//    1 yes true on
881//    0 no false off
882//
883// You can specify a DSN string using a URI as the filename.
884//   test.db
885//   file:test.db?cache=shared&mode=memory
886//   :memory:
887//   file::memory:
888//
889//   mode
890//     Access mode of the database.
891//     https://www.sqlite.org/c3ref/open.html
892//     Values:
893//      - ro
894//      - rw
895//      - rwc
896//      - memory
897//
898//   shared
899//     SQLite Shared-Cache Mode
900//     https://www.sqlite.org/sharedcache.html
901//     Values:
902//       - shared
903//       - private
904//
905//   immutable=Boolean
906//     The immutable parameter is a boolean query parameter that indicates
907//     that the database file is stored on read-only media. When immutable is set,
908//     SQLite assumes that the database file cannot be changed,
909//     even by a process with higher privilege,
910//     and so the database is opened read-only and all locking and change detection is disabled.
911//     Caution: Setting the immutable property on a database file that
912//     does in fact change can result in incorrect query results and/or SQLITE_CORRUPT errors.
913//
914// go-sqlite3 adds the following query parameters to those used by SQLite:
915//   _loc=XXX
916//     Specify location of time format. It's possible to specify "auto".
917//
918//   _mutex=XXX
919//     Specify mutex mode. XXX can be "no", "full".
920//
921//   _txlock=XXX
922//     Specify locking behavior for transactions.  XXX can be "immediate",
923//     "deferred", "exclusive".
924//
925//   _auto_vacuum=X | _vacuum=X
926//     0 | none - Auto Vacuum disabled
927//     1 | full - Auto Vacuum FULL
928//     2 | incremental - Auto Vacuum Incremental
929//
930//   _busy_timeout=XXX"| _timeout=XXX
931//     Specify value for sqlite3_busy_timeout.
932//
933//   _case_sensitive_like=Boolean | _cslike=Boolean
934//     https://www.sqlite.org/pragma.html#pragma_case_sensitive_like
935//     Default or disabled the LIKE operation is case-insensitive.
936//     When enabling this options behaviour of LIKE will become case-sensitive.
937//
938//   _defer_foreign_keys=Boolean | _defer_fk=Boolean
939//     Defer Foreign Keys until outermost transaction is committed.
940//
941//   _foreign_keys=Boolean | _fk=Boolean
942//     Enable or disable enforcement of foreign keys.
943//
944//   _ignore_check_constraints=Boolean
945//     This pragma enables or disables the enforcement of CHECK constraints.
946//     The default setting is off, meaning that CHECK constraints are enforced by default.
947//
948//   _journal_mode=MODE | _journal=MODE
949//     Set journal mode for the databases associated with the current connection.
950//     https://www.sqlite.org/pragma.html#pragma_journal_mode
951//
952//   _locking_mode=X | _locking=X
953//     Sets the database connection locking-mode.
954//     The locking-mode is either NORMAL or EXCLUSIVE.
955//     https://www.sqlite.org/pragma.html#pragma_locking_mode
956//
957//   _query_only=Boolean
958//     The query_only pragma prevents all changes to database files when enabled.
959//
960//   _recursive_triggers=Boolean | _rt=Boolean
961//     Enable or disable recursive triggers.
962//
963//   _secure_delete=Boolean|FAST
964//     When secure_delete is on, SQLite overwrites deleted content with zeros.
965//     https://www.sqlite.org/pragma.html#pragma_secure_delete
966//
967//   _synchronous=X | _sync=X
968//     Change the setting of the "synchronous" flag.
969//     https://www.sqlite.org/pragma.html#pragma_synchronous
970//
971//   _writable_schema=Boolean
972//     When this pragma is on, the SQLITE_MASTER tables in which database
973//     can be changed using ordinary UPDATE, INSERT, and DELETE statements.
974//     Warning: misuse of this pragma can easily result in a corrupt database file.
975//
976//
977func (d *SQLiteDriver) Open(dsn string) (driver.Conn, error) {
978	if C.sqlite3_threadsafe() == 0 {
979		return nil, errors.New("sqlite library was not compiled for thread-safe operation")
980	}
981
982	var pkey string
983
984	// Options
985	var loc *time.Location
986	authCreate := false
987	authUser := ""
988	authPass := ""
989	authCrypt := ""
990	authSalt := ""
991	mutex := C.int(C.SQLITE_OPEN_FULLMUTEX)
992	txlock := "BEGIN"
993
994	// PRAGMA's
995	autoVacuum := -1
996	busyTimeout := 5000
997	caseSensitiveLike := -1
998	deferForeignKeys := -1
999	foreignKeys := -1
1000	ignoreCheckConstraints := -1
1001	journalMode := "DELETE"
1002	lockingMode := "NORMAL"
1003	queryOnly := -1
1004	recursiveTriggers := -1
1005	secureDelete := "DEFAULT"
1006	synchronousMode := "NORMAL"
1007	writableSchema := -1
1008
1009	pos := strings.IndexRune(dsn, '?')
1010	if pos >= 1 {
1011		params, err := url.ParseQuery(dsn[pos+1:])
1012		if err != nil {
1013			return nil, err
1014		}
1015
1016		// Authentication
1017		if _, ok := params["_auth"]; ok {
1018			authCreate = true
1019		}
1020		if val := params.Get("_auth_user"); val != "" {
1021			authUser = val
1022		}
1023		if val := params.Get("_auth_pass"); val != "" {
1024			authPass = val
1025		}
1026		if val := params.Get("_auth_crypt"); val != "" {
1027			authCrypt = val
1028		}
1029		if val := params.Get("_auth_salt"); val != "" {
1030			authSalt = val
1031		}
1032
1033		// _loc
1034		if val := params.Get("_loc"); val != "" {
1035			switch strings.ToLower(val) {
1036			case "auto":
1037				loc = time.Local
1038			default:
1039				loc, err = time.LoadLocation(val)
1040				if err != nil {
1041					return nil, fmt.Errorf("Invalid _loc: %v: %v", val, err)
1042				}
1043			}
1044		}
1045
1046		// _mutex
1047		if val := params.Get("_mutex"); val != "" {
1048			switch strings.ToLower(val) {
1049			case "no":
1050				mutex = C.SQLITE_OPEN_NOMUTEX
1051			case "full":
1052				mutex = C.SQLITE_OPEN_FULLMUTEX
1053			default:
1054				return nil, fmt.Errorf("Invalid _mutex: %v", val)
1055			}
1056		}
1057
1058		// _txlock
1059		if val := params.Get("_txlock"); val != "" {
1060			switch strings.ToLower(val) {
1061			case "immediate":
1062				txlock = "BEGIN IMMEDIATE"
1063			case "exclusive":
1064				txlock = "BEGIN EXCLUSIVE"
1065			case "deferred":
1066				txlock = "BEGIN"
1067			default:
1068				return nil, fmt.Errorf("Invalid _txlock: %v", val)
1069			}
1070		}
1071
1072		// Auto Vacuum (_vacuum)
1073		//
1074		// https://www.sqlite.org/pragma.html#pragma_auto_vacuum
1075		//
1076		pkey = "" // Reset pkey
1077		if _, ok := params["_auto_vacuum"]; ok {
1078			pkey = "_auto_vacuum"
1079		}
1080		if _, ok := params["_vacuum"]; ok {
1081			pkey = "_vacuum"
1082		}
1083		if val := params.Get(pkey); val != "" {
1084			switch strings.ToLower(val) {
1085			case "0", "none":
1086				autoVacuum = 0
1087			case "1", "full":
1088				autoVacuum = 1
1089			case "2", "incremental":
1090				autoVacuum = 2
1091			default:
1092				return nil, fmt.Errorf("Invalid _auto_vacuum: %v, expecting value of '0 NONE 1 FULL 2 INCREMENTAL'", val)
1093			}
1094		}
1095
1096		// Busy Timeout (_busy_timeout)
1097		//
1098		// https://www.sqlite.org/pragma.html#pragma_busy_timeout
1099		//
1100		pkey = "" // Reset pkey
1101		if _, ok := params["_busy_timeout"]; ok {
1102			pkey = "_busy_timeout"
1103		}
1104		if _, ok := params["_timeout"]; ok {
1105			pkey = "_timeout"
1106		}
1107		if val := params.Get(pkey); val != "" {
1108			iv, err := strconv.ParseInt(val, 10, 64)
1109			if err != nil {
1110				return nil, fmt.Errorf("Invalid _busy_timeout: %v: %v", val, err)
1111			}
1112			busyTimeout = int(iv)
1113		}
1114
1115		// Case Sensitive Like (_cslike)
1116		//
1117		// https://www.sqlite.org/pragma.html#pragma_case_sensitive_like
1118		//
1119		pkey = "" // Reset pkey
1120		if _, ok := params["_case_sensitive_like"]; ok {
1121			pkey = "_case_sensitive_like"
1122		}
1123		if _, ok := params["_cslike"]; ok {
1124			pkey = "_cslike"
1125		}
1126		if val := params.Get(pkey); val != "" {
1127			switch strings.ToLower(val) {
1128			case "0", "no", "false", "off":
1129				caseSensitiveLike = 0
1130			case "1", "yes", "true", "on":
1131				caseSensitiveLike = 1
1132			default:
1133				return nil, fmt.Errorf("Invalid _case_sensitive_like: %v, expecting boolean value of '0 1 false true no yes off on'", val)
1134			}
1135		}
1136
1137		// Defer Foreign Keys (_defer_foreign_keys | _defer_fk)
1138		//
1139		// https://www.sqlite.org/pragma.html#pragma_defer_foreign_keys
1140		//
1141		pkey = "" // Reset pkey
1142		if _, ok := params["_defer_foreign_keys"]; ok {
1143			pkey = "_defer_foreign_keys"
1144		}
1145		if _, ok := params["_defer_fk"]; ok {
1146			pkey = "_defer_fk"
1147		}
1148		if val := params.Get(pkey); val != "" {
1149			switch strings.ToLower(val) {
1150			case "0", "no", "false", "off":
1151				deferForeignKeys = 0
1152			case "1", "yes", "true", "on":
1153				deferForeignKeys = 1
1154			default:
1155				return nil, fmt.Errorf("Invalid _defer_foreign_keys: %v, expecting boolean value of '0 1 false true no yes off on'", val)
1156			}
1157		}
1158
1159		// Foreign Keys (_foreign_keys | _fk)
1160		//
1161		// https://www.sqlite.org/pragma.html#pragma_foreign_keys
1162		//
1163		pkey = "" // Reset pkey
1164		if _, ok := params["_foreign_keys"]; ok {
1165			pkey = "_foreign_keys"
1166		}
1167		if _, ok := params["_fk"]; ok {
1168			pkey = "_fk"
1169		}
1170		if val := params.Get(pkey); val != "" {
1171			switch strings.ToLower(val) {
1172			case "0", "no", "false", "off":
1173				foreignKeys = 0
1174			case "1", "yes", "true", "on":
1175				foreignKeys = 1
1176			default:
1177				return nil, fmt.Errorf("Invalid _foreign_keys: %v, expecting boolean value of '0 1 false true no yes off on'", val)
1178			}
1179		}
1180
1181		// Ignore CHECK Constrains (_ignore_check_constraints)
1182		//
1183		// https://www.sqlite.org/pragma.html#pragma_ignore_check_constraints
1184		//
1185		if val := params.Get("_ignore_check_constraints"); val != "" {
1186			switch strings.ToLower(val) {
1187			case "0", "no", "false", "off":
1188				ignoreCheckConstraints = 0
1189			case "1", "yes", "true", "on":
1190				ignoreCheckConstraints = 1
1191			default:
1192				return nil, fmt.Errorf("Invalid _ignore_check_constraints: %v, expecting boolean value of '0 1 false true no yes off on'", val)
1193			}
1194		}
1195
1196		// Journal Mode (_journal_mode | _journal)
1197		//
1198		// https://www.sqlite.org/pragma.html#pragma_journal_mode
1199		//
1200		pkey = "" // Reset pkey
1201		if _, ok := params["_journal_mode"]; ok {
1202			pkey = "_journal_mode"
1203		}
1204		if _, ok := params["_journal"]; ok {
1205			pkey = "_journal"
1206		}
1207		if val := params.Get(pkey); val != "" {
1208			switch strings.ToUpper(val) {
1209			case "DELETE", "TRUNCATE", "PERSIST", "MEMORY", "OFF":
1210				journalMode = strings.ToUpper(val)
1211			case "WAL":
1212				journalMode = strings.ToUpper(val)
1213
1214				// For WAL Mode set Synchronous Mode to 'NORMAL'
1215				// See https://www.sqlite.org/pragma.html#pragma_synchronous
1216				synchronousMode = "NORMAL"
1217			default:
1218				return nil, fmt.Errorf("Invalid _journal: %v, expecting value of 'DELETE TRUNCATE PERSIST MEMORY WAL OFF'", val)
1219			}
1220		}
1221
1222		// Locking Mode (_locking)
1223		//
1224		// https://www.sqlite.org/pragma.html#pragma_locking_mode
1225		//
1226		pkey = "" // Reset pkey
1227		if _, ok := params["_locking_mode"]; ok {
1228			pkey = "_locking_mode"
1229		}
1230		if _, ok := params["_locking"]; ok {
1231			pkey = "_locking"
1232		}
1233		if val := params.Get("_locking"); val != "" {
1234			switch strings.ToUpper(val) {
1235			case "NORMAL", "EXCLUSIVE":
1236				lockingMode = strings.ToUpper(val)
1237			default:
1238				return nil, fmt.Errorf("Invalid _locking_mode: %v, expecting value of 'NORMAL EXCLUSIVE", val)
1239			}
1240		}
1241
1242		// Query Only (_query_only)
1243		//
1244		// https://www.sqlite.org/pragma.html#pragma_query_only
1245		//
1246		if val := params.Get("_query_only"); val != "" {
1247			switch strings.ToLower(val) {
1248			case "0", "no", "false", "off":
1249				queryOnly = 0
1250			case "1", "yes", "true", "on":
1251				queryOnly = 1
1252			default:
1253				return nil, fmt.Errorf("Invalid _query_only: %v, expecting boolean value of '0 1 false true no yes off on'", val)
1254			}
1255		}
1256
1257		// Recursive Triggers (_recursive_triggers)
1258		//
1259		// https://www.sqlite.org/pragma.html#pragma_recursive_triggers
1260		//
1261		pkey = "" // Reset pkey
1262		if _, ok := params["_recursive_triggers"]; ok {
1263			pkey = "_recursive_triggers"
1264		}
1265		if _, ok := params["_rt"]; ok {
1266			pkey = "_rt"
1267		}
1268		if val := params.Get(pkey); val != "" {
1269			switch strings.ToLower(val) {
1270			case "0", "no", "false", "off":
1271				recursiveTriggers = 0
1272			case "1", "yes", "true", "on":
1273				recursiveTriggers = 1
1274			default:
1275				return nil, fmt.Errorf("Invalid _recursive_triggers: %v, expecting boolean value of '0 1 false true no yes off on'", val)
1276			}
1277		}
1278
1279		// Secure Delete (_secure_delete)
1280		//
1281		// https://www.sqlite.org/pragma.html#pragma_secure_delete
1282		//
1283		if val := params.Get("_secure_delete"); val != "" {
1284			switch strings.ToLower(val) {
1285			case "0", "no", "false", "off":
1286				secureDelete = "OFF"
1287			case "1", "yes", "true", "on":
1288				secureDelete = "ON"
1289			case "fast":
1290				secureDelete = "FAST"
1291			default:
1292				return nil, fmt.Errorf("Invalid _secure_delete: %v, expecting boolean value of '0 1 false true no yes off on fast'", val)
1293			}
1294		}
1295
1296		// Synchronous Mode (_synchronous | _sync)
1297		//
1298		// https://www.sqlite.org/pragma.html#pragma_synchronous
1299		//
1300		pkey = "" // Reset pkey
1301		if _, ok := params["_synchronous"]; ok {
1302			pkey = "_synchronous"
1303		}
1304		if _, ok := params["_sync"]; ok {
1305			pkey = "_sync"
1306		}
1307		if val := params.Get(pkey); val != "" {
1308			switch strings.ToUpper(val) {
1309			case "0", "OFF", "1", "NORMAL", "2", "FULL", "3", "EXTRA":
1310				synchronousMode = strings.ToUpper(val)
1311			default:
1312				return nil, fmt.Errorf("Invalid _synchronous: %v, expecting value of '0 OFF 1 NORMAL 2 FULL 3 EXTRA'", val)
1313			}
1314		}
1315
1316		// Writable Schema (_writeable_schema)
1317		//
1318		// https://www.sqlite.org/pragma.html#pragma_writeable_schema
1319		//
1320		if val := params.Get("_writable_schema"); val != "" {
1321			switch strings.ToLower(val) {
1322			case "0", "no", "false", "off":
1323				writableSchema = 0
1324			case "1", "yes", "true", "on":
1325				writableSchema = 1
1326			default:
1327				return nil, fmt.Errorf("Invalid _writable_schema: %v, expecting boolean value of '0 1 false true no yes off on'", val)
1328			}
1329		}
1330
1331		if !strings.HasPrefix(dsn, "file:") {
1332			dsn = dsn[:pos]
1333		}
1334	}
1335
1336	var db *C.sqlite3
1337	name := C.CString(dsn)
1338	defer C.free(unsafe.Pointer(name))
1339	rv := C._sqlite3_open_v2(name, &db,
1340		mutex|C.SQLITE_OPEN_READWRITE|C.SQLITE_OPEN_CREATE,
1341		nil)
1342	if rv != 0 {
1343		return nil, Error{Code: ErrNo(rv)}
1344	}
1345	if db == nil {
1346		return nil, errors.New("sqlite succeeded without returning a database")
1347	}
1348
1349	rv = C.sqlite3_busy_timeout(db, C.int(busyTimeout))
1350	if rv != C.SQLITE_OK {
1351		C.sqlite3_close_v2(db)
1352		return nil, Error{Code: ErrNo(rv)}
1353	}
1354
1355	exec := func(s string) error {
1356		cs := C.CString(s)
1357		rv := C.sqlite3_exec(db, cs, nil, nil, nil)
1358		C.free(unsafe.Pointer(cs))
1359		if rv != C.SQLITE_OK {
1360			return lastError(db)
1361		}
1362		return nil
1363	}
1364
1365	// USER AUTHENTICATION
1366	//
1367	// User Authentication is always performed even when
1368	// sqlite_userauth is not compiled in, because without user authentication
1369	// the authentication is a no-op.
1370	//
1371	// Workflow
1372	//	- Authenticate
1373	//		ON::SUCCESS		=> Continue
1374	//		ON::SQLITE_AUTH => Return error and exit Open(...)
1375	//
1376	//  - Activate User Authentication
1377	//		Check if the user wants to activate User Authentication.
1378	//		If so then first create a temporary AuthConn to the database
1379	//		This is possible because we are already succesfully authenticated.
1380	//
1381	//	- Check if `sqlite_user`` table exists
1382	//		YES				=> Add the provided user from DSN as Admin User and
1383	//						   activate user authentication.
1384	//		NO				=> Continue
1385	//
1386
1387	// Create connection to SQLite
1388	conn := &SQLiteConn{db: db, loc: loc, txlock: txlock}
1389
1390	// Password Cipher has to be registerd before authentication
1391	if len(authCrypt) > 0 {
1392		switch strings.ToUpper(authCrypt) {
1393		case "SHA1":
1394			if err := conn.RegisterFunc("sqlite_crypt", CryptEncoderSHA1, true); err != nil {
1395				return nil, fmt.Errorf("CryptEncoderSHA1: %s", err)
1396			}
1397		case "SSHA1":
1398			if len(authSalt) == 0 {
1399				return nil, fmt.Errorf("_auth_crypt=ssha1, requires _auth_salt")
1400			}
1401			if err := conn.RegisterFunc("sqlite_crypt", CryptEncoderSSHA1(authSalt), true); err != nil {
1402				return nil, fmt.Errorf("CryptEncoderSSHA1: %s", err)
1403			}
1404		case "SHA256":
1405			if err := conn.RegisterFunc("sqlite_crypt", CryptEncoderSHA256, true); err != nil {
1406				return nil, fmt.Errorf("CryptEncoderSHA256: %s", err)
1407			}
1408		case "SSHA256":
1409			if len(authSalt) == 0 {
1410				return nil, fmt.Errorf("_auth_crypt=ssha256, requires _auth_salt")
1411			}
1412			if err := conn.RegisterFunc("sqlite_crypt", CryptEncoderSSHA256(authSalt), true); err != nil {
1413				return nil, fmt.Errorf("CryptEncoderSSHA256: %s", err)
1414			}
1415		case "SHA384":
1416			if err := conn.RegisterFunc("sqlite_crypt", CryptEncoderSHA384, true); err != nil {
1417				return nil, fmt.Errorf("CryptEncoderSHA384: %s", err)
1418			}
1419		case "SSHA384":
1420			if len(authSalt) == 0 {
1421				return nil, fmt.Errorf("_auth_crypt=ssha384, requires _auth_salt")
1422			}
1423			if err := conn.RegisterFunc("sqlite_crypt", CryptEncoderSSHA384(authSalt), true); err != nil {
1424				return nil, fmt.Errorf("CryptEncoderSSHA384: %s", err)
1425			}
1426		case "SHA512":
1427			if err := conn.RegisterFunc("sqlite_crypt", CryptEncoderSHA512, true); err != nil {
1428				return nil, fmt.Errorf("CryptEncoderSHA512: %s", err)
1429			}
1430		case "SSHA512":
1431			if len(authSalt) == 0 {
1432				return nil, fmt.Errorf("_auth_crypt=ssha512, requires _auth_salt")
1433			}
1434			if err := conn.RegisterFunc("sqlite_crypt", CryptEncoderSSHA512(authSalt), true); err != nil {
1435				return nil, fmt.Errorf("CryptEncoderSSHA512: %s", err)
1436			}
1437		}
1438	}
1439
1440	// Preform Authentication
1441	if err := conn.Authenticate(authUser, authPass); err != nil {
1442		return nil, err
1443	}
1444
1445	// Register: authenticate
1446	// Authenticate will perform an authentication of the provided username
1447	// and password against the database.
1448	//
1449	// If a database contains the SQLITE_USER table, then the
1450	// call to Authenticate must be invoked with an
1451	// appropriate username and password prior to enable read and write
1452	//access to the database.
1453	//
1454	// Return SQLITE_OK on success or SQLITE_ERROR if the username/password
1455	// combination is incorrect or unknown.
1456	//
1457	// If the SQLITE_USER table is not present in the database file, then
1458	// this interface is a harmless no-op returnning SQLITE_OK.
1459	if err := conn.RegisterFunc("authenticate", conn.authenticate, true); err != nil {
1460		return nil, err
1461	}
1462	//
1463	// Register: auth_user_add
1464	// auth_user_add can be used (by an admin user only)
1465	// to create a new user. When called on a no-authentication-required
1466	// database, this routine converts the database into an authentication-
1467	// required database, automatically makes the added user an
1468	// administrator, and logs in the current connection as that user.
1469	// The AuthUserAdd only works for the "main" database, not
1470	// for any ATTACH-ed databases. Any call to AuthUserAdd by a
1471	// non-admin user results in an error.
1472	if err := conn.RegisterFunc("auth_user_add", conn.authUserAdd, true); err != nil {
1473		return nil, err
1474	}
1475	//
1476	// Register: auth_user_change
1477	// auth_user_change can be used to change a users
1478	// login credentials or admin privilege.  Any user can change their own
1479	// login credentials. Only an admin user can change another users login
1480	// credentials or admin privilege setting. No user may change their own
1481	// admin privilege setting.
1482	if err := conn.RegisterFunc("auth_user_change", conn.authUserChange, true); err != nil {
1483		return nil, err
1484	}
1485	//
1486	// Register: auth_user_delete
1487	// auth_user_delete can be used (by an admin user only)
1488	// to delete a user. The currently logged-in user cannot be deleted,
1489	// which guarantees that there is always an admin user and hence that
1490	// the database cannot be converted into a no-authentication-required
1491	// database.
1492	if err := conn.RegisterFunc("auth_user_delete", conn.authUserDelete, true); err != nil {
1493		return nil, err
1494	}
1495
1496	// Register: auth_enabled
1497	// auth_enabled can be used to check if user authentication is enabled
1498	if err := conn.RegisterFunc("auth_enabled", conn.authEnabled, true); err != nil {
1499		return nil, err
1500	}
1501
1502	// Auto Vacuum
1503	// Moved auto_vacuum command, the user preference for auto_vacuum needs to be implemented directly after
1504	// the authentication and before the sqlite_user table gets created if the user
1505	// decides to activate User Authentication because
1506	// auto_vacuum needs to be set before any tables are created
1507	// and activating user authentication creates the internal table `sqlite_user`.
1508	if autoVacuum > -1 {
1509		if err := exec(fmt.Sprintf("PRAGMA auto_vacuum = %d;", autoVacuum)); err != nil {
1510			C.sqlite3_close_v2(db)
1511			return nil, err
1512		}
1513	}
1514
1515	// Check if user wants to activate User Authentication
1516	if authCreate {
1517		// Before going any further, we need to check that the user
1518		// has provided an username and password within the DSN.
1519		// We are not allowed to continue.
1520		if len(authUser) < 0 {
1521			return nil, fmt.Errorf("Missing '_auth_user' while user authentication was requested with '_auth'")
1522		}
1523		if len(authPass) < 0 {
1524			return nil, fmt.Errorf("Missing '_auth_pass' while user authentication was requested with '_auth'")
1525		}
1526
1527		// Check if User Authentication is Enabled
1528		authExists := conn.AuthEnabled()
1529		if !authExists {
1530			if err := conn.AuthUserAdd(authUser, authPass, true); err != nil {
1531				return nil, err
1532			}
1533		}
1534	}
1535
1536	// Case Sensitive LIKE
1537	if caseSensitiveLike > -1 {
1538		if err := exec(fmt.Sprintf("PRAGMA case_sensitive_like = %d;", caseSensitiveLike)); err != nil {
1539			C.sqlite3_close_v2(db)
1540			return nil, err
1541		}
1542	}
1543
1544	// Defer Foreign Keys
1545	if deferForeignKeys > -1 {
1546		if err := exec(fmt.Sprintf("PRAGMA defer_foreign_keys = %d;", deferForeignKeys)); err != nil {
1547			C.sqlite3_close_v2(db)
1548			return nil, err
1549		}
1550	}
1551
1552	// Forgein Keys
1553	if foreignKeys > -1 {
1554		if err := exec(fmt.Sprintf("PRAGMA foreign_keys = %d;", foreignKeys)); err != nil {
1555			C.sqlite3_close_v2(db)
1556			return nil, err
1557		}
1558	}
1559
1560	// Ignore CHECK Constraints
1561	if ignoreCheckConstraints > -1 {
1562		if err := exec(fmt.Sprintf("PRAGMA ignore_check_constraints = %d;", ignoreCheckConstraints)); err != nil {
1563			C.sqlite3_close_v2(db)
1564			return nil, err
1565		}
1566	}
1567
1568	// Journal Mode
1569	// Because default Journal Mode is DELETE this PRAGMA can always be executed.
1570	if err := exec(fmt.Sprintf("PRAGMA journal_mode = %s;", journalMode)); err != nil {
1571		C.sqlite3_close_v2(db)
1572		return nil, err
1573	}
1574
1575	// Locking Mode
1576	// Because the default is NORMAL and this is not changed in this package
1577	// by using the compile time SQLITE_DEFAULT_LOCKING_MODE this PRAGMA can always be executed
1578	if err := exec(fmt.Sprintf("PRAGMA locking_mode = %s;", lockingMode)); err != nil {
1579		C.sqlite3_close_v2(db)
1580		return nil, err
1581	}
1582
1583	// Query Only
1584	if queryOnly > -1 {
1585		if err := exec(fmt.Sprintf("PRAGMA query_only = %d;", queryOnly)); err != nil {
1586			C.sqlite3_close_v2(db)
1587			return nil, err
1588		}
1589	}
1590
1591	// Recursive Triggers
1592	if recursiveTriggers > -1 {
1593		if err := exec(fmt.Sprintf("PRAGMA recursive_triggers = %d;", recursiveTriggers)); err != nil {
1594			C.sqlite3_close_v2(db)
1595			return nil, err
1596		}
1597	}
1598
1599	// Secure Delete
1600	//
1601	// Because this package can set the compile time flag SQLITE_SECURE_DELETE with a build tag
1602	// the default value for secureDelete var is 'DEFAULT' this way
1603	// you can compile with secure_delete 'ON' and disable it for a specific database connection.
1604	if secureDelete != "DEFAULT" {
1605		if err := exec(fmt.Sprintf("PRAGMA secure_delete = %s;", secureDelete)); err != nil {
1606			C.sqlite3_close_v2(db)
1607			return nil, err
1608		}
1609	}
1610
1611	// Synchronous Mode
1612	//
1613	// Because default is NORMAL this statement is always executed
1614	if err := exec(fmt.Sprintf("PRAGMA synchronous = %s;", synchronousMode)); err != nil {
1615		C.sqlite3_close_v2(db)
1616		return nil, err
1617	}
1618
1619	// Writable Schema
1620	if writableSchema > -1 {
1621		if err := exec(fmt.Sprintf("PRAGMA writable_schema = %d;", writableSchema)); err != nil {
1622			C.sqlite3_close_v2(db)
1623			return nil, err
1624		}
1625	}
1626
1627	if len(d.Extensions) > 0 {
1628		if err := conn.loadExtensions(d.Extensions); err != nil {
1629			conn.Close()
1630			return nil, err
1631		}
1632	}
1633
1634	if d.ConnectHook != nil {
1635		if err := d.ConnectHook(conn); err != nil {
1636			conn.Close()
1637			return nil, err
1638		}
1639	}
1640	runtime.SetFinalizer(conn, (*SQLiteConn).Close)
1641	return conn, nil
1642}
1643
1644// Close the connection.
1645func (c *SQLiteConn) Close() error {
1646	rv := C.sqlite3_close_v2(c.db)
1647	if rv != C.SQLITE_OK {
1648		return c.lastError()
1649	}
1650	deleteHandles(c)
1651	c.mu.Lock()
1652	c.db = nil
1653	c.mu.Unlock()
1654	runtime.SetFinalizer(c, nil)
1655	return nil
1656}
1657
1658func (c *SQLiteConn) dbConnOpen() bool {
1659	if c == nil {
1660		return false
1661	}
1662	c.mu.Lock()
1663	defer c.mu.Unlock()
1664	return c.db != nil
1665}
1666
1667// Prepare the query string. Return a new statement.
1668func (c *SQLiteConn) Prepare(query string) (driver.Stmt, error) {
1669	return c.prepare(context.Background(), query)
1670}
1671
1672func (c *SQLiteConn) prepare(ctx context.Context, query string) (driver.Stmt, error) {
1673	pquery := C.CString(query)
1674	defer C.free(unsafe.Pointer(pquery))
1675	var s *C.sqlite3_stmt
1676	var tail *C.char
1677	rv := C._sqlite3_prepare_v2_internal(c.db, pquery, -1, &s, &tail)
1678	if rv != C.SQLITE_OK {
1679		return nil, c.lastError()
1680	}
1681	var t string
1682	if tail != nil && *tail != '\000' {
1683		t = strings.TrimSpace(C.GoString(tail))
1684	}
1685	ss := &SQLiteStmt{c: c, s: s, t: t}
1686	runtime.SetFinalizer(ss, (*SQLiteStmt).Close)
1687	return ss, nil
1688}
1689
1690// Run-Time Limit Categories.
1691// See: http://www.sqlite.org/c3ref/c_limit_attached.html
1692const (
1693	SQLITE_LIMIT_LENGTH              = C.SQLITE_LIMIT_LENGTH
1694	SQLITE_LIMIT_SQL_LENGTH          = C.SQLITE_LIMIT_SQL_LENGTH
1695	SQLITE_LIMIT_COLUMN              = C.SQLITE_LIMIT_COLUMN
1696	SQLITE_LIMIT_EXPR_DEPTH          = C.SQLITE_LIMIT_EXPR_DEPTH
1697	SQLITE_LIMIT_COMPOUND_SELECT     = C.SQLITE_LIMIT_COMPOUND_SELECT
1698	SQLITE_LIMIT_VDBE_OP             = C.SQLITE_LIMIT_VDBE_OP
1699	SQLITE_LIMIT_FUNCTION_ARG        = C.SQLITE_LIMIT_FUNCTION_ARG
1700	SQLITE_LIMIT_ATTACHED            = C.SQLITE_LIMIT_ATTACHED
1701	SQLITE_LIMIT_LIKE_PATTERN_LENGTH = C.SQLITE_LIMIT_LIKE_PATTERN_LENGTH
1702	SQLITE_LIMIT_VARIABLE_NUMBER     = C.SQLITE_LIMIT_VARIABLE_NUMBER
1703	SQLITE_LIMIT_TRIGGER_DEPTH       = C.SQLITE_LIMIT_TRIGGER_DEPTH
1704	SQLITE_LIMIT_WORKER_THREADS      = C.SQLITE_LIMIT_WORKER_THREADS
1705)
1706
1707// GetFilename returns the absolute path to the file containing
1708// the requested schema. When passed an empty string, it will
1709// instead use the database's default schema: "main".
1710// See: sqlite3_db_filename, https://www.sqlite.org/c3ref/db_filename.html
1711func (c *SQLiteConn) GetFilename(schemaName string) string {
1712	if schemaName == "" {
1713		schemaName = "main"
1714	}
1715	return C.GoString(C.sqlite3_db_filename(c.db, C.CString(schemaName)))
1716}
1717
1718// GetLimit returns the current value of a run-time limit.
1719// See: sqlite3_limit, http://www.sqlite.org/c3ref/limit.html
1720func (c *SQLiteConn) GetLimit(id int) int {
1721	return int(C._sqlite3_limit(c.db, C.int(id), -1))
1722}
1723
1724// SetLimit changes the value of a run-time limits.
1725// Then this method returns the prior value of the limit.
1726// See: sqlite3_limit, http://www.sqlite.org/c3ref/limit.html
1727func (c *SQLiteConn) SetLimit(id int, newVal int) int {
1728	return int(C._sqlite3_limit(c.db, C.int(id), C.int(newVal)))
1729}
1730
1731// Close the statement.
1732func (s *SQLiteStmt) Close() error {
1733	s.mu.Lock()
1734	defer s.mu.Unlock()
1735	if s.closed {
1736		return nil
1737	}
1738	s.closed = true
1739	if !s.c.dbConnOpen() {
1740		return errors.New("sqlite statement with already closed database connection")
1741	}
1742	rv := C.sqlite3_finalize(s.s)
1743	s.s = nil
1744	if rv != C.SQLITE_OK {
1745		return s.c.lastError()
1746	}
1747	runtime.SetFinalizer(s, nil)
1748	return nil
1749}
1750
1751// NumInput return a number of parameters.
1752func (s *SQLiteStmt) NumInput() int {
1753	return int(C.sqlite3_bind_parameter_count(s.s))
1754}
1755
1756type bindArg struct {
1757	n int
1758	v driver.Value
1759}
1760
1761var placeHolder = []byte{0}
1762
1763func (s *SQLiteStmt) bind(args []namedValue) error {
1764	rv := C.sqlite3_reset(s.s)
1765	if rv != C.SQLITE_ROW && rv != C.SQLITE_OK && rv != C.SQLITE_DONE {
1766		return s.c.lastError()
1767	}
1768
1769	for i, v := range args {
1770		if v.Name != "" {
1771			cname := C.CString(":" + v.Name)
1772			args[i].Ordinal = int(C.sqlite3_bind_parameter_index(s.s, cname))
1773			C.free(unsafe.Pointer(cname))
1774		}
1775	}
1776
1777	for _, arg := range args {
1778		n := C.int(arg.Ordinal)
1779		switch v := arg.Value.(type) {
1780		case nil:
1781			rv = C.sqlite3_bind_null(s.s, n)
1782		case string:
1783			if len(v) == 0 {
1784				rv = C._sqlite3_bind_text(s.s, n, (*C.char)(unsafe.Pointer(&placeHolder[0])), C.int(0))
1785			} else {
1786				b := []byte(v)
1787				rv = C._sqlite3_bind_text(s.s, n, (*C.char)(unsafe.Pointer(&b[0])), C.int(len(b)))
1788			}
1789		case int64:
1790			rv = C.sqlite3_bind_int64(s.s, n, C.sqlite3_int64(v))
1791		case bool:
1792			if v {
1793				rv = C.sqlite3_bind_int(s.s, n, 1)
1794			} else {
1795				rv = C.sqlite3_bind_int(s.s, n, 0)
1796			}
1797		case float64:
1798			rv = C.sqlite3_bind_double(s.s, n, C.double(v))
1799		case []byte:
1800			if v == nil {
1801				rv = C.sqlite3_bind_null(s.s, n)
1802			} else {
1803				ln := len(v)
1804				if ln == 0 {
1805					v = placeHolder
1806				}
1807				rv = C._sqlite3_bind_blob(s.s, n, unsafe.Pointer(&v[0]), C.int(ln))
1808			}
1809		case time.Time:
1810			b := []byte(v.Format(SQLiteTimestampFormats[0]))
1811			rv = C._sqlite3_bind_text(s.s, n, (*C.char)(unsafe.Pointer(&b[0])), C.int(len(b)))
1812		}
1813		if rv != C.SQLITE_OK {
1814			return s.c.lastError()
1815		}
1816	}
1817	return nil
1818}
1819
1820// Query the statement with arguments. Return records.
1821func (s *SQLiteStmt) Query(args []driver.Value) (driver.Rows, error) {
1822	list := make([]namedValue, len(args))
1823	for i, v := range args {
1824		list[i] = namedValue{
1825			Ordinal: i + 1,
1826			Value:   v,
1827		}
1828	}
1829	return s.query(context.Background(), list)
1830}
1831
1832func (s *SQLiteStmt) query(ctx context.Context, args []namedValue) (driver.Rows, error) {
1833	if err := s.bind(args); err != nil {
1834		return nil, err
1835	}
1836
1837	rows := &SQLiteRows{
1838		s:        s,
1839		nc:       int(C.sqlite3_column_count(s.s)),
1840		cols:     nil,
1841		decltype: nil,
1842		cls:      s.cls,
1843		closed:   false,
1844		done:     make(chan struct{}),
1845	}
1846
1847	if ctxdone := ctx.Done(); ctxdone != nil {
1848		go func(db *C.sqlite3) {
1849			select {
1850			case <-ctxdone:
1851				select {
1852				case <-rows.done:
1853				default:
1854					C.sqlite3_interrupt(db)
1855					rows.Close()
1856				}
1857			case <-rows.done:
1858			}
1859		}(s.c.db)
1860	}
1861
1862	return rows, nil
1863}
1864
1865// LastInsertId teturn last inserted ID.
1866func (r *SQLiteResult) LastInsertId() (int64, error) {
1867	return r.id, nil
1868}
1869
1870// RowsAffected return how many rows affected.
1871func (r *SQLiteResult) RowsAffected() (int64, error) {
1872	return r.changes, nil
1873}
1874
1875// Exec execute the statement with arguments. Return result object.
1876func (s *SQLiteStmt) Exec(args []driver.Value) (driver.Result, error) {
1877	list := make([]namedValue, len(args))
1878	for i, v := range args {
1879		list[i] = namedValue{
1880			Ordinal: i + 1,
1881			Value:   v,
1882		}
1883	}
1884	return s.exec(context.Background(), list)
1885}
1886
1887func (s *SQLiteStmt) exec(ctx context.Context, args []namedValue) (driver.Result, error) {
1888	if err := s.bind(args); err != nil {
1889		C.sqlite3_reset(s.s)
1890		C.sqlite3_clear_bindings(s.s)
1891		return nil, err
1892	}
1893
1894	if ctxdone := ctx.Done(); ctxdone != nil {
1895		done := make(chan struct{})
1896		defer close(done)
1897		go func(db *C.sqlite3) {
1898			select {
1899			case <-done:
1900			case <-ctxdone:
1901				select {
1902				case <-done:
1903				default:
1904					C.sqlite3_interrupt(db)
1905				}
1906			}
1907		}(s.c.db)
1908	}
1909
1910	var rowid, changes C.longlong
1911	rv := C._sqlite3_step_row_internal(s.s, &rowid, &changes)
1912	if rv != C.SQLITE_ROW && rv != C.SQLITE_OK && rv != C.SQLITE_DONE {
1913		err := s.c.lastError()
1914		C.sqlite3_reset(s.s)
1915		C.sqlite3_clear_bindings(s.s)
1916		return nil, err
1917	}
1918
1919	return &SQLiteResult{id: int64(rowid), changes: int64(changes)}, nil
1920}
1921
1922// Close the rows.
1923func (rc *SQLiteRows) Close() error {
1924	rc.s.mu.Lock()
1925	if rc.s.closed || rc.closed {
1926		rc.s.mu.Unlock()
1927		return nil
1928	}
1929	rc.closed = true
1930	if rc.done != nil {
1931		close(rc.done)
1932	}
1933	if rc.cls {
1934		rc.s.mu.Unlock()
1935		return rc.s.Close()
1936	}
1937	rv := C.sqlite3_reset(rc.s.s)
1938	if rv != C.SQLITE_OK {
1939		rc.s.mu.Unlock()
1940		return rc.s.c.lastError()
1941	}
1942	rc.s.mu.Unlock()
1943	return nil
1944}
1945
1946// Columns return column names.
1947func (rc *SQLiteRows) Columns() []string {
1948	rc.s.mu.Lock()
1949	defer rc.s.mu.Unlock()
1950	if rc.s.s != nil && rc.nc != len(rc.cols) {
1951		rc.cols = make([]string, rc.nc)
1952		for i := 0; i < rc.nc; i++ {
1953			rc.cols[i] = C.GoString(C.sqlite3_column_name(rc.s.s, C.int(i)))
1954		}
1955	}
1956	return rc.cols
1957}
1958
1959func (rc *SQLiteRows) declTypes() []string {
1960	if rc.s.s != nil && rc.decltype == nil {
1961		rc.decltype = make([]string, rc.nc)
1962		for i := 0; i < rc.nc; i++ {
1963			rc.decltype[i] = strings.ToLower(C.GoString(C.sqlite3_column_decltype(rc.s.s, C.int(i))))
1964		}
1965	}
1966	return rc.decltype
1967}
1968
1969// DeclTypes return column types.
1970func (rc *SQLiteRows) DeclTypes() []string {
1971	rc.s.mu.Lock()
1972	defer rc.s.mu.Unlock()
1973	return rc.declTypes()
1974}
1975
1976// Next move cursor to next.
1977func (rc *SQLiteRows) Next(dest []driver.Value) error {
1978	rc.s.mu.Lock()
1979	defer rc.s.mu.Unlock()
1980	if rc.s.closed {
1981		return io.EOF
1982	}
1983	rv := C._sqlite3_step_internal(rc.s.s)
1984	if rv == C.SQLITE_DONE {
1985		return io.EOF
1986	}
1987	if rv != C.SQLITE_ROW {
1988		rv = C.sqlite3_reset(rc.s.s)
1989		if rv != C.SQLITE_OK {
1990			return rc.s.c.lastError()
1991		}
1992		return nil
1993	}
1994
1995	rc.declTypes()
1996
1997	for i := range dest {
1998		switch C.sqlite3_column_type(rc.s.s, C.int(i)) {
1999		case C.SQLITE_INTEGER:
2000			val := int64(C.sqlite3_column_int64(rc.s.s, C.int(i)))
2001			switch rc.decltype[i] {
2002			case columnTimestamp, columnDatetime, columnDate:
2003				var t time.Time
2004				// Assume a millisecond unix timestamp if it's 13 digits -- too
2005				// large to be a reasonable timestamp in seconds.
2006				if val > 1e12 || val < -1e12 {
2007					val *= int64(time.Millisecond) // convert ms to nsec
2008					t = time.Unix(0, val)
2009				} else {
2010					t = time.Unix(val, 0)
2011				}
2012				t = t.UTC()
2013				if rc.s.c.loc != nil {
2014					t = t.In(rc.s.c.loc)
2015				}
2016				dest[i] = t
2017			case "boolean":
2018				dest[i] = val > 0
2019			default:
2020				dest[i] = val
2021			}
2022		case C.SQLITE_FLOAT:
2023			dest[i] = float64(C.sqlite3_column_double(rc.s.s, C.int(i)))
2024		case C.SQLITE_BLOB:
2025			p := C.sqlite3_column_blob(rc.s.s, C.int(i))
2026			if p == nil {
2027				dest[i] = nil
2028				continue
2029			}
2030			n := int(C.sqlite3_column_bytes(rc.s.s, C.int(i)))
2031			switch dest[i].(type) {
2032			default:
2033				slice := make([]byte, n)
2034				copy(slice[:], (*[1 << 30]byte)(p)[0:n])
2035				dest[i] = slice
2036			}
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] = []byte(s)
2066			}
2067
2068		}
2069	}
2070	return nil
2071}
2072