Skip to content

Instantly share code, notes, and snippets.

@benkamphaus
Created August 6, 2015 21:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benkamphaus/dc4162743958b1c1b641 to your computer and use it in GitHub Desktop.
Save benkamphaus/dc4162743958b1c1b641 to your computer and use it in GitHub Desktop.
Datomic: chaining with to explore a prospective sequence of transactions, fairly dorky schema example
(ns datomic-manual-tests.with-bonanza
(:require [datomic.api :as d]))
(def db-uri "datomic:mem://people")
(d/create-database db-uri)
(def conn (d/connect db-uri))
(def schema
[{:db/id (d/tempid :db.part/db)
:db/ident :person/age
:db/valueType :db.type/long
:db/cardinality :db.cardinality/one
:db.install/_attribute :db.part/db}
{:db/id (d/tempid :db.part/db)
:db/ident :person/name
:db/valueType :db.type/string
:db/cardinality :db.cardinality/one
:db.install/_attribute :db.part/db}])
@(d/transact conn schema)
(defn all-people [db]
(d/q '[:find ?e ?name ?age
:where [?e :person/name ?name]
[?e :person/name ?age]]
db))
(def db-with-sally (:db-after (d/with (d/db conn) [{:db/id (d/tempid :db.part/user)
:person/age 40
:person/name "Sally"}])))
(all-people db-with-sally)
; #{[17592186045418 "Sally" "Sally"]} -- one prospective branch
(def db-with-sam (:db-after (d/with (d/db conn) [{:db/id (d/tempid :db.part/user)
:person/age 42
:person/name "Sam"}])))
(all-people db-with-sam)
; #{[17592186045418 "Sam" "Sam"]} -- another prospective branch where Sam
; receives this ent-id instead of Sally
; Chained -- a `with` on a `:db-after` from a `with`
(def db-with-sam-alice (:db-after (d/with db-with-sam [{:db/id (d/tempid :db.part/user)
:person/age 50 :person/name "Alice"}])))
(all-people db-with-sam-alice)
; #{[17592186045418 "Sam" "Sam"]
; [17592186045420 "Alice" "Alice"]}
(def remove-sam-db
(let [sam-ent (d/q '[:find ?e .
:where [?e :person/name "Sam"]]
db-with-sam-alice)]
(:db-after (d/with db-with-sam-alice [[:db.fn/retractEntity sam-ent]]))))
(all-people remove-sam-db)
; #{[17592186045420 "Alice" "Alice"]} -- only Alice in next chained with
; due to retration
(all-people (d/history remove-sam-db))
; #{[17592186045418 "Sam" "Sam"] [17592186045420 "Alice" "Alice"]}
; Still have Sam in history, though.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment