Skip to content

Commit

Permalink
db: SQLite optimizations
Browse files Browse the repository at this point in the history
  • Loading branch information
goshatch committed Aug 31, 2024
1 parent 6882723 commit 661303f
Showing 1 changed file with 48 additions and 12 deletions.
60 changes: 48 additions & 12 deletions src/apossiblespace/parts/db.clj
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,34 @@
[migratus.core :as migratus]
[honey.sql :as sql]
[com.brunobonacci.mulog :as mulog]
[apossiblespace.parts.config :as conf])
[apossiblespace.parts.config :as conf]
[clojure.string :as str])
(:import
[java.util UUID]))

(def db-spec
{:dbtype "sqlite"
:dbname (conf/database-file (conf/config))})

(def datasource
(jdbc/get-datasource db-spec))
(def pragmas
["PRAGMA journal_mode = WAL;"
"PRAGMA busy_timeout = 5000;"
"PRAGMA synchronous = NORMAL;"
"PRAGMA cache_size = -20000;"
"PRAGMA foreign_keys = true;"
"PRAGMA temp_store = memory;"])

(defn- create-datasource [read-only?]
(let [url (str "jdbc:sqlite:" (:dbname db-spec))
ds-opts (cond-> {:jdbcUrl url
:connectionInitSql (str/join " " pragmas)
:foreign_keys true}
read-only? (assoc :mode "ro")
(not read-only?) (assoc :mode "rwc" :_txlock "immediate"))]
(jdbc/get-datasource ds-opts)))

(def read-datasource (create-datasource true))
(def write-datasource (create-datasource false))

(def migration-config
{:store :database
Expand All @@ -33,7 +51,7 @@

(defn query
[q]
(jdbc/execute! datasource q {:builder-fn rs/as-unqualified-maps}))
(jdbc/execute! read-datasource q {:builder-fn rs/as-unqualified-maps}))

(defn query-one
[q]
Expand All @@ -45,16 +63,34 @@
(defn insert!
[table data]
(let [data-with-uuid (assoc data :id (generate-uuid))]
(query (sql/format {:insert-into table
:values [data-with-uuid]}))))
(jdbc/execute! write-datasource
(sql/format {:insert-into table
:values [data-with-uuid]})
{:builder-fn rs/as-unqualified-maps})))

(defn udpate!
(defn update!
[table data where-clause]
(query (sql/format {:update table
:set data
:where where-clause})))
(jdbc/execute! write-datasource
(sql/format {:update table
:set data
:where where-clause})
{:builder-fn rs/as-unqualified-maps}))

(defn delete!
[table where-clause]
(query (sql/format {:delete-from table
:where where-clause})))
(jdbc/execute! write-datasource
(sql/format {:delete-from table
:where where-clause})
{:builder-fn rs/as-unqualified-maps}))

;; Connection pool configuration
(def read-pool-spec
{:datasource read-datasource
:maximum-pool-size (max 4 (.availableProcessors (Runtime/getRuntime)))})

(def write-pool-spec
{:datasource write-datasource
:maximum-pool-size 1})

(def read-pool (jdbc/get-datasource read-pool-spec))
(def write-pool (jdbc/get-datasource write-pool-spec))

0 comments on commit 661303f

Please sign in to comment.