Created
December 7, 2022 17:40
-
-
Save camsaul/5cc7245b6c36715b1d97ca55e08408d2 to your computer and use it in GitHub Desktop.
Dynamic app DB
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns waterfront.db | |
(:require | |
[waterfront.config :as config] | |
[waterfront.db.migrations :as db.migrations] | |
[toucan.db :as t.db]) | |
(:import | |
(com.mchange.v2.c3p0 DataSources))) | |
(set! *warn-on-reflection* true) | |
(defn- set-up-db! [^String url] | |
(with-open [conn (java.sql.DriverManager/getConnection url)] | |
(db.migrations/migrate! {:connection conn}))) | |
(defrecord ApplicationDatabase [^String url is-set-up?] | |
javax.sql.DataSource | |
(getConnection [_this] | |
(when-not @is-set-up? | |
(locking is-set-up? | |
(when-not @is-set-up? | |
(set-up-db! url)) | |
(reset! is-set-up? true))) | |
(java.sql.DriverManager/getConnection ^String (config/app-db-url)))) | |
(defn unpooled-application-database ^javax.sql.DataSource [url] | |
(->ApplicationDatabase url (atom false))) | |
(defn pooled-application-database ^javax.sql.DataSource [url] | |
(DataSources/pooledDataSource (unpooled-application-database url) (java.util.Properties.))) | |
(defonce ^:dynamic ^javax.sql.DataSource *db* | |
(pooled-application-database (config/app-db-url))) | |
(defrecord ^:private DynamicApplicationDatabase [] | |
javax.sql.DataSource | |
(getConnection [_this] | |
(.getConnection *db*))) | |
(t.db/set-default-db-connection! | |
{:datasource (DynamicApplicationDatabase.)}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment