Last active
July 19, 2020 13:56
-
-
Save moea/2ade336969f024ad6f505e12b7c9781c to your computer and use it in GitHub Desktop.
invariant + Datahike Example
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 invariant.datahike-scratch | |
(:refer-clojure :exclude [+]) | |
(:require [invariant.datahike | |
:refer [+]] | |
[datahike.api :as d] | |
[datahike.core :as dc])) | |
(defn query [q conn tx] | |
(d/q q | |
@conn | |
(dc/db-with @conn tx) | |
(dc/db-with (dc/empty-db) tx) | |
tx)) | |
(let [uri "datahike:mem:///invariant-test" | |
schema [#:db{:ident :x64.lcoin/balance | |
:valueType :db.type/bigdec | |
:cardinality :db.cardinality/one} | |
#:db{:ident :transaction/signed-by | |
:valueType :db.type/long | |
:cardinality :db.cardinality/many}]] | |
(d/delete-database uri) | |
(d/create-database uri) | |
(let [conn (d/connect uri)] | |
(d/transact conn schema) | |
(d/transact conn [{:db/id 1 | |
:x64.lcoin/balance 1M} | |
{:db/id 2 | |
:x64.lcoin/balance 0M} | |
{:db/id 3 | |
:x64.lcoin/balance 3000M} | |
{:db/id 4}]) | |
(let [q '[:find ?sum-change . | |
:in $before $after $empty+tx $tx | |
:where | |
[(subquery [:find (sum ?balance-change) . | |
:with ?entity | |
:in $before $after $empty+tx _ | |
:where | |
[$empty+tx ?entity :x64.lcoin/balance _] | |
[$after ?entity :x64.lcoin/balance ?balance-after] | |
[(>= ?balance-after 0M)] | |
[(get-else $before ?entity :x64.lcoin/balance 0M) ?balance-before] | |
[(- ?balance-after ?balance-before) ?balance-change] | |
[$empty+tx _ :transaction/signed-by ?sender] | |
[(= ?sender ?entity) ?is-sender] | |
[(>= ?balance-change 0M) ?pos-change] | |
[(or ?is-sender ?pos-change)]] | |
$before $after $empty+tx $tx) ?sum-change] | |
[(zero? ?sum-change)]] | |
txn [[:db.fn/call + 1 :x64.lcoin/balance -1M] | |
[:db.fn/call + 2 :x64.lcoin/balance +1M] | |
[:db/add 1 :transaction/signed-by 1]]] | |
(query q conn (concat schema txn))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment