强制 hugsql 查询函数在 return 个错误的结果数时抛出错误

Force hugsql query functions to throw an error when they return the wrong number of results

使用 Clojure 和 hugsql。我这样定义我的查询。

-- :name query-should-return-one-but-returns-multiple
-- :result one
-- :command :query
SELECT v.id FROM some_table v;

使用 def-db-fns 后,这将在我的命名空间中创建一个函数 query-should-return-one-but-returns-multiple

但是,如果我在 some_table 中有不止一行,此函数将只是 return 任意一行,并且不会发出错误信号。

如果数据库 return 编辑了多个结果,我如何强制定义为 return :one 的查询函数抛出异常?

-- :result :one 只是获取查询返回结果集的第一行,因此无法验证您的查询 returns 正好是 1 条记录(散列图)。

但是,HugSQL 使用 Clojure 多方法来定义其结果类型,因此您可以创建自己的方法或覆盖现有方法以满足您的需要。

我们定义了一个函数result-exactly-one,当结果的计数不为一时会抛出异常。然后,我们使用 :exactly-one 关键字定义 hugsql-result-fn 多方法。请注意带引号的命名空间(在本例中为 user)符号指的是我们创建的函数。

(require '[hugsql.core :as hugsql]
         '[hugsql.adapter])

(defn result-exactly-one
  [this result options]
  (let [rs (hugsql.adapter/result-many this result options)]
    (if (= 1 (count rs)) 
        rs 
        (throw (ex-info "Oops!" {})))))

(defmethod hugsql/hugsql-result-fn :exactly-one [sym] 'user/result-exactly-one)
-- :name return-exactly-one
-- :result :exactly-one
-- :command :query
SELECT v.id FROM t1 v;

返回0条或多条记录时的结果:

user=> (return-exactly-one db)

ExceptionInfo Oops!  clojure.core/ex-info (core.clj:4617)