FWIW, much safer is
(defmacro dc
[sql-cmd]
`(sql/with-connection db
~sql-cmd))
If you use the version with (list) and plain-quoting of the first two
items, then the namespace resolution is very fragile: it will only
work if the caller has referred to the sql library with the prefix
sql/, and if they have the db in scope. The syntax-quote expands those
to their fully-qualified names, so that they always refer to the thing
you intend, even if (god forbid) the user has an unrelated local
variable named db in their lexical scope.
On Dec 15, 10:37 am, Cedric Greevey <[email protected]> wrote:
> On Thu, Dec 15, 2011 at 1:14 PM, Peter Buckley <[email protected]> wrote:
> > TL;DR I have an extra clojure.core/fn wrapped around the form I want
> > returned from my macro. This is my first macro and I'm not sure what's
> > wrong, even though the macro "works."
>
> ...
>
>
>
>
>
>
>
>
>
> > (defmacro dc
> > [sql-cmd]
> > (list 'sql/with-connection 'db
> > sql-cmd))
>
> > This macro works in that it actually invokes the form I want, but when
> > I run macroexpand on it I have an extra clojure.core/fn wrapped around
> > my command, and when I compare that output to the "when" macro (which
> > does not have the clojure.core/fn wrapper that I can see), I think
> > I've got it wrong.
>
> > user> (macroexpand '(when (pos? a) (println "positive") (/ b a)))
> > (if (pos? a) (do (println "positive") (/ b a)))
>
> > user> (macroexpand '(dc (sql/create-table :testing [:data :text])))
> > (clojure.java.jdbc.internal/with-connection* db (clojure.core/fn []
> > (sql/create-table :testing [:data :text])))
>
> Try macroexpand-1. Plain macroexpand expands your macro, but the result is]
>
> (sql/with-connection db (sql/create-table :testing [:data :text]))
>
> which starts with another macro call, (sql/with-connection ...), and
> if that happens macroexpand expands that macro as well. And apparently
> (sql/with-connection foo) expands to
>
> (clojure.java.jdbc.internal/with-connection* db (clojure.core/fn [] foo))
>
> hence your confusion.
--
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