squee.scm 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. ;;; squee --- A guile interface to postgres via the ffi
  2. ;; Copyright (C) 2015 Christine Lemmer-Webber <cwebber@dustycloud.org>
  3. ;; Copyright (C) 2023 Ludovic Courtès <ludo@gnu.org>
  4. ;; This library is free software; you can redistribute it and/or
  5. ;; modify it under the terms of the GNU Lesser General Public
  6. ;; License as published by the Free Software Foundation; either
  7. ;; version 3 of the License, or (at your option) any later version.
  8. ;;
  9. ;; This library is distributed in the hope that it will be useful,
  10. ;; but 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 library; if not, write to the Free Software
  16. ;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  17. (define-module (squee)
  18. #:use-module (system foreign)
  19. #:use-module (rnrs enums)
  20. #:use-module (ice-9 match)
  21. #:use-module (ice-9 format)
  22. #:use-module ((srfi srfi-1) #:select (any))
  23. #:use-module (srfi srfi-26)
  24. #:autoload (ice-9 suspendable-ports) (current-read-waiter)
  25. #:export (;; The important ones
  26. connect-to-postgres-paramstring
  27. exec-query
  28. pg-conn-finish
  29. ;; enums and indexes of enums
  30. conn-status-enum conn-status-enum-index
  31. polling-status-enum polling-status-index
  32. exec-status-enum exec-status-enum-index
  33. transaction-status-enum transaction-status-enum-index
  34. verbosity-enum verbosity-enum-index
  35. ping-enum ping-enum-index
  36. ;; **repl and error messages only!**
  37. enum-set-ref
  38. ;; Connection stuff
  39. <pg-conn> pg-conn? wrap-pg-conn unwrap-pg-conn
  40. ;; @@: We don't export the result pointer though!
  41. ;; as this needs to be cleared to avoid memory
  42. ;; leaks...
  43. ;;
  44. ;; We might provide a (exec-with-result-ptr)
  45. ;; that cleans up the result pointer after calling
  46. ;; some thunk though?
  47. ;;
  48. ;; These are still useful for building your own
  49. ;; serializer though...
  50. result-num-rows result-num-cols result-get-value
  51. result-serializer-simple-list result-metadata))
  52. (define libpq (dynamic-link "libpq"))
  53. ;; ---------------------
  54. ;; Enums from libpq-fe.h
  55. ;; ---------------------
  56. (define conn-status-enum
  57. (make-enumeration
  58. '(connection-ok
  59. connection-bad
  60. connection-started connection-made
  61. connection-awaiting-response connection-auth-ok
  62. connection-auth-ok connection-setenv
  63. connection-ssl-startup
  64. connection-needed)))
  65. (define conn-status-enum-index
  66. (enum-set-indexer conn-status-enum))
  67. (define polling-status-enum
  68. (make-enumeration
  69. '(polling-failed
  70. polling-reading
  71. polling-writing
  72. polling-ok
  73. polling-active)))
  74. (define polling-status-enum-index
  75. (enum-set-indexer polling-status-enum))
  76. (define exec-status-enum
  77. (make-enumeration
  78. '(empty-query
  79. command-ok tuples-ok
  80. copy-out copy-in
  81. bad-response
  82. nonfatal-error fatal-error
  83. copy-both
  84. single-tuple)))
  85. (define exec-status-enum-index
  86. (enum-set-indexer exec-status-enum))
  87. (define transaction-status-enum
  88. (make-enumeration
  89. '(idle active intrans inerror unknown)))
  90. (define transaction-status-enum-index
  91. (enum-set-indexer transaction-status-enum))
  92. (define verbosity-enum
  93. (make-enumeration
  94. '(terse default verbose)))
  95. (define verbosity-enum-index
  96. (enum-set-indexer verbosity-enum))
  97. (define ping-enum
  98. (make-enumeration
  99. '(ok reject no-response no-attempt)))
  100. (define ping-enum-index
  101. (enum-set-indexer ping-enum))
  102. (define-wrapped-pointer-type <pg-conn>
  103. pg-conn?
  104. wrap-pg-conn unwrap-pg-conn
  105. (lambda (pg-conn port)
  106. (format port "#<pg-conn ~x (~a)>"
  107. (pointer-address (unwrap-pg-conn pg-conn))
  108. (let ((status (pg-conn-status pg-conn)))
  109. (cond ((eq? status (conn-status-enum-index 'connection-ok))
  110. "connected")
  111. ((eq? status (conn-status-enum-index 'connection-bad))
  112. (let ((conn-error (pg-conn-error-message pg-conn)))
  113. (if (equal? conn-error "")
  114. "disconnected"
  115. (format #f "disconnected, error: ~s" conn-error))))
  116. (#t
  117. (symbol->string
  118. (pg-conn-status-symbol pg-conn))))))))
  119. ;; This one should NOT be exposed to the outside world! We have our
  120. ;; own result structure...
  121. (define-wrapped-pointer-type <result-ptr>
  122. result-ptr?
  123. wrap-result-ptr unwrap-result-ptr
  124. (lambda (result-ptr port)
  125. (format port "#<result-ptr ~x>"
  126. (pointer-address (unwrap-result-ptr result-ptr)))))
  127. (define (enum-set-ref enum-set k)
  128. "Take an ENUM-SET and get the item at position K
  129. This is O(n) but theoretically we don't use it much.
  130. Again, REPL only!"
  131. (list-ref (enum-set->list enum-set) k))
  132. (define-syntax-rule (define-foreign-libpq name return_type func_name arg_types)
  133. (define name
  134. (pointer->procedure return_type
  135. (dynamic-func func_name libpq)
  136. arg_types)))
  137. (define-foreign-libpq %PQconnectdb '* "PQconnectdb" (list '*))
  138. (define-foreign-libpq %PQstatus int "PQstatus" (list '*))
  139. (define-foreign-libpq %PQerrorMessage '* "PQerrorMessage" (list '*))
  140. (define-foreign-libpq %PQfinish void "PQfinish" (list '*))
  141. (define-foreign-libpq %PQntuples int "PQntuples" (list '*))
  142. (define-foreign-libpq %PQnfields int "PQnfields" (list '*))
  143. ;; Synchronous interface.
  144. (define-foreign-libpq %PQexec '* "PQexec" (list '* '*))
  145. (define-foreign-libpq %PQexecParams
  146. '* ;; Returns a PGresult
  147. "PQexecParams"
  148. (list '* ;; connection
  149. '* ;; command, a string
  150. int ;; number of parameters
  151. '* ;; paramTypes, ok to leave NULL
  152. '* ;; paramValues, here goes your actual parameters!
  153. '* ;; paramLengths, ok to leave NULL
  154. '* ;; paramFormats, ok to leave NULL
  155. int)) ;; resultFormat... probably 0!
  156. ;; Asynchronous interface.
  157. (define-foreign-libpq %PQsocket int "PQsocket" '(*))
  158. (define-foreign-libpq %PQsendQuery int "PQsendQuery" (list '* '*))
  159. (define-foreign-libpq %PQsendQueryParams int "PQsendQueryParams"
  160. (list '* ;; connection
  161. '* ;; command, a string
  162. int ;; number of parameters
  163. '* ;; paramTypes, ok to leave NULL
  164. '* ;; paramValues, here goes your actual parameters!
  165. '* ;; paramLengths, ok to leave NULL
  166. '* ;; paramFormats, ok to leave NULL
  167. int))
  168. (define-foreign-libpq %PQconsumeInput int "PQconsumeInput" '(*))
  169. (define-foreign-libpq %PQisBusy int "PQisBusy" '(*))
  170. (define-foreign-libpq %PQgetResult '* "PQgetResult" '(*))
  171. (define-foreign-libpq %PQresultStatus int "PQresultStatus" (list '*))
  172. (define-foreign-libpq %PQresStatus '* "PQresStatus" (list int))
  173. (define-foreign-libpq %PQresultErrorMessage '* "PQresultErrorMessage" (list '*))
  174. (define-foreign-libpq %PQclear void "PQclear" (list '*))
  175. (define-foreign-libpq %PQcmdtuples '* "PQcmdTuples" (list '*))
  176. (define-foreign-libpq %PQntuples int "PQntuples" (list '*))
  177. (define-foreign-libpq %PQnfields int "PQnfields" (list '*))
  178. (define-foreign-libpq %PQgetisnull int "PQgetisnull" (list '* int int))
  179. (define-foreign-libpq %PQgetvalue '* "PQgetvalue" (list '* int int))
  180. ;; Via mark_weaver. Thanks Mark!
  181. ;;
  182. ;; So, apparently we can use a struct of strings just like an array
  183. ;; of strings. Because magic, and because Mark thinks the C standard
  184. ;; allows it enough!
  185. (define (string-pointer-list->string-array ls)
  186. "Take a list of strings, generate a C-compatible list of free strings"
  187. (make-c-struct
  188. (make-list (+ 1 (length ls)) '*)
  189. (append ls (list %null-pointer))))
  190. (define (pg-conn-status pg-conn)
  191. "Get the connection status from a postgres connection"
  192. (%PQstatus (unwrap-pg-conn pg-conn)))
  193. (define (pg-conn-status-symbol pg-conn)
  194. "Human readable version of the pg-conn status.
  195. Inefficient... don't use this in normal code... it's just for you and
  196. the REPL! (Well, we do use it for errors, because those are
  197. comparatively \"rare\" so this is okay.) Compare against the enum
  198. value of the symbol instead."
  199. (let ((status (pg-conn-status pg-conn)))
  200. (if (< status (length (enum-set->list conn-status-enum)))
  201. (enum-set-ref conn-status-enum
  202. (pg-conn-status pg-conn))
  203. ;; Weird, this is bigger than our enum of statuses
  204. (string->symbol
  205. (format #f "unknown-status-~a" status)))))
  206. (define (pg-conn-error-message pg-conn)
  207. "Get an error message for this connection"
  208. (pointer->string (%PQerrorMessage (unwrap-pg-conn pg-conn))))
  209. (define %connection-socket-table
  210. ;; Map <pg-conn> records to a file port backed by the connection's socket.
  211. ;; TODO: Avoid this side table.
  212. (make-weak-key-hash-table))
  213. (define (connection-socket-port pg-conn) ;internal
  214. "Return the socket port associated with PG-CONN. Cache it to avoid
  215. allocating a new one at every call."
  216. (or (hashq-ref %connection-socket-table pg-conn)
  217. (let* ((fd (%PQsocket (unwrap-pg-conn pg-conn)))
  218. (port (fdopen fd "r+0")))
  219. (set-port-revealed! port 1) ;closed by libpq
  220. (hashq-set! %connection-socket-table pg-conn port)
  221. port)))
  222. (define (pg-conn-finish pg-conn)
  223. "Close out a database connection.
  224. If the connection is already closed, this simply returns #f."
  225. (if (eq? (pg-conn-status pg-conn)
  226. (conn-status-enum-index 'connection-ok))
  227. (begin
  228. (%PQfinish (unwrap-pg-conn pg-conn))
  229. (hashq-remove! %connection-socket-table pg-conn)
  230. #t)
  231. #f))
  232. (define (connect-to-postgres-paramstring paramstring)
  233. "Open a connection to the database via a parameter string"
  234. (let* ((conn-pointer (%PQconnectdb (string->pointer paramstring)))
  235. (pg-conn (wrap-pg-conn conn-pointer)))
  236. ;; 'PQconnectdb' might return a pointer that was previously used for
  237. ;; another connection, possibly backed by a different file descriptor.
  238. ;; Thus, remove PG-CONN from the side table.
  239. (hashq-remove! %connection-socket-table pg-conn)
  240. (if (eq? conn-pointer %null-pointer)
  241. (throw 'psql-connect-error
  242. #f "Unable to establish connection"))
  243. (let ((status (pg-conn-status pg-conn)))
  244. (if (eq? status (conn-status-enum-index 'connection-ok))
  245. pg-conn
  246. (throw 'psql-connect-error
  247. (enum-set-ref conn-status-enum status)
  248. (pg-conn-error-message pg-conn))))))
  249. (define (result-num-rows result-ptr)
  250. (%PQntuples (unwrap-result-ptr result-ptr)))
  251. (define (result-num-cols result-ptr)
  252. (%PQnfields (unwrap-result-ptr result-ptr)))
  253. (define (result-get-value result-ptr row col)
  254. (let ((res (unwrap-result-ptr result-ptr)))
  255. (and (eqv? (%PQgetisnull res row col) 0)
  256. (pointer->string
  257. (%PQgetvalue res row col)))))
  258. ;; @@: We ought to also have a vector version...
  259. ;; and other serializations...
  260. (define (result-serializer-simple-list result-ptr)
  261. "Get a simple list of lists representing the result of the query"
  262. (let ((rows-range (iota (result-num-rows result-ptr)))
  263. (cols-range (iota (result-num-cols result-ptr))))
  264. (map
  265. (lambda (row-i)
  266. (map
  267. (lambda (col-i)
  268. (result-get-value result-ptr row-i col-i))
  269. cols-range))
  270. rows-range)))
  271. ;; TODO
  272. (define (result-metadata result-ptr)
  273. #f)
  274. (define (result-ptr-clear result-ptr)
  275. (%PQclear (unwrap-result-ptr result-ptr)))
  276. (define (result-error-message result-ptr)
  277. (%PQresultErrorMessage (unwrap-result-ptr result-ptr)))
  278. (define (wait-for-input pg-conn)
  279. ((current-read-waiter) (connection-socket-port pg-conn)))
  280. (define (process-result result-ptr serializer)
  281. "Process the result pointed to by RESULT-PTR, returning a regular value and
  282. data upon success."
  283. (let ((status (%PQresultStatus result-ptr))
  284. (result-ptr (wrap-result-ptr result-ptr)))
  285. (cond
  286. ;; This is the kind of query that returns tuples
  287. ((eq? status (exec-status-enum-index 'tuples-ok))
  288. (let ((serialized-result (serializer result-ptr))
  289. (metadata (result-metadata result-ptr)))
  290. ;; Gotta clear the result to prevent memory leaks
  291. (result-ptr-clear result-ptr)
  292. (values serialized-result metadata)))
  293. ;; This doesn't return tuples, eg it's a DELETE or something.
  294. ((eq? status (exec-status-enum-index 'command-ok))
  295. (let ((metadata (result-metadata result-ptr))
  296. (rows (%PQcmdtuples (unwrap-result-ptr result-ptr))))
  297. ;; Gotta clear the result to prevent memory leaks
  298. (result-ptr-clear result-ptr)
  299. ;; Return the number of affected rows.
  300. (values (string->number
  301. (pointer->string rows)) metadata)))
  302. ;; Uhoh, anything else is an error!
  303. (#t
  304. (let ((status-message (pointer->string (%PQresStatus status)))
  305. (error-message (pointer->string
  306. (%PQresultErrorMessage (unwrap-result-ptr
  307. result-ptr)))))
  308. (result-ptr-clear result-ptr)
  309. (throw 'psql-query-error
  310. ;; @@: Do we need result-status?
  311. ;; (error-symbol result-status result-error-message)
  312. (enum-set-ref exec-status-enum status)
  313. status-message error-message))))))
  314. (define %query-exception
  315. ;; Cookie to represent an exception thrown.
  316. (list 'query 'exception))
  317. (define* (exec-query pg-conn command #:optional (params '())
  318. #:key (serializer result-serializer-simple-list))
  319. (let* ((param-pointers
  320. (map (lambda (param)
  321. (if param
  322. (string->pointer param)
  323. %null-pointer))
  324. params))
  325. (command-pointer
  326. (string->pointer command))
  327. (param-array-pointer
  328. (string-pointer-list->string-array param-pointers))
  329. (conn-pointer (unwrap-pg-conn pg-conn))
  330. (query-sent?
  331. (not (zero? (if (null? params)
  332. (%PQsendQuery conn-pointer command-pointer)
  333. (%PQsendQueryParams conn-pointer command-pointer
  334. (length params)
  335. %null-pointer
  336. param-array-pointer
  337. %null-pointer
  338. %null-pointer 0))))))
  339. ;; Protect the pointers, and thus the memory regions they point to
  340. ;; from garbage collection, until %PQexecParams has returned
  341. (identity param-pointers)
  342. (identity command-pointer)
  343. (identity param-array-pointer)
  344. (unless query-sent?
  345. (throw 'psql-query-error
  346. #f #f (pg-conn-error-message pg-conn)))
  347. ;; Cooperate through the suspendable-port mechanism while waiting for a
  348. ;; reply.
  349. (let loop ()
  350. (wait-for-input pg-conn)
  351. ;; Consume available input.
  352. (when (zero? (%PQconsumeInput conn-pointer))
  353. (throw 'psql-query-error
  354. #f #f (pg-conn-error-message pg-conn)))
  355. ;; Is the query done? If not, try again.
  356. (unless (zero? (%PQisBusy conn-pointer))
  357. (loop)))
  358. ;; Call 'PQgetResult' until it returns NULL.
  359. (let loop ((result-ptr (%PQgetResult conn-pointer)))
  360. (call-with-values
  361. (lambda ()
  362. (catch 'psql-query-error
  363. (lambda ()
  364. (process-result result-ptr serializer))
  365. (lambda args
  366. (values %query-exception args))))
  367. (lambda (value metadata)
  368. (let ((next-result-ptr (%PQgetResult conn-pointer)))
  369. (if (null-pointer? next-result-ptr)
  370. (if (eq? value %query-exception)
  371. (apply throw metadata)
  372. (values value metadata))
  373. (loop next-result-ptr))))))))
  374. ;; (define conn (connect-to-postgres-paramstring "dbname=sandbox"))