Created
February 27, 2014 08:16
-
-
Save vaughnd/9246309 to your computer and use it in GitHub Desktop.
Atomic find-or-create in datomic
This file contains hidden or 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
;; Schema | |
{:db/doc "Find or create tag atomically." | |
:db/ident :find-or-create-tag | |
:db/fn #db/fn {:lang "clojure" | |
:params [mydb n key value] | |
:code (when (empty? (d/q '[:find ?e :in $ ?ns ?key ?value :where | |
[?e :meta/tag-namespace ?n] | |
[?e :meta/tag-key ?key] | |
[?e :meta/tag-value ?value]] | |
mydb n key value)) | |
[{:db/id (d/tempid :cognician) | |
:meta/tag-namespace n | |
:meta/tag-key key | |
:meta/tag-value value}])} | |
:db/id #db/id [:db.part/db]} | |
;; Application fn | |
(defn find-or-create-tag! | |
[tag-ns tag-key tag-value] | |
(if-let [tag (find-tag tag-ns tag-key tag-value)] | |
tag | |
(do | |
(db/transact! [[:find-or-create-tag tag-ns tag-key tag-value]]) | |
(find-tag tag-ns tag-key tag-value)))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment