sqlite3.go 35 KB

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