What is the proper way to store a global connection in Clojure?

I have the following file that acts as an access point to my database from API endpoints. How can one connection (or connection pool?) Be maintained during the life of the server?

(ns my-api.repository
  (:require [clojure.java.jdbc :as sql]))

(defn some-query
  (sql/with-connection (System/getenv "DATABASE_URL")
    (sql/with-query-results results
      ;; You get the picture
      )))
+5
source share
4 answers

stored DATABASE_URLif you use a macro with-connectionfor a single connection. you can use c3p0 library for connection pool:

(defn pooled-spec
  "return pooled conn spec.
   Usage:
     (def pooled-db (pooled-spec db-spec))
     (with-connection pooled-db ...)"
  [{:keys [classname subprotocol subname user password] :as other-spec}]
  (let [cpds (doto (ComboPooledDataSource.)
               (.setDriverClass classname)
               (.setJdbcUrl (str "jdbc:" subprotocol ":" subname))
               (.setUser user)
               (.setPassword password))]
    {:datasource cpds}))
+4
source

I also recommend c3p0. Clojure pooling provides a brief introduction to how to configure clojure.java.jdbcc3p0.

+2
source

jdbc-pool C3P0 clojure.java.jdbc. ( ).

+1

, . Doc , 2.3 , db . :

(defn with-connection*
  "Evaluates func in the context of a new connection to a database then
  closes the connection."
  [db-spec func]
  (with-open [^java.sql.Connection con (get-connection db-spec)]
    (binding [*db* (assoc *db* :connection con :level 0 :rollback (atom false))]
      (func))))

A connection pool can be useful for lazy creation, but this does not make them open. It seems like you need to establish a connection. However, the latter API emphasizes simply creating a connection and passing it to each call. Although ALPHA still looks, it looks like the future for this library (and is still compatible with the connection pool). From the wiki library:

(require '[clojure.java.jdbc :as j]
     '[clojure.java.jdbc.sql :as s])

(def mysql-db {:subprotocol "mysql"
               :subname "//127.0.0.1:3306/clojure_test"
               :user "clojure_test"
               :password "clojure_test"})

(j/insert! mysql-db :fruit
  {:name "Apple" :appearance "rosy" :cost 24}
  {:name "Orange" :appearance "round" :cost 49})
0
source

All Articles