sqlite3.go 58 KB

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