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?
1 Answer
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
.
-
thank you for your answer, however I found hard to do in this way. Is that performatic? Specially in the case of finding the "update" time? Do you think is it ok to create an attribute "created-at" and "update-at" or would be waste? If I want to order by creation time, e.g., is that easy? And why didn't you use "(history db)" in the first statement? I didn't get it. Thank you so much.– FelipeCommented Jul 10, 2014 at 18:44
-
1It's unnecessary and somewhat counterproductive to define those attributes yourself unless they correspond to a time dimension outside of Datomic (Datomic having logged times for assertions about facts). Datomic's log index (see the Log API docs.datomic.com/log.html) is optimized for these types of transaction time based queries. Commented Jul 10, 2014 at 19:46
-
1You may also find the provenance section from day-of-datomic helpful: github.com/Datomic/day-of-datomic/blob/master/tutorial/… Commented Jul 10, 2014 at 19:50