Skip to content

Instantly share code, notes, and snippets.

@benkamphaus
Created October 26, 2015 23:20
Show Gist options
  • Save benkamphaus/4f991901b2fe8d00e20b to your computer and use it in GitHub Desktop.
Save benkamphaus/4f991901b2fe8d00e20b to your computer and use it in GitHub Desktop.
Example of reified references as components of an entity
(ns datomic-manual-tests.membership
(:require [datomic.api :as d]))
(def db-uri "datomic:mem://memership")
(d/create-database db-uri)
(def conn (d/connect db-uri))
(def schema
[{:db/id (d/tempid :db.part/db)
:db/ident :person/name
:db/valueType :db.type/string
:db/cardinality :db.cardinality/one
:db/unique :db.unique/identity
:db.install/_attribute :db.part/db}
{:db/id (d/tempid :db.part/db)
:db/ident :person/membership
:db/valueType :db.type/ref
:db/cardinality :db.cardinality/many
:db/isComponent true
:db.install/_attribute :db.part/db}
{:db/id (d/tempid :db.part/db)
:db/ident :membership/org
:db/valueType :db.type/ref
:db/cardinality :db.cardinality/one
:db.install/_attribute :db.part/db}
{:db/id (d/tempid :db.part/db)
:db/ident :membership/role
:db/valueType :db.type/string
:db/cardinality :db.cardinality/one
:db.install/_attribute :db.part/db}
{:db/id (d/tempid :db.part/db)
:db/ident :org/name
:db/valueType :db.type/string
:db/cardinality :db.cardinality/one
:db/unique :db.unique/identity
:db.install/_attribute :db.part/db}])
@(d/transact conn schema)
(def init-data
[{:db/id (d/tempid :db.part/user -1)
:person/name "Jonas"
:person/membership [{:db/id (d/tempid :db.part/user -2)
:membership/org (d/tempid :db.part/user -3)
:membership/role "President"}]}
{:db/id (d/tempid :db.part/user -3)
:org/name "Chess Club"}
{:db/id (d/tempid :db.part/user -4)
:person/name "Will"
:person/membership [{:db/id (d/tempid :db.part/user -5)
:membership/org (d/tempid :db.part/user -3)
:membership/role "Underling"}]}])
@(d/transact conn init-data)
(let [db (d/db conn)
pattern '[:person/name
{:person/membership
[{:membership/org
[:org/name
{:membership/_org
[{:person/_membership [:person/name]}]}]}]}]]
(d/pull db pattern [:person/name "Jonas"]))
;; Traversing refs from person -> membership -> org -> memberships -> people
;{:person/membership [{:membership/org {:membership/_org [{:person/_membership {:person/name "Jonas"}}
; {:person/_membership {:person/name "Will"}}]
; :org/name "Chess Club"}}]
; :person/name "Jonas"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment