sqlite3.go 36 KB

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