sqlite3.go 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282
  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
  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 int
  352. cols []string
  353. decltype []string
  354. cls bool
  355. closed bool
  356. ctx context.Context // no better alternative to pass context into Next() method
  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. return nil, fmt.Errorf("not enough args to execute query: want %d got %d", na, len(args)-start)
  841. }
  842. // consume the number of arguments used in the current
  843. // statement and append all named arguments not contained
  844. // therein
  845. stmtArgs = append(stmtArgs, args[start:start+na]...)
  846. for i := range args {
  847. if (i < start || i >= na) && args[i].Name != "" {
  848. stmtArgs = append(stmtArgs, args[i])
  849. }
  850. }
  851. for i := range stmtArgs {
  852. stmtArgs[i].Ordinal = i + 1
  853. }
  854. rows, err := s.(*SQLiteStmt).query(ctx, stmtArgs)
  855. if err != nil && err != driver.ErrSkip {
  856. s.Close()
  857. return rows, err
  858. }
  859. start += na
  860. tail := s.(*SQLiteStmt).t
  861. if tail == "" {
  862. return rows, nil
  863. }
  864. rows.Close()
  865. s.Close()
  866. query = tail
  867. }
  868. }
  869. // Begin transaction.
  870. func (c *SQLiteConn) Begin() (driver.Tx, error) {
  871. return c.begin(context.Background())
  872. }
  873. func (c *SQLiteConn) begin(ctx context.Context) (driver.Tx, error) {
  874. if _, err := c.exec(ctx, c.txlock, nil); err != nil {
  875. return nil, err
  876. }
  877. return &SQLiteTx{c}, nil
  878. }
  879. // Open database and return a new connection.
  880. //
  881. // A pragma can take either zero or one argument.
  882. // The argument is may be either in parentheses or it may be separated from
  883. // the pragma name by an equal sign. The two syntaxes yield identical results.
  884. // In many pragmas, the argument is a boolean. The boolean can be one of:
  885. //
  886. // 1 yes true on
  887. // 0 no false off
  888. //
  889. // You can specify a DSN string using a URI as the filename.
  890. //
  891. // test.db
  892. // file:test.db?cache=shared&mode=memory
  893. // :memory:
  894. // file::memory:
  895. //
  896. // mode
  897. // Access mode of the database.
  898. // https://www.sqlite.org/c3ref/open.html
  899. // Values:
  900. // - ro
  901. // - rw
  902. // - rwc
  903. // - memory
  904. //
  905. // cache
  906. // SQLite Shared-Cache Mode
  907. // https://www.sqlite.org/sharedcache.html
  908. // Values:
  909. // - shared
  910. // - private
  911. //
  912. // immutable=Boolean
  913. // The immutable parameter is a boolean query parameter that indicates
  914. // that the database file is stored on read-only media. When immutable is set,
  915. // SQLite assumes that the database file cannot be changed,
  916. // even by a process with higher privilege,
  917. // and so the database is opened read-only and all locking and change detection is disabled.
  918. // Caution: Setting the immutable property on a database file that
  919. // does in fact change can result in incorrect query results and/or SQLITE_CORRUPT errors.
  920. //
  921. // go-sqlite3 adds the following query parameters to those used by SQLite:
  922. //
  923. // _loc=XXX
  924. // Specify location of time format. It's possible to specify "auto".
  925. //
  926. // _mutex=XXX
  927. // Specify mutex mode. XXX can be "no", "full".
  928. //
  929. // _txlock=XXX
  930. // Specify locking behavior for transactions. XXX can be "immediate",
  931. // "deferred", "exclusive".
  932. //
  933. // _auto_vacuum=X | _vacuum=X
  934. // 0 | none - Auto Vacuum disabled
  935. // 1 | full - Auto Vacuum FULL
  936. // 2 | incremental - Auto Vacuum Incremental
  937. //
  938. // _busy_timeout=XXX"| _timeout=XXX
  939. // Specify value for sqlite3_busy_timeout.
  940. //
  941. // _case_sensitive_like=Boolean | _cslike=Boolean
  942. // https://www.sqlite.org/pragma.html#pragma_case_sensitive_like
  943. // Default or disabled the LIKE operation is case-insensitive.
  944. // When enabling this options behaviour of LIKE will become case-sensitive.
  945. //
  946. // _defer_foreign_keys=Boolean | _defer_fk=Boolean
  947. // Defer Foreign Keys until outermost transaction is committed.
  948. //
  949. // _foreign_keys=Boolean | _fk=Boolean
  950. // Enable or disable enforcement of foreign keys.
  951. //
  952. // _ignore_check_constraints=Boolean
  953. // This pragma enables or disables the enforcement of CHECK constraints.
  954. // The default setting is off, meaning that CHECK constraints are enforced by default.
  955. //
  956. // _journal_mode=MODE | _journal=MODE
  957. // Set journal mode for the databases associated with the current connection.
  958. // https://www.sqlite.org/pragma.html#pragma_journal_mode
  959. //
  960. // _locking_mode=X | _locking=X
  961. // Sets the database connection locking-mode.
  962. // The locking-mode is either NORMAL or EXCLUSIVE.
  963. // https://www.sqlite.org/pragma.html#pragma_locking_mode
  964. //
  965. // _query_only=Boolean
  966. // The query_only pragma prevents all changes to database files when enabled.
  967. //
  968. // _recursive_triggers=Boolean | _rt=Boolean
  969. // Enable or disable recursive triggers.
  970. //
  971. // _secure_delete=Boolean|FAST
  972. // When secure_delete is on, SQLite overwrites deleted content with zeros.
  973. // https://www.sqlite.org/pragma.html#pragma_secure_delete
  974. //
  975. // _synchronous=X | _sync=X
  976. // Change the setting of the "synchronous" flag.
  977. // https://www.sqlite.org/pragma.html#pragma_synchronous
  978. //
  979. // _writable_schema=Boolean
  980. // When this pragma is on, the SQLITE_MASTER tables in which database
  981. // can be changed using ordinary UPDATE, INSERT, and DELETE statements.
  982. // Warning: misuse of this pragma can easily result in a corrupt database file.
  983. func (d *SQLiteDriver) Open(dsn string) (driver.Conn, error) {
  984. if C.sqlite3_threadsafe() == 0 {
  985. return nil, errors.New("sqlite library was not compiled for thread-safe operation")
  986. }
  987. var pkey string
  988. // Options
  989. var loc *time.Location
  990. authCreate := false
  991. authUser := ""
  992. authPass := ""
  993. authCrypt := ""
  994. authSalt := ""
  995. mutex := C.int(C.SQLITE_OPEN_FULLMUTEX)
  996. txlock := "BEGIN"
  997. // PRAGMA's
  998. autoVacuum := -1
  999. busyTimeout := 5000
  1000. caseSensitiveLike := -1
  1001. deferForeignKeys := -1
  1002. foreignKeys := -1
  1003. ignoreCheckConstraints := -1
  1004. var journalMode string
  1005. lockingMode := "NORMAL"
  1006. queryOnly := -1
  1007. recursiveTriggers := -1
  1008. secureDelete := "DEFAULT"
  1009. synchronousMode := "NORMAL"
  1010. writableSchema := -1
  1011. vfsName := ""
  1012. var cacheSize *int64
  1013. pos := strings.IndexRune(dsn, '?')
  1014. if pos >= 1 {
  1015. params, err := url.ParseQuery(dsn[pos+1:])
  1016. if err != nil {
  1017. return nil, err
  1018. }
  1019. // Authentication
  1020. if _, ok := params["_auth"]; ok {
  1021. authCreate = true
  1022. }
  1023. if val := params.Get("_auth_user"); val != "" {
  1024. authUser = val
  1025. }
  1026. if val := params.Get("_auth_pass"); val != "" {
  1027. authPass = val
  1028. }
  1029. if val := params.Get("_auth_crypt"); val != "" {
  1030. authCrypt = val
  1031. }
  1032. if val := params.Get("_auth_salt"); val != "" {
  1033. authSalt = val
  1034. }
  1035. // _loc
  1036. if val := params.Get("_loc"); val != "" {
  1037. switch strings.ToLower(val) {
  1038. case "auto":
  1039. loc = time.Local
  1040. default:
  1041. loc, err = time.LoadLocation(val)
  1042. if err != nil {
  1043. return nil, fmt.Errorf("Invalid _loc: %v: %v", val, err)
  1044. }
  1045. }
  1046. }
  1047. // _mutex
  1048. if val := params.Get("_mutex"); val != "" {
  1049. switch strings.ToLower(val) {
  1050. case "no":
  1051. mutex = C.SQLITE_OPEN_NOMUTEX
  1052. case "full":
  1053. mutex = C.SQLITE_OPEN_FULLMUTEX
  1054. default:
  1055. return nil, fmt.Errorf("Invalid _mutex: %v", val)
  1056. }
  1057. }
  1058. // _txlock
  1059. if val := params.Get("_txlock"); val != "" {
  1060. switch strings.ToLower(val) {
  1061. case "immediate":
  1062. txlock = "BEGIN IMMEDIATE"
  1063. case "exclusive":
  1064. txlock = "BEGIN EXCLUSIVE"
  1065. case "deferred":
  1066. txlock = "BEGIN"
  1067. default:
  1068. return nil, fmt.Errorf("Invalid _txlock: %v", val)
  1069. }
  1070. }
  1071. // Auto Vacuum (_vacuum)
  1072. //
  1073. // https://www.sqlite.org/pragma.html#pragma_auto_vacuum
  1074. //
  1075. pkey = "" // Reset pkey
  1076. if _, ok := params["_auto_vacuum"]; ok {
  1077. pkey = "_auto_vacuum"
  1078. }
  1079. if _, ok := params["_vacuum"]; ok {
  1080. pkey = "_vacuum"
  1081. }
  1082. if val := params.Get(pkey); val != "" {
  1083. switch strings.ToLower(val) {
  1084. case "0", "none":
  1085. autoVacuum = 0
  1086. case "1", "full":
  1087. autoVacuum = 1
  1088. case "2", "incremental":
  1089. autoVacuum = 2
  1090. default:
  1091. return nil, fmt.Errorf("Invalid _auto_vacuum: %v, expecting value of '0 NONE 1 FULL 2 INCREMENTAL'", val)
  1092. }
  1093. }
  1094. // Busy Timeout (_busy_timeout)
  1095. //
  1096. // https://www.sqlite.org/pragma.html#pragma_busy_timeout
  1097. //
  1098. pkey = "" // Reset pkey
  1099. if _, ok := params["_busy_timeout"]; ok {
  1100. pkey = "_busy_timeout"
  1101. }
  1102. if _, ok := params["_timeout"]; ok {
  1103. pkey = "_timeout"
  1104. }
  1105. if val := params.Get(pkey); val != "" {
  1106. iv, err := strconv.ParseInt(val, 10, 64)
  1107. if err != nil {
  1108. return nil, fmt.Errorf("Invalid _busy_timeout: %v: %v", val, err)
  1109. }
  1110. busyTimeout = int(iv)
  1111. }
  1112. // Case Sensitive Like (_cslike)
  1113. //
  1114. // https://www.sqlite.org/pragma.html#pragma_case_sensitive_like
  1115. //
  1116. pkey = "" // Reset pkey
  1117. if _, ok := params["_case_sensitive_like"]; ok {
  1118. pkey = "_case_sensitive_like"
  1119. }
  1120. if _, ok := params["_cslike"]; ok {
  1121. pkey = "_cslike"
  1122. }
  1123. if val := params.Get(pkey); val != "" {
  1124. switch strings.ToLower(val) {
  1125. case "0", "no", "false", "off":
  1126. caseSensitiveLike = 0
  1127. case "1", "yes", "true", "on":
  1128. caseSensitiveLike = 1
  1129. default:
  1130. return nil, fmt.Errorf("Invalid _case_sensitive_like: %v, expecting boolean value of '0 1 false true no yes off on'", val)
  1131. }
  1132. }
  1133. // Defer Foreign Keys (_defer_foreign_keys | _defer_fk)
  1134. //
  1135. // https://www.sqlite.org/pragma.html#pragma_defer_foreign_keys
  1136. //
  1137. pkey = "" // Reset pkey
  1138. if _, ok := params["_defer_foreign_keys"]; ok {
  1139. pkey = "_defer_foreign_keys"
  1140. }
  1141. if _, ok := params["_defer_fk"]; ok {
  1142. pkey = "_defer_fk"
  1143. }
  1144. if val := params.Get(pkey); val != "" {
  1145. switch strings.ToLower(val) {
  1146. case "0", "no", "false", "off":
  1147. deferForeignKeys = 0
  1148. case "1", "yes", "true", "on":
  1149. deferForeignKeys = 1
  1150. default:
  1151. return nil, fmt.Errorf("Invalid _defer_foreign_keys: %v, expecting boolean value of '0 1 false true no yes off on'", val)
  1152. }
  1153. }
  1154. // Foreign Keys (_foreign_keys | _fk)
  1155. //
  1156. // https://www.sqlite.org/pragma.html#pragma_foreign_keys
  1157. //
  1158. pkey = "" // Reset pkey
  1159. if _, ok := params["_foreign_keys"]; ok {
  1160. pkey = "_foreign_keys"
  1161. }
  1162. if _, ok := params["_fk"]; ok {
  1163. pkey = "_fk"
  1164. }
  1165. if val := params.Get(pkey); val != "" {
  1166. switch strings.ToLower(val) {
  1167. case "0", "no", "false", "off":
  1168. foreignKeys = 0
  1169. case "1", "yes", "true", "on":
  1170. foreignKeys = 1
  1171. default:
  1172. return nil, fmt.Errorf("Invalid _foreign_keys: %v, expecting boolean value of '0 1 false true no yes off on'", val)
  1173. }
  1174. }
  1175. // Ignore CHECK Constrains (_ignore_check_constraints)
  1176. //
  1177. // https://www.sqlite.org/pragma.html#pragma_ignore_check_constraints
  1178. //
  1179. if val := params.Get("_ignore_check_constraints"); val != "" {
  1180. switch strings.ToLower(val) {
  1181. case "0", "no", "false", "off":
  1182. ignoreCheckConstraints = 0
  1183. case "1", "yes", "true", "on":
  1184. ignoreCheckConstraints = 1
  1185. default:
  1186. return nil, fmt.Errorf("Invalid _ignore_check_constraints: %v, expecting boolean value of '0 1 false true no yes off on'", val)
  1187. }
  1188. }
  1189. // Journal Mode (_journal_mode | _journal)
  1190. //
  1191. // https://www.sqlite.org/pragma.html#pragma_journal_mode
  1192. //
  1193. pkey = "" // Reset pkey
  1194. if _, ok := params["_journal_mode"]; ok {
  1195. pkey = "_journal_mode"
  1196. }
  1197. if _, ok := params["_journal"]; ok {
  1198. pkey = "_journal"
  1199. }
  1200. if val := params.Get(pkey); val != "" {
  1201. switch strings.ToUpper(val) {
  1202. case "DELETE", "TRUNCATE", "PERSIST", "MEMORY", "OFF":
  1203. journalMode = strings.ToUpper(val)
  1204. case "WAL":
  1205. journalMode = strings.ToUpper(val)
  1206. // For WAL Mode set Synchronous Mode to 'NORMAL'
  1207. // See https://www.sqlite.org/pragma.html#pragma_synchronous
  1208. synchronousMode = "NORMAL"
  1209. default:
  1210. return nil, fmt.Errorf("Invalid _journal: %v, expecting value of 'DELETE TRUNCATE PERSIST MEMORY WAL OFF'", val)
  1211. }
  1212. }
  1213. // Locking Mode (_locking)
  1214. //
  1215. // https://www.sqlite.org/pragma.html#pragma_locking_mode
  1216. //
  1217. pkey = "" // Reset pkey
  1218. if _, ok := params["_locking_mode"]; ok {
  1219. pkey = "_locking_mode"
  1220. }
  1221. if _, ok := params["_locking"]; ok {
  1222. pkey = "_locking"
  1223. }
  1224. if val := params.Get(pkey); val != "" {
  1225. switch strings.ToUpper(val) {
  1226. case "NORMAL", "EXCLUSIVE":
  1227. lockingMode = strings.ToUpper(val)
  1228. default:
  1229. return nil, fmt.Errorf("Invalid _locking_mode: %v, expecting value of 'NORMAL EXCLUSIVE", val)
  1230. }
  1231. }
  1232. // Query Only (_query_only)
  1233. //
  1234. // https://www.sqlite.org/pragma.html#pragma_query_only
  1235. //
  1236. if val := params.Get("_query_only"); val != "" {
  1237. switch strings.ToLower(val) {
  1238. case "0", "no", "false", "off":
  1239. queryOnly = 0
  1240. case "1", "yes", "true", "on":
  1241. queryOnly = 1
  1242. default:
  1243. return nil, fmt.Errorf("Invalid _query_only: %v, expecting boolean value of '0 1 false true no yes off on'", val)
  1244. }
  1245. }
  1246. // Recursive Triggers (_recursive_triggers)
  1247. //
  1248. // https://www.sqlite.org/pragma.html#pragma_recursive_triggers
  1249. //
  1250. pkey = "" // Reset pkey
  1251. if _, ok := params["_recursive_triggers"]; ok {
  1252. pkey = "_recursive_triggers"
  1253. }
  1254. if _, ok := params["_rt"]; ok {
  1255. pkey = "_rt"
  1256. }
  1257. if val := params.Get(pkey); val != "" {
  1258. switch strings.ToLower(val) {
  1259. case "0", "no", "false", "off":
  1260. recursiveTriggers = 0
  1261. case "1", "yes", "true", "on":
  1262. recursiveTriggers = 1
  1263. default:
  1264. return nil, fmt.Errorf("Invalid _recursive_triggers: %v, expecting boolean value of '0 1 false true no yes off on'", val)
  1265. }
  1266. }
  1267. // Secure Delete (_secure_delete)
  1268. //
  1269. // https://www.sqlite.org/pragma.html#pragma_secure_delete
  1270. //
  1271. if val := params.Get("_secure_delete"); val != "" {
  1272. switch strings.ToLower(val) {
  1273. case "0", "no", "false", "off":
  1274. secureDelete = "OFF"
  1275. case "1", "yes", "true", "on":
  1276. secureDelete = "ON"
  1277. case "fast":
  1278. secureDelete = "FAST"
  1279. default:
  1280. return nil, fmt.Errorf("Invalid _secure_delete: %v, expecting boolean value of '0 1 false true no yes off on fast'", val)
  1281. }
  1282. }
  1283. // Synchronous Mode (_synchronous | _sync)
  1284. //
  1285. // https://www.sqlite.org/pragma.html#pragma_synchronous
  1286. //
  1287. pkey = "" // Reset pkey
  1288. if _, ok := params["_synchronous"]; ok {
  1289. pkey = "_synchronous"
  1290. }
  1291. if _, ok := params["_sync"]; ok {
  1292. pkey = "_sync"
  1293. }
  1294. if val := params.Get(pkey); val != "" {
  1295. switch strings.ToUpper(val) {
  1296. case "0", "OFF", "1", "NORMAL", "2", "FULL", "3", "EXTRA":
  1297. synchronousMode = strings.ToUpper(val)
  1298. default:
  1299. return nil, fmt.Errorf("Invalid _synchronous: %v, expecting value of '0 OFF 1 NORMAL 2 FULL 3 EXTRA'", val)
  1300. }
  1301. }
  1302. // Writable Schema (_writeable_schema)
  1303. //
  1304. // https://www.sqlite.org/pragma.html#pragma_writeable_schema
  1305. //
  1306. if val := params.Get("_writable_schema"); val != "" {
  1307. switch strings.ToLower(val) {
  1308. case "0", "no", "false", "off":
  1309. writableSchema = 0
  1310. case "1", "yes", "true", "on":
  1311. writableSchema = 1
  1312. default:
  1313. return nil, fmt.Errorf("Invalid _writable_schema: %v, expecting boolean value of '0 1 false true no yes off on'", val)
  1314. }
  1315. }
  1316. // Cache size (_cache_size)
  1317. //
  1318. // https://sqlite.org/pragma.html#pragma_cache_size
  1319. //
  1320. if val := params.Get("_cache_size"); val != "" {
  1321. iv, err := strconv.ParseInt(val, 10, 64)
  1322. if err != nil {
  1323. return nil, fmt.Errorf("Invalid _cache_size: %v: %v", val, err)
  1324. }
  1325. cacheSize = &iv
  1326. }
  1327. if val := params.Get("vfs"); val != "" {
  1328. vfsName = val
  1329. }
  1330. if !strings.HasPrefix(dsn, "file:") {
  1331. dsn = dsn[:pos]
  1332. }
  1333. }
  1334. var db *C.sqlite3
  1335. name := C.CString(dsn)
  1336. defer C.free(unsafe.Pointer(name))
  1337. var vfs *C.char
  1338. if vfsName != "" {
  1339. vfs = C.CString(vfsName)
  1340. defer C.free(unsafe.Pointer(vfs))
  1341. }
  1342. rv := C._sqlite3_open_v2(name, &db,
  1343. mutex|C.SQLITE_OPEN_READWRITE|C.SQLITE_OPEN_CREATE,
  1344. vfs)
  1345. if rv != 0 {
  1346. // Save off the error _before_ closing the database.
  1347. // This is safe even if db is nil.
  1348. err := lastError(db)
  1349. if db != nil {
  1350. C.sqlite3_close_v2(db)
  1351. }
  1352. return nil, err
  1353. }
  1354. if db == nil {
  1355. return nil, errors.New("sqlite succeeded without returning a database")
  1356. }
  1357. exec := func(s string) error {
  1358. cs := C.CString(s)
  1359. rv := C.sqlite3_exec(db, cs, nil, nil, nil)
  1360. C.free(unsafe.Pointer(cs))
  1361. if rv != C.SQLITE_OK {
  1362. return lastError(db)
  1363. }
  1364. return nil
  1365. }
  1366. // Busy timeout
  1367. if err := exec(fmt.Sprintf("PRAGMA busy_timeout = %d;", busyTimeout)); err != nil {
  1368. C.sqlite3_close_v2(db)
  1369. return nil, err
  1370. }
  1371. // USER AUTHENTICATION
  1372. //
  1373. // User Authentication is always performed even when
  1374. // sqlite_userauth is not compiled in, because without user authentication
  1375. // the authentication is a no-op.
  1376. //
  1377. // Workflow
  1378. // - Authenticate
  1379. // ON::SUCCESS => Continue
  1380. // ON::SQLITE_AUTH => Return error and exit Open(...)
  1381. //
  1382. // - Activate User Authentication
  1383. // Check if the user wants to activate User Authentication.
  1384. // If so then first create a temporary AuthConn to the database
  1385. // This is possible because we are already successfully authenticated.
  1386. //
  1387. // - Check if `sqlite_user`` table exists
  1388. // YES => Add the provided user from DSN as Admin User and
  1389. // activate user authentication.
  1390. // NO => Continue
  1391. //
  1392. // Create connection to SQLite
  1393. conn := &SQLiteConn{db: db, loc: loc, txlock: txlock}
  1394. // Password Cipher has to be registered before authentication
  1395. if len(authCrypt) > 0 {
  1396. switch strings.ToUpper(authCrypt) {
  1397. case "SHA1":
  1398. if err := conn.RegisterFunc("sqlite_crypt", CryptEncoderSHA1, true); err != nil {
  1399. return nil, fmt.Errorf("CryptEncoderSHA1: %s", err)
  1400. }
  1401. case "SSHA1":
  1402. if len(authSalt) == 0 {
  1403. return nil, fmt.Errorf("_auth_crypt=ssha1, requires _auth_salt")
  1404. }
  1405. if err := conn.RegisterFunc("sqlite_crypt", CryptEncoderSSHA1(authSalt), true); err != nil {
  1406. return nil, fmt.Errorf("CryptEncoderSSHA1: %s", err)
  1407. }
  1408. case "SHA256":
  1409. if err := conn.RegisterFunc("sqlite_crypt", CryptEncoderSHA256, true); err != nil {
  1410. return nil, fmt.Errorf("CryptEncoderSHA256: %s", err)
  1411. }
  1412. case "SSHA256":
  1413. if len(authSalt) == 0 {
  1414. return nil, fmt.Errorf("_auth_crypt=ssha256, requires _auth_salt")
  1415. }
  1416. if err := conn.RegisterFunc("sqlite_crypt", CryptEncoderSSHA256(authSalt), true); err != nil {
  1417. return nil, fmt.Errorf("CryptEncoderSSHA256: %s", err)
  1418. }
  1419. case "SHA384":
  1420. if err := conn.RegisterFunc("sqlite_crypt", CryptEncoderSHA384, true); err != nil {
  1421. return nil, fmt.Errorf("CryptEncoderSHA384: %s", err)
  1422. }
  1423. case "SSHA384":
  1424. if len(authSalt) == 0 {
  1425. return nil, fmt.Errorf("_auth_crypt=ssha384, requires _auth_salt")
  1426. }
  1427. if err := conn.RegisterFunc("sqlite_crypt", CryptEncoderSSHA384(authSalt), true); err != nil {
  1428. return nil, fmt.Errorf("CryptEncoderSSHA384: %s", err)
  1429. }
  1430. case "SHA512":
  1431. if err := conn.RegisterFunc("sqlite_crypt", CryptEncoderSHA512, true); err != nil {
  1432. return nil, fmt.Errorf("CryptEncoderSHA512: %s", err)
  1433. }
  1434. case "SSHA512":
  1435. if len(authSalt) == 0 {
  1436. return nil, fmt.Errorf("_auth_crypt=ssha512, requires _auth_salt")
  1437. }
  1438. if err := conn.RegisterFunc("sqlite_crypt", CryptEncoderSSHA512(authSalt), true); err != nil {
  1439. return nil, fmt.Errorf("CryptEncoderSSHA512: %s", err)
  1440. }
  1441. }
  1442. }
  1443. // Preform Authentication
  1444. if err := conn.Authenticate(authUser, authPass); err != nil {
  1445. return nil, err
  1446. }
  1447. // Register: authenticate
  1448. // Authenticate will perform an authentication of the provided username
  1449. // and password against the database.
  1450. //
  1451. // If a database contains the SQLITE_USER table, then the
  1452. // call to Authenticate must be invoked with an
  1453. // appropriate username and password prior to enable read and write
  1454. //access to the database.
  1455. //
  1456. // Return SQLITE_OK on success or SQLITE_ERROR if the username/password
  1457. // combination is incorrect or unknown.
  1458. //
  1459. // If the SQLITE_USER table is not present in the database file, then
  1460. // this interface is a harmless no-op returnning SQLITE_OK.
  1461. if err := conn.RegisterFunc("authenticate", conn.authenticate, true); err != nil {
  1462. return nil, err
  1463. }
  1464. //
  1465. // Register: auth_user_add
  1466. // auth_user_add can be used (by an admin user only)
  1467. // to create a new user. When called on a no-authentication-required
  1468. // database, this routine converts the database into an authentication-
  1469. // required database, automatically makes the added user an
  1470. // administrator, and logs in the current connection as that user.
  1471. // The AuthUserAdd only works for the "main" database, not
  1472. // for any ATTACH-ed databases. Any call to AuthUserAdd by a
  1473. // non-admin user results in an error.
  1474. if err := conn.RegisterFunc("auth_user_add", conn.authUserAdd, true); err != nil {
  1475. return nil, err
  1476. }
  1477. //
  1478. // Register: auth_user_change
  1479. // auth_user_change can be used to change a users
  1480. // login credentials or admin privilege. Any user can change their own
  1481. // login credentials. Only an admin user can change another users login
  1482. // credentials or admin privilege setting. No user may change their own
  1483. // admin privilege setting.
  1484. if err := conn.RegisterFunc("auth_user_change", conn.authUserChange, true); err != nil {
  1485. return nil, err
  1486. }
  1487. //
  1488. // Register: auth_user_delete
  1489. // auth_user_delete can be used (by an admin user only)
  1490. // to delete a user. The currently logged-in user cannot be deleted,
  1491. // which guarantees that there is always an admin user and hence that
  1492. // the database cannot be converted into a no-authentication-required
  1493. // database.
  1494. if err := conn.RegisterFunc("auth_user_delete", conn.authUserDelete, true); err != nil {
  1495. return nil, err
  1496. }
  1497. // Register: auth_enabled
  1498. // auth_enabled can be used to check if user authentication is enabled
  1499. if err := conn.RegisterFunc("auth_enabled", conn.authEnabled, true); err != nil {
  1500. return nil, err
  1501. }
  1502. // Auto Vacuum
  1503. // Moved auto_vacuum command, the user preference for auto_vacuum needs to be implemented directly after
  1504. // the authentication and before the sqlite_user table gets created if the user
  1505. // decides to activate User Authentication because
  1506. // auto_vacuum needs to be set before any tables are created
  1507. // and activating user authentication creates the internal table `sqlite_user`.
  1508. if autoVacuum > -1 {
  1509. if err := exec(fmt.Sprintf("PRAGMA auto_vacuum = %d;", autoVacuum)); err != nil {
  1510. C.sqlite3_close_v2(db)
  1511. return nil, err
  1512. }
  1513. }
  1514. // Check if user wants to activate User Authentication
  1515. if authCreate {
  1516. // Before going any further, we need to check that the user
  1517. // has provided an username and password within the DSN.
  1518. // We are not allowed to continue.
  1519. if len(authUser) == 0 {
  1520. return nil, fmt.Errorf("Missing '_auth_user' while user authentication was requested with '_auth'")
  1521. }
  1522. if len(authPass) == 0 {
  1523. return nil, fmt.Errorf("Missing '_auth_pass' while user authentication was requested with '_auth'")
  1524. }
  1525. // Check if User Authentication is Enabled
  1526. authExists := conn.AuthEnabled()
  1527. if !authExists {
  1528. if err := conn.AuthUserAdd(authUser, authPass, true); err != nil {
  1529. return nil, err
  1530. }
  1531. }
  1532. }
  1533. // Case Sensitive LIKE
  1534. if caseSensitiveLike > -1 {
  1535. if err := exec(fmt.Sprintf("PRAGMA case_sensitive_like = %d;", caseSensitiveLike)); err != nil {
  1536. C.sqlite3_close_v2(db)
  1537. return nil, err
  1538. }
  1539. }
  1540. // Defer Foreign Keys
  1541. if deferForeignKeys > -1 {
  1542. if err := exec(fmt.Sprintf("PRAGMA defer_foreign_keys = %d;", deferForeignKeys)); err != nil {
  1543. C.sqlite3_close_v2(db)
  1544. return nil, err
  1545. }
  1546. }
  1547. // Forgein Keys
  1548. if foreignKeys > -1 {
  1549. if err := exec(fmt.Sprintf("PRAGMA foreign_keys = %d;", foreignKeys)); err != nil {
  1550. C.sqlite3_close_v2(db)
  1551. return nil, err
  1552. }
  1553. }
  1554. // Ignore CHECK Constraints
  1555. if ignoreCheckConstraints > -1 {
  1556. if err := exec(fmt.Sprintf("PRAGMA ignore_check_constraints = %d;", ignoreCheckConstraints)); err != nil {
  1557. C.sqlite3_close_v2(db)
  1558. return nil, err
  1559. }
  1560. }
  1561. // Journal Mode
  1562. if journalMode != "" {
  1563. if err := exec(fmt.Sprintf("PRAGMA journal_mode = %s;", journalMode)); err != nil {
  1564. C.sqlite3_close_v2(db)
  1565. return nil, err
  1566. }
  1567. }
  1568. // Locking Mode
  1569. // Because the default is NORMAL and this is not changed in this package
  1570. // by using the compile time SQLITE_DEFAULT_LOCKING_MODE this PRAGMA can always be executed
  1571. if err := exec(fmt.Sprintf("PRAGMA locking_mode = %s;", lockingMode)); err != nil {
  1572. C.sqlite3_close_v2(db)
  1573. return nil, err
  1574. }
  1575. // Query Only
  1576. if queryOnly > -1 {
  1577. if err := exec(fmt.Sprintf("PRAGMA query_only = %d;", queryOnly)); err != nil {
  1578. C.sqlite3_close_v2(db)
  1579. return nil, err
  1580. }
  1581. }
  1582. // Recursive Triggers
  1583. if recursiveTriggers > -1 {
  1584. if err := exec(fmt.Sprintf("PRAGMA recursive_triggers = %d;", recursiveTriggers)); err != nil {
  1585. C.sqlite3_close_v2(db)
  1586. return nil, err
  1587. }
  1588. }
  1589. // Secure Delete
  1590. //
  1591. // Because this package can set the compile time flag SQLITE_SECURE_DELETE with a build tag
  1592. // the default value for secureDelete var is 'DEFAULT' this way
  1593. // you can compile with secure_delete 'ON' and disable it for a specific database connection.
  1594. if secureDelete != "DEFAULT" {
  1595. if err := exec(fmt.Sprintf("PRAGMA secure_delete = %s;", secureDelete)); err != nil {
  1596. C.sqlite3_close_v2(db)
  1597. return nil, err
  1598. }
  1599. }
  1600. // Synchronous Mode
  1601. //
  1602. // Because default is NORMAL this statement is always executed
  1603. if err := exec(fmt.Sprintf("PRAGMA synchronous = %s;", synchronousMode)); err != nil {
  1604. conn.Close()
  1605. return nil, err
  1606. }
  1607. // Writable Schema
  1608. if writableSchema > -1 {
  1609. if err := exec(fmt.Sprintf("PRAGMA writable_schema = %d;", writableSchema)); err != nil {
  1610. C.sqlite3_close_v2(db)
  1611. return nil, err
  1612. }
  1613. }
  1614. // Cache Size
  1615. if cacheSize != nil {
  1616. if err := exec(fmt.Sprintf("PRAGMA cache_size = %d;", *cacheSize)); err != nil {
  1617. C.sqlite3_close_v2(db)
  1618. return nil, err
  1619. }
  1620. }
  1621. if len(d.Extensions) > 0 {
  1622. if err := conn.loadExtensions(d.Extensions); err != nil {
  1623. conn.Close()
  1624. return nil, err
  1625. }
  1626. }
  1627. if d.ConnectHook != nil {
  1628. if err := d.ConnectHook(conn); err != nil {
  1629. conn.Close()
  1630. return nil, err
  1631. }
  1632. }
  1633. runtime.SetFinalizer(conn, (*SQLiteConn).Close)
  1634. return conn, nil
  1635. }
  1636. // Close the connection.
  1637. func (c *SQLiteConn) Close() error {
  1638. rv := C.sqlite3_close_v2(c.db)
  1639. if rv != C.SQLITE_OK {
  1640. return c.lastError()
  1641. }
  1642. deleteHandles(c)
  1643. c.mu.Lock()
  1644. c.db = nil
  1645. c.mu.Unlock()
  1646. runtime.SetFinalizer(c, nil)
  1647. return nil
  1648. }
  1649. func (c *SQLiteConn) dbConnOpen() bool {
  1650. if c == nil {
  1651. return false
  1652. }
  1653. c.mu.Lock()
  1654. defer c.mu.Unlock()
  1655. return c.db != nil
  1656. }
  1657. // Prepare the query string. Return a new statement.
  1658. func (c *SQLiteConn) Prepare(query string) (driver.Stmt, error) {
  1659. return c.prepare(context.Background(), query)
  1660. }
  1661. func (c *SQLiteConn) prepare(ctx context.Context, query string) (driver.Stmt, error) {
  1662. pquery := C.CString(query)
  1663. defer C.free(unsafe.Pointer(pquery))
  1664. var s *C.sqlite3_stmt
  1665. var tail *C.char
  1666. rv := C._sqlite3_prepare_v2_internal(c.db, pquery, C.int(-1), &s, &tail)
  1667. if rv != C.SQLITE_OK {
  1668. return nil, c.lastError()
  1669. }
  1670. var t string
  1671. if tail != nil && *tail != '\000' {
  1672. t = strings.TrimSpace(C.GoString(tail))
  1673. }
  1674. ss := &SQLiteStmt{c: c, s: s, t: t}
  1675. runtime.SetFinalizer(ss, (*SQLiteStmt).Close)
  1676. return ss, nil
  1677. }
  1678. // Run-Time Limit Categories.
  1679. // See: http://www.sqlite.org/c3ref/c_limit_attached.html
  1680. const (
  1681. SQLITE_LIMIT_LENGTH = C.SQLITE_LIMIT_LENGTH
  1682. SQLITE_LIMIT_SQL_LENGTH = C.SQLITE_LIMIT_SQL_LENGTH
  1683. SQLITE_LIMIT_COLUMN = C.SQLITE_LIMIT_COLUMN
  1684. SQLITE_LIMIT_EXPR_DEPTH = C.SQLITE_LIMIT_EXPR_DEPTH
  1685. SQLITE_LIMIT_COMPOUND_SELECT = C.SQLITE_LIMIT_COMPOUND_SELECT
  1686. SQLITE_LIMIT_VDBE_OP = C.SQLITE_LIMIT_VDBE_OP
  1687. SQLITE_LIMIT_FUNCTION_ARG = C.SQLITE_LIMIT_FUNCTION_ARG
  1688. SQLITE_LIMIT_ATTACHED = C.SQLITE_LIMIT_ATTACHED
  1689. SQLITE_LIMIT_LIKE_PATTERN_LENGTH = C.SQLITE_LIMIT_LIKE_PATTERN_LENGTH
  1690. SQLITE_LIMIT_VARIABLE_NUMBER = C.SQLITE_LIMIT_VARIABLE_NUMBER
  1691. SQLITE_LIMIT_TRIGGER_DEPTH = C.SQLITE_LIMIT_TRIGGER_DEPTH
  1692. SQLITE_LIMIT_WORKER_THREADS = C.SQLITE_LIMIT_WORKER_THREADS
  1693. )
  1694. // GetFilename returns the absolute path to the file containing
  1695. // the requested schema. When passed an empty string, it will
  1696. // instead use the database's default schema: "main".
  1697. // See: sqlite3_db_filename, https://www.sqlite.org/c3ref/db_filename.html
  1698. func (c *SQLiteConn) GetFilename(schemaName string) string {
  1699. if schemaName == "" {
  1700. schemaName = "main"
  1701. }
  1702. return C.GoString(C.sqlite3_db_filename(c.db, C.CString(schemaName)))
  1703. }
  1704. // GetLimit returns the current value of a run-time limit.
  1705. // See: sqlite3_limit, http://www.sqlite.org/c3ref/limit.html
  1706. func (c *SQLiteConn) GetLimit(id int) int {
  1707. return int(C._sqlite3_limit(c.db, C.int(id), C.int(-1)))
  1708. }
  1709. // SetLimit changes the value of a run-time limits.
  1710. // Then this method returns the prior value of the limit.
  1711. // See: sqlite3_limit, http://www.sqlite.org/c3ref/limit.html
  1712. func (c *SQLiteConn) SetLimit(id int, newVal int) int {
  1713. return int(C._sqlite3_limit(c.db, C.int(id), C.int(newVal)))
  1714. }
  1715. // SetFileControlInt invokes the xFileControl method on a given database. The
  1716. // dbName is the name of the database. It will default to "main" if left blank.
  1717. // The op is one of the opcodes prefixed by "SQLITE_FCNTL_". The arg argument
  1718. // and return code are both opcode-specific. Please see the SQLite documentation.
  1719. //
  1720. // This method is not thread-safe as the returned error code can be changed by
  1721. // another call if invoked concurrently.
  1722. //
  1723. // See: sqlite3_file_control, https://www.sqlite.org/c3ref/file_control.html
  1724. func (c *SQLiteConn) SetFileControlInt(dbName string, op int, arg int) error {
  1725. if dbName == "" {
  1726. dbName = "main"
  1727. }
  1728. cDBName := C.CString(dbName)
  1729. defer C.free(unsafe.Pointer(cDBName))
  1730. cArg := C.int(arg)
  1731. rv := C.sqlite3_file_control(c.db, cDBName, C.int(op), unsafe.Pointer(&cArg))
  1732. if rv != C.SQLITE_OK {
  1733. return c.lastError()
  1734. }
  1735. return nil
  1736. }
  1737. // Close the statement.
  1738. func (s *SQLiteStmt) Close() error {
  1739. s.mu.Lock()
  1740. defer s.mu.Unlock()
  1741. if s.closed {
  1742. return nil
  1743. }
  1744. s.closed = true
  1745. if !s.c.dbConnOpen() {
  1746. return errors.New("sqlite statement with already closed database connection")
  1747. }
  1748. rv := C.sqlite3_finalize(s.s)
  1749. s.s = nil
  1750. if rv != C.SQLITE_OK {
  1751. return s.c.lastError()
  1752. }
  1753. s.c = nil
  1754. runtime.SetFinalizer(s, nil)
  1755. return nil
  1756. }
  1757. // NumInput return a number of parameters.
  1758. func (s *SQLiteStmt) NumInput() int {
  1759. return int(C.sqlite3_bind_parameter_count(s.s))
  1760. }
  1761. var placeHolder = []byte{0}
  1762. func (s *SQLiteStmt) bind(args []driver.NamedValue) error {
  1763. rv := C.sqlite3_reset(s.s)
  1764. if rv != C.SQLITE_ROW && rv != C.SQLITE_OK && rv != C.SQLITE_DONE {
  1765. return s.c.lastError()
  1766. }
  1767. bindIndices := make([][3]int, len(args))
  1768. prefixes := []string{":", "@", "$"}
  1769. for i, v := range args {
  1770. bindIndices[i][0] = args[i].Ordinal
  1771. if v.Name != "" {
  1772. for j := range prefixes {
  1773. cname := C.CString(prefixes[j] + v.Name)
  1774. bindIndices[i][j] = int(C.sqlite3_bind_parameter_index(s.s, cname))
  1775. C.free(unsafe.Pointer(cname))
  1776. }
  1777. args[i].Ordinal = bindIndices[i][0]
  1778. }
  1779. }
  1780. for i, arg := range args {
  1781. for j := range bindIndices[i] {
  1782. if bindIndices[i][j] == 0 {
  1783. continue
  1784. }
  1785. n := C.int(bindIndices[i][j])
  1786. switch v := arg.Value.(type) {
  1787. case nil:
  1788. rv = C.sqlite3_bind_null(s.s, n)
  1789. case string:
  1790. if len(v) == 0 {
  1791. rv = C._sqlite3_bind_text(s.s, n, (*C.char)(unsafe.Pointer(&placeHolder[0])), C.int(0))
  1792. } else {
  1793. b := []byte(v)
  1794. rv = C._sqlite3_bind_text(s.s, n, (*C.char)(unsafe.Pointer(&b[0])), C.int(len(b)))
  1795. }
  1796. case int64:
  1797. rv = C.sqlite3_bind_int64(s.s, n, C.sqlite3_int64(v))
  1798. case bool:
  1799. if v {
  1800. rv = C.sqlite3_bind_int(s.s, n, 1)
  1801. } else {
  1802. rv = C.sqlite3_bind_int(s.s, n, 0)
  1803. }
  1804. case float64:
  1805. rv = C.sqlite3_bind_double(s.s, n, C.double(v))
  1806. case []byte:
  1807. if v == nil {
  1808. rv = C.sqlite3_bind_null(s.s, n)
  1809. } else {
  1810. ln := len(v)
  1811. if ln == 0 {
  1812. v = placeHolder
  1813. }
  1814. rv = C._sqlite3_bind_blob(s.s, n, unsafe.Pointer(&v[0]), C.int(ln))
  1815. }
  1816. case time.Time:
  1817. b := []byte(v.Format(SQLiteTimestampFormats[0]))
  1818. rv = C._sqlite3_bind_text(s.s, n, (*C.char)(unsafe.Pointer(&b[0])), C.int(len(b)))
  1819. }
  1820. if rv != C.SQLITE_OK {
  1821. return s.c.lastError()
  1822. }
  1823. }
  1824. }
  1825. return nil
  1826. }
  1827. // Query the statement with arguments. Return records.
  1828. func (s *SQLiteStmt) Query(args []driver.Value) (driver.Rows, error) {
  1829. list := make([]driver.NamedValue, len(args))
  1830. for i, v := range args {
  1831. list[i] = driver.NamedValue{
  1832. Ordinal: i + 1,
  1833. Value: v,
  1834. }
  1835. }
  1836. return s.query(context.Background(), list)
  1837. }
  1838. func (s *SQLiteStmt) query(ctx context.Context, args []driver.NamedValue) (driver.Rows, error) {
  1839. if err := s.bind(args); err != nil {
  1840. return nil, err
  1841. }
  1842. rows := &SQLiteRows{
  1843. s: s,
  1844. nc: int(C.sqlite3_column_count(s.s)),
  1845. cols: nil,
  1846. decltype: nil,
  1847. cls: s.cls,
  1848. closed: false,
  1849. ctx: ctx,
  1850. }
  1851. runtime.SetFinalizer(rows, (*SQLiteRows).Close)
  1852. return rows, nil
  1853. }
  1854. // LastInsertId return last inserted ID.
  1855. func (r *SQLiteResult) LastInsertId() (int64, error) {
  1856. return r.id, nil
  1857. }
  1858. // RowsAffected return how many rows affected.
  1859. func (r *SQLiteResult) RowsAffected() (int64, error) {
  1860. return r.changes, nil
  1861. }
  1862. // Exec execute the statement with arguments. Return result object.
  1863. func (s *SQLiteStmt) Exec(args []driver.Value) (driver.Result, error) {
  1864. list := make([]driver.NamedValue, len(args))
  1865. for i, v := range args {
  1866. list[i] = driver.NamedValue{
  1867. Ordinal: i + 1,
  1868. Value: v,
  1869. }
  1870. }
  1871. return s.exec(context.Background(), list)
  1872. }
  1873. func isInterruptErr(err error) bool {
  1874. sqliteErr, ok := err.(Error)
  1875. if ok {
  1876. return sqliteErr.Code == ErrInterrupt
  1877. }
  1878. return false
  1879. }
  1880. // exec executes a query that doesn't return rows. Attempts to honor context timeout.
  1881. func (s *SQLiteStmt) exec(ctx context.Context, args []driver.NamedValue) (driver.Result, error) {
  1882. if ctx.Done() == nil {
  1883. return s.execSync(args)
  1884. }
  1885. type result struct {
  1886. r driver.Result
  1887. err error
  1888. }
  1889. resultCh := make(chan result)
  1890. defer close(resultCh)
  1891. go func() {
  1892. r, err := s.execSync(args)
  1893. resultCh <- result{r, err}
  1894. }()
  1895. var rv result
  1896. select {
  1897. case rv = <-resultCh:
  1898. case <-ctx.Done():
  1899. select {
  1900. case rv = <-resultCh: // no need to interrupt, operation completed in db
  1901. default:
  1902. // this is still racy and can be no-op if executed between sqlite3_* calls in execSync.
  1903. C.sqlite3_interrupt(s.c.db)
  1904. rv = <-resultCh // wait for goroutine completed
  1905. if isInterruptErr(rv.err) {
  1906. return nil, ctx.Err()
  1907. }
  1908. }
  1909. }
  1910. return rv.r, rv.err
  1911. }
  1912. func (s *SQLiteStmt) execSync(args []driver.NamedValue) (driver.Result, error) {
  1913. if err := s.bind(args); err != nil {
  1914. C.sqlite3_reset(s.s)
  1915. C.sqlite3_clear_bindings(s.s)
  1916. return nil, err
  1917. }
  1918. var rowid, changes C.longlong
  1919. rv := C._sqlite3_step_row_internal(s.s, &rowid, &changes)
  1920. if rv != C.SQLITE_ROW && rv != C.SQLITE_OK && rv != C.SQLITE_DONE {
  1921. err := s.c.lastError()
  1922. C.sqlite3_reset(s.s)
  1923. C.sqlite3_clear_bindings(s.s)
  1924. return nil, err
  1925. }
  1926. return &SQLiteResult{id: int64(rowid), changes: int64(changes)}, nil
  1927. }
  1928. // Readonly reports if this statement is considered readonly by SQLite.
  1929. //
  1930. // See: https://sqlite.org/c3ref/stmt_readonly.html
  1931. func (s *SQLiteStmt) Readonly() bool {
  1932. return C.sqlite3_stmt_readonly(s.s) == 1
  1933. }
  1934. // Close the rows.
  1935. func (rc *SQLiteRows) Close() error {
  1936. rc.s.mu.Lock()
  1937. if rc.s.closed || rc.closed {
  1938. rc.s.mu.Unlock()
  1939. return nil
  1940. }
  1941. rc.closed = true
  1942. if rc.cls {
  1943. rc.s.mu.Unlock()
  1944. return rc.s.Close()
  1945. }
  1946. rv := C.sqlite3_reset(rc.s.s)
  1947. if rv != C.SQLITE_OK {
  1948. rc.s.mu.Unlock()
  1949. return rc.s.c.lastError()
  1950. }
  1951. rc.s.mu.Unlock()
  1952. rc.s = nil
  1953. runtime.SetFinalizer(rc, nil)
  1954. return nil
  1955. }
  1956. // Columns return column names.
  1957. func (rc *SQLiteRows) Columns() []string {
  1958. rc.s.mu.Lock()
  1959. defer rc.s.mu.Unlock()
  1960. if rc.s.s != nil && rc.nc != len(rc.cols) {
  1961. rc.cols = make([]string, rc.nc)
  1962. for i := 0; i < rc.nc; i++ {
  1963. rc.cols[i] = C.GoString(C.sqlite3_column_name(rc.s.s, C.int(i)))
  1964. }
  1965. }
  1966. return rc.cols
  1967. }
  1968. func (rc *SQLiteRows) declTypes() []string {
  1969. if rc.s.s != nil && rc.decltype == nil {
  1970. rc.decltype = make([]string, rc.nc)
  1971. for i := 0; i < rc.nc; i++ {
  1972. rc.decltype[i] = strings.ToLower(C.GoString(C.sqlite3_column_decltype(rc.s.s, C.int(i))))
  1973. }
  1974. }
  1975. return rc.decltype
  1976. }
  1977. // DeclTypes return column types.
  1978. func (rc *SQLiteRows) DeclTypes() []string {
  1979. rc.s.mu.Lock()
  1980. defer rc.s.mu.Unlock()
  1981. return rc.declTypes()
  1982. }
  1983. // Next move cursor to next. Attempts to honor context timeout from QueryContext call.
  1984. func (rc *SQLiteRows) Next(dest []driver.Value) error {
  1985. rc.s.mu.Lock()
  1986. defer rc.s.mu.Unlock()
  1987. if rc.s.closed {
  1988. return io.EOF
  1989. }
  1990. if rc.ctx.Done() == nil {
  1991. return rc.nextSyncLocked(dest)
  1992. }
  1993. resultCh := make(chan error)
  1994. defer close(resultCh)
  1995. go func() {
  1996. resultCh <- rc.nextSyncLocked(dest)
  1997. }()
  1998. select {
  1999. case err := <-resultCh:
  2000. return err
  2001. case <-rc.ctx.Done():
  2002. select {
  2003. case <-resultCh: // no need to interrupt
  2004. default:
  2005. // this is still racy and can be no-op if executed between sqlite3_* calls in nextSyncLocked.
  2006. C.sqlite3_interrupt(rc.s.c.db)
  2007. <-resultCh // ensure goroutine completed
  2008. }
  2009. return rc.ctx.Err()
  2010. }
  2011. }
  2012. // nextSyncLocked moves cursor to next; must be called with locked mutex.
  2013. func (rc *SQLiteRows) nextSyncLocked(dest []driver.Value) error {
  2014. rv := C._sqlite3_step_internal(rc.s.s)
  2015. if rv == C.SQLITE_DONE {
  2016. return io.EOF
  2017. }
  2018. if rv != C.SQLITE_ROW {
  2019. rv = C.sqlite3_reset(rc.s.s)
  2020. if rv != C.SQLITE_OK {
  2021. return rc.s.c.lastError()
  2022. }
  2023. return nil
  2024. }
  2025. rc.declTypes()
  2026. for i := range dest {
  2027. switch C.sqlite3_column_type(rc.s.s, C.int(i)) {
  2028. case C.SQLITE_INTEGER:
  2029. val := int64(C.sqlite3_column_int64(rc.s.s, C.int(i)))
  2030. switch rc.decltype[i] {
  2031. case columnTimestamp, columnDatetime, columnDate:
  2032. var t time.Time
  2033. // Assume a millisecond unix timestamp if it's 13 digits -- too
  2034. // large to be a reasonable timestamp in seconds.
  2035. if val > 1e12 || val < -1e12 {
  2036. val *= int64(time.Millisecond) // convert ms to nsec
  2037. t = time.Unix(0, val)
  2038. } else {
  2039. t = time.Unix(val, 0)
  2040. }
  2041. t = t.UTC()
  2042. if rc.s.c.loc != nil {
  2043. t = t.In(rc.s.c.loc)
  2044. }
  2045. dest[i] = t
  2046. case "boolean":
  2047. dest[i] = val > 0
  2048. default:
  2049. dest[i] = val
  2050. }
  2051. case C.SQLITE_FLOAT:
  2052. dest[i] = float64(C.sqlite3_column_double(rc.s.s, C.int(i)))
  2053. case C.SQLITE_BLOB:
  2054. p := C.sqlite3_column_blob(rc.s.s, C.int(i))
  2055. if p == nil {
  2056. dest[i] = []byte{}
  2057. continue
  2058. }
  2059. n := C.sqlite3_column_bytes(rc.s.s, C.int(i))
  2060. dest[i] = C.GoBytes(p, n)
  2061. case C.SQLITE_NULL:
  2062. dest[i] = nil
  2063. case C.SQLITE_TEXT:
  2064. var err error
  2065. var timeVal time.Time
  2066. n := int(C.sqlite3_column_bytes(rc.s.s, C.int(i)))
  2067. s := C.GoStringN((*C.char)(unsafe.Pointer(C.sqlite3_column_text(rc.s.s, C.int(i)))), C.int(n))
  2068. switch rc.decltype[i] {
  2069. case columnTimestamp, columnDatetime, columnDate:
  2070. var t time.Time
  2071. s = strings.TrimSuffix(s, "Z")
  2072. for _, format := range SQLiteTimestampFormats {
  2073. if timeVal, err = time.ParseInLocation(format, s, time.UTC); err == nil {
  2074. t = timeVal
  2075. break
  2076. }
  2077. }
  2078. if err != nil {
  2079. // The column is a time value, so return the zero time on parse failure.
  2080. t = time.Time{}
  2081. }
  2082. if rc.s.c.loc != nil {
  2083. t = t.In(rc.s.c.loc)
  2084. }
  2085. dest[i] = t
  2086. default:
  2087. dest[i] = s
  2088. }
  2089. }
  2090. }
  2091. return nil
  2092. }