我正在检查YeSQL是否可以帮助我的Clojure项目,但我找不到使用连接池的任何YeSQL示例.
这是否意味着YeSQL创建了与每个语句的新连接?
我还找到了一个关于如何使用clojure.java.jdbc/with-db-transaction来使用事务的例子,但我觉得它已经过时了(我还没有尝试过).
这是否意味着YeSQL依赖clojure.java.jdbc来提交/回滚控制?在这种情况下,我不应该单独使用clojure.java.jdbc,因为YeSQL不提供太多(除了命名我的查询和外化它们)?
提前致谢
YeSQL 不处理连接或连接池。您需要在外部处理它并为查询函数提供连接实例。
正如您从README中的 YeSQL 示例中看到的:
; Define a database connection spec. (This is standard clojure.java.jdbc.)
(def db-spec {:classname "org.postgresql.Driver"
:subprotocol "postgresql"
:subname "//localhost:5432/demo"
:user "me"})
; Use it standalone. Note that the first argument is the db-spec.
(users-by-country db-spec "GB")
;=> ({:count 58})
; Use it in a clojure.java.jdbc transaction.
(require '[clojure.java.jdbc :as jdbc])
(jdbc/with-db-transaction [connection db-spec]
{:limeys (users-by-country connection "GB")
:yanks (users-by-country connection "US")})
Run Code Online (Sandbox Code Playgroud)
如果您询问如何添加连接池处理,您可以查看Clojure Cookbook中的示例。
至于事务处理,YeSQL 文档没有,但是源码很容易理解:
(defn- emit-query-fn
"Emit function to run a query.
- If the query name ends in `!` it will call `clojure.java.jdbc/execute!`,
- If the query name ends in `<!` it will call `clojure.java.jdbc/insert!`,
- otherwise `clojure.java.jdbc/query` will be used."
[{:keys [name docstring statement]}]
(let [split-query (split-at-parameters statement)
{:keys [query-args display-args function-args]} (split-query->args split-query)
jdbc-fn (cond
(= [\< \!] (take-last 2 name)) `insert-handler
(= \! (last name)) `execute-handler
:else `jdbc/query)]
`(def ~(fn-symbol (symbol name) docstring statement display-args)
(fn [db# ~@function-args]
(~jdbc-fn db#
(reassemble-query '~split-query
~query-args))))))
Run Code Online (Sandbox Code Playgroud)
因此它只会生成一个函数,该函数将调用clojure.java.jdbc/execute!或clojure.java.jdbc/insert!使用生成的查询。您可能需要参阅这些函数的文档以获取更多详细信息。