Last active
March 12, 2020 16:28
-
-
Save mhvelplund/128100daaaf586058b157e52f895faaa to your computer and use it in GitHub Desktop.
Clojure workshop memory db
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
(def memory-db "A blank database" (atom {})) | |
(defn read-db "Return the entire database" [] @memory-db) | |
(defn write-db "Update the database" [new-db] (reset! memory-db new-db)) | |
(defn create-table "Create a new table" [table] | |
(write-db (assoc-in (read-db) [table] {:data [], :indexes {}}))) | |
(defn drop-table "Destroy a table" [table] | |
(write-db (dissoc (read-db) table))) | |
(defn insert "Insert a record in a table with the id-key as index" [table record id-key] | |
( | |
if (get-in (read-db) [table :indexes id-key (record id-key)]) | |
(println (str "ERROR: id '" (record id-key) "' already exists in " table)) | |
(let [ | |
database (read-db) | |
idx (count (get-in database [table :data])) | |
updated-db (assoc-in database [table :data] (conj (get-in database [table :data]) record)) | |
updated-idx (assoc-in updated-db [table :indexes id-key (record id-key)] idx) | |
] | |
(write-db updated-idx) | |
) | |
) | |
) | |
(defn select-* "Return every record in a table" [table] | |
(get-in (read-db) [table :data]) | |
) | |
(defn select-*-where "Return the record from table with the give id-key value" [table id-key value] | |
(let [ | |
database (read-db) | |
idx (get-in database [table :indexes id-key value]) | |
] | |
((get-in database [table :data]) idx) | |
) | |
) | |
;-------------------------------------------------------------------------------- | |
(create-table :clients) | |
(create-table :fruits) | |
(create-table :purchases) | |
(insert :clients {:id 1 :name "Bob" :age 32} :id) | |
(insert :clients {:id 2 :name "Alice" :age 24} :id) | |
(insert :fruits {:name "Lemon" :stock 24} :name) | |
(insert :fruits {:name "Coconut" :stock 3} :name) | |
(insert :fruits {:name "Pear" :stock 3} :name) | |
(insert :purchases {:id 1 :user-id 1 :item "Coconut"} :id) | |
(insert :purchases {:id 2 :user-id 2 :item "Lemon"} :id) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment