what's wrong with this code to use clojure.java.jdbc/insert -
i tried use java.jdbc insert! function, can receive multiple objects. clojure.java.jdbc/insert!
should called this:
(clojure.java.jdbc/insert! db {:name "john" :password "123"} {:name "george" :password "234"})
i defined function add multiple user records:
(defn add-users [user & more] (-add-users db-spec user more)) (defmacro -add-users ([db user] `(j/with-db-connection [con-db# db] (j/insert! con-db# ~user))) ([db user & more] (let [users (-mk-user-list user more)] `(j/with-db-connection [con-db# db] (j/insert! con-db# ~@(flatten users))))) (defmacro -mk-usre-list ([user] `~user) ([user & more] `(list ~user (-mk-user-list ~@more))))
when macroexpand -add-users, looks result ok this:
=> (macroexpand '(-add-users db-spec {:name "john" :password "1234"})) (let* [db-spec__21320__auto__ db-spec] (clojure.core/with-open [con__21321__auto__ (clojure.java.jdbc/get-connection db-spec__21320__auto__)] (clojure.core/let [con-db__23557__auto__ (clojure.java.jdbc/add-connection db-spec__21320__auto__ con__21321__auto__)] (clojure.java.jdbc/insert! con-db__23557__auto__ {:name "john", :password "1234"}))))
but when run :
=> (add-users {:name "john" :password "1234"}) illegalargumentexception insert called columns no values clojure.java.jdbc/insert-sql (jdbc.clj:992)
what's wrong macro? or how should wrap , pass number of arguments function insert!
needs arguments flattened?
[update] problem found: insert! needs table while in code it's not there.
(j/insert! con-db# ~user) should (j/insert! con-db# :users ~user) (j/insert! con-db# ~@(flatten users)) should (j/insert! con-db# :users ~@(flatten users))
but there anyway simpler it?
you can solve without macro, using apply:
user=> (doc apply) ------------------------- clojure.core/apply ([f args] [f x args] [f x y args] [f x y z args] [f b c d & args]) applies fn f argument list formed prepending intervening arguments args. (defn my-insert! [x & more] (apply jdbc/insert! db :table x more))
Comments
Post a Comment