Getting the id of an inserted entity in datomic?

前端 未结 4 1857
臣服心动
臣服心动 2021-02-19 20:43

After I run a transaction in datomic to insert a value, how I can use the return value of the transaction to get the ids of any entities that were created?

Here is a sam

4条回答
  •  名媛妹妹
    2021-02-19 21:13

    Wrote a quick function based on a2ndrade's answer. The naming isn't ideal and I may be committing idiomatic faux pas; suggestions are very much welcome.

    (ns my.datomic.util
      (:require [datomic.api :as d]))
    
    (defn transact-and-get-id
      "Transact tx and return entity id."
      [conn tx]
      (let [tempid (:db/id tx)
            post-tx @(d/transact conn [tx])
            db (:db-after post-tx)
            entid (d/resolve-tempid db (:tempids post-tx) tempid)]
        entid))
    

    Example usage:

    (def my-conn
      (d/connect (str "datomic:sql://datomic?jdbc:postgresql://"
                      "127.0.1:5432/datomic?user=datomic&password=somepw")
    
    (defn thing-tx
      "Create transaction for new thing."
      [name]
      {:db/id (d/tempid :db.part/user)
       :thing/name name})
    
    (transact-and-get-id my-conn (thing-tx "Bob")) ;; => 17592186045502
    

提交回复
热议问题