Skip to content

Instantly share code, notes, and snippets.

@a2ndrade
Last active March 23, 2021 07:34
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save a2ndrade/5814355 to your computer and use it in GitHub Desktop.
Save a2ndrade/5814355 to your computer and use it in GitHub Desktop.
Datomic: Getting the id of an inserted entity
;; see http://stackoverflow.com/questions/17190334/getting-the-id-of-an-inserted-entity-in-diatomic
(require '[datomic.api :as d])
(def uri "datomic:mem://test")
(d/create-database uri)
(def conn (d/connect uri))
;; create an atribute
(d/transact conn [{:db/id #db/id[:db.part/db]
:db/ident :some/attribute
:db/valueType :db.type/string
:db/cardinality :db.cardinality/one
:db.install/_attribute :db.part/db}])
;; transact multiple entities with that attribute
(def tx @(d/transact conn
[[:db/add #db/id [:db.part/user -100] :some/attribute "A"]
[:db/add #db/id [:db.part/user -200] :some/attribute "B"]
[:db/add #db/id [:db.part/user -300] :some/attribute "C"]]))
;; get back the real entity id from a temporary id
(def bEid (d/resolve-tempid (d/db conn) (:tempids tx) (d/tempid :db.part/user -200)))
;; 17592186045440. Go from -200 (tempid) to 17592186045440 (real entity id)
;; verify you got the right one
(:some/attribute (d/entity (d/db conn) bEid))
;; "B"
@camdez
Copy link

camdez commented Dec 10, 2015

Would it be better to use (:db-after tx) instead of (d/db conn)?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment