Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Has entities in Datomic metadata like creation and update time?

I want to know e.g. when an entity was created or updated. Should I create an attribute like :created-at and :update-at or Datomic has theses attributes by default? Or any manner to find out when an entity was created or updated?

like image 349
Felipe Avatar asked Jul 09 '14 05:07

Felipe


1 Answers

Time is fundamental to Datomic's design. Part of Datomic's view of time is that entities are not created or updated as in a traditional CRUD database where row are inserted into tables and new facts overwrite old facts in the row. Instead, facts about entities are asserted and retracted over time. Given this immutable history, Datomic knows how it got to be in its current state. You can gather that info about the structure of your data over time the history database:

http://docs.datomic.com/clojure/#datomic.api/history

So to answer your question about added-at and updated-at, you can rely on Datomic's built-in time awareness. For querying on when things were created - here are two options. If your schema includes a unique identifier of some sort, you can constrain your query to refer to the transaction when this attribute was created (should be once, when the entity was first added):

(d/q '[:find ?e ?tx-time
       :where
       [?e :user/id _ ?tx]
       [?tx :db/txInstant ?tx-time]]
  db)

If you can't rely on an attribute at initialization, you could use a history database to take the minimum time for all transactions corresponding to an entity, such as in this parameterized query:

(d/q ':find ?e (min ?tx-time)
      :in $ ?e
      :where
      [?e _ _ ?tx _]
      [?tx :db/txInstant ?tx-time]
  (history db) entity-id)

Note that this way will be slower, but potentially more robust. If you wanted the latest fact asserted (the "update"), you could sub max for min.

like image 59
Ben Kamphaus Avatar answered Sep 30 '22 19:09

Ben Kamphaus