Clojure 数据库访问模式/惯用语
此要点中列出的宏 https://gist.github.com/1177043 (粘贴在下面)
(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))))
似乎非常有用。这些有“标准”实施吗?按照标准,我指的是 clojure.contrib 或类似的东西。我可以轻松地将其复制并粘贴到我的代码中,但我想知道是否有更好的方法。或者,换句话说,clojure 执行此操作的方法是什么?
这是我第一次尝试实际编写 clojure 代码(我已经阅读了很多有关它和 Common Lisp 的内容),因此我也尝试了解现有的库。在我看来,Lisp 的心态有点像“我自己可以用 15 行写出来,为什么我要用别人的”。
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".
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
据我所知,当您抽象超出
sql/transactions
等时,抽象往往更加特定于应用程序。 按照上面的方式编写自己的包装器,当它真正使事情变得更简单时,这是处理事情的规范方法。仅使用尽可能多的宏,实际上使您的生活更简单,它可能会以更令人困惑或更难维护的方式吸引下一个宏(如要点)。我喜欢这个要点;只是要小心不要过度宏观。
ps:如果某些代码超过五行,我会首先查看是否是其他人编写的:),但许多 clojurian 人有不同的感觉。
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.