Created
January 9, 2023 13:02
-
-
Save eduardofcgo/c29927b24e1b13d8440350bfa4082699 to your computer and use it in GitHub Desktop.
Serialize ring session store into a jdbc compatible database, sqlite...
This file contains 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 ll.session.store | |
(:require | |
[taoensso.nippy :as nippy] | |
[clojure.java.jdbc :as jdbc] | |
[ring.middleware.session.store :refer [SessionStore]])) | |
(def serialize nippy/freeze) | |
(defn deserialize [session] | |
(when session | |
(nippy/thaw session))) | |
(def table :session_store) | |
(defn read-session-jdbc [key conn] | |
(-> (jdbc/query conn [(str "select value from " (name table) " where session_id = ?") key]) | |
first | |
:value | |
deserialize)) | |
(defn insert-session-jdbc! [session conn] | |
(let [new-session-key (java.util.UUID/randomUUID) | |
new-jdbc-session {:session_id new-session-key :value (serialize session)}] | |
(do (jdbc/insert! conn table new-jdbc-session) | |
new-session-key))) | |
(defn update-session-jdbc! [key session conn] | |
(let [new-jdbc-session {:session_id key :value (serialize session)} | |
updated (jdbc/update! conn table new-jdbc-session ["session_id = ?" key]) | |
unchanged (zero? (first updated)) | |
session-exists (not unchanged)] | |
(do (when-not session-exists (jdbc/insert! conn table new-jdbc-session)) | |
key))) | |
(defn delete-session-jdbc! [key conn] | |
(jdbc/delete! conn table ["session_id = ?" key])) | |
(deftype JdbcStore [datasource] | |
SessionStore | |
(read-session | |
[_ key] | |
(jdbc/db-transaction* datasource (partial read-session-jdbc key))) | |
(write-session | |
[_ key value] | |
(if key | |
(jdbc/db-transaction* datasource (partial update-session-jdbc! key value)) | |
(jdbc/db-transaction* datasource (partial insert-session-jdbc! value)))) | |
(delete-session | |
[_ key] | |
(jdbc/db-transaction* (partial delete-session-jdbc! key)) | |
nil)) | |
(defn jdbc-store [datasource] | |
(JdbcStore. datasource)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment