[英]clojure: dynamically compose query with korma
我正在嘗試使用korma創建一個非常簡單的API
用戶可以這樣查詢數據庫:
localhost:8080/my_postgres_db/users.json?where[age]=50&limit=1
當前,當我嘗試將where子句應用於現有的,可組合的查詢時遇到錯誤。
clojure.lang.ArityException: Wrong number of args (2) passed to: core$where
有問題的代碼 :
(defn- comp-query [q [func arg]]
(let [sql-fn (ns-resolve 'korma.core (-> func name symbol))]
(sql-fn q arg)))
(defn compose-query [table col]
(reduce comp-query (select* table) col))
用法 :
(def clauses {:where {:column1 10} :fields "a,b" :limit 10 :offset 500})
(-> (compose-query table clauses) select)
除where子句外,其他所有行為均符合預期。 我可以選擇任何方式組合極限,偏移量和字段,從而獲得預期的結果。 只有在我的地圖中有:where
鍵時,我才會遇到錯誤。
我在嘗試不該做的事情嗎? 這是不好的Clojure嗎? 任何幫助,將不勝感激。
注意:我已閱讀過此問題
編輯 :從lein repl
我可以以相同的方式手動組成查詢,並且可以正常工作
(where (select* "my_table") {:a 5})
編輯:如果我修改我的compose-query
函數為此:
(defn compose-query [table col]
; remove where clause to process seperately
(let [base (reduce comp-query (select* table) (dissoc col :where))]
(if-let [where-clause (:where col)]
(-> base (where where-clause))
base)))
一切都按預期工作。
這里的問題是korma.core/where
不是函數,需要特別處理。 無法在哪里實現為函數,仍然可以正確處理類似的東西(where query (or (= :hits 1) (> :hits 5)))
您可以像使用select*
一樣使用where*
功能。 只需使您的子句映射如下:
(def clauses {:where* {:column1 10} :fields "a,b" :limit 10 :offset 500})
只是一種預感; 擴展一些線程宏會使您很難看清它們是否正確:
core> (macroexpand-1 '(-> (compose-query table clauses) select))
(select (compose-query table clauses))
core> (macroexpand-1 '(-> func name symbol))
(clojure.core/-> (clojure.core/-> func name) symbol)
core> (macroexpand-1 '(clojure.core/-> func name))
(name func)
將func傳遞給名稱看起來很可疑。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.