gpt4 book ai didi

sql - 编写 clojure Honeysql where 子句

转载 作者:行者123 更新时间:2023-12-04 13:27:39 24 4
gpt4 key购买 nike

起初,我对 clojure 真的很陌生。
因此,我正在尝试使用 Honeysql 动态编写查询:

(:use [honeysql.core :as sql]
[honeysql.helpers :refer :all])

(sql/format {:select [:*] :from [:test]
:where [:or [:= :name "foo"]
[:= :name "bar"]]})

;; ["SELECT * FROM test WHERE (name = ? OR name = ?)" "foo" "bar"]

我有函数构建子句:
(defn build-clause [names]
[:or (map #(vector := :name %) names)])

(sql/format {:select [:*]
:from [:test]
:where (build-clause ["foo" "bar"])})

;; ClassCastException clojure.lang.PersistentVector cannot be cast to clojure.lang.Named

我认为问题出在返回的构建子句函数中
[:or ([:= :name "foo"] [:= :name "bar"])]

我想要这个:
[:or [:= :name "foo"] [:= :name :bar]]

我应该如何以正确的方式重写构建子句?什么样的列表展开?

最佳答案

你是对的, map 函数插入一个列表作为第二个元素,而不是按照你的意图插入。

尝试这个:

(defn build-clause2 [names]
(into [:or] (map #(vector := :name %) names)))

或者:
(defn build-clause2 [names]
(apply conj [:or] (map #(vector := :name %) names)))

或者:
(defn build-clause2 [names]
(reduce conj [:or] (map #(vector := :name %) names)))

所有这些都将达到相同的结果,因此在这种情况下更多的是品味问题。

另外, build-clausehoneysql.helpers 中的多方法命名空间。当您 honeysql.helpers :refer :all您可以创建名称冲突。

关于sql - 编写 clojure Honeysql where 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18817516/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com