Create a gist now

Instantly share code, notes, and snippets.

Simple template expansion meta-definitions for Datomic
(defn extract-key [m k]
(when-let [value (k m)] [(dissoc m k) value]))
(defn expand-entry-id [entry]
(if (keyword? (:db/id entry))
(update-in entry [:db/id] d/tempid)
entry))
(defn expand-schema-entry [entry templates]
(if (and (map? entry) (:meta/templates entry))
(let [[entry template-refs] (extract-key entry :meta/templates)]
(merge (apply merge (map templates template-refs)) entry))
entry))
(defn preprocess-schema
; If passed a set of entries, return a processed set of entries
; Otherwise expect a {:schema :templates} map.
([schema]
(if (map? schema)
(preprocess-schema (:schema schema :templates schema))
(:schema (preprocess-schema schema {}))))
([schema templates]
(reduce
(fn [res entry]
(let [entry (expand-schema-entry entry (:templates res))]
(if-let [[templ templ-name] (extract-key entry :meta/def-template)]
(update-in res [:templates] assoc templ-name templ)
(update-in res [:schema] conj (expand-entry-id entry)))))
{:schema [] :templates {}}
schema)))
[
;; meta templates
{:meta/def-template :string
:db/valueType :db.type/string}
{:meta/def-template :attr-one
:db/id :db.part/db
:db/cardinality :db.cardinality/one
:db.install/_attribute :db.part/db}
{:meta/def-template :ref
:db/valueType :db.type/ref}
{:meta/def-template :id
:db/index true
:db/unique :db.unique/value}
{:meta/def-template :string-id
:meta/templates [:string :attr-one :id]}
;; Sessions
{:db/id #db/id[:db.part/db]
:db/ident :db.part/sysdea-sessions
:db.install/_partition :db.part/db}
{:meta/templates [:string-id]
:db/ident :session/id
:db/doc "A session's ID."
:db/noHistory true}
{:meta/templates [:attr-one :ref]
:db/ident :session/user
:db/doc "Which user the session is associated with, if any."
:db/noHistory true}
{:meta/templates [:attr-one :string]
:db/ident :session/metadata
:db/doc "Any additional information needed on the session."
:db/noHistory true}
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment