使用korma和clojure生成查询子句 [英] Generating query clauses with korma and clojure

查看:129
本文介绍了使用korma和clojure生成查询子句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图根据传递给函数的列和值的映射生成korma查询条件。



我发现当一个空的地图是传递到korma的位置:

 (选择things
(where条件))

生成带有WHERE的查询,导致SQL错误:

  SELECT * FROM WHERE()LIMIT 10 



 (选择事物
(如果不是(空?条件)
)))

导致错误:错误的args数(1)传递给:core $其中



在korma中处理动态子句有没有惯用的方式?



UPDATE

$




(defn do-select []
( - >(select *things)
(fields:id:data)
(limit 10)))
$ b b(defn add-constraints [query conditions]
(if(empty?条件)
查询
(其中query(条件到条款映射条件))))

(select(do-select)
条件)
(where(is_owner?owner)))


解决方案

你可能想出了一种方法来解决这个问题,但我会chime。个人而言,我最终使用cond->宏,如果你使用Clojure 1.6 +。可用。



您可以在新的线程宏中找到信息此处



生成的代码看起来像这样:

 (let [query( - >(select *things)
(fields:id:data)
10))]
( - >(cond-> query
条件(其中条件)
more-


I am trying to generate korma query conditions based on a map of columns and values that I pass into a function.

I am finding that when an empty map is passed to korma's where:

(select "things"
  (where conditions))

Generates queries with an empty WHERE which causes a SQL error:

SELECT * FROM things WHERE () LIMIT 10 

However using this form:

(select "things"
  (if-not (empty? conditions) 
    (where conditions)))

Results in an error: "Wrong number of args (1) passed to: core$where"

Is there an idiomatic way of handling dynamic clauses in korma?

UPDATE

The following works, but is pretty clumsy (note the strangely necessary if format)

(defn do-select []
  (->  (select* "things") 
    (fields :id :data)
    (limit 10)))

(defn add-constraints [query conditions]
  (if (empty? conditions) 
      query
      (where query (conditions-to-clause-map conditions))))

(select (do-select) 
  (add-constraints conditions)           
  (where (is_owner? owner)))     

解决方案

You've probably figured out a way to solve this but I'll chime in. Personally I end up using the cond-> macro which is available if you're using Clojure 1.6+.

You can find information on the new threading macros here.

The resulting code looks like something like this:

(let [query (->(select* "things") 
                 (fields :id :data)
                 (limit 10))]
  (-> (cond-> query
         conditions (where conditions)
         more-conditions (where more-conditions))
      (exec)))

这篇关于使用korma和clojure生成查询子句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆