Skip to content

Instantly share code, notes, and snippets.

@verma
Created May 6, 2016 17:07
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save verma/754521e85d9ddbc6554df13b82e3e255 to your computer and use it in GitHub Desktop.
Save verma/754521e85d9ddbc6554df13b82e3e255 to your computer and use it in GitHub Desktop.
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 "ceo@bmw.com"
:maker/name "BMW"}
{:car/model "E39530i"
:car/maker [:maker/email "ceo@bmw.com"]
: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 "ceo@bmw.com"]
:car/name "2003 520i"}])
;; Query all cars made by our maker
(d/q '[:find [?name ...]
:where
[?c :car/maker [:maker/email "ceo@bmw.com"]]
[?c :car/name ?name]]
@conn)
;; query some stuffs
(d/entity @conn [:car/model "E39530i"]) ;; {:db/id 2}
(d/entity @conn [:maker/email "ceo@bmw.com"]) ;; {:db/id 1}
;; lazy-query an attribute out of an entity
(:maker/name (d/entity @conn [:maker/email "ceo@bmw.com"])) ;; "BMW"
;; Update the name of a maker by using lookup refs
(d/transact! conn [{:maker/email "ceo@bmw.com"
:maker/name "BWM Motors"}])
;; query the name again and see it change
(:maker/name (d/entity @conn [:maker/email "ceo@bmw.com"])) ;; "BMW Motors"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment