sqlite3.go 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374
  1. // +build cgo
  2. // Copyright (C) 2014 Yasuhiro Matsumoto <mattn.jp@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. package sqlite3
  7. /*
  8. #cgo CFLAGS: -std=gnu99
  9. #cgo CFLAGS: -DSQLITE_ENABLE_RTREE -DSQLITE_THREADSAFE=1 -DHAVE_USLEEP=1
  10. #cgo linux,!android CFLAGS: -DHAVE_PREAD64=1 -DHAVE_PWRITE64=1
  11. #cgo CFLAGS: -DSQLITE_ENABLE_FTS3 -DSQLITE_ENABLE_FTS3_PARENTHESIS -DSQLITE_ENABLE_FTS4_UNICODE61
  12. #cgo CFLAGS: -DSQLITE_TRACE_SIZE_LIMIT=15
  13. #cgo CFLAGS: -DSQLITE_OMIT_DEPRECATED
  14. #cgo CFLAGS: -DSQLITE_DISABLE_INTRINSIC
  15. #cgo CFLAGS: -DSQLITE_ENABLE_UPDATE_DELETE_LIMIT
  16. #cgo CFLAGS: -Wno-deprecated-declarations
  17. #ifndef USE_LIBSQLITE3
  18. #include <sqlite3-binding.h>
  19. #else
  20. #include <sqlite3.h>
  21. #endif
  22. #include <stdlib.h>
  23. #include <string.h>
  24. #ifdef __CYGWIN__
  25. # include <errno.h>
  26. #endif
  27. #ifndef SQLITE_OPEN_READWRITE
  28. # define SQLITE_OPEN_READWRITE 0
  29. #endif
  30. #ifndef SQLITE_OPEN_FULLMUTEX
  31. # define SQLITE_OPEN_FULLMUTEX 0
  32. #endif
  33. #ifndef SQLITE_DETERMINISTIC
  34. # define SQLITE_DETERMINISTIC 0
  35. #endif
  36. static int
  37. _sqlite3_open_v2(const char *filename, sqlite3 **ppDb, int flags, const char *zVfs) {
  38. #ifdef SQLITE_OPEN_URI
  39. return sqlite3_open_v2(filename, ppDb, flags | SQLITE_OPEN_URI, zVfs);
  40. #else
  41. return sqlite3_open_v2(filename, ppDb, flags, zVfs);
  42. #endif
  43. }
  44. static int
  45. _sqlite3_bind_text(sqlite3_stmt *stmt, int n, char *p, int np) {
  46. return sqlite3_bind_text(stmt, n, p, np, SQLITE_TRANSIENT);
  47. }
  48. static int
  49. _sqlite3_bind_blob(sqlite3_stmt *stmt, int n, void *p, int np) {
  50. return sqlite3_bind_blob(stmt, n, p, np, SQLITE_TRANSIENT);
  51. }
  52. #include <stdio.h>
  53. #include <stdint.h>
  54. static int
  55. _sqlite3_exec(sqlite3* db, const char* pcmd, long long* rowid, long long* changes)
  56. {
  57. int rv = sqlite3_exec(db, pcmd, 0, 0, 0);
  58. *rowid = (long long) sqlite3_last_insert_rowid(db);
  59. *changes = (long long) sqlite3_changes(db);
  60. return rv;
  61. }
  62. static int
  63. _sqlite3_step(sqlite3_stmt* stmt, long long* rowid, long long* changes)
  64. {
  65. int rv = sqlite3_step(stmt);
  66. sqlite3* db = sqlite3_db_handle(stmt);
  67. *rowid = (long long) sqlite3_last_insert_rowid(db);
  68. *changes = (long long) sqlite3_changes(db);
  69. return rv;
  70. }
  71. void _sqlite3_result_text(sqlite3_context* ctx, const char* s) {
  72. sqlite3_result_text(ctx, s, -1, &free);
  73. }
  74. void _sqlite3_result_blob(sqlite3_context* ctx, const void* b, int l) {
  75. sqlite3_result_blob(ctx, b, l, SQLITE_TRANSIENT);
  76. }
  77. int _sqlite3_create_function(
  78. sqlite3 *db,
  79. const char *zFunctionName,
  80. int nArg,
  81. int eTextRep,
  82. uintptr_t pApp,
  83. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  84. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  85. void (*xFinal)(sqlite3_context*)
  86. ) {
  87. return sqlite3_create_function(db, zFunctionName, nArg, eTextRep, (void*) pApp, xFunc, xStep, xFinal);
  88. }
  89. void callbackTrampoline(sqlite3_context*, int, sqlite3_value**);
  90. void stepTrampoline(sqlite3_context*, int, sqlite3_value**);
  91. void doneTrampoline(sqlite3_context*);
  92. int compareTrampoline(void*, int, char*, int, char*);
  93. int commitHookTrampoline(void*);
  94. void rollbackHookTrampoline(void*);
  95. void updateHookTrampoline(void*, int, char*, char*, sqlite3_int64);
  96. #ifdef SQLITE_LIMIT_WORKER_THREADS
  97. # define _SQLITE_HAS_LIMIT
  98. # define SQLITE_LIMIT_LENGTH 0
  99. # define SQLITE_LIMIT_SQL_LENGTH 1
  100. # define SQLITE_LIMIT_COLUMN 2
  101. # define SQLITE_LIMIT_EXPR_DEPTH 3
  102. # define SQLITE_LIMIT_COMPOUND_SELECT 4
  103. # define SQLITE_LIMIT_VDBE_OP 5
  104. # define SQLITE_LIMIT_FUNCTION_ARG 6
  105. # define SQLITE_LIMIT_ATTACHED 7
  106. # define SQLITE_LIMIT_LIKE_PATTERN_LENGTH 8
  107. # define SQLITE_LIMIT_VARIABLE_NUMBER 9
  108. # define SQLITE_LIMIT_TRIGGER_DEPTH 10
  109. # define SQLITE_LIMIT_WORKER_THREADS 11
  110. # else
  111. # define SQLITE_LIMIT_WORKER_THREADS 11
  112. #endif
  113. static int _sqlite3_limit(sqlite3* db, int limitId, int newLimit) {
  114. #ifndef _SQLITE_HAS_LIMIT
  115. return -1;
  116. #else
  117. return sqlite3_limit(db, limitId, newLimit);
  118. #endif
  119. }
  120. */
  121. import "C"
  122. import (
  123. "context"
  124. "database/sql"
  125. "database/sql/driver"
  126. "errors"
  127. "fmt"
  128. "io"
  129. "net/url"
  130. "reflect"
  131. "runtime"
  132. "strconv"
  133. "strings"
  134. "sync"
  135. "time"
  136. "unsafe"
  137. )
  138. // SQLiteTimestampFormats is timestamp formats understood by both this module
  139. // and SQLite. The first format in the slice will be used when saving time
  140. // values into the database. When parsing a string from a timestamp or datetime
  141. // column, the formats are tried in order.
  142. var SQLiteTimestampFormats = []string{
  143. // By default, store timestamps with whatever timezone they come with.
  144. // When parsed, they will be returned with the same timezone.
  145. "2006-01-02 15:04:05.999999999-07:00",
  146. "2006-01-02T15:04:05.999999999-07:00",
  147. "2006-01-02 15:04:05.999999999",
  148. "2006-01-02T15:04:05.999999999",
  149. "2006-01-02 15:04:05",
  150. "2006-01-02T15:04:05",
  151. "2006-01-02 15:04",
  152. "2006-01-02T15:04",
  153. "2006-01-02",
  154. }
  155. const (
  156. columnDate string = "date"
  157. columnDatetime string = "datetime"
  158. columnTimestamp string = "timestamp"
  159. )
  160. func init() {
  161. sql.Register("sqlite3", &SQLiteDriver{})
  162. }
  163. // Version returns SQLite library version information.
  164. func Version() (libVersion string, libVersionNumber int, sourceID string) {
  165. libVersion = C.GoString(C.sqlite3_libversion())
  166. libVersionNumber = int(C.sqlite3_libversion_number())
  167. sourceID = C.GoString(C.sqlite3_sourceid())
  168. return libVersion, libVersionNumber, sourceID
  169. }
  170. const (
  171. SQLITE_DELETE = C.SQLITE_DELETE
  172. SQLITE_INSERT = C.SQLITE_INSERT
  173. SQLITE_UPDATE = C.SQLITE_UPDATE
  174. )
  175. // SQLiteDriver implement sql.Driver.
  176. type SQLiteDriver struct {
  177. Extensions []string
  178. ConnectHook func(*SQLiteConn) error
  179. }
  180. // SQLiteConn implement sql.Conn.
  181. type SQLiteConn struct {
  182. mu sync.Mutex
  183. db *C.sqlite3
  184. loc *time.Location
  185. txlock string
  186. funcs []*functionInfo
  187. aggregators []*aggInfo
  188. }
  189. // SQLiteTx implemen sql.Tx.
  190. type SQLiteTx struct {
  191. c *SQLiteConn
  192. }
  193. // SQLiteStmt implement sql.Stmt.
  194. type SQLiteStmt struct {
  195. mu sync.Mutex
  196. c *SQLiteConn
  197. s *C.sqlite3_stmt
  198. t string
  199. closed bool
  200. cls bool
  201. }
  202. // SQLiteResult implement sql.Result.
  203. type SQLiteResult struct {
  204. id int64
  205. changes int64
  206. }
  207. // SQLiteRows implement sql.Rows.
  208. type SQLiteRows struct {
  209. s *SQLiteStmt
  210. nc int
  211. cols []string
  212. decltype []string
  213. cls bool
  214. closed bool
  215. done chan struct{}
  216. }
  217. type functionInfo struct {
  218. f reflect.Value
  219. argConverters []callbackArgConverter
  220. variadicConverter callbackArgConverter
  221. retConverter callbackRetConverter
  222. }
  223. func (fi *functionInfo) Call(ctx *C.sqlite3_context, argv []*C.sqlite3_value) {
  224. args, err := callbackConvertArgs(argv, fi.argConverters, fi.variadicConverter)
  225. if err != nil {
  226. callbackError(ctx, err)
  227. return
  228. }
  229. ret := fi.f.Call(args)
  230. if len(ret) == 2 && ret[1].Interface() != nil {
  231. callbackError(ctx, ret[1].Interface().(error))
  232. return
  233. }
  234. err = fi.retConverter(ctx, ret[0])
  235. if err != nil {
  236. callbackError(ctx, err)
  237. return
  238. }
  239. }
  240. type aggInfo struct {
  241. constructor reflect.Value
  242. // Active aggregator objects for aggregations in flight. The
  243. // aggregators are indexed by a counter stored in the aggregation
  244. // user data space provided by sqlite.
  245. active map[int64]reflect.Value
  246. next int64
  247. stepArgConverters []callbackArgConverter
  248. stepVariadicConverter callbackArgConverter
  249. doneRetConverter callbackRetConverter
  250. }
  251. func (ai *aggInfo) agg(ctx *C.sqlite3_context) (int64, reflect.Value, error) {
  252. aggIdx := (*int64)(C.sqlite3_aggregate_context(ctx, C.int(8)))
  253. if *aggIdx == 0 {
  254. *aggIdx = ai.next
  255. ret := ai.constructor.Call(nil)
  256. if len(ret) == 2 && ret[1].Interface() != nil {
  257. return 0, reflect.Value{}, ret[1].Interface().(error)
  258. }
  259. if ret[0].IsNil() {
  260. return 0, reflect.Value{}, errors.New("aggregator constructor returned nil state")
  261. }
  262. ai.next++
  263. ai.active[*aggIdx] = ret[0]
  264. }
  265. return *aggIdx, ai.active[*aggIdx], nil
  266. }
  267. func (ai *aggInfo) Step(ctx *C.sqlite3_context, argv []*C.sqlite3_value) {
  268. _, agg, err := ai.agg(ctx)
  269. if err != nil {
  270. callbackError(ctx, err)
  271. return
  272. }
  273. args, err := callbackConvertArgs(argv, ai.stepArgConverters, ai.stepVariadicConverter)
  274. if err != nil {
  275. callbackError(ctx, err)
  276. return
  277. }
  278. ret := agg.MethodByName("Step").Call(args)
  279. if len(ret) == 1 && ret[0].Interface() != nil {
  280. callbackError(ctx, ret[0].Interface().(error))
  281. return
  282. }
  283. }
  284. func (ai *aggInfo) Done(ctx *C.sqlite3_context) {
  285. idx, agg, err := ai.agg(ctx)
  286. if err != nil {
  287. callbackError(ctx, err)
  288. return
  289. }
  290. defer func() { delete(ai.active, idx) }()
  291. ret := agg.MethodByName("Done").Call(nil)
  292. if len(ret) == 2 && ret[1].Interface() != nil {
  293. callbackError(ctx, ret[1].Interface().(error))
  294. return
  295. }
  296. err = ai.doneRetConverter(ctx, ret[0])
  297. if err != nil {
  298. callbackError(ctx, err)
  299. return
  300. }
  301. }
  302. // Commit transaction.
  303. func (tx *SQLiteTx) Commit() error {
  304. _, err := tx.c.exec(context.Background(), "COMMIT", nil)
  305. if err != nil && err.(Error).Code == C.SQLITE_BUSY {
  306. // sqlite3 will leave the transaction open in this scenario.
  307. // However, database/sql considers the transaction complete once we
  308. // return from Commit() - we must clean up to honour its semantics.
  309. tx.c.exec(context.Background(), "ROLLBACK", nil)
  310. }
  311. return err
  312. }
  313. // Rollback transaction.
  314. func (tx *SQLiteTx) Rollback() error {
  315. _, err := tx.c.exec(context.Background(), "ROLLBACK", nil)
  316. return err
  317. }
  318. // RegisterCollation makes a Go function available as a collation.
  319. //
  320. // cmp receives two UTF-8 strings, a and b. The result should be 0 if
  321. // a==b, -1 if a < b, and +1 if a > b.
  322. //
  323. // cmp must always return the same result given the same
  324. // inputs. Additionally, it must have the following properties for all
  325. // strings A, B and C: if A==B then B==A; if A==B and B==C then A==C;
  326. // if A<B then B>A; if A<B and B<C then A<C.
  327. //
  328. // If cmp does not obey these constraints, sqlite3's behavior is
  329. // undefined when the collation is used.
  330. func (c *SQLiteConn) RegisterCollation(name string, cmp func(string, string) int) error {
  331. handle := newHandle(c, cmp)
  332. cname := C.CString(name)
  333. defer C.free(unsafe.Pointer(cname))
  334. rv := C.sqlite3_create_collation(c.db, cname, C.SQLITE_UTF8, unsafe.Pointer(handle), (*[0]byte)(unsafe.Pointer(C.compareTrampoline)))
  335. if rv != C.SQLITE_OK {
  336. return c.lastError()
  337. }
  338. return nil
  339. }
  340. // RegisterCommitHook sets the commit hook for a connection.
  341. //
  342. // If the callback returns non-zero the transaction will become a rollback.
  343. //
  344. // If there is an existing commit hook for this connection, it will be
  345. // removed. If callback is nil the existing hook (if any) will be removed
  346. // without creating a new one.
  347. func (c *SQLiteConn) RegisterCommitHook(callback func() int) {
  348. if callback == nil {
  349. C.sqlite3_commit_hook(c.db, nil, nil)
  350. } else {
  351. C.sqlite3_commit_hook(c.db, (*[0]byte)(C.commitHookTrampoline), unsafe.Pointer(newHandle(c, callback)))
  352. }
  353. }
  354. // RegisterRollbackHook sets the rollback hook for a connection.
  355. //
  356. // If there is an existing rollback hook for this connection, it will be
  357. // removed. If callback is nil the existing hook (if any) will be removed
  358. // without creating a new one.
  359. func (c *SQLiteConn) RegisterRollbackHook(callback func()) {
  360. if callback == nil {
  361. C.sqlite3_rollback_hook(c.db, nil, nil)
  362. } else {
  363. C.sqlite3_rollback_hook(c.db, (*[0]byte)(C.rollbackHookTrampoline), unsafe.Pointer(newHandle(c, callback)))
  364. }
  365. }
  366. // RegisterUpdateHook sets the update hook for a connection.
  367. //
  368. // The parameters to the callback are the operation (one of the constants
  369. // SQLITE_INSERT, SQLITE_DELETE, or SQLITE_UPDATE), the database name, the
  370. // table name, and the rowid.
  371. //
  372. // If there is an existing update hook for this connection, it will be
  373. // removed. If callback is nil the existing hook (if any) will be removed
  374. // without creating a new one.
  375. func (c *SQLiteConn) RegisterUpdateHook(callback func(int, string, string, int64)) {
  376. if callback == nil {
  377. C.sqlite3_update_hook(c.db, nil, nil)
  378. } else {
  379. C.sqlite3_update_hook(c.db, (*[0]byte)(C.updateHookTrampoline), unsafe.Pointer(newHandle(c, callback)))
  380. }
  381. }
  382. // RegisterFunc makes a Go function available as a SQLite function.
  383. //
  384. // The Go function can have arguments of the following types: any
  385. // numeric type except complex, bool, []byte, string and
  386. // interface{}. interface{} arguments are given the direct translation
  387. // of the SQLite data type: int64 for INTEGER, float64 for FLOAT,
  388. // []byte for BLOB, string for TEXT.
  389. //
  390. // The function can additionally be variadic, as long as the type of
  391. // the variadic argument is one of the above.
  392. //
  393. // If pure is true. SQLite will assume that the function's return
  394. // value depends only on its inputs, and make more aggressive
  395. // optimizations in its queries.
  396. //
  397. // See _example/go_custom_funcs for a detailed example.
  398. func (c *SQLiteConn) RegisterFunc(name string, impl interface{}, pure bool) error {
  399. var fi functionInfo
  400. fi.f = reflect.ValueOf(impl)
  401. t := fi.f.Type()
  402. if t.Kind() != reflect.Func {
  403. return errors.New("Non-function passed to RegisterFunc")
  404. }
  405. if t.NumOut() != 1 && t.NumOut() != 2 {
  406. return errors.New("SQLite functions must return 1 or 2 values")
  407. }
  408. if t.NumOut() == 2 && !t.Out(1).Implements(reflect.TypeOf((*error)(nil)).Elem()) {
  409. return errors.New("Second return value of SQLite function must be error")
  410. }
  411. numArgs := t.NumIn()
  412. if t.IsVariadic() {
  413. numArgs--
  414. }
  415. for i := 0; i < numArgs; i++ {
  416. conv, err := callbackArg(t.In(i))
  417. if err != nil {
  418. return err
  419. }
  420. fi.argConverters = append(fi.argConverters, conv)
  421. }
  422. if t.IsVariadic() {
  423. conv, err := callbackArg(t.In(numArgs).Elem())
  424. if err != nil {
  425. return err
  426. }
  427. fi.variadicConverter = conv
  428. // Pass -1 to sqlite so that it allows any number of
  429. // arguments. The call helper verifies that the minimum number
  430. // of arguments is present for variadic functions.
  431. numArgs = -1
  432. }
  433. conv, err := callbackRet(t.Out(0))
  434. if err != nil {
  435. return err
  436. }
  437. fi.retConverter = conv
  438. // fi must outlast the database connection, or we'll have dangling pointers.
  439. c.funcs = append(c.funcs, &fi)
  440. cname := C.CString(name)
  441. defer C.free(unsafe.Pointer(cname))
  442. opts := C.SQLITE_UTF8
  443. if pure {
  444. opts |= C.SQLITE_DETERMINISTIC
  445. }
  446. rv := sqlite3CreateFunction(c.db, cname, C.int(numArgs), C.int(opts), newHandle(c, &fi), C.callbackTrampoline, nil, nil)
  447. if rv != C.SQLITE_OK {
  448. return c.lastError()
  449. }
  450. return nil
  451. }
  452. 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 {
  453. return C._sqlite3_create_function(db, zFunctionName, nArg, eTextRep, C.uintptr_t(pApp), (*[0]byte)(xFunc), (*[0]byte)(xStep), (*[0]byte)(xFinal))
  454. }
  455. // RegisterAggregator makes a Go type available as a SQLite aggregation function.
  456. //
  457. // Because aggregation is incremental, it's implemented in Go with a
  458. // type that has 2 methods: func Step(values) accumulates one row of
  459. // data into the accumulator, and func Done() ret finalizes and
  460. // returns the aggregate value. "values" and "ret" may be any type
  461. // supported by RegisterFunc.
  462. //
  463. // RegisterAggregator takes as implementation a constructor function
  464. // that constructs an instance of the aggregator type each time an
  465. // aggregation begins. The constructor must return a pointer to a
  466. // type, or an interface that implements Step() and Done().
  467. //
  468. // The constructor function and the Step/Done methods may optionally
  469. // return an error in addition to their other return values.
  470. //
  471. // See _example/go_custom_funcs for a detailed example.
  472. func (c *SQLiteConn) RegisterAggregator(name string, impl interface{}, pure bool) error {
  473. var ai aggInfo
  474. ai.constructor = reflect.ValueOf(impl)
  475. t := ai.constructor.Type()
  476. if t.Kind() != reflect.Func {
  477. return errors.New("non-function passed to RegisterAggregator")
  478. }
  479. if t.NumOut() != 1 && t.NumOut() != 2 {
  480. return errors.New("SQLite aggregator constructors must return 1 or 2 values")
  481. }
  482. if t.NumOut() == 2 && !t.Out(1).Implements(reflect.TypeOf((*error)(nil)).Elem()) {
  483. return errors.New("Second return value of SQLite function must be error")
  484. }
  485. if t.NumIn() != 0 {
  486. return errors.New("SQLite aggregator constructors must not have arguments")
  487. }
  488. agg := t.Out(0)
  489. switch agg.Kind() {
  490. case reflect.Ptr, reflect.Interface:
  491. default:
  492. return errors.New("SQlite aggregator constructor must return a pointer object")
  493. }
  494. stepFn, found := agg.MethodByName("Step")
  495. if !found {
  496. return errors.New("SQlite aggregator doesn't have a Step() function")
  497. }
  498. step := stepFn.Type
  499. if step.NumOut() != 0 && step.NumOut() != 1 {
  500. return errors.New("SQlite aggregator Step() function must return 0 or 1 values")
  501. }
  502. if step.NumOut() == 1 && !step.Out(0).Implements(reflect.TypeOf((*error)(nil)).Elem()) {
  503. return errors.New("type of SQlite aggregator Step() return value must be error")
  504. }
  505. stepNArgs := step.NumIn()
  506. start := 0
  507. if agg.Kind() == reflect.Ptr {
  508. // Skip over the method receiver
  509. stepNArgs--
  510. start++
  511. }
  512. if step.IsVariadic() {
  513. stepNArgs--
  514. }
  515. for i := start; i < start+stepNArgs; i++ {
  516. conv, err := callbackArg(step.In(i))
  517. if err != nil {
  518. return err
  519. }
  520. ai.stepArgConverters = append(ai.stepArgConverters, conv)
  521. }
  522. if step.IsVariadic() {
  523. conv, err := callbackArg(t.In(start + stepNArgs).Elem())
  524. if err != nil {
  525. return err
  526. }
  527. ai.stepVariadicConverter = conv
  528. // Pass -1 to sqlite so that it allows any number of
  529. // arguments. The call helper verifies that the minimum number
  530. // of arguments is present for variadic functions.
  531. stepNArgs = -1
  532. }
  533. doneFn, found := agg.MethodByName("Done")
  534. if !found {
  535. return errors.New("SQlite aggregator doesn't have a Done() function")
  536. }
  537. done := doneFn.Type
  538. doneNArgs := done.NumIn()
  539. if agg.Kind() == reflect.Ptr {
  540. // Skip over the method receiver
  541. doneNArgs--
  542. }
  543. if doneNArgs != 0 {
  544. return errors.New("SQlite aggregator Done() function must have no arguments")
  545. }
  546. if done.NumOut() != 1 && done.NumOut() != 2 {
  547. return errors.New("SQLite aggregator Done() function must return 1 or 2 values")
  548. }
  549. if done.NumOut() == 2 && !done.Out(1).Implements(reflect.TypeOf((*error)(nil)).Elem()) {
  550. return errors.New("second return value of SQLite aggregator Done() function must be error")
  551. }
  552. conv, err := callbackRet(done.Out(0))
  553. if err != nil {
  554. return err
  555. }
  556. ai.doneRetConverter = conv
  557. ai.active = make(map[int64]reflect.Value)
  558. ai.next = 1
  559. // ai must outlast the database connection, or we'll have dangling pointers.
  560. c.aggregators = append(c.aggregators, &ai)
  561. cname := C.CString(name)
  562. defer C.free(unsafe.Pointer(cname))
  563. opts := C.SQLITE_UTF8
  564. if pure {
  565. opts |= C.SQLITE_DETERMINISTIC
  566. }
  567. rv := sqlite3CreateFunction(c.db, cname, C.int(stepNArgs), C.int(opts), newHandle(c, &ai), nil, C.stepTrampoline, C.doneTrampoline)
  568. if rv != C.SQLITE_OK {
  569. return c.lastError()
  570. }
  571. return nil
  572. }
  573. // AutoCommit return which currently auto commit or not.
  574. func (c *SQLiteConn) AutoCommit() bool {
  575. return int(C.sqlite3_get_autocommit(c.db)) != 0
  576. }
  577. func (c *SQLiteConn) lastError() error {
  578. return lastError(c.db)
  579. }
  580. func lastError(db *C.sqlite3) error {
  581. rv := C.sqlite3_errcode(db)
  582. if rv == C.SQLITE_OK {
  583. return nil
  584. }
  585. return Error{
  586. Code: ErrNo(rv),
  587. ExtendedCode: ErrNoExtended(C.sqlite3_extended_errcode(db)),
  588. err: C.GoString(C.sqlite3_errmsg(db)),
  589. }
  590. }
  591. // Exec implements Execer.
  592. func (c *SQLiteConn) Exec(query string, args []driver.Value) (driver.Result, error) {
  593. list := make([]namedValue, len(args))
  594. for i, v := range args {
  595. list[i] = namedValue{
  596. Ordinal: i + 1,
  597. Value: v,
  598. }
  599. }
  600. return c.exec(context.Background(), query, list)
  601. }
  602. func (c *SQLiteConn) exec(ctx context.Context, query string, args []namedValue) (driver.Result, error) {
  603. start := 0
  604. for {
  605. s, err := c.prepare(ctx, query)
  606. if err != nil {
  607. return nil, err
  608. }
  609. var res driver.Result
  610. if s.(*SQLiteStmt).s != nil {
  611. na := s.NumInput()
  612. if len(args) < na {
  613. s.Close()
  614. return nil, fmt.Errorf("not enough args to execute query: want %d got %d", na, len(args))
  615. }
  616. for i := 0; i < na; i++ {
  617. args[i].Ordinal -= start
  618. }
  619. res, err = s.(*SQLiteStmt).exec(ctx, args[:na])
  620. if err != nil && err != driver.ErrSkip {
  621. s.Close()
  622. return nil, err
  623. }
  624. args = args[na:]
  625. start += na
  626. }
  627. tail := s.(*SQLiteStmt).t
  628. s.Close()
  629. if tail == "" {
  630. return res, nil
  631. }
  632. query = tail
  633. }
  634. }
  635. type namedValue struct {
  636. Name string
  637. Ordinal int
  638. Value driver.Value
  639. }
  640. // Query implements Queryer.
  641. func (c *SQLiteConn) Query(query string, args []driver.Value) (driver.Rows, error) {
  642. list := make([]namedValue, len(args))
  643. for i, v := range args {
  644. list[i] = namedValue{
  645. Ordinal: i + 1,
  646. Value: v,
  647. }
  648. }
  649. return c.query(context.Background(), query, list)
  650. }
  651. func (c *SQLiteConn) query(ctx context.Context, query string, args []namedValue) (driver.Rows, error) {
  652. start := 0
  653. for {
  654. s, err := c.prepare(ctx, query)
  655. if err != nil {
  656. return nil, err
  657. }
  658. s.(*SQLiteStmt).cls = true
  659. na := s.NumInput()
  660. if len(args) < na {
  661. return nil, fmt.Errorf("not enough args to execute query: want %d got %d", na, len(args))
  662. }
  663. for i := 0; i < na; i++ {
  664. args[i].Ordinal -= start
  665. }
  666. rows, err := s.(*SQLiteStmt).query(ctx, args[:na])
  667. if err != nil && err != driver.ErrSkip {
  668. s.Close()
  669. return rows, err
  670. }
  671. args = args[na:]
  672. start += na
  673. tail := s.(*SQLiteStmt).t
  674. if tail == "" {
  675. return rows, nil
  676. }
  677. rows.Close()
  678. s.Close()
  679. query = tail
  680. }
  681. }
  682. // Begin transaction.
  683. func (c *SQLiteConn) Begin() (driver.Tx, error) {
  684. return c.begin(context.Background())
  685. }
  686. func (c *SQLiteConn) begin(ctx context.Context) (driver.Tx, error) {
  687. if _, err := c.exec(ctx, c.txlock, nil); err != nil {
  688. return nil, err
  689. }
  690. return &SQLiteTx{c}, nil
  691. }
  692. func errorString(err Error) string {
  693. return C.GoString(C.sqlite3_errstr(C.int(err.Code)))
  694. }
  695. // Open database and return a new connection.
  696. // You can specify a DSN string using a URI as the filename.
  697. // test.db
  698. // file:test.db?cache=shared&mode=memory
  699. // :memory:
  700. // file::memory:
  701. // go-sqlite3 adds the following query parameters to those used by SQLite:
  702. // _loc=XXX
  703. // Specify location of time format. It's possible to specify "auto".
  704. // _busy_timeout=XXX
  705. // Specify value for sqlite3_busy_timeout.
  706. // _txlock=XXX
  707. // Specify locking behavior for transactions. XXX can be "immediate",
  708. // "deferred", "exclusive".
  709. // _foreign_keys=X
  710. // Enable or disable enforcement of foreign keys. X can be 1 or 0.
  711. // _recursive_triggers=X
  712. // Enable or disable recursive triggers. X can be 1 or 0.
  713. // _mutex=XXX
  714. // Specify mutex mode. XXX can be "no", "full".
  715. func (d *SQLiteDriver) Open(dsn string) (driver.Conn, error) {
  716. if C.sqlite3_threadsafe() == 0 {
  717. return nil, errors.New("sqlite library was not compiled for thread-safe operation")
  718. }
  719. var loc *time.Location
  720. txlock := "BEGIN"
  721. busyTimeout := 5000
  722. foreignKeys := -1
  723. recursiveTriggers := -1
  724. mutex := C.int(C.SQLITE_OPEN_FULLMUTEX)
  725. pos := strings.IndexRune(dsn, '?')
  726. if pos >= 1 {
  727. params, err := url.ParseQuery(dsn[pos+1:])
  728. if err != nil {
  729. return nil, err
  730. }
  731. // _loc
  732. if val := params.Get("_loc"); val != "" {
  733. if val == "auto" {
  734. loc = time.Local
  735. } else {
  736. loc, err = time.LoadLocation(val)
  737. if err != nil {
  738. return nil, fmt.Errorf("Invalid _loc: %v: %v", val, err)
  739. }
  740. }
  741. }
  742. // _busy_timeout
  743. if val := params.Get("_busy_timeout"); val != "" {
  744. iv, err := strconv.ParseInt(val, 10, 64)
  745. if err != nil {
  746. return nil, fmt.Errorf("Invalid _busy_timeout: %v: %v", val, err)
  747. }
  748. busyTimeout = int(iv)
  749. }
  750. // _txlock
  751. if val := params.Get("_txlock"); val != "" {
  752. switch val {
  753. case "immediate":
  754. txlock = "BEGIN IMMEDIATE"
  755. case "exclusive":
  756. txlock = "BEGIN EXCLUSIVE"
  757. case "deferred":
  758. txlock = "BEGIN"
  759. default:
  760. return nil, fmt.Errorf("Invalid _txlock: %v", val)
  761. }
  762. }
  763. // _foreign_keys
  764. if val := params.Get("_foreign_keys"); val != "" {
  765. switch val {
  766. case "1":
  767. foreignKeys = 1
  768. case "0":
  769. foreignKeys = 0
  770. default:
  771. return nil, fmt.Errorf("Invalid _foreign_keys: %v", val)
  772. }
  773. }
  774. // _recursive_triggers
  775. if val := params.Get("_recursive_triggers"); val != "" {
  776. switch val {
  777. case "1":
  778. recursiveTriggers = 1
  779. case "0":
  780. recursiveTriggers = 0
  781. default:
  782. return nil, fmt.Errorf("Invalid _recursive_triggers: %v", val)
  783. }
  784. }
  785. // _mutex
  786. if val := params.Get("_mutex"); val != "" {
  787. switch val {
  788. case "no":
  789. mutex = C.SQLITE_OPEN_NOMUTEX
  790. case "full":
  791. mutex = C.SQLITE_OPEN_FULLMUTEX
  792. default:
  793. return nil, fmt.Errorf("Invalid _mutex: %v", val)
  794. }
  795. }
  796. if !strings.HasPrefix(dsn, "file:") {
  797. dsn = dsn[:pos]
  798. }
  799. }
  800. var db *C.sqlite3
  801. name := C.CString(dsn)
  802. defer C.free(unsafe.Pointer(name))
  803. rv := C._sqlite3_open_v2(name, &db,
  804. mutex|C.SQLITE_OPEN_READWRITE|C.SQLITE_OPEN_CREATE,
  805. nil)
  806. if rv != 0 {
  807. return nil, Error{Code: ErrNo(rv)}
  808. }
  809. if db == nil {
  810. return nil, errors.New("sqlite succeeded without returning a database")
  811. }
  812. rv = C.sqlite3_busy_timeout(db, C.int(busyTimeout))
  813. if rv != C.SQLITE_OK {
  814. C.sqlite3_close_v2(db)
  815. return nil, Error{Code: ErrNo(rv)}
  816. }
  817. exec := func(s string) error {
  818. cs := C.CString(s)
  819. rv := C.sqlite3_exec(db, cs, nil, nil, nil)
  820. C.free(unsafe.Pointer(cs))
  821. if rv != C.SQLITE_OK {
  822. return lastError(db)
  823. }
  824. return nil
  825. }
  826. if foreignKeys == 0 {
  827. if err := exec("PRAGMA foreign_keys = OFF;"); err != nil {
  828. C.sqlite3_close_v2(db)
  829. return nil, err
  830. }
  831. } else if foreignKeys == 1 {
  832. if err := exec("PRAGMA foreign_keys = ON;"); err != nil {
  833. C.sqlite3_close_v2(db)
  834. return nil, err
  835. }
  836. }
  837. if recursiveTriggers == 0 {
  838. if err := exec("PRAGMA recursive_triggers = OFF;"); err != nil {
  839. C.sqlite3_close_v2(db)
  840. return nil, err
  841. }
  842. } else if recursiveTriggers == 1 {
  843. if err := exec("PRAGMA recursive_triggers = ON;"); err != nil {
  844. C.sqlite3_close_v2(db)
  845. return nil, err
  846. }
  847. }
  848. conn := &SQLiteConn{db: db, loc: loc, txlock: txlock}
  849. if len(d.Extensions) > 0 {
  850. if err := conn.loadExtensions(d.Extensions); err != nil {
  851. conn.Close()
  852. return nil, err
  853. }
  854. }
  855. if d.ConnectHook != nil {
  856. if err := d.ConnectHook(conn); err != nil {
  857. conn.Close()
  858. return nil, err
  859. }
  860. }
  861. runtime.SetFinalizer(conn, (*SQLiteConn).Close)
  862. return conn, nil
  863. }
  864. // Close the connection.
  865. func (c *SQLiteConn) Close() error {
  866. rv := C.sqlite3_close_v2(c.db)
  867. if rv != C.SQLITE_OK {
  868. return c.lastError()
  869. }
  870. deleteHandles(c)
  871. c.mu.Lock()
  872. c.db = nil
  873. c.mu.Unlock()
  874. runtime.SetFinalizer(c, nil)
  875. return nil
  876. }
  877. func (c *SQLiteConn) dbConnOpen() bool {
  878. if c == nil {
  879. return false
  880. }
  881. c.mu.Lock()
  882. defer c.mu.Unlock()
  883. return c.db != nil
  884. }
  885. // Prepare the query string. Return a new statement.
  886. func (c *SQLiteConn) Prepare(query string) (driver.Stmt, error) {
  887. return c.prepare(context.Background(), query)
  888. }
  889. func (c *SQLiteConn) prepare(ctx context.Context, query string) (driver.Stmt, error) {
  890. pquery := C.CString(query)
  891. defer C.free(unsafe.Pointer(pquery))
  892. var s *C.sqlite3_stmt
  893. var tail *C.char
  894. rv := C.sqlite3_prepare_v2(c.db, pquery, -1, &s, &tail)
  895. if rv != C.SQLITE_OK {
  896. return nil, c.lastError()
  897. }
  898. var t string
  899. if tail != nil && *tail != '\000' {
  900. t = strings.TrimSpace(C.GoString(tail))
  901. }
  902. ss := &SQLiteStmt{c: c, s: s, t: t}
  903. runtime.SetFinalizer(ss, (*SQLiteStmt).Close)
  904. return ss, nil
  905. }
  906. // Run-Time Limit Categories.
  907. // See: http://www.sqlite.org/c3ref/c_limit_attached.html
  908. const (
  909. SQLITE_LIMIT_LENGTH = C.SQLITE_LIMIT_LENGTH
  910. SQLITE_LIMIT_SQL_LENGTH = C.SQLITE_LIMIT_SQL_LENGTH
  911. SQLITE_LIMIT_COLUMN = C.SQLITE_LIMIT_COLUMN
  912. SQLITE_LIMIT_EXPR_DEPTH = C.SQLITE_LIMIT_EXPR_DEPTH
  913. SQLITE_LIMIT_COMPOUND_SELECT = C.SQLITE_LIMIT_COMPOUND_SELECT
  914. SQLITE_LIMIT_VDBE_OP = C.SQLITE_LIMIT_VDBE_OP
  915. SQLITE_LIMIT_FUNCTION_ARG = C.SQLITE_LIMIT_FUNCTION_ARG
  916. SQLITE_LIMIT_ATTACHED = C.SQLITE_LIMIT_ATTACHED
  917. SQLITE_LIMIT_LIKE_PATTERN_LENGTH = C.SQLITE_LIMIT_LIKE_PATTERN_LENGTH
  918. SQLITE_LIMIT_VARIABLE_NUMBER = C.SQLITE_LIMIT_VARIABLE_NUMBER
  919. SQLITE_LIMIT_TRIGGER_DEPTH = C.SQLITE_LIMIT_TRIGGER_DEPTH
  920. SQLITE_LIMIT_WORKER_THREADS = C.SQLITE_LIMIT_WORKER_THREADS
  921. )
  922. // GetLimit returns the current value of a run-time limit.
  923. // See: sqlite3_limit, http://www.sqlite.org/c3ref/limit.html
  924. func (c *SQLiteConn) GetLimit(id int) int {
  925. return int(C._sqlite3_limit(c.db, C.int(id), -1))
  926. }
  927. // SetLimit changes the value of a run-time limits.
  928. // Then this method returns the prior value of the limit.
  929. // See: sqlite3_limit, http://www.sqlite.org/c3ref/limit.html
  930. func (c *SQLiteConn) SetLimit(id int, newVal int) int {
  931. return int(C._sqlite3_limit(c.db, C.int(id), C.int(newVal)))
  932. }
  933. // Close the statement.
  934. func (s *SQLiteStmt) Close() error {
  935. s.mu.Lock()
  936. defer s.mu.Unlock()
  937. if s.closed {
  938. return nil
  939. }
  940. s.closed = true
  941. if !s.c.dbConnOpen() {
  942. return errors.New("sqlite statement with already closed database connection")
  943. }
  944. rv := C.sqlite3_finalize(s.s)
  945. s.s = nil
  946. if rv != C.SQLITE_OK {
  947. return s.c.lastError()
  948. }
  949. runtime.SetFinalizer(s, nil)
  950. return nil
  951. }
  952. // NumInput return a number of parameters.
  953. func (s *SQLiteStmt) NumInput() int {
  954. return int(C.sqlite3_bind_parameter_count(s.s))
  955. }
  956. type bindArg struct {
  957. n int
  958. v driver.Value
  959. }
  960. var placeHolder = []byte{0}
  961. func (s *SQLiteStmt) bind(args []namedValue) error {
  962. rv := C.sqlite3_reset(s.s)
  963. if rv != C.SQLITE_ROW && rv != C.SQLITE_OK && rv != C.SQLITE_DONE {
  964. return s.c.lastError()
  965. }
  966. for i, v := range args {
  967. if v.Name != "" {
  968. cname := C.CString(":" + v.Name)
  969. args[i].Ordinal = int(C.sqlite3_bind_parameter_index(s.s, cname))
  970. C.free(unsafe.Pointer(cname))
  971. }
  972. }
  973. for _, arg := range args {
  974. n := C.int(arg.Ordinal)
  975. switch v := arg.Value.(type) {
  976. case nil:
  977. rv = C.sqlite3_bind_null(s.s, n)
  978. case string:
  979. if len(v) == 0 {
  980. rv = C._sqlite3_bind_text(s.s, n, (*C.char)(unsafe.Pointer(&placeHolder[0])), C.int(0))
  981. } else {
  982. b := []byte(v)
  983. rv = C._sqlite3_bind_text(s.s, n, (*C.char)(unsafe.Pointer(&b[0])), C.int(len(b)))
  984. }
  985. case int64:
  986. rv = C.sqlite3_bind_int64(s.s, n, C.sqlite3_int64(v))
  987. case bool:
  988. if v {
  989. rv = C.sqlite3_bind_int(s.s, n, 1)
  990. } else {
  991. rv = C.sqlite3_bind_int(s.s, n, 0)
  992. }
  993. case float64:
  994. rv = C.sqlite3_bind_double(s.s, n, C.double(v))
  995. case []byte:
  996. ln := len(v)
  997. if ln == 0 {
  998. v = placeHolder
  999. }
  1000. rv = C._sqlite3_bind_blob(s.s, n, unsafe.Pointer(&v[0]), C.int(ln))
  1001. case time.Time:
  1002. b := []byte(v.Format(SQLiteTimestampFormats[0]))
  1003. rv = C._sqlite3_bind_text(s.s, n, (*C.char)(unsafe.Pointer(&b[0])), C.int(len(b)))
  1004. }
  1005. if rv != C.SQLITE_OK {
  1006. return s.c.lastError()
  1007. }
  1008. }
  1009. return nil
  1010. }
  1011. // Query the statement with arguments. Return records.
  1012. func (s *SQLiteStmt) Query(args []driver.Value) (driver.Rows, error) {
  1013. list := make([]namedValue, len(args))
  1014. for i, v := range args {
  1015. list[i] = namedValue{
  1016. Ordinal: i + 1,
  1017. Value: v,
  1018. }
  1019. }
  1020. return s.query(context.Background(), list)
  1021. }
  1022. func (s *SQLiteStmt) query(ctx context.Context, args []namedValue) (driver.Rows, error) {
  1023. if err := s.bind(args); err != nil {
  1024. return nil, err
  1025. }
  1026. rows := &SQLiteRows{
  1027. s: s,
  1028. nc: int(C.sqlite3_column_count(s.s)),
  1029. cols: nil,
  1030. decltype: nil,
  1031. cls: s.cls,
  1032. closed: false,
  1033. done: make(chan struct{}),
  1034. }
  1035. if ctxdone := ctx.Done(); ctxdone != nil {
  1036. go func(db *C.sqlite3) {
  1037. select {
  1038. case <-ctxdone:
  1039. select {
  1040. case <-rows.done:
  1041. default:
  1042. C.sqlite3_interrupt(db)
  1043. rows.Close()
  1044. }
  1045. case <-rows.done:
  1046. }
  1047. }(s.c.db)
  1048. }
  1049. return rows, nil
  1050. }
  1051. // LastInsertId teturn last inserted ID.
  1052. func (r *SQLiteResult) LastInsertId() (int64, error) {
  1053. return r.id, nil
  1054. }
  1055. // RowsAffected return how many rows affected.
  1056. func (r *SQLiteResult) RowsAffected() (int64, error) {
  1057. return r.changes, nil
  1058. }
  1059. // Exec execute the statement with arguments. Return result object.
  1060. func (s *SQLiteStmt) Exec(args []driver.Value) (driver.Result, error) {
  1061. list := make([]namedValue, len(args))
  1062. for i, v := range args {
  1063. list[i] = namedValue{
  1064. Ordinal: i + 1,
  1065. Value: v,
  1066. }
  1067. }
  1068. return s.exec(context.Background(), list)
  1069. }
  1070. func (s *SQLiteStmt) exec(ctx context.Context, args []namedValue) (driver.Result, error) {
  1071. if err := s.bind(args); err != nil {
  1072. C.sqlite3_reset(s.s)
  1073. C.sqlite3_clear_bindings(s.s)
  1074. return nil, err
  1075. }
  1076. if ctxdone := ctx.Done(); ctxdone != nil {
  1077. done := make(chan struct{})
  1078. defer close(done)
  1079. go func(db *C.sqlite3) {
  1080. select {
  1081. case <-done:
  1082. case <-ctxdone:
  1083. select {
  1084. case <-done:
  1085. default:
  1086. C.sqlite3_interrupt(db)
  1087. }
  1088. }
  1089. }(s.c.db)
  1090. }
  1091. var rowid, changes C.longlong
  1092. rv := C._sqlite3_step(s.s, &rowid, &changes)
  1093. if rv != C.SQLITE_ROW && rv != C.SQLITE_OK && rv != C.SQLITE_DONE {
  1094. err := s.c.lastError()
  1095. C.sqlite3_reset(s.s)
  1096. C.sqlite3_clear_bindings(s.s)
  1097. return nil, err
  1098. }
  1099. return &SQLiteResult{id: int64(rowid), changes: int64(changes)}, nil
  1100. }
  1101. // Close the rows.
  1102. func (rc *SQLiteRows) Close() error {
  1103. rc.s.mu.Lock()
  1104. if rc.s.closed || rc.closed {
  1105. rc.s.mu.Unlock()
  1106. return nil
  1107. }
  1108. rc.closed = true
  1109. if rc.done != nil {
  1110. close(rc.done)
  1111. }
  1112. if rc.cls {
  1113. rc.s.mu.Unlock()
  1114. return rc.s.Close()
  1115. }
  1116. rv := C.sqlite3_reset(rc.s.s)
  1117. if rv != C.SQLITE_OK {
  1118. rc.s.mu.Unlock()
  1119. return rc.s.c.lastError()
  1120. }
  1121. rc.s.mu.Unlock()
  1122. return nil
  1123. }
  1124. // Columns return column names.
  1125. func (rc *SQLiteRows) Columns() []string {
  1126. rc.s.mu.Lock()
  1127. defer rc.s.mu.Unlock()
  1128. if rc.s.s != nil && rc.nc != len(rc.cols) {
  1129. rc.cols = make([]string, rc.nc)
  1130. for i := 0; i < rc.nc; i++ {
  1131. rc.cols[i] = C.GoString(C.sqlite3_column_name(rc.s.s, C.int(i)))
  1132. }
  1133. }
  1134. return rc.cols
  1135. }
  1136. func (rc *SQLiteRows) declTypes() []string {
  1137. if rc.s.s != nil && rc.decltype == nil {
  1138. rc.decltype = make([]string, rc.nc)
  1139. for i := 0; i < rc.nc; i++ {
  1140. rc.decltype[i] = strings.ToLower(C.GoString(C.sqlite3_column_decltype(rc.s.s, C.int(i))))
  1141. }
  1142. }
  1143. return rc.decltype
  1144. }
  1145. // DeclTypes return column types.
  1146. func (rc *SQLiteRows) DeclTypes() []string {
  1147. rc.s.mu.Lock()
  1148. defer rc.s.mu.Unlock()
  1149. return rc.declTypes()
  1150. }
  1151. // Next move cursor to next.
  1152. func (rc *SQLiteRows) Next(dest []driver.Value) error {
  1153. if rc.s.closed {
  1154. return io.EOF
  1155. }
  1156. rc.s.mu.Lock()
  1157. defer rc.s.mu.Unlock()
  1158. rv := C.sqlite3_step(rc.s.s)
  1159. if rv == C.SQLITE_DONE {
  1160. return io.EOF
  1161. }
  1162. if rv != C.SQLITE_ROW {
  1163. rv = C.sqlite3_reset(rc.s.s)
  1164. if rv != C.SQLITE_OK {
  1165. return rc.s.c.lastError()
  1166. }
  1167. return nil
  1168. }
  1169. rc.declTypes()
  1170. for i := range dest {
  1171. switch C.sqlite3_column_type(rc.s.s, C.int(i)) {
  1172. case C.SQLITE_INTEGER:
  1173. val := int64(C.sqlite3_column_int64(rc.s.s, C.int(i)))
  1174. switch rc.decltype[i] {
  1175. case columnTimestamp, columnDatetime, columnDate:
  1176. var t time.Time
  1177. // Assume a millisecond unix timestamp if it's 13 digits -- too
  1178. // large to be a reasonable timestamp in seconds.
  1179. if val > 1e12 || val < -1e12 {
  1180. val *= int64(time.Millisecond) // convert ms to nsec
  1181. t = time.Unix(0, val)
  1182. } else {
  1183. t = time.Unix(val, 0)
  1184. }
  1185. t = t.UTC()
  1186. if rc.s.c.loc != nil {
  1187. t = t.In(rc.s.c.loc)
  1188. }
  1189. dest[i] = t
  1190. case "boolean":
  1191. dest[i] = val > 0
  1192. default:
  1193. dest[i] = val
  1194. }
  1195. case C.SQLITE_FLOAT:
  1196. dest[i] = float64(C.sqlite3_column_double(rc.s.s, C.int(i)))
  1197. case C.SQLITE_BLOB:
  1198. p := C.sqlite3_column_blob(rc.s.s, C.int(i))
  1199. if p == nil {
  1200. dest[i] = nil
  1201. continue
  1202. }
  1203. n := int(C.sqlite3_column_bytes(rc.s.s, C.int(i)))
  1204. switch dest[i].(type) {
  1205. case sql.RawBytes:
  1206. dest[i] = (*[1 << 30]byte)(p)[0:n]
  1207. default:
  1208. slice := make([]byte, n)
  1209. copy(slice[:], (*[1 << 30]byte)(p)[0:n])
  1210. dest[i] = slice
  1211. }
  1212. case C.SQLITE_NULL:
  1213. dest[i] = nil
  1214. case C.SQLITE_TEXT:
  1215. var err error
  1216. var timeVal time.Time
  1217. n := int(C.sqlite3_column_bytes(rc.s.s, C.int(i)))
  1218. s := C.GoStringN((*C.char)(unsafe.Pointer(C.sqlite3_column_text(rc.s.s, C.int(i)))), C.int(n))
  1219. switch rc.decltype[i] {
  1220. case columnTimestamp, columnDatetime, columnDate:
  1221. var t time.Time
  1222. s = strings.TrimSuffix(s, "Z")
  1223. for _, format := range SQLiteTimestampFormats {
  1224. if timeVal, err = time.ParseInLocation(format, s, time.UTC); err == nil {
  1225. t = timeVal
  1226. break
  1227. }
  1228. }
  1229. if err != nil {
  1230. // The column is a time value, so return the zero time on parse failure.
  1231. t = time.Time{}
  1232. }
  1233. if rc.s.c.loc != nil {
  1234. t = t.In(rc.s.c.loc)
  1235. }
  1236. dest[i] = t
  1237. default:
  1238. dest[i] = []byte(s)
  1239. }
  1240. }
  1241. }
  1242. return nil
  1243. }