简体   繁体   English

强制hugsql查询函数在返回错误数量的结果时引发错误

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

Using Clojure and hugsql. 使用Clojure和hugsql。 I define my queries as such. 我这样定义我的查询。

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

After using def-db-fns , this will create a function query-should-return-one-but-returns-multiple in my namespace. 在使用def-db-fns ,这将在我的命名空间中创建一个query-should-return-one-but-returns-multiple的函数。

However, if I have more than one row in some_table , this function will simply return an arbitrary row, and will not signal an error. 但是,如果some_table有多行,则此函数将仅返回任意行,并且不会发出错误信号。

How could I force query functions defined to return :one to throw an exception if the database returned more than one result? 如果数据库返回多个结果,如何强制定义的查询函数返回:one引发异常?

-- :result :one simply takes the first row of the returned result set of your query, so there is no verification that your query returns exactly 1 record (hashmap). -- :result :one只是获取查询返回结果集的第一行,因此无法验证查询是否恰好返回了-- :result :one记录(哈希映射)。

However, HugSQL uses Clojure multimethods to define its result types, so you can create your own or override existing methods to fit your needs. 但是,HugSQL使用Clojure多方法来定义其结果类型,因此您可以创建自己的方法或覆盖现有方法以满足需要。

We define a function result-exactly-one that will throw an exception when the count of the result is not one. 我们定义一个函数result-exactly-one ,当结果的计数不为1时将抛出异常。 We then define the hugsql-result-fn multimethod with the :exactly-one keyword. 然后,使用:exactly-one关键字定义hugsql-result-fn多方法。 Please note the quoted, namespaced ( user in this case) symbol referring to the function we've created. 请注意,带引号的命名空间符号(在本例中为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;

And the result when 0 or more than one records are returned: 并返回0个或多个记录的结果:

user=> (return-exactly-one db)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM