0

I have a database with a status entity that I'd like to be able to fetch in many different ways. As a result, I'd like to build the WHEN clause of my query based on the content of a map.

For instance, like this:

(get-status *db* {:message_id 2 :user_id 1 :status "sent"})
;; or
(get-status *db* {:message_id 2})
;; or
(get-status *db* {:user_id 1})
;; etc.

I'm struggling using hubsql's clojure expressions. I am doing the following:

-- :name get-status
-- :doc fetch the status of a specific message
-- :command :query
-- :return :many
/* :require [clojure.string :as s] */
SELECT
    *
FROM
    message_status
/*~
(let [params (filter (comp some? val) params)]
  (when (not (empty? params))
    (str "WHERE "
      (s/join ","
              (for [[field value] params]
                (str field " = " (keyword field)))))))
~*/

However, here is how the request is prepared by hugsql:

=> (get-status-sqlvec {:message_id 2 :user_id 1})
["SELECT\n    *\nFROM\n    message_status\nWHERE ? = ?,? = ?" 2 2 1 1]

Whereas I want something like:

=> (get-status-sqlvec {:message_id 2 :user_id 1})
["SELECT\n    *\nFROM\n    message_status\nWHERE message_id = 2, user_id = 1"]
4

1 回答 1

0

我终于设法让这个工作。上面的代码有两个问题。

首先,我们有

(s/join ","
  (for [[field value] params]
    (str field " = " (keyword field)))

由于field是关键字,这实际上会生成这种字符串::foo = :foo, :bar = :bar. 然后将关键字替换为?hugsql。我们想要的是构建这种字符串foo = :foo, bar = :bar,我们可以用这段代码来做:

(s/join ", "
  (for [[field _] params]
    (str (name field) " = " field))))))

第二个问题是该WHEN子句甚至不是有效的 SQL。上面的代码最终生成请求,例如:

SELECT * FROM message_status WHERE foo = 2, bar = 1

子句中的逗号WHERE应该是AND,所以最终(工作)代码是:

-- :name get-status
-- :doc fetch the status of a specific message
-- :command :query
-- :return :many
/* :require [clojure.string :as s] */
SELECT
    *
FROM
    message_status
/*~
(let [params (filter (comp some? val) params)]
  (when (not (empty? params))
    (str "WHERE "
      (s/join " AND "
              (for [[field _] params]
                (str (name field) " = " field))))))
~*/
于 2019-07-24T15:58:15.803 回答