本站源代码
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

2071 linhas
58KB

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