Fork me on GitHub
#sql
<
2020-10-26
>
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? ;; https://gist.githubusercontent.com/mikeball/ba04dd5479f51c00205f/raw/583f292cc2ba2528ffa0629d92de0fbe597d7cb7/core.clj I did my best to make it look more how I (as a beginner) would expect it to. ;; http://ix.io/2C8g Unfortunately the way I made it, returns a PGPreparedStatement instead of a PGSimpleStatement.

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

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

seancorfield20:10:37

(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.

seancorfield20:10:30

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

seancorfield20:10:50

And clojure.java.jdbc 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.

seancorfield20:10:31

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
seancorfield20:10:42

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
seancorfield20:10:59

(that automatically closes the statement after use)