Component Attributes

A component is an entity that belongs to some other entity, and has no independent lifecycle. For example, your arm is a component of you, but your friend is not.

In Datomic, components are modeled with the :db/isComponent property of a schema attribute. For example, the comments attribute in the social news schema is a component attribute.

{:db/id #db/id[:db.part/db]
 :db/ident :comments
 :db/valueType :db.type/ref
 :db/cardinality :db.cardinality/many
 :db/isComponent true
 :db.install/_attribute :db.part/db}

Datomic treats component attributes specially in two ways: First, component attributes are recursively retrieved when you touch an entity. So the call to touch below will retrieve all the comments on the story, and all the comments on those comments, and so on:

(-> conn d/db (d/entity story) d/touch)
=> {:story/title "Getting Started", :story/url "http://docs.datomic.com/getting-started.html",
    :comments #{{:comment/body "It woud be great to learn about component attributes.",
                 :db/id 17592186045428
                 :comments #{{:comment/body "I agree.", :db/id 17592186045429}}}},
    :db/id 17592186045427}

Since components have no independent existence, retracting everything about an entity implies the following algorithm:

  • Retract all datoms where the entity appears in E position.
  • Retract all datoms where the entity appears in A position.
  • Repeat the previous two steps for all component entities, recursively.

Datomic's data function db.fn/retractEntity implements the algorithm above, making it easy to "retract an entity". The example below retracts a story and all its comments:

(d/transact conn [[:db.fn/retractEntity story]])
Have more questions? Submit a request

0 Comments

Please sign in to leave a comment.
Powered by Zendesk