HoneySQL无法在WHERE子句中处理复合键吗?

时间:2019-02-19 18:42:44

标签: clojure honeysql

我无法让HoneySQL发出允许我在WHERE子句中使用复合键的SQL。

我想要得到的是: SQL:

SELECT field_id, layer, event_date, is_deleted
FROM event
WHERE 
  field_id in ('1325629', '1627236', '1673576') AND
  layer in ('fha.raw') AND
  (field_id,layer,event_date) > ('1627236','fha.raw', '2018-07-23 09:45:07.6-07')
ORDER BY field_id, layer, event_date;

HoneySQL:

(-> (sqlh/select :field_id :layer :event_date :is_deleted)
    (sqlh/from :event)
    (sqlh/merge-where [:in :field_id field-ids])
    (sqlh/merge-where (cond (not-empty layers) [:in :layer layers]))
    (sqlh/merge-where [:> 
                       [:field_id :layer :event_date] 
                       ["1627236" "fha.raw" (c/from-string "2018-07-23T09:45:07.6-07:00")]])
    (sqlh/order-by :field_id :layer :event_date)
    sql/format)

HoneySQL产生了无法正常工作的东西

["SELECT field_id, layer, event_date, is_deleted FROM event WHERE (((field_id in (?, ?, ?)) AND (layer in (?, ?, ?, ?))) AND field_id(layer, event_date) > 1627236(?, ?)) ORDER BY field_id, layer, event_date"
 "1325629"
 "1627236"
 "1673576"
 "fha.abs"
 "fha.rank"
 "fha.true-color"
 "fha.raw"
 "fha.raw"
 #object[org.joda.time.DateTime 0x4fa79ee8 "2018-07-23T16:45:07.600Z"]]


...它在WHERE子句中混淆了我的复合键,错误地构建了函数调用或诸如此类:field_id(layer, event_date)而不是(field_id, layer, event_date)

我如何进行这项工作?

这与我之前在ORDER BY子句(How can I make HoneySQL handle order by as a compound key?)中尝试执行相同操作时所问的问题有关。事实证明,从没有真正解决过复合键问题,但是确实允许我在其中一个字段上对DESC进行排序。换句话说,我还没有找到如何使HoneySQL在WHERE或ORDER BY子句中执行复合键。

我可以多说一些。

2 个答案:

答案 0 :(得分:1)

与大多数SQL抽象一样,HoneySQL仅适用于标准情况。我相信现在是使用raw语句的好时机。它按原样插入SQL语句,而不用功能或标记对其进行预处理:

(sql/raw "@var := foo.bar")
#sql/raw "@var := foo.bar"

在您的情况下,只是:

...
(sqlh/merge-where
  #sql/raw "(field_id,layer,event_date) > ('1627236','fha.raw', '2018-07-23 09:45:07.6-07')")
...

你很好。

当然,千万不要将用户的输入传递到原始SQL语句中。

答案 1 :(得分:0)

您可能要考虑Walkable,这是另一个SQL语言库,具有较强的表达能力 https://walkable.gitlab.io/s-expressions.html

例如,这是您的查询翻译为Walkable:

(let [field-ids     [1 2 3]
      layers        ["a" "b" "c"]
      layer-filters (when (not-empty layers) `([:in :layer ~@layers]))]
  `[(:event/all {:filters  [:and [:in :event/field-id ~@field-ids]
                            ~@layer-filters
                            [:> [:tuple :event/field-id :event/layer :event/event-date]
                             [:tuple "1627236" "fha.raw" "2018-07-23T09:45:07.6-07:00"]]]
                 :order-by [:event/field-id :event/layer :event/event-date]}
                [:event/field-id :event/layer :event/event-date :event/is-deleted])])