Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Datascript101 - Chapter 2
(ns dt.core
(:require [datascript.core :as d]))
;; schema so nice
(def schema {:maker/email {:db/unique :db.unique/identity}
:car/model {:db/unique :db.unique/identity}
:car/maker {:db/type :db.type/ref}
:car/colors {:db/cardinality :db.cardinality/many}})
;; create the connection
(def conn (d/create-conn schema))
;; insert a car
(d/transact! conn [{:maker/email ""
:maker/name "BMW"}
{:car/model "E39530i"
:car/maker [:maker/email ""]
:car/name "2003 530i"}])
;; insert a car by using a lookup ref to an already existing maker
(d/transact! conn [{:car/model "E39520i"
:car/maker [:maker/email ""]
:car/name "2003 520i"}])
;; Query all cars made by our maker
(d/q '[:find [?name ...]
[?c :car/maker [:maker/email ""]]
[?c :car/name ?name]]
;; query some stuffs
(d/entity @conn [:car/model "E39530i"]) ;; {:db/id 2}
(d/entity @conn [:maker/email ""]) ;; {:db/id 1}
;; lazy-query an attribute out of an entity
(:maker/name (d/entity @conn [:maker/email ""])) ;; "BMW"
;; Update the name of a maker by using lookup refs
(d/transact! conn [{:maker/email ""
:maker/name "BWM Motors"}])
;; query the name again and see it change
(:maker/name (d/entity @conn [:maker/email ""])) ;; "BMW Motors"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment