sqlite3.go 55 KB

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