sqlite3.go 65 KB

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