Skip to content

Commit

Permalink
Do not throw from d/touch when finding hanging refs
Browse files Browse the repository at this point in the history
  • Loading branch information
tonsky committed Aug 14, 2023
1 parent 6c18d23 commit 3360f74
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 16 deletions.
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
# WIP

- JVM: Return `nil` from `d/restore-conn` if there is no db
- Do not throw from d/touch when finding hanging refs

# 1.5.2

- JVM: Fixed `d/collect-garbage`
Expand Down
34 changes: 18 additions & 16 deletions src/datascript/impl/entity.cljc
Original file line number Diff line number Diff line change
Expand Up @@ -181,14 +181,15 @@
not-found)))))))

(defn touch-components [db a->v]
(reduce-kv (fn [acc a v]
(assoc acc a
(if (db/component? db a)
(if (db/multival? db a)
(set (map touch v))
(touch v))
v)))
{} a->v))
(reduce-kv
(fn [acc a v]
(assoc acc a
(if (db/component? db a)
(if (db/multival? db a)
(set (map touch v))
(touch v))
v)))
{} a->v))

(defn- datoms->cache [db datoms]
(reduce (fn [acc part]
Expand All @@ -197,13 +198,14 @@
{} (partition-by :a datoms)))

(defn touch [^Entity e]
{:pre [(entity? e)]}
(when-not @(.-touched e)
(when-let [datoms (not-empty (db/-search (.-db e) [(.-eid e)]))]
(vreset! (.-cache e) (->> datoms
(datoms->cache (.-db e))
(touch-components (.-db e))))
(vreset! (.-touched e) true)))
e)
{:pre [(or (nil? e) (entity? e))]}
(when (some? e)
(when-not @(.-touched e)
(when-let [datoms (not-empty (db/-search (.-db e) [(.-eid e)]))]
(vreset! (.-cache e) (->> datoms
(datoms->cache (.-db e))
(touch-components (.-db e))))
(vreset! (.-touched e) true)))
e))

#?(:cljs (goog/exportSymbol "datascript.impl.entity.Entity" Entity))
23 changes: 23 additions & 0 deletions test/datascript/test/entity.cljc
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,29 @@
(is (= (-> (e 100) :_children first :_children) #{(e 1)}))
)))

(deftest test-missing-refs
(let [schema {:ref {:db/valueType :db.type/ref}
:comp {:db/valueType :db.type/ref
:db/isComponent true}
:multiref {:db/valueType :db.type/ref
:db/cardinality :db.cardinality/many}
:multicomp {:db/valueType :db.type/ref
:db/isComponent true
:db/cardinality :db.cardinality/many}}
db (d/empty-db schema)
db' (d/db-with db
[[:db/add 1 :ref 2]
[:db/add 1 :comp 3]
[:db/add 1 :multiref 4]
[:db/add 1 :multiref 5]
[:db/add 1 :multicomp 6]
[:db/add 1 :multicomp 6]])]
(d/touch (d/entity db 1)) ;; does not throw
(is (= nil (:ref (d/entity db 1))))
(is (= nil (:comp (d/entity db 1))))
(is (= nil (:multiref (d/entity db 1))))
(is (= nil (:multicomp (d/entity db 1))))))

(deftest test-entity-misses
(let [db (-> (d/empty-db {:name {:db/unique :db.unique/identity}})
(d/db-with [{:db/id 1, :name "Ivan"}
Expand Down

0 comments on commit 3360f74

Please sign in to comment.