sqlite3.go 65 KB

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