我试图动态地向Korma查询添加WHERE条件
(-> the-query
(where {:archived false})
(add-where-conditions params)
(limit 200)
(select))
我试图动态地构建对korma's where函数的调用。这个电话看起来有点像(where query (or (between :freq [100 200]) (between :freq [300 400]) ... ))
。助手函数make-conds列出where函数的参数列表,如:(or (between :freq [100 200]) ...
。
我尝试了以下方法来构建动态where调用。只有第一个,使用eval
的那个工作。为什么?有更好的方法吗?
(defn add-where-conditions [query params]
(eval (list 'where query (make-conds params))))
(defmacro add-where-conditions-2 [query params]
(list 'where query (make-conds params))) ; broken
(defmacro add-where-conditions-3 [query params]
`(where ~query ~(make-conds params))) ; broken
免责声明:我是Clojure和Korma的新手
发布于 2013-06-17 20:22:11
宏不能工作的原因是,在这两种情况下,params
参数的值都是符号params
。这就是为什么在add-where-conditions-2
和add-where-conditions-3
中,当宏进行(make-conds params)
调用时,函数接收的值不是您正在考虑的列表,而是符号params
,在以下代码行中显示了一个错误:
IllegalArgumentException Don't know how to create ISeq from: clojure.lang.Symbol clojure.lang.RT.seqFrom (RT.java:505)
第一种情况之所以有效,是因为函数接收列表(而不是符号)作为params
参数的值,因此eval
接收列表(where {:your-query nil} (or (between :freq [100 200]) ,,,))
,这是where
宏所期望的,并且知道如何处理。
where
宏解析表达式,以搜索用于构建表达式的一些谓词。where*
,函数替代,没有这种功能,所以我想不出一个替代eval
吃蛋糕和拥有它。
https://stackoverflow.com/questions/17135794
复制相似问题