Skip to content

Instantly share code, notes, and snippets.

@henryw-erudine
Last active August 29, 2015 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save henryw-erudine/614fee493d2e0535fd48 to your computer and use it in GitHub Desktop.
Save henryw-erudine/614fee493d2e0535fd48 to your computer and use it in GitHub Desktop.
datomic backreferences where iscomponent=true
(def uri "datomic:mem://my-db")
(d/create-database uri)
(def conn (d/connect uri))
(d/transact conn [
{:db/id #db/id [:db.part/db]
:db/ident :entity/name
:db/valueType :db.type/string
:db/isComponent true
:db/cardinality :db.cardinality/one
:db/doc ""
:db.install/_attribute :db.part/db}
{:db/id #db/id [:db.part/db]
:db/ident :entity/one
:db/valueType :db.type/ref
:db/isComponent true
:db/cardinality :db.cardinality/one
:db/doc ""
:db.install/_attribute :db.part/db}
])
(d/transact conn [{:db/id (d/tempid :db.part/user)
:entity/name "parent 1"
:entity/one {:db/id (d/tempid :db.part/user -1)
:entity/name "child"}}
{:db/id (d/tempid :db.part/user)
:entity/name "parent 2"
:entity/one {:db/id (d/tempid :db.part/user -1)
:entity/name "child"}}])
(def db (d/db conn))
;; confirm 2 parents ref the same child
(d/q '[:find ?parent ?one-child :where [?parent :entity/one ?one-child]] db)
;;; nav via back references. the result is not a set but a single entity (one of the 'parent' entities) because the attribute is
;;; ':db/isComponent true'
(def one-child (ffirst (d/q '[:find ?one-child :where [_ :entity/one ?one-child]] db)))
(->> (d/entity db one-child)
:entity/_one)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment