sqlite3.go 67 KB

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