github.com/aergoio/aergo@v1.3.1/contract/sqlite3.go (about)

     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  
     9  package contract
    10  
    11  /*
    12  #cgo CFLAGS: -std=gnu99
    13  #cgo CFLAGS: -DSQLITE_THREADSAFE=1
    14  #cgo CFLAGS: -DHAVE_USLEEP=1
    15  #cgo CFLAGS: -DSQLITE_USE_URI=1
    16  #cgo CFLAGS: -DSQLITE_ENABLE_JSON1
    17  #cgo CFLAGS: -DSQLITE_ENABLE_COLUMN_METADATA
    18  #cgo CFLAGS: -DSQLITE_DEFAULT_FOREIGN_KEYS=1
    19  #cgo CFLAGS: -DSQLITE_OMIT_LOCALTIME
    20  #cgo linux CFLAGS: -DHAVE_PREAD64=1 -DHAVE_PWRITE64=1
    21  #cgo CFLAGS: -DSQLITE_TRACE_SIZE_LIMIT=15
    22  #cgo CFLAGS: -DSQLITE_DISABLE_INTRINSIC
    23  #cgo CFLAGS: -DOMIT_BRANCH_LOG
    24  #cgo CFLAGS: -I${SRCDIR}/../libtool/include
    25  #cgo LDFLAGS: ${SRCDIR}/../libtool/lib/liblmdb.a -lm
    26  #include "sqlite3-binding.h"
    27  #include <stdlib.h>
    28  #include <string.h>
    29  
    30  #ifdef __CYGWIN__
    31  # include <errno.h>
    32  #endif
    33  
    34  #ifndef SQLITE_OPEN_READWRITE
    35  # define SQLITE_OPEN_READWRITE 0
    36  #endif
    37  
    38  #ifndef SQLITE_OPEN_FULLMUTEX
    39  # define SQLITE_OPEN_FULLMUTEX 0
    40  #endif
    41  
    42  #ifndef SQLITE_DETERMINISTIC
    43  # define SQLITE_DETERMINISTIC 0
    44  #endif
    45  
    46  static int
    47  _sqlite3_open_v2(const char *filename, sqlite3 **ppDb, int flags, const char *zVfs) {
    48  #ifdef SQLITE_OPEN_URI
    49    return sqlite3_open_v2(filename, ppDb, flags | SQLITE_OPEN_URI, zVfs);
    50  #else
    51    return sqlite3_open_v2(filename, ppDb, flags, zVfs);
    52  #endif
    53  }
    54  
    55  static int
    56  _sqlite3_bind_text(sqlite3_stmt *stmt, int n, char *p, int np) {
    57    return sqlite3_bind_text(stmt, n, p, np, SQLITE_TRANSIENT);
    58  }
    59  
    60  static int
    61  _sqlite3_bind_blob(sqlite3_stmt *stmt, int n, void *p, int np) {
    62    return sqlite3_bind_blob(stmt, n, p, np, SQLITE_TRANSIENT);
    63  }
    64  
    65  #include <stdio.h>
    66  #include <stdint.h>
    67  
    68  static int
    69  _sqlite3_exec(sqlite3* db, const char* pcmd, long long* rowid, long long* changes)
    70  {
    71    int rv = sqlite3_exec(db, pcmd, 0, 0, 0);
    72    *rowid = (long long) sqlite3_last_insert_rowid(db);
    73    *changes = (long long) sqlite3_changes(db);
    74    return rv;
    75  }
    76  
    77  static int
    78  _sqlite3_step(sqlite3_stmt* stmt, long long* rowid, long long* changes)
    79  {
    80    int rv = sqlite3_step(stmt);
    81    sqlite3* db = sqlite3_db_handle(stmt);
    82    *rowid = (long long) sqlite3_last_insert_rowid(db);
    83    *changes = (long long) sqlite3_changes(db);
    84    return rv;
    85  }
    86  
    87  void _sqlite3_result_text(sqlite3_context* ctx, const char* s) {
    88    sqlite3_result_text(ctx, s, -1, &free);
    89  }
    90  
    91  void _sqlite3_result_blob(sqlite3_context* ctx, const void* b, int l) {
    92    sqlite3_result_blob(ctx, b, l, SQLITE_TRANSIENT);
    93  }
    94  
    95  
    96  int _sqlite3_create_function(
    97    sqlite3 *db,
    98    const char *zFunctionName,
    99    int nArg,
   100    int eTextRep,
   101    uintptr_t pApp,
   102    void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
   103    void (*xStep)(sqlite3_context*,int,sqlite3_value**),
   104    void (*xFinal)(sqlite3_context*)
   105  ) {
   106    return sqlite3_create_function(db, zFunctionName, nArg, eTextRep, (void*) pApp, xFunc, xStep, xFinal);
   107  }
   108  
   109  void callbackTrampoline(sqlite3_context*, int, sqlite3_value**);
   110  void stepTrampoline(sqlite3_context*, int, sqlite3_value**);
   111  void doneTrampoline(sqlite3_context*);
   112  
   113  int compareTrampoline(void*, int, char*, int, char*);
   114  int commitHookTrampoline(void*);
   115  void rollbackHookTrampoline(void*);
   116  void updateHookTrampoline(void*, int, char*, char*, sqlite3_int64);
   117  
   118  int authorizerTrampoline(void*, int, char*, char*, char*, char*);
   119  
   120  #ifdef SQLITE_LIMIT_WORKER_THREADS
   121  # define _SQLITE_HAS_LIMIT
   122  # define SQLITE_LIMIT_LENGTH                    0
   123  # define SQLITE_LIMIT_SQL_LENGTH                1
   124  # define SQLITE_LIMIT_COLUMN                    2
   125  # define SQLITE_LIMIT_EXPR_DEPTH                3
   126  # define SQLITE_LIMIT_COMPOUND_SELECT           4
   127  # define SQLITE_LIMIT_VDBE_OP                   5
   128  # define SQLITE_LIMIT_FUNCTION_ARG              6
   129  # define SQLITE_LIMIT_ATTACHED                  7
   130  # define SQLITE_LIMIT_LIKE_PATTERN_LENGTH       8
   131  # define SQLITE_LIMIT_VARIABLE_NUMBER           9
   132  # define SQLITE_LIMIT_TRIGGER_DEPTH            10
   133  # define SQLITE_LIMIT_WORKER_THREADS           11
   134  # else
   135  # define SQLITE_LIMIT_WORKER_THREADS           11
   136  #endif
   137  
   138  static int _sqlite3_limit(sqlite3* db, int limitId, int newLimit) {
   139  #ifndef _SQLITE_HAS_LIMIT
   140    return -1;
   141  #else
   142    return sqlite3_limit(db, limitId, newLimit);
   143  #endif
   144  }
   145  
   146  static int _sqlite3_disable_loadextfunc(sqlite3* db)
   147  {
   148    int rv = sqlite3_enable_load_extension(db, 0);
   149    if (rv != SQLITE_OK) {
   150      return rv;
   151    }
   152    return sqlite3_db_config(db, SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, 1, NULL);
   153  }
   154  */
   155  import "C"
   156  import (
   157  	"context"
   158  	"database/sql"
   159  	"database/sql/driver"
   160  	"errors"
   161  	"fmt"
   162  	"io"
   163  	"net/url"
   164  	"reflect"
   165  	"runtime"
   166  	"strings"
   167  	"sync"
   168  	"time"
   169  	"unsafe"
   170  )
   171  
   172  // SQLiteTimestampFormats is timestamp formats understood by both this module
   173  // and SQLite.  The first format in the slice will be used when saving time
   174  // values into the database. When parsing a string from a timestamp or datetime
   175  // column, the formats are tried in order.
   176  var SQLiteTimestampFormats = []string{
   177  	// By default, store timestamps with whatever timezone they come with.
   178  	// When parsed, they will be returned with the same timezone.
   179  	"2006-01-02 15:04:05.999999999-07:00",
   180  	"2006-01-02T15:04:05.999999999-07:00",
   181  	"2006-01-02 15:04:05.999999999",
   182  	"2006-01-02T15:04:05.999999999",
   183  	"2006-01-02 15:04:05",
   184  	"2006-01-02T15:04:05",
   185  	"2006-01-02 15:04",
   186  	"2006-01-02T15:04",
   187  	"2006-01-02",
   188  }
   189  
   190  const (
   191  	columnDate      string = "date"
   192  	columnDatetime  string = "datetime"
   193  	columnTimestamp string = "timestamp"
   194  )
   195  
   196  func init() {
   197  	sql.Register("litetree", &SQLiteDriver{})
   198  }
   199  
   200  // Version returns SQLite library version information.
   201  func Version() (libVersion string, libVersionNumber int, sourceID string) {
   202  	libVersion = C.GoString(C.sqlite3_libversion())
   203  	libVersionNumber = int(C.sqlite3_libversion_number())
   204  	sourceID = C.GoString(C.sqlite3_sourceid())
   205  	return libVersion, libVersionNumber, sourceID
   206  }
   207  
   208  const (
   209  	// used by authorizer and pre_update_hook
   210  	SQLITE_DELETE = C.SQLITE_DELETE
   211  	SQLITE_INSERT = C.SQLITE_INSERT
   212  	SQLITE_UPDATE = C.SQLITE_UPDATE
   213  
   214  	// used by authorzier - as return value
   215  	SQLITE_OK     = C.SQLITE_OK
   216  	SQLITE_IGNORE = C.SQLITE_IGNORE
   217  	SQLITE_DENY   = C.SQLITE_DENY
   218  
   219  	// different actions query tries to do - passed as argument to authorizer
   220  	SQLITE_CREATE_INDEX        = C.SQLITE_CREATE_INDEX
   221  	SQLITE_CREATE_TABLE        = C.SQLITE_CREATE_TABLE
   222  	SQLITE_CREATE_TEMP_INDEX   = C.SQLITE_CREATE_TEMP_INDEX
   223  	SQLITE_CREATE_TEMP_TABLE   = C.SQLITE_CREATE_TEMP_TABLE
   224  	SQLITE_CREATE_TEMP_TRIGGER = C.SQLITE_CREATE_TEMP_TRIGGER
   225  	SQLITE_CREATE_TEMP_VIEW    = C.SQLITE_CREATE_TEMP_VIEW
   226  	SQLITE_CREATE_TRIGGER      = C.SQLITE_CREATE_TRIGGER
   227  	SQLITE_CREATE_VIEW         = C.SQLITE_CREATE_VIEW
   228  	SQLITE_CREATE_VTABLE       = C.SQLITE_CREATE_VTABLE
   229  	SQLITE_DROP_INDEX          = C.SQLITE_DROP_INDEX
   230  	SQLITE_DROP_TABLE          = C.SQLITE_DROP_TABLE
   231  	SQLITE_DROP_TEMP_INDEX     = C.SQLITE_DROP_TEMP_INDEX
   232  	SQLITE_DROP_TEMP_TABLE     = C.SQLITE_DROP_TEMP_TABLE
   233  	SQLITE_DROP_TEMP_TRIGGER   = C.SQLITE_DROP_TEMP_TRIGGER
   234  	SQLITE_DROP_TEMP_VIEW      = C.SQLITE_DROP_TEMP_VIEW
   235  	SQLITE_DROP_TRIGGER        = C.SQLITE_DROP_TRIGGER
   236  	SQLITE_DROP_VIEW           = C.SQLITE_DROP_VIEW
   237  	SQLITE_DROP_VTABLE         = C.SQLITE_DROP_VTABLE
   238  	SQLITE_PRAGMA              = C.SQLITE_PRAGMA
   239  	SQLITE_READ                = C.SQLITE_READ
   240  	SQLITE_SELECT              = C.SQLITE_SELECT
   241  	SQLITE_TRANSACTION         = C.SQLITE_TRANSACTION
   242  	SQLITE_ATTACH              = C.SQLITE_ATTACH
   243  	SQLITE_DETACH              = C.SQLITE_DETACH
   244  	SQLITE_ALTER_TABLE         = C.SQLITE_ALTER_TABLE
   245  	SQLITE_REINDEX             = C.SQLITE_REINDEX
   246  	SQLITE_ANALYZE             = C.SQLITE_ANALYZE
   247  	SQLITE_FUNCTION            = C.SQLITE_FUNCTION
   248  	SQLITE_SAVEPOINT           = C.SQLITE_SAVEPOINT
   249  	SQLITE_COPY                = C.SQLITE_COPY
   250  	/*SQLITE_RECURSIVE           = C.SQLITE_RECURSIVE*/
   251  )
   252  
   253  // SQLiteDriver implements driver.Driver.
   254  type SQLiteDriver struct {
   255  	Extensions  []string
   256  	ConnectHook func(*SQLiteConn) error
   257  }
   258  
   259  // SQLiteConn implements driver.Conn.
   260  type SQLiteConn struct {
   261  	mu          sync.Mutex
   262  	db          *C.sqlite3
   263  	loc         *time.Location
   264  	txlock      string
   265  	funcs       []*functionInfo
   266  	aggregators []*aggInfo
   267  }
   268  
   269  // SQLiteTx implements driver.Tx.
   270  type SQLiteTx struct {
   271  	c *SQLiteConn
   272  }
   273  
   274  // SQLiteStmt implements driver.Stmt.
   275  type SQLiteStmt struct {
   276  	mu     sync.Mutex
   277  	c      *SQLiteConn
   278  	s      *C.sqlite3_stmt
   279  	t      string
   280  	closed bool
   281  	cls    bool
   282  }
   283  
   284  // SQLiteResult implements sql.Result.
   285  type SQLiteResult struct {
   286  	id      int64
   287  	changes int64
   288  }
   289  
   290  // SQLiteRows implements driver.Rows.
   291  type SQLiteRows struct {
   292  	s        *SQLiteStmt
   293  	nc       int
   294  	cols     []string
   295  	decltype []string
   296  	cls      bool
   297  	closed   bool
   298  	done     chan struct{}
   299  }
   300  
   301  type functionInfo struct {
   302  	f                 reflect.Value
   303  	argConverters     []callbackArgConverter
   304  	variadicConverter callbackArgConverter
   305  	retConverter      callbackRetConverter
   306  }
   307  
   308  func (fi *functionInfo) Call(ctx *C.sqlite3_context, argv []*C.sqlite3_value) {
   309  	args, err := callbackConvertArgs(argv, fi.argConverters, fi.variadicConverter)
   310  	if err != nil {
   311  		callbackError(ctx, err)
   312  		return
   313  	}
   314  
   315  	ret := fi.f.Call(args)
   316  
   317  	if len(ret) == 2 && ret[1].Interface() != nil {
   318  		callbackError(ctx, ret[1].Interface().(error))
   319  		return
   320  	}
   321  
   322  	err = fi.retConverter(ctx, ret[0])
   323  	if err != nil {
   324  		callbackError(ctx, err)
   325  		return
   326  	}
   327  }
   328  
   329  type aggInfo struct {
   330  	constructor reflect.Value
   331  
   332  	// Active aggregator objects for aggregations in flight. The
   333  	// aggregators are indexed by a counter stored in the aggregation
   334  	// user data space provided by sqlite.
   335  	active map[int64]reflect.Value
   336  	next   int64
   337  
   338  	stepArgConverters     []callbackArgConverter
   339  	stepVariadicConverter callbackArgConverter
   340  
   341  	doneRetConverter callbackRetConverter
   342  }
   343  
   344  func (ai *aggInfo) agg(ctx *C.sqlite3_context) (int64, reflect.Value, error) {
   345  	aggIdx := (*int64)(C.sqlite3_aggregate_context(ctx, C.int(8)))
   346  	if *aggIdx == 0 {
   347  		*aggIdx = ai.next
   348  		ret := ai.constructor.Call(nil)
   349  		if len(ret) == 2 && ret[1].Interface() != nil {
   350  			return 0, reflect.Value{}, ret[1].Interface().(error)
   351  		}
   352  		if ret[0].IsNil() {
   353  			return 0, reflect.Value{}, errors.New("aggregator constructor returned nil state")
   354  		}
   355  		ai.next++
   356  		ai.active[*aggIdx] = ret[0]
   357  	}
   358  	return *aggIdx, ai.active[*aggIdx], nil
   359  }
   360  
   361  func (ai *aggInfo) Step(ctx *C.sqlite3_context, argv []*C.sqlite3_value) {
   362  	_, agg, err := ai.agg(ctx)
   363  	if err != nil {
   364  		callbackError(ctx, err)
   365  		return
   366  	}
   367  
   368  	args, err := callbackConvertArgs(argv, ai.stepArgConverters, ai.stepVariadicConverter)
   369  	if err != nil {
   370  		callbackError(ctx, err)
   371  		return
   372  	}
   373  
   374  	ret := agg.MethodByName("Step").Call(args)
   375  	if len(ret) == 1 && ret[0].Interface() != nil {
   376  		callbackError(ctx, ret[0].Interface().(error))
   377  		return
   378  	}
   379  }
   380  
   381  func (ai *aggInfo) Done(ctx *C.sqlite3_context) {
   382  	idx, agg, err := ai.agg(ctx)
   383  	if err != nil {
   384  		callbackError(ctx, err)
   385  		return
   386  	}
   387  	defer func() { delete(ai.active, idx) }()
   388  
   389  	ret := agg.MethodByName("Done").Call(nil)
   390  	if len(ret) == 2 && ret[1].Interface() != nil {
   391  		callbackError(ctx, ret[1].Interface().(error))
   392  		return
   393  	}
   394  
   395  	err = ai.doneRetConverter(ctx, ret[0])
   396  	if err != nil {
   397  		callbackError(ctx, err)
   398  		return
   399  	}
   400  }
   401  
   402  // Commit transaction.
   403  func (tx *SQLiteTx) Commit() error {
   404  	_, err := tx.c.exec(context.Background(), "COMMIT", nil)
   405  	if err != nil && err.(Error).Code == C.SQLITE_BUSY {
   406  		// sqlite3 will leave the transaction open in this scenario.
   407  		// However, database/sql considers the transaction complete once we
   408  		// return from Commit() - we must clean up to honour its semantics.
   409  		tx.c.exec(context.Background(), "ROLLBACK", nil)
   410  	}
   411  	return err
   412  }
   413  
   414  // Rollback transaction.
   415  func (tx *SQLiteTx) Rollback() error {
   416  	_, err := tx.c.exec(context.Background(), "ROLLBACK", nil)
   417  	return err
   418  }
   419  
   420  // RegisterCollation makes a Go function available as a collation.
   421  //
   422  // cmp receives two UTF-8 strings, a and b. The result should be 0 if
   423  // a==b, -1 if a < b, and +1 if a > b.
   424  //
   425  // cmp must always return the same result given the same
   426  // inputs. Additionally, it must have the following properties for all
   427  // strings A, B and C: if A==B then B==A; if A==B and B==C then A==C;
   428  // if A<B then B>A; if A<B and B<C then A<C.
   429  //
   430  // If cmp does not obey these constraints, sqlite3's behavior is
   431  // undefined when the collation is used.
   432  func (c *SQLiteConn) RegisterCollation(name string, cmp func(string, string) int) error {
   433  	handle := newHandle(c, cmp)
   434  	cname := C.CString(name)
   435  	defer C.free(unsafe.Pointer(cname))
   436  	rv := C.sqlite3_create_collation(c.db, cname, C.SQLITE_UTF8, unsafe.Pointer(handle), (*[0]byte)(unsafe.Pointer(C.compareTrampoline)))
   437  	if rv != C.SQLITE_OK {
   438  		return c.lastError()
   439  	}
   440  	return nil
   441  }
   442  
   443  // RegisterCommitHook sets the commit hook for a connection.
   444  //
   445  // If the callback returns non-zero the transaction will become a rollback.
   446  //
   447  // If there is an existing commit hook for this connection, it will be
   448  // removed. If callback is nil the existing hook (if any) will be removed
   449  // without creating a new one.
   450  func (c *SQLiteConn) RegisterCommitHook(callback func() int) {
   451  	if callback == nil {
   452  		C.sqlite3_commit_hook(c.db, nil, nil)
   453  	} else {
   454  		C.sqlite3_commit_hook(c.db, (*[0]byte)(C.commitHookTrampoline), unsafe.Pointer(newHandle(c, callback)))
   455  	}
   456  }
   457  
   458  // RegisterRollbackHook sets the rollback hook for a connection.
   459  //
   460  // If there is an existing rollback hook for this connection, it will be
   461  // removed. If callback is nil the existing hook (if any) will be removed
   462  // without creating a new one.
   463  func (c *SQLiteConn) RegisterRollbackHook(callback func()) {
   464  	if callback == nil {
   465  		C.sqlite3_rollback_hook(c.db, nil, nil)
   466  	} else {
   467  		C.sqlite3_rollback_hook(c.db, (*[0]byte)(C.rollbackHookTrampoline), unsafe.Pointer(newHandle(c, callback)))
   468  	}
   469  }
   470  
   471  // RegisterUpdateHook sets the update hook for a connection.
   472  //
   473  // The parameters to the callback are the operation (one of the constants
   474  // SQLITE_INSERT, SQLITE_DELETE, or SQLITE_UPDATE), the database name, the
   475  // table name, and the rowid.
   476  //
   477  // If there is an existing update hook for this connection, it will be
   478  // removed. If callback is nil the existing hook (if any) will be removed
   479  // without creating a new one.
   480  func (c *SQLiteConn) RegisterUpdateHook(callback func(int, string, string, int64)) {
   481  	if callback == nil {
   482  		C.sqlite3_update_hook(c.db, nil, nil)
   483  	} else {
   484  		C.sqlite3_update_hook(c.db, (*[0]byte)(C.updateHookTrampoline), unsafe.Pointer(newHandle(c, callback)))
   485  	}
   486  }
   487  
   488  // RegisterAuthorizer sets the authorizer for connection.
   489  //
   490  // The parameters to the callback are the operation (one of the constants
   491  // SQLITE_INSERT, SQLITE_DELETE, or SQLITE_UPDATE), and 1 to 3 arguments,
   492  // depending on operation. More details see:
   493  // https://www.sqlite.org/c3ref/c_alter_table.html
   494  func (c *SQLiteConn) RegisterAuthorizer(callback func(int, string, string, string) int) {
   495  	if callback == nil {
   496  		C.sqlite3_set_authorizer(c.db, nil, nil)
   497  	} else {
   498  		C.sqlite3_set_authorizer(c.db, (*[0]byte)(C.authorizerTrampoline), unsafe.Pointer(newHandle(c, callback)))
   499  	}
   500  }
   501  
   502  // RegisterFunc makes a Go function available as a SQLite function.
   503  //
   504  // The Go function can have arguments of the following types: any
   505  // numeric type except complex, bool, []byte, string and
   506  // interface{}. interface{} arguments are given the direct translation
   507  // of the SQLite data type: int64 for INTEGER, float64 for FLOAT,
   508  // []byte for BLOB, string for TEXT.
   509  //
   510  // The function can additionally be variadic, as long as the type of
   511  // the variadic argument is one of the above.
   512  //
   513  // If pure is true. SQLite will assume that the function's return
   514  // value depends only on its inputs, and make more aggressive
   515  // optimizations in its queries.
   516  //
   517  // See _example/go_custom_funcs for a detailed example.
   518  func (c *SQLiteConn) RegisterFunc(name string, impl interface{}, pure bool) error {
   519  	var fi functionInfo
   520  	fi.f = reflect.ValueOf(impl)
   521  	t := fi.f.Type()
   522  	if t.Kind() != reflect.Func {
   523  		return errors.New("Non-function passed to RegisterFunc")
   524  	}
   525  	if t.NumOut() != 1 && t.NumOut() != 2 {
   526  		return errors.New("SQLite functions must return 1 or 2 values")
   527  	}
   528  	if t.NumOut() == 2 && !t.Out(1).Implements(reflect.TypeOf((*error)(nil)).Elem()) {
   529  		return errors.New("Second return value of SQLite function must be error")
   530  	}
   531  
   532  	numArgs := t.NumIn()
   533  	if t.IsVariadic() {
   534  		numArgs--
   535  	}
   536  
   537  	for i := 0; i < numArgs; i++ {
   538  		conv, err := callbackArg(t.In(i))
   539  		if err != nil {
   540  			return err
   541  		}
   542  		fi.argConverters = append(fi.argConverters, conv)
   543  	}
   544  
   545  	if t.IsVariadic() {
   546  		conv, err := callbackArg(t.In(numArgs).Elem())
   547  		if err != nil {
   548  			return err
   549  		}
   550  		fi.variadicConverter = conv
   551  		// Pass -1 to sqlite so that it allows any number of
   552  		// arguments. The call helper verifies that the minimum number
   553  		// of arguments is present for variadic functions.
   554  		numArgs = -1
   555  	}
   556  
   557  	conv, err := callbackRet(t.Out(0))
   558  	if err != nil {
   559  		return err
   560  	}
   561  	fi.retConverter = conv
   562  
   563  	// fi must outlast the database connection, or we'll have dangling pointers.
   564  	c.funcs = append(c.funcs, &fi)
   565  
   566  	cname := C.CString(name)
   567  	defer C.free(unsafe.Pointer(cname))
   568  	opts := C.SQLITE_UTF8
   569  	if pure {
   570  		opts |= C.SQLITE_DETERMINISTIC
   571  	}
   572  	rv := sqlite3CreateFunction(c.db, cname, C.int(numArgs), C.int(opts), newHandle(c, &fi), C.callbackTrampoline, nil, nil)
   573  	if rv != C.SQLITE_OK {
   574  		return c.lastError()
   575  	}
   576  	return nil
   577  }
   578  
   579  func 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 {
   580  	return C._sqlite3_create_function(db, zFunctionName, nArg, eTextRep, C.uintptr_t(pApp), (*[0]byte)(xFunc), (*[0]byte)(xStep), (*[0]byte)(xFinal))
   581  }
   582  
   583  // RegisterAggregator makes a Go type available as a SQLite aggregation function.
   584  //
   585  // Because aggregation is incremental, it's implemented in Go with a
   586  // type that has 2 methods: func Step(values) accumulates one row of
   587  // data into the accumulator, and func Done() ret finalizes and
   588  // returns the aggregate value. "values" and "ret" may be any type
   589  // supported by RegisterFunc.
   590  //
   591  // RegisterAggregator takes as implementation a constructor function
   592  // that constructs an instance of the aggregator type each time an
   593  // aggregation begins. The constructor must return a pointer to a
   594  // type, or an interface that implements Step() and Done().
   595  //
   596  // The constructor function and the Step/Done methods may optionally
   597  // return an error in addition to their other return values.
   598  //
   599  // See _example/go_custom_funcs for a detailed example.
   600  func (c *SQLiteConn) RegisterAggregator(name string, impl interface{}, pure bool) error {
   601  	var ai aggInfo
   602  	ai.constructor = reflect.ValueOf(impl)
   603  	t := ai.constructor.Type()
   604  	if t.Kind() != reflect.Func {
   605  		return errors.New("non-function passed to RegisterAggregator")
   606  	}
   607  	if t.NumOut() != 1 && t.NumOut() != 2 {
   608  		return errors.New("SQLite aggregator constructors must return 1 or 2 values")
   609  	}
   610  	if t.NumOut() == 2 && !t.Out(1).Implements(reflect.TypeOf((*error)(nil)).Elem()) {
   611  		return errors.New("Second return value of SQLite function must be error")
   612  	}
   613  	if t.NumIn() != 0 {
   614  		return errors.New("SQLite aggregator constructors must not have arguments")
   615  	}
   616  
   617  	agg := t.Out(0)
   618  	switch agg.Kind() {
   619  	case reflect.Ptr, reflect.Interface:
   620  	default:
   621  		return errors.New("SQlite aggregator constructor must return a pointer object")
   622  	}
   623  	stepFn, found := agg.MethodByName("Step")
   624  	if !found {
   625  		return errors.New("SQlite aggregator doesn't have a Step() function")
   626  	}
   627  	step := stepFn.Type
   628  	if step.NumOut() != 0 && step.NumOut() != 1 {
   629  		return errors.New("SQlite aggregator Step() function must return 0 or 1 values")
   630  	}
   631  	if step.NumOut() == 1 && !step.Out(0).Implements(reflect.TypeOf((*error)(nil)).Elem()) {
   632  		return errors.New("type of SQlite aggregator Step() return value must be error")
   633  	}
   634  
   635  	stepNArgs := step.NumIn()
   636  	start := 0
   637  	if agg.Kind() == reflect.Ptr {
   638  		// Skip over the method receiver
   639  		stepNArgs--
   640  		start++
   641  	}
   642  	if step.IsVariadic() {
   643  		stepNArgs--
   644  	}
   645  	for i := start; i < start+stepNArgs; i++ {
   646  		conv, err := callbackArg(step.In(i))
   647  		if err != nil {
   648  			return err
   649  		}
   650  		ai.stepArgConverters = append(ai.stepArgConverters, conv)
   651  	}
   652  	if step.IsVariadic() {
   653  		conv, err := callbackArg(t.In(start + stepNArgs).Elem())
   654  		if err != nil {
   655  			return err
   656  		}
   657  		ai.stepVariadicConverter = conv
   658  		// Pass -1 to sqlite so that it allows any number of
   659  		// arguments. The call helper verifies that the minimum number
   660  		// of arguments is present for variadic functions.
   661  		stepNArgs = -1
   662  	}
   663  
   664  	doneFn, found := agg.MethodByName("Done")
   665  	if !found {
   666  		return errors.New("SQlite aggregator doesn't have a Done() function")
   667  	}
   668  	done := doneFn.Type
   669  	doneNArgs := done.NumIn()
   670  	if agg.Kind() == reflect.Ptr {
   671  		// Skip over the method receiver
   672  		doneNArgs--
   673  	}
   674  	if doneNArgs != 0 {
   675  		return errors.New("SQlite aggregator Done() function must have no arguments")
   676  	}
   677  	if done.NumOut() != 1 && done.NumOut() != 2 {
   678  		return errors.New("SQLite aggregator Done() function must return 1 or 2 values")
   679  	}
   680  	if done.NumOut() == 2 && !done.Out(1).Implements(reflect.TypeOf((*error)(nil)).Elem()) {
   681  		return errors.New("second return value of SQLite aggregator Done() function must be error")
   682  	}
   683  
   684  	conv, err := callbackRet(done.Out(0))
   685  	if err != nil {
   686  		return err
   687  	}
   688  	ai.doneRetConverter = conv
   689  	ai.active = make(map[int64]reflect.Value)
   690  	ai.next = 1
   691  
   692  	// ai must outlast the database connection, or we'll have dangling pointers.
   693  	c.aggregators = append(c.aggregators, &ai)
   694  
   695  	cname := C.CString(name)
   696  	defer C.free(unsafe.Pointer(cname))
   697  	opts := C.SQLITE_UTF8
   698  	if pure {
   699  		opts |= C.SQLITE_DETERMINISTIC
   700  	}
   701  	rv := sqlite3CreateFunction(c.db, cname, C.int(stepNArgs), C.int(opts), newHandle(c, &ai), nil, C.stepTrampoline, C.doneTrampoline)
   702  	if rv != C.SQLITE_OK {
   703  		return c.lastError()
   704  	}
   705  	return nil
   706  }
   707  
   708  // AutoCommit return which currently auto commit or not.
   709  func (c *SQLiteConn) AutoCommit() bool {
   710  	return int(C.sqlite3_get_autocommit(c.db)) != 0
   711  }
   712  
   713  func (c *SQLiteConn) lastError() error {
   714  	return lastError(c.db)
   715  }
   716  
   717  func lastError(db *C.sqlite3) error {
   718  	rv := C.sqlite3_errcode(db)
   719  	if rv == C.SQLITE_OK {
   720  		return nil
   721  	}
   722  	return Error{
   723  		Code:         ErrNo(rv),
   724  		ExtendedCode: ErrNoExtended(C.sqlite3_extended_errcode(db)),
   725  		err:          C.GoString(C.sqlite3_errmsg(db)),
   726  	}
   727  }
   728  
   729  // Exec implements Execer.
   730  func (c *SQLiteConn) Exec(query string, args []driver.Value) (driver.Result, error) {
   731  	list := make([]namedValue, len(args))
   732  	for i, v := range args {
   733  		list[i] = namedValue{
   734  			Ordinal: i + 1,
   735  			Value:   v,
   736  		}
   737  	}
   738  	return c.exec(context.Background(), query, list)
   739  }
   740  
   741  func (c *SQLiteConn) exec(ctx context.Context, query string, args []namedValue) (driver.Result, error) {
   742  	start := 0
   743  	for {
   744  		s, err := c.prepare(ctx, query)
   745  		if err != nil {
   746  			return nil, err
   747  		}
   748  		var res driver.Result
   749  		if s.(*SQLiteStmt).s != nil {
   750  			na := s.NumInput()
   751  			if len(args) < na {
   752  				s.Close()
   753  				return nil, fmt.Errorf("not enough args to execute query: want %d got %d", na, len(args))
   754  			}
   755  			for i := 0; i < na; i++ {
   756  				args[i].Ordinal -= start
   757  			}
   758  			res, err = s.(*SQLiteStmt).exec(ctx, args[:na])
   759  			if err != nil && err != driver.ErrSkip {
   760  				s.Close()
   761  				return nil, err
   762  			}
   763  			args = args[na:]
   764  			start += na
   765  		}
   766  		tail := s.(*SQLiteStmt).t
   767  		s.Close()
   768  		if tail == "" {
   769  			return res, nil
   770  		}
   771  		query = tail
   772  	}
   773  }
   774  
   775  type namedValue struct {
   776  	Name    string
   777  	Ordinal int
   778  	Value   driver.Value
   779  }
   780  
   781  // Query implements Queryer.
   782  func (c *SQLiteConn) Query(query string, args []driver.Value) (driver.Rows, error) {
   783  	list := make([]namedValue, len(args))
   784  	for i, v := range args {
   785  		list[i] = namedValue{
   786  			Ordinal: i + 1,
   787  			Value:   v,
   788  		}
   789  	}
   790  	return c.query(context.Background(), query, list)
   791  }
   792  
   793  func (c *SQLiteConn) query(ctx context.Context, query string, args []namedValue) (driver.Rows, error) {
   794  	start := 0
   795  	for {
   796  		s, err := c.prepare(ctx, query)
   797  		if err != nil {
   798  			return nil, err
   799  		}
   800  		s.(*SQLiteStmt).cls = true
   801  		na := s.NumInput()
   802  		if len(args) < na {
   803  			return nil, fmt.Errorf("not enough args to execute query: want %d got %d", na, len(args))
   804  		}
   805  		for i := 0; i < na; i++ {
   806  			args[i].Ordinal -= start
   807  		}
   808  		rows, err := s.(*SQLiteStmt).query(ctx, args[:na])
   809  		if err != nil && err != driver.ErrSkip {
   810  			s.Close()
   811  			return rows, err
   812  		}
   813  		args = args[na:]
   814  		start += na
   815  		tail := s.(*SQLiteStmt).t
   816  		if tail == "" {
   817  			return rows, nil
   818  		}
   819  		rows.Close()
   820  		s.Close()
   821  		query = tail
   822  	}
   823  }
   824  
   825  // Begin transaction.
   826  func (c *SQLiteConn) Begin() (driver.Tx, error) {
   827  	return c.begin(context.Background())
   828  }
   829  
   830  func (c *SQLiteConn) begin(ctx context.Context) (driver.Tx, error) {
   831  	if _, err := c.exec(ctx, c.txlock, nil); err != nil {
   832  		return nil, err
   833  	}
   834  	return &SQLiteTx{c}, nil
   835  }
   836  
   837  func errorString(err Error) string {
   838  	return C.GoString(C.sqlite3_errstr(C.int(err.Code)))
   839  }
   840  
   841  // Open database and return a new connection.
   842  //
   843  // A pragma can take either zero or one argument.
   844  // The argument is may be either in parentheses or it may be separated from
   845  // the pragma name by an equal sign. The two syntaxes yield identical results.
   846  // In many pragmas, the argument is a boolean. The boolean can be one of:
   847  //    1 yes true on
   848  //    0 no false off
   849  //
   850  // You can specify a DSN string using a URI as the filename.
   851  //   test.db
   852  //   file:test.db?cache=shared&mode=memory
   853  //   :memory:
   854  //   file::memory:
   855  //
   856  //   mode
   857  //     Access mode of the database.
   858  //     https://www.sqlite.org/c3ref/open.html
   859  //     Values:
   860  //      - ro
   861  //      - rw
   862  //      - rwc
   863  //      - memory
   864  //
   865  //   shared
   866  //     SQLite Shared-Cache Mode
   867  //     https://www.sqlite.org/sharedcache.html
   868  //     Values:
   869  //       - shared
   870  //       - private
   871  //
   872  //   immutable=Boolean
   873  //     The immutable parameter is a boolean query parameter that indicates
   874  //     that the database file is stored on read-only media. When immutable is set,
   875  //     SQLite assumes that the database file cannot be changed,
   876  //     even by a process with higher privilege,
   877  //     and so the database is opened read-only and all locking and change detection is disabled.
   878  //     Caution: Setting the immutable property on a database file that
   879  //     does in fact change can result in incorrect query results and/or SQLITE_CORRUPT errors.
   880  //
   881  // go-sqlite3 adds the following query parameters to those used by SQLite:
   882  //   _loc=XXX
   883  //     Specify location of time format. It's possible to specify "auto".
   884  //
   885  //   _mutex=XXX
   886  //     Specify mutex mode. XXX can be "no", "full".
   887  //
   888  //   _txlock=XXX
   889  //     Specify locking behavior for transactions.  XXX can be "immediate",
   890  //     "deferred", "exclusive".
   891  //
   892  //   _auto_vacuum=X | _vacuum=X
   893  //     0 | none - Auto Vacuum disabled
   894  //     1 | full - Auto Vacuum FULL
   895  //     2 | incremental - Auto Vacuum Incremental
   896  //
   897  //   _busy_timeout=XXX"| _timeout=XXX
   898  //     Specify value for sqlite3_busy_timeout.
   899  //
   900  //   _case_sensitive_like=Boolean | _cslike=Boolean
   901  //     https://www.sqlite.org/pragma.html#pragma_case_sensitive_like
   902  //     Default or disabled the LIKE operation is case-insensitive.
   903  //     When enabling this options behaviour of LIKE will become case-sensitive.
   904  //
   905  //   _defer_foreign_keys=Boolean | _defer_fk=Boolean
   906  //     Defer Foreign Keys until outermost transaction is committed.
   907  //
   908  //   _foreign_keys=Boolean | _fk=Boolean
   909  //     Enable or disable enforcement of foreign keys.
   910  //
   911  //   _ignore_check_constraints=Boolean
   912  //     This pragma enables or disables the enforcement of CHECK constraints.
   913  //     The default setting is off, meaning that CHECK constraints are enforced by default.
   914  //
   915  //   _journal_mode=MODE | _journal=MODE
   916  //     Set journal mode for the databases associated with the current connection.
   917  //     https://www.sqlite.org/pragma.html#pragma_journal_mode
   918  //
   919  //   _locking_mode=X | _locking=X
   920  //     Sets the database connection locking-mode.
   921  //     The locking-mode is either NORMAL or EXCLUSIVE.
   922  //     https://www.sqlite.org/pragma.html#pragma_locking_mode
   923  //
   924  //   _query_only=Boolean
   925  //     The query_only pragma prevents all changes to database files when enabled.
   926  //
   927  //   _recursive_triggers=Boolean | _rt=Boolean
   928  //     Enable or disable recursive triggers.
   929  //
   930  //   _secure_delete=Boolean|FAST
   931  //     When secure_delete is on, SQLite overwrites deleted content with zeros.
   932  //     https://www.sqlite.org/pragma.html#pragma_secure_delete
   933  //
   934  //   _synchronous=X | _sync=X
   935  //     Change the setting of the "synchronous" flag.
   936  //     https://www.sqlite.org/pragma.html#pragma_synchronous
   937  //
   938  //   _writable_schema=Boolean
   939  //     When this pragma is on, the SQLITE_MASTER tables in which database
   940  //     can be changed using ordinary UPDATE, INSERT, and DELETE statements.
   941  //     Warning: misuse of this pragma can easily result in a corrupt database file.
   942  //
   943  //
   944  func (d *SQLiteDriver) Open(dsn string) (driver.Conn, error) {
   945  	if C.sqlite3_threadsafe() == 0 {
   946  		return nil, errors.New("sqlite library was not compiled for thread-safe operation")
   947  	}
   948  
   949  	// Options
   950  	var loc *time.Location
   951  	txlock := "BEGIN"
   952  
   953  	// PRAGMA's
   954  	queryOnly := -1
   955  
   956  	pos := strings.IndexRune(dsn, '?')
   957  	if pos >= 1 {
   958  		params, err := url.ParseQuery(dsn[pos+1:])
   959  		if err != nil {
   960  			return nil, err
   961  		}
   962  
   963  		// Query Only (_query_only)
   964  		//
   965  		// https://www.sqlite.org/pragma.html#pragma_query_only
   966  		//
   967  		if val := params.Get("_query_only"); val != "" {
   968  			switch strings.ToLower(val) {
   969  			case "0", "no", "false", "off":
   970  				queryOnly = 0
   971  			case "1", "yes", "true", "on":
   972  				queryOnly = 1
   973  			default:
   974  				return nil, fmt.Errorf("Invalid _query_only: %v, expecting boolean value of '0 1 false true no yes off on'", val)
   975  			}
   976  		}
   977  
   978  		if !strings.HasPrefix(dsn, "file:") {
   979  			dsn = dsn[:pos]
   980  		}
   981  	}
   982  
   983  	var db *C.sqlite3
   984  	name := C.CString(dsn)
   985  	defer C.free(unsafe.Pointer(name))
   986  	rv := C._sqlite3_open_v2(name, &db, C.SQLITE_OPEN_READWRITE|C.SQLITE_OPEN_CREATE, nil)
   987  	if rv != 0 {
   988  		return nil, Error{Code: ErrNo(rv)}
   989  	}
   990  	if db == nil {
   991  		return nil, errors.New("sqlite succeeded without returning a database")
   992  	}
   993  
   994  	exec := func(s string) error {
   995  		cs := C.CString(s)
   996  		rv := C.sqlite3_exec(db, cs, nil, nil, nil)
   997  		C.free(unsafe.Pointer(cs))
   998  		if rv != C.SQLITE_OK {
   999  			return lastError(db)
  1000  		}
  1001  		return nil
  1002  	}
  1003  
  1004  	rv = C._sqlite3_disable_loadextfunc(db)
  1005  	if rv != C.SQLITE_OK {
  1006  		C.sqlite3_close_v2(db)
  1007  		return nil, Error{Code: ErrNo(rv)}
  1008  	}
  1009  
  1010  	// USER AUTHENTICATION
  1011  	//
  1012  	// User Authentication is always performed even when
  1013  	// sqlite_userauth is not compiled in, because without user authentication
  1014  	// the authentication is a no-op.
  1015  	//
  1016  	// Workflow
  1017  	//	- Authenticate
  1018  	//		ON::SUCCESS		=> Continue
  1019  	//		ON::SQLITE_AUTH => Return error and exit Open(...)
  1020  	//
  1021  	//  - Activate User Authentication
  1022  	//		Check if the user wants to activate User Authentication.
  1023  	//		If so then first create a temporary AuthConn to the database
  1024  	//		This is possible because we are already succesfully authenticated.
  1025  	//
  1026  	//	- Check if `sqlite_user`` table exists
  1027  	//		YES				=> Add the provided user from DSN as Admin User and
  1028  	//						   activate user authentication.
  1029  	//		NO				=> Continue
  1030  	//
  1031  
  1032  	// Create connection to SQLite
  1033  	conn := &SQLiteConn{db: db, loc: loc, txlock: txlock}
  1034  
  1035  	// Query Only
  1036  	if queryOnly > -1 {
  1037  		if err := exec(fmt.Sprintf("PRAGMA query_only = %d;", queryOnly)); err != nil {
  1038  			C.sqlite3_close_v2(db)
  1039  			return nil, err
  1040  		}
  1041  	}
  1042  
  1043  	if d.ConnectHook != nil {
  1044  		if err := d.ConnectHook(conn); err != nil {
  1045  			conn.Close()
  1046  			return nil, err
  1047  		}
  1048  	}
  1049  	runtime.SetFinalizer(conn, (*SQLiteConn).Close)
  1050  	return conn, nil
  1051  }
  1052  
  1053  // Close the connection.
  1054  func (c *SQLiteConn) Close() error {
  1055  	rv := C.sqlite3_close_v2(c.db)
  1056  	if rv != C.SQLITE_OK {
  1057  		return c.lastError()
  1058  	}
  1059  	deleteHandles(c)
  1060  	c.mu.Lock()
  1061  	c.db = nil
  1062  	c.mu.Unlock()
  1063  	runtime.SetFinalizer(c, nil)
  1064  	return nil
  1065  }
  1066  
  1067  func (c *SQLiteConn) dbConnOpen() bool {
  1068  	if c == nil {
  1069  		return false
  1070  	}
  1071  	c.mu.Lock()
  1072  	defer c.mu.Unlock()
  1073  	return c.db != nil
  1074  }
  1075  
  1076  // Prepare the query string. Return a new statement.
  1077  func (c *SQLiteConn) Prepare(query string) (driver.Stmt, error) {
  1078  	return c.prepare(context.Background(), query)
  1079  }
  1080  
  1081  func (c *SQLiteConn) prepare(ctx context.Context, query string) (driver.Stmt, error) {
  1082  	pquery := C.CString(query)
  1083  	defer C.free(unsafe.Pointer(pquery))
  1084  	var s *C.sqlite3_stmt
  1085  	var tail *C.char
  1086  	rv := C.sqlite3_prepare_v2(c.db, pquery, -1, &s, &tail)
  1087  	if rv != C.SQLITE_OK {
  1088  		return nil, c.lastError()
  1089  	}
  1090  	var t string
  1091  	if tail != nil && *tail != '\000' {
  1092  		t = strings.TrimSpace(C.GoString(tail))
  1093  	}
  1094  	ss := &SQLiteStmt{c: c, s: s, t: t}
  1095  	runtime.SetFinalizer(ss, (*SQLiteStmt).Close)
  1096  	return ss, nil
  1097  }
  1098  
  1099  // Run-Time Limit Categories.
  1100  // See: http://www.sqlite.org/c3ref/c_limit_attached.html
  1101  const (
  1102  	SQLITE_LIMIT_LENGTH              = C.SQLITE_LIMIT_LENGTH
  1103  	SQLITE_LIMIT_SQL_LENGTH          = C.SQLITE_LIMIT_SQL_LENGTH
  1104  	SQLITE_LIMIT_COLUMN              = C.SQLITE_LIMIT_COLUMN
  1105  	SQLITE_LIMIT_EXPR_DEPTH          = C.SQLITE_LIMIT_EXPR_DEPTH
  1106  	SQLITE_LIMIT_COMPOUND_SELECT     = C.SQLITE_LIMIT_COMPOUND_SELECT
  1107  	SQLITE_LIMIT_VDBE_OP             = C.SQLITE_LIMIT_VDBE_OP
  1108  	SQLITE_LIMIT_FUNCTION_ARG        = C.SQLITE_LIMIT_FUNCTION_ARG
  1109  	SQLITE_LIMIT_ATTACHED            = C.SQLITE_LIMIT_ATTACHED
  1110  	SQLITE_LIMIT_LIKE_PATTERN_LENGTH = C.SQLITE_LIMIT_LIKE_PATTERN_LENGTH
  1111  	SQLITE_LIMIT_VARIABLE_NUMBER     = C.SQLITE_LIMIT_VARIABLE_NUMBER
  1112  	SQLITE_LIMIT_TRIGGER_DEPTH       = C.SQLITE_LIMIT_TRIGGER_DEPTH
  1113  	SQLITE_LIMIT_WORKER_THREADS      = C.SQLITE_LIMIT_WORKER_THREADS
  1114  )
  1115  
  1116  // GetFilename returns the absolute path to the file containing
  1117  // the requested schema. When passed an empty string, it will
  1118  // instead use the database's default schema: "main".
  1119  // See: sqlite3_db_filename, https://www.sqlite.org/c3ref/db_filename.html
  1120  func (c *SQLiteConn) GetFilename(schemaName string) string {
  1121  	if schemaName == "" {
  1122  		schemaName = "main"
  1123  	}
  1124  	return C.GoString(C.sqlite3_db_filename(c.db, C.CString(schemaName)))
  1125  }
  1126  
  1127  // GetLimit returns the current value of a run-time limit.
  1128  // See: sqlite3_limit, http://www.sqlite.org/c3ref/limit.html
  1129  func (c *SQLiteConn) GetLimit(id int) int {
  1130  	return int(C._sqlite3_limit(c.db, C.int(id), -1))
  1131  }
  1132  
  1133  // SetLimit changes the value of a run-time limits.
  1134  // Then this method returns the prior value of the limit.
  1135  // See: sqlite3_limit, http://www.sqlite.org/c3ref/limit.html
  1136  func (c *SQLiteConn) SetLimit(id int, newVal int) int {
  1137  	return int(C._sqlite3_limit(c.db, C.int(id), C.int(newVal)))
  1138  }
  1139  
  1140  func (c *SQLiteConn) DBCacheFlush() error {
  1141  	rv := C.sqlite3_db_cacheflush(c.db)
  1142  	if rv != C.SQLITE_OK {
  1143  		return c.lastError()
  1144  	}
  1145  	return nil
  1146  }
  1147  
  1148  // Close the statement.
  1149  func (s *SQLiteStmt) Close() error {
  1150  	s.mu.Lock()
  1151  	defer s.mu.Unlock()
  1152  	if s.closed {
  1153  		return nil
  1154  	}
  1155  	s.closed = true
  1156  	if !s.c.dbConnOpen() {
  1157  		return errors.New("sqlite statement with already closed database connection")
  1158  	}
  1159  	rv := C.sqlite3_finalize(s.s)
  1160  	s.s = nil
  1161  	if rv != C.SQLITE_OK {
  1162  		return s.c.lastError()
  1163  	}
  1164  	runtime.SetFinalizer(s, nil)
  1165  	return nil
  1166  }
  1167  
  1168  // NumInput return a number of parameters.
  1169  func (s *SQLiteStmt) NumInput() int {
  1170  	return int(C.sqlite3_bind_parameter_count(s.s))
  1171  }
  1172  
  1173  type bindArg struct {
  1174  	n int
  1175  	v driver.Value
  1176  }
  1177  
  1178  var placeHolder = []byte{0}
  1179  
  1180  func (s *SQLiteStmt) bind(args []namedValue) error {
  1181  	rv := C.sqlite3_reset(s.s)
  1182  	if rv != C.SQLITE_ROW && rv != C.SQLITE_OK && rv != C.SQLITE_DONE {
  1183  		return s.c.lastError()
  1184  	}
  1185  
  1186  	for i, v := range args {
  1187  		if v.Name != "" {
  1188  			cname := C.CString(":" + v.Name)
  1189  			args[i].Ordinal = int(C.sqlite3_bind_parameter_index(s.s, cname))
  1190  			C.free(unsafe.Pointer(cname))
  1191  		}
  1192  	}
  1193  
  1194  	for _, arg := range args {
  1195  		n := C.int(arg.Ordinal)
  1196  		switch v := arg.Value.(type) {
  1197  		case nil:
  1198  			rv = C.sqlite3_bind_null(s.s, n)
  1199  		case string:
  1200  			if len(v) == 0 {
  1201  				rv = C._sqlite3_bind_text(s.s, n, (*C.char)(unsafe.Pointer(&placeHolder[0])), C.int(0))
  1202  			} else {
  1203  				b := []byte(v)
  1204  				rv = C._sqlite3_bind_text(s.s, n, (*C.char)(unsafe.Pointer(&b[0])), C.int(len(b)))
  1205  			}
  1206  		case int64:
  1207  			rv = C.sqlite3_bind_int64(s.s, n, C.sqlite3_int64(v))
  1208  		case bool:
  1209  			if v {
  1210  				rv = C.sqlite3_bind_int(s.s, n, 1)
  1211  			} else {
  1212  				rv = C.sqlite3_bind_int(s.s, n, 0)
  1213  			}
  1214  		case float64:
  1215  			rv = C.sqlite3_bind_double(s.s, n, C.double(v))
  1216  		case []byte:
  1217  			if v == nil {
  1218  				rv = C.sqlite3_bind_null(s.s, n)
  1219  			} else {
  1220  				ln := len(v)
  1221  				if ln == 0 {
  1222  					v = placeHolder
  1223  				}
  1224  				rv = C._sqlite3_bind_blob(s.s, n, unsafe.Pointer(&v[0]), C.int(ln))
  1225  			}
  1226  		case time.Time:
  1227  			b := []byte(v.Format(SQLiteTimestampFormats[0]))
  1228  			rv = C._sqlite3_bind_text(s.s, n, (*C.char)(unsafe.Pointer(&b[0])), C.int(len(b)))
  1229  		}
  1230  		if rv != C.SQLITE_OK {
  1231  			return s.c.lastError()
  1232  		}
  1233  	}
  1234  	return nil
  1235  }
  1236  
  1237  // Query the statement with arguments. Return records.
  1238  func (s *SQLiteStmt) Query(args []driver.Value) (driver.Rows, error) {
  1239  	list := make([]namedValue, len(args))
  1240  	for i, v := range args {
  1241  		list[i] = namedValue{
  1242  			Ordinal: i + 1,
  1243  			Value:   v,
  1244  		}
  1245  	}
  1246  	return s.query(context.Background(), list)
  1247  }
  1248  
  1249  func (s *SQLiteStmt) query(ctx context.Context, args []namedValue) (driver.Rows, error) {
  1250  	if err := s.bind(args); err != nil {
  1251  		return nil, err
  1252  	}
  1253  
  1254  	rows := &SQLiteRows{
  1255  		s:        s,
  1256  		nc:       int(C.sqlite3_column_count(s.s)),
  1257  		cols:     nil,
  1258  		decltype: nil,
  1259  		cls:      s.cls,
  1260  		closed:   false,
  1261  		done:     make(chan struct{}),
  1262  	}
  1263  
  1264  	if ctxdone := ctx.Done(); ctxdone != nil {
  1265  		go func(db *C.sqlite3) {
  1266  			select {
  1267  			case <-ctxdone:
  1268  				select {
  1269  				case <-rows.done:
  1270  				default:
  1271  					C.sqlite3_interrupt(db)
  1272  					rows.Close()
  1273  				}
  1274  			case <-rows.done:
  1275  			}
  1276  		}(s.c.db)
  1277  	}
  1278  
  1279  	return rows, nil
  1280  }
  1281  
  1282  // LastInsertId teturn last inserted ID.
  1283  func (r *SQLiteResult) LastInsertId() (int64, error) {
  1284  	return r.id, nil
  1285  }
  1286  
  1287  // RowsAffected return how many rows affected.
  1288  func (r *SQLiteResult) RowsAffected() (int64, error) {
  1289  	return r.changes, nil
  1290  }
  1291  
  1292  // Exec execute the statement with arguments. Return result object.
  1293  func (s *SQLiteStmt) Exec(args []driver.Value) (driver.Result, error) {
  1294  	list := make([]namedValue, len(args))
  1295  	for i, v := range args {
  1296  		list[i] = namedValue{
  1297  			Ordinal: i + 1,
  1298  			Value:   v,
  1299  		}
  1300  	}
  1301  	return s.exec(context.Background(), list)
  1302  }
  1303  
  1304  func (s *SQLiteStmt) exec(ctx context.Context, args []namedValue) (driver.Result, error) {
  1305  	if err := s.bind(args); err != nil {
  1306  		C.sqlite3_reset(s.s)
  1307  		C.sqlite3_clear_bindings(s.s)
  1308  		return nil, err
  1309  	}
  1310  
  1311  	if ctxdone := ctx.Done(); ctxdone != nil {
  1312  		done := make(chan struct{})
  1313  		defer close(done)
  1314  		go func(db *C.sqlite3) {
  1315  			select {
  1316  			case <-done:
  1317  			case <-ctxdone:
  1318  				select {
  1319  				case <-done:
  1320  				default:
  1321  					C.sqlite3_interrupt(db)
  1322  				}
  1323  			}
  1324  		}(s.c.db)
  1325  	}
  1326  
  1327  	var rowid, changes C.longlong
  1328  	rv := C._sqlite3_step(s.s, &rowid, &changes)
  1329  	if rv != C.SQLITE_ROW && rv != C.SQLITE_OK && rv != C.SQLITE_DONE {
  1330  		err := s.c.lastError()
  1331  		C.sqlite3_reset(s.s)
  1332  		C.sqlite3_clear_bindings(s.s)
  1333  		return nil, err
  1334  	}
  1335  
  1336  	return &SQLiteResult{id: int64(rowid), changes: int64(changes)}, nil
  1337  }
  1338  
  1339  // Close the rows.
  1340  func (rc *SQLiteRows) Close() error {
  1341  	rc.s.mu.Lock()
  1342  	if rc.s.closed || rc.closed {
  1343  		rc.s.mu.Unlock()
  1344  		return nil
  1345  	}
  1346  	rc.closed = true
  1347  	if rc.done != nil {
  1348  		close(rc.done)
  1349  	}
  1350  	if rc.cls {
  1351  		rc.s.mu.Unlock()
  1352  		return rc.s.Close()
  1353  	}
  1354  	rv := C.sqlite3_reset(rc.s.s)
  1355  	if rv != C.SQLITE_OK {
  1356  		rc.s.mu.Unlock()
  1357  		return rc.s.c.lastError()
  1358  	}
  1359  	rc.s.mu.Unlock()
  1360  	return nil
  1361  }
  1362  
  1363  // Columns return column names.
  1364  func (rc *SQLiteRows) Columns() []string {
  1365  	rc.s.mu.Lock()
  1366  	defer rc.s.mu.Unlock()
  1367  	if rc.s.s != nil && rc.nc != len(rc.cols) {
  1368  		rc.cols = make([]string, rc.nc)
  1369  		for i := 0; i < rc.nc; i++ {
  1370  			rc.cols[i] = C.GoString(C.sqlite3_column_name(rc.s.s, C.int(i)))
  1371  		}
  1372  	}
  1373  	return rc.cols
  1374  }
  1375  
  1376  func (rc *SQLiteRows) declTypes() []string {
  1377  	if rc.s.s != nil && rc.decltype == nil {
  1378  		rc.decltype = make([]string, rc.nc)
  1379  		for i := 0; i < rc.nc; i++ {
  1380  			rc.decltype[i] = strings.ToLower(C.GoString(C.sqlite3_column_decltype(rc.s.s, C.int(i))))
  1381  		}
  1382  	}
  1383  	return rc.decltype
  1384  }
  1385  
  1386  // DeclTypes return column types.
  1387  func (rc *SQLiteRows) DeclTypes() []string {
  1388  	rc.s.mu.Lock()
  1389  	defer rc.s.mu.Unlock()
  1390  	return rc.declTypes()
  1391  }
  1392  
  1393  // Next move cursor to next.
  1394  func (rc *SQLiteRows) Next(dest []driver.Value) error {
  1395  	rc.s.mu.Lock()
  1396  	defer rc.s.mu.Unlock()
  1397  	if rc.s.closed {
  1398  		return io.EOF
  1399  	}
  1400  	rv := C.sqlite3_step(rc.s.s)
  1401  	if rv == C.SQLITE_DONE {
  1402  		return io.EOF
  1403  	}
  1404  	if rv != C.SQLITE_ROW {
  1405  		rv = C.sqlite3_reset(rc.s.s)
  1406  		if rv != C.SQLITE_OK {
  1407  			return rc.s.c.lastError()
  1408  		}
  1409  		return nil
  1410  	}
  1411  
  1412  	rc.declTypes()
  1413  
  1414  	for i := range dest {
  1415  		switch C.sqlite3_column_type(rc.s.s, C.int(i)) {
  1416  		case C.SQLITE_INTEGER:
  1417  			val := int64(C.sqlite3_column_int64(rc.s.s, C.int(i)))
  1418  			switch rc.decltype[i] {
  1419  			case columnTimestamp, columnDatetime, columnDate:
  1420  				var t time.Time
  1421  				// Assume a millisecond unix timestamp if it's 13 digits -- too
  1422  				// large to be a reasonable timestamp in seconds.
  1423  				if val > 1e12 || val < -1e12 {
  1424  					val *= int64(time.Millisecond) // convert ms to nsec
  1425  					t = time.Unix(0, val)
  1426  				} else {
  1427  					t = time.Unix(val, 0)
  1428  				}
  1429  				t = t.UTC()
  1430  				if rc.s.c.loc != nil {
  1431  					t = t.In(rc.s.c.loc)
  1432  				}
  1433  				dest[i] = t
  1434  			case "boolean":
  1435  				dest[i] = val > 0
  1436  			default:
  1437  				dest[i] = val
  1438  			}
  1439  		case C.SQLITE_FLOAT:
  1440  			dest[i] = float64(C.sqlite3_column_double(rc.s.s, C.int(i)))
  1441  		case C.SQLITE_BLOB:
  1442  			p := C.sqlite3_column_blob(rc.s.s, C.int(i))
  1443  			if p == nil {
  1444  				dest[i] = nil
  1445  				continue
  1446  			}
  1447  			n := int(C.sqlite3_column_bytes(rc.s.s, C.int(i)))
  1448  			switch dest[i].(type) {
  1449  			default:
  1450  				slice := make([]byte, n)
  1451  				copy(slice[:], (*[1 << 30]byte)(p)[0:n])
  1452  				dest[i] = slice
  1453  			}
  1454  		case C.SQLITE_NULL:
  1455  			dest[i] = nil
  1456  		case C.SQLITE_TEXT:
  1457  			var err error
  1458  			var timeVal time.Time
  1459  
  1460  			n := int(C.sqlite3_column_bytes(rc.s.s, C.int(i)))
  1461  			s := C.GoStringN((*C.char)(unsafe.Pointer(C.sqlite3_column_text(rc.s.s, C.int(i)))), C.int(n))
  1462  
  1463  			switch rc.decltype[i] {
  1464  			case columnTimestamp, columnDatetime, columnDate:
  1465  				var t time.Time
  1466  				s = strings.TrimSuffix(s, "Z")
  1467  				for _, format := range SQLiteTimestampFormats {
  1468  					if timeVal, err = time.ParseInLocation(format, s, time.UTC); err == nil {
  1469  						t = timeVal
  1470  						break
  1471  					}
  1472  				}
  1473  				if err != nil {
  1474  					// The column is a time value, so return the zero time on parse failure.
  1475  					t = time.Time{}
  1476  				}
  1477  				if rc.s.c.loc != nil {
  1478  					t = t.In(rc.s.c.loc)
  1479  				}
  1480  				dest[i] = t
  1481  			default:
  1482  				dest[i] = []byte(s)
  1483  			}
  1484  
  1485  		}
  1486  	}
  1487  	return nil
  1488  }