|
| 1 | +(ns datascript.datafy |
| 2 | + (:require [clojure.core.protocols :as cp] |
| 3 | + [datascript.pull-api :as dp] |
| 4 | + [clojure.string :as str])) |
| 5 | + |
| 6 | +(declare datafy-entity) |
| 7 | +(declare datafy-entity-seq) |
| 8 | + |
| 9 | +(defn- attr<->rattr [attr] |
| 10 | + (keyword (namespace attr) |
| 11 | + (if (str/starts-with? (name attr) "_") |
| 12 | + (subs (name attr) 1) |
| 13 | + (str "_" (name attr))))) |
| 14 | + |
| 15 | +(defn- pull-pattern [ref-rattrs] |
| 16 | + (into ["*"] ref-rattrs)) |
| 17 | + |
| 18 | + |
| 19 | +(defn- navize-entity [db-val entity] |
| 20 | + (let [ref-attrs (:db.type/ref (:rschema db-val)) |
| 21 | + ref-rattrs (set (map attr<->rattr ref-attrs)) |
| 22 | + many-attrs (:db.cardinality/many (:rschema db-val)) |
| 23 | + pull-pattern (into ["*"] ref-rattrs)] |
| 24 | + (with-meta entity |
| 25 | + {`cp/nav (fn [coll k v] |
| 26 | + (cond |
| 27 | + (or (and (many-attrs k) (ref-attrs k)) |
| 28 | + (ref-rattrs k)) |
| 29 | + (datafy-entity-seq db-val |
| 30 | + (dp/pull-many db-val pull-pattern (mapv :db/id v))) |
| 31 | + (ref-attrs k) |
| 32 | + (datafy-entity db-val (dp/pull db-val pull-pattern (:db/id v))) |
| 33 | + :else v))}))) |
| 34 | + |
| 35 | +(defn- navize-entity-seq [db-val entities] |
| 36 | + (with-meta entities |
| 37 | + {`cp/nav (fn [coll k v] |
| 38 | + (datafy-entity db-val v))})) |
| 39 | + |
| 40 | +(defn- datafy-entity [db-val entity] |
| 41 | + (with-meta entity |
| 42 | + {`cp/datafy (fn [entity] |
| 43 | + (navize-entity db-val entity))})) |
| 44 | + |
| 45 | +(defn- datafy-entity-seq [db-val entities] |
| 46 | + (with-meta entities |
| 47 | + {`cp/datafy (fn [entities] (navize-entity-seq db-val entities))})) |
| 48 | + |
| 49 | +(defn pull |
| 50 | + "Same as `datascript.core/pull` but the returned map implements `datafy/nav` (See [https://clojure.github.io/clojure/clojure.datafy-api.html](https://clojure.github.io/clojure/clojure.datafy-api.html). |
| 51 | +
|
| 52 | + This can be used to navigate through the database following ref fields. |
| 53 | +
|
| 54 | + Usage: |
| 55 | + ``` |
| 56 | + (pull db [:ref, :name] 1) |
| 57 | + ; => {:db/id 1, |
| 58 | + ; :name \"Child\", |
| 59 | + ; :ref {:db/id 2}} |
| 60 | + (nav (datafy (pull db [:ref, :name] 1)) |
| 61 | + :ref |
| 62 | + {:db/id 2}) |
| 63 | + ; => {:db/id 2, |
| 64 | + ; :name \"Parent\", |
| 65 | + ; :_ref {:db/id 1}} |
| 66 | + ``` |
| 67 | + " |
| 68 | + [db selector eid] |
| 69 | + (datafy-entity db (dp/pull db selector eid))) |
| 70 | + |
| 71 | +(defn pull-many |
| 72 | + "Same as [[pull]] but accepts sequence of ids and returns sequence of maps that implements `datafy/nav`." |
| 73 | + [db selector eids] |
| 74 | + (datafy-entity-seq db (dp/pull-many db selector eids))) |
0 commit comments