Cut & paste from my own code base:
(def ^:dynamic *db-conn*)
(defmacro with-db-connection [& body]
`(jdbc/with-db-connection [con# (get-db-conn)]
(binding [*db-conn* con#]
~@body)))
A few points. Do not give any value to the dynamic var, make it unbound and
make it fail early for unexpected usage. Set a value via binding and make a
macro then use the dynamic var only through the macro (i.e., hide its
existence)
That's how I normally use dynamic vars. Some people afraid of using it, but
it is like a knife - If you know how to use it, it is useful to remove
unnecessary complexity.
On Friday, 31 July 2015 10:44:31 UTC+10, J. Pablo Fernández wrote:
>
> Hello Clojurians,
>
> I found passing around the database connection to each function that uses
> it very error prone when you are using transactions as passing the wrong
> one could mean a query runs outside the transaction when in the source code
> it is inside the with-db-transaction function. So I ended up defining the
> db namespace like this:
>
> (ns db)
>
> (defonce ^:dynamic conn (atom nil))
>
> (defn connect!
> (reset conn (generate-new-connection)))
>
> (defn run-query
> [query] (run-query query @conn)
> [query conn] (run-the-query-in-connection query conn))
>
>
> This is pseudo-code of course, simplified to highlight the part that I'm
> most unfamiliar with:
>
> (defonce ^:dynamic conn (atom nil))
>
> The reason why it's an atom is so that connect! can *set* it and the
> reason why it's a dynamic var is so I can do this:
>
> (jdbc/with-db-transaction
> [db-connection-with-transaction @db/conn]
> (binding [db/conn (atom db-connection-with-transaction)]
> (db/run-query "SELECT *"))))))
>
> and the query will be implicitly run inside the transaction. Does it make
> sense? Is this wrong? will it fail in unexpected ways? Is there a better
> way?
>
> Thanks.
>
>
>
--
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to [email protected]
Note that posts from new members are moderated - please be patient with your
first post.
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en
---
You received this message because you are subscribed to the Google Groups
"Clojure" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
For more options, visit https://groups.google.com/d/optout.