[英]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
有多行,則此函數將僅返回任意行,並且不會發出錯誤信號。
如果數據庫返回多個結果,如何強制定義的查詢函數返回:one
引發異常?
-- :result :one
只是獲取查詢返回結果集的第一行,因此無法驗證查詢是否恰好返回了-- :result :one
記錄(哈希映射)。
但是,HugSQL使用Clojure多方法來定義其結果類型,因此您可以創建自己的方法或覆蓋現有方法以滿足需要。
我們定義一個函數result-exactly-one
,當結果的計數不為1時將拋出異常。 然后,使用: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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.