Hello,

I think you are coming to a point where you might want to consider Stuart 
Sierra's component library. 
https://github.com/stuartsierra/component

A dynamic var is kind of thread-bounded global state, which is to be 
avoided. 

There is a nice talk to go with it
https://www.youtube.com/watch?v=13cmHf_kt-Q

Kr,

Jo



Op vrijdag 31 juli 2015 02:44:31 UTC+2 schreef J. Pablo Fernández:
>
> 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.

Reply via email to