Fork github.com/mattn/go-sqlite3 with adjustment for go1.16.2
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2262 lines
65 KiB

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