使用 hugSQL def-db-fns 宏时如何避免使用 clj-kond 无法解析的符号?

How to avoid unresolved symbol with clj-kond when using hugSQL def-db-fns macro?

我使用 VS Code Calva extension, which uses clj-kondo 编写 Clojure 来对我的代码执行静态分析。

我正在使用 HugSQL 从 SQL 查询和语句创建 Clojure 函数。

我知道我可以处理数据库连接和 HugSQL 与像 conman 这样的库的集成,事实上我过去使用过它并且我喜欢它,但这次我想保持原样,自己和 HugSQL 谈谈。

HugSQL 的 def-db-fns 宏采用 SQL 文件并根据该文件中包含的 SQL 查询和语句创建 Clojure 函数。

我下面的代码有效,但 clj-kondo 抱怨说 seed-mytable! 是一个未解析的符号。

(ns my-app.db
  "This namespace represents the bridge between the database world and the clojure world."
  (:require [environ.core :refer [env]]
            [hugsql.core :as hugsql]
            [nano-id.core :refer [nano-id]]))

;; This create the function seed-mytable!, but clj-kondo doesn't (cannot?) know it.
(hugsql/def-db-fns "sql/mytable.sql")

;; The functions created by HugSQL can accept a db-spec, a connection, a connection pool,
;; or a transaction object. Let's keep it simple and use a db-spec for a SQLite database.
(def db-spec {:classname "org.sqlite.JDBC"
              :subprotocol "sqlite"
              :subname (env :database-subname)})

(defn db-seed
  "Populate the table with some fakes."
  []
  (let [fakes [[(nano-id) "First fake title" "First fake content"]
               [(nano-id) "Second fake title" "Second fake content"]]]

    ;; clj-kondo complains that seed-my-table! is an unresolved symbol
    (seed-mytable! db-spec {:fakes fakes})))

我明白为什么 clj-kondo 抱怨:seed-mytable! 没有在任何地方定义,它在调用 def-db-fns 宏时在此命名空间中 "injected"。

有没有办法告诉 clj-kondo 在调用 hugsql/def-db-fns 宏之后符号确实存在?

可能没那么有用,但这是我用 HugSQL.SQL.

加载的 SQL 文件
-- :name seed-mytable!
-- :command :execute
-- :result :affected
-- :doc Seed the `mytable` table with some fakes.
INSERT INTO mytable (id, title, content)
VALUES :t*:fakes;

来自 clj-kondo documentation:

有时通过执行宏来引入变量,例如使用 HugSQLdef-db-fns 时。您可以使用 declare 抑制有关这些变量的警告。示例:

(ns hugsql-example
  (:require [hugsql.core :as hugsql]))

(declare select-things)

;; this will define a var #'select-things:
(hugsql/def-db-fns "select_things.sql")

(defn get-my-things [conn params]
  (select-things conn params))

如果 HugSQL 引入的符号数量变得太笨重,请考虑 引入一个单独的命名空间,HugSQL 在其中生成变量: foo.db.hugsql。然后,您可以使用 foo.db 引用此命名空间 (require '[foo.db.hugsql :as sql]) (sql/insert! ...) clj-kondo 不会 抱怨这个。