sqlite3.scm 19 KB

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