squee.scm 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. ;;; squee --- A guile interface to postgres via the ffi
  2. ;; Copyright (C) 2015 Christopher Allan Webber <cwebber@dustycloud.org>
  3. ;; This library is free software; you can redistribute it and/or
  4. ;; modify it under the terms of the GNU Lesser General Public
  5. ;; License as published by the Free Software Foundation; either
  6. ;; version 3 of the License, or (at your option) any later version.
  7. ;;
  8. ;; This library is distributed in the hope that it will be useful,
  9. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. ;; Lesser General Public License for more details.
  12. ;;
  13. ;; You should have received a copy of the GNU Lesser General Public
  14. ;; License along with this library; if not, write to the Free Software
  15. ;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  16. (define-module (squee)
  17. #:use-module (system foreign)
  18. #:use-module (rnrs enums)
  19. #:use-module (ice-9 match)
  20. #:use-module (ice-9 format)
  21. #:use-module (srfi srfi-26)
  22. #:export (;; The important ones
  23. connect-to-postgres-paramstring
  24. exec-query
  25. pg-conn-finish
  26. ;; enums and indexes of enums
  27. conn-status-enum conn-status-enum-index
  28. polling-status-enum polling-status-index
  29. exec-status-enum exec-status-enum-index
  30. transaction-status-enum transaction-status-enum-index
  31. verbosity-enum verbosity-enum-index
  32. ping-enum ping-enum-index
  33. ;; **repl and error messages only!**
  34. enum-set-ref
  35. ;; Connection stuff
  36. <pg-conn> pg-conn? wrap-pg-conn unwrap-pg-conn
  37. ;; @@: We don't export the result pointer though!
  38. ;; as this needs to be cleared to avoid memory
  39. ;; leaks...
  40. ;;
  41. ;; We might provide a (exec-with-result-ptr)
  42. ;; that cleans up the result pointer after calling
  43. ;; some thunk though?
  44. ;;
  45. ;; These are still useful for building your own
  46. ;; serializer though...
  47. result-num-rows result-num-cols result-get-value
  48. result-serializer-simple-list result-metadata))
  49. (define libpq (dynamic-link "libpq"))
  50. ;; ---------------------
  51. ;; Enums from libpq-fe.h
  52. ;; ---------------------
  53. (define conn-status-enum
  54. (make-enumeration
  55. '(connection-ok
  56. connection-bad
  57. connection-started connection-made
  58. connection-awaiting-response connection-auth-ok
  59. connection-auth-ok connection-setenv
  60. connection-ssl-startup
  61. connection-needed)))
  62. (define conn-status-enum-index
  63. (enum-set-indexer conn-status-enum))
  64. (define polling-status-enum
  65. (make-enumeration
  66. '(polling-failed
  67. polling-reading
  68. polling-writing
  69. polling-ok
  70. polling-active)))
  71. (define polling-status-enum-index
  72. (enum-set-indexer polling-status-enum))
  73. (define exec-status-enum
  74. (make-enumeration
  75. '(empty-query
  76. command-ok tuples-ok
  77. copy-out copy-in
  78. bad-response
  79. nonfatal-error fatal-error
  80. copy-both
  81. single-tuple)))
  82. (define exec-status-enum-index
  83. (enum-set-indexer exec-status-enum))
  84. (define transaction-status-enum
  85. (make-enumeration
  86. '(idle active intrans inerror unknown)))
  87. (define transaction-status-enum-index
  88. (enum-set-indexer transaction-status-enum))
  89. (define verbosity-enum
  90. (make-enumeration
  91. '(terse default verbose)))
  92. (define verbosity-enum-index
  93. (enum-set-indexer verbosity-enum))
  94. (define ping-enum
  95. (make-enumeration
  96. '(ok reject no-response no-attempt)))
  97. (define ping-enum-index
  98. (enum-set-indexer ping-enum))
  99. (define-wrapped-pointer-type <pg-conn>
  100. pg-conn?
  101. wrap-pg-conn unwrap-pg-conn
  102. (lambda (pg-conn port)
  103. (format port "#<pg-conn ~x (~a)>"
  104. (pointer-address (unwrap-pg-conn pg-conn))
  105. (let ((status (pg-conn-status pg-conn)))
  106. (cond ((eq? status (conn-status-enum-index 'connection-ok))
  107. "connected")
  108. ((eq? status (conn-status-enum-index 'connection-bad))
  109. (let ((conn-error (pg-conn-error-message pg-conn)))
  110. (if (equal? conn-error "")
  111. "disconnected"
  112. (format #f "disconnected, error: ~s" conn-error))))
  113. (#t
  114. (symbol->string
  115. (pg-conn-status-symbol pg-conn))))))))
  116. ;; This one should NOT be exposed to the outside world! We have our
  117. ;; own result structure...
  118. (define-wrapped-pointer-type <result-ptr>
  119. result-ptr?
  120. wrap-result-ptr unwrap-result-ptr
  121. (lambda (result-ptr port)
  122. (format port "#<result-ptr ~x>"
  123. (pointer-address (unwrap-result-ptr result-ptr)))))
  124. (define (enum-set-ref enum-set k)
  125. "Take an ENUM-SET and get the item at position K
  126. This is O(n) but theoretically we don't use it much.
  127. Again, REPL only!"
  128. (list-ref (enum-set->list enum-set) k))
  129. (define-syntax-rule (define-foreign-libpq name return_type func_name arg_types)
  130. (define name
  131. (pointer->procedure return_type
  132. (dynamic-func func_name libpq)
  133. arg_types)))
  134. (define-foreign-libpq %PQconnectdb '* "PQconnectdb" (list '*))
  135. (define-foreign-libpq %PQstatus int "PQstatus" (list '*))
  136. (define-foreign-libpq %PQerrorMessage '* "PQerrorMessage" (list '*))
  137. (define-foreign-libpq %PQfinish void "PQfinish" (list '*))
  138. (define-foreign-libpq %PQntuples int "PQntuples" (list '*))
  139. (define-foreign-libpq %PQnfields int "PQnfields" (list '*))
  140. (define-foreign-libpq %PQexecParams
  141. '* ;; Returns a PGresult
  142. "PQexecParams"
  143. (list '* ;; connection
  144. '* ;; command, a string
  145. int ;; number of parameters
  146. '* ;; paramTypes, ok to leave NULL
  147. '* ;; paramValues, here goes your actual parameters!
  148. '* ;; paramLengths, ok to leave NULL
  149. '* ;; paramFormats, ok to leave NULL
  150. int)) ;; resultFormat... probably 0!
  151. (define-foreign-libpq %PQresultStatus int "PQresultStatus" (list '*))
  152. (define-foreign-libpq %PQresStatus '* "PQresStatus" (list int))
  153. (define-foreign-libpq %PQresultErrorMessage '* "PQresultErrorMessage" (list '*))
  154. (define-foreign-libpq %PQclear void "PQclear" (list '*))
  155. (define-foreign-libpq %PQntuples int "PQntuples" (list '*))
  156. (define-foreign-libpq %PQnfields int "PQnfields" (list '*))
  157. (define-foreign-libpq %PQgetvalue '* "PQgetvalue" (list '* int int))
  158. ;; Via mark_weaver. Thanks Mark!
  159. ;;
  160. ;; So, apparently we can use a struct of strings just like an array
  161. ;; of strings. Because magic, and because Mark thinks the C standard
  162. ;; allows it enough!
  163. (define (string-list->string-array ls)
  164. "Take a list of strings, generate a C-compatible list of free strings"
  165. (make-c-struct
  166. (make-list (+ 1 (length ls)) '*)
  167. (append (map string->pointer ls)
  168. (list %null-pointer))))
  169. (define (pg-conn-status pg-conn)
  170. "Get the connection status from a postgres connection"
  171. (%PQstatus (unwrap-pg-conn pg-conn)))
  172. (define (pg-conn-status-symbol pg-conn)
  173. "Human readable version of the pg-conn status.
  174. Inefficient... don't use this in normal code... it's just for you and
  175. the REPL! (Well, we do use it for errors, because those are
  176. comparatively \"rare\" so this is okay.) Compare against the enum
  177. value of the symbol instead."
  178. (let ((status (pg-conn-status pg-conn)))
  179. (if (< status (length (enum-set->list conn-status-enum)))
  180. (enum-set-ref conn-status-enum
  181. (pg-conn-status pg-conn))
  182. ;; Weird, this is bigger than our enum of statuses
  183. (string->symbol
  184. (format #f "unknown-status-~a" status)))))
  185. (define (pg-conn-error-message pg-conn)
  186. "Get an error message for this connection"
  187. (pointer->string (%PQerrorMessage (unwrap-pg-conn pg-conn))))
  188. (define (pg-conn-finish pg-conn)
  189. "Close out a database connection.
  190. If the connection is already closed, this simply returns #f."
  191. (if (eq? (pg-conn-status pg-conn)
  192. (conn-status-enum-index 'connection-ok))
  193. (begin
  194. (%PQfinish (unwrap-pg-conn pg-conn))
  195. #t)
  196. #f))
  197. (define (connect-to-postgres-paramstring paramstring)
  198. "Open a connection to the database via a parameter string"
  199. (let* ((conn-pointer (%PQconnectdb (string->pointer paramstring)))
  200. (pg-conn (wrap-pg-conn conn-pointer)))
  201. (if (eq? conn-pointer %null-pointer)
  202. (throw 'psql-connect-error
  203. #f "Unable to establish connection"))
  204. (let ((status (pg-conn-status pg-conn)))
  205. (if (eq? status (conn-status-enum-index 'connection-ok))
  206. pg-conn
  207. (throw 'psql-connect-error
  208. (enum-set-ref conn-status-enum status)
  209. (pg-conn-error-message pg-conn))))))
  210. (define (result-num-rows result-ptr)
  211. (%PQntuples (unwrap-result-ptr result-ptr)))
  212. (define (result-num-cols result-ptr)
  213. (%PQnfields (unwrap-result-ptr result-ptr)))
  214. (define (result-get-value result-ptr row col)
  215. (pointer->string
  216. (%PQgetvalue (unwrap-result-ptr result-ptr) row col)))
  217. ;; @@: We ought to also have a vector version...
  218. ;; and other serializations...
  219. (define (result-serializer-simple-list result-ptr)
  220. "Get a simple list of lists representing the result of the query"
  221. (let ((rows-range (iota (result-num-rows result-ptr)))
  222. (cols-range (iota (result-num-cols result-ptr))))
  223. (map
  224. (lambda (row-i)
  225. (map
  226. (lambda (col-i)
  227. (result-get-value result-ptr row-i col-i))
  228. cols-range))
  229. rows-range)))
  230. ;; TODO
  231. (define (result-metadata result-ptr)
  232. #f)
  233. (define (result-ptr-clear result-ptr)
  234. (%PQclear (unwrap-result-ptr result-ptr)))
  235. (define (result-error-message result-ptr)
  236. (%PQresultErrorMessage (unwrap-result-ptr result-ptr)))
  237. (define* (exec-query pg-conn command #:optional (params '())
  238. #:key (serializer result-serializer-simple-list))
  239. (let ((result-ptr
  240. (wrap-result-ptr
  241. (%PQexecParams
  242. (unwrap-pg-conn pg-conn)
  243. (string->pointer command)
  244. (length params)
  245. %null-pointer
  246. (string-list->string-array params)
  247. %null-pointer %null-pointer 0))))
  248. (if (eq? result-ptr %null-pointer)
  249. ;; Presumably a database connection issue...
  250. (throw 'psql-query-error
  251. ;; See below for psql-query-error param definition
  252. #f #f (pg-conn-error-message pg-conn)))
  253. (let ((status (%PQresultStatus (unwrap-result-ptr result-ptr))))
  254. (cond
  255. ;; This is the kind of query that returns tuples
  256. ((eq? status (exec-status-enum-index 'tuples-ok))
  257. (let ((serialized-result (serializer result-ptr))
  258. (metadata (result-metadata result-ptr)))
  259. ;; Gotta clear the result to prevent memory leaks
  260. (result-ptr-clear result-ptr)
  261. (values serialized-result metadata)))
  262. ;; This doesn't return tuples, eg it's a DELETE or something.
  263. ((eq? status (exec-status-enum-index 'command-ok))
  264. (let ((metadata (result-metadata result-ptr)))
  265. ;; Gotta clear the result to prevent memory leaks
  266. (result-ptr-clear result-ptr)
  267. ;; Just return #t if there's no tuples to look at
  268. (values #t metadata)))
  269. ;; Uhoh, anything else is an error!
  270. (#t
  271. (let ((status-message (pointer->string (%PQresStatus status)))
  272. (error-message (pointer->string
  273. (%PQresultErrorMessage (unwrap-result-ptr
  274. result-ptr)))))
  275. (result-ptr-clear result-ptr)
  276. (throw 'psql-query-error
  277. ;; @@: Do we need result-status?
  278. ;; (error-symbol result-status result-error-message)
  279. (enum-set-ref exec-status-enum status)
  280. status-message error-message)))))))
  281. ;; (define conn (connect-to-postgres-paramstring "dbname=sandbox"))