diff options
Diffstat (limited to 'src')
-rw-r--r-- | src/mulk/benki/db.clj | 92 |
1 files changed, 18 insertions, 74 deletions
diff --git a/src/mulk/benki/db.clj b/src/mulk/benki/db.clj index a0475fb..89ef768 100644 --- a/src/mulk/benki/db.clj +++ b/src/mulk/benki/db.clj @@ -1,82 +1,26 @@ (ns mulk.benki.db (:refer-clojure) - (:use mulk.benki.util - clojure.java.io) - (:import [tokyocabinet HDB ADB])) + (:use mulk.benki.util) + (:require [clojure.java.jdbc :as sql])) -(def ^{:private true} db (HDB.)) -(defn- db-directory [] - ;; FIXME: This is a hack. - ;;(file (.getParent (first (clojure.java.classpath/classpath))) "db") - (file "db")) +(def ^:private db + {:classname "org.postgresql.Driver" + :subprotocol "postgresql" + :subname "//localhost:5432/benki" + :user "benki" + :password ""}) -(defn call-with-transaction [thunk] - (let [tr? (.tranbegin db)] - (if tr? - (try (let [result (thunk)] - (.trancommit db) - result) - (finally (.tranabort db))) - (do (.println java.lang.System/err "-- RETRYING TRANSACTION --") - (Thread/sleep 300) - (call-with-transaction thunk))))) +(defn call-with-db [thunk] + (sql/with-connection db + (thunk))) -(defn call-with-db [thunk mode] - (let [op? (.open db (str (file (db-directory) "benki.tch")) mode)] - (if op? - (try (thunk) - (finally (.close db))) - (do (.println java.lang.System/err "-- RETRYING OPENING DB --") - (Thread/sleep 300) - (call-with-transaction thunk))))) +(defmacro with-db [& body] + `(call-with-db (fn [] ~@body))) -(defmacro with-dbw [& body] - `(call-with-db (fn [] (call-with-transaction (fn [] ~@body))) - (bit-or HDB/OTSYNC HDB/OWRITER HDB/OCREAT))) +(defmacro with-dbt [& body] + `(call-with-db (fn [] (sql/transaction ~@body)))) -(defmacro with-dbr [& body] - `(call-with-db (fn [] ~@body) HDB/OREADER)) - -(defn- dump-str-for-db [x] - (binding [*print-dup* true - *print-meta* true] - (pr-str x))) - -(defn- getkey [key default] - (let [thing (.get db (str key))] - (if (nil? thing) - default - (read-string thing)))) - -(defn- putkey [key val] - (.put db (str key) (dump-str-for-db val))) - - -(defonce state-vars (atom {})) - - -(defmacro defstate [sym default] - (let [dbkey (str *ns* "/" (name sym))] - `(defonce ~sym - (let [r# (ref (with-dbr (getkey ~dbkey ~default)))] - (swap! state-vars #(assoc % ~dbkey r#)) - r#)))) - - -(defn save-all-global-state! [] - (with-dbw - (dosync - (doseq [[key r] @state-vars] - (putkey key (ensure r)))))) - -(defn reload-all-global-state! [] - (with-dbr - (dosync - (doseq [[key r] @state-vars] - (alter r #(getkey key %)))))) - - -;; Example. -(comment - (defstate testvar 150)) +(defmacro query [query-string & params] + `(sql/with-query-results results# ~(into [] (concat [query-string] params)) + (into '() results#))) |