Last active
January 20, 2016 17:44
-
-
Save sparkofreason/6b3ffd63d148cd7dc37a to your computer and use it in GitHub Desktop.
Utility functions for bridging Datomic/Datascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns allgress.datascript.util | |
(:require [clojure.walk :refer [postwalk]])) | |
;;; Datomic pull API will return :db/idents as references, like {:my-enum-att {:db/ident :enum-value}}. | |
;;; This function replaces with the Datascript equivalent {:my-enum-att :enum-value}. Only works | |
;;; for true "enums", whose only attribute in the entity map is :db/ident. | |
defn replace-enum-refs [entity-map] | |
(postwalk | |
(fn [arg] | |
(if (and (coll? arg) (map? (second arg)) (= 1 (count (second arg))) (contains? (second arg) :db/ident)) | |
(do | |
[(first arg) (:db/ident (second arg))]) | |
arg)) | |
entity-map)) | |
;;; To pull enums using Datomic pull API, you would specify a pattern like [{:my-enum-att [:db/ident]}]. | |
;;; For Datascript, you only need to specify the attribute: [:my-enum-att]. This function transforms the | |
;;; Datomic form to the Datascript form. | |
(defn replace-enum-patterns [entity-pattern] | |
(postwalk | |
(fn [arg] | |
(if (and (map? arg) (= [:db/ident] (first (vals arg)))) | |
(first (keys arg)) | |
arg)) | |
entity-pattern)) | |
;;; Utility function for creating UUID in either Clojure or ClojureScript. | |
(defn random-uuid [] | |
#+clj (java.util.UUID/randomUUID) #+cljs (datascript/squuid)) | |
;;; Extends UUID in ClojureScript to implement IComparable, so Datomic attributes of type db.type/uuid | |
;;; can be added to Datascript. | |
#+cljs | |
(extend-type UUID | |
IComparable | |
(-compare [x y] (compare (datascript/squuid-time-millis x) (datascript/squuid-time-millis y)))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment