Skip to content

Instantly share code, notes, and snippets.

View kumarshantanu's full-sized avatar

Shantanu Kumar kumarshantanu

View GitHub Profile
(defrecord BlogEntry [])
(defrecord EntryComment [])
(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"
(def blog-entry-meta
(entity-meta :entry :autoid (from-row BlogEntry.)
[: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
[(one-to-many :autoid entry-comment-meta :entryid)] )
(extend-entity EntryComment
[(many-to-one :entryid blog-entry-meta :autoid)] )
(in-db db
(println "** Dropping tables **")
(drop-table blog-entry-meta)
(catch Exception e
(println (str "Error dropping table " (:name blog-entry-meta) ": "
(.getMessage e) " [Ignored]"))))
(drop-table entry-comment-meta)
(catch Exception e
(defn ppe ;; pretty-print-entities
(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 [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-db db
(let [e (find-by-id blog-entry-meta 2)
r ((find-rels e entry-comment-meta) e)
rc ((find-rels e entry-comment-meta :cols [:content :name :email]) e)
rw ((find-rels e entry-comment-meta :where ["email=?" ""]) e)
rb ((find-rels e entry-comment-meta :cols [:content :name :email]
:where ["email=?" ""]) e)]
(ppe "\nEntry:" e)
(ppe "\nRelations:" r)
(ppe "\nRelations with selected columns:" rc)
(in-db db
(let [e (find-by-id blog-entry-meta 2)
r ((find-rels e entry-comment-meta) e)
c (first r)
s (find-siblings c e)
sc (find-siblings c e :cols [:content :name :email])
sw (find-siblings c e :where ["name LIKE ?" "Phi%"])
sb (find-siblings c e :cols [:content :name :email] :where ["name LIKE ?" "Phi%"])]
(ppe "\nChild: " c)
(ppe "\nSiblings:" s)