Johan
Johan

Reputation: 40530

Find entity id of last transaction in Datomic?

I'd like to know how to I can find the id of the entity that was modified/created/deleted by the latest transaction in Datomic. How can I do this?

Upvotes: 3

Views: 391

Answers (1)

Valentin Waeselynck
Valentin Waeselynck

Reputation: 6051

For this kind of read pattern (temporal-based), you'll want to use the Log API. Note that:

  1. there may be more than one entity that was affected by the last transaction.
  2. actually, the transaction itself is represented by an entity which is created for that transaction, which you may want to filter out of your result.

Here's a sample implementation:

(defn affected-entities
  "Given a Datomic connection, returns the set of entity ids that were affected
  by the last transaction (in e position), excluding the entity representing the 
  transaction itself."
  [conn]
  (let [db (d/db conn)]
    (->>
      (d/q '[:find [?e ...] :in ?log ?t1 ?t2 :where
             [(tx-ids ?log ?t1 ?t2) [?tx ...]] ;; binds the last tx 
             [(tx-data ?log ?tx) [[?e]]]]
        (d/log conn) (d/basis-t db) (d/next-t db))
      ;; filtering out the transaction entity
      (remove (fn [eid]
                (->> eid d/part (d/ident db) (= :db.part/tx))))
      set)))

Upvotes: 3

Related Questions