Fork me on GitHub
Malik Kennedy19:10:41

I found an example of someone using pg_listen, the postgres Pub/Sub extension in Clojure but it felt very java-y? ;; I did my best to make it look more how I (as a beginner) would expect it to. ;; Unfortunately the way I made it, returns a PGPreparedStatement instead of a PGSimpleStatement.

;; how to go from this
(doto (.createStatement connection)
      (.execute "LISTEN messages;")

;; to something using clojure's JDBC (?) 
  (jdbc/get-connection pg-db) 
  "LISTEN messages;")


(Caveat: I'm no PostgreSQL user) According to that gist, you need to keep a connection open all the time you're listening and you need to add a notification listener to the connection -- and that's the same connection you should use for the create statement.


So, first off you'll need to have something like (def conn (doto (jdbc/get-connection pg-db) (.addNotificationListener your-listener)))


And doesn't offer a way to create a plain statement, as far as I recall (`next.jdbc` does support that), so you really need to use the Java interop in that gist.


The gist is idiomatic @mksybr -- Clojure is a hosted language so using interop is expected when dealing with certain java objects (like this example).

❤️ 6

It would be easier to use next.jdbc here if you insist on trying to wrap the Java interop.

(with-open [stmt (next.jdbc.prepare/statement conn)]
  (execute! stmt ["LISTEN messages"]))

❤️ 3

(that automatically closes the statement after use)