12

在 datomic 中运行事务以插入值后,如何使用事务的返回值来获取已创建的任何实体的 id?

这是插入后得到的返回值示例:

#<promise$settable_future$reify__4841@7c92b2e9: {:db-before datomic.db.Db@62d0401f, :db-after datomic.db.Db@bba61dfc,
 :tx-data [#Datum{:e 13194139534331 :a 50 
:v #inst "2013-06-19T11:38:08.025-00:00" 
:tx 13194139534331 :added true} #Datum{:e 17592186045436 .....

我可以看到基础数据...如何提取它们的值?

4

4 回答 4

12

使用d/resolve-tempid。如果您要交易单个实体,查看:tx-data 会起作用,但如果您的交易包含多个实体,那么您将不知道它们出现在:tx-data.

您应该做的是使用其中一个(d/tempid)或其文字表示为您的实体(在处理它们之前)提供临时 ID #db/id[:db.part/user _negativeId_],然后使用d/resolve-tempid从您的临时 ID 转到数据库给出的真实 ID。代码看起来像:

(d/resolve-tempid (d/db conn) (:tempids tx) (d/tempid :db.part/user _negativeId_))

有关完整的代码示例,请参阅此要点

于 2013-06-19T13:39:29.747 回答
7

啊,想通了。

我不得不取消对 Clojure 的承诺,然后我能够抽出我想要的值:

 (:e (second (:tx-data @(transact! conn query))))
于 2013-06-19T12:14:23.837 回答
1

根据 a2ndrade 的回答写了一个快速函数。命名不理想,我可能犯了惯用的失礼;非常欢迎提出建议。

(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))

示例用法:

(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
于 2015-03-08T07:51:41.033 回答
0

Tupelo Datomic 库具有(td/eids tx-result)轻松提取事务中创建的 EID 的功能。例如:

  ; Create Honey Rider and add her to the :people partition
  (let [tx-result   @(td/transact *conn* 
                        (td/new-entity :people ; <- partition is first arg (optional) to td/new-entity 
                          { :person/name "Honey Rider" :location "Caribbean" :weapon/type #{:weapon/knife} } ))
        [honey-eid]  (td/eids tx-result)  ; retrieve Honey Rider's EID from the seq (destructuring)
  ]
于 2015-09-02T18:03:40.183 回答