sqlite3.scm.in 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580
  1. ;; Guile-SQLite3
  2. ;; Copyright (C) 2010, 2014 Andy Wingo <wingo at pobox dot com>
  3. ;; Copyright (C) 2018 Ludovic Courtès <ludo@gnu.org>
  4. ;; This library is free software; you can redistribute it and/or modify
  5. ;; it under the terms of the GNU Lesser General Public License as
  6. ;; published by the Free Software Foundation; either version 3 of the
  7. ;; License, or (at your option) any later version.
  8. ;;
  9. ;; This library is distributed in the hope that it will be useful, but
  10. ;; WITHOUT ANY WARRANTY; without even the implied warranty of
  11. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. ;; Lesser General Public License for more details.
  13. ;;
  14. ;; You should have received a copy of the GNU Lesser General Public
  15. ;; License along with this program; if not, contact:
  16. ;;
  17. ;; Free Software Foundation Voice: +1-617-542-5942
  18. ;; 59 Temple Place - Suite 330 Fax: +1-617-542-2652
  19. ;; Boston, MA 02111-1307, USA gnu@gnu.org
  20. ;;; Commentary:
  21. ;;
  22. ;; A Guile binding for sqlite.
  23. ;;
  24. ;;; Code:
  25. (define-module (sqlite3)
  26. #:use-module (system foreign)
  27. #:use-module (rnrs bytevectors)
  28. #:use-module (ice-9 match)
  29. #:use-module (srfi srfi-1)
  30. #:use-module (srfi srfi-9)
  31. #:use-module (srfi srfi-19)
  32. #:export (sqlite-open
  33. sqlite-db?
  34. sqlite-close
  35. sqlite-enable-load-extension
  36. sqlite-exec
  37. sqlite-prepare
  38. sqlite-bind
  39. sqlite-bind-arguments
  40. sqlite-column-names
  41. sqlite-step
  42. sqlite-fold
  43. sqlite-fold-right
  44. sqlite-map
  45. sqlite-reset
  46. sqlite-finalize
  47. sqlite-bind-parameter-index
  48. sqlite-busy-timeout
  49. SQLITE_OPEN_READONLY
  50. SQLITE_OPEN_READWRITE
  51. SQLITE_OPEN_CREATE
  52. SQLITE_OPEN_DELETEONCLOSE
  53. SQLITE_OPEN_EXCLUSIVE
  54. SQLITE_OPEN_MAIN_DB
  55. SQLITE_OPEN_TEMP_DB
  56. SQLITE_OPEN_TRANSIENT_DB
  57. SQLITE_OPEN_MAIN_JOURNAL
  58. SQLITE_OPEN_TEMP_JOURNAL
  59. SQLITE_OPEN_SUBJOURNAL
  60. SQLITE_OPEN_MASTER_JOURNAL
  61. SQLITE_OPEN_NOMUTEX
  62. SQLITE_OPEN_FULLMUTEX
  63. SQLITE_OPEN_SHAREDCACHE
  64. SQLITE_OPEN_PRIVATECACHE
  65. SQLITE_CONSTRAINT
  66. SQLITE_CONSTRAINT_PRIMARYKEY
  67. SQLITE_CONSTRAINT_UNIQUE))
  68. ;;
  69. ;; Utils
  70. ;;
  71. (define (string->utf8-pointer s)
  72. (string->pointer s "utf-8"))
  73. (define (utf8-pointer->string p)
  74. (pointer->string p -1 "utf-8"))
  75. ;;
  76. ;; Constants
  77. ;;
  78. ;; FIXME: snarf using compiler. These are just copied from the header...
  79. ;;
  80. (define SQLITE_OPEN_READONLY #x00000001) ;; Ok for sqlite3_open_v2()
  81. (define SQLITE_OPEN_READWRITE #x00000002) ;; Ok for sqlite3_open_v2()
  82. (define SQLITE_OPEN_CREATE #x00000004) ;; Ok for sqlite3_open_v2()
  83. (define SQLITE_OPEN_DELETEONCLOSE #x00000008) ;; VFS only
  84. (define SQLITE_OPEN_EXCLUSIVE #x00000010) ;; VFS only
  85. (define SQLITE_OPEN_MAIN_DB #x00000100) ;; VFS only
  86. (define SQLITE_OPEN_TEMP_DB #x00000200) ;; VFS only
  87. (define SQLITE_OPEN_TRANSIENT_DB #x00000400) ;; VFS only
  88. (define SQLITE_OPEN_MAIN_JOURNAL #x00000800) ;; VFS only
  89. (define SQLITE_OPEN_TEMP_JOURNAL #x00001000) ;; VFS only
  90. (define SQLITE_OPEN_SUBJOURNAL #x00002000) ;; VFS only
  91. (define SQLITE_OPEN_MASTER_JOURNAL #x00004000) ;; VFS only
  92. (define SQLITE_OPEN_NOMUTEX #x00008000) ;; Ok for sqlite3_open_v2()
  93. (define SQLITE_OPEN_FULLMUTEX #x00010000) ;; Ok for sqlite3_open_v2()
  94. (define SQLITE_OPEN_SHAREDCACHE #x00020000) ;; Ok for sqlite3_open_v2()
  95. (define SQLITE_OPEN_PRIVATECACHE #x00040000) ;; Ok for sqlite3_open_v2()
  96. (define SQLITE_CONSTRAINT 19)
  97. (define SQLITE_CONSTRAINT_PRIMARYKEY
  98. (logior SQLITE_CONSTRAINT (ash 6 8)))
  99. (define SQLITE_CONSTRAINT_UNIQUE
  100. (logior SQLITE_CONSTRAINT (ash 8 8)))
  101. (define libsqlite3 (dynamic-link "@SQLITE_LIBDIR@/libsqlite3"))
  102. (define-record-type <sqlite-db>
  103. (make-db pointer open? stmts)
  104. db?
  105. (pointer db-pointer)
  106. (open? db-open? set-db-open?!)
  107. (stmts db-stmts))
  108. (define-syntax sqlite-db?
  109. (identifier-syntax db?))
  110. (define-record-type <sqlite-stmt>
  111. (make-stmt pointer live? reset? cached?)
  112. stmt?
  113. (pointer stmt-pointer)
  114. (live? stmt-live? set-stmt-live?!)
  115. (reset? stmt-reset? set-stmt-reset?!)
  116. (cached? stmt-cached? set-stmt-cached?!))
  117. (define sqlite-errmsg
  118. (let ((f (pointer->procedure
  119. '*
  120. (dynamic-func "sqlite3_errmsg" libsqlite3)
  121. (list '*))))
  122. (lambda (db)
  123. (utf8-pointer->string (f (db-pointer db))))))
  124. (define sqlite-errcode
  125. (let ((f (pointer->procedure
  126. int
  127. (dynamic-func "sqlite3_extended_errcode" libsqlite3)
  128. (list '*))))
  129. (lambda (db)
  130. (f (db-pointer db)))))
  131. (define* (sqlite-error db who #:optional code
  132. (errmsg (and db (sqlite-errmsg db))))
  133. (throw 'sqlite-error who code errmsg))
  134. (define* (check-error db #:optional who)
  135. (let ((code (sqlite-errcode db)))
  136. (if (not (zero? code))
  137. (sqlite-error db who code))))
  138. (define sqlite-close
  139. (let ((f (pointer->procedure
  140. int
  141. (dynamic-func "sqlite3_close" libsqlite3)
  142. (list '*))))
  143. (lambda (db)
  144. (when (db-open? db)
  145. ;; Finalize cached statements.
  146. (hash-for-each (lambda (sql stmt)
  147. (set-stmt-cached?! stmt #f)
  148. (sqlite-finalize stmt))
  149. (db-stmts db))
  150. (hash-clear! (db-stmts db))
  151. (let ((p (db-pointer db)))
  152. (set-db-open?! db #f)
  153. (f p))))))
  154. (define db-guardian (make-guardian))
  155. (define (pump-db-guardian)
  156. (let ((db (db-guardian)))
  157. (if db
  158. (begin
  159. (sqlite-close db)
  160. (pump-db-guardian)))))
  161. (add-hook! after-gc-hook pump-db-guardian)
  162. (define (static-errcode->errmsg code)
  163. (case code
  164. ((1) "SQL error or missing database")
  165. ((2) "Internal logic error in SQLite")
  166. ((3) "Access permission denied")
  167. ((5) "The database file is locked")
  168. ((6) "A table in the database is locked")
  169. ((7) "A malloc() failed")
  170. ((8) "Attempt to write a readonly database")
  171. ((10) "Some kind of disk I/O error occurred")
  172. ((11) "The database disk image is malformed")
  173. ((14) "Unable to open the database file")
  174. ((21) "Library used incorrectly")
  175. ((22) "Uses OS features not supported on host")
  176. ((23) "Authorization denied")
  177. ((24) "Auxiliary database format error")
  178. ((26) "File opened that is not a database file")
  179. (else "Unknown error")))
  180. (define sqlite-open
  181. (let ((f (pointer->procedure
  182. int
  183. (dynamic-func "sqlite3_open_v2" libsqlite3)
  184. (list '* '* int '*))))
  185. (lambda* (filename #:optional
  186. (flags (logior SQLITE_OPEN_READWRITE SQLITE_OPEN_CREATE))
  187. (vfs #f))
  188. (let* ((out-db (bytevector->pointer (make-bytevector (sizeof '*) 0)))
  189. (ret (f (string->utf8-pointer filename)
  190. out-db
  191. flags
  192. (if vfs (string->utf8-pointer vfs) %null-pointer))))
  193. (if (zero? ret)
  194. (let ((db (make-db (dereference-pointer out-db) #t
  195. (make-hash-table))))
  196. (db-guardian db)
  197. db)
  198. (sqlite-error #f 'sqlite-open ret (static-errcode->errmsg ret)))))))
  199. (define sqlite-enable-load-extension
  200. (let ((ele (pointer->procedure
  201. int
  202. (dynamic-func "sqlite3_enable_load_extension" libsqlite3)
  203. (list '* int))))
  204. (lambda (db onoff)
  205. (ele (db-pointer db) onoff))))
  206. (define sqlite-exec
  207. (let ((exec (pointer->procedure
  208. int
  209. (dynamic-func "sqlite3_exec" (@@ (sqlite3) libsqlite3))
  210. '(* * * * *))))
  211. (lambda* (db sql)
  212. "Evaluate the string SQL, which may contain one or several SQL
  213. statements, into DB. The result is unspecified."
  214. ;; XXX: 'sqlite3_exec' has a 'callback' parameter but we ignore it
  215. ;; here.
  216. (assert-live-db! db)
  217. (unless (zero? (exec (db-pointer db) (string->pointer sql)
  218. %null-pointer %null-pointer %null-pointer))
  219. (check-error db 'sqlite-exec)))))
  220. ;;;
  221. ;;; SQL statements
  222. ;;;
  223. (define sqlite-remove-statement!
  224. (lambda (db stmt)
  225. (when (stmt-cached? stmt)
  226. (let* ((stmts (db-stmts db))
  227. (key (catch 'value
  228. (lambda ()
  229. (hash-for-each (lambda (key value)
  230. (when (eq? value stmt)
  231. (throw 'value key)))
  232. stmts)
  233. #f)
  234. (lambda (_ key) key))))
  235. (hash-remove! stmts key)))))
  236. (define sqlite-finalize
  237. (let ((f (pointer->procedure
  238. int
  239. (dynamic-func "sqlite3_finalize" libsqlite3)
  240. (list '*))))
  241. (lambda (stmt)
  242. ;; Note: When STMT is cached, this is a no-op. This ensures caching
  243. ;; actually works while still separating concerns: users can turn
  244. ;; caching on and off without having to change the rest of their code.
  245. (when (and (stmt-live? stmt)
  246. (not (stmt-cached? stmt)))
  247. (let ((p (stmt-pointer stmt)))
  248. (sqlite-remove-statement! (stmt->db stmt) stmt)
  249. (set-stmt-live?! stmt #f)
  250. (f p))))))
  251. (define *stmt-map* (make-weak-key-hash-table))
  252. (define (stmt->db stmt)
  253. (hashq-ref *stmt-map* stmt))
  254. (define stmt-guardian (make-guardian))
  255. (define (pump-stmt-guardian)
  256. (let ((stmt (stmt-guardian)))
  257. (if stmt
  258. (begin
  259. (sqlite-finalize stmt)
  260. (pump-stmt-guardian)))))
  261. (add-hook! after-gc-hook pump-stmt-guardian)
  262. (define sqlite-reset
  263. (let ((reset (pointer->procedure
  264. int
  265. (dynamic-func "sqlite3_reset" libsqlite3)
  266. (list '*))))
  267. (lambda (stmt)
  268. (if (stmt-live? stmt)
  269. (let ((p (stmt-pointer stmt)))
  270. (set-stmt-reset?! stmt #t)
  271. (reset p))
  272. (error "statement already finalized" stmt)))))
  273. (define (assert-live-stmt! stmt)
  274. (if (not (stmt-live? stmt))
  275. (error "statement already finalized" stmt)))
  276. (define (assert-live-db! db)
  277. (if (not (db-open? db))
  278. (error "database already closed" db)))
  279. (define %sqlite-prepare
  280. (let ((prepare (pointer->procedure
  281. int
  282. (dynamic-func "sqlite3_prepare_v2" libsqlite3)
  283. (list '* '* int '* '*))))
  284. (lambda* (db sql #:key cache?)
  285. (assert-live-db! db)
  286. (let* ((out-stmt (bytevector->pointer (make-bytevector (sizeof '*) 0)))
  287. (out-tail (bytevector->pointer (make-bytevector (sizeof '*) 0)))
  288. (bv (string->utf8 sql))
  289. (bvp (bytevector->pointer bv))
  290. (ret (prepare (db-pointer db)
  291. bvp
  292. (bytevector-length bv)
  293. out-stmt
  294. out-tail)))
  295. (if (zero? ret)
  296. (if (= (bytevector-length bv)
  297. (- (pointer-address (dereference-pointer out-tail))
  298. (pointer-address bvp)))
  299. (let ((stmt (make-stmt (dereference-pointer out-stmt) #t #t
  300. cache?)))
  301. (stmt-guardian stmt)
  302. (hashq-set! *stmt-map* stmt db)
  303. stmt)
  304. (error "input sql has useless tail"
  305. (utf8-pointer->string
  306. (dereference-pointer out-tail))))
  307. (check-error db 'sqlite-prepare))))))
  308. (define* (sqlite-prepare db sql #:key cache?)
  309. (if cache?
  310. (match (hash-ref (db-stmts db) sql)
  311. (#f
  312. (let ((stmt (%sqlite-prepare db sql #:cache? #t)))
  313. (hash-set! (db-stmts db) sql stmt)
  314. stmt))
  315. (stmt
  316. (sqlite-reset stmt)
  317. stmt))
  318. (%sqlite-prepare db sql)))
  319. (define sqlite-bind-parameter-index
  320. (let ((bind-parameter-index (pointer->procedure
  321. int
  322. (dynamic-func "sqlite3_bind_parameter_index" libsqlite3)
  323. (list '* '*))))
  324. (lambda (stmt name)
  325. (assert-live-stmt! stmt)
  326. (let* ((ret (bind-parameter-index (stmt-pointer stmt)
  327. (string->utf8-pointer name))))
  328. (if (> ret 0)
  329. ret
  330. (begin
  331. (check-error (stmt->db stmt) 'sqlite-bind-parameter-index)
  332. (write ret)
  333. (newline)
  334. (error "No such parameter" name)))))))
  335. (define key->index
  336. (lambda (stmt key)
  337. (cond
  338. ((string? key) (sqlite-bind-parameter-index stmt key))
  339. ((symbol? key) (sqlite-bind-parameter-index stmt
  340. (string-append ":" (symbol->string key))))
  341. (else key))))
  342. (define sqlite-bind
  343. (let ((bind-blob (pointer->procedure
  344. int
  345. (dynamic-func "sqlite3_bind_blob" libsqlite3)
  346. (list '* int '* int '*)))
  347. (bind-text (pointer->procedure
  348. int
  349. (dynamic-func "sqlite3_bind_text" libsqlite3)
  350. (list '* int '* int '*)))
  351. (bind-int64 (pointer->procedure
  352. int
  353. (dynamic-func "sqlite3_bind_int64" libsqlite3)
  354. (list '* int int64)))
  355. (bind-double (pointer->procedure
  356. int
  357. (dynamic-func "sqlite3_bind_double" libsqlite3)
  358. (list '* int double)))
  359. (bind-null (pointer->procedure
  360. int
  361. (dynamic-func "sqlite3_bind_null" libsqlite3)
  362. (list '* int)))
  363. (sqlite-transient (make-pointer
  364. (bit-extract (lognot 0) 0 (* 8 (sizeof '*))))))
  365. (lambda (stmt key val)
  366. (assert-live-stmt! stmt)
  367. (let ((idx (key->index stmt key))
  368. (p (stmt-pointer stmt)))
  369. (cond
  370. ((bytevector? val)
  371. (bind-blob p idx (bytevector->pointer val) (bytevector-length val)
  372. sqlite-transient))
  373. ((string? val)
  374. (let ((bv (string->utf8 val)))
  375. (bind-text p idx (bytevector->pointer bv) (bytevector-length bv)
  376. sqlite-transient)))
  377. ((and (integer? val) (exact? val))
  378. (bind-int64 p idx val))
  379. ((number? val)
  380. (bind-double p idx (exact->inexact val)))
  381. ((not val)
  382. (bind-null p idx))
  383. (else
  384. (error "unexpected value" val)))
  385. (check-error (stmt->db stmt))))))
  386. (define (sqlite-bind-arguments stmt . args)
  387. "Bind STMT parameters, one after another, to ARGS.
  388. Also bind named parameters to the respective ones."
  389. (let loop ((i 1)
  390. (args args))
  391. (match args
  392. (()
  393. #f)
  394. (((? keyword? kw) value . rest)
  395. (sqlite-bind stmt (keyword->symbol kw) value)
  396. (loop i rest))
  397. ((arg . rest)
  398. (sqlite-bind stmt i arg)
  399. (loop (+ 1 i) rest)))))
  400. (define sqlite-column-count
  401. (let ((column-count
  402. (pointer->procedure
  403. int
  404. (dynamic-pointer "sqlite3_column_count" libsqlite3)
  405. (list '*))))
  406. (lambda (stmt)
  407. (assert-live-stmt! stmt)
  408. (column-count (stmt-pointer stmt)))))
  409. (define sqlite-column-name
  410. (let ((column-name
  411. (pointer->procedure
  412. '*
  413. (dynamic-pointer "sqlite3_column_name" libsqlite3)
  414. (list '* int))))
  415. (lambda (stmt i)
  416. (assert-live-stmt! stmt)
  417. (utf8-pointer->string (column-name (stmt-pointer stmt) i)))))
  418. (define sqlite-column-value
  419. (let ((value-type
  420. (pointer->procedure
  421. int
  422. (dynamic-pointer "sqlite3_column_type" libsqlite3)
  423. (list '* int)))
  424. (value-int
  425. (pointer->procedure
  426. int64
  427. (dynamic-pointer "sqlite3_column_int64" libsqlite3)
  428. (list '* int)))
  429. (value-double
  430. (pointer->procedure
  431. double
  432. (dynamic-pointer "sqlite3_column_double" libsqlite3)
  433. (list '* int)))
  434. (value-text
  435. (pointer->procedure
  436. '*
  437. (dynamic-pointer "sqlite3_column_text" libsqlite3)
  438. (list '* int)))
  439. (value-blob
  440. (pointer->procedure
  441. '*
  442. (dynamic-pointer "sqlite3_column_blob" libsqlite3)
  443. (list '* int)))
  444. (value-bytes
  445. (pointer->procedure
  446. int
  447. (dynamic-pointer "sqlite3_column_bytes" libsqlite3)
  448. (list '* int))))
  449. (lambda (stmt i)
  450. (assert-live-stmt! stmt)
  451. (case (value-type (stmt-pointer stmt) i)
  452. ((1) ; SQLITE_INTEGER
  453. (value-int (stmt-pointer stmt) i))
  454. ((2) ; SQLITE_FLOAT
  455. (value-double (stmt-pointer stmt) i))
  456. ((3) ; SQLITE3_TEXT
  457. (let ((p (value-blob (stmt-pointer stmt) i)))
  458. (if (null-pointer? p)
  459. ""
  460. (utf8->string
  461. (pointer->bytevector p (value-bytes (stmt-pointer stmt) i))))))
  462. ((4) ; SQLITE_BLOB
  463. (let ((p (value-blob (stmt-pointer stmt) i)))
  464. (if (null-pointer? p)
  465. (make-bytevector 0)
  466. (pointer->bytevector p (value-bytes (stmt-pointer stmt) i)))))
  467. ((5) ; SQLITE_NULL
  468. #f)))))
  469. (define (sqlite-column-names stmt)
  470. (let ((v (make-vector (sqlite-column-count stmt))))
  471. (let lp ((i 0))
  472. (if (< i (vector-length v))
  473. (begin
  474. (vector-set! v i (sqlite-column-name stmt i))
  475. (lp (1+ i)))
  476. v))))
  477. (define (sqlite-row stmt)
  478. (let ((v (make-vector (sqlite-column-count stmt))))
  479. (let lp ((i 0))
  480. (if (< i (vector-length v))
  481. (begin
  482. (vector-set! v i (sqlite-column-value stmt i))
  483. (lp (1+ i)))
  484. v))))
  485. (define sqlite-busy-timeout
  486. (let ((f (pointer->procedure
  487. int
  488. (dynamic-func "sqlite3_busy_timeout" libsqlite3)
  489. (list '* int))))
  490. (lambda (db value)
  491. (assert-live-db! db)
  492. (let ((ret (f (db-pointer db) value)))
  493. (when (not (zero? ret))
  494. (check-error db 'sqlite-busy-timeout))))))
  495. (define sqlite-step
  496. (let ((step (pointer->procedure
  497. int
  498. (dynamic-pointer "sqlite3_step" libsqlite3)
  499. (list '*))))
  500. (lambda (stmt)
  501. (assert-live-stmt! stmt)
  502. (let ((ret (step (stmt-pointer stmt))))
  503. (case ret
  504. ((100) ; SQLITE_ROW
  505. (sqlite-row stmt))
  506. ((101) ; SQLITE_DONE
  507. #f)
  508. (else
  509. (check-error (stmt->db stmt))
  510. (error "shouldn't get here")))))))
  511. (define (sqlite-fold kons knil stmt)
  512. (assert-live-stmt! stmt)
  513. (let lp ((seed knil))
  514. (let ((row (sqlite-step stmt)))
  515. (if row
  516. (lp (kons row seed))
  517. seed))))
  518. (define (sqlite-fold-right kons knil stmt)
  519. (assert-live-stmt! stmt)
  520. (let lp ()
  521. (let ((row (sqlite-step stmt)))
  522. (if row
  523. (kons row (lp))
  524. knil))))
  525. (define (sqlite-map proc stmt)
  526. (map proc
  527. (reverse! (sqlite-fold cons '() stmt))))