Skip to content

Instantly share code, notes, and snippets.

@stuarthalloway
Created April 30, 2012 16:11
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save stuarthalloway/2559635 to your computer and use it in GitHub Desktop.
Save stuarthalloway/2559635 to your computer and use it in GitHub Desktop.
Using data functions on both peer and transactor side
;; this code valid as of build 3084
;; in-memory example database
(use '[datomic.api :only (db q) :as d])
(def uri "datomic:mem://test")
(d/create-database uri)
(def conn (d/connect uri))
;; example schema
(d/transact conn [{:db.install/_attribute :db.part/db,
:db/id #db/id[:db.part/db],
:db/ident :email,
:db/valueType :db.type/string,
:db/cardinality :db.cardinality/one,
:db/unique :db.unique/identity,}
{:db.install/_attribute :db.part/db,
:db/id #db/id[:db.part/db],
:db/ident :firstName,
:db/valueType :db.type/string,
:db/cardinality :db.cardinality/one}
{:db.install/_attribute :db.part/db
:db/id #db/id[:db.part/db],
:db/ident :lastName,
:db/valueType :db.type/string,
:db/cardinality :db.cardinality/one}])
;; simple validation function
(def validate-person (d/function '{:lang :clojure
:params [db person]
:code (do (assert (:firstName person))
(assert (:lastName person))
(assert (:email person))
[person])}))
;; test calling validation function (this will fail)
(validate-person nil {})
;; install function in the database
(d/transact conn [{:db/id #db/id[:db.part/user -1]
:db/ident :validate-person
:db/fn validate-person}])
;; retrieve function from the database
(def validate-person (d/fn (db conn) :validate-person))
;; test fn retrieved frome the db
(validate-person (db conn) {:firstName "Stu"})
;; retrieve the source code, can read-string it if Clojure
(:code validate-person)
(def stu {:firstName "Stu"
:lastName "Halloway"
:email "stuarthalloway@datomic.com"
:db/id #db/id [:db.part/user]})
;; run the validation peer side...
(d/transact conn (validate-person (db conn) stu))
;; run the validation transactor side...
(d/transact conn [[:validate-person stu]])
;; run validation on peer *and* on transactor
(d/transact
conn
[(cons :validate-person (validate-person (db conn) stu))])
;; find all the emails resulting from transactions above.
;; How many will you find? (Hint: email is :db.unique/identity.)
(q '[:find ?e ?v
:where [?e :email ?v]]
(db conn))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment