three-cups
three-cups

Reputation: 4385

Clojure Database Access Patterns/Idioms

The macros listed in this gist https://gist.github.com/1177043 (pasted below)

(defmacro wrap-connection [& body]
  `(if (sql/find-connection)
    ~@body
    (sql/with-connection db ~@body)))

(defmacro transaction [& body]
  `(if (sql/find-connection)
     (sql/transaction ~@body)
     (sql/with-connection db (sql/transaction ~@body))))

seem to be pretty useful. Is there a "standard" implementation of these? By standard, I mean something in clojure.contrib or similar. I can easily copy and paste this into my code, but I'm wondering if there's a better way. Or, put another way, what's the clojure way of doing this?

This is my first forray into actually writing clojure code (I've read a lot about it and Common Lisp), so I'm also trying to get a feel for what libraries are out there. It seems to me that the Lisp mentality is kind of "I can write it myself in 15 lines, so why would I use somebody else's".

Upvotes: 2

Views: 349

Answers (1)

Arthur Ulfeldt
Arthur Ulfeldt

Reputation: 91577

From what I have seen, when you abstract beyond sql/transactions etc then the abstractions tend to be more application specific. writing your own wrappers as above when it truely makes things simpler is the canonical way to go about things.

Only use as many macroes as actually makes your life simpler, it can be tempting to next macroes (as in the gist) in ways that are more confusing or harder to maintain. I like this gist; just be careful not to over-macro.

ps: if some code is more than about five lines I look to see if someone else has written it first :) but many clojurians feel differently.

Upvotes: 1

Related Questions