Skip to content

Instantly share code, notes, and snippets.

View kumarshantanu's full-sized avatar

Shantanu Kumar kumarshantanu

View GitHub Profile
(def db-mysql
(let [db-host "localhost"
db-port 3306
db-name "sqlrat"]
{ :classname "com.mysql.jdbc.Driver" ; must be in classpath
:subprotocol "mysql"
:subname (str "//" db-host ":" db-port "/" db-name)
; Any additional keys are passed to the driver
; as driver-specific properties.
:user "root"
(defrecord BlogEntry [])
(defrecord EntryComment [])
(def blog-entry-meta
(entity-meta :entry :autoid (from-row BlogEntry.)
:cols [[:autoid :int "NOT NULL PRIMARY KEY AUTO_INCREMENT"]
[:title "varchar(30)" "NOT NULL"]
[:content "varchar(500)" "NOT NULL"]
[:whenposted "DATETIME" "NOT NULL"]
[:isdeleted "BOOLEAN" "NOT NULL DEFAULT false"]] ))
(def entry-comment-meta
(entity-meta :comment :autoid (from-row EntryComment.)
(extend-entity BlogEntry
blog-entry-meta
[(one-to-many :autoid entry-comment-meta :entryid)] )
(extend-entity EntryComment
entry-comment-meta
[(many-to-one :entryid blog-entry-meta :autoid)] )
(in-db db
(println "** Dropping tables **")
(try
(drop-table blog-entry-meta)
(catch Exception e
(println (str "Error dropping table " (:name blog-entry-meta) ": "
(.getMessage e) " [Ignored]"))))
(try
(drop-table entry-comment-meta)
(catch Exception e
(defn ppe ;; pretty-print-entities
([e]
(print-entities e))
([label e]
(println label)
(print-entities e)))
(let [e1 (BlogEntry. {}
{:title "Test"
:content "Hello World"
(in-txn db
(let [saved (save (BlogEntry. {}
{:title "Test"
:content "Hello World"
:whenposted (new java.util.Date)} ))]
(ppe "Saved row #1" saved)
(let [saved-again (save (assoc saved :title "Test Updated"))]
(ppe "Saved again (updated) row #1" saved-again))))
(in-db db
(let [e1 (find-by-id blog-entry-meta 1)
ea (find-by-criteria blog-entry-meta) ;; finds all records
ec (find-by-criteria blog-entry-meta :cols [:title :content])
ew (find-by-criteria blog-entry-meta :where ["title=?" "Hello World"])
eb (find-by-criteria blog-entry-meta :cols [:title :content] :where ["title LIKE ?" "Hello%"])]
(ppe "Entry 1:" e1)
(ppe "All Entries:" ea)
(ppe "Entries with selected columns:" ec)
(ppe "Entries with WHERE clause:" ew)
(in-db db
(let [ea (find-by-criteria blog-entry-meta :cols count-col)
ew (find-by-criteria blog-entry-meta :cols count-col :where ["title=?" "Hello World"])]
(println "All records:" (read-count-col ea))
(println "Records with WHERE clause:" (read-count-col ew)))
(in-txn db
(let [e (find-by-id blog-entry-meta 1)
c (EntryComment. {}
{:content "Comment #1"
:whenposted (new java.util.Date)
:name "Whatever"
:email "[email protected]"} )
saved (save-deps e [c])]
(ppe "Saved 1 child for entry (ID=1)" saved))
(let [e (find-by-id blog-entry-meta 2)