on master help sign in
161 files changed+7831−3539
since splitsnapshots
unifiedsplit
.appveyor.yml+2−3 .github/workflows/ci.yaml+69 .gitignore+3−1 .travis.yml−60 .travis/attach-binary.sh−25 .travis/install-dependencies.sh−22 .travis/install-ghc.sh−16 .travis/install-ghr.sh−21 .travis/install-stack.sh−27 Changelog.markdown+33 README.markdown+14−7 cabal.project+9−2 default.nix+1 docker.nix+18 docs/15_minute_tutorial.markdown+65−68 docs/commits_in_constant_time.markdown+134 docs/data_independence.markdown+109 docs/filesystem-persistence.markdown+1−1 docs/import_export_csv.markdown+65 docs/introduction_to_projectm36.markdown+28−9 docs/introduction_to_the_relational_algebra.markdown+2−2 docs/merkle_transaction_graph.markdown+33 docs/reaching_out_of_the_tarpit.markdown+1−1 docs/server_mode.markdown+1−1 docs/transaction_graph_operators.markdown+6−4 docs/tupleable.markdown+19 docs/tutd_cheatsheet.markdown+99 docs/tutd_tutorial.markdown+56−2 docs/websocket_server.markdown+2−2 examples/DerivingCustomTupleable.hs+54 examples/Plantfarm.hs+446 examples/SimpleClient.hs+1−1 examples/blog.hs+11−8 examples/hair.hs+9−6 examples/out_of_the_tarpit.hs+11−7 examples/out_of_the_tarpit.tutd+4−4 jupyter/TutorialD Notebook Walkthrough.ipynb+1−1 nix/sources.json+50 nix/sources.nix+171 project-m36.cabal+160−162 release.nix+36 scripts/DateExamples.tutd+2−2 scripts/multiline.tutd+2 shell.nix+1 src/bin/ProjectM36/Client/Json.hs+4−1 src/bin/ProjectM36/Server/RemoteCallTypes/Json.hs+37−3 src/bin/ProjectM36/Server/WebSocket.hs+33−21 src/bin/ProjectM36/Server/WebSocket/websocket-client.html+1−1 src/bin/ProjectM36/Server/WebSocket/websocket-server.hs+48−18 src/bin/TutorialD/Interpreter.hs+32−28 src/bin/TutorialD/Interpreter/Base.hs+68−38 src/bin/TutorialD/Interpreter/DatabaseContextExpr.hs+26−17 src/bin/TutorialD/Interpreter/Export/Base.hs+3 src/bin/TutorialD/Interpreter/Import/Base.hs+11−3 src/bin/TutorialD/Interpreter/Import/BasicExamples.hs+2−2 src/bin/TutorialD/Interpreter/Import/CSV.hs+3−3 src/bin/TutorialD/Interpreter/Import/TutorialD.hs+70−17 src/bin/TutorialD/Interpreter/RODatabaseContextOperator.hs+33−16 src/bin/TutorialD/Interpreter/RelationalExpr.hs+80−46 src/bin/TutorialD/Interpreter/SchemaOperator.hs+3−3 src/bin/TutorialD/Interpreter/TransGraphRelationalOperator.hs+2−2 src/bin/TutorialD/Interpreter/TransactionGraphOperator.hs+12−3 src/bin/TutorialD/Interpreter/Types.hs+10−4 src/bin/TutorialD/Printer.hs+165 src/bin/TutorialD/tutd.hs+16−18 src/bin/benchmark/Handles.hs+25−14 src/bin/benchmark/bigrel.hs+19−8 src/lib/ProjectM36/Arbitrary.hs+6−1 src/lib/ProjectM36/Atom.hs+3 src/lib/ProjectM36/AtomFunction.hs+19−2 src/lib/ProjectM36/AtomFunctionError.hs+1−2 src/lib/ProjectM36/AtomType.hs+86−14 src/lib/ProjectM36/Atomable.hs+37−54 src/lib/ProjectM36/Attribute.hs+148−29 src/lib/ProjectM36/AttributeNames.hs+3−2 src/lib/ProjectM36/Base.hs+189−113 src/lib/ProjectM36/Client.hs+280−356 src/lib/ProjectM36/Client/Simple.hs+2−1 src/lib/ProjectM36/DataFrame.hs+24−14 src/lib/ProjectM36/DataTypes/Interval.hs+2 src/lib/ProjectM36/DataTypes/Primitive.hs+1 src/lib/ProjectM36/DataTypes/Sorting.hs+1 src/lib/ProjectM36/DatabaseContext.hs+24−5 src/lib/ProjectM36/DatabaseContextFunction.hs+17−1 src/lib/ProjectM36/DatabaseContextFunctionError.hs+1−2 src/lib/ProjectM36/DatabaseContextFunctionUtils.hs+15−8 src/lib/ProjectM36/DateExamples.hs+3−3 src/lib/ProjectM36/DisconnectedTransaction.hs+7−1 src/lib/ProjectM36/Error.hs+24−14 src/lib/ProjectM36/FileLock.hs+1−1 src/lib/ProjectM36/GraphRefRelationalExpr.hs+45 src/lib/ProjectM36/InclusionDependency.hs+5−6 src/lib/ProjectM36/IsomorphicSchema.hs+26−27 src/lib/ProjectM36/Key.hs+2 src/lib/ProjectM36/MerkleHash.hs+9 src/lib/ProjectM36/NormalizeExpr.hs+132 src/lib/ProjectM36/Notifications.hs+12−7 src/lib/ProjectM36/Persist.hs+3−4 src/lib/ProjectM36/Relation.hs+19−40 src/lib/ProjectM36/Relation/Parse/CSV.hs+7−3 src/lib/ProjectM36/Relation/Show/CSV.hs+5−5 src/lib/ProjectM36/Relation/Show/HTML.hs+5−2 src/lib/ProjectM36/Relation/Show/Term.hs+5 src/lib/ProjectM36/RelationalExpression.hs+1047−657 src/lib/ProjectM36/ScriptSession.hs+72−44 src/lib/ProjectM36/Serialise/AtomFunctionError.hs+7 src/lib/ProjectM36/Serialise/Base.hs+85 src/lib/ProjectM36/Serialise/DataFrame.hs+13 src/lib/ProjectM36/Serialise/DatabaseContextFunctionError.hs+7 src/lib/ProjectM36/Serialise/Error.hs+15 src/lib/ProjectM36/Serialise/IsomorphicSchema.hs+7 src/lib/ProjectM36/Serialise/MergeError.hs+1 src/lib/ProjectM36/Server.hs+166−88 src/lib/ProjectM36/Server/Config.hs+6 src/lib/ProjectM36/Server/EntryPoints.hs+126−153 src/lib/ProjectM36/Server/ParseArgs.hs+40−15 src/lib/ProjectM36/Server/RemoteCallTypes.hs+67−35 src/lib/ProjectM36/Session.hs+3−2 src/lib/ProjectM36/Sessions.hs+3−4 src/lib/ProjectM36/Shortcuts.hs+247 src/lib/ProjectM36/StaticOptimizer.hs+370−249 src/lib/ProjectM36/TransGraphRelationalExpression.hs+133−135 src/lib/ProjectM36/Transaction.hs+24−16 src/lib/ProjectM36/Transaction/Persist.hs+61−52 src/lib/ProjectM36/Transaction/Type.hs+8 src/lib/ProjectM36/TransactionDiffs.hs+12 src/lib/ProjectM36/TransactionGraph.hs+238−148 src/lib/ProjectM36/TransactionGraph/Merge.hs+16−12 src/lib/ProjectM36/TransactionGraph/Persist.hs+8−5 src/lib/ProjectM36/TransactionGraph/Show.hs+3−4 src/lib/ProjectM36/TransactionGraph/Types.hs+12 src/lib/ProjectM36/TransactionInfo.hs+12 src/lib/ProjectM36/Tuple.hs+47−33 src/lib/ProjectM36/TupleSet.hs+7 src/lib/ProjectM36/Tupleable.hs+112−32 src/lib/ProjectM36/Tupleable/Deriving.hs+229 src/lib/ProjectM36/WithNameExpr.hs+86 stack.ghc8.0.yaml−50 stack.ghc8.10.yaml+19 stack.ghc8.4.yaml → stack.ghc8.6.yaml+26−17 stack.ghc8.2.yaml → stack.ghc8.8.yaml+26−15 test/Client/Simple.hs+1−2 test/IsomorphicSchema.hs+37−27 test/Relation/Atomable.hs+74−16 test/Relation/Basic.hs+24−17 test/Relation/Export/CSV.hs+23−18 test/Relation/StaticOptimizer.hs+76−51 test/Relation/Tupleable.hs+188−10 test/Server/Main.hs+24−23 test/Server/WebSocket.hs+8−12 test/TransactionGraph/Merge.hs+70−39 test/TransactionGraph/Persist.hs+79−15 test/TutorialD/Interpreter/AtomFunctionScript.hs+25−17 test/TutorialD/Interpreter/DatabaseContextFunctionScript.hs+14−7 test/TutorialD/Interpreter/Import/ImportTest.hs+47 test/TutorialD/Interpreter/Import/TutorialD.hs−29 test/TutorialD/Interpreter/Import/httpimporttest.tutd+2 test/TutorialD/Interpreter/TestBase.hs+10−13 test/TutorialD/Interpreter.hs → test/TutorialD/InterpreterTest.hs+115−27 test/TutorialD/PrinterTest.hs+47 test/scripts.hs+5−2
.appveyor.yml+2−3
@@ -17,8 +17,7 @@ environment:
1717 global:
1818 STACK_ROOT: "c:\\sr"
1919 matrix:
20− - YAML: "stack.ghc8.2.yaml"
21− - YAML: "stack.ghc8.4.yaml"
20+ - YAML: "stack.ghc8.6.yaml"
2221
2322platform:
2423 - x64
@@ -37,4 +36,4 @@ test_script:
3736
3837#artifacts:
3938# - path: project-m36.7z
40−# name: project-m36.7z
39+# name: project-m36.7z
.github/workflows/ci.yamlnew file+69
@@ -0,0 +1,69 @@
1+name: "CI"
2+on:
3+ pull_request:
4+ push:
5+jobs:
6+ dockerimage:
7+ runs-on: ubuntu-latest
8+ steps:
9+ - uses: actions/checkout@v2.3.1
10+ - uses: cachix/install-nix-action@v12
11+ with:
12+ nix_path: nixpkgs=channel:nixos-unstable
13+ - uses: cachix/cachix-action@v8
14+ with:
15+ name: project-m36
16+ signingKey: "${{ secrets.CACHIX_SIGNING_KEY }}"
17+ - run: cachix use iohk
18+ - name: docker load
19+ run: docker load < $(nix-build docker.nix)
20+ - name: docker login
21+ if: ${{ github.ref == 'refs/heads/master' }}
22+ run: echo ${{secrets.DOCKERHUB_PASSWORD}} | docker login --username ${{secrets.DOCKERHUB_USER}} --password-stdin
23+ - name: docker tag with version
24+ run: docker tag project-m36:latest projectm36/project-m36:$(awk '/^Version:/ {print $2}' project-m36.cabal)
25+ if: ${{ github.ref == 'refs/heads/master' }}
26+ - name: docker tag latest
27+ run: docker tag project-m36:latest projectm36/project-m36:latest
28+ if: ${{ github.ref == 'refs/heads/master' }}
29+ - run: docker push projectm36/project-m36
30+ if: ${{ github.ref == 'refs/heads/master' }}
31+
32+ stack-build:
33+ runs-on: ${{ matrix.os }}
34+ strategy:
35+ matrix:
36+ os: [ubuntu-latest]
37+ ghc:
38+ - ghc8.10
39+ - ghc8.8
40+ - ghc8.6
41+ include:
42+ - os: macos-latest
43+ ghc: ghc8.10
44+ env:
45+ STACK_YAML: stack.${{ matrix.ghc }}.yaml
46+ steps:
47+ - uses: actions/checkout@v2
48+ - name: Cache
49+ uses: actions/cache@v1
50+ with:
51+ path: ~/.stack
52+ key: ${{ runner.os }}-build-stack-${{ matrix.ghc }}-${{ hashFiles(env.STACK_YAML) }}-${{ hashFiles('**/*.cabal') }}
53+ restore-keys: |
54+ ${{ runner.os }}-build-stack-${{ matrix.ghc }}-${{ hashFiles(env.STACK_YAML) }}
55+ ${{ runner.os }}-build-stack-${{ matrix.ghc }}
56+ - name: Fix macOS cache bug
57+ run: rm -rf ~/.stack/setup-exe-cache
58+ - name: Build
59+ run: stack build --ghc-options -O2 --local-bin-path out --copy-bins
60+ - name: Test
61+ run: stack test --stack-yaml=${{ env.STACK_YAML }}
62+ - name: HLint
63+ run: curl -sSL https://raw.github.com/ndmitchell/hlint/master/misc/run.sh | sh -s .
64+ - name: Haddock
65+ run: stack --no-install-ghc --system-ghc --no-haddock-deps haddock
66+ - uses: actions/upload-artifact@v2
67+ with:
68+ name: project-m36-${{ matrix.os }}-${{ matrix.ghc }}
69+ path: out/
.gitignore+3−1
@@ -18,4 +18,6 @@ persistence-notes
1818jupyter/itutd.egg-info
1919jupyter/build
2020juyter/dist
21−.ipynb_checkpoints
21+.ipynb_checkpoints
22+project-m36.nix
23+stack.yaml
.travis.ymldeleted−60
@@ -1,60 +0,0 @@
1−# For more information, see https://github.com/ChrisPenner/haskell-stack-travis-ci
2−language: c
3−sudo: false
4−
5−git:
6− submodules: false # whether to recursively clone submodules
7−
8−cache:
9− directories:
10− - $HOME/.ghc
11− - $HOME/.cabal
12− - $HOME/.stack
13− - .stack-work
14− timeout: 1000
15−
16−matrix:
17− fast_finish: true
18− include:
19− - env: CACHE_NAME=8.2.2 STACK_YAML=stack.ghc8.2.yaml
20− compiler: ": #stack 8.2.2"
21−
22− - env: CACHE_NAME=osx-8.2.2 STACK_YAML=stack.ghc8.2.yaml
23− os: osx
24− os_image: xcode7.3
25− compiler: ": #stack 8.2.2"
26−
27− - env: CACHE_NAME=8.4.3 STACK_YAML=stack.ghc8.4.yaml
28− compiler: ": #stack 8.4.3"
29−
30−before_script:
31− - unset CC
32− - export PATH=$HOME/.local/bin:/opt/ghc/$GHC_VERSION/bin:$PATH
33− - ./.travis/install-ghr.sh
34− - ./.travis/install-stack.sh
35−
36−# Here starts the actual work to be performed for the package under test;
37−# any command which exits with a non-zero exit code causes the build to fail.
38−script:
39− - |
40− # Run tests
41− set -e
42− ./.travis/install-dependencies.sh
43− stack --no-terminal --jobs=2 --system-ghc test
44− - |
45− #Run HLint
46− if [[ "$(uname)" = "Linux" ]]; then
47− curl -sL https://raw.github.com/ndmitchell/hlint/master/misc/travis.sh | sh -s lint src test examples --cpp-define VERSION_project_m36=HLINT
48− fi
49− - |
50− #Run Haddock
51− if [[ "$(uname)" = "Linux" ]]; then
52− stack --no-install-ghc --system-ghc --no-haddock-deps haddock
53− fi
54−
55−after_success:
56− - |
57− # Build and ship binary
58− #./.travis/attach-binary.sh
59−
60−# EOF
.travis/attach-binary.shdeleted−25
@@ -1,25 +0,0 @@
1−#!/bin/sh
2−set -o errexit -o verbose
3−
4−if test ! "$BUILD_BINARY" || test ! "$TRAVIS_TAG"
5−then
6− echo 'This is not a release build.'
7−elif test ! "$GITHUB_TOKEN"
8−then
9− echo 'The GITHUB_TOKEN environment variable is not set!'
10− exit 1
11−else
12− echo "Building binary for $TRAVIS_OS_NAME to $TRAVIS_TAG..."
13− stack build --ghc-options -O2 --pedantic
14− echo "Attaching binary for $TRAVIS_OS_NAME to $TRAVIS_TAG..."
15− OWNER="$(echo "$TRAVIS_REPO_SLUG" | cut -f1 -d/)"
16− REPO="$(echo "$TRAVIS_REPO_SLUG" | cut -f2 -d/)"
17− BIN="$(stack path --local-install-root)/bin/$REPO"
18− BUNDLE_NAME="$REPO-$TRAVIS_TAG-$TRAVIS_OS_NAME.tar.gz"
19− cp "$BIN" "./$REPO"
20− chmod +x "./$REPO"
21− tar -czf "$BUNDLE_NAME" "$REPO"
22− echo "SHA256:"
23− shasum -a 256 "$BUNDLE_NAME"
24− ghr -t "$GITHUB_TOKEN" -u "$OWNER" -r "$REPO" --replace "$(git describe --tags)" "$BUNDLE_NAME"
25−fi
.travis/install-dependencies.shdeleted−22
@@ -1,22 +0,0 @@
1−# Run tests
2−if [[ "$(uname)" = "Darwin" ]]; then
3− timeout_cmd="gtimeout"
4−else
5− timeout_cmd="timeout"
6−fi
7−$timeout_cmd 40m stack --no-terminal --jobs=2 --install-ghc --system-ghc build --only-dependencies --fast
8−ret=$?
9−case "$ret" in
10− 0)
11− # continue
12− ;;
13− 124)
14− echo "Timed out while installing dependencies."
15− echo "Try building again by pushing a new commit."
16− exit 1
17− ;;
18− *)
19− echo "Failed to install dependencies; stack exited with $ret"
20− exit "$ret"
21− ;;
22−esac
.travis/install-ghc.shdeleted−16
@@ -1,16 +0,0 @@
1−#!/bin/sh
2−set -eux
3−#assume stack is installed
4−STACK=~/.local/bin/stack
5−
6−fetch_ghc_osx() {
7− echo "Using stack to install GHC $GHC_VERSION"
8− $STACK setup $GHC_VERSION
9−}
10−
11−if [ "$(uname)" = "Darwin" ]; then
12− fetch_ghc_osx
13−else
14− #installed by apt
15− echo "Linux GHC $GHC_VERSION via APT already installed."
16−fi
.travis/install-ghr.shdeleted−21
@@ -1,21 +0,0 @@
1−#!/bin/sh
2−set -o errexit -o verbose
3−
4−if test ! "$BUILD_BINARY" || test ! "$TRAVIS_TAG"
5−then
6− echo 'This is not a release build.'
7−else
8− if [ "$TRAVIS_OS_NAME" = "linux" ]
9− then
10− ARCH="linux"
11− else
12− ARCH="darwin"
13− fi
14− echo "Installing ghr"
15− URL="https://github.com/tcnksm/ghr/releases/download/v0.5.4/ghr_v0.5.4_${ARCH}_386.zip"
16− curl -L ${URL} > ghr.zip
17− mkdir -p "$HOME/bin"
18− export PATH="$HOME/bin:$PATH"
19− unzip ghr.zip -d "$HOME/bin"
20− rm ghr.zip
21−fi
.travis/install-stack.shdeleted−27
@@ -1,27 +0,0 @@
1−#!/bin/sh
2−
3−# Adapted from https://github.com/commercialhaskell/stack
4−
5−set -eux
6−
7−travis_retry() {
8− cmd=$*
9− $cmd || (sleep 2 && $cmd) || (sleep 10 && $cmd)
10−}
11−
12−fetch_stack_osx() {
13− curl -skL https://www.stackage.org/stack/osx-x86_64 | tar xz --strip-components=1 --include '*/stack' -C ~/.local/bin;
14−}
15−
16−fetch_stack_linux() {
17− curl -sL https://www.stackage.org/stack/linux-x86_64 | tar xz --wildcards --strip-components=1 -C ~/.local/bin '*/stack';
18−}
19−
20−# We need stack to generate cabal files with precise bounds, even for cabal
21−# builds.
22−mkdir -p ~/.local/bin;
23−if [ "$(uname)" = "Darwin" ]; then
24− travis_retry fetch_stack_osx
25−else
26− travis_retry fetch_stack_linux
27−fi
Changelog.markdown+33
@@ -1,3 +1,36 @@
1+# 2021-04-01 (v0.9.3)
2+
3+* add new ":importtutd <URI> <SHA256 hash>" feature to import TutorialD from a local file or a HTTP/HTTPS URI
4+
5+# 2020-12-27 (v0.9.0)
6+
7+* replace unmaintained distributed-process-client-server RPC package with new curryer RPC package
8+* drop support for GHC 8.2 and GHC 8.4 due to dependency on DerivingVia extension
9+
10+# 2020-11-21 (v0.8.2)
11+
12+* support multiple extend expressions in TutorialD
13+* fix parsing of Bool atoms in TutorialD
14+* fix database context expressions which include self-references such as `s:=s union s`
15+* show constraints as TutorialD when using tutd console
16+* add `RelationalExprAtom` data type useful for storing `RelationalExpr` within the database
17+
18+# 2020-10-05 (v0.8.1)
19+
20+* support GHC 8.10
21+
22+# 2020-05-25 (v0.8)
23+
24+* refactor backend to maximize laziness: [An Architecture for Data Independence](docs/data_independence.markdown)
25+
26+# 2019-09-07 (v0.7)
27+
28+* fix case sensitivity issue with relation variables in tutd
29+* fix multibyte escaping in data frames
30+* fix broken instances of `Atomable [a]`
31+* fix `TypeConstructor` validation of argument count
32+* add help option to executables
33+
134# 2019-01-08 (v0.6)
235
336* fix atom type parsing to support more complex data types
README.markdown+14−7
@@ -4,8 +4,8 @@
44[![Public Domain](https://img.shields.io/badge/license-Public%20Domain-brightgreen.svg)](http://unlicense.org)
55[![Hackage](https://img.shields.io/hackage/v/project-m36.svg)](http://hackage.haskell.org/package/project-m36)
66[![Hackage dependency status](https://img.shields.io/hackage-deps/v/project-m36.svg)](http://packdeps.haskellers.com/feed?needle=project-m36)
7−[![Build status](https://travis-ci.org/agentm/project-m36.svg?branch=master)](https://travis-ci.org/agentm/project-m36)
87[![Windows Build status](https://ci.appveyor.com/api/projects/status/q7jyddd6dy1ibqdo/branch/master?svg=true)](https://ci.appveyor.com/project/agentm/project-m36)
8+[![Github Workflow status](https://github.com/agentm/project-m36/workflows/CI/badge.svg)](https://github.com/agentm/project-m36/actions?query=workflow%3ACI)
99
1010
1111*Software can always be made faster, but rarely can it be made more correct.*
@@ -14,6 +14,12 @@
1414
1515Project:M36 implements a relational algebra engine as inspired by the writings of Chris Date.
1616
17+## Quick Install
18+
19+Project:M36 can be downloaded and run via docker, which supports Windows 10, macOS, and Linux.
20+
21+Run `docker run -it projectm36/project-m36 tutd` to start the TutorialD command line interface.
22+
1723## Description
1824
1925Unlike most database management systems (DBMS), Project:M36 is opinionated software which adheres strictly to the mathematics of the relational algebra. The purpose of this adherence is to prove that software which implements mathematically-sound design principles reaps benefits in the form of code clarity, consistency, performance, and future-proofing.
@@ -26,10 +32,6 @@ Project:M36 is written entirely in the [Haskell programming language](https://ww
2632
2733[![asciicast](https://asciinema.org/a/3syu35c8cydm403292a74l1n5.png)](https://asciinema.org/a/3syu35c8cydm403292a74l1n5)
2834
29−## Try It!
30−
31−You can experiment instantly with Project:M36 straight from your browser at [try.project-m36.io](https://try.project-m36.io)!
32−
3335## Use-Cases
3436
3537Project:M36 supports multiple frontends which target different audiences.
@@ -42,7 +44,7 @@ Project:M36 supports multiple frontends which target different audiences.
4244
4345* [Developer's Blog](https://agentm.github.io/project-m36/)
4446* [Mailing List/Discussion Group](https://groups.google.com/d/forum/project-m36)
45−* IRC Channel: chat.freenode.net #project-m36
47+* IRC Channel: irc.libera.chat #project-m36 -- [Chat via Web Client](http://kiwiirc.com/nextclient/irc.libera.chat:+6697/#project-m36)
4648* [Hackage](https://hackage.haskell.org/package/project-m36)
4749* [Diogo Biazus' Project:M36 Video Tutorial](https://www.youtube.com/watch?v=_GC_lxlVEnE)
4850
@@ -52,17 +54,20 @@ Project:M36 supports multiple frontends which target different audiences.
5254
53551. [Installation and Introduction to Project:M36](docs/introduction_to_projectm36.markdown)
54561. [Introduction to the Relational Algebra](docs/introduction_to_the_relational_algebra.markdown)
57+1. [TutorialD Cheatsheet](docs/tutd_cheatsheet.markdown)
55581. [TutorialD via Jupyter Notebook Walkthrough](jupyter/TutorialD%20Notebook%20Walkthrough.ipynb)
56591. [TutorialD Tutorial](docs/tutd_tutorial.markdown)
57601. [15 Minute Tutorial](docs/15_minute_tutorial.markdown)
58611. [Developer's Change Log](Changelog.markdown)
59621. [Simple Client API](docs/simple_api.markdown)
63+1. [CSV Import/Export](docs/import_export_csv.markdown)
6064
6165### Database Comparisons
6266
63671. [ACID Database Properties](docs/acid_assessment.markdown)
64681. [On NULL (in SQL)](docs/on_null.markdown)
65691. [Reaching "Out of the Tarpit" with Project:M36](docs/reaching_out_of_the_tarpit.markdown)
70+1. [An Architecture for Data Independence](docs/data_independence.markdown)
6671
6772### Advanced Features
6873
@@ -79,15 +84,17 @@ Project:M36 supports multiple frontends which target different audiences.
79841. [Isomorphic Schemas](docs/isomorphic_schemas.markdown)
80851. [Replication](docs/replication.markdown)
81861. [Basic Operator Benchmarks](https://rawgit.com/agentm/project-m36/master/docs/basic_benchmarks.html)
87+1. [Merkle Transaction Hashes](docs/merkle_transaction_graph.markdown)
8288
8389### Integrations
8490
85911. [WebSocket Server](docs/websocket_server.markdown)
86921. [Jupyter Notebook Kernel](docs/jupyter_kernel.markdown)
93+1. [Persistent Driver](https://github.com/YuMingLiao/persistent-project-m36)
8794
8895## Development
8996
90−Project:M36 is developed in Haskell and compiled with GHC 8.0.2 or later.
97+Project:M36 is developed in Haskell and compiled with GHC 8.6 or later.
9198
9299## Related Projects
93100
cabal.project+9−2
@@ -1,3 +1,10 @@
1−-- this is needed for GHC8 until distributed-process-extras is updated on Hackage with increased upper bounds
21packages: project-m36.cabal
3−allow-newer: distributed-process-extras:time,distributed-process-extras:binary,distributed-process-client-server:binary,distributed-process-client-server:time,distributed-process-async:time,distributed-process-async:binary
2+
3+package *
4+ split-sections: True
5+
6+--high-performance streaming library
7+source-repository-package
8+ type: git
9+ location: https://github.com/composewell/streamly.git
10+ tag: ac3af8749194f1788704dda8667d0b3807075cc2
default.nixnew file+1
@@ -0,0 +1 @@
1+(import ./release.nix { }).project
docker.nixnew file+18
@@ -0,0 +1,18 @@
1+{ compiler ? "ghc8104"
2+, sources ? import ./nix/sources.nix
3+, pkgs ? import sources.nixpkgs { }
4+}:
5+let
6+ release = import ./release.nix { inherit pkgs compiler sources; };
7+ static-project-m36 = pkgs.haskell.lib.dontCheck (pkgs.haskell.lib.justStaticExecutables release.project);
8+in
9+pkgs.dockerTools.buildImage {
10+ name = "project-m36";
11+ tag = "latest";
12+ contents = [ static-project-m36 ];
13+ # expose default project-m36 and websocket server ports
14+ config = {
15+ Env = [ "LC_ALL=en_US.UTF-8" ];
16+ ExposedPorts = { "6543/tcp" = { }; "8000/tcp" = { }; };
17+ };
18+}
docs/15_minute_tutorial.markdown+65−68
@@ -4,40 +4,34 @@ Thank you for evaluating Project:M36, a new relational algebra engine written in
44
55## Prerequisites
66
7−* any Linux
8−* GHC 7.10 or later version (Haskell compiler)
9−* cabal (package downloader) installed
7+* any Linux, MacOS, or Windows computer with Docker installed
108
119## Download and Install
1210
11+Run a pre-built docker image:
12+
13+```docker run -it projectm36/project-m36 tutd```
14+
15+or build it yourself with GHC >= 8.6:
16+
1317```bash
1418git clone https://github.com/agentm/project-m36.git
15−cabal sandbox init
16−cabal install --dependencies-only
17−cabal run tutd
19+cabal new-run tutd
1820```
1921
2022## Some Basic TutorialD
2123
22−When you run the ```tutd``` interpreter, you are interacting with an in-memory database using a dialect of the TutorialD language which is described in numerous book by Chris J. Date. It is a language specifically designed for human interaction with the relational algebra.
24+When you run the ```tutd``` interpreter, you are interacting with an in-memory database using a dialect of the TutorialD language which is described in numerous books by Chris J. Date. It is a language specifically designed for human interaction with the relational algebra.
2325
2426Note that TutorialD is strongly-typed- no type coercions take place automatically. For example, an integer will never be interpreted as a string or vice versa.
2527
2628### Load the Canonical Chris Date Example
2729
2830```
29−TutorialD (master/main): :importexample date
30−```
31−
32−or
33−
34−```
35−TutorialD (master/main): :importtud "scripts/DateExamples.tutd"
31+TutorialD (master/main): :importexample cjdate
3632```
3733
38−```:importtutd``` (do not skip typing the preceding colon), loads a file which contains a script written in the TutorialD dialect used by Project:M36 and executes it to change the state of the database. In this case, the relations "s" (supplier), "p" (product), and "sp" (suppliers-products) are now loaded.
39−
40−```:importexample date``` loads the date example directly without any file I/O, so it is safe to use with the websocket server.
34+```:importexample``` (do not skip typing the preceding colon), loads a built-in example schema and executes it to change the state of the database. In this case, the relations "s" (supplier), "p" (product), and "sp" (suppliers-products) are now loaded.
4135
4236### Execute Relational Expressions
4337
@@ -164,7 +158,7 @@ Database context expressions change the state of the database, much like "CREATE
164158#### Create a Relation Variable
165159
166160```
167−TutorialD (master/main): x:=relation{name Text, age Int}{tuple{name "Steve", age 40},tuple{name "Mike", age 31}}
161+TutorialD (master/main): x:=relation{name Text, age Integer}{tuple{name "Steve", age 40},tuple{name "Mike", age 31}}
168162TutorialD (master/main): :showexpr x
169163┌────────┬──────────┐
170164│age::Int│name::Text│
@@ -179,23 +173,25 @@ This is similar to SQL's "CREATE TABLE" operator.
179173#### Insert Additional Tuples
180174
181175```
182−TutorialD (master/main): x:=relation{name Text, age Int}{tuple{name "Steve", age 40},tuple{name "Mike", age 31}}
176+TutorialD (master/main): x:=relation{name Text, age Integer}{tuple{name "Steve", age 40},tuple{name "Mike", age 31}}
183177TutorialD (master/main): :showexpr x
184−┌────────┬──────────┐
185−│age::Int│name::Text│
186−├────────┼──────────┤
187−│40 │"Steve" │
188−│31 │"Mike" │
189−└────────┴──────────┘
178+┌────────────┬──────────┐
179+│age::Integer│name::Text│
180+├────────────┼──────────┤
181+│31 │"Mike" │
182+│40 │"Steve" │
183+└────────────┴──────────┘
184+
190185TutorialD (master/main): insert x relation{tuple{name "Bob", age 24}}
191186TutorialD (master/main): :showexpr x
192−┌────────┬──────────┐
193−│age::Int│name::Text│
194−├────────┼──────────┤
195−│40 │"Steve" │
196−│24 │"Bob" │
197−│31 │"Mike" │
198−└────────┴──────────┘
187+┌────────────┬──────────┐
188+│age::Integer│name::Text│
189+├────────────┼──────────┤
190+│31 │"Mike" │
191+│40 │"Steve" │
192+│24 │"Bob" │
193+└────────────┴──────────┘
194+
199195```
200196
201197Note that the relational insertion is identical to "x:=x union relation{...}".
@@ -204,50 +200,51 @@ Note that the relational insertion is identical to "x:=x union relation{...}".
204200
205201```
206202TutorialD (master/main): :showexpr s
207−┌──────────┬────────┬───────────┬───────────┐
208−│city::Text│s#::Text│sname::Text│status::Int│
209−├──────────┼────────┼───────────┼───────────┤
210−│"Paris" │"S2" │"Jones" │10 │
211−│"Paris" │"S3" │"Blake" │30 │
212−│"London" │"S1" │"Smith" │20 │
213−│"London" │"S4" │"Clark" │20 │
214−│"Athens" │"S5" │"Adams" │30 │
215−└──────────┴────────┴───────────┴───────────┘
203+┌──────────┬────────┬───────────┬───────────────┐
204+│city::Text│s#::Text│sname::Text│status::Integer│
205+├──────────┼────────┼───────────┼───────────────┤
206+│"London" │"S1" │"Smith" │20 │
207+│"Athens" │"S5" │"Adams" │30 │
208+│"Paris" │"S3" │"Blake" │30 │
209+│"London" │"S4" │"Clark" │20 │
210+│"Paris" │"S2" │"Jones" │10 │
211+└──────────┴────────┴───────────┴───────────────┘
216212TutorialD (master/main): update s where city="London" (status:=35)
217213TutorialD (master/main): :showexpr s
218−┌──────────┬────────┬───────────┬───────────┐
219−│city::Text│s#::Text│sname::Text│status::Int│
220−├──────────┼────────┼───────────┼───────────┤
221−│"London" │"S4" │"Clark" │35 │
222−│"London" │"S1" │"Smith" │35 │
223−│"Paris" │"S2" │"Jones" │10 │
224−│"Paris" │"S3" │"Blake" │30 │
225−│"Athens" │"S5" │"Adams" │30 │
226−└──────────┴────────┴───────────┴───────────┘
214+┌──────────┬────────┬───────────┬───────────────┐
215+│city::Text│s#::Text│sname::Text│status::Integer│
216+├──────────┼────────┼───────────┼───────────────┤
217+│"Athens" │"S5" │"Adams" │30 │
218+│"London" │"S1" │"Smith" │35 │
219+│"London" │"S4" │"Clark" │35 │
220+│"Paris" │"S3" │"Blake" │30 │
221+│"Paris" │"S2" │"Jones" │10 │
222+└──────────┴────────┴───────────┴───────────────┘
223+
227224```
228225#### Deleting Tuples from a Relation Variable
229226
230227```
231228TutorialD (master/main): :showexpr s
232−┌──────────┬────────┬───────────┬───────────┐
233−│city::Text│s#::Text│sname::Text│status::Int│
234−├──────────┼────────┼───────────┼───────────┤
235−│"Paris" │"S2" │"Jones" │10 │
236−│"Paris" │"S3" │"Blake" │30 │
237−│"London" │"S1" │"Smith" │20 │
238−│"London" │"S4" │"Clark" │20 │
239−│"Athens" │"S5" │"Adams" │30 │
240−└──────────┴────────┴───────────┴───────────┘
229+┌──────────┬────────┬───────────┬───────────────┐
230+│city::Text│s#::Text│sname::Text│status::Integer│
231+├──────────┼────────┼───────────┼───────────────┤
232+│"Paris" │"S2" │"Jones" │10 │
233+│"Paris" │"S3" │"Blake" │30 │
234+│"London" │"S1" │"Smith" │20 │
235+│"Athens" │"S5" │"Adams" │30 │
236+│"London" │"S4" │"Clark" │20 │
237+└──────────┴────────┴───────────┴───────────────┘
241238TutorialD (master/main): delete s where sname="Adams"
242239TutorialD (master/main): :showexpr s
243−┌──────────┬────────┬───────────┬───────────┐
244−│city::Text│s#::Text│sname::Text│status::Int│
245−├──────────┼────────┼───────────┼───────────┤
246−│"Paris" │"S2" │"Jones" │10 │
247−│"Paris" │"S3" │"Blake" │30 │
248−│"London" │"S1" │"Smith" │20 │
249−│"London" │"S4" │"Clark" │20 │
250−└──────────┴────────┴───────────┴───────────┘
240+┌──────────┬────────┬───────────┬───────────────┐
241+│city::Text│s#::Text│sname::Text│status::Integer│
242+├──────────┼────────┼───────────┼───────────────┤
243+│"Paris" │"S2" │"Jones" │10 │
244+│"London" │"S4" │"Clark" │20 │
245+│"Paris" │"S3" │"Blake" │30 │
246+│"London" │"S1" │"Smith" │20 │
247+└──────────┴────────┴───────────┴───────────────┘
251248```
252249
253250### Execute Transaction Graph Expressions
@@ -270,7 +267,7 @@ TutorialD (master/main): :rollback
270267
271268```
272269TutorialD (master/main): :branch experimental
273−TutorialD (experimental): employee:=relation{name Text, salary Int}
270+TutorialD (experimental): employee:=relation{name Text, salary Integer}
274271TutorialD (experimental): :commit
275272```
276273
docs/commits_in_constant_time.markdownnew file+134
@@ -0,0 +1,134 @@
1+# Transactional Database Commits in O(1)
2+
3+A.M.
4+
5+[Project:M36](https://github.com/agentm/project-m36)
6+
7+## Synopsis
8+
9+Common relational database management systems operate in an imperative manner by executing statements immediately. This naive strategy quickly becomes an IO-bound bottleneck. By applying Haskell's laziness-in-evaluation to database updates, new doors for optimizations based on what is queried make themselves apparent. Furthermore, by serializing thunks representing idempotent database updates, the database can commit transactions in constant time with regards to the tuple count since the tuples themselves need not be serialized. This optimization, combined with *fsync*-coalescing, can allow databases to commit to disk faster than tuples updates can be processed.
10+
11+Using this deferred execution technique, database updates can be processed in the background or, in the case when the tuples are never requested, never.
12+
13+These database update thunks and other interesting optimizations are implemented in [Project:M36](https://github.com/agentm/project-m36): an experimental, clean-room, purely Haskell implementation of an RDBMS engine based on the mathematical principles of the relational algebra.
14+
15+## Rationale
16+
17+A typical SQL RDBMS such as PostgreSQL executes a list of commands serially against a serializable representation of the database state without concern to whether or not the commands are effectively necessary to service subsequent requests. A database update which affects *n* tuples will necessitate disk writes of *O(n)* plus *O(n\*log(n))* writes for each affected index.
18+
19+By validating and serializing thunks of validated commands, Project:M36 commits can be independent of the tuple write cost. The thunks, which are flushed to non-volatile storage to complete the transaction commit, allow the DBMS to defer execution in preference to commit time.
20+
21+The deferral is, however, not required, and could be left as a option to the user or application.
22+
23+The final cost of committing in Project:M36 relates to the size of the update expression. If the update expression is, for example, a insertion of a large number of rows, then the commit cost will be *O(t)* where *t* is the number of tuples expressed in the update, but still independent of the cost of the existing tuples in the database.
24+
25+## Example and Comparison to PostgreSQL
26+
27+Let us walk through a specific example using SQL. While Project:M36 does not support SQL (and for [good reasons](https://github.com/agentm/project-m36/blob/master/docs/on_null.markdown)), comparing both databases with a common language is useful for illustrative purposes.
28+
29+Let us consider an existing database with a table/relation named "BigTable" which has 10 billion rows/tuples (an arbitrarily large number) of which one column is named "x" and represents a randomly-assigned integer. Next, assume that the user of the database will execute an update which will update every row/tuple, commit the changes, then query a subset of the resultant updated rows/tuples.
30+
31+
32+### The Update Expression
33+
34+Consider the following database update:
35+
36+```
37+UPDATE "BigTable" SET x = x + 1;
38+```
39+In PostgreSQL, the cost of executing this expression is incurred immediately upon execution. New tuples are laid down to disk (if the dataset is larger than *shared_buffers*), duplicating the entirety of the existing table/relation in storage (due to MVCC) for a cost of *O(n)* where *n* is the number of existing rows/tuples in "BigTable". If *x* is indexed, then the index writes incur an additional cost of *O(n\*log(n))* writes. Furthermore, PostgreSQL will write all changes to its write-ahead log, so the cost is multiplied by some factor.
40+
41+In Project:M36, the same expression can first be statically validated to adhere to the database constraints. The only constraint affected here is for the column/attribute *x* which requires an integer. Since adding one to any integer retains the integer type, the constraint can be determined to be unviolated without evaluating the expression, thus at a cost of *O(1)*. Project:M36 uses a novel WORM (write-once, read-many) strategy over journaled filesystems to avoid the need for a separate journal.
42+
43+*For the purpose of this example, assume that integer overflow is not a concern.*
44+
45+### The Commit
46+
47+```
48+COMMIT;
49+```
50+
51+In PostgreSQL, the write-ahead log mentioned above containing all tuples changes must now be flushed to non-volatile storage, creating a bottleneck to the slowest form of storage. A necessary checkpoint (which is configurable) could incur further writes as the tuples are flushed to disk as well.
52+
53+In Project:M36, the update expression must also be flushed to disk, but the expression is a mere few bytes appended to the transaction graph.
54+
55+### The Subsequent Query
56+
57+Finally, the user queries a subset of the updated table/relation.
58+
59+```
60+SELECT a, b, c, x FROM "BigTable" WHERE x > 10000;
61+```
62+
63+In PostgreSQL, considering that the column/attribute has an index, *O(log(n))* reads are needed to identify on which pages in the table's on-disk storage the proper values can be found. Considering that the value *x* was previously described as random, despite the restriction, in the worst case, every page of the on-disk table may need to be read because each page could contain one value matching the restriction. This would necessitate reading *O(n)* tuples previously written to disk. After reading the tuples, the tuples must be filtered by the restriction to service the query.
64+
65+In Project:M36, the state of the database is determined to be the difference of the previous state *S* (before the *x+1* update above) and *S'* (after the update). The serialized update expression can be deserialized and merged into the rewritten query:
66+
67+```
68+SELECT orig.a, orig.b, orig.c, x_orig + 1 AS x FROM (SELECT a, b, c, x AS x_orig FROM "BigTable"@S) AS orig WHERE x > 10000;
69+```
70+
71+where the *@* symbol references the state of "BigTable" at transaction state *S* in the past. The rewrite process can occur in constant time regarding the tuple count, but the execution does require reading the previous state *S* of "BigTable", filtering it as expected. The tuple read cost is equivalent to that of the same statement at *S'*: *O(log(n))* utilizing a b-tree index.
72+
73+### Summary
74+
75+| | PostgreSQL | Project:M36 |
76+|-|------------|-------------|
77+| UPDATE x+1 | *O(nlog(n))* | *O(1)* |
78+| COMMIT | flush *n* tuples to disk | flush expression to disk |
79+| SELECT x>10000 | *Ω(log(n))*, *O(n)* worst case | *O(log(n))* |
80+
81+Even if the user were to query all the tuples back, the actual IO cost in Project:M36 would be lower since the updates are only "executed" on the fly and not necessarily written to disk. However, a clever cacheing strategy could note that state *S* is queried often enough to warrant a cached version. The table's data on disk, however, is not required to answer the query.
82+
83+## Constraint Oracles
84+
85+To be able to perform an update and commit in constant or less than *O(n)* time does have some preconditions:
86+
87+ * constraints must be able to be statically validated in linear or logarithmic time
88+
89+However, even if constraints lack a proper oracle such as an index or a static means of validation and, thus, cannot be validated in constant time, the user may still benefit from serialization of the database update expression since writing the validated tuples to disk can be deferred beyond commit time and could go directly into an on-disk cache.
90+
91+## Worst Case Behavior
92+
93+Every database constraint can be represented as an inclusion dependency whereby the evaluation of a relational expression `sub` must be a subset of the evaluation of relational expression `super` (`sub ⊆ super`) for the constraint to validate. Therefore, the worst case time to validate any constraint, assuming that the constraint has an ideal oracle, is O(n) in the tuple count. However, as mentioned above, there are many constraints that can be validated in constant or less-than-linear time. Furthermore, the validated tuples need not be written to disk once the constraint is found to hold.
94+
95+Since there is great variation in constraint validation cost, the RDBMS could pre-analyze and report on associated constraints costs or make use of data independence to guide storage to optimize queries needed to service the constraint checker.
96+
97+## Caveats
98+
99+Certain types of updates still take a similar amount of time to commit in Project:M36 in comparison to PostgreSQL. Specifically, any update which relies on data outside the database's purview will necessitate flushing the tuple data since the update expression contains new tuple data not based on existing tuples. For example, the equivalent of:
100+
101+```
102+INSERT INTO "BigTable"(a, b, c, x) VALUES (1,5,10,10),(20,20,21,30),.... #many tuples
103+```
104+will still necessitate a *O(n)* tuple writes to disk in both databases. Though the asymptotic costs are equivalent, the number of writes are cut in half in Project:M36 since it does not require a write-ahead log.
105+
106+While PostgreSQL makes use of MVCC (multi-version concurrency control) which marks which tuples belong to a linear progression of transaction states, Project:M36 stores a full history of database state using a transaction graph (a directed acyclic graph similar to the commit-based graph of `git`). The graph allows named branches to be created and merged which also reduce contention around a singular graph head.
107+
108+## Applying Laziness to SQL RDBMSes
109+
110+Would it be possible to apply transaction-based laziness to an SQL-based RDBMS? Certainly, with sufficient shoe-horning, it could work, but SQL includes a few malfeatures which would make it difficult, if not impossible:
111+
112+ * Non-idempotent server-side functions prevent laziness because of side effects. PostgreSQL can mark functions as idempotent, but does not validate or enforce the idempotence, Project:M36, via Safe Haskell, can validate pure functions.
113+ * The lack of "time travel", the ability to query database state in the past prevents reliance on previous states, prevents direct referencing of previous database states on which the state differences can be built.
114+ * Tightly-coupled table-to-storage management prevents alternative data models. Indexing and constraint checking need to be statically verifiable and deferrable.
115+
116+These hurdles are not insurmountable, just perhaps not a good fit for SQL databases with a lot of historical and implementation baggage.
117+
118+## Benchmarks
119+
120+Forthcoming.
121+
122+## Conclusion
123+
124+Transactional time-to-commit is critical in ensuring that business decisions can make it to non-volatile storage as quickly as possible. By introducing Haskell-like, lazy evaluation to update expressions and serializing the resultant thunk, commits can be serialized in constant time, disregarding the number of tuples modified in the expression.
125+
126+This serialization strategy turns modern RDBMS architecture on its head since the table/relation-to-file mapping is broken, resulting in true data independence. Any on-disk representation of a relation at a specific transaction state therefore merely becomes a cached and purgeable entity, drastically shrinking on-disk cacheing requirements while expanding the scope in which said strategies can operate. Hopefully, a truly data independent architecture will result in new optimization discoveries.
127+
128+Project:M36 implements a transaction graph which can represent the entirety of database state, leaving room for any number of alternative representations, even for a single relation or relation across transaction states. A simple example could include storing two different orderings of tuples of the same relation in order to optimally serve different join queries. Common RDBMSes offer only two on-disk representations: the set of fully-evaluated tuples and indexes to those tuples, preventing data independence. Data independence paves the way towards the elimination of implementation-specific, gatekeeper roles such as database administrators.
129+
130+The promise of the relational algebra has always been the liberation of data from its data structure representation in order to be able to answer arbitrary queries. Modern DBMSes which typically map tables directly to one or more files on disk fail to live up to this promise. Project:M36 sets out to rectify this failure.
131+
132+In a greater context, applying laziness to an architecture to make use of more interesting optimizations is hardly new. The OpenGL API views its "immediate" mode as effectively deprecated. Filesystems take advantage of laziness using copy-on-write semantics. High-level programming languages can make greater, more interesting inferences about how a computation must be execute. A computer can always consider many more possible solution paths than a human can.
133+
134+The adherence to mathematical priniciples in Project:M36 results in features and optimization opportunities which have not yet been discovered. In contrast to RDBMSes designed around specific optimizations (such as indexes, specific disk layouts, or key-value lookups), Project:M36 sets out to demonstrate practically that future optimizations can only be discovered when operating within a mathematically-coherent architecture.
docs/data_independence.markdownnew file+109
@@ -0,0 +1,109 @@
1+# Project:M36: Towards an Architecture for Data Independence
2+
3+## Introduction
4+
5+The Project:M36 relational algebra architecture sets itself apart from typical DBMSes by ensuring strict transactional isolation, a branchable/mergeable (rather than linear) transaction graph, and storage of relational expressions (rather than storage of tuples). Let's look at how these architectural features work together to make Project:M36 the first relational algebra engine to implement true data independence.
6+
7+## What is Data Independence?
8+
9+C.J. Date writes:
10+
11+`Certainly most SQL products have failed to live up to the [relational] model's full potential...in those products, what the user sees and what is physically stored are essentially the same thing... In particular, it accounts for the argument, so often heard, to the effect that we have to "denormalize for performance."`
12+
13+`In principle, logical design has absolutely nothing to do with performance at all.`
14+
15+(Date, C.J. "Database In Depth: Relational Theory for Practitioners". O'Reilly Media. 2005. pages 156-157.)
16+
17+Data independence is therefore defined as the separation of the database user's experience from the database's means of in-memory or on-disk representation. As Date points out, virtually all database products implement a one-to-one mapping of relations to files in storage.
18+
19+One advantage of high-level abstractions in programming languages is to leverage advanced algorithms which can choose optimization paths on behalf of the user which a human may never be able to discover. While the promise of ever higher-level abstractions is realized by progamming languages such as Haskell, DBMS implementors have been resistant to data independence. This is due to several legacy factors such as companies pushing one-trick-pony database technologies and middlemen such as DBAs required to play gatekeeper against "bad" schema changes. The result is customers forced to run multiple disparate databases such as one for realtime transaction processing and another for analytics and another for audit logging. This recalcitrance has also led to the rise of databases such as "document" JSON databases with weak mathematical underpinnings in the name of performance as users become frustrated when hitting performance walls and dealing with arbitrary database limitations.
20+
21+Implementations which closely tie the user interface to backend representation close the door on interesting alternative representations and optimizations. For example, SQL databases typically store a single relation as a list of tuples on disk with supplementary indexes stored in separate files. There is no reason that the same relation couldn't be on disk or in memory in any number of formats. Such a table might be useful in various formats ideal for servicing different types of queries. Data independence grants the DBMS the permission to create any number of representations- including none at all- as long as the correct answer is provided to the user. "Column-store" databases may try to slice the tuples in a different axis, but those databases simply shift the performance problems elsewhere. Only implementation details prevent a database from offering both column-oriented *and* tuple-oriented representation while allowing the database to choose.
22+
23+That is why it is critical for the user's interface to the database *not* to include features such as "query hints" which would force a specific implementation in the backend. The user's interface must be declarative (describing the state change or query rather than *how* to execute it) and sufficiently high level. Any implementation detail leakage to the user's interface is a lost potential algorithmic optimization. While the topic of providing high-level interfaces is not specific to database design, we will continue to explore the ramifications of data independence in databases.
24+
25+
26+## Transactional Isolation
27+
28+While other databases offer various transaction isolation levels with differing levels of implementation-specific surprises, Project:M36 solely suppports the maximum transaction isolation level. Instead of relying on details of [MVCC](https://www.postgresql.org/docs/current/mvcc-intro.html) which marks each tuple in a relation with a monotonically-increasing number identifying from which transaction the tuple was added or deleted, Project:M36 includes no singular backing store for tuples, instead storing a stream of state change requests. Because the transaction graph supports branching and merging (similar to version control such as git), transactions can be committed without contention at a singular head of the graph. Committing to disk can be implemented as writing a file to represent the transaction's state and
29+
30+## The Transaction Graph
31+
32+These state changes are, in fact, the idempotent relational update expressions that the user has submitted. For example, given a transaction which includes a single relation `s`:
33+
34+```
35+┌──────────┬────────┬───────────┬───────────┐
36+│city::Text│s#::Text│sname::Text│status::Int│
37+├──────────┼────────┼───────────┼───────────┤
38+│"Paris" │"S2" │"Jones" │10 │
39+└──────────┴────────┴───────────┴───────────┘
40+```
41+
42+if the user commits a transaction with an insert such as:
43+
44+```
45+insert x relation{tuple{city "Boston", s# "S3", sname "Smith", status 400}}
46+```
47+
48+then a typical database will find the file representing the relation, find some free space in it and save the new tuple along with the MVCC transaction identifier. Subsequent transactions will find the tuple and compare it to their own transaction id in order to determine its "visibility". Project:M36, on the other hand, after validating that all relational constraints (such as primary and foreign keys) still hold, will simply serialize and append the expression to the transaction graph log. By default, there is no file representing the relation.
49+
50+For those familiar with Haskell, note how serializing the update expression is similar to being able to serialize a thunk or deferred execution.
51+
52+The transaction graph also allows users to travel back to previously-committed transactions. This may be useful for audit logging or alternative schemas.
53+
54+## Storage Representations
55+
56+Given the ever-growing transaction graph based on state changes, let's examine how Project:M36 services subsequent queries.
57+
58+## Benefits
59+
60+The primary goal of a database should be to ensure data integrity. Project:M36 takes no shortcuts in achieving this goal, but choosing a backend architecture which minimizes the time which it takes to get the transaction to non-volatile storage (disk) by storing update expressions rather than attempting to shuffle tuples on disk. This architecture open the door to many optimization techniques, many of which are new to databases.
61+
62+### Multiple On-Disk Representations
63+
64+The promise of data independence allows database backends to store relations as they see fit. That can include any number of on-disk representations including none at all. For example, for a table accessed by multiple projections, the database may choose to materialize the relation in those projections. The representations are therefore created in service to the queries submitted or anticipated instead of being based on past update expressions. Because on-disk storage is obviously limited, the database must decide what is valuable to keep around for future queries. This could open a new area of research into the appropriate machine learning algorithms, but, fundamentally, this set of materialized query responses is effectively a cache which can always be refreshed.
65+
66+The alternative representations need not be a direct answer to queries- for example, a materialized relation from a transaction could be used to service a query from a later transaction if the updates since that transaction are applied.
67+
68+The database could also anticipate, for example, scheduled queries and actually materialize relations before the query is executed. On-disk cache could represent "denormalized" tuple sets while the user-facing interface shows a properly normalized schema, thereby supporting data independence.
69+
70+More research in determining just what should be in the cache is needed.
71+
72+### Transactional Commits in O(1) Time
73+
74+Because the Project:M36 backend need not save tuples into a specific file representing a relation, the backend can drastically reduce the amount of time needed to commit a transaction to disk. Specifically, following constraint validation (which can often be done in constant or logarithmic time relative to the tuple count), the fastest means of committing the transaction is to save the update expression itself. Since the previous state has already been presumably committed, any idempotent operation can be saved for deferred execution. This means that transactions can be committed to disk relative to the size of the update expression rather than the number of the tuples affected- committing can occur at a rate relative to that of update expression size (typically a few kilobytes) rather than relative to the number of tuples that the update expression happened to alter.
75+
76+This technique gets transactions to disk faster, thus drastically increasing the rate transactions can be committed overall. Note that the execution of the update expression may be deferred by this process, so the cost to evaluate it may occur later, but this processing may be performed in the background after the transaction is committed. When the data is never requested, for example, for a defunct transaction graph branch, the actual execution could be deferred indefinitely, incurring zero cost to calculate the consquence of the update.
77+
78+### Less Disk Usage
79+
80+Because Project:M36 stores a stream of update expressions rather than tuples themselves, the minimum storage requirements for a given database may be reduced. For example, if a relation with an attribute `x` of type `Integer` has 1,000,000 tuples, a subsequent update to increment all 1,000,000 values by one may be cheaper to evaluate on-demand rather than immediately generating 1,000,000 new tuples and saving them to disk. If the new tuples are requested, the database can determine that the tuples are not materialized, calculate them, and return them, all without ever having the tuples on disk. Furthermore, if only a subset of the tuples are ever requested, for example, due to a query restriction, then some of the tuples may never need to be calculated or materialized.
81+
82+### Audit Logging
83+
84+Typical databases implement various strategies for audit logging, including:
85+
86+* exposing MVCC-like values such as tuple "created at" and "created by" to the user and forcing all tables to be insert-only
87+* shuttling audit logs to a secondary database
88+
89+Project:M36, through its inherent ability to travel the append-only transaction graph, enables audit-logging by allowing users to checkout previous transaction states. Committed transaction states are immutable, so no relation pollution or secondary database is necessary.
90+
91+### Selective Caching
92+
93+Typical databases materialize entire tuple sets representing each named relation (relation variable), but there is nothing special about relations that happen to be named. Data independence allows us to cache answers to common or even anticipated queries- this allows the schema to be normalized and unmaterialized while the *denormalized* query results are materialized cached. This flexibility saves disk space and allows the cache to be much more dynamic than in a typical DBMS.
94+
95+### Never-Materialized Tuples Replace Partitions
96+
97+Queries on very large relations often very often restricted (filtered by tuple) to generate subsets which are often partitioned, for example, by an event's date. Instead of requiring DBMS users to manually partition and slice their data in one, fixed, particular way, Project:M36's cacheing system will only cache those tuples that serve the interests of the queries. With something like an LRU cache, a data independent architecture will naturally cache "partitions" of the full relation without manual intervention.
98+
99+### Elimination of DBA role
100+
101+Databases essential to a business function are often guarded by a human database administrator (DBA) whose role it is to monitor database performance and to play gatekeeper to database schema changes as the database grows. This role is necessary because database tuning can be an arcane skill, rife with pitfalls for those who don't know the database software inside-and-out. This is a direct cause of data dependence, forcing DBAs to manually enforce data partitioning and shuffling data to different servers, configuring database replicas, and making Faustian bargains to "denormalize" tables for analytical workloads.
102+
103+A data independent architecture eliminates this role by allowing the database to make the optimal choices itself. This means that the database can respond to schema changes immediately, without manual repartitioning or denormalization steps.
104+
105+## Conclusion
106+
107+Project:M36's backend architecture enables new optimizations and features that are sorely lacking in existing DBMSes. By leveraging its novel transaction graph and deferred evaluation, Project:M36 handles more DBMS use-cases.
108+
109+Project:M36's novel architecture opens the door for further database and algorithmic research.
docs/filesystem-persistence.markdown+1−1
@@ -1,4 +1,4 @@
1−# Project-M36 Filesystem Persistence
1+# Project-M36 Filesystem Persistence (Change Proposal)
22
33## Introduction
44
docs/import_export_csv.markdownnew file+65
@@ -0,0 +1,65 @@
1+# Project:M36 CSV Import/Export
2+
3+Project:M36's `tutd` console supports the import and export of CSV files as a lowest-common denominator format for moving data. Because the CSV file format does not support all the features of Project:M36- most notably, nested relations- not all relation variables can be marshalled to-and-from CSV files.
4+
5+## CSV Export
6+
7+If a relation variable cannot be exported due to data types which are not supported by the CSV format- such as with a nested relation- then Project:M36 throws an error rather than export a partial file.
8+
9+### Example Export
10+
11+```
12+TutorialD (master/main): :importexample cjdate
13+TutorialD (master/main): :exportcsv s "/tmp/csv"
14+```
15+```
16+$ cat /tmp/csv
17+s#,sname,status,city
18+S2,Jones,10,Paris
19+S1,Smith,20,London
20+S4,Clark,20,London
21+S5,Adams,30,Athens
22+S3,Blake,30,Paris
23+```
24+
25+## CSV Import
26+
27+An import is equivalent to an insert and does not replace the target relation variable.
28+
29+Because relations do not have a natural ordering for their attributes, the CSV file to import must contain a header row which matches the names of attributes.
30+
31+If a value in the CSV file cannot be converted to the expected type (determined by the existing relation attributes), then the entire import is aborted rather than perform a partial import.
32+
33+### Example Import
34+```
35+$ cat /tmp/csv
36+s#,sname,status,city
37+S6,Samson,100,New York
38+```
39+```
40+TutorialD (master/main): :importexample cjdate
41+TutorialD (master/main): :showexpr s
42+┌──────────┬────────┬───────────┬───────────────┐
43+│city::Text│s#::Text│sname::Text│status::Integer│
44+├──────────┼────────┼───────────┼───────────────┤
45+│"Paris" │"S2" │"Jones" │10 │
46+│"Paris" │"S3" │"Blake" │30 │
47+│"London" │"S4" │"Clark" │20 │
48+│"London" │"S1" │"Smith" │20 │
49+│"Athens" │"S5" │"Adams" │30 │
50+└──────────┴────────┴───────────┴───────────────┘
51+TutorialD (master/main): :importcsv "/tmp/csv" s
52+TutorialD (master/main): :showexpr s
53+┌──────────┬────────┬───────────┬───────────────┐
54+│city::Text│s#::Text│sname::Text│status::Integer│
55+├──────────┼────────┼───────────┼───────────────┤
56+│"Paris" │"S3" │"Blake" │30 │
57+│"London" │"S4" │"Clark" │20 │
58+│"New York"│"S6" │"Samson" │100 │
59+│"Athens" │"S5" │"Adams" │30 │
60+│"London" │"S1" │"Smith" │20 │
61+│"Paris" │"S2" │"Jones" │10 │
62+└──────────┴────────┴───────────┴───────────────┘
63+```
64+
65+Note that relations do not have ordering, thus, no ordering from the CSV file is preserved.
docs/introduction_to_projectm36.markdown+28−9
@@ -15,16 +15,35 @@ The relational algebra is the mathematical model underpinning Project:M36. When
1515
1616## Binary Releases
1717
18−### Windows
19−Project:M36 now provides binary installations for Windows. Check the (releases page)[https://github.com/agentm/project-m36/releases] for downloads.
18+The quickest and preferred method of installation is via docker, which works on Linux, macOS, and Windows. Docker downloads and runs preconfigured software in secure, sandboxed containers, preventing third-party software from altering the host system without your permission.
2019
21−### MacOS X
20+### Install Docker:
2221
23−Binary releases are not yet available for MacOS X, but compiling from source is easy.
22+* [Windows 10 Docker Installation](https://docs.docker.com/docker-for-windows/wsl/)
23+* [MacOS Docker Installation](https://docs.docker.com/docker-for-mac/install/)
24+* [Linux Docker Installation](https://docs.docker.com/engine/install/#server)
2425
25−### Linux
26+### Run TutorialD from Docker Image
2627
27−The currently-preferred method of installation is from source. A future enhancement would be installation from deb or rpm.
28+This downloads the docker image tagged "latest" and runs `tutd`, the TutorialD command line interface. Try the [15-Minute TutorialD Tutorial](15_minute_tutorial.markdown) and try some expressions.
29+
30+```bash
31+docker run -it projectm36/project-m36 tutd
32+```
33+
34+### Run Project:M36 Server
35+
36+The default port for the project-m36 server is 6543.
37+
38+```bash
39+docker run --network host projectm36/project-m36 project-m36-server -n <database_name>
40+```
41+
42+### Connect to Project:M36 Server
43+
44+```bash
45+docker run --network host projectm36/project-m36
46+```
2847
2948## Source Installation
3049
@@ -32,7 +51,7 @@ Requirements:
3251
3352To build with stack:
3453
35−* [GHC 8.2.2 or greater](https://www.haskell.org/downloads)
54+* [GHC 8.6.5 or greater](https://www.haskell.org/downloads)
3655* [Haskell stack](https://docs.haskellstack.org/en/stable/README/)
3756* Linux, macOS, or Microsoft Windows
3857
@@ -40,11 +59,11 @@ Compilation steps:
4059
4160* ```git clone https://github.com/agentm/project-m36```
4261* ```cd project-m36```
43−* ```stack --stack-yaml stack.ghc8.2.yaml build```
62+* ```stack --stack-yaml stack.ghc8.6.yaml build```
4463
4564At this point, the TutorialD interactive interpreter can be run using ```stack exec tutd```.
4665
47−Alternative building with GHC 8.0.2 or greater:
66+Alternative building with GHC 8.6.5 or greater:
4867
4968* ```cabal new-build```
5069
docs/introduction_to_the_relational_algebra.markdown+2−2
@@ -202,7 +202,7 @@ Join (Instructor relation)
202202
203203(Course Relation)
204204
205−|(Course Name, Course Name Type)|(Instructor, Instructor Name Type)|(Course Room Number, Room Number Type)|
205+|(Course Name, Course Name Type)|(Instructor Name, Instructor Name Type)|(Course Room Number, Room Number Type)|
206206|-------------------------------|----------------------------------|--------------------------------------|
207207|English 1|Steve|Room 104|
208208|French 2|Bob|Room 103|
@@ -378,7 +378,7 @@ Since a value can store any (immutable) type, it can certainly hold a relation.
378378
379379For example, in SQL, if one wants to collect some aggregate data over some tuples while still returning the individual tuples, in the best case, the aggregate information must be repeated for every individual tuple. In the worst case, two separate queries are required since nested tables are not supported.
380380
381−In the relational algebra, The aggregate value can be placed alongside the relation value from whic the aggregate was derived.
381+In the relational algebra, The aggregate value can be placed alongside the relation value from which the aggregate was derived.
382382
383383Example:
384384
docs/merkle_transaction_graph.markdownnew file+33
@@ -0,0 +1,33 @@
1+# Project:M36: Merkle Hashing for Transaction Graph
2+
3+## Introduction
4+
5+Project:M36 supports an append-only transaction graph model (similar to git) whereby new transactions can be added to the graph but not removed. As with any graph, each node can contain a Merkle hash which ensures not only that it's state since being added to the graph has not changed but also that none of its parent nodes all the way to the root node (initial state) have not been modified. This validation has a number of use cases.
6+
7+## Usage
8+
9+Project:M36 automatically adds Merkle hashes to every transaction. All data which represents the database state at that transaction is included in the hash including (but not limited to) relation variable definitions, atom and database context functions, constraints, and types.
10+
11+Project:M36 validates all merkle hashes at database startup. For users who need validation after the database is started, the user can issue `:validatemerklehashes` at the `tutd` command line.
12+
13+### Audit Logging
14+
15+Project:M36 supports audit logging by allowing users to travel to transactions in the past and recreate the database state at that past point-in-time. To ensure that those past states cannot be modified either by malicious on-disk or in-memory changes, each transaction is protected by its own Merkle hash. If the calculated hash does not match the stored hash, Project:M36 can immediately report which transaction triggered the tamper-proof log.
16+
17+### Reproducibility
18+
19+Since a Merkle tree is effectively immutable except to add more nodes, it can be used to save and restore a whole database with very high confidence in the results. This feature could also be used to restore a database partially; for example, to duplicate just the latest database state on a second machine for OLAP analysis.
20+
21+### High-Availability
22+
23+Merkle tree hashes can be used to assert database integrity across high-availibility or database replication. Since the hash covers all database state, it can be used to validate log-shipping-based replication. Corrupted cache tuple data can be easily detected and flushed.
24+
25+## Merkle Hashes in Other DBMSes
26+
27+While Merkle hashes have become prevalent in blockchain-style databases, they have not made many appearances in typical SQL databases. This is likely due to the fact that such databases consider any additional operations against the large tuple stores as prohibitively expensive. Project:M36 is able to skirt this cost by only hashing database update expressions rather than the result of these executed expressions. This also means that the Merkle hash can be computed against transactions which have been created but never executed.
28+
29+## Conclusion
30+
31+Merkle hashes are an obvious improvement to any graph-based transaction log and are a low-cost method of ensuring data integrity.
32+
33+A further improvement could allow users to specify an initial key provided by an admin user to salt the hash used to create the database. Additionally, a multi-user system could allow individual users to sign their committed transactions. The signature would then be included in the Merkle hash.
docs/reaching_out_of_the_tarpit.markdown+1−1
@@ -57,7 +57,7 @@ Project:M36 implements multiple interfaces:
5757To understand how Project:M36 stacks up against the fictional programming language shown in the paper, we have implemented the [example from the paper](/examples/out_of_the_tarpit.tutd). The language used in the script is a dialect of Chris Date's TutorialD language. It can be loaded into an interactive ```tutd``` session like so:
5858
5959```
60−TutorialD (master/main): :importexample date
60+TutorialD (master/main): :importexample cjdate
6161TutorialD (master/main): :showexpr p
6262┌───────────────────┬────────────┬───────────────────┬────────────┬────────────┐
6363│address::Address │agent::Agent│dateRegistered::Day│photo::Text │price::Price│
docs/server_mode.markdown+1−1
@@ -8,7 +8,7 @@ While Project:M36 is easy-to-use as an interactive, in-process database manageme
88
99To start the Project:M36 server to serve the local host with a database named "mydbname", run ```cabal run project-m36-server -- --database mydbname --hostname 127.0.0.1``` in the project-m36 source directory. The double-dash indicates that the arguments should be passed to ```project-m36-server``` instead of ```cabal```. Under normal conditions, this command will print nothing and block indefinitely to serve incoming requests on the default port 6543.
1010
11−Note that the above invocation will serve and in-memory, transient "mydbname" database. The database is deleted when the server exits. To serve a database with filesystem persistence, invoke ```cabal run project-m36-server -- --database mydbname --hostname 127.0.0.1 --database-directory /path/to/dbdirectory --fsync```.
11+Note that the above invocation will serve an in-memory, transient "mydbname" database. The database is deleted when the server exits. To serve a database with filesystem persistence, invoke ```cabal run project-m36-server -- --database mydbname --hostname 127.0.0.1 --database-directory /path/to/dbdirectory --fsync```.
1212
1313## Connecting an Interactive Client
1414
docs/transaction_graph_operators.markdown+6−4
@@ -43,15 +43,17 @@ TutorialD (master/main): :rollback
4343In order to navigate the transaction graph, one must specify transaction UUIDs. Viewing the entirety of the transaction graph as a relation is a single command.
4444
4545```
46−TutorialD (master/main): :showgraph
47−┌─────────────┬──────────┬──────────────────────────────────────┬────────────────────────────┬──────────────────────────────┐
48−│current::Bool│head::Text│id::Text │parents::relation {id::Text}│stamp::DateTime │
49−├─────────────┼──────────┼──────────────────────────────────────┼────────────────────────────┼──────────────────────────────┤
46+┌─────────────┬────────────────────────────────────────────┬──────────┬──────────────────────────────────────┬────────────────────────────────────────┬─────────────────────────────────┐
47+│current::Bool│hash::ByteString │head::Text│id::Text │parents::relation {id::Text} │stamp::DateTime │
48+├─────────────┼────────────────────────────────────────────┼──────────┼──────────────────────────────────────┼────────────────────────────────────────┼─────────────────────────────────┤
49+
5050
5151<big result elided>
5252```
5353The "current" attribute is a boolean value. If true, the transaction is the parent of the current database context. Commits will be children of this transaction.
5454
55+The "hash" attribute contains the merkle tree hash for the given transaction. This can be used to ensure that the transaction graph has been used in an append-only fashion, ensuring historical state and audit log integrity.
56+
5557The "head" attribute is a boolean value indicating whether or not the transaction is a "head" node of its graph. Head nodes are nodes which have no children.
5658
5759The "id" attribute is the UUID needed in order to navigate the graph.
docs/tupleable.markdown+19
@@ -23,6 +23,25 @@ instance Tupleable Person
2323
2424Now, ```Person``` values can be marshaled between the database and the client. The attribute names appearing in the Haskell data type will appear identically in the server with the same types.
2525
26+### Changing Options
27+
28+If our field names don't exactly match attribute names, but follow a common pattern, we can derive Tupleable with custom options. Let's say each field on person has a prefix "person", but we still want to use the attribute names without the prefix. We can make use of the ProjectM36.Tupleable module to accomplish our goal like so:
29+
30+```haskell
31+import ProjectM36.Tupleable.Deriving
32+
33+data Person = Person {
34+ personName :: Text,
35+ personEmployeeNumber :: Int,
36+ personLikesHorses :: Bool
37+ }
38+ deriving stock Generic
39+ deriving Tupleable
40+ via Codec (Field (DropPrefix "person" >>> CamelCase)) Person
41+```
42+
43+The extensions DerivingGeneric, DerivingVia, TypeOperators, and DataKinds must be enabled for this code to compile. See the documentation on Hackage for all available options.
44+
2645## Usage
2746
2847The ```Tupleable``` module includes the following functions:
docs/tutd_cheatsheet.markdownnew file+99
@@ -0,0 +1,99 @@
1+# Tutorial D Cheatsheet
2+
3+The following tables list examples of expressions for `tutd`, Project:M36's "Tutorial D" implementation.
4+
5+## Relational Expressions
6+
7+Relational expressions query database state without being able to change it.
8+
9+|Relational Expression |Description |
10+|------------------------------------------------------|---------------------------------------|
11+|`:showexpr p`|Display the relation variable `p`|
12+|`:showexpr s rename {city as town}`|Display the result after renaming a relational attribute|
13+|`:showexpr p{color,city}`|Display the result of the projection on the `color` and `city` attributes|
14+|`:showexpr p{all but city}`|Display the result of the projection of all attribute of `p` except `city`|
15+|`:showexpr p join sp`|Display the result of the relational expression `p` joined against `sp` (equivalent to `NATURAL JOIN` in SQL)|
16+|`:showexpr (s join sp){all from s}`|Display the result of a join but only include attributes from `s`|
17+|`:showexpr s semijoin sp`|Equivalent to `(s join sp){all from s}`|
18+|`:showexpr s antijoin sp`|Display the result of all tuples in `s` which do not match appear in the result of `s semijoin sp`|
19+|`:showexpr s union s`| Display the result of `s` unioned with itself (which is equivalent to `s`)|
20+|`:showexpr s:{status2:=add(10,@status)}`| Display the result of extending the `s` relation variable with a new attribute which adds 10 to each `status` attribute|
21+|`:showexpr s group ({sname,status,s#} as subrel)`| Display the result of grouping the `sname`, `status`, and `s#` into a subrel for each tuple in the `s` relation where the `city` attribute (not mentioned) is the grouping criteria|
22+|`:showexpr (s group ({sname,status,s#} as subrel)) ungroup subrel`| Display the result of unwrapping a subrelation to create one new tuple for each subrelation tuple in the result|
23+|`:showexpr s minus s`|Display the result after removing all tuples that match the second argument. `x minus x` is equivalent to `x where false`|
24+|`:showexpr relation{tuple{name "Mike",age 6},tuple{name "Sam",age 10}}`|Display an unnamed relation using manually constructed tuples|
25+|`:showexpr relation{a Integer, b Text}`|Display an empty-tupled relation of a specified type|
26+|`:showexpr relation{a Integer, b Text}{tuple{a 4, b "four"}}`|Display a relation bound by the specified types and containing one or more tuples|
27+|`:showexpr s group ({s#,sname,status} as subrel):{citycount:=count(@subrel)}`|Display a result which groups `s` by `city` and extends the relation by a count for each city.|
28+|`:showrelvars`|Display a list of relation variables in the current context along with their types (attributes)|
29+
30+## Built-In Types
31+
32+|Example Value Expression |Type |Explanation|
33+|------------------------------------------------------|---------------------------------------|-----------|
34+|`"abc"`|Text|UTF-8 string|
35+|`123`|Integer|an integer of limitless size (using gmp)|
36+|`int(456)`|Int|machine-word-based integer|
37+|`12.56`|Double|64-bit IEEE 754 floating point number|
38+|`dateTimeFromEpochSeconds(1502304846)`|DateTime||
39+|`fromGregorian(2017,05,30)`|Date||
40+|`t`|Bool|`t` or `f`|
41+|`bytestring("dGVzdGRhdGE=")`|Bytestring|base-64-encoded string of bytes|
42+|`interval(3,5,f,f)`|Interval(Integer)|the constructor function includes two bounds and two boolean flags for inclusiveness|
43+
44+## Database Context Expressions
45+
46+Database context expressions take the current database context as input and alter it to create a new
47+
48+|Database Context Expression |Description |
49+|------------------------------------------------------|---------------------------------------|
50+|`:importexample cjdate`|Imports a precooked schema from Chris Date's books resulting in relvars `s`, `sp`, and `p`|
51+|`:importtutd "file:///home/agentm/project-m36/scripts/emp.tutd"`|Imports TutorialD from file URI|
52+|`:importtutd "https://raw.githubusercontent.com/agentm/project-m36/master/scripts/emp.tutd" "effe32b247586dc3ac0079fc241b9618d41d189afcaeb7907edbe5a8b45992a4"`| Imports TutorialD from HTTP or HTTPS URI|
53+|`newrelvar:=relation{tuple{age 3}}`|Assign a new relation variable named `newrelvar`|
54+|`undefine s`|Remove a relation variable|
55+|`insert s relation{tuple{city "Boston",s# "S10",sname "Gonzalez",status 10}}`| Append to an existing relation variable with another relational expression|
56+|`update s where status=20 (sname:="Mr. Twenty")`|Replace one or more values in matching tuples with a new value|
57+|`delete sp where s#="S4"`|Remove tuples matching the criteria|
58+|`key s_key_constraint {s#} s`|Add a constraint named `s_key_constraint` on relation variable `s` ensuring that `s#` is unique|
59+|`foreign key s#_in_sp sp{s#} in s{s#}`|Add a foreign key constraint that ensures that `sp`'s `s#` attribute always references a `s#` value in `s`|
60+|`constraint s_status_less_than_50 (s where ^lt(50,@status)){} in false`|Add a constraint that stipulates that the `status` values in `s` are less than 50|
61+|`createarbitraryrelation employee {name Text, empid Int, hired DateTime} 3-100`|Create a relation variable with random values with between 3-100 tuples- useful for testing|
62+|`notify steve_change person where name="Steve" true (person where name="Steve"){address}`|Notify the current connection with an asynchronous event if any committed tuples matching `person where name="Steve"` with `true` for the pre-change state and `person where name="Steve"){address}` for the post-change state- these states will be sent along with the notification|
63+|`data Hair = Bald | Brown | Blond | OtherColor Text`|Create a new algebraic data type for use with values inside tuples|
64+|`undata Hair`|Delete the `Hair` custom type|
65+
66+
67+## Transaction Graph Expressions
68+
69+Transaction graph expressions alter the state of the transaction graph by append new states.
70+
71+|Transaction Graph Expression |Description |
72+|------------------------------------------------------|---------------------------------------|
73+|`:commit`|Save the current database context to a new transaction and add it to the transaction graph|
74+|`:rollback`|Return the database context to the state before any alterations were made|
75+|`:branch experimental`|Create a new branch from the existing branch and switch the current context to be able to commit to the new branch|
76+|`:jumphead master`|Discard any changes in the current context and jump to the head of a different branch|
77+|`:jump 11b601c9-f46b-42b0-a2ce-cf18ced31b7f`|Jump to the specific transaction by UUID- useful for introspecting past states|
78+|`:showgraph`|Display a representation of the transaction graph|
79+|`:walkbacktotime "2017-08-10 16:44:00"`|Walk back in time from the current branch until a transaction less than or equal to the time is found and switch the current context to that past transaction- useful for auditing|
80+
81+## Data Frame Expressions
82+
83+In contrast to relational expressions, data frame expressions generate ordered tuples.
84+
85+|Data Frame Expression |Description |
86+|------------------------------------------------------|---------------------------------------|
87+|`:showdataframe s orderby {status}`|Display a data frame result for the relational expression `s` and sort the tuples by `status`|
88+|`:showdataframe s{status} orderby {status descending} offset 1 limit 3`|Display a data frame result for `s{status}` but ordered by `status` values descending, skip the first tuple, and return no more than 3 tuples|
89+
90+## Trans-Graph Relational Expressions
91+
92+Trans-graph relational expressions allow queries spanning multiple transactions.
93+
94+|Trans-Graph Relational Expressions |Description |
95+|------------------------------------------------------|---------------------------------------|
96+|`:showtransgraphexpr s@master join sp@master`|Display a result for joining `s` and `sp` on the branch `master`|
97+|`:showtransgraphexpr s@master~ join sp@master`|Display a result for joining `s` on the parent transaction of `master`'s current head and `sp` on master|
98+|`:showtransgraphexpr s@master~^2`|Display a result for `s` two parents previous to the parent of the current `master`'s head|
99+
docs/tutd_tutorial.markdown+56−2
@@ -19,7 +19,7 @@ TutorialD (master/main):
1919The examples in this tutorial can be executed after loading Chris Date's sample relations using:
2020
2121```
22−:importexample date
22+:importexample cjdate
2323```
2424
2525Each section assumes a fresh instance of the Date examples. The relation variables created in the script are:
@@ -30,6 +30,24 @@ Each section assumes a fresh instance of the Date examples. The relation variabl
3030|p|parts|
3131|sp|contains mapping of which suppliers supply which parts|
3232
33+### Importing TutorialD from Other Sources
34+
35+The `tutd` console can also run TutorialD from a local file or from a web server.
36+
37+To import TutorialD from a file:
38+
39+```
40+:importtutd "file:///home/agentm/project-m36/scripts/emp.tutd"
41+```
42+
43+or from a web server:
44+
45+```
46+:importtutd "https://raw.githubusercontent.com/agentm/project-m36/master/scripts/DateExamples.tutd" "db9f3d9fe06d0a29b8355e045b89ec94d6428e3a3de93def7ca77bf0298b7010"
47+```
48+
49+The second argument is an optional SHA256 hash in hexadecimal form. This can be used to validate that the script has not changed since the last import. Importing TutorialD from the web is in general safe because it is effectively sandboxed with "Safe Haskell" for functions, so the script is contained security-wise, however, nothing prevents the script from running forever. Downloading a schema from the web is a great way to share schemas and to kick start your project without starting from scratch.
50+
3351### Types
3452
3553TutorialD is strongly-typed. The basic built-in types are:
@@ -197,7 +215,7 @@ TutorialD (master/main): :showexpr s{all but city}
197215└────────┴───────────┴───────────────┘
198216```
199217
200−Projection attributes can also be derived from a relational expression using `all from`:
218+Projection attributes can be derived from a relational expression using `all from`:
201219
202220```
203221TutorialD (master/main): :showexpr (s join sp){all from s}
@@ -213,6 +231,42 @@ TutorialD (master/main): :showexpr (s join sp){all from s}
213231
214232Above, we join `s` and `sp` but project the result back onto the attributes of `s`.
215233
234+Projection attributes can be unioned from multiple sources using `union of`:
235+
236+```
237+TutorialD (master/main): :showexpr (s join sp){union of {all from s} {all but p#}}
238+┌──────────┬────────────┬────────┬───────────┬───────────────┐
239+│city::Text│qty::Integer│s#::Text│sname::Text│status::Integer│
240+├──────────┼────────────┼────────┼───────────┼───────────────┤
241+│"Paris" │400 │"S2" │"Jones" │10 │
242+│"London" │400 │"S1" │"Smith" │20 │
243+│"Paris" │200 │"S3" │"Blake" │30 │
244+│"London" │200 │"S4" │"Clark" │20 │
245+│"London" │200 │"S1" │"Smith" │20 │
246+│"Paris" │300 │"S2" │"Jones" │10 │
247+│"London" │100 │"S1" │"Smith" │20 │
248+│"London" │300 │"S4" │"Clark" │20 │
249+│"London" │300 │"S1" │"Smith" │20 │
250+│"London" │400 │"S4" │"Clark" │20 │
251+└──────────┴────────────┴────────┴───────────┴───────────────┘
252+```
253+
254+Here, after joining `s` and `p`, the union of all attributes from `s` and all attributes from `p` except for `p#` are returned.all
255+
256+Finally, projection attributes can be intersected using `intersection of`:
257+
258+```
259+TutorialD (master/main): :showexpr (s join sp){intersection of {all from s} {all from p}}
260+┌──────────┐
261+│city::Text│
262+├──────────┤
263+│"London" │
264+│"Paris" │
265+└──────────┘
266+```
267+
268+Here, after joining `s` and `p`, we project on the intersection of attributes from `s` and `p` which happens to be `city`.
269+
216270#### Restriction
217271
218272Restriction is applied using a "where" clause, much like in SQL.
docs/websocket_server.markdown+2−2
@@ -16,8 +16,8 @@ except that the websocket server is now listening for websocket connections on p
1616
1717## Client Connection
1818
19−A [simple JavaScript library](/ProjectM36/Server/WebSocket/project-m36.js) to manage the WebSocket connection is available.
19+A [simple JavaScript library](/src/bin/ProjectM36/Server/WebSocket/project-m36.js) to manage the WebSocket connection is available.
2020
2121## Sample Application
2222
23−The [WebSocket example application](/ProjectM36/Server/WebSocket/websocket-client.html) can be used to learn TutorialD and for remote database access from the web browser.
23+The [WebSocket example application](/src/bin/ProjectM36/Server/WebSocket/websocket-client.html) can be used to learn TutorialD and for remote database access from the web browser.
examples/DerivingCustomTupleable.hsnew file+54
@@ -0,0 +1,54 @@
1+{-# LANGUAGE DeriveGeneric, DerivingVia, GeneralizedNewtypeDeriving, TypeOperators, DataKinds, OverloadedStrings #-}
2+
3+import ProjectM36.Tupleable.Deriving
4+import ProjectM36.Atomable (Atomable)
5+import Control.DeepSeq (NFData)
6+import Data.Text (Text)
7+import GHC.Generics (Generic)
8+import Codec.Winery
9+
10+newtype BlogId = BlogId { getBlogId :: Int }
11+ deriving stock (Eq, Ord, Show, Generic)
12+ deriving newtype (Num)
13+ deriving Serialise via WineryRecord BlogId
14+
15+instance NFData BlogId
16+instance Atomable BlogId
17+
18+data Blog = Blog
19+ { blogId :: BlogId
20+ , blogTitle :: Text
21+ , blogAuthorName :: Text
22+ }
23+ deriving stock (Show, Generic)
24+ deriving (Tupleable)
25+ via Codec (Field (DropPrefix "blog" >>> CamelCase)) Blog
26+ deriving Serialise via WineryRecord Blog
27+
28+data Comment = Comment
29+ { commentAuthorName :: Text
30+ , commentComment :: Text
31+ , commentFor :: BlogId
32+ }
33+ deriving stock (Show, Generic)
34+ deriving (Tupleable)
35+ via Codec (Field (DropPrefix "comment" >>> CamelCase)) Comment
36+ deriving Serialise via WineryRecord Comment
37+
38+main :: IO ()
39+main = do
40+ let exampleBlog = Blog
41+ { blogId = 0
42+ , blogTitle = "Cat Pics"
43+ , blogAuthorName = "Alice"
44+ }
45+ exampleComment = Comment
46+ { commentAuthorName = "Bob"
47+ , commentComment = "great"
48+ , commentFor = 0
49+ }
50+ print exampleBlog
51+ print (toTuple exampleBlog)
52+ putStrLn ""
53+ print exampleComment
54+ print (toTuple exampleComment)
examples/Plantfarm.hsnew file+446
@@ -0,0 +1,446 @@
1+{-# LANGUAGE DeriveGeneric #-}
2+
3+{-# LANGUAGE OverloadedStrings #-}
4+
5+{-# LANGUAGE DeriveAnyClass #-}
6+
7+{-# LANGUAGE DerivingVia #-}
8+
9+
10+import Codec.Winery (Serialise, WineryVariant(WineryVariant))
11+import Control.DeepSeq (NFData)
12+import Data.Aeson (FromJSON, ToJSON(toEncoding, toJSON))
13+import Data.Data (Proxy(Proxy))
14+import Data.Either (lefts, rights)
15+import Data.Functor (($>))
16+import Data.Text as T (Text)
17+import qualified Data.Text.Lazy as TL (pack)
18+import GHC.Generics (Generic)
19+import qualified ProjectM36.Base as Base
20+import ProjectM36.Client
21+ ( AtomExprBase(NakedAtomExpr)
22+ , Atomable(toAddTypeExpr, toAtom)
23+ , AttributeName
24+ , Connection
25+ , ConnectionInfo(InProcessConnectionInfo)
26+ , DatabaseContextExpr
27+ , DatabaseContextExprBase(Delete)
28+ , PersistenceStrategy(NoPersistence)
29+ , RelationalError
30+ , RelationalExprBase(RelationVariable, Restrict)
31+ , RestrictionPredicateExprBase(AttributeEqualityPredicate)
32+ , SessionId
33+ , close
34+ , commit
35+ , connectProjectM36
36+ , createSessionAtHead
37+ , databaseContextExprForUniqueKey
38+ , defaultHeadName
39+ , emptyNotificationCallback
40+ , executeDatabaseContextExpr
41+ , executeRelationalExpr
42+ , withTransaction
43+ )
44+import qualified ProjectM36.Relation as Relation
45+import ProjectM36.Tupleable
46+ ( Tupleable(fromTuple)
47+ , toDefineExpr
48+ , toDeleteExpr
49+ , toInsertExpr
50+ , toUpdateExpr
51+ )
52+import qualified System.Random as R
53+
54+
55+import Control.Monad.IO.Class (MonadIO(liftIO))
56+import qualified Web.Scotty as S
57+
58+-- | This is an example showcasing the updating of data
59+-- with the help of plants. \\
60+-- This is a very simple example and of course not how
61+-- plants grow in nature. \\
62+-- The main goal of this example is to showcase the updating
63+-- of data and the different options of persistence.
64+-- You can just pipe the output from curl into jq:
65+--
66+-- curl -X POST -H 'Accept: application/json' http://localhost:8001/plant/water/angu | jq -r '.stage'
67+
68+
69+data Stage = Seed | Sprout | Seedling | Adult | Dead
70+ deriving (Show, Eq, Ord, Generic, NFData, Atomable)
71+ deriving Serialise via WineryVariant Stage
72+
73+
74+instance ToJSON Stage where -- The where can be removed and the implementation commented out
75+ -- if the ascii values are not wanted
76+ toJSON s = toJSON $ show s <> "\nascii only provided for visualisation:\n" <> stagetoAscii s
77+
78+ toEncoding s = toEncoding $ show s <> "\nascii only provided for visualisation:\n" <> stagetoAscii s
79+
80+instance FromJSON Stage
81+
82+instance S.Parsable Stage where
83+ parseParam t
84+ | t == "seed" || t == "Seed" = Right Seed
85+ | t == "sprout" || t == "Sprout" = Right Sprout
86+ | t == "seedling" || t == "Seedling" = Right Seedling
87+ | t == "adult" || t == "Adult" = Right Adult
88+ | t == "dead" || t == "Dead" = Right Dead
89+ | otherwise = Left t
90+
91+
92+-- Just for ToJSON for ilustration of stage
93+type ASCIIStage = String
94+
95+seedStr :: ASCIIStage
96+seedStr = "<>\n\
97+ \'''\n"
98+sproutStr :: ASCIIStage
99+sproutStr = " ..\n\
100+ \<|>\n\
101+ \''''\n"
102+seedlingStr :: ASCIIStage
103+seedlingStr = " `\\⁄o \n\
104+ \ v|/\n\
105+ \'´;'''\n"
106+adultStr :: ASCIIStage
107+adultStr = "*~(#)~\n\
108+ \ \\,Y,e\n\
109+ \ \\|/\n\
110+ \''+'\\''\n"
111+deadStr :: ASCIIStage
112+deadStr = " ,__:<\n\
113+ \'/'''''\n"
114+
115+-- Just used for ToJSON illustration of stages
116+stagetoAscii :: Stage -> ASCIIStage
117+stagetoAscii Seed = seedStr
118+stagetoAscii Sprout = sproutStr
119+stagetoAscii Seedling = seedlingStr
120+stagetoAscii Adult = adultStr
121+stagetoAscii Dead = deadStr
122+
123+-- used for update stage
124+next :: Stage -> Stage
125+next Seed = Sprout
126+next Sprout = Seedling
127+next Seedling = Adult
128+next s = s
129+
130+data Plant = Plant { name :: Text, species :: Text, stage :: Stage, waterings:: Integer } deriving (Show, Generic)
131+instance Tupleable Plant
132+instance ToJSON Plant
133+instance FromJSON Plant
134+
135+
136+main :: IO ()
137+main = do
138+ putStrLn "Connecting to plant farm"
139+ c <- dbConnection
140+ _ <- createSchema c
141+ putStrLn "Planting some plants"
142+ _ <- insertSampleData c
143+ let port = 8001
144+ putStrLn $ "Started Plant farm at " <> show port
145+ S.scotty port $ do
146+
147+ -- retrieve a plant by name
148+ S.get "/plant/:name" $ do
149+ n <- S.param "name"
150+ e <- liftIO $ getPlant c n
151+ p <- handleWebError e
152+ S.json p
153+
154+
155+ -- save a plant providing it as json data
156+ S.post "/plant" $ do
157+ pl <- S.jsonData :: S.ActionM Plant
158+ e <- liftIO $ savePlant c [pl]
159+ p <- handleWebError e
160+ S.json p
161+
162+ -- updating a plant providing it as json data
163+ S.put "/plant" $ do
164+ pl <- S.jsonData :: S.ActionM Plant
165+ e <- liftIO $ updatePlantFst c pl
166+ p <- handleWebError e
167+ S.json p
168+
169+ -- watering the plant having the provided name.
170+ -- This will water the plant and might let it progress to the next stage. It might also die.
171+ S.post "/plant/water/:name" $ do
172+ n <- S.param "name"
173+ e <- liftIO $ waterPlant c n
174+ p <- handleWebError e
175+ S.json p
176+
177+ -- retriving all the plants as json data
178+ S.get "/plants" $ do
179+ e <- liftIO $ getAllPlants c
180+ ps <- handleWebErrors e
181+ S.json ps
182+
183+ -- saving many plants at the same time
184+ S.post "/plants" $ do
185+ pl <- S.jsonData :: S.ActionM [Plant]
186+ e <- liftIO $ savePlant c pl
187+ p <- handleWebError e
188+ S.json p
189+
190+ -- deleting all plants at a specific stage
191+ S.delete "/plants?stage=:stage" $ do
192+ s <- S.param "stage"
193+ e <- liftIO $ deletePlantsByStage c s
194+ p <- handleWebError e
195+ S.json p
196+
197+ -- deleting all plants at a specific stage
198+ S.delete "/plants" $ do
199+ s <- S.param "name"
200+ e <- liftIO $ deletePlantByName c s
201+ p <- handleWebError e
202+ S.json p
203+
204+ -- deleting all dead plants
205+ S.delete "/plants/clear" $ do
206+ e <- liftIO $ clearDeadPlants c
207+ ps <- handleWebErrors e
208+ S.json ps
209+
210+handleWebError :: Either Err b -> S.ActionM b
211+handleWebError (Left e) = S.raise (TL.pack $ "An error occurred:\n" <> show e)
212+handleWebError (Right v) = pure v
213+
214+handleWebErrors :: [Either Err b] -> S.ActionM [b]
215+handleWebErrors e = do
216+ case lefts e of
217+ [] -> pure (rights e)
218+ l -> S.raise (TL.pack $ "Errors occurred:\n" <> concatMap ((<>"\n") . show) l)
219+
220+
221+-- | watering a plant and thereby possibly updating its stage
222+waterPlant :: DBConnection -> Text -> IO (Either Err Plant)
223+waterPlant db n = do
224+ p <- getPlant db n
225+ case p of
226+ Left e -> pure $ Left e
227+ Right v -> updateStage db $ v { waterings = waterings v + 1 }
228+
229+-- | used by 'waterPlant' updates the stage depending on random numbers
230+updateStage :: DBConnection -> Plant -> IO (Either Err Plant)
231+updateStage db p@(Plant _ _ Dead _ ) = do
232+ tmp <- updatePlantFst db p
233+ case tmp of
234+ Left e -> pure $ Left e
235+ Right _ -> pure $ Right p
236+updateStage db p = do
237+ res <- calculateStage p
238+ tmp <- updatePlantFst db res
239+ case tmp of
240+ Left e -> pure $ Left e
241+ Right _ -> pure $ Right res
242+ where calculateStage p' = do
243+ r1 <- R.randomRIO (1, 10) :: IO Integer
244+ let np = if r1 < waterings p' then p' { stage = next $ stage p', waterings = 0 } else p'
245+ r2 <- R.randomRIO (1, 20)
246+ pure $ if r2 < waterings np then np { stage = Dead, waterings = 0 } else np
247+
248+-- | deletes all plants with Stage = Dead
249+clearDeadPlants :: DBConnection -> IO [Either Err Plant]
250+clearDeadPlants db = do
251+ _ <- deletePlantsByStage db Dead
252+ getAllPlants db
253+
254+
255+-- ****************************
256+-- | *Database functions* :
257+-- ****************************
258+
259+
260+-- | Error type for passing. It is not very specific.
261+-- Just minimal and non optimal for this example.
262+data Err = NotSpecified | NotFound deriving (Show ,Generic)
263+
264+instance ToJSON Err
265+
266+-- | Just for convinience for passing around the SessionId
267+-- and the Connection
268+data DBConnection = DB SessionId Connection
269+
270+
271+-- | Getting plants by their name.\
272+-- Because plant has name as primary key \
273+-- we can assume will get at most one result. \
274+-- Alternatively we could return a list.
275+getPlant :: DBConnection -> Text -> IO (Either Err Plant)
276+getPlant db n = defaultHead (Left NotFound) <$> (
277+ get db
278+ ( Restrict -- Restrict can be thought of as similar to "WITH" in SQL
279+ (AttributeEqualityPredicate "name" (NakedAtomExpr (toAtom n))) -- This is the Predicate we are "restricting" our RelationalExprBase with
280+ (RelationVariable "plants" ())
281+ )
282+ :: IO [Either Err Plant] -- this is needed because our 'get' function is
283+ )
284+
285+defaultHead :: a -> [a] -> a
286+defaultHead d [] = d
287+defaultHead _ (x:_) = x
288+
289+-- | Getting all the plants
290+getAllPlants :: DBConnection -> IO [Either Err Plant]
291+getAllPlants db = get db (RelationVariable "plants" ())
292+
293+-- | Getting all the plants that satisfy the restrictions
294+getAllPlantsWith :: DBConnection -> Base.RestrictionPredicateExpr -> IO [Either Err Plant]
295+getAllPlantsWith db ex = get db (Restrict ex (RelationVariable "plants" ()))
296+
297+
298+-- | Saving a plant
299+savePlant :: (Traversable t) => DBConnection -> t Plant -> IO (Either Err ())
300+savePlant db sps = insert db sps "plants"
301+
302+-- | An alternative to update alone because due to updates
303+-- not being cached yet \
304+-- they have to be calculated every update. \
305+-- This seems like an alternative until caching is implemented.
306+updatePlantFst :: DBConnection -> Plant -> IO (Either Err ())
307+updatePlantFst db pln = do
308+ _ <- delete db pln ["name"] "plants"
309+ savePlant db [pln]
310+
311+-- | Updating a plant. Due to the way project 36 works, \
312+-- updates have to be executed every time.\
313+-- This is slow but won't be an issue soon because they will
314+-- be cached.\
315+-- But because of this project 36 can provide O(1) commits.
316+updatePlant :: DBConnection -> Plant -> IO (Either Err ())
317+updatePlant db sps = update
318+ db -- db connection
319+ sps -- plant value
320+ ["name"] -- the attributes to be updated by (in case of unique key)
321+ "plants" -- the relation we want to update on
322+
323+
324+-- | deleting all plants that have given name.
325+deletePlantByName :: DBConnection -> Text -> IO (Either Err ())
326+deletePlantByName db s = executeWithTransaction db $ Right $ Delete "plants" $ AttributeEqualityPredicate "name" (NakedAtomExpr (toAtom s))
327+
328+-- | deleting all plants that have given stage.
329+deletePlantsByStage :: DBConnection -> Stage -> IO (Either Err ())
330+deletePlantsByStage db s = executeWithTransaction db $ Right $ Delete "plants" $ AttributeEqualityPredicate "stage" (NakedAtomExpr (toAtom s))
331+
332+
333+-- | Inserting the schema into the DB
334+createSchema :: DBConnection -> IO ()
335+createSchema (DB sessionId conn) = do
336+ _ <- handleIOErrorsAndQuit $ mapM (executeDatabaseContextExpr sessionId conn) [
337+ toAddTypeExpr (Proxy :: Proxy Stage) -- Adds the Type Stage as data to the DB
338+ , toDefineExpr (Proxy :: Proxy Plant) "plants" -- Creates the plants relation
339+ , databaseContextExprForUniqueKey "plants" ["name"] -- Makes name of the plants relation a uniqe Key,
340+ -- Foreign Key restrictions are available too
341+ ]
342+ pure ()
343+
344+
345+-- | inserting some sample data
346+insertSampleData :: DBConnection -> IO (Either Err ())
347+insertSampleData (DB sid conn) = do
348+ insert (DB sid conn) [
349+ Plant "angu" "Caladenia angustata" Seed 0
350+ , Plant "thely" "Thelymitra alcockiae" Seed 0
351+ , Plant "monstera" "Araceae" Seed 0
352+ ] "plants"
353+
354+dbConnection :: IO DBConnection
355+dbConnection = do
356+ -- connect to the database
357+ let connInfo = InProcessConnectionInfo NoPersistence emptyNotificationCallback []
358+ -- The code below persists the data in a DB with the name "base". \\
359+-- let connInfo = InProcessConnectionInfo (CrashSafePersistence "base") emptyNotificationCallback [] \\
360+ -- In addition minimal persistance is available. \\
361+-- let connInfo = InProcessConnectionInfo (MinimalPersistence "base") emptyNotificationCallback []
362+ conn <- handleIOErrorAndQuit $ connectProjectM36 connInfo
363+ --create a database session at the default branch of the database
364+ sessionId <- handleIOErrorAndQuit $ createSessionAtHead conn defaultHeadName
365+ pure (DB sessionId conn)
366+
367+
368+-- | A polymorphic function to insert data (a traversable of data) into the DB
369+insert :: (Tupleable a, Traversable t) => DBConnection -> t a -> Base.RelVarName -> IO (Either Err ())
370+insert db rlv rlvName = executeWithTransaction db $ toInsertExpr rlv rlvName
371+
372+-- | A polymorphic function to update data in the DB.
373+-- An update in one funtion would take:
374+--
375+-- - SessionId
376+-- - Connection
377+-- - Tuplable a -- the Tuplable you want to update
378+-- - [AttributeName] -- the Attributes of the Tuplable you want to update those are of StringType
379+-- - RelVarName -- the name of the relation
380+--
381+-- With that you can via 'toUpdateExpr' create a 'DatabaseContextExpr' to be executed. \\
382+-- For inserting its very similarly done with 'toInsertExpr'.
383+update :: (Tupleable a) => DBConnection -> a -> [AttributeName]-> Base.RelVarName -> IO (Either Err ())
384+update db rlv attr rlvName = executeWithTransaction db $ toUpdateExpr rlvName attr rlv
385+
386+-- | A polymorphic function to delete data in the DB
387+delete :: (Tupleable a) => DBConnection -> a -> [AttributeName]-> Base.RelVarName -> IO (Either Err ())
388+delete db rlv attr rlvName = executeWithTransaction db $ toDeleteExpr rlvName attr rlv
389+
390+-- | A convenience function to make executing DBContextExpr with commiting simpler. \\
391+-- In particular for expr that just insert, delete and update.
392+-- Therefor ultimately return Either _ ()
393+executeWithTransaction :: DBConnection -> Either RelationalError DatabaseContextExpr -> IO (Either Err ())
394+executeWithTransaction (DB sid conn) expr = do
395+ iEx <- handleError expr
396+ case iEx of
397+ Left e -> pure $ Left e
398+ Right v -> handleIOError $ withTransaction sid conn (executeDatabaseContextExpr sid conn v) (commit sid conn)
399+
400+-- | A polymorphic function to get data (a list of data and possibly errors) from the DB
401+get :: Tupleable b => DBConnection -> Base.RelationalExpr -> IO [Either Err b]
402+get (DB sessionId conn) q = do
403+ eRel <- executeRelationalExpr sessionId conn q
404+ e <- handleError eRel
405+ case e of
406+ Left err -> pure [Left err]
407+ Right pRel -> do
408+ ws <- Relation.toList pRel
409+ mapM (handleError . fromTuple) ws
410+
411+-- | for closing the DB connection.
412+-- Not really needed when using in-memory DB
413+closeConn :: DBConnection -> IO ()
414+closeConn (DB _ conn) = close conn
415+
416+
417+-- | Error handling is heavily inspired by 'blog.hs' the blog example \\
418+-- by (agentm)[https://github.com/agentm] (https://github.com/agentm/project-m36, commit: f8432522adaafeae7c32bc2b8b6cb09c00396fc6). \\
419+-- As stated there, your application should have proper error handling.
420+handleIOErrorAndQuit :: Show e => IO (Either e a) -> IO a
421+handleIOErrorAndQuit m = do
422+ v <- m
423+ handleErrorAndQuit v
424+
425+handleError :: Show e => Either e a -> IO (Either Err a)
426+handleError eErr = case eErr of
427+ Left err -> print err $> Left NotSpecified
428+ Right v -> pure $ Right v
429+
430+handleIOError :: Show e => IO (Either e a) -> IO (Either Err a)
431+handleIOError m = do
432+ v <- m
433+ handleError v
434+
435+handleErrorAndQuit :: Show e => Either e a -> IO a
436+handleErrorAndQuit eErr = case eErr of
437+ Left err -> print err >> error "Quit."
438+ Right v -> pure v
439+
440+handleIOErrorsAndQuit :: Show e => IO [Either e a] -> IO [a]
441+handleIOErrorsAndQuit m = do
442+ eErrs <- m
443+ case lefts eErrs of
444+ [] -> pure (rights eErrs)
445+ err:_ -> handleErrorAndQuit (Left err)
446+
examples/SimpleClient.hs+1−1
@@ -6,7 +6,7 @@ import Data.Text.IO as TIO
66main :: IO ()
77main = do
88 -- 1. create a ConnectionInfo
9− let connInfo = RemoteProcessConnectionInfo "mytestdb" (createNodeId "127.0.0.1" defaultServerPort) emptyNotificationCallback
9+ let connInfo = RemoteConnectionInfo "mytestdb" "127.0.0.1" (show defaultServerPort) emptyNotificationCallback
1010 -- 2. conncted to the remote database
1111 eConn <- connectProjectM36 connInfo
1212 case eConn of
examples/blog.hs+11−8
@@ -1,5 +1,5 @@
11-- a simple example of a blog schema
2−{-# LANGUAGE DeriveAnyClass, DeriveGeneric, OverloadedStrings #-}
2+{-# LANGUAGE DeriveAnyClass, DeriveGeneric, OverloadedStrings, CPP, DerivingVia #-}
33
44import ProjectM36.Client
55import ProjectM36.Base
@@ -10,16 +10,18 @@ import ProjectM36.Tuple (atomForAttributeName)
1010
1111import Data.Either
1212import GHC.Generics
13−import Data.Binary
1413import qualified Data.Text as T
1514import qualified Data.Text.Lazy as TL
1615import Data.Time.Clock
1716import Data.Time.Calendar
1817import Control.DeepSeq
1918import Data.Proxy
19+#if __GLASGOW_HASKELL__ < 804
2020import Data.Monoid
21+#endif
2122import Data.List
2223import Control.Monad (when, forM_)
24+import Codec.Winery
2325
2426import Web.Scotty as S
2527import Text.Blaze.Html5 (h1, h2, h3, p, form, input, (!), toHtml, Html, a, toValue, hr, textarea)
@@ -33,7 +35,7 @@ import Data.Time.Format
3335data Blog = Blog {
3436 title :: T.Text,
3537 entry :: T.Text,
36− stamp :: UTCTime,
38+ tstamp :: UTCTime,
3739 category :: Category --note that this type is an algebraic data type
3840 }
3941 deriving (Generic, Show) --derive Generic so that Tupleable can use default instances
@@ -50,7 +52,8 @@ data Comment = Comment {
5052instance Tupleable Comment
5153
5254data Category = Food | Cats | Photos | Other T.Text -- note that this data type could not be represented by an "enumeration" as found in SQL databases
53− deriving (Atomable, Eq, Show, NFData, Binary, Generic) -- derive Atomable so that values of this type can be stored as a database value
55+ deriving (Atomable, Eq, Show, NFData, Generic) -- derive Atomable so that values of this type can be stored as a database value
56+ deriving Serialise via WineryVariant Category -- derive Serialisable to be able to transmit this data remotely
5457
5558-- add some short-hand error handling- your application should have proper handling
5659handleIOError :: Show e => IO (Either e a) -> IO a
@@ -103,11 +106,11 @@ insertSampleData :: SessionId -> Connection -> IO ()
103106insertSampleData sessionId conn = do
104107 let blogs = [Blog { title = "Haskell Lenses",
105108 entry = "I wear Haskell rose-colored lenses.",
106− stamp = UTCTime (fromGregorian 2017 5 8) (secondsToDiffTime 1000),
109+ tstamp = UTCTime (fromGregorian 2017 5 8) (secondsToDiffTime 1000),
107110 category = Food },
108111 Blog { title = "Haskell Monad Analogy",
109112 entry = "Monads are like burritos going through intestines.",
110− stamp = UTCTime (fromGregorian 2017 6 10) (secondsToDiffTime 2000),
113+ tstamp = UTCTime (fromGregorian 2017 6 10) (secondsToDiffTime 2000),
111114 category = Cats }
112115 ]
113116 comments = [Comment { blogTitle = "Haskell Lenses",
@@ -136,7 +139,7 @@ listBlogs sessionId conn = do
136139 Left err -> render500 (toHtml (show err))
137140 Right blogRel -> do
138141 blogs <- liftIO (toList blogRel) >>= mapM (handleWebError . fromTuple) :: ActionM [Blog]
139− let sortedBlogs = sortBy (\b1 b2 -> stamp b1 `compare` stamp b2) blogs
142+ let sortedBlogs = sortBy (\b1 b2 -> tstamp b1 `compare` tstamp b2) blogs
140143 html . renderHtml $ do
141144 h1 "Blog Posts"
142145 forM_ sortedBlogs $ \blog -> a ! href (toValue $ "/blog/" <> title blog) $ h2 (toHtml (title blog))
@@ -182,7 +185,7 @@ showBlogEntry sessionId conn = do
182185 render $ do
183186 --show blog details
184187 h1 (toHtml (title blog))
185− p (toHtml ("Posted at " <> formatStamp (stamp blog) <> " under " <> show (category blog)))
188+ p (toHtml ("Posted at " <> formatStamp (tstamp blog) <> " under " <> show (category blog)))
186189 p (toHtml (entry blog))
187190 hr
188191 h3 "Comments"
examples/hair.hs+9−6
@@ -1,16 +1,17 @@
1−{-# LANGUAGE DeriveGeneric, DeriveAnyClass, OverloadedStrings #-}
1+{-# LANGUAGE DeriveGeneric, DeriveAnyClass, OverloadedStrings, DerivingVia #-}
22import ProjectM36.Client
33import ProjectM36.Relation.Show.Term
44import GHC.Generics
55import Data.Text
6−import Data.Binary
76import Control.DeepSeq
87import qualified Data.Map as M
98import qualified Data.Text.IO as TIO
109import Data.Proxy
10+import Codec.Winery
1111
1212data Hair = Bald | Brown | Blond | OtherColor Text
13− deriving (Generic, Show, Eq, Binary, NFData, Atomable)
13+ deriving (Generic, Show, Eq, NFData, Atomable)
14+ deriving Serialise via WineryVariant Hair
1415
1516main :: IO ()
1617main = do
@@ -31,11 +32,13 @@ main = do
3132
3233 --create a relation with the new Hair AtomType
3334 let blond = NakedAtomExpr (toAtom Blond)
34− eCheck $ executeDatabaseContextExpr sessionId conn (Assign "people" (MakeRelationFromExprs Nothing [
35− TupleExpr (M.fromList [("hair", blond), ("name", NakedAtomExpr (TextAtom "Colin"))])]))
35+ eCheck $ executeDatabaseContextExpr sessionId conn
36+ (Assign "people"
37+ (MakeRelationFromExprs Nothing $ TupleExprs () [
38+ TupleExpr (M.fromList [("hair", blond), ("name", NakedAtomExpr (TextAtom "Colin"))])]))
3639
3740 let restrictionPredicate = AttributeEqualityPredicate "hair" blond
3841 peopleRel <- eCheck $ executeRelationalExpr sessionId conn (Restrict restrictionPredicate (RelationVariable "people" ()))
3942
4043 TIO.putStrLn (showRelation peopleRel)
41−
44+
examples/out_of_the_tarpit.hs+11−7
@@ -1,5 +1,5 @@
11-- the Out-of-the-Tarpit example in Haskell and Project:M36
2−{-# LANGUAGE DeriveAnyClass, DeriveGeneric, OverloadedStrings #-}
2+{-# LANGUAGE DeriveAnyClass, DeriveGeneric, OverloadedStrings, DerivingVia #-}
33import ProjectM36.Client
44import ProjectM36.DataTypes.Primitive
55import ProjectM36.Tupleable
@@ -7,11 +7,11 @@ import ProjectM36.Relation
77import ProjectM36.Error
88import Data.Either
99import GHC.Generics
10−import Data.Binary
1110import Control.DeepSeq
1211import qualified Data.Text as T
1312import Data.Time.Calendar
1413import Data.Proxy
14+import Codec.Winery
1515
1616--create various database value (atom) types
1717type Price = Double
@@ -21,16 +21,20 @@ type Name = T.Text
2121type Address = T.Text
2222
2323data RoomType = Kitchen | Bathroom | LivingRoom
24− deriving (Generic, Atomable, Eq, Show, Binary, NFData)
24+ deriving (Generic, Atomable, Eq, Show, NFData)
25+ deriving Serialise via WineryVariant RoomType
2526
2627data PriceBand = Low | Medium | High | Premium
27− deriving (Generic, Atomable, Eq, Show, Binary, NFData)
28+ deriving (Generic, Atomable, Eq, Show, NFData)
29+ deriving Serialise via WineryVariant PriceBand
2830
2931data AreaCode = City | Suburban | Rural
30− deriving (Generic, Atomable, Eq, Show, Binary, NFData)
32+ deriving (Generic, Atomable, Eq, Show, NFData)
33+ deriving Serialise via WineryVariant AreaCode
3134
3235data SpeedBand = VeryFastBand | FastBand | MediumBand | SlowBand
33− deriving (Generic, Atomable, Eq, Show, Binary, NFData)
36+ deriving (Generic, Atomable, Eq, Show, NFData)
37+ deriving Serialise via WineryVariant SpeedBand
3438
3539main :: IO ()
3640main = do
@@ -257,4 +261,4 @@ handleIOErrors m = do
257261 [] -> pure (rights eErrs)
258262 errs -> handleError (Left (someErrors errs))
259263
260−
264+
examples/out_of_the_tarpit.tutd+4−4
@@ -3,9 +3,9 @@
33data Address = Address Text
44data Agent = Agent Text
55data Name = Name Text
6−data Price = Price Double
6+data Price = Price Integer --dollars
77data RoomType = Kitchen | Bathroom | LivingRoom
8−data PriceBand = Low | Medium | High | Premium
8+data PriceBand = Low | Med | High | Premium
99data AreaCode = City | Suburban | Rural
1010data SpeedBand = VeryFast | Fast | Medium | Slow
1111
@@ -57,9 +57,9 @@ constraint noOffersAfterSale (offer join decision where ^dayEarlierThan(@offerDa
5757--1. identify offerPrices > 2000 (arbitrarily-chosen high price band which is not specified in the paper)
5858--2. remove the properties which have been sold
5959--3. group and count sub-relation and restrict by greater than 50
60−constraint noMoreThan50PremiumProperties ((((property where ^gt(offerPrice,2000.0)) minus ((property join decision){address,agent,dateRegistered,photo,price})) group ({} as x) : {z:=gt(count(@x),50)}) {z}){} equals false
60+constraint noMoreThan50PremiumProperties ((((property where ^gt(@price,Price 2000)) minus ((property join decision){address,agent,dateRegistered,photo,price})) group ({} as x) : {z:=gt(count(@x),50)}) {z}){} equals false
6161
62−constraint noBidderCanMakeMoreThan10BidsOnAProperty (((offer group ({all but bidderAddress} as bidder)) : {bidCount:=gt(count(@bidder),10)}) where ^gt(bidCount,10)) {} equals false
62+constraint noBidderCanMakeMoreThan10BidsOnAProperty (((offer group ({all but bidderAddress} as bidder)) : {bidCount:=gt(count(@bidder),10)}) where ^gt(@bidCount,10)) {} equals false
6363
6464-- sample data
6565
jupyter/TutorialD Notebook Walkthrough.ipynb+1−1
@@ -38,7 +38,7 @@
3838 }
3939 ],
4040 "source": [
41− ":importexample date"
41+ ":importexample cjdate"
4242 ]
4343 },
4444 {
nix/sources.jsonnew file+50
@@ -0,0 +1,50 @@
1+{
2+ "curryer": {
3+ "branch": "master",
4+ "description": "Fast Haskell RPC",
5+ "homepage": null,
6+ "owner": "agentm",
7+ "repo": "curryer",
8+ "rev": "74ecaac619ad1165a4517d5c0f4e530493bda130",
9+ "sha256": "1izdvzj00k0y76ixm7dfgvq2fzphb8h4nzqgwkl3p0bg0806rsn1",
10+ "type": "tarball",
11+ "url": "https://github.com/agentm/curryer/archive/74ecaac619ad1165a4517d5c0f4e530493bda130.tar.gz",
12+ "url_template": "https://github.com/<owner>/<repo>/archive/<rev>.tar.gz"
13+ },
14+ "niv": {
15+ "branch": "master",
16+ "description": "Easy dependency management for Nix projects",
17+ "homepage": "https://github.com/nmattia/niv",
18+ "owner": "nmattia",
19+ "repo": "niv",
20+ "rev": "1819632b5823e0527da28ad82fecd6be5136c1e9",
21+ "sha256": "08jz17756qchq0zrqmapcm33nr4ms9f630mycc06i6zkfwl5yh5i",
22+ "type": "tarball",
23+ "url": "https://github.com/nmattia/niv/archive/1819632b5823e0527da28ad82fecd6be5136c1e9.tar.gz",
24+ "url_template": "https://github.com/<owner>/<repo>/archive/<rev>.tar.gz"
25+ },
26+ "nixpkgs": {
27+ "branch": "master",
28+ "description": "Nix Packages collection",
29+ "homepage": "",
30+ "owner": "NixOS",
31+ "repo": "nixpkgs",
32+ "rev": "429c23aad0fce9ef38b0e60d55d7459c19d53ddc",
33+ "sha256": "1nj8sh1fnxp07jdlvjkijwfd1pnsi2zj0ivy7a0dhx02g63byhg3",
34+ "type": "tarball",
35+ "url": "https://github.com/NixOS/nixpkgs/archive/429c23aad0fce9ef38b0e60d55d7459c19d53ddc.tar.gz",
36+ "url_template": "https://github.com/<owner>/<repo>/archive/<rev>.tar.gz"
37+ },
38+ "streamly": {
39+ "branch": "ac3af8749194f1788704dda8667d0b3807075cc2",
40+ "description": "Beautiful Streaming, Concurrent and Reactive Composition (Haskell)",
41+ "homepage": "https://hackage.haskell.org/package/streamly",
42+ "owner": "composewell",
43+ "repo": "streamly",
44+ "rev": "ac3af8749194f1788704dda8667d0b3807075cc2",
45+ "sha256": "04d8fk654vawdfs0dfidmq2awwgwi8x44iv8r7vqz70zkcsd5fij",
46+ "type": "tarball",
47+ "url": "https://github.com/composewell/streamly/archive/ac3af8749194f1788704dda8667d0b3807075cc2.tar.gz",
48+ "url_template": "https://github.com/<owner>/<repo>/archive/<rev>.tar.gz"
49+ }
50+}
nix/sources.nixnew file+171
@@ -0,0 +1,171 @@
1+# This file has been generated by Niv.
2+
3+let
4+
5+ #
6+ # The fetchers. fetch_<type> fetches specs of type <type>.
7+ #
8+
9+ fetch_file = pkgs: name: spec:
10+ let
11+ name' = sanitizeName name + "-src";
12+ in
13+ if spec.builtin or true then
14+ builtins_fetchurl { inherit (spec) url sha256; name = name'; }
15+ else
16+ pkgs.fetchurl { inherit (spec) url sha256; name = name'; };
17+
18+ fetch_tarball = pkgs: name: spec:
19+ let
20+ name' = sanitizeName name + "-src";
21+ in
22+ if spec.builtin or true then
23+ builtins_fetchTarball { name = name'; inherit (spec) url sha256; }
24+ else
25+ pkgs.fetchzip { name = name'; inherit (spec) url sha256; };
26+
27+ fetch_git = name: spec:
28+ let
29+ ref =
30+ if spec ? ref then spec.ref else
31+ if spec ? branch then "refs/heads/${spec.branch}" else
32+ if spec ? tag then "refs/tags/${spec.tag}" else
33+ abort "In git source '${name}': Please specify `ref`, `tag` or `branch`!";
34+ in
35+ builtins.fetchGit { url = spec.repo; inherit (spec) rev; inherit ref; };
36+
37+ fetch_local = spec: spec.path;
38+
39+ fetch_builtin-tarball = name: throw
40+ ''[${name}] The niv type "builtin-tarball" is deprecated. You should instead use `builtin = true`.
41+ $ niv modify ${name} -a type=tarball -a builtin=true'';
42+
43+ fetch_builtin-url = name: throw
44+ ''[${name}] The niv type "builtin-url" will soon be deprecated. You should instead use `builtin = true`.
45+ $ niv modify ${name} -a type=file -a builtin=true'';
46+
47+ #
48+ # Various helpers
49+ #
50+
51+ # https://github.com/NixOS/nixpkgs/pull/83241/files#diff-c6f540a4f3bfa4b0e8b6bafd4cd54e8bR695
52+ sanitizeName = name:
53+ (
54+ concatMapStrings (s: if builtins.isList s then "-" else s)
55+ (
56+ builtins.split "[^[:alnum:]+._?=-]+"
57+ ((x: builtins.elemAt (builtins.match "\\.*(.*)" x) 0) name)
58+ )
59+ );
60+
61+ # The set of packages used when specs are fetched using non-builtins.
62+ mkPkgs = sources: system:
63+ let
64+ sourcesNixpkgs =
65+ import (builtins_fetchTarball { inherit (sources.nixpkgs) url sha256; }) { inherit system; };
66+ hasNixpkgsPath = builtins.any (x: x.prefix == "nixpkgs") builtins.nixPath;
67+ hasThisAsNixpkgsPath = <nixpkgs> == ./.;
68+ in
69+ if builtins.hasAttr "nixpkgs" sources
70+ then sourcesNixpkgs
71+ else if hasNixpkgsPath && ! hasThisAsNixpkgsPath then
72+ import <nixpkgs> {}
73+ else
74+ abort
75+ ''
76+ Please specify either <nixpkgs> (through -I or NIX_PATH=nixpkgs=...) or
77+ add a package called "nixpkgs" to your sources.json.
78+ '';
79+
80+ # The actual fetching function.
81+ fetch = pkgs: name: spec:
82+
83+ if ! builtins.hasAttr "type" spec then
84+ abort "ERROR: niv spec ${name} does not have a 'type' attribute"
85+ else if spec.type == "file" then fetch_file pkgs name spec
86+ else if spec.type == "tarball" then fetch_tarball pkgs name spec
87+ else if spec.type == "git" then fetch_git name spec
88+ else if spec.type == "local" then fetch_local spec
89+ else if spec.type == "builtin-tarball" then fetch_builtin-tarball name
90+ else if spec.type == "builtin-url" then fetch_builtin-url name
91+ else
92+ abort "ERROR: niv spec ${name} has unknown type ${builtins.toJSON spec.type}";
93+
94+ # If the environment variable NIV_OVERRIDE_${name} is set, then use
95+ # the path directly as opposed to the fetched source.
96+ replace = name: drv:
97+ let
98+ saneName = stringAsChars (c: if isNull (builtins.match "[a-zA-Z0-9]" c) then "_" else c) name;
99+ ersatz = builtins.getEnv "NIV_OVERRIDE_${saneName}";
100+ in
101+ if ersatz == "" then drv else ersatz;
102+
103+ # Ports of functions for older nix versions
104+
105+ # a Nix version of mapAttrs if the built-in doesn't exist
106+ mapAttrs = builtins.mapAttrs or (
107+ f: set: with builtins;
108+ listToAttrs (map (attr: { name = attr; value = f attr set.${attr}; }) (attrNames set))
109+ );
110+
111+ # https://github.com/NixOS/nixpkgs/blob/0258808f5744ca980b9a1f24fe0b1e6f0fecee9c/lib/lists.nix#L295
112+ range = first: last: if first > last then [] else builtins.genList (n: first + n) (last - first + 1);
113+
114+ # https://github.com/NixOS/nixpkgs/blob/0258808f5744ca980b9a1f24fe0b1e6f0fecee9c/lib/strings.nix#L257
115+ stringToCharacters = s: map (p: builtins.substring p 1 s) (range 0 (builtins.stringLength s - 1));
116+
117+ # https://github.com/NixOS/nixpkgs/blob/0258808f5744ca980b9a1f24fe0b1e6f0fecee9c/lib/strings.nix#L269
118+ stringAsChars = f: s: concatStrings (map f (stringToCharacters s));
119+ concatMapStrings = f: list: concatStrings (map f list);
120+ concatStrings = builtins.concatStringsSep "";
121+
122+ # https://github.com/NixOS/nixpkgs/blob/8a9f58a375c401b96da862d969f66429def1d118/lib/attrsets.nix#L331
123+ optionalAttrs = cond: as: if cond then as else {};
124+
125+ # fetchTarball version that is compatible between all the versions of Nix
126+ builtins_fetchTarball = { url, name ? null, sha256 }@attrs:
127+ let
128+ inherit (builtins) lessThan nixVersion fetchTarball;
129+ in
130+ if lessThan nixVersion "1.12" then
131+ fetchTarball ({ inherit url; } // (optionalAttrs (!isNull name) { inherit name; }))
132+ else
133+ fetchTarball attrs;
134+
135+ # fetchurl version that is compatible between all the versions of Nix
136+ builtins_fetchurl = { url, name ? null, sha256 }@attrs:
137+ let
138+ inherit (builtins) lessThan nixVersion fetchurl;
139+ in
140+ if lessThan nixVersion "1.12" then
141+ fetchurl ({ inherit url; } // (optionalAttrs (!isNull name) { inherit name; }))
142+ else
143+ fetchurl attrs;
144+
145+ # Create the final "sources" from the config
146+ mkSources = config:
147+ mapAttrs (
148+ name: spec:
149+ if builtins.hasAttr "outPath" spec
150+ then abort
151+ "The values in sources.json should not have an 'outPath' attribute"
152+ else
153+ spec // { outPath = replace name (fetch config.pkgs name spec); }
154+ ) config.sources;
155+
156+ # The "config" used by the fetchers
157+ mkConfig =
158+ { sourcesFile ? if builtins.pathExists ./sources.json then ./sources.json else null
159+ , sources ? if isNull sourcesFile then {} else builtins.fromJSON (builtins.readFile sourcesFile)
160+ , system ? builtins.currentSystem
161+ , pkgs ? mkPkgs sources system
162+ }: rec {
163+ # The sources, i.e. the attribute set of spec name to spec
164+ inherit sources;
165+
166+ # The "pkgs" (evaluated nixpkgs) to use for e.g. non-builtin fetchers
167+ inherit pkgs;
168+ };
169+
170+in
171+mkSources (mkConfig {}) // { __functor = _: settings: mkSources (mkConfig settings); }
project-m36.cabal+160−162
@@ -1,6 +1,8 @@
1+Cabal-Version: 2.2
12Name: project-m36
2−Version: 0.6
3−License: PublicDomain
3+Version: 0.9.3
4+License: MIT
5+--note that this license specification is erroneous and only labeled MIT to appease hackage which does not recognize public domain packages in cabal >2.2- Project:M36 is dedicated to the public domain
46Build-Type: Simple
57Homepage: https://github.com/agentm/project-m36
68Bug-Reports: https://github.com/agentm/project-m36/issues
@@ -8,7 +10,6 @@ Author: AgentM
810Stability: experimental
911Category: Relational Algebra
1012Maintainer: agentm@themactionfaction.com
11−Cabal-Version: >= 1.10
1213Synopsis: Relational Algebra Engine
1314Description: A relational algebra engine which can be used to persist and query Haskell data types.
1415Extra-Source-Files: Changelog.markdown README.markdown
@@ -28,8 +29,21 @@ Flag stack
2829 Manual: True
2930 Default: False
3031
32+Flag haskell-scripting
33+ Description: enables Haskell scripting which links against GHC as a library
34+ Manual: True
35+ Default: True
36+
3137Library
32− Build-Depends: base>=4.8 && < 4.12, ghc >= 7.8 && < 8.5, ghc-paths, mtl, containers, unordered-containers, hashable, haskeline, directory, MonadRandom, random-shuffle, uuid >= 1.3.12, cassava >= 0.4.5.1 && < 0.6, text, bytestring, deepseq, deepseq-generics, vector, parallel, monad-parallel, exceptions, transformers, gnuplot, binary, filepath, zlib, directory, vector-binary-instances, temporary, stm, time, hashable-time, old-locale, rset, attoparsec, either, base64-bytestring, data-interval, extended-reals, network-transport, aeson >= 1.1, path-pieces, conduit, resourcet, http-api-data, semigroups, QuickCheck, quickcheck-instances, distributed-process-client-server >= 0.2.3, distributed-process >= 0.7.4, distributed-process-extras >= 0.3.2, distributed-process-async >= 0.2.4.1, network-transport-tcp >= 0.6.0, network-transport, list-t, stm-containers >= 0.2.15, foldl, optparse-applicative, Glob, cryptohash-sha256
38+ Build-Depends: base>=4.8 && < 4.15, ghc-paths, mtl, containers, unordered-containers, hashable, haskeline, directory, MonadRandom, random-shuffle, uuid >= 1.3.12, cassava >= 0.4.5.1 && < 0.6, text, bytestring, deepseq, deepseq-generics, vector, parallel, monad-parallel, exceptions, transformers, gnuplot, filepath, zlib, directory, temporary, stm, time, hashable-time, old-locale, rset, attoparsec, either, base64-bytestring, data-interval, extended-reals, aeson >= 1.1, path-pieces, conduit, resourcet, http-api-data, semigroups, QuickCheck, quickcheck-instances, list-t, stm-containers >= 0.2.15, foldl, optparse-applicative, Glob, cryptohash-sha256, text-manipulate >= 0.2.0.1 && < 0.4, winery, curryer-rpc, network, async, vector-instances, recursion-schemes, streamly >= 0.7.2, convertible
39+ if flag(haskell-scripting)
40+ Build-Depends: ghc >= 8.2 && < 8.11
41+ CPP-Options: -DPM36_HASKELL_SCRIPTING
42+ if impl(ghc>= 8) && flag(haskell-scripting)
43+ build-depends:
44+ ghc-boot, ghci
45+ if impl(ghc>= 8.6)
46+ Build-Depends: deferred-folds
3347 Exposed-Modules: ProjectM36.Error,
3448 ProjectM36.Transaction,
3549 ProjectM36.TransactionGraph,
@@ -38,6 +52,8 @@ Library
3852 ProjectM36.TransactionGraph.Merge,
3953 ProjectM36.TransGraphRelationalExpression,
4054 ProjectM36.Base,
55+ ProjectM36.Serialise.Base,
56+ ProjectM36.Serialise.Error,
4157 ProjectM36.DataFrame,
4258 ProjectM36.Attribute,
4359 ProjectM36.AttributeNames,
@@ -47,6 +63,7 @@ Library
4763 ProjectM36.AtomFunction,
4864 ProjectM36.AtomFunctionError,
4965 ProjectM36.ScriptSession,
66+ ProjectM36.Shortcuts,
5067 ProjectM36.DatabaseContextFunction,
5168 ProjectM36.DatabaseContextFunctionError,
5269 ProjectM36.DatabaseContextFunctionUtils,
@@ -66,6 +83,7 @@ Library
6683 ProjectM36.Relation.Parse.CSV,
6784 ProjectM36.IsomorphicSchema,
6885 ProjectM36.InclusionDependency,
86+ ProjectM36.MerkleHash,
6987 ProjectM36.Client,
7088 ProjectM36.Client.Simple,
7189 ProjectM36.Persist,
@@ -75,6 +93,7 @@ Library
7593 ProjectM36.AtomFunctions.Primitive,
7694 ProjectM36.Atomable,
7795 ProjectM36.Tupleable,
96+ ProjectM36.Tupleable.Deriving,
7897 ProjectM36.DataConstructorDef,
7998 ProjectM36.DataTypes.Basic,
8099 ProjectM36.DataTypes.Sorting,
@@ -95,6 +114,10 @@ Library
95114 ProjectM36.Server.EntryPoints,
96115 ProjectM36.Server.ParseArgs,
97116 ProjectM36.Server.RemoteCallTypes,
117+ ProjectM36.Serialise.AtomFunctionError,
118+ ProjectM36.Serialise.DataFrame,
119+ ProjectM36.Serialise.DatabaseContextFunctionError,
120+ ProjectM36.Serialise.IsomorphicSchema,
98121 ProjectM36.Session,
99122 ProjectM36.Sessions,
100123 ProjectM36.Transaction.Persist,
@@ -102,29 +125,31 @@ Library
102125 ProjectM36.TypeConstructorDef,
103126 ProjectM36.FileLock,
104127 ProjectM36.FSType,
105− ProjectM36.Arbitrary
128+ ProjectM36.Arbitrary,
129+ ProjectM36.GraphRefRelationalExpr,
130+ ProjectM36.NormalizeExpr,
131+ ProjectM36.TransactionInfo,
132+ ProjectM36.WithNameExpr
106133 GHC-Options: -Wall -rdynamic
107134 if os(windows)
108135 Build-Depends: Win32 >= 2.5.4.1
109136 Other-Modules: ProjectM36.Win32Handle
110137 else
111138 --219- too many exported symbols under Windows and GHC 8.4
112− GHC-Options: -rdynamic
139+ GHC-Options: -rdynamic -fexternal-interpreter
113140 C-sources: cbits/DirectoryFsync.c, cbits/darwin_statfs.c
114141 Build-Depends: unix
115− CC-Options: -fPIC
142+ CC-Options: -fPIC
116143 Hs-Source-Dirs: ./src/lib
117144 Default-Language: Haskell2010
118145 Default-Extensions: OverloadedStrings, CPP
119− if impl(ghc>= 8)
120− build-depends:
121− ghc-boot, ghci
122− if !flag(stack)
146+ if !flag(stack)
123147 Build-Depends: deferred-folds
124148
125149Executable tutd
150+ if flag(haskell-scripting)
151+ Build-Depends: ghc >= 8.2 && < 8.11
126152 Build-Depends: base >=4.8 && <5.0,
127− ghc >= 7.8 && < 8.5,
128153 ghc-paths,
129154 project-m36,
130155 containers,
@@ -138,13 +163,11 @@ Executable tutd
138163 MonadRandom, MonadRandom,
139164 vector,
140165 text,
141− vector-binary-instances,
142166 time,
143167 hashable-time,
144168 bytestring,
145169 stm,
146170 deepseq,
147− binary,
148171 data-interval,
149172 parallel,
150173 cassava,
@@ -152,14 +175,23 @@ Executable tutd
152175 directory,
153176 filepath,
154177 temporary,
155− megaparsec >= 5.2.0 && < 7,
178+ megaparsec >= 5.2.0 && < 10,
156179 haskeline,
157180 random, MonadRandom,
158181 base64-bytestring,
159182 optparse-applicative,
160183 attoparsec,
161184 stm-containers >= 1.0.0,
162− list-t
185+ list-t,
186+ parser-combinators,
187+ curryer-rpc,
188+ prettyprinter,
189+ cryptohash-sha256,
190+ --due to decode signature change
191+ base16-bytestring >= 1.0.0.0,
192+ http-conduit,
193+ modern-uri,
194+ http-types
163195 Other-Modules: TutorialD.Interpreter,
164196 TutorialD.Interpreter.Base,
165197 TutorialD.Interpreter.DatabaseContextExpr,
@@ -178,6 +210,7 @@ Executable tutd
178210 TutorialD.Interpreter.SchemaOperator,
179211 TutorialD.Interpreter.TransGraphRelationalOperator,
180212 TutorialD.Interpreter.SchemaOperator
213+ TutorialD.Printer
181214 main-is: TutorialD/tutd.hs
182215 CC-Options: -fPIC
183216 GHC-Options: -Wall -threaded
@@ -186,12 +219,12 @@ Executable tutd
186219 Default-Extensions: OverloadedStrings
187220
188221Executable project-m36-server
222+ if flag(haskell-scripting)
223+ Build-Depends: ghc >= 8.2 && < 8.11
189224 Build-Depends: base,
190− ghc >= 7.8 && < 8.5,
191225 ghc-paths,
192− project-m36,
193− binary,
194226 transformers,
227+ project-m36,
195228 temporary,
196229 data-interval,
197230 deepseq,
@@ -204,7 +237,6 @@ Executable project-m36-server
204237 optparse-applicative,
205238 hashable-time,
206239 time,
207− vector-binary-instances,
208240 text,
209241 deepseq-generics,
210242 mtl,
@@ -217,7 +249,7 @@ Executable project-m36-server
217249 list-t,
218250 base64-bytestring
219251 Main-Is: ./src/bin/ProjectM36/Server/project-m36-server.hs
220− GHC-Options: -Wall -threaded -rtsopts
252+ GHC-Options: -Wall -threaded -rtsopts
221253 if flag(profiler)
222254 GHC-Prof-Options: -fprof-auto -rtsopts -threaded -Wall
223255 Default-Language: Haskell2010
@@ -226,7 +258,7 @@ Executable project-m36-server
226258Executable bigrel
227259 Default-Language: Haskell2010
228260 Default-Extensions: OverloadedStrings
229− Build-Depends: base, HUnit, Cabal, containers, hashable, unordered-containers, mtl, vector, vector-binary-instances, time, hashable-time, bytestring, uuid, stm, deepseq, deepseq-generics, binary, parallel, cassava, attoparsec, gnuplot, directory, temporary, haskeline, megaparsec, text, base64-bytestring, data-interval, filepath, optparse-applicative, stm-containers, list-t, ghc, ghc-paths, transformers, project-m36, random, MonadRandom, semigroups
261+ Build-Depends: base, HUnit, Cabal, containers, hashable, unordered-containers, mtl, vector, time, hashable-time, bytestring, uuid, stm, deepseq, deepseq-generics, parallel, cassava, attoparsec, gnuplot, directory, temporary, haskeline, megaparsec, text, base64-bytestring, data-interval, filepath, optparse-applicative, stm-containers, list-t, ghc, ghc-paths, transformers, project-m36, random, MonadRandom, semigroups, parser-combinators
230262 Other-Modules: TutorialD.Interpreter.Base,
231263 TutorialD.Interpreter.DatabaseContextExpr,
232264 TutorialD.Interpreter.RelationalExpr,
@@ -237,6 +269,13 @@ Executable bigrel
237269 if flag(profiler)
238270 GHC-Prof-Options: -fprof-auto -rtsopts -threaded -Wall
239271
272+Common commontest
273+ Default-Language: Haskell2010
274+ Build-Depends: base, HUnit, Cabal, containers, hashable, unordered-containers, mtl, vector, time, hashable-time, bytestring, uuid, stm, deepseq, deepseq-generics,parallel, cassava, attoparsec, gnuplot, directory, temporary, haskeline, megaparsec, text, base64-bytestring, data-interval, filepath, transformers, stm-containers, list-t, websockets, optparse-applicative, network, aeson, project-m36, random, MonadRandom, semigroups, parser-combinators, winery, curryer-rpc, prettyprinter, base64-bytestring, modern-uri, http-types, http-conduit, base16-bytestring,cryptohash-sha256
275+ Default-Extensions: OverloadedStrings
276+ GHC-Options: -Wall -threaded
277+ Hs-Source-Dirs: test, src/bin
278+
240279Benchmark basic-benchmark
241280 Default-Language: Haskell2010
242281 Default-Extensions: OverloadedStrings
@@ -248,240 +287,202 @@ Benchmark basic-benchmark
248287 if flag(profiler)
249288 GHC-Prof-Options: -fprof-auto -rtsopts -threaded -Wall
250289
290+--benchmark inserts, updates, deletes for a basic use-case to shake out any space leaks
291+Benchmark update-exprs
292+ Default-Language: Haskell2010
293+ Default-Extensions: OverloadedStrings
294+ Build-Depends: base, criterion, project-m36, text, winery
295+ Main-Is: benchmark/Server.hs
296+ Type: exitcode-stdio-1.0
297+ GHC-Options: -Wall -threaded -rtsopts
298+ HS-Source-Dirs: ./src/bin
299+ if flag(profiler)
300+ GHC-Prof-Options: -fprof-auto -rtsopts -threaded -Wall -fexternal-interpreter
301+
251302Test-Suite test-tutoriald
252− Default-Language: Haskell2010
253− Default-Extensions: OverloadedStrings
303+ import: commontest
254304 type: exitcode-stdio-1.0
255− main-is: test/TutorialD/Interpreter.hs
256− Build-Depends: base, HUnit, Cabal, containers, hashable, unordered-containers, mtl, vector, vector-binary-instances, time, hashable-time, bytestring, uuid, stm, deepseq, deepseq-generics, binary, parallel, cassava, attoparsec, gnuplot, directory, temporary, haskeline, megaparsec, text, base64-bytestring, data-interval, filepath, stm-containers, list-t, project-m36, random, MonadRandom, semigroups
257− Other-Modules: TutorialD.Interpreter, TutorialD.Interpreter.Base, TutorialD.Interpreter.Export.Base, TutorialD.Interpreter.Export.CSV, TutorialD.Interpreter.Import.Base, TutorialD.Interpreter.Import.CSV, TutorialD.Interpreter.Import.TutorialD, TutorialD.Interpreter.RODatabaseContextOperator, TutorialD.Interpreter.RelationalExpr, TutorialD.Interpreter.TransactionGraphOperator, TutorialD.Interpreter.Types, TutorialD.Interpreter.DatabaseContextExpr, TutorialD.Interpreter.InformationOperator, TutorialD.Interpreter.Import.BasicExamples, TutorialD.Interpreter.DatabaseContextIOOperator, TutorialD.Interpreter.TestBase, TutorialD.Interpreter.TransGraphRelationalOperator, TutorialD.Interpreter.SchemaOperator
258− GHC-Options: -Wall -threaded
259− Hs-Source-Dirs: ./src/bin, ., test
305+ main-is: TutorialD/InterpreterTest.hs
306+ Other-Modules: TutorialD.Interpreter, TutorialD.Interpreter.Base, TutorialD.Interpreter.Export.Base, TutorialD.Interpreter.Export.CSV, TutorialD.Interpreter.Import.Base, TutorialD.Interpreter.Import.CSV, TutorialD.Interpreter.Import.TutorialD, TutorialD.Interpreter.RODatabaseContextOperator, TutorialD.Interpreter.RelationalExpr, TutorialD.Interpreter.TransactionGraphOperator, TutorialD.Interpreter.Types, TutorialD.Interpreter.DatabaseContextExpr, TutorialD.Interpreter.InformationOperator, TutorialD.Interpreter.Import.BasicExamples, TutorialD.Interpreter.DatabaseContextIOOperator, TutorialD.Interpreter.TestBase, TutorialD.Interpreter.TransGraphRelationalOperator, TutorialD.Interpreter.SchemaOperator, TutorialD.Printer
307+ Build-Depends: base, HUnit, Cabal, containers, hashable, unordered-containers, mtl, vector, time, hashable-time, bytestring, uuid, stm, deepseq, deepseq-generics, parallel, cassava, attoparsec, gnuplot, directory, temporary, haskeline, megaparsec, text, base64-bytestring, data-interval, filepath, stm-containers, list-t, project-m36, random, MonadRandom, semigroups, parser-combinators, prettyprinter
260308
261309Test-Suite test-tutoriald-atomfunctionscript
262− Default-Language: Haskell2010
263− Default-Extensions: OverloadedStrings
310+ import: commontest
264311 type: exitcode-stdio-1.0
265− Other-Modules: TutorialD.Interpreter, TutorialD.Interpreter.Base, TutorialD.Interpreter.DatabaseContextExpr, TutorialD.Interpreter.DatabaseContextIOOperator, TutorialD.Interpreter.Export.Base, TutorialD.Interpreter.Export.CSV, TutorialD.Interpreter.Import.Base, TutorialD.Interpreter.Import.BasicExamples, TutorialD.Interpreter.Import.CSV, TutorialD.Interpreter.Import.TutorialD, TutorialD.Interpreter.InformationOperator, TutorialD.Interpreter.RODatabaseContextOperator, TutorialD.Interpreter.RelationalExpr, TutorialD.Interpreter.TestBase, TutorialD.Interpreter.TransGraphRelationalOperator, TutorialD.Interpreter.TransactionGraphOperator, TutorialD.Interpreter.Types, TutorialD.Interpreter.SchemaOperator
266− main-is: test/TutorialD/Interpreter/AtomFunctionScript.hs
267− Build-Depends: base, HUnit, project-m36, uuid, containers, megaparsec, text, vector, directory, bytestring, mtl, haskeline, random, MonadRandom, semigroups, time
268− GHC-Options: -Wall -threaded
269− Hs-Source-Dirs: ./src/bin, ./test, .
312+ Other-Modules: TutorialD.Interpreter, TutorialD.Interpreter.Base, TutorialD.Interpreter.DatabaseContextExpr, TutorialD.Interpreter.DatabaseContextIOOperator, TutorialD.Interpreter.Export.Base, TutorialD.Interpreter.Export.CSV, TutorialD.Interpreter.Import.Base, TutorialD.Interpreter.Import.BasicExamples, TutorialD.Interpreter.Import.CSV, TutorialD.Interpreter.Import.TutorialD, TutorialD.Interpreter.InformationOperator, TutorialD.Interpreter.RODatabaseContextOperator, TutorialD.Interpreter.RelationalExpr, TutorialD.Interpreter.TestBase, TutorialD.Interpreter.TransGraphRelationalOperator, TutorialD.Interpreter.TransactionGraphOperator, TutorialD.Interpreter.Types, TutorialD.Interpreter.SchemaOperator, TutorialD.Printer
313+ main-is: TutorialD/Interpreter/AtomFunctionScript.hs
270314
271315Test-Suite test-tutoriald-databasecontextfunctionscript
272− Default-Language: Haskell2010
273− Default-Extensions: OverloadedStrings
316+ import: commontest
274317 type: exitcode-stdio-1.0
275− Other-Modules: TutorialD.Interpreter, TutorialD.Interpreter.Base, TutorialD.Interpreter.DatabaseContextExpr, TutorialD.Interpreter.DatabaseContextIOOperator, TutorialD.Interpreter.Export.Base, TutorialD.Interpreter.Export.CSV, TutorialD.Interpreter.Import.Base, TutorialD.Interpreter.Import.BasicExamples, TutorialD.Interpreter.Import.CSV, TutorialD.Interpreter.Import.TutorialD, TutorialD.Interpreter.InformationOperator, TutorialD.Interpreter.RODatabaseContextOperator, TutorialD.Interpreter.RelationalExpr, TutorialD.Interpreter.TestBase, TutorialD.Interpreter.TransGraphRelationalOperator, TutorialD.Interpreter.TransactionGraphOperator, TutorialD.Interpreter.Types, TutorialD.Interpreter.SchemaOperator
276− main-is: test/TutorialD/Interpreter/DatabaseContextFunctionScript.hs
277− Build-Depends: base, HUnit, project-m36, uuid, containers, megaparsec, text, vector, directory, bytestring, mtl, haskeline, random, MonadRandom, semigroups, time
278− GHC-Options: -Wall -threaded
279− Hs-Source-Dirs: ./src/bin, ./test, .
318+ Other-Modules: TutorialD.Interpreter, TutorialD.Interpreter.Base, TutorialD.Interpreter.DatabaseContextExpr, TutorialD.Interpreter.DatabaseContextIOOperator, TutorialD.Interpreter.Export.Base, TutorialD.Interpreter.Export.CSV, TutorialD.Interpreter.Import.Base, TutorialD.Interpreter.Import.BasicExamples, TutorialD.Interpreter.Import.CSV, TutorialD.Interpreter.Import.TutorialD, TutorialD.Interpreter.InformationOperator, TutorialD.Interpreter.RODatabaseContextOperator, TutorialD.Interpreter.RelationalExpr, TutorialD.Interpreter.TestBase, TutorialD.Interpreter.TransGraphRelationalOperator, TutorialD.Interpreter.TransactionGraphOperator, TutorialD.Interpreter.Types, TutorialD.Interpreter.SchemaOperator, TutorialD.Printer
319+ main-is: TutorialD/Interpreter/DatabaseContextFunctionScript.hs
280320
281321Test-Suite test-relation
282− Default-Language: Haskell2010
283− Default-Extensions: OverloadedStrings
322+ import: commontest
284323 type: exitcode-stdio-1.0
285− main-is: test/Relation/Basic.hs
286− Build-Depends: base, HUnit, Cabal, containers, hashable, unordered-containers, mtl, vector, vector-binary-instances, time, hashable-time, bytestring, uuid, stm, deepseq, deepseq-generics, binary, parallel, cassava, attoparsec, gnuplot, directory, temporary, haskeline, megaparsec, text, base64-bytestring, data-interval, filepath, stm-containers, project-m36, transformers
287− GHC-Options: -Wall -threaded
324+ main-is: Relation/Basic.hs
288325
289326Test-Suite test-static-optimizer
290− Default-Language: Haskell2010
291− Default-Extensions: OverloadedStrings
327+ import: commontest
292328 type: exitcode-stdio-1.0
293− main-is: test/Relation/StaticOptimizer.hs
294− Build-Depends: base, HUnit, Cabal, containers, hashable, unordered-containers, mtl, vector, vector-binary-instances, time, hashable-time, bytestring, uuid, stm, deepseq, deepseq-generics, binary, parallel, cassava, attoparsec, gnuplot, directory, temporary, haskeline, megaparsec, text, base64-bytestring, data-interval, filepath, stm-containers, project-m36, transformers
295− GHC-Options: -Wall -threaded
329+ main-is: Relation/StaticOptimizer.hs
296330
297331Test-Suite test-transactiongraph-persist
298− Default-Language: Haskell2010
299− Default-Extensions: OverloadedStrings
332+ import: commontest
300333 type: exitcode-stdio-1.0
301− main-is: test/TransactionGraph/Persist.hs
302− Build-Depends: base, HUnit, Cabal, containers, hashable, unordered-containers, mtl, vector, vector-binary-instances, time, hashable-time, bytestring, uuid, stm, deepseq, deepseq-generics, binary, parallel, cassava, attoparsec, gnuplot, directory, temporary, haskeline, megaparsec, text, base64-bytestring, data-interval, filepath, stm-containers, project-m36, random, MonadRandom, semigroups
303− Other-Modules: TutorialD.Interpreter.Base, TutorialD.Interpreter.RelationalExpr, TutorialD.Interpreter.Types, TutorialD.Interpreter.DatabaseContextExpr, TutorialD.Interpreter.Import.BasicExamples
304− Hs-Source-Dirs: ., ./src/bin
305− GHC-Options: -Wall -threaded
334+ main-is: TransactionGraph/Persist.hs
335+ Other-Modules: TutorialD.Interpreter.Base, TutorialD.Interpreter.RelationalExpr, TutorialD.Interpreter.Types, TutorialD.Interpreter.DatabaseContextExpr, TutorialD.Interpreter.Import.BasicExamples, TutorialD.Printer
306336
307337Test-Suite test-relation-import-csv
308− Default-Language: Haskell2010
309− Default-Extensions: OverloadedStrings
338+ import: commontest
310339 type: exitcode-stdio-1.0
311− main-is: test/Relation/Import/CSV.hs
312− Build-Depends: base, HUnit, Cabal, containers, hashable, unordered-containers, mtl, vector, vector-binary-instances, time, hashable-time, bytestring, uuid, stm, deepseq, deepseq-generics, binary, parallel, cassava, attoparsec, gnuplot, directory, temporary, haskeline, megaparsec, text, base64-bytestring, data-interval, filepath, stm-containers, project-m36
313− GHC-Options: -Wall -threaded
340+ main-is: Relation/Import/CSV.hs
314341
315342Test-Suite test-tutoriald-import-tutoriald
316− Default-Language: Haskell2010
317− Default-Extensions: OverloadedStrings
343+ import: commontest
318344 type: exitcode-stdio-1.0
319− main-is: test/TutorialD/Interpreter/Import/TutorialD.hs
320− Build-Depends: base, HUnit, Cabal, containers, hashable, unordered-containers, mtl, vector, vector-binary-instances, time, hashable-time, bytestring, uuid, stm, deepseq, deepseq-generics, binary, parallel, cassava, attoparsec, gnuplot, directory, temporary, haskeline, megaparsec, text, base64-bytestring, data-interval, filepath, stm-containers, project-m36, random, MonadRandom, semigroups
321− Other-Modules: TutorialD.Interpreter.Base, TutorialD.Interpreter.Import.Base, TutorialD.Interpreter.Import.TutorialD, TutorialD.Interpreter.RelationalExpr, TutorialD.Interpreter.Types, TutorialD.Interpreter.DatabaseContextExpr, TutorialD.Interpreter.Import.BasicExamples
322− GHC-Options: -Wall -threaded
323− Hs-Source-Dirs: ., ./src/bin
345+ main-is: TutorialD/Interpreter/Import/ImportTest.hs
346+ Other-Modules: TutorialD.Interpreter.Base, TutorialD.Interpreter.Import.Base, TutorialD.Interpreter.Import.TutorialD, TutorialD.Interpreter.RelationalExpr, TutorialD.Interpreter.Types, TutorialD.Interpreter.DatabaseContextExpr, TutorialD.Interpreter.Import.BasicExamples, TutorialD.Printer
324347
325348Test-Suite test-relation-export-csv
326− Default-Language: Haskell2010
327− Default-Extensions: OverloadedStrings
349+ import: commontest
328350 type: exitcode-stdio-1.0
329− main-is: test/Relation/Export/CSV.hs
330− Build-Depends: base, HUnit, Cabal, containers, hashable, unordered-containers, mtl, vector, vector-binary-instances, time, hashable-time, bytestring, uuid, stm, deepseq, deepseq-generics, binary, parallel, cassava, attoparsec, gnuplot, directory, temporary, haskeline, megaparsec, text, base64-bytestring, data-interval, filepath, stm-containers, project-m36
331− GHC-Options: -Wall -threaded
351+ main-is: Relation/Export/CSV.hs
332352
333353Test-Suite test-transactiongraph-merge
334− Default-Language: Haskell2010
335− Default-Extensions: OverloadedStrings
354+ import: commontest
336355 type: exitcode-stdio-1.0
337− main-is: test/TransactionGraph/Merge.hs
338− Build-Depends: base, HUnit, Cabal, containers, hashable, unordered-containers, mtl, vector, vector-binary-instances, time, hashable-time, bytestring, uuid, stm, deepseq, deepseq-generics, binary, parallel, cassava, attoparsec, gnuplot, directory, temporary, haskeline, megaparsec, text, base64-bytestring, data-interval, filepath, template-haskell, transformers, aeson, conduit, either, path-pieces, http-api-data, stm-containers, list-t, project-m36
339− GHC-Options: -Wall -threaded
356+ main-is: TransactionGraph/Merge.hs
357+
358+
359+Test-Suite test-prettyprinter
360+ import: commontest
361+ type: exitcode-stdio-1.0
362+ main-is: TutorialD/PrinterTest.hs
363+ Other-Modules: TutorialD.Printer, TutorialD.Interpreter.Base, TutorialD.Interpreter.RelationalExpr, TutorialD.Interpreter.Types
340364
341365benchmark bench
342− Default-Language: Haskell2010
343− Default-Extensions: OverloadedStrings
366+ import: commontest
344367 type: exitcode-stdio-1.0
345368 main-is: benchmark/Relation.hs
346− Build-Depends: base, HUnit, Cabal, containers, hashable, unordered-containers, mtl, vector, vector-binary-instances, time, hashable-time, bytestring, uuid, stm, deepseq, deepseq-generics, binary, parallel, cassava, attoparsec, gnuplot, directory, temporary, haskeline, megaparsec, text, base64-bytestring, data-interval, filepath, criterion, stm-containers, project-m36
347− GHC-Options: -Wall -rtsopts -threaded
348− Hs-Source-Dirs: ./src/bin
349369
350370Test-Suite test-server
351− Default-Language: Haskell2010
352− Default-Extensions: OverloadedStrings
371+ import: commontest
353372 type: exitcode-stdio-1.0
354− main-is: test/Server/Main.hs
355− Build-Depends: base, HUnit, Cabal, containers, hashable, unordered-containers, mtl, vector, vector-binary-instances, time, hashable-time, bytestring, network-transport-tcp, uuid, stm, deepseq, deepseq-generics, binary, parallel, cassava, attoparsec, gnuplot, directory, temporary, haskeline, megaparsec, text, base64-bytestring, data-interval, filepath, transformers, stm-containers, list-t, project-m36, network-transport, semigroups
356− HS-Source-Dirs: ., ./src/bin
357− GHC-Options: -Wall -threaded
373+ main-is: Server/Main.hs
374+
358375
359376Executable Example-SimpleClient
360377 Default-Language: Haskell2010
361378 Default-Extensions: OverloadedStrings
362− Build-Depends: base, HUnit, Cabal, containers, hashable, unordered-containers, mtl, vector, vector-binary-instances, time, hashable-time, bytestring, uuid, stm, deepseq, deepseq-generics, binary, parallel, cassava, attoparsec, gnuplot, directory, temporary, haskeline, megaparsec, text, base64-bytestring, data-interval, filepath, transformers, stm-containers, list-t, ghc, ghc-paths, project-m36, random, MonadRandom
379+ Build-Depends: base, HUnit, Cabal, containers, hashable, unordered-containers, mtl, vector, time, hashable-time, bytestring, uuid, stm, deepseq, deepseq-generics,parallel, cassava, attoparsec, gnuplot, directory, temporary, haskeline, megaparsec, text, base64-bytestring, data-interval, filepath, transformers, stm-containers, list-t, ghc, ghc-paths, project-m36, random, MonadRandom
363380 Main-Is: examples/SimpleClient.hs
364381 GHC-Options: -Wall -threaded
365382
366383Executable Example-OutOfTheTarpit
367384 Default-Language: Haskell2010
368385 Default-Extensions: OverloadedStrings
369− Build-Depends: base, HUnit, Cabal, containers, hashable, unordered-containers, mtl, vector, vector-binary-instances, time, hashable-time, bytestring, uuid, stm, deepseq, deepseq-generics, binary, parallel, cassava, attoparsec, gnuplot, directory, temporary, haskeline, megaparsec, text, base64-bytestring, data-interval, filepath, transformers, stm-containers, list-t, aeson, path-pieces, either, conduit, http-api-data, template-haskell, ghc, ghc-paths, project-m36
386+ Build-Depends: base, HUnit, Cabal, containers, hashable, unordered-containers, mtl, vector, time, hashable-time, bytestring, uuid, stm, deepseq, deepseq-generics,parallel, cassava, attoparsec, gnuplot, directory, temporary, haskeline, megaparsec, text, base64-bytestring, data-interval, filepath, transformers, stm-containers, list-t, aeson, path-pieces, either, conduit, http-api-data, template-haskell, ghc, ghc-paths, project-m36, winery
370387 Main-Is: examples/out_of_the_tarpit.hs
371388 GHC-Options: -Wall -threaded
372389
373390Executable Example-Blog
374391 Default-Language: Haskell2010
375392 Default-Extensions: OverloadedStrings
376− Build-Depends: base, HUnit, Cabal, containers, hashable, unordered-containers, mtl, vector, vector-binary-instances, time, hashable-time, bytestring, uuid, stm, deepseq, deepseq-generics, binary, parallel, cassava, attoparsec, gnuplot, directory, temporary, haskeline, megaparsec, text, base64-bytestring, data-interval, filepath, transformers, stm-containers, list-t, aeson, path-pieces, either, conduit, http-api-data, template-haskell, ghc, ghc-paths, project-m36, scotty, blaze-html, http-types
393+ Build-Depends: base, HUnit, Cabal, containers, hashable, unordered-containers, mtl, vector, time, hashable-time, bytestring, uuid, stm, deepseq, deepseq-generics,parallel, cassava, attoparsec, gnuplot, directory, temporary, haskeline, megaparsec, text, base64-bytestring, data-interval, filepath, transformers, stm-containers, list-t, aeson, path-pieces, either, conduit, http-api-data, template-haskell, ghc, ghc-paths, project-m36, scotty, blaze-html, http-types, winery
377394 Main-Is: examples/blog.hs
378395 GHC-Options: -Wall -threaded
379396
380−
381397Executable Example-Hair
382398 Default-Language: Haskell2010
383399 Default-Extensions: OverloadedStrings
384− Build-Depends: base, HUnit, Cabal, containers, hashable, unordered-containers, mtl, vector, vector-binary-instances, time, hashable-time, bytestring, uuid, stm, deepseq, deepseq-generics, binary, parallel, cassava, attoparsec, gnuplot, directory, temporary, haskeline, megaparsec, text, base64-bytestring, data-interval, filepath, transformers, stm-containers, list-t, aeson, path-pieces, either, conduit, http-api-data, template-haskell, ghc, ghc-paths, project-m36
400+ Build-Depends: base, HUnit, Cabal, containers, hashable, unordered-containers, mtl, vector, time, hashable-time, bytestring, uuid, stm, deepseq, deepseq-generics,parallel, cassava, attoparsec, gnuplot, directory, temporary, haskeline, megaparsec, text, base64-bytestring, data-interval, filepath, transformers, stm-containers, list-t, aeson, path-pieces, either, conduit, http-api-data, template-haskell, ghc, ghc-paths, project-m36, winery
385401 Main-Is: examples/hair.hs
386402 GHC-Options: -Wall -threaded
387403
404+Executable Example-Plantfarm
405+ Default-Language: Haskell2010
406+ Default-Extensions: OverloadedStrings
407+ Build-Depends: aeson, barbies, base, binary, containers, deepseq, hashable, project-m36, random, scotty, text, winery
408+ Main-Is: examples/Plantfarm.hs
409+ GHC-Options: -Wall -threaded
410+
388411Executable Example-CustomTupleable
389412 Default-Language: Haskell2010
390413 Default-Extensions: OverloadedStrings
391− Build-Depends: base, HUnit, Cabal, containers, hashable, unordered-containers, mtl, vector, vector-binary-instances, time, hashable-time, bytestring, uuid, stm, deepseq, deepseq-generics, binary, parallel, cassava, attoparsec, gnuplot, directory, temporary, haskeline, megaparsec, text, base64-bytestring, data-interval, filepath, transformers, stm-containers, list-t, aeson, path-pieces, either, conduit, http-api-data, template-haskell, ghc, ghc-paths, project-m36
414+ Build-Depends: base, HUnit, Cabal, containers, hashable, unordered-containers, mtl, vector, time, hashable-time, bytestring, uuid, stm, deepseq, deepseq-generics,parallel, cassava, attoparsec, gnuplot, directory, temporary, haskeline, megaparsec, text, base64-bytestring, data-interval, filepath, transformers, stm-containers, list-t, aeson, path-pieces, either, conduit, http-api-data, template-haskell, ghc, ghc-paths, project-m36, winery
392415 Main-Is: examples/CustomTupleable.hs
393416 GHC-Options: -Wall -threaded
394417
395−Test-Suite test-scripts
418+Executable Example-DerivingCustomTupleable
419+ if impl(ghc>=8.6)
420+ Buildable: True
421+ else
422+ Buildable: False
396423 Default-Language: Haskell2010
397− Default-Extensions: OverloadedStrings
398− type: exitcode-stdio-1.0
399− main-is: test/scripts.hs
400− Build-Depends: base, HUnit, Cabal, containers, hashable, unordered-containers, mtl, vector, vector-binary-instances, time, hashable-time, bytestring, network-transport-tcp, uuid, stm, deepseq, deepseq-generics, binary, parallel, cassava, attoparsec, gnuplot, directory, temporary, haskeline, megaparsec, text, base64-bytestring, data-interval, filepath, transformers, stm-containers, list-t, project-m36, random, MonadRandom, semigroups
401− Other-Modules: TutorialD.Interpreter.Base, TutorialD.Interpreter.DatabaseContextExpr, TutorialD.Interpreter.Import.Base, TutorialD.Interpreter.Import.TutorialD, TutorialD.Interpreter.RelationalExpr, TutorialD.Interpreter.Types, TutorialD.Interpreter.Import.BasicExamples
424+ Build-Depends: base, text, deepseq, project-m36, winery
425+ Main-Is: examples/DerivingCustomTupleable.hs
402426 GHC-Options: -Wall -threaded
403− Hs-Source-Dirs: ., ./src/bin
427+
428+Test-Suite test-scripts
429+ import: commontest
430+ type: exitcode-stdio-1.0
431+ main-is: scripts.hs
432+ Other-Modules: TutorialD.Interpreter.Base, TutorialD.Interpreter.DatabaseContextExpr, TutorialD.Interpreter.Import.Base, TutorialD.Interpreter.Import.TutorialD, TutorialD.Interpreter.RelationalExpr, TutorialD.Interpreter.Types, TutorialD.Interpreter.Import.BasicExamples, TutorialD.Printer
404433
405434Executable project-m36-websocket-server
406435 Default-Language: Haskell2010
407− Build-Depends: base, aeson, path-pieces, either, conduit, http-api-data, template-haskell, websockets, aeson, optparse-applicative, project-m36, containers, bytestring, text, vector, uuid, megaparsec, haskeline, mtl, directory, base64-bytestring, random, MonadRandom, time, network-transport-tcp, semigroups, attoparsec
436+ Build-Depends: base, aeson, path-pieces, either, conduit, http-api-data, template-haskell, websockets, aeson, optparse-applicative, project-m36, containers, bytestring, text, vector, uuid, megaparsec, haskeline, mtl, directory, base64-bytestring, random, MonadRandom, time, semigroups, attoparsec, parser-combinators, prettyprinter, network, modern-uri, http-conduit, base16-bytestring, http-types, cryptohash-sha256, wai, wai-websockets, warp, warp-tls
408437 Main-Is: ProjectM36/Server/WebSocket/websocket-server.hs
409− Other-Modules: ProjectM36.Client.Json, ProjectM36.Server.RemoteCallTypes.Json, ProjectM36.Server.WebSocket, TutorialD.Interpreter, TutorialD.Interpreter.Base, TutorialD.Interpreter.DatabaseContextExpr, TutorialD.Interpreter.DatabaseContextIOOperator, TutorialD.Interpreter.Export.Base, TutorialD.Interpreter.Export.CSV, TutorialD.Interpreter.Import.Base, TutorialD.Interpreter.Import.BasicExamples, TutorialD.Interpreter.Import.CSV, TutorialD.Interpreter.Import.TutorialD, TutorialD.Interpreter.InformationOperator, TutorialD.Interpreter.RODatabaseContextOperator, TutorialD.Interpreter.RelationalExpr, TutorialD.Interpreter.TransactionGraphOperator, TutorialD.Interpreter.Types, TutorialD.Interpreter.TransGraphRelationalOperator, TutorialD.Interpreter.SchemaOperator
438+ Other-Modules: ProjectM36.Client.Json, ProjectM36.Server.RemoteCallTypes.Json, ProjectM36.Server.WebSocket, TutorialD.Interpreter, TutorialD.Interpreter.Base, TutorialD.Interpreter.DatabaseContextExpr, TutorialD.Interpreter.DatabaseContextIOOperator, TutorialD.Interpreter.Export.Base, TutorialD.Interpreter.Export.CSV, TutorialD.Interpreter.Import.Base, TutorialD.Interpreter.Import.BasicExamples, TutorialD.Interpreter.Import.CSV, TutorialD.Interpreter.Import.TutorialD, TutorialD.Interpreter.InformationOperator, TutorialD.Interpreter.RODatabaseContextOperator, TutorialD.Interpreter.RelationalExpr, TutorialD.Interpreter.TransactionGraphOperator, TutorialD.Interpreter.Types, TutorialD.Interpreter.TransGraphRelationalOperator, TutorialD.Interpreter.SchemaOperator, TutorialD.Printer
410439 GHC-Options: -Wall -threaded
411440 Hs-Source-Dirs: ./src/bin
412441 Default-Extensions: OverloadedStrings
413442
414443Test-Suite test-websocket-server
415− Default-Language: Haskell2010
444+ import: commontest
416445 type: exitcode-stdio-1.0
417− main-is: test/Server/WebSocket.hs
418− Build-Depends: base, HUnit, Cabal, containers, hashable, unordered-containers, mtl, vector, vector-binary-instances, time, hashable-time, bytestring, uuid, stm, deepseq, deepseq-generics, binary, parallel, cassava, attoparsec, gnuplot, directory, temporary, haskeline, megaparsec, text, base64-bytestring, data-interval, filepath, transformers, stm-containers, list-t, websockets, optparse-applicative, network, aeson, project-m36, random, MonadRandom, network-transport-tcp, semigroups
419− Other-Modules: TutorialD.Interpreter.Export.Base, TutorialD.Interpreter.Export.CSV, TutorialD.Interpreter.Import.BasicExamples, TutorialD.Interpreter.Import.CSV, TutorialD.Interpreter.InformationOperator, TutorialD.Interpreter.RODatabaseContextOperator, TutorialD.Interpreter.TransactionGraphOperator, ProjectM36.Client.Json, ProjectM36.Server.RemoteCallTypes.Json, ProjectM36.Server.WebSocket, TutorialD.Interpreter, TutorialD.Interpreter.Base, TutorialD.Interpreter.DatabaseContextExpr, TutorialD.Interpreter.Import.Base, TutorialD.Interpreter.Import.TutorialD, TutorialD.Interpreter.RelationalExpr, TutorialD.Interpreter.Types, TutorialD.Interpreter.DatabaseContextIOOperator, TutorialD.Interpreter.TransGraphRelationalOperator, TutorialD.Interpreter.SchemaOperator
420− Default-Extensions: OverloadedStrings
421− GHC-Options: -Wall -threaded
422− Hs-Source-Dirs: ./src/bin, .
446+ main-is: Server/WebSocket.hs
447+ Other-Modules: TutorialD.Interpreter.Export.Base, TutorialD.Interpreter.Export.CSV, TutorialD.Interpreter.Import.BasicExamples, TutorialD.Interpreter.Import.CSV, TutorialD.Interpreter.InformationOperator, TutorialD.Interpreter.RODatabaseContextOperator, TutorialD.Interpreter.TransactionGraphOperator, ProjectM36.Client.Json, ProjectM36.Server.RemoteCallTypes.Json, ProjectM36.Server.WebSocket, TutorialD.Interpreter, TutorialD.Interpreter.Base, TutorialD.Interpreter.DatabaseContextExpr, TutorialD.Interpreter.Import.Base, TutorialD.Interpreter.Import.TutorialD, TutorialD.Interpreter.RelationalExpr, TutorialD.Interpreter.Types, TutorialD.Interpreter.DatabaseContextIOOperator, TutorialD.Interpreter.TransGraphRelationalOperator, TutorialD.Interpreter.SchemaOperator, TutorialD.Printer
423448
424449Test-Suite test-isomorphic-schemas
425− Default-Language: Haskell2010
450+ import: commontest
426451 type: exitcode-stdio-1.0
427− main-is: test/IsomorphicSchema.hs
428− Build-Depends: base, HUnit, Cabal, containers, hashable, unordered-containers, mtl, vector, vector-binary-instances, time, hashable-time, bytestring, uuid, stm, deepseq, deepseq-generics, binary, parallel, cassava, attoparsec, gnuplot, directory, temporary, haskeline, megaparsec, text, base64-bytestring, data-interval, filepath, transformers, stm-containers, list-t, websockets, optparse-applicative, network, aeson, project-m36
429− Default-Extensions: OverloadedStrings
430− GHC-Options: -Wall -threaded
431− Hs-Source-Dirs: ./src/bin, .
452+ main-is: IsomorphicSchema.hs
432453
433454Test-Suite test-atomable
434− Default-Language: Haskell2010
455+ import: commontest
435456 type: exitcode-stdio-1.0
436− main-is: test/Relation/Atomable.hs
437− Build-Depends: base, HUnit, Cabal, containers, hashable, unordered-containers, mtl, vector, vector-binary-instances, time, hashable-time, bytestring, uuid, stm, deepseq, deepseq-generics, binary, parallel, cassava, attoparsec, gnuplot, directory, temporary, haskeline, megaparsec, text, base64-bytestring, data-interval, filepath, transformers, stm-containers, list-t, websockets, optparse-applicative, network, aeson, project-m36, random, MonadRandom, semigroups
438− Other-Modules: TutorialD.Interpreter, TutorialD.Interpreter.Base, TutorialD.Interpreter.DatabaseContextExpr, TutorialD.Interpreter.DatabaseContextIOOperator, TutorialD.Interpreter.Export.Base, TutorialD.Interpreter.Export.CSV, TutorialD.Interpreter.Import.Base, TutorialD.Interpreter.Import.BasicExamples, TutorialD.Interpreter.Import.CSV, TutorialD.Interpreter.Import.TutorialD, TutorialD.Interpreter.InformationOperator, TutorialD.Interpreter.RODatabaseContextOperator, TutorialD.Interpreter.RelationalExpr, TutorialD.Interpreter.SchemaOperator, TutorialD.Interpreter.TestBase, TutorialD.Interpreter.TransGraphRelationalOperator, TutorialD.Interpreter.TransactionGraphOperator, TutorialD.Interpreter.Types
439− Default-Extensions: OverloadedStrings
440− GHC-Options: -Wall -threaded
441− Hs-Source-Dirs: ./src/bin, ., test/
457+ main-is: Relation/Atomable.hs
458+ Other-Modules: TutorialD.Interpreter, TutorialD.Interpreter.Base, TutorialD.Interpreter.DatabaseContextExpr, TutorialD.Interpreter.DatabaseContextIOOperator, TutorialD.Interpreter.Export.Base, TutorialD.Interpreter.Export.CSV, TutorialD.Interpreter.Import.Base, TutorialD.Interpreter.Import.BasicExamples, TutorialD.Interpreter.Import.CSV, TutorialD.Interpreter.Import.TutorialD, TutorialD.Interpreter.InformationOperator, TutorialD.Interpreter.RODatabaseContextOperator, TutorialD.Interpreter.RelationalExpr, TutorialD.Interpreter.SchemaOperator, TutorialD.Interpreter.TestBase, TutorialD.Interpreter.TransGraphRelationalOperator, TutorialD.Interpreter.TransactionGraphOperator, TutorialD.Interpreter.Types, TutorialD.Printer
442459
443460Test-Suite test-multiprocess-access
444− Default-Language: Haskell2010
461+ import: commontest
445462 type: exitcode-stdio-1.0
446− main-is: test/MultiProcessDatabaseAccess.hs
447− Build-Depends: base, HUnit, Cabal, containers, hashable, unordered-containers, mtl, vector, vector-binary-instances, time, hashable-time, bytestring, uuid, stm, deepseq, deepseq-generics, binary, parallel, cassava, attoparsec, gnuplot, directory, temporary, haskeline, megaparsec, text, base64-bytestring, data-interval, filepath, transformers, stm-containers, list-t, websockets, optparse-applicative, network, aeson, project-m36, random, MonadRandom
448− Default-Extensions: OverloadedStrings
449− GHC-Options: -Wall -threaded
450− Hs-Source-Dirs: ./src/bin, ., test/
463+ main-is: MultiProcessDatabaseAccess.hs
451464
452465Test-Suite test-transactiongraph-automerge
453− Default-Language: Haskell2010
466+ import: commontest
454467 type: exitcode-stdio-1.0
455− main-is: test/TransactionGraph/Automerge.hs
456− Build-Depends: base, HUnit, Cabal, containers, hashable, unordered-containers, mtl, vector, vector-binary-instances, time, hashable-time, bytestring, uuid, stm, deepseq, deepseq-generics, binary, parallel, cassava, attoparsec, gnuplot, directory, temporary, haskeline, megaparsec, text, base64-bytestring, data-interval, filepath, transformers, stm-containers, list-t, websockets, optparse-applicative, network, aeson, project-m36, random, MonadRandom, semigroups
457− Other-Modules: TutorialD.Interpreter, TutorialD.Interpreter.Base, TutorialD.Interpreter.DatabaseContextExpr, TutorialD.Interpreter.DatabaseContextIOOperator, TutorialD.Interpreter.Export.Base, TutorialD.Interpreter.Export.CSV, TutorialD.Interpreter.Import.Base, TutorialD.Interpreter.Import.BasicExamples, TutorialD.Interpreter.Import.CSV, TutorialD.Interpreter.Import.TutorialD, TutorialD.Interpreter.InformationOperator, TutorialD.Interpreter.RODatabaseContextOperator, TutorialD.Interpreter.RelationalExpr, TutorialD.Interpreter.SchemaOperator, TutorialD.Interpreter.TestBase, TutorialD.Interpreter.TransGraphRelationalOperator, TutorialD.Interpreter.TransactionGraphOperator, TutorialD.Interpreter.Types
458− Default-Extensions: OverloadedStrings
459− GHC-Options: -Wall -threaded
460− Hs-Source-Dirs: ./src/bin, ., test/
468+ main-is: TransactionGraph/Automerge.hs
469+ Other-Modules: TutorialD.Interpreter, TutorialD.Interpreter.Base, TutorialD.Interpreter.DatabaseContextExpr, TutorialD.Interpreter.DatabaseContextIOOperator, TutorialD.Interpreter.Export.Base, TutorialD.Interpreter.Export.CSV, TutorialD.Interpreter.Import.Base, TutorialD.Interpreter.Import.BasicExamples, TutorialD.Interpreter.Import.CSV, TutorialD.Interpreter.Import.TutorialD, TutorialD.Interpreter.InformationOperator, TutorialD.Interpreter.RODatabaseContextOperator, TutorialD.Interpreter.RelationalExpr, TutorialD.Interpreter.SchemaOperator, TutorialD.Interpreter.TestBase, TutorialD.Interpreter.TransGraphRelationalOperator, TutorialD.Interpreter.TransactionGraphOperator, TutorialD.Interpreter.Types, TutorialD.Printer
461470
462471Test-Suite test-tupleable
463− Default-Language: Haskell2010
472+ import: commontest
464473 type: exitcode-stdio-1.0
465− main-is: test/Relation/Tupleable.hs
466− Build-Depends: base, HUnit, Cabal, containers, hashable, unordered-containers, mtl, vector, vector-binary-instances, time, hashable-time, bytestring, uuid, stm, deepseq, deepseq-generics, binary, parallel, cassava, attoparsec, gnuplot, directory, temporary, haskeline, megaparsec, text, base64-bytestring, data-interval, filepath, transformers, stm-containers, list-t, websockets, optparse-applicative, network, aeson, project-m36, random, MonadRandom, semigroups
467− Default-Extensions: OverloadedStrings
468− GHC-Options: -Wall -threaded
469− Hs-Source-Dirs: ./src/bin, ., test/
474+ main-is: Relation/Tupleable.hs
470475
471476Test-Suite test-client-simple
472− Default-Language: Haskell2010
473− Main-Is: test/Client/Simple.hs
477+ import: commontest
478+ Main-Is: Client/Simple.hs
474479 type: exitcode-stdio-1.0
475− Build-Depends: base, HUnit, Cabal, containers, hashable, unordered-containers, mtl, vector, vector-binary-instances, time, hashable-time, bytestring, uuid, stm, deepseq, deepseq-generics, binary, parallel, cassava, attoparsec, gnuplot, directory, temporary, haskeline, megaparsec, text, base64-bytestring, data-interval, filepath, transformers, stm-containers, list-t, websockets, optparse-applicative, network, aeson, project-m36, random, MonadRandom, semigroups
476− Default-Extensions: OverloadedStrings
477− GHC-Options: -Wall -threaded
478− Hs-Source-Dirs: ./src/bin, ., test/
479480
480481-- test for file handle leaks
481482Executable handles
482483 Default-Language: Haskell2010
483484 Default-Extensions: OverloadedStrings
484− Build-Depends: base, HUnit, Cabal, containers, hashable, unordered-containers, mtl, vector, vector-binary-instances, time, hashable-time, bytestring, uuid, stm, deepseq, deepseq-generics, binary, parallel, cassava, attoparsec, gnuplot, directory, temporary, haskeline, megaparsec, text, base64-bytestring, data-interval, filepath, optparse-applicative, stm-containers, list-t, ghc, ghc-paths, transformers, project-m36, random, MonadRandom, semigroups
485+ Build-Depends: base, HUnit, Cabal, containers, hashable, unordered-containers, mtl, vector, time, hashable-time, bytestring, uuid, stm, deepseq, deepseq-generics,parallel, cassava, attoparsec, gnuplot, directory, temporary, haskeline, megaparsec, text, base64-bytestring, data-interval, filepath, optparse-applicative, stm-containers, list-t, ghc, ghc-paths, transformers, project-m36, random, MonadRandom, semigroups, parser-combinators, prettyprinter, modern-uri, http-types, http-conduit, base16-bytestring, cryptohash-sha256
485486 main-is: benchmark/Handles.hs
486487 Other-Modules: TutorialD.Interpreter,
487488 TutorialD.Interpreter.Base,
@@ -500,17 +501,14 @@ Executable handles
500501 TutorialD.Interpreter.TransGraphRelationalOperator,
501502 TutorialD.Interpreter.TransactionGraphOperator,
502503 TutorialD.Interpreter.Types
504+ TutorialD.Printer
503505 GHC-Options: -Wall -threaded -rtsopts
504506 HS-Source-Dirs: ./src/bin
505507 if flag(profiler)
506508 GHC-Prof-Options: -fprof-auto -rtsopts -threaded -Wall
507−
509+
508510Test-Suite test-dataframe
509− Default-Language: Haskell2010
510− Main-Is: test/DataFrame.hs
511+ import: commontest
511512 type: exitcode-stdio-1.0
512− Other-Modules: TutorialD.Interpreter, TutorialD.Interpreter.Base, TutorialD.Interpreter.DatabaseContextExpr, TutorialD.Interpreter.DatabaseContextIOOperator, TutorialD.Interpreter.Export.Base, TutorialD.Interpreter.Export.CSV, TutorialD.Interpreter.Import.Base, TutorialD.Interpreter.Import.BasicExamples, TutorialD.Interpreter.Import.CSV, TutorialD.Interpreter.Import.TutorialD, TutorialD.Interpreter.InformationOperator, TutorialD.Interpreter.RODatabaseContextOperator, TutorialD.Interpreter.RelationalExpr, TutorialD.Interpreter.SchemaOperator, TutorialD.Interpreter.TestBase, TutorialD.Interpreter.TransGraphRelationalOperator, TutorialD.Interpreter.TransactionGraphOperator, TutorialD.Interpreter.Types
513− Build-Depends: base, HUnit, Cabal, containers, hashable, unordered-containers, mtl, vector, vector-binary-instances, time, hashable-time, bytestring, uuid, stm, deepseq, deepseq-generics, binary, parallel, cassava, attoparsec, gnuplot, directory, temporary, haskeline, megaparsec, text, base64-bytestring, data-interval, filepath, transformers, stm-containers, list-t, websockets, optparse-applicative, network, aeson, project-m36, random, MonadRandom, semigroups
514− Default-Extensions: OverloadedStrings
515− GHC-Options: -Wall -threaded
516− Hs-Source-Dirs: ./src/bin, ., test/
513+ Main-Is: DataFrame.hs
514+ Other-Modules: TutorialD.Interpreter, TutorialD.Interpreter.Base, TutorialD.Interpreter.DatabaseContextExpr, TutorialD.Interpreter.DatabaseContextIOOperator, TutorialD.Interpreter.Export.Base, TutorialD.Interpreter.Export.CSV, TutorialD.Interpreter.Import.Base, TutorialD.Interpreter.Import.BasicExamples, TutorialD.Interpreter.Import.CSV, TutorialD.Interpreter.Import.TutorialD, TutorialD.Interpreter.InformationOperator, TutorialD.Interpreter.RODatabaseContextOperator, TutorialD.Interpreter.RelationalExpr, TutorialD.Interpreter.SchemaOperator, TutorialD.Interpreter.TestBase, TutorialD.Interpreter.TransGraphRelationalOperator, TutorialD.Interpreter.TransactionGraphOperator, TutorialD.Interpreter.Types, TutorialD.Printer
release.nixnew file+36
@@ -0,0 +1,36 @@
1+{ compiler ? "ghc8104"
2+, sources ? import ./nix/sources.nix
3+, pkgs ? import sources.nixpkgs { }
4+}:
5+let
6+ doJailbreak = pkgs.haskell.lib.doJailbreak;
7+ needsCocoa = drv:
8+ if pkgs.stdenv.isDarwin
9+ then drv.overrideDerivation (old:
10+ { buildInputs = [ pkgs.darwin.apple_sdk.frameworks.Cocoa ] ++ old.buildInputs; }
11+ )
12+ else drv;
13+
14+ haskellPackages = pkgs.haskell.packages.${compiler}.override {
15+ overrides = self: super: {
16+ curryer-rpc = self.callCabal2nix "curryer-rpc" sources.curryer { };
17+ streamly = doJailbreak (needsCocoa (self.callCabal2nix "streamly" sources.streamly { }));
18+ project-m36 = ((self.callCabal2nixWithOptions "project-m36" ./. "-f-haskell-scripting" { }));
19+ };
20+ };
21+in
22+{
23+ project = haskellPackages.project-m36;
24+
25+ shell = haskellPackages.shellFor {
26+ packages = p: [
27+ p.project-m36
28+ ];
29+ buildInputs = [
30+ haskellPackages.ghcid
31+ haskellPackages.hlint
32+ pkgs.docker
33+ ];
34+ withHoogle = true;
35+ };
36+}
scripts/DateExamples.tutd+2−2
@@ -20,7 +20,7 @@ sp := relation{tuple{s# "S1",p# "P1",qty 300},
2020 tuple{s# "S3",p# "P2",qty 200},
2121 tuple{s# "S4",p# "P4",qty 300},
2222 tuple{s# "S4",p# "P5",qty 400}};
23−key s_pkey {s#} s
24−key p_key {p#} p
23+key s_pkey {s#} s;
24+key p_key {p#} p;
2525foreign key s_sp_fk sp{s#} in s{s#};
2626foreign key p_sp_fk sp{p#} in p{p#};
scripts/multiline.tutdnew file+2
@@ -0,0 +1,2 @@
1+x:=relation{
2+tuple{ x 2}} -- nice
shell.nixnew file+1
@@ -0,0 +1 @@
1+(import ./release.nix { }).shell
src/bin/ProjectM36/Client/Json.hs+4−1
@@ -3,6 +3,7 @@ module ProjectM36.Client.Json where
33import Data.Aeson
44import ProjectM36.Server.RemoteCallTypes.Json ()
55import ProjectM36.Client
6+import ProjectM36.TransactionGraph
67import Control.Exception (IOException)
78
89instance ToJSON EvaluatedNotification
@@ -11,4 +12,6 @@ instance FromJSON EvaluatedNotification
1112instance ToJSON ConnectionError
1213
1314instance ToJSON IOException where
14− toJSON err = object ["IOException" .= show err]
15+ toJSON err = object ["IOException" .= show err]
16+
17+instance ToJSON MerkleValidationError
src/bin/ProjectM36/Server/RemoteCallTypes/Json.hs+37−3
@@ -1,5 +1,5 @@
11--create a bunch of orphan instances for use with the websocket server
2−{-# LANGUAGE FlexibleInstances, TypeSynonymInstances #-}
2+{-# LANGUAGE FlexibleInstances #-}
33{-# OPTIONS_GHC -fno-warn-orphans #-}
44module ProjectM36.Server.RemoteCallTypes.Json where
55import ProjectM36.AtomFunctionError
@@ -10,6 +10,8 @@ import ProjectM36.DataTypes.Primitive
1010import ProjectM36.Error
1111import ProjectM36.IsomorphicSchema
1212import ProjectM36.Server.RemoteCallTypes
13+import ProjectM36.MerkleHash
14+import ProjectM36.Attribute as A
1315
1416import Data.Aeson
1517import Data.ByteString.Base64 as B64
@@ -22,6 +24,9 @@ instance FromJSON RelationalExpr
2224instance ToJSON TupleExpr
2325instance FromJSON TupleExpr
2426
27+instance ToJSON TupleExprs
28+instance FromJSON TupleExprs
29+
2530instance ToJSON RestrictionPredicateExpr
2631instance FromJSON RestrictionPredicateExpr
2732
@@ -40,8 +45,11 @@ instance FromJSON ExecuteRelationalExpr
4045instance ToJSON Relation
4146instance FromJSON Relation
4247
43−instance ToJSON Attribute
44−instance FromJSON Attribute
48+instance ToJSON Attribute where
49+ toJSON (Attribute attrName aType) = object [ "name" .= attrName
50+ , "type" .= toJSON aType ]
51+instance FromJSON Attribute where
52+ parseJSON = withObject "Attribute" $ \v -> Attribute <$> v .: "name" <*> v .: "type"
4553
4654instance ToJSON ExtendTupleExpr
4755instance FromJSON ExtendTupleExpr
@@ -95,6 +103,8 @@ instance ToJSON Atom where
95103 "val" .= i ]
96104 toJSON atom@(RelationAtom i) = object [ "type" .= atomTypeForAtom atom,
97105 "val" .= i ]
106+ toJSON atom@(RelationalExprAtom i) = object [ "type" .= atomTypeForAtom atom,
107+ "val" .= i ]
98108 toJSON (ConstructedAtom dConsName atomtype atomlist) = object [
99109 "dataconstructorname" .= dConsName,
100110 "type" .= toJSON atomtype,
@@ -122,6 +132,7 @@ instance FromJSON Atom where
122132 Left err -> fail ("Failed to parse base64-encoded ByteString: " ++ err)
123133 Right bs -> pure (ByteStringAtom bs)
124134 BoolAtomType -> BoolAtom <$> o .: "val"
135+ RelationalExprAtomType -> RelationalExprAtom <$> o .: "val"
125136
126137instance ToJSON Notification
127138instance FromJSON Notification
@@ -129,6 +140,21 @@ instance FromJSON Notification
129140instance ToJSON ScriptCompilationError
130141instance FromJSON ScriptCompilationError
131142
143+instance ToJSON MerkleHash where
144+ toJSON h = object [ "merklehash" .= decodeUtf8 (B64.encode (_unMerkleHash h))]
145+instance FromJSON MerkleHash where
146+ parseJSON = withObject "merklehash" $ \o -> do
147+ b64bs <- encodeUtf8 <$> o .: "merklehash"
148+ case B64.decode b64bs of
149+ Left err -> fail ("Failed to parse merkle hash: " ++ err)
150+ Right bs -> pure (MerkleHash bs)
151+
152+instance ToJSON Attributes where
153+ toJSON attrs = object ["attributes" .= map toJSON (A.toList attrs)]
154+instance FromJSON Attributes where
155+ parseJSON = withObject "Attributes" $ \o ->
156+ A.attributesFromList <$> o .: "attributes"
157+
132158instance ToJSON RelationalError
133159instance FromJSON RelationalError
134160
@@ -138,6 +164,9 @@ instance FromJSON SchemaError
138164instance ToJSON MergeError
139165instance FromJSON MergeError
140166
167+instance ToJSON ImportError'
168+instance FromJSON ImportError'
169+
141170instance ToJSON DatabaseContextFunctionError
142171instance FromJSON DatabaseContextFunctionError
143172
@@ -149,3 +178,8 @@ instance FromJSON PersistenceError
149178
150179instance ToJSON AtomFunctionError
151180instance FromJSON AtomFunctionError
181+
182+instance ToJSON WithNameExpr
183+instance FromJSON WithNameExpr
184+
185+
src/bin/ProjectM36/Server/WebSocket.hs+33−21
@@ -1,4 +1,4 @@
1−{-# LANGUAGE LambdaCase #-}
1+{-# LANGUAGE LambdaCase, CPP #-}
22module ProjectM36.Server.WebSocket where
33-- while the tutd client performs TutorialD parsing on the client, the websocket server will pass tutd to be parsed and executed on the server- otherwise I have to pull in ghcjs as a dependency to allow client-side parsing- that's not appealing because then the frontend is not language-agnostic, but this could change in the future, perhaps by sending different messages over the websocket
44-- ideally, the wire protocol should not be exposed to a straight string-based API ala SQL, so we could make perhaps a javascript DSL which compiles to the necessary JSON- anaylyze tradeoffs
@@ -22,9 +22,14 @@ import Data.Attoparsec.Text
2222import Control.Applicative
2323import Text.Megaparsec.Error
2424import Data.Functor
25+import Data.Either (fromRight)
26+
27+#if MIN_VERSION_megaparsec(7,0,0)
28+import Data.List.NonEmpty as NE
29+#endif
2530
2631websocketProxyServer :: Port -> Hostname -> WS.ServerApp
27−websocketProxyServer port host pending = do
32+websocketProxyServer port host pending = do
2833 conn <- WS.acceptRequest pending
2934 let unexpectedMsg = WS.sendTextData conn ("messagenotexpected" :: T.Text)
3035 --phase 1- accept database name for connection
@@ -33,10 +38,10 @@ websocketProxyServer port host pending = do
3338 if not (connectdbmsg `T.isPrefixOf` dbmsg) then unexpectedMsg >> WS.sendClose conn ("" :: T.Text)
3439 else do
3540 let dbname = T.unpack $ T.drop (T.length connectdbmsg) dbmsg
36− bracket (createConnection conn dbname port host)
41+ bracket (createConnection conn dbname port host)
3742 (\case
3843 Right dbconn -> close dbconn
39− Left _ -> pure ()) $ \case
44+ Left _ -> pure ()) $ \case
4045 Left err -> sendError conn err
4146 Right dbconn -> do
4247 eSessionId <- createSessionAtHead dbconn "master"
@@ -47,34 +52,41 @@ websocketProxyServer port host pending = do
4752 _ <- forever $ do
4853 pInfo <- promptInfo sessionId dbconn
4954 --figure out why sending three times during startup is necessary
50− sendPromptInfo pInfo conn
55+ sendPromptInfo pInfo conn
5156 sendPromptInfo pInfo conn
5257 msg <- WS.receiveData conn :: IO T.Text
5358 case parseOnly parseExecuteMessage msg of
5459 Left _ -> unexpectedMsg
5560 Right (presentation, tutdString) ->
5661 case parseTutorialD tutdString of
57− Left err -> handleOpResult conn dbconn presentation (DisplayErrorResult ("parse error: " `T.append` T.pack (parseErrorPretty err)))
62+ Left err -> handleOpResult conn dbconn presentation
63+#if MIN_VERSION_megaparsec(7,0,0)
64+ (DisplayErrorResult
65+ ("parse error: " `T.append` T.pack
66+ (parseErrorPretty . NE.head . bundleErrors $ err)))
67+#else
68+ (DisplayErrorResult ("parse error: " `T.append` T.pack (parseErrorPretty err)))
69+#endif
5870 Right parsed -> do
59− let timeoutFilter exc = if exc == RequestTimeoutException
60− then Just exc
71+ let timeoutFilter exc = if exc == RequestTimeoutException
72+ then Just exc
6173 else Nothing
6274 responseHandler = do
6375 result <- evalTutorialD sessionId dbconn SafeEvaluation parsed
6476 pInfo' <- promptInfo sessionId dbconn
65− sendPromptInfo pInfo' conn
77+ sendPromptInfo pInfo' conn
6678 handleOpResult conn dbconn presentation result
6779 catchJust timeoutFilter responseHandler (\_ -> handleOpResult conn dbconn presentation (DisplayErrorResult "Request Timed Out."))
6880 pure ()
69−
70−notificationCallback :: WS.Connection -> NotificationCallback
81+
82+notificationCallback :: WS.Connection -> NotificationCallback
7183notificationCallback conn notifName evaldNotif = WS.sendTextData conn (encode (object ["notificationname" .= notifName,
7284 "evaldnotification" .= evaldNotif
7385 ]))
74−
86+
7587--this creates a new database for each connection- perhaps not what we want (?)
7688createConnection :: WS.Connection -> DatabaseName -> Port -> Hostname -> IO (Either ConnectionError Connection)
77−createConnection wsconn dbname port host = connectProjectM36 (RemoteProcessConnectionInfo dbname (createNodeId host port) (notificationCallback wsconn))
89+createConnection wsconn dbname port host = connectProjectM36 (RemoteConnectionInfo dbname host (show port) (notificationCallback wsconn))
7890
7991sendError :: (ToJSON a) => WS.Connection -> a -> IO ()
8092sendError conn err = WS.sendTextData conn (encode (object ["displayerror" .= err]))
@@ -100,32 +112,32 @@ handleOpResult conn _ presentation (DisplayDataFrameResult df) = do
100112 texto = ["text" .= showDataFrame df | textPresentation presentation]
101113 htmlo = ["html" .= dataFrameAsHTML df | htmlPresentation presentation]
102114 WS.sendTextData conn (encode (object ["displaydataframe" .= object (jsono ++ texto ++ htmlo)]))
103−
115+
104116-- get current schema and head name for client
105117promptInfo :: SessionId -> Connection -> IO (HeadName, SchemaName)
106118promptInfo sessionId conn = do
107− eHeadName <- headName sessionId conn
119+ eHeadName <- headName sessionId conn
108120 eSchemaName <- currentSchemaName sessionId conn
109− pure (either (const "<unknown>") id eHeadName, either (const "<no schema>") id eSchemaName)
110−
121+ pure (fromRight "<unknown>" eHeadName, fromRight "<no schema>" eSchemaName)
122+
111123sendPromptInfo :: (HeadName, SchemaName) -> WS.Connection -> IO ()
112124sendPromptInfo (hName, sName) conn = WS.sendTextData conn (encode (object ["promptInfo" .= object ["headname" .= hName, "schemaname" .= sName]]))
113125
114126--a returning relation can be returned as JSON, Text (for consoles), or HTML
115127data Presentation = Presentation {
116− jsonPresentation :: Bool,
128+ jsonPresentation :: Bool,
117129 textPresentation :: Bool,
118130 htmlPresentation :: Bool }
119−
131+
120132data PresentationFlag = JSONFlag | TextFlag | HTMLFlag
121−
133+
122134parseExecuteMessage :: Parser (Presentation, T.Text)
123135parseExecuteMessage = do
124136 _ <- string "executetutd/"
125137 flags <- sepBy ((string "json" $> JSONFlag) <|>
126138 (string "text" $> TextFlag) <|>
127139 (string "html" $> HTMLFlag)) "+"
128− let presentation = foldr (\flag acc -> case flag of
140+ let presentation = foldr (\flag acc -> case flag of
129141 JSONFlag -> acc {jsonPresentation = True}
130142 TextFlag -> acc {textPresentation = True}
131143 HTMLFlag -> acc {htmlPresentation = True}) (Presentation False False False) flags
src/bin/ProjectM36/Server/WebSocket/websocket-client.html+1−1
@@ -126,7 +126,7 @@ margin-bottom: 5pt;
126126 <li>:showrelvars</li>
127127 <li>:showexpr true</li>
128128 <li>:showexpr false</li>
129− <li>:importexample date</li>
129+ <li>:importexample cjdate</li>
130130 <li>:showexpr s join sp</li>
131131 <li>update s where city=&quot;Paris&quot; (status:=10)</li>
132132 <li>:showexpr s</li>
src/bin/ProjectM36/Server/WebSocket/websocket-server.hs+48−18
@@ -1,33 +1,63 @@
11{-# LANGUAGE CPP #-}
2−import ProjectM36.Server.WebSocket
3−import ProjectM36.Server.Config
4−import ProjectM36.Server.ParseArgs
5−import ProjectM36.Server
6−import Control.Concurrent
7−import qualified Network.WebSockets as WS
8−
9−#if MIN_VERSION_network_transport_tcp(0,6,0)
10−import Network.Transport.TCP.Internal (decodeEndPointAddress)
11−#else
12−import Network.Transport.TCP (decodeEndPointAddress)
13−#endif
142
3+import Control.Concurrent
154import Control.Exception
5+import Control.Monad (when)
6+import Data.Maybe (isJust)
7+import Data.String (fromString)
8+import Network.HTTP.Types (status400)
9+import Network.Socket
10+import Network.Wai (Application, responseLBS)
11+import Network.Wai.Handler.Warp
12+import Network.Wai.Handler.WarpTLS (runTLS, tlsSettings)
13+import qualified Network.Wai.Handler.WebSockets as WS
14+import Network.WebSockets (defaultConnectionOptions)
15+import ProjectM36.Server
16+import ProjectM36.Server.Config
17+import ProjectM36.Server.ParseArgs
18+import ProjectM36.Server.WebSocket
1619
1720main :: IO ()
1821main = do
1922 -- launch normal project-m36-server
2023 addressMVar <- newEmptyMVar
21− serverConfig <- parseConfigWithDefaults (defaultServerConfig { bindPort = 8000, bindHost = "127.0.0.1" })
24+ wsConfig <- parseWSConfigWithDefaults (defaultServerConfig {bindPort = 8000, bindHost = "127.0.0.1"})
25+
2226 --usurp the serverConfig for our websocket server and make the proxied server run locally
23− let wsHost = bindHost serverConfig
27+ let serverConfig = wsServerConfig wsConfig
28+ wsHost = bindHost serverConfig
2429 wsPort = bindPort serverConfig
2530 serverHost = "127.0.0.1"
2631 serverConfig' = serverConfig {bindPort = 0, bindHost = serverHost}
32+ configCertificateFile = tlsCertificatePath wsConfig
33+ configKeyFile = tlsKeyPath wsConfig
34+
35+ when (isJust configCertificateFile /= isJust configKeyFile) $
36+ throwIO $ ErrorCall "TLS_CERTIFICATE_PATH and TLS_KEY_PATH must be set in tandem"
37+
2738 _ <- forkFinally (launchServer serverConfig' (Just addressMVar) >> pure ()) (either throwIO pure)
2839 --wait for server to be listening
29− address <- takeMVar addressMVar
30− let Just (_, serverPort, _) = decodeEndPointAddress address
31− --this built-in server is apparently not meant for production use, but it's easier to test than starting up the wai or snap interfaces
32− WS.runServer wsHost (fromIntegral wsPort) (websocketProxyServer (read serverPort) serverHost)
40+ addr <- takeMVar addressMVar
41+ let port =
42+ case addr of
43+ SockAddrInet port' _ -> fromIntegral port'
44+ _ -> error "unsupported socket address (IPv4 only currently)"
45+ wsApp = websocketProxyServer port serverHost
46+ waiApp = WS.websocketsOr defaultConnectionOptions wsApp backupApp
47+ settings = warpSettings wsHost (fromIntegral wsPort)
48+
49+ case (configCertificateFile, configKeyFile) of
50+ (Just certificate, Just key) -> runTLS (tlsSettings certificate key) settings waiApp
51+ _ -> runSettings settings waiApp
52+
53+backupApp :: Application
54+backupApp _ respond = respond $ responseLBS status400 [] "Not a WebSocket request"
3355
56+warpSettings :: HostName -> Port -> Settings
57+warpSettings host port =
58+ setHost (fromString host)
59+ . setPort port
60+ . setServerName "project-m36"
61+ . setTimeout 3600
62+ . setGracefulShutdownTimeout (Just 5)
63+ $ defaultSettings
src/bin/TutorialD/Interpreter.hs+32−28
@@ -1,4 +1,4 @@
1−{-# LANGUAGE GADTs, LambdaCase #-}
1+{-# LANGUAGE GADTs, LambdaCase, CPP #-}
22module TutorialD.Interpreter where
33import TutorialD.Interpreter.Base
44import TutorialD.Interpreter.RODatabaseContextOperator
@@ -28,10 +28,13 @@ import System.Console.Haskeline
2828import System.Directory (getHomeDirectory)
2929import qualified Data.Text as T
3030import System.IO (hPutStrLn, stderr)
31+#if __GLASGOW_HASKELL__ < 804
3132import Data.Monoid
33+#endif
3234import Data.List (isPrefixOf)
3335import Control.Exception
3436import System.Exit
37+import Data.Either (fromRight)
3538
3639{-
3740context ops are read-only operations which only operate on the database context (relvars and constraints)
@@ -59,7 +62,7 @@ interpreterParserP = safeInterpreterParserP <|>
5962 fmap ImportDBContextOp (tutdImportP <* eof) <|>
6063 fmap RelVarExportOp (exportCSVP <* eof) <|>
6164 fmap DatabaseContextIOExprOp (dbContextIOExprP <* eof)
62−
65+
6366-- the safe interpreter never reads or writes the file system
6467safeInterpreterParserP :: Parser ParsedOperation
6568safeInterpreterParserP = fmap RODatabaseContextOp (roDatabaseContextOperatorP <* eof) <|>
@@ -75,8 +78,8 @@ safeInterpreterParserP = fmap RODatabaseContextOp (roDatabaseContextOperatorP <*
7578promptText :: Either RelationalError HeadName -> Either RelationalError SchemaName -> StringType
7679promptText eHeadName eSchemaName = "TutorialD (" <> transInfo <> "): "
7780 where
78− transInfo = either (const "<unknown>") id eHeadName <> "/" <> either (const "<no schema>") id eSchemaName
79−
81+ transInfo = fromRight "<unknown>" eHeadName <> "/" <> fromRight "<no schema>" eSchemaName
82+
8083parseTutorialD :: T.Text -> Either ParserError ParsedOperation
8184parseTutorialD = parse interpreterParserP ""
8285
@@ -104,20 +107,20 @@ evalTutorialDInteractive sessionId conn safe interactive expr = case expr of
104107 else
105108 pure res
106109 _ -> pure res
107−
108− (DatabaseContextExprOp execOp) ->
109− eHandler $ C.executeDatabaseContextExpr sessionId conn execOp
110−
111− (DatabaseContextIOExprOp execOp) ->
110+
111+ (DatabaseContextExprOp execOp) ->
112+ eHandler $ C.executeDatabaseContextExpr sessionId conn execOp
113+
114+ (DatabaseContextIOExprOp execOp) ->
112115 if needsSafe then
113116 unsafeError
114117 else
115118 eHandler $ C.executeDatabaseContextIOExpr sessionId conn execOp
116−
119+
117120 (GraphOp execOp) -> do
118121 -- warn if the graph op could cause uncommited changes to be discarded
119122 eIsDirty <- C.disconnectedTransactionIsDirty sessionId conn
120− let runGraphOp = eHandler $ C.executeGraphExpr sessionId conn execOp
123+ let runGraphOp = eHandler $ C.executeGraphExpr sessionId conn execOp
121124 settings = Settings {complete = noCompletion,
122125 historyFile = Nothing,
123126 autoAddHistory = False}
@@ -141,20 +144,20 @@ evalTutorialDInteractive sessionId conn safe interactive expr = case expr of
141144 pure (DisplayErrorResult "Graph operation cancelled.")
142145 else
143146 runGraphOp
144−
147+
145148 (ConvenienceGraphOp execOp) ->
146149 eHandler $ evalConvenienceGraphOp sessionId conn execOp
147150
148151 (ROGraphOp execOp) -> do
149152 opResult <- evalROGraphOp sessionId conn execOp
150− case opResult of
153+ case opResult of
151154 Left err -> barf err
152155 Right rel -> pure (DisplayRelationResult rel)
153−
156+
154157 (SchemaOp execOp) ->
155158 eHandler $ evalSchemaOperator sessionId conn execOp
156−
157− (ImportRelVarOp execOp@(RelVarDataImportOperator relVarName _ _)) ->
159+
160+ (ImportRelVarOp execOp@(RelVarDataImportOperator relVarName _ _)) ->
158161 if needsSafe then
159162 unsafeError
160163 else do
@@ -172,8 +175,8 @@ evalTutorialDInteractive sessionId conn safe interactive expr = case expr of
172175 case exprErr of
173176 Left err -> barf err
174177 Right dbexpr -> evalTutorialD sessionId conn safe (DatabaseContextExprOp dbexpr)
175−
176− (ImportDBContextOp execOp) ->
178+
179+ (ImportDBContextOp execOp) ->
177180 if needsSafe then
178181 unsafeError
179182 else do
@@ -181,15 +184,15 @@ evalTutorialDInteractive sessionId conn safe interactive expr = case expr of
181184 case eErr of
182185 Left err -> barf err
183186 Right dbexprs -> evalTutorialD sessionId conn safe (DatabaseContextExprOp dbexprs)
184−
185− (InfoOp execOp) ->
187+
188+ (InfoOp execOp) ->
186189 if needsSafe then
187190 unsafeError
188191 else
189192 case evalInformationOperator execOp of
190193 Left err -> pure (DisplayErrorResult err)
191194 Right info -> pure (DisplayResult info)
192−
195+
193196 (RelVarExportOp execOp@(RelVarDataExportOperator relExpr _ _)) ->
194197 --eval relexpr to relation and pass to export function
195198 if needsSafe then
@@ -213,19 +216,20 @@ evalTutorialDInteractive sessionId conn safe interactive expr = case expr of
213216 unsafeError = pure $ DisplayErrorResult "File I/O operation prohibited."
214217 barf :: RelationalError -> IO TutorialDOperatorResult
215218 barf (ScriptError (OtherScriptCompilationError errStr)) = pure (DisplayErrorResult (T.pack errStr))
219+ barf (ParseError err) = pure (DisplayErrorResult err)
216220 barf err = return $ DisplayErrorResult (T.pack (show err))
217221 eHandler io = do
218222 eErr <- io
219223 case eErr of
220224 Left err -> barf err
221225 Right () -> return QuietSuccessResult
222−
223−type GhcPkgPath = String
226+
227+type GhcPkgPath = String
224228type TutorialDExec = String
225229type CheckFS = Bool
226−
230+
227231data InterpreterConfig = LocalInterpreterConfig PersistenceStrategy HeadName (Maybe TutorialDExec) [GhcPkgPath] CheckFS |
228− RemoteInterpreterConfig C.NodeId C.DatabaseName HeadName (Maybe TutorialDExec) CheckFS
232+ RemoteInterpreterConfig C.Hostname C.Port C.DatabaseName HeadName (Maybe TutorialDExec) CheckFS
229233
230234outputNotificationCallback :: C.NotificationCallback
231235outputNotificationCallback notName evaldNot = hPutStrLn stderr $ "Notification received " ++ show notName ++ ":\n" ++ "\n" ++ prettyEvaluatedNotification evaldNot
@@ -254,12 +258,12 @@ reprLoop config sessionId conn = do
254258 Just line -> do
255259 runTutorialD sessionId conn (Just (T.length prompt)) (T.pack line)
256260 reprLoop config sessionId conn
257−
261+
258262
259263runTutorialD :: C.SessionId -> C.Connection -> Maybe PromptLength -> T.Text -> IO ()
260−runTutorialD sessionId conn mPromptLength tutd =
264+runTutorialD sessionId conn mPromptLength tutd =
261265 case parseTutorialD tutd of
262− Left err ->
266+ Left err ->
263267 displayOpResult $ DisplayParseErrorResult mPromptLength err
264268 Right parsed ->
265269 catchJust (\exc -> if exc == C.RequestTimeoutException then Just exc else Nothing) (do
src/bin/TutorialD/Interpreter/Base.hs+68−38
@@ -1,8 +1,8 @@
11{-# LANGUAGE DeriveGeneric, CPP #-}
22module TutorialD.Interpreter.Base (
3− module TutorialD.Interpreter.Base,
3+ module TutorialD.Interpreter.Base,
44 module Text.Megaparsec,
5−#if MIN_VERSION_megaparsec(6,0,0)
5+#if MIN_VERSION_megaparsec(6,0,0)
66 module Text.Megaparsec.Char,
77 module Control.Applicative
88#else
@@ -12,11 +12,12 @@ module TutorialD.Interpreter.Base (
1212 where
1313import ProjectM36.Base
1414import ProjectM36.AtomType
15+import ProjectM36.Attribute as A
1516import ProjectM36.Relation
1617import ProjectM36.DataFrame
1718
1819#if MIN_VERSION_megaparsec(6,0,0)
19−import Text.Megaparsec.Char
20+import Text.Megaparsec.Char
2021import qualified Text.Megaparsec.Char.Lexer as Lex
2122import Text.Megaparsec
2223import Data.Void
@@ -30,24 +31,31 @@ import Data.Text hiding (count)
3031import System.Random
3132import qualified Data.Text as T
3233import qualified Data.List as L
33−import qualified Data.Vector as V
3434import qualified Data.Text.IO as TIO
3535import System.IO
3636import ProjectM36.Relation.Show.Term
3737import GHC.Generics
38+#if __GLASGOW_HASKELL__ < 804
3839import Data.Monoid
40+#endif
3941import qualified Data.UUID as U
4042import Control.Monad.Random
4143import Data.List.NonEmpty as NE
4244import Data.Time.Clock
4345import Data.Time.Format
4446import Control.Monad (void)
47+import Data.Char
48+
49+#if !MIN_VERSION_megaparsec(7,0,0)
50+anySingle :: Parsec Void Text (Token Text)
51+anySingle = anyChar
52+#endif
4553
4654displayOpResult :: TutorialDOperatorResult -> IO ()
4755displayOpResult QuitResult = return ()
4856displayOpResult (DisplayResult out) = TIO.putStrLn out
4957displayOpResult (DisplayIOResult ioout) = ioout
50−displayOpResult (DisplayErrorResult err) = let outputf = if T.length err > 0 && T.last err /= '\n' then TIO.hPutStrLn else TIO.hPutStr in
58+displayOpResult (DisplayErrorResult err) = let outputf = if T.length err > 0 && T.last err /= '\n' then TIO.hPutStrLn else TIO.hPutStr in
5159 outputf stderr ("ERR: " <> err)
5260displayOpResult QuietSuccessResult = return ()
5361displayOpResult (DisplayRelationResult rel) = do
@@ -55,8 +63,13 @@ displayOpResult (DisplayRelationResult rel) = do
5563 let randomlySortedRel = evalRand (randomizeTupleOrder rel) gen
5664 TIO.putStrLn (showRelation randomlySortedRel)
5765displayOpResult (DisplayParseErrorResult mPromptLength err) = do
58− let errString = T.pack (parseErrorPretty err)
59− errorIndent = unPos (sourceColumn (NE.head (errorPos err)))
66+#if MIN_VERSION_megaparsec(7,0,0)
67+ let errorIndent = errorOffset . NE.head . bundleErrors $ err
68+ errString = T.pack (parseErrorPretty . NE.head . bundleErrors $ err)
69+#else
70+ let errorIndent = unPos (sourceColumn (NE.head (errorPos err)))
71+ errString = T.pack (parseErrorPretty err)
72+#endif
6073 pointyString len = T.justifyRight (len + fromIntegral errorIndent) '_' "^"
6174 maybe (pure ()) (TIO.putStrLn . pointyString) mPromptLength
6275 TIO.putStr ("ERR:" <> errString)
@@ -69,9 +82,10 @@ type ParseStr = Text
6982type ParseStr = String
7083#endif
7184
85+-- consumes only horizontal spaces
7286spaceConsumer :: Parser ()
73−spaceConsumer = Lex.space (void spaceChar) (Lex.skipLineComment "--") (Lex.skipBlockComment "{-" "-}")
74−
87+spaceConsumer = Lex.space space1 (Lex.skipLineComment "--") (Lex.skipBlockComment "{-" "-}")
88+
7589opChar :: Parser Char
7690opChar = oneOf (":!#$%&*+./<=>?\\^|-~" :: String)-- remove "@" so it can be used as attribute marker without spaces
7791
@@ -90,9 +104,13 @@ braces = between (symbol "{") (symbol "}")
90104identifier :: Parser Text
91105identifier = do
92106 istart <- letterChar <|> char '_'
93− irest <- many (alphaNumChar <|> char '_' <|> char '#')
107+ identifierRemainder istart
108+
109+identifierRemainder :: Char -> Parser Text
110+identifierRemainder c = do
111+ rest <- many (alphaNumChar <|> char '_' <|> char '#')
94112 spaceConsumer
95− pure (pack (istart:irest))
113+ pure (pack (c:rest))
96114
97115symbol :: ParseStr -> Parser Text
98116#if MIN_VERSION_megaparsec(6,0,0)
@@ -119,11 +137,14 @@ arrow = symbol "->"
119137semi :: Parser Text
120138semi = symbol ";"
121139
140+nline :: Parser Text
141+nline = (T.singleton <$> newline) <|> crlf
142+
122143integer :: Parser Integer
123144#if MIN_VERSION_megaparsec(6,0,0)
124−integer = Lex.signed spaceConsumer Lex.decimal
145+integer = Lex.signed (pure ()) Lex.decimal <* spaceConsumer
125146#else
126−integer = Lex.signed spaceConsumer Lex.integer
147+integer = Lex.signed (pure ()) Lex.integer <* spaceConsumer
127148#endif
128149
129150natural :: Parser Integer
@@ -134,36 +155,30 @@ natural = Lex.integer <* spaceConsumer
134155#endif
135156
136157float :: Parser Double
137−float = Lex.float
158+float = Lex.float <* spaceConsumer
138159
139160capitalizedIdentifier :: Parser Text
140−capitalizedIdentifier = do
141− fletter <- upperChar
142− restOfIdentifier_ fletter
143−
144−restOfIdentifier_ :: Char -> Parser Text
145−restOfIdentifier_ fletter = do
146− rest <- option "" identifier
147− spaceConsumer
148− pure (T.cons fletter rest)
149−
161+capitalizedIdentifier =
162+ upperChar >>= identifierRemainder
163+
150164uncapitalizedIdentifier :: Parser Text
151−uncapitalizedIdentifier = do
152− fletter <- lowerChar
153− restOfIdentifier_ fletter
165+uncapitalizedIdentifier =
166+ lowerChar >>= identifierRemainder
154167
155168showRelationAttributes :: Attributes -> Text
156169showRelationAttributes attrs = "{" <> T.concat (L.intersperse ", " $ L.map showAttribute attrsL) <> "}"
157170 where
158− showAttribute (Attribute name atomType) = name <> " " <> prettyAtomType atomType
159− attrsL = V.toList attrs
171+ showAttribute (Attribute name atomType') = name <> " " <> prettyAtomType atomType'
172+ attrsL = A.toList attrs
160173
161−type PromptLength = Int
174+type PromptLength = Int
162175
163−#if MIN_VERSION_megaparsec(6,0,0)
176+#if MIN_VERSION_megaparsec(7,0,0)
177+type ParserError = ParseErrorBundle T.Text Void
178+#elif MIN_VERSION_megaparsec(6,0,0)
164179type ParserError = ParseError Char Void
165−#else
166−type ParserError = ParseError Char Dec
180+#else
181+type ParserError = ParseError Char Dec
167182#endif
168183
169184data TutorialDOperatorResult = QuitResult |
@@ -175,24 +190,27 @@ data TutorialDOperatorResult = QuitResult |
175190 DisplayParseErrorResult (Maybe PromptLength) ParserError | -- PromptLength refers to length of prompt text
176191 QuietSuccessResult
177192 deriving (Generic)
178−
193+
179194type TransactionGraphWasUpdated = Bool
180195
181196--allow for python-style triple quoting because guessing the correct amount of escapes in different contexts is annoying
182197tripleQuotedString :: Parser Text
183198tripleQuotedString = do
184199 _ <- tripleQuote
185− pack <$> manyTill anyChar (try (tripleQuote >> notFollowedBy quote))
186−
200+ pack <$> manyTill anySingle (try (tripleQuote >> notFollowedBy quote))
201+
187202normalQuotedString :: Parser Text
188203normalQuotedString = quote *> (T.pack <$> manyTill Lex.charLiteral quote)
189204
190205quotedString :: Parser Text
191206quotedString = try tripleQuotedString <|> normalQuotedString
192207
208+quoted :: Parser a -> Parser a
209+quoted = between quote quote
210+
193211uuidP :: Parser U.UUID
194212uuidP = do
195− uuidStart <- count 8 hexDigitChar
213+ uuidStart <- count 8 hexDigitChar
196214 _ <- char '-' -- min 28 with no dashes, maximum 4 dashes
197215 uuidMid1 <- count 4 hexDigitChar
198216 _ <- char '-'
@@ -211,5 +229,17 @@ utcTimeP = do
211229 timeStr <- quotedString
212230 case parseTimeM True defaultTimeLocale "%Y-%m-%d %H:%M:%S" (T.unpack timeStr) of
213231 Nothing -> fail "invalid datetime input, use \"YYYY-MM-DD HH:MM:SS\""
214− Just stamp -> pure stamp
232+ Just stamp' -> pure stamp'
233+
234+
235+colonOp :: Text -> Parser ()
236+colonOp opStr = do
237+ _ <- string opStr <* (void spaceChar <|> eof) <* spaceConsumer
238+ pure ()
239+
240+hex :: Parser Text
241+hex = takeWhileP (Just "hexadecimal")
242+ (\c ->
243+ isDigit c
244+ || (c >= 'a' && c <= 'f'))
215245
src/bin/TutorialD/Interpreter/DatabaseContextExpr.hs+26−17
@@ -1,3 +1,4 @@
1+{-# LANGUAGE CPP #-}
12module TutorialD.Interpreter.DatabaseContextExpr where
23import ProjectM36.Base
34import TutorialD.Interpreter.Base
@@ -5,14 +6,15 @@ import qualified Data.Text as T
56import TutorialD.Interpreter.RelationalExpr
67import TutorialD.Interpreter.Types
78import qualified Data.Map as M
8−import Control.Monad.State
99import ProjectM36.StaticOptimizer
1010import qualified ProjectM36.Error as PM36E
1111import ProjectM36.Error
1212import qualified ProjectM36.RelationalExpression as RE
1313import ProjectM36.Key
1414import ProjectM36.FunctionalDependency
15+#if __GLASGOW_HASKELL__ < 804
1516import Data.Monoid
17+#endif
1618import Data.Functor
1719
1820--parsers which create "database expressions" which modify the database context (such as relvar assignment)
@@ -42,7 +44,7 @@ nothingP = spaceConsumer >> pure NoOperation
4244assignP :: Parser DatabaseContextExpr
4345assignP = do
4446 relVarName <- try $ do
45− relVarName <- identifier
47+ relVarName <- relVarNameP
4648 reservedOp ":="
4749 return relVarName
4850 Assign relVarName <$> relExprP
@@ -51,19 +53,20 @@ multilineSep :: Parser T.Text
5153multilineSep = newline >> pure "\n"
5254
5355multipleDatabaseContextExprP :: Parser DatabaseContextExpr
54−multipleDatabaseContextExprP =
55− MultipleExpr <$> sepBy1 databaseContextExprP semi
56+multipleDatabaseContextExprP = do
57+ exprs <- filter (/= NoOperation) <$> sepBy1 databaseContextExprP semi
58+ pure (MultipleExpr exprs)
5659
5760insertP :: Parser DatabaseContextExpr
5861insertP = do
5962 reservedOp "insert"
60− relvar <- identifier
63+ relvar <- relVarNameP
6164 Insert relvar <$> relExprP
6265
6366defineP :: Parser DatabaseContextExpr
6467defineP = do
6568 relVarName <- try $ do
66− relVarName <- identifier
69+ relVarName <- relVarNameP
6770 reservedOp "::"
6871 return relVarName
6972 Define relVarName <$> makeAttributeExprsP
@@ -71,17 +74,17 @@ defineP = do
7174undefineP :: Parser DatabaseContextExpr
7275undefineP = do
7376 reservedOp "undefine"
74− Undefine <$> identifier
77+ Undefine <$> relVarNameP
7578
7679deleteP :: Parser DatabaseContextExpr
7780deleteP = do
7881 reservedOp "delete"
79− Delete <$> identifier <*> option TruePredicate (reservedOp "where" *> restrictionPredicateP)
82+ Delete <$> relVarNameP <*> option TruePredicate (reservedOp "where" *> restrictionPredicateP)
8083
8184updateP :: Parser DatabaseContextExpr
8285updateP = do
8386 reservedOp "update"
84− relVarName <- identifier
87+ relVarName <- relVarNameP
8588 predicate <- option TruePredicate (reservedOp "where" *> restrictionPredicateP <* spaceConsumer)
8689 attributeAssignments <- M.fromList <$> parens (sepBy attributeAssignmentP comma)
8790 return $ Update relVarName attributeAssignments predicate
@@ -164,7 +167,7 @@ addTypeConstructorP = do
164167removeTypeConstructorP :: Parser DatabaseContextExpr
165168removeTypeConstructorP = do
166169 reserved "undata"
167− RemoveTypeConstructor <$> identifier
170+ RemoveTypeConstructor <$> typeConstructorNameP
168171
169172removeAtomFunctionP :: Parser DatabaseContextExpr
170173removeAtomFunctionP = do
@@ -176,29 +179,35 @@ removeDatabaseContextFunctionP = do
176179 reserved "removedatabasecontextfunction"
177180 RemoveDatabaseContextFunction <$> quotedString
178181
182+functionNameP :: Parser AtomFunctionName
183+functionNameP = uncapitalizedIdentifier
184+
179185executeDatabaseContextFunctionP :: Parser DatabaseContextExpr
180186executeDatabaseContextFunctionP = do
181187 reserved "execute"
182− funcName <- identifier
188+ funcName <- functionNameP
183189 args <- parens (sepBy atomExprP comma)
184190 pure (ExecuteDatabaseContextFunction funcName args)
185191
186192databaseExprOpP :: Parser DatabaseContextExpr
187193databaseExprOpP = multipleDatabaseContextExprP
188194
195+{-
189196evalDatabaseContextExpr :: Bool -> DatabaseContext -> DatabaseContextExpr -> Either RelationalError DatabaseContext
190197evalDatabaseContextExpr useOptimizer context expr = do
191198 optimizedExpr <- evalState (applyStaticDatabaseOptimization expr) (RE.freshDatabaseState context)
192199 case runState (RE.evalDatabaseContextExpr (if useOptimizer then optimizedExpr else expr)) (RE.freshDatabaseState context) of
193200 (Right (), (context',_, _)) -> Right context'
194201 (Left err, _) -> Left err
202+-}
195203
196−
197−interpretDatabaseContextExpr :: DatabaseContext -> T.Text -> Either RelationalError DatabaseContext
198−interpretDatabaseContextExpr context tutdstring = case parse databaseExprOpP "" tutdstring of
199− Left err -> Left $ PM36E.ParseError (T.pack (show err))
200− Right parsed ->
201− evalDatabaseContextExpr True context parsed
204+interpretDatabaseContextExpr :: DatabaseContext -> TransactionId -> TransactionGraph -> T.Text -> Either RelationalError DatabaseContext
205+interpretDatabaseContextExpr context transId graph tutdstring =
206+ case parse databaseExprOpP "" tutdstring of
207+ Left err -> Left $ PM36E.ParseError (T.pack (show err))
208+ Right parsed -> do
209+ let env = RE.mkDatabaseContextEvalEnv transId graph
210+ RE.dbc_context <$> RE.runDatabaseContextEvalMonad context env (optimizeAndEvalDatabaseContextExpr True parsed)
202211
203212{-
204213--no optimization
src/bin/TutorialD/Interpreter/Export/Base.hs+3
@@ -1,7 +1,10 @@
1+{-# LANGUAGE CPP #-}
12module TutorialD.Interpreter.Export.Base where
23import ProjectM36.Base
34import ProjectM36.Error
5+#if __GLASGOW_HASKELL__ < 804
46import Data.Monoid
7+#endif
58
69data RelVarDataExportOperator = RelVarDataExportOperator RelationalExpr FilePath (RelVarDataExportOperator -> Relation -> IO (Maybe RelationalError))
710
src/bin/TutorialD/Interpreter/Import/Base.hs+11−3
@@ -1,7 +1,12 @@
1+{-# LANGUAGE CPP #-}
12module TutorialD.Interpreter.Import.Base where
23import ProjectM36.Base
34import ProjectM36.Error
5+import Text.URI (URI)
6+import Data.Text (Text)
7+#if __GLASGOW_HASKELL__ < 804
48import Data.Monoid
9+#endif
510
611-- | import data into a relation variable
712data RelVarDataImportOperator = RelVarDataImportOperator RelVarName FilePath (RelVarName -> TypeConstructorMapping -> Attributes -> FilePath -> IO (Either RelationalError DatabaseContextExpr))
@@ -9,11 +14,14 @@ data RelVarDataImportOperator = RelVarDataImportOperator RelVarName FilePath (Re
914instance Show RelVarDataImportOperator where
1015 show (RelVarDataImportOperator rv path _) = "RelVarDataImportOperator " <> show rv <> " " <> path
1116
17+type HashVerification = Maybe Text
18+
1219-- | import data into a database context
13−data DatabaseContextDataImportOperator = DatabaseContextDataImportOperator FilePath (FilePath -> IO (Either RelationalError DatabaseContextExpr))
20+data DatabaseContextDataImportOperator = DatabaseContextDataImportOperator URI HashVerification (URI -> HashVerification -> IO (Either RelationalError DatabaseContextExpr))
1421
1522instance Show DatabaseContextDataImportOperator where
16− show (DatabaseContextDataImportOperator path _) = "DatabaseContextDataImportOperator " <> path
23+ show (DatabaseContextDataImportOperator uri hash _) =
24+ "DatabaseContextDataImportOperator " <> show uri <> " " <> show hash
1725
1826-- perhaps create a structure to import a whole transaction graph section in the future
1927
@@ -21,4 +29,4 @@ evalRelVarDataImportOperator :: RelVarDataImportOperator -> TypeConstructorMappi
2129evalRelVarDataImportOperator (RelVarDataImportOperator relVarName path importFunc) tConsMap attrs = importFunc relVarName tConsMap attrs path
2230
2331evalDatabaseContextDataImportOperator :: DatabaseContextDataImportOperator -> IO (Either RelationalError DatabaseContextExpr)
24−evalDatabaseContextDataImportOperator (DatabaseContextDataImportOperator path importFunc) = importFunc path
32+evalDatabaseContextDataImportOperator (DatabaseContextDataImportOperator uri hash importFunc) = importFunc uri hash
src/bin/TutorialD/Interpreter/Import/BasicExamples.hs+2−2
@@ -20,8 +20,8 @@ importBasicExampleOperatorP :: Parser ImportBasicExampleOperator
2020importBasicExampleOperatorP = do
2121 reservedOp ":importexample"
2222 example <- identifier
23− if example == "date" then
23+ if example == "cjdate" then
2424 pure ImportBasicDateExampleOperator
2525 else
2626 fail "Unknown example name"
27−
27+
src/bin/TutorialD/Interpreter/Import/CSV.hs+3−3
@@ -14,10 +14,10 @@ importCSVRelation relVarName tConsMap attrs pathIn = do
1414 --TODO: handle filesystem errors
1515 csvData <- try (BS.readFile pathIn) :: IO (Either IOError BS.ByteString)
1616 case csvData of
17− Left err -> return $ Left (ImportError $ T.pack (show err))
17+ Left err -> pure $ Left (ImportError (ImportFileError (T.pack (show err))))
1818 Right csvData' -> case csvAsRelation attrs tConsMap csvData' of
19− Left err -> return $ Left (ParseError $ T.pack (show err))
20− Right csvRel -> return $ Right (Insert relVarName (ExistingRelation csvRel))
19+ Left err -> pure $ Left (ParseError $ T.pack (show err))
20+ Right csvRel -> pure $ Right (Insert relVarName (ExistingRelation csvRel))
2121
2222importCSVP :: Parser RelVarDataImportOperator
2323importCSVP = do
src/bin/TutorialD/Interpreter/Import/TutorialD.hs+70−17
@@ -9,25 +9,78 @@ import qualified Data.Text as T
99import Control.Exception
1010import qualified Data.ByteString as BS
1111import qualified Data.Text.Encoding as TE
12−--import a file containing TutorialD database context expressions
12+import qualified Text.URI as URI
13+import Text.URI (URI)
14+import Crypto.Hash.SHA256
15+import Data.ByteString.Base16 as B16
16+import Network.HTTP.Simple
17+import Network.HTTP.Types
18+--import a file containing TutorialD database context expressions via local files or HTTP/HTTPS
1319
14−importTutorialD :: FilePath -> IO (Either RelationalError DatabaseContextExpr)
15−importTutorialD pathIn = do
16− eTutdBytes <- try (BS.readFile pathIn) :: IO (Either IOError BS.ByteString)
17− case eTutdBytes of
18− Left err -> return $ Left (ImportError $ T.pack (show err))
19− Right tutdBytes ->
20− case TE.decodeUtf8' tutdBytes of
21− Left err -> pure (Left (ImportError $ T.pack (show err)))
22− Right tutdUtf8 ->
23− case parse multipleDatabaseContextExprP "import" tutdUtf8 of
24− --parseErrorPretty is new in megaparsec 5
25− Left err -> pure (Left (PM36E.ParseError (T.pack (show err))))
26− Right expr -> pure (Right expr)
27−
20+importTutorialDFromFile :: URI -> HashVerification -> IO (Either RelationalError DatabaseContextExpr)
21+importTutorialDFromFile fileURI mHash = do
22+ case URI.uriPath fileURI of
23+ Just (False, _) -> do
24+ eTutdBytes <- try (BS.readFile filePath) :: IO (Either IOError BS.ByteString)
25+ case eTutdBytes of
26+ Left err -> pure $ Left (ImportError (ImportFileError (T.pack (show err))))
27+ Right tutdBytes ->
28+ case validateBytes tutdBytes mHash of
29+ Left err -> pure (Left err)
30+ Right tutdBytes' -> importTutorialDBytes tutdBytes'
31+ _ -> pure (Left (ImportError (InvalidFileURIError (URI.render fileURI))))
32+ where
33+ filePath = drop (length ("file://" :: String)) (URI.renderStr fileURI)
34+
35+
36+importTutorialDBytes :: BS.ByteString -> IO (Either RelationalError DatabaseContextExpr)
37+importTutorialDBytes tutdBytes =
38+ case TE.decodeUtf8' tutdBytes of
39+ Left err -> pure (Left (ImportError (ImportFileDecodeError (T.pack (show err)))))
40+ Right tutdUtf8 ->
41+ case parse (multipleDatabaseContextExprP <* eof) "import" tutdUtf8 of
42+ --parseErrorPretty is new in megaparsec 5
43+ Left err -> pure (Left (PM36E.ParseError (T.pack (errorBundlePretty err))))
44+ Right expr -> pure (Right expr)
45+
46+importTutorialDViaHTTP :: URI -> HashVerification -> IO (Either RelationalError DatabaseContextExpr)
47+importTutorialDViaHTTP uri mHash = do
48+ reqURI <- parseRequest (URI.renderStr uri)
49+ response <- httpBS reqURI
50+ let scode = getResponseStatus response
51+ if scode == ok200 then
52+ let byteBody = getResponseBody response in
53+ case validateBytes byteBody mHash of
54+ Right byteBody' -> do
55+ importTutorialDBytes byteBody'
56+ Left err -> pure (Left err)
57+ else
58+ pure (Left (ImportError (ImportDownloadError (T.pack ("download failed: " <> show scode)))))
59+
60+validateBytes :: BS.ByteString -> HashVerification -> Either RelationalError BS.ByteString
61+validateBytes tutdBytes mHash =
62+ case mHash of
63+ Nothing -> pure tutdBytes
64+ Just expectedHashText ->
65+ case B16.decode (TE.encodeUtf8 expectedHashText) of
66+ Left _ -> Left (ImportError (InvalidSHA256Error expectedHashText))
67+ Right expectedHash | hashBytes == expectedHash -> pure tutdBytes
68+ | otherwise ->
69+ let p = TE.decodeUtf8 . B16.encode in
70+ Left (ImportError (SHA256MismatchError (p expectedHash) (p hashBytes)))
71+ where
72+ hashBytes = hash tutdBytes
73+
74+
2875tutdImportP :: Parser DatabaseContextDataImportOperator
2976tutdImportP = do
3077 reserved ":importtutd"
31− path <- quotedString
78+ uri <- quoted URI.parser
3279 spaceConsumer
33− return $ DatabaseContextDataImportOperator (T.unpack path) importTutorialD
80+ mhash <- optional (quoted hex)
81+ handler <- case URI.unRText <$> URI.uriScheme uri of
82+ Nothing -> fail "URI scheme missing"
83+ Just "file" -> pure importTutorialDFromFile
84+ Just scheme | scheme `elem` ["http", "https"] -> pure importTutorialDViaHTTP
85+ | otherwise -> fail ( "unsupported URI scheme: " <> show scheme)
86+ pure $ DatabaseContextDataImportOperator uri mhash handler
src/bin/TutorialD/Interpreter/RODatabaseContextOperator.hs+33−16
@@ -1,13 +1,16 @@
11{-# LANGUAGE GADTs #-}
22module TutorialD.Interpreter.RODatabaseContextOperator where
33import ProjectM36.Base
4+import ProjectM36.Relation
45import qualified ProjectM36.DataFrame as DF
56import ProjectM36.Error
7+import ProjectM36.Tuple
68import ProjectM36.InclusionDependency
79import qualified ProjectM36.Client as C
810import TutorialD.Interpreter.Base
911import TutorialD.Interpreter.RelationalExpr
1012import TutorialD.Interpreter.DatabaseContextExpr
13+import TutorialD.Printer
1114import Control.Monad.State
1215import qualified Data.Text as T
1316import ProjectM36.Relation.Show.Gnuplot
@@ -19,7 +22,7 @@ data RODatabaseContextOperator where
1922 ShowRelation :: RelationalExpr -> RODatabaseContextOperator
2023 PlotRelation :: RelationalExpr -> RODatabaseContextOperator
2124 ShowRelationType :: RelationalExpr -> RODatabaseContextOperator
22− ShowConstraint :: StringType -> RODatabaseContextOperator
25+ ShowConstraints :: StringType -> RODatabaseContextOperator
2326 ShowPlan :: DatabaseContextExpr -> RODatabaseContextOperator
2427 ShowTypes :: RODatabaseContextOperator
2528 ShowRelationVariables :: RODatabaseContextOperator
@@ -31,44 +34,44 @@ data RODatabaseContextOperator where
3134
3235typeP :: Parser RODatabaseContextOperator
3336typeP = do
34− reservedOp ":type"
37+ colonOp ":type"
3538 ShowRelationType <$> relExprP
3639
3740showRelP :: Parser RODatabaseContextOperator
3841showRelP = do
39− reservedOp ":showexpr"
42+ colonOp ":showexpr"
4043 ShowRelation <$> relExprP
4144
4245showPlanP :: Parser RODatabaseContextOperator
4346showPlanP = do
44− reservedOp ":showplan"
47+ colonOp ":showplan"
4548 ShowPlan <$> databaseContextExprP
4649
4750showTypesP :: Parser RODatabaseContextOperator
48−showTypesP = reserved ":showtypes" >> pure ShowTypes
51+showTypesP = colonOp ":showtypes" >> pure ShowTypes
4952
5053showRelationVariables :: Parser RODatabaseContextOperator
51−showRelationVariables = reserved ":showrelvars" >> pure ShowRelationVariables
54+showRelationVariables = colonOp ":showrelvars" >> pure ShowRelationVariables
5255
5356showAtomFunctionsP :: Parser RODatabaseContextOperator
54−showAtomFunctionsP = reserved ":showatomfunctions" >> pure ShowAtomFunctions
57+showAtomFunctionsP = colonOp ":showatomfunctions" >> pure ShowAtomFunctions
5558
5659showDatabaseContextFunctionsP :: Parser RODatabaseContextOperator
57−showDatabaseContextFunctionsP = reserved ":showdatabasecontextfunctions" >> pure ShowDatabaseContextFunctions
60+showDatabaseContextFunctionsP = colonOp ":showdatabasecontextfunctions" >> pure ShowDatabaseContextFunctions
5861
5962quitP :: Parser RODatabaseContextOperator
6063quitP = do
61− reservedOp ":quit"
64+ colonOp ":quit"
6265 return Quit
6366
6467showConstraintsP :: Parser RODatabaseContextOperator
6568showConstraintsP = do
66− reservedOp ":constraints"
67− ShowConstraint <$> option "" identifier
69+ colonOp ":constraints"
70+ ShowConstraints <$> option "" identifier
6871
6972plotRelExprP :: Parser RODatabaseContextOperator
7073plotRelExprP = do
71− reserved ":plotexpr"
74+ colonOp ":plotexpr"
7275 PlotRelation <$> relExprP
7376
7477roDatabaseContextOperatorP :: Parser RODatabaseContextOperator
@@ -106,15 +109,16 @@ evalRODatabaseContextOp sessionId conn (PlotRelation expr) = do
106109 err <- plotRelation rel
107110 when (isJust err) $ print err
108111
109−evalRODatabaseContextOp sessionId conn (ShowConstraint name) = do
112+evalRODatabaseContextOp sessionId conn (ShowConstraints name) = do
110113 eIncDeps <- C.inclusionDependencies sessionId conn
111114 let val = case eIncDeps of
112115 Left err -> Left err
113116 Right incDeps -> case name of
114− "" -> inclusionDependenciesAsRelation incDeps
117+ "" -> inclusionDependenciesAsRelation incDeps >>= renderRelExprsInIncDeps
115118 depName -> case M.lookup depName incDeps of
116119 Nothing -> Left (InclusionDependencyNameNotInUseError depName)
117− Just dep -> inclusionDependenciesAsRelation (M.singleton depName dep)
120+ Just dep ->
121+ inclusionDependenciesAsRelation (M.singleton depName dep) >>= renderRelExprsInIncDeps
118122 pure $ case val of
119123 Left err -> DisplayErrorResult (T.pack (show err))
120124 Right rel -> DisplayRelationResult rel
@@ -164,7 +168,7 @@ interpretRODatabaseContextOp sessionId conn tutdstring = case parse roDatabaseCo
164168
165169showDataFrameP :: Parser RODatabaseContextOperator
166170showDataFrameP = do
167− reservedOp ":showdataframe"
171+ colonOp ":showdataframe"
168172 relExpr <- relExprP
169173 reservedOp "orderby"
170174 attrOrdersExpr <- attrOrdersExprP
@@ -191,3 +195,16 @@ attrOrderExprP = DF.AttributeOrderExpr <$> identifier <*> orderP
191195
192196orderP :: Parser DF.Order
193197orderP = try (reservedOp "ascending" >> pure DF.AscendingOrder) <|> try (reservedOp "descending" >> pure DF.DescendingOrder) <|> pure DF.AscendingOrder
198+
199+-- render RelationalExprAtoms as TutorialD
200+renderRelExprsInIncDeps :: Relation -> Either RelationalError Relation
201+renderRelExprsInIncDeps = relMogrify tupMapper attrs
202+ where
203+ tupMapper tup = pure $ mkRelationTupleFromMap (M.map mapper (tupleToMap tup))
204+ mapper (RelationalExprAtom expr) = TextAtom (T.pack (show (prettyRelationalExpr expr)))
205+ mapper atom = atom
206+ attrs = C.attributesFromList [Attribute "name" TextAtomType,
207+ Attribute "sub" TextAtomType,
208+ Attribute "super" TextAtomType
209+ ]
210+
src/bin/TutorialD/Interpreter/RelationalExpr.hs+80−46
@@ -1,6 +1,11 @@
1+{-# LANGUAGE CPP #-}
12module TutorialD.Interpreter.RelationalExpr where
23import Text.Megaparsec
4+#if MIN_VERSION_megaparsec(7,0,0)
5+import Control.Monad.Combinators.Expr
6+#else
37import Text.Megaparsec.Expr
8+#endif
49import ProjectM36.Base
510import TutorialD.Interpreter.Base
611import TutorialD.Interpreter.Types
@@ -12,26 +17,36 @@ import ProjectM36.MiscUtils
1217
1318--used in projection
1419attributeListP :: RelationalMarkerExpr a => Parser (AttributeNamesBase a)
15−attributeListP =
20+attributeListP =
1621 (reservedOp "all but" >>
17− InvertedAttributeNames . S.fromList <$> sepBy identifier comma) <|>
22+ InvertedAttributeNames . S.fromList <$> sepBy attributeNameP comma) <|>
23+
1824 (reservedOp "all from" >>
1925 RelationalExprAttributeNames <$> relExprP) <|>
20− (AttributeNames . S.fromList <$> sepBy identifier comma)
26+
27+ (reservedOp "union of" >>
28+ UnionAttributeNames <$> braces attributeListP <*> braces attributeListP) <|>
29+
30+ (reservedOp "intersection of" >>
31+ IntersectAttributeNames <$> braces attributeListP <*> braces attributeListP) <|>
32+
33+ (AttributeNames . S.fromList <$> sepBy attributeNameP comma)
34+
2135
2236makeRelationP :: RelationalMarkerExpr a => Parser (RelationalExprBase a)
2337makeRelationP = do
2438 reserved "relation"
2539 attrExprs <- try (fmap Just makeAttributeExprsP) <|> pure Nothing
2640 tupleExprs <- braces (sepBy tupleExprP comma) <|> pure []
27− pure $ MakeRelationFromExprs attrExprs tupleExprs
41+ marker <- parseMarkerP
42+ pure $ MakeRelationFromExprs attrExprs (TupleExprs marker tupleExprs)
43+
2844
29−
3045--abstract data type parser- in this context, the type constructor must not include any type arguments
3146--Either Text Int
3247adTypeConstructorP :: Parser TypeConstructor
3348adTypeConstructorP = do
34− tConsName <- capitalizedIdentifier
49+ tConsName <- typeConstructorNameP
3550 tConsArgs <- many typeConstructorP
3651 pure $ ADTypeConstructor tConsName tConsArgs
3752
@@ -41,25 +56,25 @@ tupleExprP = do
4156 attrAssocs <- braces (sepBy tupleAtomExprP comma)
4257 --detect duplicate attribute names
4358 let dupAttrNames = dupes (sort (map fst attrAssocs))
44− if not (null dupAttrNames) then
59+ if not (null dupAttrNames) then
4560 fail ("Attribute names duplicated: " ++ show dupAttrNames)
4661 else
4762 pure (TupleExpr (M.fromList attrAssocs))
4863
4964tupleAtomExprP :: RelationalMarkerExpr a => Parser (AttributeName, AtomExprBase a)
5065tupleAtomExprP = do
51− attributeName <- identifier
66+ attributeName <- attributeNameP
5267 atomExpr <- atomExprP
5368 pure (attributeName, atomExpr)
54−
69+
5570projectP :: RelationalMarkerExpr a => Parser (RelationalExprBase a -> RelationalExprBase a)
5671projectP = Project <$> braces attributeListP
5772
5873renameClauseP :: Parser (T.Text, T.Text)
5974renameClauseP = do
60− oldAttr <- identifier
75+ oldAttr <- attributeNameP
6176 reservedOp "as"
62− newAttr <- identifier
77+ newAttr <- attributeNameP
6378 pure (oldAttr, newAttr)
6479
6580renameP :: Parser (RelationalExprBase a -> RelationalExprBase a)
@@ -68,7 +83,7 @@ renameP = do
6883 renameList <- braces (sepBy renameClauseP comma)
6984 case renameList of
7085 [] -> pure (Restrict TruePredicate) --no-op when rename list is empty
71− renames ->
86+ renames ->
7287 pure $ \expr -> foldl (\acc (oldAttr, newAttr) -> Rename oldAttr newAttr acc) expr renames
7388
7489whereClauseP :: RelationalMarkerExpr a => Parser (RelationalExprBase a -> RelationalExprBase a)
@@ -78,7 +93,7 @@ groupClauseP :: RelationalMarkerExpr a => Parser (AttributeNamesBase a, T.Text)
7893groupClauseP = do
7994 attrs <- braces attributeListP
8095 reservedOp "as"
81− newAttrName <- identifier
96+ newAttrName <- attributeNameP
8297 pure (attrs, newAttrName)
8398
8499groupP :: RelationalMarkerExpr a => Parser (RelationalExprBase a -> RelationalExprBase a)
@@ -91,26 +106,30 @@ groupP = do
91106ungroupP :: Parser (RelationalExprBase a -> RelationalExprBase a)
92107ungroupP = do
93108 reservedOp "ungroup"
94− Ungroup <$> identifier
109+ Ungroup <$> attributeNameP
95110
96111extendP :: RelationalMarkerExpr a => Parser (RelationalExprBase a -> RelationalExprBase a)
97112extendP = do
98113 reservedOp ":"
99− Extend <$> braces extendTupleExpressionP
100−
114+ extends <- braces (sepBy extendTupleExpressionP comma)
115+ case extends of
116+ [] -> pure (Restrict TruePredicate)
117+ extends' ->
118+ pure $ \expr -> foldl (flip Extend) expr extends'
119+
101120semijoinP :: RelationalMarkerExpr a => Parser (RelationalExprBase a -> RelationalExprBase a -> RelationalExprBase a)
102121semijoinP = do
103122 reservedOp "semijoin" <|> reservedOp "matching"
104− pure (\exprA exprB ->
123+ pure (\exprA exprB ->
105124 Project (RelationalExprAttributeNames exprA) (Join exprA exprB))
106−
107−antijoinP :: RelationalMarkerExpr a => Parser (RelationalExprBase a -> RelationalExprBase a -> RelationalExprBase a)
125+
126+antijoinP :: RelationalMarkerExpr a => Parser (RelationalExprBase a -> RelationalExprBase a -> RelationalExprBase a)
108127antijoinP = do
109128 reservedOp "not matching" <|> reservedOp "antijoin"
110129 pure (\exprA exprB ->
111130 Difference exprA (
112131 Project (RelationalExprAttributeNames exprA) (Join exprA exprB)))
113−
132+
114133relOperators :: RelationalMarkerExpr a => [[Operator Parser (RelationalExprBase a)]]
115134relOperators = [
116135 [Postfix projectP],
@@ -123,15 +142,23 @@ relOperators = [
123142 [InfixL antijoinP],
124143 [InfixL (reservedOp "union" >> return Union)],
125144 [InfixL (reservedOp "minus" >> return Difference)],
126− [InfixN (reservedOp "=" >> return Equals)],
145+ [InfixN (reservedOp "=" >> return Equals),
146+ InfixN (reservedOp "/=" >> return NotEquals)],
127147 [Postfix extendP]
128148 ]
129149
130150relExprP :: RelationalMarkerExpr a => Parser (RelationalExprBase a)
131151relExprP = try withMacroExprP <|> makeExprParser relTerm relOperators
132152
153+--allow for additional characters
154+attributeNameP :: Parser AttributeName
155+attributeNameP = uncapitalizedIdentifier
156+
157+relVarNameP :: Parser RelVarName
158+relVarNameP = uncapitalizedIdentifier
159+
133160relVarP :: RelationalMarkerExpr a => Parser (RelationalExprBase a)
134−relVarP = RelationVariable <$> identifier <*> parseMarkerP
161+relVarP = RelationVariable <$> relVarNameP <*> parseMarkerP
135162
136163relTerm :: RelationalMarkerExpr a => Parser (RelationalExprBase a)
137164relTerm = parens relExprP
@@ -152,13 +179,13 @@ restrictionPredicateP = makeExprParser predicateTerm predicateOperators
152179 <|> relationalBooleanExprP
153180
154181relationalBooleanExprP :: RelationalMarkerExpr a => Parser (RestrictionPredicateExprBase a)
155−relationalBooleanExprP =
182+relationalBooleanExprP =
156183 --we can't actually detect if the type is relational boolean, so we just pass it to the next phase
157184 RelationalExprPredicate <$> (parens relExprP <|> relTerm)
158−
185+
159186restrictionAttributeEqualityP :: RelationalMarkerExpr a => Parser (RestrictionPredicateExprBase a)
160187restrictionAttributeEqualityP = do
161− attributeName <- identifier
188+ attributeName <- attributeNameP
162189 reservedOp "="
163190 AttributeEqualityPredicate attributeName <$> atomExprP
164191
@@ -175,7 +202,7 @@ extendTupleExpressionP = attributeExtendTupleExpressionP
175202
176203attributeExtendTupleExpressionP :: RelationalMarkerExpr a => Parser (ExtendTupleExprBase a)
177204attributeExtendTupleExpressionP = do
178− newAttr <- identifier
205+ newAttr <- attributeNameP
179206 reservedOp ":="
180207 AttributeExtendTupleExpr newAttr <$> atomExprP
181208
@@ -187,33 +214,34 @@ consumeAtomExprP consume = try functionAtomExprP <|>
187214 try (parens (constructedAtomExprP True)) <|>
188215 constructedAtomExprP consume <|>
189216 attributeAtomExprP <|>
190− nakedAtomExprP <|>
217+ try nakedAtomExprP <|>
191218 relationalAtomExprP
219+
192220
193221attributeAtomExprP :: Parser (AtomExprBase a)
194222attributeAtomExprP = do
195223 _ <- string "@"
196− AttributeAtomExpr <$> identifier
224+ AttributeAtomExpr <$> attributeNameP
197225
198226nakedAtomExprP :: Parser (AtomExprBase a)
199227nakedAtomExprP = NakedAtomExpr <$> atomP
200228
201229constructedAtomExprP :: RelationalMarkerExpr a => Bool -> Parser (AtomExprBase a)
202230constructedAtomExprP consume = do
203− dConsName <- capitalizedIdentifier
231+ dConsName <- dataConstructorNameP
204232 dConsArgs <- if consume then sepBy (consumeAtomExprP False) spaceConsumer else pure []
205233 ConstructedAtomExpr dConsName dConsArgs <$> parseMarkerP
206−
234+
207235-- used only for primitive type parsing ?
208236atomP :: Parser Atom
209−atomP = stringAtomP <|>
210− doubleAtomP <|>
211− integerAtomP <|>
237+atomP = stringAtomP <|>
238+ try doubleAtomP <|>
239+ integerAtomP <|>
212240 boolAtomP
213−
241+
214242functionAtomExprP :: RelationalMarkerExpr a => Parser (AtomExprBase a)
215−functionAtomExprP =
216− FunctionAtomExpr <$> identifier <*> parens (sepBy atomExprP comma) <*> parseMarkerP
243+functionAtomExprP =
244+ FunctionAtomExpr <$> uncapitalizedIdentifier <*> parens (sepBy atomExprP comma) <*> parseMarkerP
217245
218246relationalAtomExprP :: RelationalMarkerExpr a => Parser (AtomExprBase a)
219247relationalAtomExprP = RelationAtomExpr <$> relExprP
@@ -221,30 +249,36 @@ relationalAtomExprP = RelationAtomExpr <$> relExprP
221249stringAtomP :: Parser Atom
222250stringAtomP = TextAtom <$> quotedString
223251
224−doubleAtomP :: Parser Atom
225−doubleAtomP = DoubleAtom <$> try float
252+doubleAtomP :: Parser Atom
253+doubleAtomP = DoubleAtom <$> float
226254
227255integerAtomP :: Parser Atom
228256integerAtomP = IntegerAtom <$> integer
229257
230258boolAtomP :: Parser Atom
231259boolAtomP = do
232− val <- char 't' <|> char 'f'
233− return $ BoolAtom (val == 't')
234−
260+ v <- identifier
261+ if v == "t" || v == "f" then
262+ pure $ BoolAtom (v == "t")
263+ else
264+ fail "invalid boolAtom"
265+
266+
235267relationAtomExprP :: RelationalMarkerExpr a => Parser (AtomExprBase a)
236268relationAtomExprP = RelationAtomExpr <$> makeRelationP
237269
238270withMacroExprP :: RelationalMarkerExpr a => Parser (RelationalExprBase a)
239271withMacroExprP = do
240272 reservedOp "with"
241− views <- parens (sepBy1 createViewP comma)
273+ views <- parens (sepBy1 createMacroP comma)
242274 With views <$> relExprP
243275
244−createViewP :: RelationalMarkerExpr a => Parser (RelVarName, RelationalExprBase a)
245−createViewP = do
276+createMacroP :: RelationalMarkerExpr a => Parser (WithNameExprBase a, RelationalExprBase a)
277+createMacroP = do
246278 name <- identifier
247279 reservedOp "as"
248280 expr <- relExprP
249− pure (name, expr)
250−
281+ marker <- parseMarkerP
282+ pure (WithNameExpr name marker, expr)
283+
284+
src/bin/TutorialD/Interpreter/SchemaOperator.hs+3−3
@@ -42,7 +42,7 @@ isoRestrictP = do
4242 reserved "isorestrict"
4343 relVarIn <- qrelVarP
4444 relvarsOut <- isoRestrictOutRelVarsP
45− IsoRestrict <$> pure relVarIn <*> restrictionPredicateP <*> pure relvarsOut
45+ IsoRestrict relVarIn <$> restrictionPredicateP <*> pure relvarsOut
4646
4747isoRestrictOutRelVarsP :: Parser (RelVarName, RelVarName)
4848isoRestrictOutRelVarsP = (,) <$> qrelVarP <*> qrelVarP
@@ -55,7 +55,7 @@ isoUnionP = do
5555 reserved "isounion"
5656 relVarsIn <- isoUnionInRelVarsP
5757 relVarsOut <- qrelVarP
58− IsoUnion <$> pure relVarsIn <*> restrictionPredicateP <*> pure relVarsOut
58+ IsoUnion relVarsIn <$> restrictionPredicateP <*> pure relVarsOut
5959
6060isoRenameP :: Parser SchemaIsomorph
6161isoRenameP = do
@@ -74,4 +74,4 @@ isoUnionInRelVarsP = (,) <$> qrelVarP <*> qrelVarP
7474evalSchemaOperator :: SessionId -> Connection -> SchemaOperator -> IO (Either RelationalError ())
7575evalSchemaOperator sessionId conn (ModifySchemaExpr expr) = executeSchemaExpr sessionId conn expr
7676evalSchemaOperator sessionId conn (SetCurrentSchema sname) = setCurrentSchemaName sessionId conn sname
77−
77+
src/bin/TutorialD/Interpreter/TransGraphRelationalOperator.hs+2−2
@@ -1,4 +1,4 @@
1−{-# LANGUAGE TypeSynonymInstances, FlexibleInstances #-}
1+{-# LANGUAGE FlexibleInstances #-}
22{-# OPTIONS_GHC -fno-warn-orphans #-}
33module TutorialD.Interpreter.TransGraphRelationalOperator where
44import ProjectM36.TransGraphRelationalExpression
@@ -43,4 +43,4 @@ evalTransGraphRelationalOp sessionId conn (ShowTransGraphRelation expr) = do
4343 case res of
4444 Left err -> pure $ DisplayErrorResult $ T.pack (show err)
4545 Right rel -> pure $ DisplayRelationResult rel
46−
46+
src/bin/TutorialD/Interpreter/TransactionGraphOperator.hs+12−3
@@ -2,8 +2,9 @@
22module TutorialD.Interpreter.TransactionGraphOperator where
33import TutorialD.Interpreter.Base
44import ProjectM36.TransactionGraph hiding (autoMergeToHead)
5−import ProjectM36.Client
5+import ProjectM36.Client as C
66import ProjectM36.Base
7+import ProjectM36.Relation (relationTrue)
78import Data.Functor
89
910data ConvenienceTransactionGraphOperator = AutoMergeToHead MergeStrategy HeadName
@@ -71,6 +72,9 @@ mergeTransactionsP = do
7172 reservedOp ":mergetrans"
7273 MergeTransactions <$> mergeTransactionStrategyP <*> identifier <*> identifier
7374
75+validateMerkleHashesP :: Parser ROTransactionGraphOperator
76+validateMerkleHashesP = reservedOp ":validatemerklehashes" $> ValidateMerkleHashes
77+
7478transactionGraphOpP :: Parser TransactionGraphOperator
7579transactionGraphOpP =
7680 jumpToHeadP
@@ -83,7 +87,7 @@ transactionGraphOpP =
8387 <|> mergeTransactionsP
8488
8589roTransactionGraphOpP :: Parser ROTransactionGraphOperator
86−roTransactionGraphOpP = showGraphP
90+roTransactionGraphOpP = showGraphP <|> validateMerkleHashesP
8791
8892
8993
@@ -101,6 +105,11 @@ interpretOps newUUID trans@(DisconnectedTransaction _ context) transGraph instri
101105
102106evalROGraphOp :: SessionId -> Connection -> ROTransactionGraphOperator -> IO (Either RelationalError Relation)
103107evalROGraphOp sessionId conn ShowGraph = transactionGraphAsRelation sessionId conn
108+evalROGraphOp sessionId conn ValidateMerkleHashes = do
109+ eVal <- C.validateMerkleHashes sessionId conn
110+ case eVal of
111+ Left err -> pure (Left err)
112+ Right _ -> pure (Right relationTrue)
104113
105114evalConvenienceGraphOp :: SessionId -> Connection -> ConvenienceTransactionGraphOperator -> IO (Either RelationalError ())
106−evalConvenienceGraphOp sessionId conn (AutoMergeToHead strat head') = autoMergeToHead sessionId conn strat head'
115+evalConvenienceGraphOp sessionId conn (AutoMergeToHead strat head') = autoMergeToHead sessionId conn strat head'
src/bin/TutorialD/Interpreter/Types.hs+10−4
@@ -9,18 +9,24 @@ class RelationalMarkerExpr a where
99
1010instance RelationalMarkerExpr () where
1111 parseMarkerP = pure ()
12−
12+
13+typeConstructorNameP :: Parser TypeConstructorName
14+typeConstructorNameP = capitalizedIdentifier
15+
16+dataConstructorNameP :: Parser DataConstructorName
17+dataConstructorNameP = capitalizedIdentifier
18+
1319-- | Upper case names are type names while lower case names are polymorphic typeconstructor arguments.
1420-- data *Either a b* = Left a | Right b
1521typeConstructorDefP :: Parser TypeConstructorDef
16−typeConstructorDefP = ADTypeConstructorDef <$> capitalizedIdentifier <*> typeVarNamesP
22+typeConstructorDefP = ADTypeConstructorDef <$> typeConstructorNameP <*> typeVarNamesP
1723
1824typeVarNamesP :: Parser [TypeVarName]
1925typeVarNamesP = many uncapitalizedIdentifier
2026
2127-- data Either a b = *Left a* | *Right b*
2228dataConstructorDefP :: Parser DataConstructorDef
23−dataConstructorDefP = DataConstructorDef <$> capitalizedIdentifier <*> many dataConstructorDefArgP
29+dataConstructorDefP = DataConstructorDef <$> typeConstructorNameP <*> many dataConstructorDefArgP
2430
2531-- data *Either a b* = Left *a* | Right *b*
2632dataConstructorDefArgP :: Parser DataConstructorDefArg
@@ -47,7 +53,7 @@ typeConstructorP = relationTypeConstructorP <|>
4753 monoTypeConstructorP
4854
4955monoTypeConstructorP :: Parser TypeConstructor
50−monoTypeConstructorP = ADTypeConstructor <$> capitalizedIdentifier <*> pure [] <|>
56+monoTypeConstructorP = ADTypeConstructor <$> typeConstructorNameP <*> pure [] <|>
5157 TypeVariable <$> uncapitalizedIdentifier
5258
5359
src/bin/TutorialD/Printer.hsnew file+165
@@ -0,0 +1,165 @@
1+{-# OPTIONS_GHC -fno-warn-orphans #-}
2+{-# LANGUAGE FlexibleInstances #-}
3+{-# LANGUAGE OverloadedStrings #-}
4+{-# LANGUAGE ScopedTypeVariables #-}
5+{-# LANGUAGE TypeApplications #-}
6+module TutorialD.Printer where
7+import ProjectM36.Base
8+import ProjectM36.Attribute as A hiding (null)
9+import Data.Text.Prettyprint.Doc
10+import qualified Data.Set as S hiding (fromList)
11+import qualified Data.Vector as V
12+import qualified Data.Map.Strict as M
13+import Data.Time.Calendar
14+import Data.Time.Clock.POSIX
15+import qualified Data.ByteString.Base64 as B64
16+import qualified Data.Text.Encoding as TE
17+
18+instance Pretty Atom where
19+ pretty (IntegerAtom x) = pretty x
20+ pretty (IntAtom x) = "int" <> parensList [pretty x]
21+ pretty (DoubleAtom x) = pretty x
22+ pretty (TextAtom x) = dquotes (pretty x)
23+ pretty (DayAtom x) = "fromGregorian" <> parensList [pretty a, pretty b, pretty c]
24+ where
25+ (a,b,c) = toGregorian x
26+ pretty (DateTimeAtom time) = "dateTimeFromEpochSeconds" <> parensList [pretty @Integer (round (utcTimeToPOSIXSeconds time))]
27+ pretty (ByteStringAtom bs) = "bytestring" <> parensList [dquotes (pretty (TE.decodeUtf8 (B64.encode bs)))]
28+ pretty (BoolAtom x) = if x then "t" else "f"
29+ pretty (RelationAtom x) = pretty x
30+ pretty (RelationalExprAtom re) = pretty re
31+ pretty (ConstructedAtom n _ as) = pretty n <+> prettyList as
32+
33+instance Pretty AtomExpr where
34+ pretty (AttributeAtomExpr attrName) = pretty attrName
35+ pretty (NakedAtomExpr atom) = pretty atom
36+ pretty (FunctionAtomExpr atomFuncName' atomExprs _) = pretty atomFuncName' <> prettyAtomExprsAsArguments atomExprs
37+ pretty (RelationAtomExpr relExpr) = pretty relExpr
38+ pretty (ConstructedAtomExpr dName [] _) = pretty dName
39+ pretty (ConstructedAtomExpr dName atomExprs _) = pretty dName <+> hsep (map prettyAtomExpr atomExprs)
40+
41+prettyAtomExpr :: AtomExpr -> Doc ann
42+prettyAtomExpr atomExpr =
43+ case atomExpr of
44+ AttributeAtomExpr attrName -> "@" <> pretty attrName
45+ ConstructedAtomExpr dConsName [] () -> pretty dConsName
46+ ConstructedAtomExpr dConsName atomExprs () -> parens (pretty dConsName <+> hsep (map prettyAtomExpr atomExprs))
47+ _ -> pretty atomExpr
48+
49+prettyAtomExprsAsArguments :: [AtomExpr] -> Doc ann
50+prettyAtomExprsAsArguments = align . parensList . map addAt
51+ where addAt (atomExpr :: AtomExpr) =
52+ case atomExpr of
53+ AttributeAtomExpr attrName -> "@" <> pretty attrName
54+ _ -> pretty atomExpr
55+
56+instance Pretty TupleExpr where
57+ pretty (TupleExpr map') = "tuple" <> bracesList (Prelude.map (\(attrName,atom)-> pretty attrName <+> pretty atom) (M.toList map'))
58+
59+instance Pretty RelationTuple where
60+ pretty (RelationTuple attrs atoms) = "tuple" <> bracesList (zipWith (\x y-> pretty x <+> pretty y) (V.toList (attributeNames attrs)) (V.toList atoms))
61+
62+instance Pretty Relation where
63+ pretty (Relation attrs tupSet) | attrs == mempty && null (asList tupSet) = "false"
64+ pretty (Relation attrs tupSet) | attrs == mempty && asList tupSet == [RelationTuple mempty mempty] = "true"
65+ pretty (Relation attrs tupSet) = "relation" <> prettyBracesList (A.toList attrs) <> prettyBracesList (asList tupSet)
66+
67+instance Pretty Attribute where
68+ pretty (Attribute n aTy) = pretty n <+> pretty (show aTy) -- workaround
69+
70+instance Pretty RelationalExpr where
71+ pretty (RelationVariable n _) = pretty n
72+ pretty (ExistingRelation r) = pretty r
73+ pretty (NotEquals a b) = pretty' a <+> "!=" <+> pretty' b
74+ pretty (Equals a b) = pretty' a <+> "==" <+> pretty' b
75+ pretty (Project ns r) = pretty' (ignoreProjects r) <> pretty ns
76+ pretty (Extend ext r) = collectExtends r <> pretty ext <> "}"
77+ pretty (MakeRelationFromExprs Nothing (TupleExprs () tupExprs)) = "relation" <> prettyBracesList tupExprs
78+ pretty (MakeRelationFromExprs (Just attrExprs) (TupleExprs () tupExprs)) = "relation" <> prettyBracesList attrExprs <> prettyBracesList tupExprs
79+ pretty (MakeStaticRelation attrs tupSet) = "relation" <> prettyBracesList (A.toList attrs) <> prettyBracesList (asList tupSet)
80+ pretty (Union a b) = parens $ pretty' a <+> "union" <+> pretty' b
81+ pretty (Join a b) = parens $ pretty' a <+> "join" <+> pretty' b
82+ pretty (Rename n1 n2 relExpr) = parens $ pretty relExpr <+> "rename" <+> braces (pretty n1 <+> "as" <+> pretty n2)
83+ pretty (Difference a b) = parens $ pretty' a <+> "minus" <+> pretty' b
84+ pretty (Group attrNames attrName relExpr) = parens $ pretty relExpr <+> "group" <+> parens (pretty attrNames <+> "as" <+> pretty attrName)
85+ pretty (Ungroup attrName relExpr) = parens $ pretty' relExpr <+> "ungroup" <+> pretty attrName
86+ pretty (Restrict resPreExpr relExpr) = parens $ pretty' relExpr <+> "where" <+> pretty resPreExpr
87+ pretty (With pairs a) = "with" <+> parensList (map (\(name,expr)-> pretty name <+> "as" <+> pretty expr) pairs) <+> pretty' a
88+
89+-- relvar:{a:=?}:{b:=?}:... in ADTs => relvar:{a:=?, b:=?, ...} in Doc ann
90+collectExtends :: RelationalExpr -> Doc ann
91+collectExtends (Extend ext r) = collectExtends r <> pretty ext <> ", "
92+collectExtends r = pretty r <> ":{"
93+
94+--relvar{a,b,c,...}{a,b,...}..{a} => relvar{a}
95+ignoreProjects :: RelationalExpr -> RelationalExpr
96+ignoreProjects (Project _ r) = ignoreProjects r
97+ignoreProjects r = r
98+
99+prettyRelationalExpr :: RelationalExpr -> Doc n
100+prettyRelationalExpr (RelationVariable n _) = pretty n
101+prettyRelationalExpr r = parens (pretty r)
102+
103+pretty' :: RelationalExpr -> Doc n
104+pretty' = prettyRelationalExpr
105+
106+instance Pretty AttributeNames where
107+ pretty (AttributeNames attrNames) = prettyBracesList (S.toList attrNames)
108+ pretty (InvertedAttributeNames attrNames) = braces $ "all but" <+> concatWith (surround ", ") (map pretty (S.toList attrNames))
109+ pretty (RelationalExprAttributeNames relExpr) = braces $ "all from" <+> pretty relExpr
110+ pretty (UnionAttributeNames aAttrNames bAttrNames) = braces ("union of" <+> pretty aAttrNames <+> pretty bAttrNames)
111+ pretty (IntersectAttributeNames aAttrNames bAttrNames) = braces ("intersection of" <+> pretty aAttrNames <+> pretty bAttrNames)
112+
113+instance Pretty AttributeExpr where
114+ pretty (NakedAttributeExpr attr) = pretty attr
115+ pretty (AttributeAndTypeNameExpr name typeCons _) = pretty name <+> pretty typeCons
116+
117+instance Pretty TypeConstructor where
118+ pretty (ADTypeConstructor tcName []) = pretty tcName
119+ pretty (ADTypeConstructor tcName tConsArgs) = pretty tcName <+> hsep (map pretty tConsArgs)
120+ pretty (PrimitiveTypeConstructor tcName atomType') = pretty tcName <+> pretty atomType'
121+ pretty (RelationAtomTypeConstructor attrExprs) = "relation" <> prettyBracesList attrExprs
122+ pretty (TypeVariable x) = pretty x
123+
124+instance Pretty AtomType where
125+ pretty IntAtomType = "Int"
126+ pretty IntegerAtomType = "Integer"
127+ pretty DoubleAtomType = "Double"
128+ pretty TextAtomType = "Text"
129+ pretty DayAtomType = "Day"
130+ pretty DateTimeAtomType = "DateTime"
131+ pretty ByteStringAtomType = "ByteString"
132+ pretty BoolAtomType = "Bool"
133+ pretty (RelationAtomType attrs) = "relation " <+> prettyBracesList (A.toList attrs)
134+ pretty (ConstructedAtomType tcName tvMap) = pretty tcName <+> hsep (map pretty (M.toList tvMap)) --order matters
135+ pretty RelationalExprAtomType = "RelationalExpr"
136+ pretty (TypeVariableType x) = pretty x
137+
138+instance Pretty ExtendTupleExpr where
139+ pretty (AttributeExtendTupleExpr attrName atomExpr) = pretty attrName <> ":=" <> pretty atomExpr
140+
141+
142+instance Pretty RestrictionPredicateExpr where
143+ pretty TruePredicate = "true"
144+ pretty (AndPredicate a b) = pretty a <+> "and" <+> pretty b
145+ pretty (OrPredicate a b) = pretty a <+> "or" <+> pretty b
146+ pretty (NotPredicate a) = "not" <+> pretty a
147+ pretty (RelationalExprPredicate relExpr) = pretty relExpr
148+ pretty (AtomExprPredicate atomExpr) = pretty atomExpr
149+ pretty (AttributeEqualityPredicate attrName atomExpr) = pretty attrName <> "=" <> pretty atomExpr
150+
151+instance Pretty WithNameExpr where
152+ pretty (WithNameExpr name _) = pretty name
153+
154+bracesList :: [Doc ann] -> Doc ann
155+bracesList = group . encloseSep (flatAlt "{ " "{") (flatAlt " }" "}") ", "
156+
157+prettyBracesList :: Pretty a => [a] -> Doc ann
158+prettyBracesList = align . bracesList . map pretty
159+
160+parensList :: [Doc ann] -> Doc ann
161+parensList = group . encloseSep (flatAlt "( " "(") (flatAlt " )" ")") ", "
162+
163+prettyParensList :: Pretty a => [a] -> Doc ann
164+prettyParensList = align . parensList . map pretty
165+
src/bin/TutorialD/tutd.hs+16−18
@@ -5,9 +5,13 @@ import ProjectM36.Client
55import ProjectM36.Server.ParseArgs
66import ProjectM36.Server
77import System.IO
8+import GHC.IO.Encoding
89import Options.Applicative
910import System.Exit
11+import Control.Monad
12+#if __GLASGOW_HASKELL__ < 804
1013import Data.Monoid
14+#endif
1115import Data.Maybe
1216import qualified Data.Text as T
1317
@@ -18,7 +22,7 @@ import qualified Data.Text as T
1822
1923parseArgs :: Parser InterpreterConfig
2024parseArgs = LocalInterpreterConfig <$> parsePersistenceStrategy <*> parseHeadName <*> parseTutDExec <*> many parseGhcPkgPath <*> parseCheckFS <|>
21− RemoteInterpreterConfig <$> parseNodeId <*> parseDatabaseName <*> parseHeadName <*> parseTutDExec <*> parseCheckFS
25+ RemoteInterpreterConfig <$> parseHostname "127.0.0.1" <*> parsePort defaultServerPort <*> parseDatabaseName <*> parseHeadName <*> parseTutDExec <*> parseCheckFS
2226
2327parseHeadName :: Parser HeadName
2428parseHeadName = option auto (long "head" <>
@@ -27,19 +31,6 @@ parseHeadName = option auto (long "head" <>
2731 value "master"
2832 )
2933
30−parseNodeId :: Parser NodeId
31−parseNodeId = createNodeId <$>
32− strOption (long "host" <>
33− short 'h' <>
34− help "Remote host name" <>
35− metavar "HOSTNAME" <>
36− value "127.0.0.1") <*>
37− option auto (long "port" <>
38− metavar "PORT NUMBER" <>
39− short 'p' <>
40− help "Remote port" <>
41− value defaultServerPort)
42−
4334--just execute some tutd and exit
4435parseTutDExec :: Parser (Maybe TutorialDExec)
4536parseTutDExec = optional $ strOption (long "exec-tutd" <>
@@ -53,19 +44,19 @@ opts = info (parseArgs <**> helpOption) idm
5344
5445connectionInfoForConfig :: InterpreterConfig -> ConnectionInfo
5546connectionInfoForConfig (LocalInterpreterConfig pStrategy _ _ ghcPkgPaths _) = InProcessConnectionInfo pStrategy outputNotificationCallback ghcPkgPaths
56−connectionInfoForConfig (RemoteInterpreterConfig remoteNodeId remoteDBName _ _ _) = RemoteProcessConnectionInfo remoteDBName remoteNodeId outputNotificationCallback
47+connectionInfoForConfig (RemoteInterpreterConfig remoteHost remotePort remoteDBName _ _ _) = RemoteConnectionInfo remoteDBName remoteHost (show remotePort) outputNotificationCallback
5748
5849headNameForConfig :: InterpreterConfig -> HeadName
5950headNameForConfig (LocalInterpreterConfig _ headn _ _ _) = headn
60−headNameForConfig (RemoteInterpreterConfig _ _ headn _ _) = headn
51+headNameForConfig (RemoteInterpreterConfig _ _ _ headn _ _) = headn
6152
6253execTutDForConfig :: InterpreterConfig -> Maybe String
6354execTutDForConfig (LocalInterpreterConfig _ _ t _ _) = t
64−execTutDForConfig (RemoteInterpreterConfig _ _ _ t _) = t
55+execTutDForConfig (RemoteInterpreterConfig _ _ _ _ t _) = t
6556
6657checkFSForConfig :: InterpreterConfig -> Bool
6758checkFSForConfig (LocalInterpreterConfig _ _ _ _ c) = c
68−checkFSForConfig (RemoteInterpreterConfig _ _ _ _ c) = c
59+checkFSForConfig (RemoteInterpreterConfig _ _ _ _ _ c) = c
6960
7061persistenceStrategyForConfig :: InterpreterConfig -> Maybe PersistenceStrategy
7162persistenceStrategyForConfig (LocalInterpreterConfig strat _ _ _ _) = Just strat
@@ -84,8 +75,15 @@ printWelcome = do
8475 putStrLn "A full tutorial is available at:"
8576 putStrLn "https://github.com/agentm/project-m36/blob/master/docs/tutd_tutorial.markdown"
8677
78+-- | If the locale is set to ASCII, upgrade it to UTF-8 because tutd outputs UTF-8-encoded attributes. This is especially important in light docker images where the locale data may be missing.
79+setLocaleIfNecessary :: IO ()
80+setLocaleIfNecessary = do
81+ l <- getLocaleEncoding
82+ when (textEncodingName l == "ASCII") (setLocaleEncoding utf8)
83+
8784main :: IO ()
8885main = do
86+ setLocaleIfNecessary
8987 interpreterConfig <- execParser opts
9088 let connInfo = connectionInfoForConfig interpreterConfig
9189 fscheck <- checkFSType (checkFSForConfig interpreterConfig) (fromMaybe NoPersistence (persistenceStrategyForConfig interpreterConfig))
src/bin/benchmark/Handles.hs+25−14
@@ -6,13 +6,15 @@ import Options.Applicative
66import TutorialD.Interpreter
77import TutorialD.Interpreter.Base hiding (Parser, option)
88import qualified Data.Text as T
9+#if __GLASGOW_HASKELL__ < 804
910import Data.Monoid
11+#endif
1012import Control.Monad
1113
1214data HandlesArgs = HandlesArgs {
1315 openCloseCount :: Int,
1416 transactionCount :: Int,
15− dbdir :: FilePath,
17+ dbdir :: FilePath,
1618 tutdSetup :: String,
1719 tutdIterate :: String
1820 }
@@ -38,13 +40,13 @@ parseTutdIterate = strOption (short 'i' <> long "iterate-tutd" <> value "update
3840main :: IO ()
3941main = do
4042 args <- execParser $ info (helper <*> parseArgs) fullDesc
41− replicateM_ (openCloseCount args) (runOpenClose
43+ replicateM_ (openCloseCount args) (runOpenClose
4244 (T.pack (tutdSetup args))
4345 (T.pack (tutdIterate args))
44− (transactionCount args)
46+ (transactionCount args)
4547 (dbdir args))
46−
47−runOpenClose :: T.Text -> T.Text -> Int -> FilePath -> IO ()
48+
49+runOpenClose :: T.Text -> T.Text -> Int -> FilePath -> IO ()
4850runOpenClose tutdSetup' tutdIterate' tCount dbdir' = do
4951 let connInfo = InProcessConnectionInfo (MinimalPersistence dbdir') emptyNotificationCallback []
5052 eConn <- connectProjectM36 connInfo
@@ -54,7 +56,7 @@ runOpenClose tutdSetup' tutdIterate' tCount dbdir' = do
5456 eSess <- createSessionAtHead conn "master"
5557 case eSess of
5658 Left err -> error (show err)
57− Right session ->
59+ Right session ->
5860 --database setup
5961 case parseTutorialD tutdSetup' of
6062 Left err -> error (show err)
@@ -62,14 +64,19 @@ runOpenClose tutdSetup' tutdIterate' tCount dbdir' = do
6264 res <- evalTutorialD session conn UnsafeEvaluation parsed
6365 case res of
6466 DisplayErrorResult err -> error (T.unpack err)
65− DisplayParseErrorResult _ err -> error (parseErrorPretty err)
66− _ -> do
67+ DisplayParseErrorResult _ err ->
68+#if MIN_VERSION_megaparsec(7,0,0)
69+ error (errorBundlePretty err)
70+#else
71+ error (parseErrorPretty err)
72+#endif
73+ _ -> do
6774 replicateM_ tCount (runTransaction tutdIterate' session conn)
6875 close conn
6976 printFdCount
70−
77+
7178runTransaction :: T.Text -> SessionId -> Connection -> IO ()
72−runTransaction tutdIterate' sess conn =
79+runTransaction tutdIterate' sess conn =
7380 --run tutd on every iteration
7481 case parseTutorialD tutdIterate' of
7582 Left err -> error (show err)
@@ -77,10 +84,14 @@ runTransaction tutdIterate' sess conn =
7784 res <- evalTutorialD sess conn UnsafeEvaluation parsed
7885 case res of
7986 DisplayErrorResult err -> error (T.unpack err)
80− DisplayParseErrorResult _ err -> error (parseErrorPretty err)
81− _ -> do
82− eErr <- commit sess conn
87+ DisplayParseErrorResult _ err ->
88+#if MIN_VERSION_megaparsec(7,0,0)
89+ error (errorBundlePretty err)
90+#else
91+ error (parseErrorPretty err)
92+#endif
93+ _ -> do
94+ eErr <- commit sess conn
8395 case eErr of
8496 Left err -> error (show err)
8597 Right _ -> printFdCount
86−
src/bin/benchmark/bigrel.hs+19−8
@@ -1,28 +1,32 @@
1−{-# LANGUAGE FlexibleInstances #-}
1+{-# LANGUAGE FlexibleInstances, CPP #-}
22{-# OPTIONS_GHC -fno-warn-orphans #-}
33import ProjectM36.Base
44import ProjectM36.Relation
55import ProjectM36.DateExamples
66import ProjectM36.Error
7+import ProjectM36.StaticOptimizer
78import qualified ProjectM36.Attribute as A
89import qualified Data.Text as T
910--import ProjectM36.Relation.Show.CSV
1011import ProjectM36.Relation.Show.HTML
11−import TutorialD.Interpreter.DatabaseContextExpr (interpretDatabaseContextExpr)
1212import ProjectM36.RelationalExpression
13+import ProjectM36.TransactionGraph
1314--import qualified Data.HashSet as HS
1415--import qualified Data.ByteString.Lazy.Char8 as BS
1516--import qualified Data.IntMap as IM
1617--import qualified Data.Hashable as Hash
1718import qualified Data.Vector as V
1819import Options.Applicative
19−import qualified Data.Map as M
2020import qualified Data.Text.IO as TIO
2121import System.IO
22−import Control.Monad.State
2322import Control.DeepSeq
2423import Data.Text hiding (map)
24+import Data.Time.Clock
25+import Data.UUID.V4
26+#if __GLASGOW_HASKELL__ < 804
2527import Data.Monoid
28+#endif
29+
2630
2731{-
2832dumpcsv :: Relation -> IO ()
@@ -60,13 +64,20 @@ matrixRun (BigrelArgs attributeCount tupleCount tutd) =
6064 Right rel -> if tutd == "" then
6165 putStrLn "Done."
6266 else do
67+ now <- getCurrentTime
68+ tid <- nextRandom
6369 let setx = Assign "x" (ExistingRelation (force rel))
64− (context,_,_) = execState (evalDatabaseContextExpr setx) (freshDatabaseState dateExamples)
65− interpreted = interpretDatabaseContextExpr context tutd
70+ graph = bootstrapTransactionGraph now tid dateExamples
71+ env = mkDatabaseContextEvalEnv tid graph
72+ eNewState = runDatabaseContextEvalMonad dateExamples env (optimizeAndEvalDatabaseContextExpr True setx)
6673 --plan = interpretRODatabaseContextOp context $ ":showplan " ++ tutd
6774 --displayOpResult plan
68− case interpreted of
69− Right context' -> TIO.putStrLn $ relationAsHTML (relationVariables context' M.! "x")
75+ case eNewState of
76+ Right newState -> do
77+ let ctx = dbc_context newState
78+ Right x = optimizeAndEvalRelationalExpr env' (RelationVariable "x" ())
79+ env' = RelationalExprEnv ctx graph Nothing
80+ TIO.putStrLn $ relationAsHTML x
7081 Left err -> hPrint stderr err
7182
7283{-
src/lib/ProjectM36/Arbitrary.hs+6−1
@@ -9,6 +9,7 @@ import ProjectM36.AtomType
99import ProjectM36.Attribute (atomType)
1010import ProjectM36.DataConstructorDef as DCD
1111import ProjectM36.DataTypes.Interval
12+import ProjectM36.Relation
1213import qualified Data.Vector as V
1314import Data.Text (Text)
1415import Test.QuickCheck
@@ -48,6 +49,10 @@ arbitrary' ByteStringAtomType =
4849
4950arbitrary' BoolAtomType =
5051 Right . BoolAtom <$> lift (arbitrary :: Gen Bool)
52+
53+arbitrary' RelationalExprAtomType =
54+ pure (Right (RelationalExprAtom (ExistingRelation relationTrue))) -- don't bother with arbitrary relational expressions
55+
5156arbitrary' constructedAtomType@(ConstructedAtomType tcName tvMap)
5257 --special-casing for Interval type
5358 | isIntervalAtomType constructedAtomType = createArbitraryInterval (intervalSubType constructedAtomType)
@@ -79,7 +84,7 @@ maybeToRight y Nothing = Left y
7984arbitraryRelationTuple :: Attributes -> WithTCMap Gen (Either RelationalError RelationTuple)
8085arbitraryRelationTuple attris = do
8186 tcMap <- ask
82− listOfMaybeAType <- lift $ mapM ((\aTy -> runReaderT (arbitrary' aTy) tcMap) . atomType) (V.toList attris)
87+ listOfMaybeAType <- lift $ mapM ((\aTy -> runReaderT (arbitrary' aTy) tcMap) . atomType) (V.toList (attributesVec attris))
8388 case sequence listOfMaybeAType of
8489 Left err -> pure $ Left err
8590 Right listOfAttr -> do
src/lib/ProjectM36/Atom.hs+3
@@ -3,7 +3,9 @@ import ProjectM36.Base
33import ProjectM36.Error
44import ProjectM36.DataTypes.Interval
55import qualified Data.Text as T
6+#if __GLASGOW_HASKELL__ < 804
67import Data.Monoid
8+#endif
79
810relationForAtom :: Atom -> Either RelationalError Relation
911relationForAtom (RelationAtom rel) = Right rel
@@ -18,6 +20,7 @@ atomToText (DayAtom i) = (T.pack . show) i
1820atomToText (DateTimeAtom i) = (T.pack . show) i
1921atomToText (ByteStringAtom i) = (T.pack . show) i
2022atomToText (BoolAtom i) = (T.pack . show) i
23+atomToText (RelationalExprAtom re) = (T.pack . show) re
2124
2225atomToText (RelationAtom i) = (T.pack . show) i
2326atomToText (ConstructedAtom dConsName typ atoms)
src/lib/ProjectM36/AtomFunction.hs+19−2
@@ -1,5 +1,7 @@
1+{-# LANGUAGE CPP #-}
12module ProjectM36.AtomFunction where
23import ProjectM36.Base
4+import ProjectM36.Serialise.Base ()
35import ProjectM36.Error
46import ProjectM36.Relation
57import ProjectM36.AtomType
@@ -8,7 +10,8 @@ import ProjectM36.ScriptSession
810import qualified ProjectM36.Attribute as A
911import qualified Data.HashSet as HS
1012import qualified Data.Text as T
11−
13+import qualified Data.ByteString.Lazy as BL
14+import Codec.Winery
1215
1316foldAtomFuncType :: AtomType -> AtomType -> [AtomType]
1417--the underscore in the attribute name means that any attributes are acceptable
@@ -72,7 +75,11 @@ createScriptedAtomFunction funcName argsType retType = AddAtomFunction funcName
7275 retType]])
7376
7477loadAtomFunctions :: ModName -> FuncName -> FilePath -> IO (Either LoadSymbolError [AtomFunction])
78+#ifdef PM36_HASKELL_SCRIPTING
7579loadAtomFunctions = loadFunction
80+#else
81+loadAtomFunctions _ _ _ = pure (Left LoadSymbolError)
82+#endif
7683
7784atomFunctionsAsRelation :: AtomFunctions -> Either RelationalError Relation
7885atomFunctionsAsRelation funcs = mkRelationFromList attrs tups
@@ -81,4 +88,14 @@ atomFunctionsAsRelation funcs = mkRelationFromList attrs tups
8188 Attribute "arguments" TextAtomType]
8289 atomFuncToTuple aFunc = [TextAtom (atomFuncName aFunc),
8390 TextAtom (atomFuncTypeToText aFunc)]
84− atomFuncTypeToText aFunc = T.intercalate " -> " (map prettyAtomType (atomFuncType aFunc))
91+ atomFuncTypeToText aFunc = T.intercalate " -> " (map prettyAtomType (atomFuncType aFunc))
92+
93+--for calculating the merkle hash
94+hashBytes :: AtomFunction -> BL.ByteString
95+hashBytes func = BL.fromChunks [serialise (atomFuncName func),
96+ serialise (atomFuncType func),
97+ bodyBin
98+ ]
99+ where
100+ bodyBin = case atomFuncBody func of
101+ AtomFunctionBody mScript _ -> serialise mScript
src/lib/ProjectM36/AtomFunctionError.hs+1−2
@@ -1,6 +1,5 @@
11{-# LANGUAGE DeriveGeneric, DeriveAnyClass #-}
22module ProjectM36.AtomFunctionError where
3−import Data.Binary
43import GHC.Generics
54import Control.DeepSeq
65import Data.Text
@@ -14,5 +13,5 @@ data AtomFunctionError = AtomFunctionUserError String |
1413 AtomTypeDoesNotSupportOrderingError Text |
1514 AtomTypeDoesNotSupportIntervalError Text |
1615 AtomFunctionBytesDecodingError String
17− deriving(Generic, Eq, Show, Binary, NFData)
16+ deriving(Generic, Eq, Show, NFData)
1817
src/lib/ProjectM36/AtomType.hs+86−14
@@ -139,14 +139,37 @@ resolveAttributeExprTypeVars (AttributeAndTypeNameExpr _ tCons _) aType tConsMap
139139
140140-- check that type vars on the right also appear on the left
141141-- check that the data constructor names are unique
142−validateTypeConstructorDef :: TypeConstructorDef -> [DataConstructorDef] -> [RelationalError]
143−validateTypeConstructorDef tConsDef dConsList = execWriter $ do
142+validateTypeConstructorDef :: TypeConstructorDef -> [DataConstructorDef] -> TypeConstructorMapping -> Either RelationalError ()
143+validateTypeConstructorDef tConsDef dConsList tConsMap = do
144144 let duplicateDConsNames = dupes (L.sort (map DCD.name dConsList))
145− mapM_ tell [map DataConstructorNameInUseError duplicateDConsNames]
145+ unless (null duplicateDConsNames) (Left (someErrors (map DataConstructorNameInUseError duplicateDConsNames)))
146146 let leftSideVars = S.fromList (TCD.typeVars tConsDef)
147147 rightSideVars = S.unions (map DCD.typeVars dConsList)
148148 varsDiff = S.difference leftSideVars rightSideVars
149− mapM_ tell [map DataConstructorUsesUndeclaredTypeVariable (S.toList varsDiff)]
149+ when (S.size varsDiff > 0) (Left (someErrors (map DataConstructorUsesUndeclaredTypeVariable (S.toList varsDiff))))
150+ mapM_ (\dConsDef -> validateDataConstructorDef dConsDef tConsDef tConsMap) dConsList
151+
152+--check that the data constructor names are not in use (recursively)
153+validateDataConstructorDef :: DataConstructorDef -> TypeConstructorDef -> TypeConstructorMapping -> Either RelationalError ()
154+validateDataConstructorDef (DataConstructorDef dConsName dConsDefArgs) tConsDef tConsMap =
155+ case findDataConstructor dConsName tConsMap of
156+ Just _ -> Left (DataConstructorNameInUseError dConsName)
157+ Nothing ->
158+ mapM_ (\arg -> validateDataConstructorDefArg arg tConsDef tConsMap) dConsDefArgs
159+
160+
161+validateDataConstructorDefArg :: DataConstructorDefArg -> TypeConstructorDef -> TypeConstructorMapping -> Either RelationalError ()
162+validateDataConstructorDefArg (DataConstructorDefTypeConstructorArg (PrimitiveTypeConstructor _ _)) _ _ = Right ()
163+validateDataConstructorDefArg (DataConstructorDefTypeConstructorArg (TypeVariable _)) _ _ = Right ()
164+validateDataConstructorDefArg (DataConstructorDefTypeConstructorArg tCons) tConsDef tConsMap = case findTypeConstructor (TC.name tCons) tConsMap of
165+ Nothing ->
166+ when (TC.name tCons /= TCD.name tConsDef) (Left (NoSuchTypeConstructorName (TC.name tCons))) --allows for recursively-defined types
167+ Just (ADTypeConstructorDef _ tConsArgs, _) -> do --validate that the argument count matches- type matching can occur later
168+ let existingCount = length tConsArgs
169+ newCount = length (TC.arguments tCons)
170+ when (newCount /= existingCount) (Left (ConstructedAtomArgumentCountMismatchError existingCount newCount))
171+ Just (PrimitiveTypeConstructorDef _ _, _) -> pure ()
172+validateDataConstructorDefArg (DataConstructorDefTypeVarNameArg _) _ _ = Right ()
150173
151174atomTypeForTypeConstructor :: TypeConstructor -> TypeConstructorMapping -> TypeVarMap -> Either RelationalError AtomType
152175atomTypeForTypeConstructor = atomTypeForTypeConstructorValidate False
@@ -188,7 +211,7 @@ isValidAtomTypeForTypeConstructor (ConstructedAtomType tConsName _) (ADTypeConst
188211
189212isValidAtomTypeForTypeConstructor (RelationAtomType attrs) (RelationAtomTypeConstructor attrExprs) tConsMap = do
190213 evaldAtomTypes <- mapM (\expr -> atomTypeForAttributeExpr expr tConsMap M.empty) attrExprs
191− mapM_ (uncurry resolveAtomType) (zip (map A.atomType (V.toList attrs)) evaldAtomTypes)
214+ mapM_ (uncurry resolveAtomType) (zip (A.atomTypesList attrs) evaldAtomTypes)
192215isValidAtomTypeForTypeConstructor aType tCons _ = Left (AtomTypeTypeConstructorReconciliationError aType (TC.name tCons))
193216
194217findTypeConstructor :: TypeConstructorName -> TypeConstructorMapping -> Maybe (TypeConstructorDef, [DataConstructorDef])
@@ -198,10 +221,18 @@ findTypeConstructor name = foldr tConsFolder Nothing
198221 Just (tCons, dConsList)
199222 else
200223 accum
201−
224+
225+resolveAttributes :: Attribute -> Attribute -> Either RelationalError Attribute
226+resolveAttributes attrA attrB =
227+ if A.attributeName attrA /= A.attributeName attrB then
228+ Left $ AttributeNamesMismatchError (S.fromList (map A.attributeName [attrA, attrB]))
229+ else
230+ Attribute (A.attributeName attrA) <$> resolveAtomType (A.atomType attrA) (A.atomType attrB)
231+
232+--given two atom types, try to resolve type variables
202233resolveAtomType :: AtomType -> AtomType -> Either RelationalError AtomType
203234resolveAtomType (ConstructedAtomType tConsName resolvedTypeVarMap) (ConstructedAtomType _ unresolvedTypeVarMap) =
204− ConstructedAtomType tConsName <$> resolveAtomTypesInTypeVarMap resolvedTypeVarMap unresolvedTypeVarMap
235+ ConstructedAtomType tConsName <$> resolveAtomTypesInTypeVarMap resolvedTypeVarMap unresolvedTypeVarMap
205236resolveAtomType typeFromRelation unresolvedType = if typeFromRelation == unresolvedType then
206237 Right typeFromRelation
207238 else
@@ -229,12 +260,16 @@ resolveAtomTypesInTypeVarMap resolvedTypeMap unresolvedTypeMap = do
229260 let resolveTypePair resKey resType =
230261 -- if the key is missing in the unresolved type map, then fill it in with the value from the resolved map
231262 case M.lookup resKey unresolvedTypeMap of
232− Just unresType -> case unresType of
263+ Just unresType -> case unresType of
233264 --do we need to recurse for RelationAtomType?
234265 subType@(ConstructedAtomType _ _) -> do
235266 resSubType <- resolveAtomType resType subType
236267 pure (resKey, resSubType)
237− _ -> pure (resKey, resType)
268+ TypeVariableType _ -> pure (resKey, resType)
269+ typ -> if typ == resType then
270+ pure (resKey, resType)
271+ else
272+ Left $ AtomTypeMismatchError typ resType
238273 Nothing ->
239274 pure (resKey, resType) --swipe the missing type var from the expected map
240275 tVarList <- mapM (uncurry resolveTypePair) (M.toList resolvedTypeMap)
@@ -260,7 +295,7 @@ resolveTypeInAtom _ atom _ = Right atom
260295-- Example: "Nothing" does not specify the the argument in "Maybe a", so allow delayed resolution in the tuple before it is added to the relation. Note that this resolution could cause a type error. Hardly a Hindley-Milner system.
261296resolveTypesInTuple :: Attributes -> TypeConstructorMapping -> RelationTuple -> Either RelationalError RelationTuple
262297resolveTypesInTuple resolvedAttrs tConss (RelationTuple _ tupAtoms) = do
263− newAtoms <- mapM (\(atom, resolvedType) -> resolveTypeInAtom resolvedType atom tConss) (zip (V.toList tupAtoms) $ map A.atomType (V.toList resolvedAttrs))
298+ newAtoms <- mapM (\(atom, resolvedType) -> resolveTypeInAtom resolvedType atom tConss) (zip (V.toList tupAtoms) $ A.atomTypesList resolvedAttrs)
264299 Right (RelationTuple resolvedAttrs (V.fromList newAtoms))
265300
266301-- | Validate that the type is provided with complete type variables for type constructors.
@@ -279,10 +314,19 @@ validateAtomType typ@(ConstructedAtomType tConsName tVarMap) tConss =
279314 _ -> Right ()
280315validateAtomType (RelationAtomType attrs) tConss =
281316 mapM_ (\attr ->
282− validateAtomType (A.atomType attr) tConss) (V.toList attrs)
317+ validateAtomType (A.atomType attr) tConss) (attributesVec attrs)
283318validateAtomType (TypeVariableType x) _ = Left (TypeConstructorTypeVarMissing x)
284319validateAtomType _ _ = pure ()
285320
321+validateAttributes :: TypeConstructorMapping -> Attributes -> Either RelationalError ()
322+validateAttributes tConss attrs =
323+ if not (null errs) then
324+ Left (someErrors errs)
325+ else
326+ pure ()
327+ where
328+ errs = lefts $ map (`validateAtomType` tConss) (A.atomTypesList attrs)
329+
286330--ensure that all type vars are fully resolved
287331validateTypeVarMap :: TypeVarMap -> TypeConstructorMapping -> Either RelationalError ()
288332validateTypeVarMap tvMap tConss = mapM_ (`validateAtomType` tConss) $ M.elems tvMap
@@ -314,7 +358,7 @@ atomTypeVerify x@(RelationAtomType attrs1) y@(RelationAtomType attrs2) = do
314358 if notElem "_" [name1, name2] && name1 /= name2 then
315359 Left $ AtomTypeMismatchError x y
316360 else
317− atomTypeVerify (A.atomType attr1) (A.atomType attr2)) $ V.toList (V.zip attrs1 attrs2)
361+ atomTypeVerify (A.atomType attr1) (A.atomType attr2)) $ V.toList (V.zip (attributesVec attrs1) (attributesVec attrs2))
318362 return x
319363atomTypeVerify x y = if x == y then
320364 Right x
@@ -323,10 +367,15 @@ atomTypeVerify x y = if x == y then
323367
324368-- | Determine if two typeVars are logically compatible.
325369typeVarMapsVerify :: TypeVarMap -> TypeVarMap -> Bool
326−typeVarMapsVerify a b = M.keysSet a == M.keysSet b && (length . rights) (map (\((_,v1),(_,v2)) -> atomTypeVerify v1 v2) (zip (M.toAscList a) (M.toAscList b))) == M.size a
370+typeVarMapsVerify a b = M.keysSet a == M.keysSet b && (length . rights) zipped == M.size a
371+ where
372+ zipped = zipWith
373+ (curry (\ ((_, v1), (_, v2)) -> atomTypeVerify v1 v2))
374+ (M.toAscList a)
375+ (M.toAscList b)
327376
328377prettyAtomType :: AtomType -> T.Text
329−prettyAtomType (RelationAtomType attrs) = "relation {" `T.append` T.intercalate "," (map prettyAttribute (V.toList attrs)) `T.append` "}"
378+prettyAtomType (RelationAtomType attrs) = "relation {" `T.append` T.intercalate "," (map prettyAttribute (V.toList (attributesVec attrs))) `T.append` "}"
330379prettyAtomType (ConstructedAtomType tConsName typeVarMap) = tConsName `T.append` T.concat (map showTypeVars (M.toList typeVarMap))
331380 where
332381 showTypeVars (_, TypeVariableType x) = " " <> x
@@ -382,3 +431,26 @@ resolvedAtomTypeForDataConstructorDefArg _ tvMap (DataConstructorDefTypeVarNameA
382431 Nothing -> Left (DataConstructorUsesUndeclaredTypeVariable tvName)
383432 Just typ -> Right typ
384433
434+isResolvedType :: AtomType -> Bool
435+isResolvedType typ =
436+ case typ of
437+ IntAtomType -> True
438+ IntegerAtomType -> True
439+ DoubleAtomType -> True
440+ TextAtomType -> True
441+ DayAtomType -> True
442+ DateTimeAtomType -> True
443+ ByteStringAtomType -> True
444+ BoolAtomType -> True
445+ RelationalExprAtomType -> True
446+ RelationAtomType attrs -> isResolvedAttributes attrs
447+ ConstructedAtomType _ tvMap -> all isResolvedType (M.elems tvMap)
448+ TypeVariableType _ -> False
449+
450+isResolvedAttributes :: Attributes -> Bool
451+isResolvedAttributes attrs = all isResolvedAttribute (V.toList (attributesVec attrs))
452+
453+isResolvedAttribute :: Attribute -> Bool
454+isResolvedAttribute = isResolvedType . A.atomType
455+
456+--given two AtomTypes x,y
src/lib/ProjectM36/Atomable.hs+37−54
@@ -13,29 +13,16 @@ import qualified Data.Map as M
1313import qualified Data.Text as T
1414import qualified Data.Vector as V
1515import Control.DeepSeq (NFData)
16−import Data.Binary
1716import Control.Applicative
1817import Data.Time.Calendar
1918import Data.ByteString (ByteString)
2019import Data.Time.Clock
2120import Data.Proxy
2221import qualified Data.List.NonEmpty as NE
22+import Codec.Winery
2323
24−--also add haskell scripting atomable support
25−--rename this module to Atomable along with test
26−
27−{-
28−data Test1T = Test1C Int
29− deriving (Generic, Show, Eq, Binary, NFData, Atomable)
30−
31−data Test2T = Test2C Int Int
32− deriving (Generic, Show, Eq, Binary, NFData, Atomable)
33−
34−data Test3T = Test3Ca | Test3Cb
35− deriving (Generic, Show, Eq, Binary, NFData, Atomable)
36−-}
3724-- | All database values ("atoms") adhere to the 'Atomable' typeclass. This class is derivable allowing new datatypes to be easily marshaling between Haskell values and database values.
38−class (Eq a, NFData a, Binary a, Show a) => Atomable a where
25+class (Eq a, NFData a, Serialise a, Show a) => Atomable a where
3926 toAtom :: a -> Atom
4027 default toAtom :: (Generic a, AtomableG (Rep a)) => a -> Atom
4128 toAtom v = toAtomG (from v) (toAtomTypeG (from v))
@@ -56,7 +43,7 @@ class (Eq a, NFData a, Binary a, Show a) => Atomable a where
5643 -- | Creates DatabaseContextExpr necessary to load the type constructor and data constructor into the database.
5744 toAddTypeExpr :: proxy a -> DatabaseContextExpr
5845 default toAddTypeExpr :: (Generic a, AtomableG (Rep a)) => proxy a -> DatabaseContextExpr
59− toAddTypeExpr _ = toAddTypeExprG (from (undefined :: a)) (toAtomType (Proxy :: Proxy a))
46+ toAddTypeExpr _ = toAddTypeExprG (from (error "insufficient laziness" :: a)) (toAtomType (Proxy :: Proxy a))
6047
6148instance Atomable Integer where
6249 toAtom = IntegerAtom
@@ -148,10 +135,10 @@ instance (Atomable a, Atomable b) => Atomable (Either a b) where
148135--convert to ADT list
149136instance Atomable a => Atomable [a] where
150137 toAtom [] = ConstructedAtom "Empty" (listAtomType (toAtomType (Proxy :: Proxy a))) []
151− toAtom (x:xs) = ConstructedAtom "Cons" (listAtomType (toAtomType (Proxy :: Proxy a))) (map toAtom (x:xs))
138+ toAtom (x:xs) = ConstructedAtom "Cons" (listAtomType (toAtomType (Proxy :: Proxy a))) (toAtom x: [toAtom xs])
152139
153140 fromAtom (ConstructedAtom "Empty" _ _) = []
154− fromAtom (ConstructedAtom "Cons" _ (x:xs)) = fromAtom x:map fromAtom xs
141+ fromAtom (ConstructedAtom "Cons" _ [x,y]) = fromAtom x:fromAtom y
155142 fromAtom _ = error "improper fromAtom [a]"
156143
157144 toAtomType _ = ConstructedAtomType "List" (M.singleton "a" (toAtomType (Proxy :: Proxy a)))
@@ -165,10 +152,6 @@ instance Atomable a => Atomable (NE.NonEmpty a) where
165152 toAtomType _ = ConstructedAtomType "NonEmptyList" (M.singleton "a" (toAtomType (Proxy :: Proxy a)))
166153 toAddTypeExpr _ = NoOperation
167154
168−#if !MIN_VERSION_binary(0,8,4)
169−instance Binary a => Binary (NE.NonEmpty a)
170−#endif
171−
172155-- Generics
173156class AtomableG g where
174157 --type AtomTG g
@@ -184,17 +167,17 @@ class AtomableG g where
184167instance (Datatype c, AtomableG a) => AtomableG (M1 D c a) where
185168 toAtomG (M1 v) = toAtomG v
186169 fromAtomG atom args = M1 <$> fromAtomG atom args
187− toAtomsG = undefined
170+ toAtomsG = error "invalid toAtomsG in M1 D"
188171 toAtomTypeG _ = ConstructedAtomType (T.pack typeName) M.empty -- generics don't allow us to get the type constructor variables- alternatives?
189172 where
190173 typeName = datatypeName (undefined :: M1 D c a x)
191− toAddTypeExprG (M1 v) (ConstructedAtomType tcName _) = AddTypeConstructor tcDef dataConstructors
174+ toAddTypeExprG ~(M1 v) (ConstructedAtomType tcName _) = AddTypeConstructor tcDef dataConstructors
192175 where
193176 tcDef = ADTypeConstructorDef tcName []
194177 dataConstructors = getConstructorsG v
195178 toAddTypeExprG _ _ = NoOperation
196− getConstructorsG (M1 v) = getConstructorsG v
197− getConstructorArgsG = undefined
179+ getConstructorsG ~(M1 v) = getConstructorsG v
180+ getConstructorArgsG = error "invalid getConstructorArgsG in M1 D"
198181
199182--constructor metadata
200183instance (Constructor c, AtomableG a) => AtomableG (M1 C c a) where
@@ -209,11 +192,11 @@ instance (Constructor c, AtomableG a) => AtomableG (M1 C c a) where
209192 Nothing
210193 where
211194 dName = T.pack (conName (undefined :: M1 C c a x))
212− fromAtomG _ _ = error "unsupported generic traversal"
213− toAtomsG = undefined
214− toAtomTypeG = undefined
215− toAddTypeExprG = undefined
216− getConstructorsG (M1 v) = [DataConstructorDef (T.pack dName) dArgs]
195+ fromAtomG _ _ = error "invalid fromAtomG in M1 C"
196+ toAtomsG = error "invalid toAtomsG in M1 C"
197+ toAtomTypeG = error "invalid toAtomTypeG in M1 C"
198+ toAddTypeExprG = error "invalid toAddTypeExprG in M1 C"
199+ getConstructorsG ~(M1 v) = [DataConstructorDef (T.pack dName) dArgs]
217200 where
218201 dName = conName (undefined :: M1 C c a x)
219202 dArgs = getConstructorArgsG v
@@ -225,9 +208,9 @@ instance (Selector c, AtomableG a) => AtomableG (M1 S c a) where
225208 fromAtomG atom args = M1 <$> fromAtomG atom args
226209 toAtomsG (M1 v) = toAtomsG v
227210 toAtomTypeG (M1 v) = toAtomTypeG v
228− toAddTypeExprG _ _ = undefined
229− getConstructorsG = undefined
230− getConstructorArgsG (M1 v) = getConstructorArgsG v
211+ toAddTypeExprG = error "invalid toAddTypeExprG in M1 S"
212+ getConstructorsG = error "invalid getConstructorsG in M1 S"
213+ getConstructorArgsG ~(M1 v) = getConstructorArgsG v
231214
232215-- field data metadata
233216instance (Atomable a) => AtomableG (K1 c a) where
@@ -237,9 +220,9 @@ instance (Atomable a) => AtomableG (K1 c a) where
237220 headatom [] = error "no more atoms for constructor!"
238221 toAtomsG (K1 v) = [toAtom v]
239222 toAtomTypeG _ = toAtomType (Proxy :: Proxy a)
240− toAddTypeExprG _ _ = undefined
241− getConstructorsG = undefined
242− getConstructorArgsG (K1 _) = [DataConstructorDefTypeConstructorArg tCons]
223+ toAddTypeExprG = error "invalid toAddTypeExprG in K1"
224+ getConstructorsG = error "invalid getConstructorsG in K1"
225+ getConstructorArgsG ~(K1 _) = [DataConstructorDefTypeConstructorArg tCons]
243226 where
244227 tCons = typeToTypeConstructor $ toAtomType (Proxy :: Proxy a)
245228
@@ -252,8 +235,9 @@ typeToTypeConstructor x@DayAtomType = PrimitiveTypeConstructor "Day" x
252235typeToTypeConstructor x@DateTimeAtomType = PrimitiveTypeConstructor "DateTime" x
253236typeToTypeConstructor x@ByteStringAtomType = PrimitiveTypeConstructor "ByteString" x
254237typeToTypeConstructor x@BoolAtomType = PrimitiveTypeConstructor "Bool" x
238+typeToTypeConstructor x@RelationalExprAtomType = PrimitiveTypeConstructor "RelationalExpr" x
255239typeToTypeConstructor (RelationAtomType attrs)
256− = RelationAtomTypeConstructor $ map attrToAttrExpr $ V.toList attrs
240+ = RelationAtomTypeConstructor $ map attrToAttrExpr $ V.toList (attributesVec attrs)
257241 where
258242 attrToAttrExpr (Attribute n t) = AttributeAndTypeNameExpr n (typeToTypeConstructor t) ()
259243typeToTypeConstructor (ConstructedAtomType tcName tvMap)
@@ -261,39 +245,38 @@ typeToTypeConstructor (ConstructedAtomType tcName tvMap)
261245typeToTypeConstructor (TypeVariableType tvName) = TypeVariable tvName
262246
263247instance AtomableG U1 where
264− toAtomG = undefined
248+ toAtomG = error "invalid toAtomG in U1"
265249 fromAtomG _ _ = pure U1
266250 toAtomsG _ = []
267− toAtomTypeG = undefined
268− toAddTypeExprG = undefined
269− getConstructorsG = undefined
251+ toAtomTypeG = error "invalid toAtomTypeG in U1"
252+ toAddTypeExprG = error "invalid toAddTypeExprG in U1"
253+ getConstructorsG = error "invalid getConstructorsG in U1"
270254 getConstructorArgsG _ = []
271255
272256-- product types
273257instance (AtomableG a, AtomableG b) => AtomableG (a :*: b) where
274258 toAtomG = undefined
275− fromAtomG atom args = (:*:) <$> fromAtomG atom [headatom args] <*> fromAtomG atom (tailatoms args)
276− where headatom (x:_) = x
277− headatom [] = error "no more atoms in head for product!"
278− tailatoms (_:xs) = xs
279− tailatoms [] = error "no more atoms in tail for product!"
280− toAtomTypeG = undefined
259+ fromAtomG atom args = (:*:) <$> fromAtomG atom splitargs1 <*> fromAtomG atom splitargs2
260+ where splitargs1 = take splitpoint args
261+ splitargs2 = drop splitpoint args
262+ splitpoint = length args `div` 2
263+ toAtomTypeG = error "invalid toAtomTypeG in :*:"
281264 toAtomsG (x :*: y) = toAtomsG x ++ toAtomsG y
282− toAddTypeExprG _ _ = undefined
283− getConstructorsG = undefined
284− getConstructorArgsG (x :*: y) = getConstructorArgsG x ++ getConstructorArgsG y
265+ toAddTypeExprG = error "invalid toAddTypeExprG in :*:"
266+ getConstructorsG = error "invalid getConstructorsG in :*:"
267+ getConstructorArgsG ~(x :*: y) = getConstructorArgsG x ++ getConstructorArgsG y
285268
286269-- sum types
287270instance (AtomableG a, AtomableG b) => AtomableG (a :+: b) where
288271 toAtomG (L1 x) = toAtomG x
289272 toAtomG (R1 x) = toAtomG x
290273 fromAtomG atom args = (L1 <$> fromAtomG atom args) <|> (R1 <$> fromAtomG atom args)
291− toAtomTypeG = undefined
274+ toAtomTypeG = error "invalid toAtomTypeG in :+:"
292275 toAtomsG (L1 x) = toAtomsG x
293276 toAtomsG (R1 x) = toAtomsG x
294− toAddTypeExprG _ _ = undefined
277+ toAddTypeExprG = error "invalid toAddTypeExprG in :+:"
295278 getConstructorsG _ = getConstructorsG (undefined :: a x) ++ getConstructorsG (undefined :: b x)
296− getConstructorArgsG = undefined
279+ getConstructorArgsG = error "invalid getConstructorArgsG in :+:"
297280
298281--this represents the unimplemented generics traversals which should never be called
299282{-
src/lib/ProjectM36/Attribute.hs+148−29
@@ -1,3 +1,4 @@
1+{-# OPTIONS_GHC -fno-warn-orphans #-}
12module ProjectM36.Attribute where
23import ProjectM36.Base
34import ProjectM36.Error
@@ -10,16 +11,54 @@ import qualified Data.Map as M
1011import Data.Either
1112
1213arity :: Attributes -> Int
13−arity = V.length
14+arity a = V.length (attributesVec a)
15+
16+instance Semigroup Attributes where
17+ attrsA <> attrsB =
18+ case joinAttributes attrsA attrsB of
19+ Left err -> error (show err)
20+ Right attrs' -> attrs'
21+
22+instance Monoid Attributes where
23+ mempty = Attributes {
24+ attributesVec = mempty
25+ --,attributeSet = mempty
26+ }
1427
1528emptyAttributes :: Attributes
16−emptyAttributes = V.empty
29+emptyAttributes = mempty
1730
1831null :: Attributes -> Bool
19−null = V.null
32+null a = V.null (attributesVec a)
33+
34+singleton :: Attribute -> Attributes
35+singleton attr = Attributes {
36+ attributesVec = V.singleton attr
37+ --,attributesSet = HS.singleton attr
38+ }
39+
40+toList :: Attributes -> [Attribute]
41+toList attrs = V.toList (attributesVec attrs)
2042
2143attributesFromList :: [Attribute] -> Attributes
22−attributesFromList = V.fromList -- . L.nub --too expensive
44+attributesFromList attrsL = Attributes {
45+ attributesVec = vec
46+ --,attributesSet = hset
47+ }
48+ where
49+ vec = if length attrsL == HS.size hset then
50+ --fast path- no duplicates
51+ V.fromList attrsL
52+ else
53+ --duplicate detected, uniqueify while maintaining original ordering
54+ V.fromList uniquedL
55+ hset = HS.fromList attrsL
56+ uniquedL = fst $ foldr (\attr acc@(l,s) ->
57+ if HS.member attr s then
58+ acc
59+ else
60+ (l ++ [attr], HS.insert attr s))
61+ ([],mempty) attrsL
2362
2463attributeName :: Attribute -> AttributeName
2564attributeName (Attribute name _) = name
@@ -28,17 +67,16 @@ atomType :: Attribute -> AtomType
2867atomType (Attribute _ atype) = atype
2968
3069atomTypes :: Attributes -> V.Vector AtomType
31−atomTypes = V.map atomType
70+atomTypes attrs = V.map atomType (attributesVec attrs)
3271
3372atomTypesList :: Attributes -> [AtomType]
3473atomTypesList = V.toList . atomTypes
3574
36−--hm- no error-checking here
3775addAttribute :: Attribute -> Attributes -> Attributes
38−addAttribute attr attrs = attrs `V.snoc` attr
76+addAttribute attr attrs = attrs <> singleton attr
3977
4078--if some attribute names overlap but the types do not, then spit back an error
41−joinAttributes :: Attributes -> Attributes -> Either RelationalError Attributes
79+{-joinAttributes :: Attributes -> Attributes -> Either RelationalError Attributes
4280joinAttributes attrs1 attrs2 | V.length uniqueOverlappingAttributes /= V.length overlappingAttributes = Left (TupleAttributeTypeMismatchError overlappingAttributes)
4381 | V.length overlappingAttrsDifferentTypes > 0 = Left (TupleAttributeTypeMismatchError overlappingAttrsDifferentTypes)
4482 | otherwise = Right $ vectorUniqueify (attrs1 V.++ attrs2)
@@ -47,20 +85,52 @@ joinAttributes attrs1 attrs2 | V.length uniqueOverlappingAttributes /= V.length
4785 attrNames2 = V.map attributeName attrs2
4886 uniqueOverlappingAttributes = vectorUniqueify overlappingAttributes
4987 overlappingAttributes = V.filter (`V.elem` attrs2) attrs1
88+-}
89+joinAttributes :: Attributes -> Attributes -> Either RelationalError Attributes
90+joinAttributes attrs1 attrs2
91+ | S.size overlappingNames == 0 = -- fast path, no overlapping names
92+ pure (concated id)
93+ | attributesForNames overlappingNames attrs1 == attributesForNames overlappingNames attrs2 = -- that atomtypes match
94+ pure (concated vectorUniqueify)
95+ | otherwise =
96+ --special handling to validate that overlapping names have the same atom types
97+ Left (TupleAttributeTypeMismatchError (attributesForNames overlappingNames attrs1))
98+ where
99+ nameSet1 = attributeNameSet attrs1
100+ nameSet2 = attributeNameSet attrs2
101+ overlappingNames = S.intersection nameSet1 nameSet2
102+ concated f = Attributes {
103+ attributesVec = f (attributesVec attrs1 <> attributesVec attrs2)
104+ --,attributesSet = attributesSet attrs1 <> attributesSet attrs2
105+ }
50106
51107addAttributes :: Attributes -> Attributes -> Attributes
52−addAttributes = (V.++)
108+addAttributes = (<>)
109+
110+member :: Attribute -> Attributes -> Bool
111+member attr attrs = HS.member attr (attributesSet attrs)
53112
54113deleteAttributeName :: AttributeName -> Attributes -> Attributes
55−deleteAttributeName attrName = V.filter (\attr -> attributeName attr /= attrName)
114+deleteAttributeName attrName = deleteAttributeNames (S.singleton attrName)
115+
116+deleteAttributeNames :: S.Set AttributeName -> Attributes -> Attributes
117+deleteAttributeNames attrNames attrs = Attributes {
118+ attributesVec = vec
119+ }
120+ where
121+ vec = V.filter attrFilter (attributesVec attrs)
122+ attrFilter attr = S.notMember (attributeName attr) attrNames
56123
57124renameAttribute :: AttributeName -> Attribute -> Attribute
58125renameAttribute newAttrName (Attribute _ typeo) = Attribute newAttrName typeo
59126
60127renameAttributes :: AttributeName -> AttributeName -> Attributes -> Attributes
61−renameAttributes oldAttrName newAttrName = V.map renamer
128+renameAttributes oldAttrName newAttrName attrs = Attributes {
129+ attributesVec = vec
130+ }
62131 where
63− renamer attr = if attributeName attr == oldAttrName then
132+ vec = V.map renamer (attributesVec attrs)
133+ renamer attr = if attributeName attr == oldAttrName then
64134 renameAttribute newAttrName attr
65135 else
66136 attr
@@ -71,7 +141,7 @@ atomTypeForAttributeName attrName attrs = do
71141 return atype
72142
73143attributeForName :: AttributeName -> Attributes -> Either RelationalError Attribute
74−attributeForName attrName attrs = case V.find (\attr -> attributeName attr == attrName) attrs of
144+attributeForName attrName attrs = case V.find (\attr -> attributeName attr == attrName) (attributesVec attrs) of
75145 Nothing -> Left (NoSuchAttributeNamesError (S.singleton attrName))
76146 Just attr -> Right attr
77147
@@ -89,15 +159,18 @@ projectionAttributesForNames names attrsIn =
89159 missingNames = attributeNamesNotContained names (S.fromList (V.toList (attributeNames attrsIn)))
90160
91161attributesForNames :: S.Set AttributeName -> Attributes -> Attributes
92−attributesForNames attrNameSet = V.filter filt
162+attributesForNames attrNameSet attrs = Attributes {
163+ attributesVec = vec
164+ }
93165 where
166+ vec = V.filter filt (attributesVec attrs)
94167 filt attr = S.member (attributeName attr) attrNameSet
95168
96169attributeNameSet :: Attributes -> S.Set AttributeName
97−attributeNameSet attrVec = S.fromList $ V.toList $ V.map (\(Attribute name _) -> name) attrVec
170+attributeNameSet attrs = S.fromList $ V.toList $ V.map (\(Attribute name _) -> name) (attributesVec attrs)
98171
99172attributeNames :: Attributes -> V.Vector AttributeName
100−attributeNames = V.map attributeName
173+attributeNames attrs = V.map attributeName (attributesVec attrs)
101174
102175--checks if set s1 is wholly contained in the set s2
103176attributesContained :: Attributes -> Attributes -> Bool
@@ -118,42 +191,88 @@ attributeNamesNotContained subset superset = S.filter (`S.notMember` superset) s
118191
119192-- useful for display
120193orderedAttributes :: Attributes -> [Attribute]
121−orderedAttributes attrs = L.sortBy (\a b -> attributeName a `compare` attributeName b) (V.toList attrs)
194+orderedAttributes attrs = L.sortBy (\a b -> attributeName a `compare` attributeName b) (V.toList (attributesVec attrs))
122195
123196orderedAttributeNames :: Attributes -> [AttributeName]
124197orderedAttributeNames attrs = map attributeName (orderedAttributes attrs)
125198
126199-- take two attribute sets and return an attribute set with the attributes which do not match
200+--this is the function which benefits the most from the HashSet representation- this turned up in the insert performance test
127201attributesDifference :: Attributes -> Attributes -> Attributes
128−attributesDifference attrsA attrsB = V.fromList $ diff (V.toList attrsA) (V.toList attrsB)
202+{-attributesDifference attrsA attrsB = V.fromList $ diff (V.toList attrsA) (V.toList attrsB)
129203 where
130204 diff a b = (a L.\\ b) ++ (b L.\\ a)
205+-}
206+attributesDifference attrsA attrsB =
207+ if attributesSet attrsA == attributesSet attrsB then
208+ mempty
209+ else
210+ Attributes {
211+ attributesVec = vec
212+ --,attributesSet = hset
213+ }
214+ where
215+ hset = HS.difference setA setB <> HS.difference setB setA
216+ setA = attributesSet attrsA
217+ setB = attributesSet attrsB
218+ vec = V.filter (`HS.member` hset) (attributesVec attrsA <> attributesVec attrsB)
131219
132220vectorUniqueify :: (Hash.Hashable a, Eq a) => V.Vector a -> V.Vector a
133221vectorUniqueify vecIn = V.fromList $ HS.toList $ HS.fromList $ V.toList vecIn
134222
135223--check that each attribute only appears once
136224verifyAttributes :: Attributes -> Either RelationalError Attributes
137−verifyAttributes attrs = if collapsedAttrs /= attrs then
138− Left (TupleAttributeTypeMismatchError (attributesDifference collapsedAttrs attrs))
139− else
140− Right attrs
225+verifyAttributes attrs =
226+ if vecSet == attributesSet attrs then
227+ pure attrs
228+ else
229+ Left (TupleAttributeTypeMismatchError diffAttrs)
141230 where
142− collapsedAttrs = vectorUniqueify attrs
231+ vecSet = V.foldr' HS.insert HS.empty (attributesVec attrs)
232+ diffSet = HS.difference vecSet (attributesSet attrs) <> HS.difference (attributesSet attrs) vecSet
233+ diffAttrs = Attributes {
234+ attributesVec = V.fromList (HS.toList diffSet)
235+ --,attributesSet = diffSet
236+ }
237+
238+--used in Generics derivation for ADTs without named attributes- not to be used elsewhere
239+--drop first n attributes from vector representation
240+drop :: Int -> Attributes -> Attributes
241+drop c attrs = Attributes { attributesVec = vec
242+ }
243+ where
244+ vec = V.drop c (attributesVec attrs)
245+
246+
247+-- use this in preference to attributesEqual when the attribute ordering matters such as during tuple unions
248+attributesAndOrderEqual :: Attributes -> Attributes -> Bool
249+attributesAndOrderEqual a b = attributesVec a == attributesVec b
143250
251+-- use to determine if the same attributes are contained (but ordering is irrelevant)
144252attributesEqual :: Attributes -> Attributes -> Bool
145−attributesEqual attrs1 attrs2 = V.null (attributesDifference attrs1 attrs2)
253+attributesEqual attrsA attrsB =
254+ attributesVec attrsA == attributesVec attrsB ||
255+ attributesSet attrsA == attributesSet attrsB
146256
147257attributesAsMap :: Attributes -> M.Map AttributeName Attribute
148−attributesAsMap attrs = (M.fromList . V.toList) (V.map (\attr -> (attributeName attr, attr)) attrs)
258+attributesAsMap attrs = V.foldr' (\attr acc -> M.insert (attributeName attr) attr acc) mempty (attributesVec attrs)
259+
149260
150261-- | Left-biased union of attributes.
151262union :: Attributes -> Attributes -> Attributes
152−union attrsA attrsB = V.fromList (M.elems unioned)
263+union attrsA attrsB = Attributes {
264+ attributesVec = vec
265+ --,attributesSet = hset
266+ }
153267 where
154− unioned = M.union (attributesAsMap attrsA) (attributesAsMap attrsB)
268+ hset = HS.union (attributesSet attrsA) (attributesSet attrsB)
269+ vec = HS.foldr (flip V.snoc) mempty hset
155270
156271intersection :: Attributes -> Attributes -> Attributes
157−intersection attrsA attrsB = V.fromList (M.elems intersected)
272+intersection attrsA attrsB = Attributes {
273+ attributesVec = vec
274+ --,attributesSet = hset
275+ }
158276 where
159− intersected = M.intersection (attributesAsMap attrsA) (attributesAsMap attrsB)
277+ hset = HS.intersection (attributesSet attrsA) (attributesSet attrsB)
278+ vec = HS.foldr (flip V.snoc) mempty hset
src/lib/ProjectM36/AttributeNames.hs+3−2
@@ -3,8 +3,9 @@ import ProjectM36.Base
33import qualified Data.Set as S
44--AttributeNames is a data structure which can represent inverted projection attributes and attribute names derived from relational expressions
55
6−empty :: AttributeNames
6+empty :: AttributeNamesBase a
77empty = AttributeNames S.empty
88
9−all :: AttributeNames
9+all :: AttributeNamesBase a
1010all = InvertedAttributeNames S.empty
11+
src/lib/ProjectM36/Base.hs+189−113
@@ -1,10 +1,12 @@
1−{-# LANGUAGE ExistentialQuantification,DeriveGeneric,DeriveAnyClass,TypeSynonymInstances,FlexibleInstances,OverloadedStrings #-}
1+{-# LANGUAGE ExistentialQuantification,DeriveGeneric,DeriveAnyClass,FlexibleInstances,OverloadedStrings, DeriveTraversable, DerivingVia, TemplateHaskell, TypeFamilies #-}
22{-# OPTIONS_GHC -fno-warn-orphans #-}
33
44module ProjectM36.Base where
55import ProjectM36.DatabaseContextFunctionError
66import ProjectM36.AtomFunctionError
7+import ProjectM36.MerkleHash
78
9+import Data.Functor.Foldable.TH
810import qualified Data.Map as M
911import qualified Data.HashSet as HS
1012import Data.Hashable (Hashable, hashWithSalt)
@@ -13,18 +15,21 @@ import Data.UUID (UUID)
1315import Control.DeepSeq (NFData, rnf)
1416import Control.DeepSeq.Generics (genericRnf)
1517import GHC.Generics (Generic)
18+import GHC.Stack
1619import qualified Data.Vector as V
1720import qualified Data.List as L
1821import Data.Text (Text,unpack)
19−import Data.Binary
20−import Data.Vector.Binary()
2122import Data.Time.Clock
22−import Data.Time.Clock.POSIX
23−import Data.Time.Calendar (Day,toGregorian,fromGregorian)
2423import Data.Hashable.Time ()
24+import Data.Time.Calendar (Day)
2525import Data.Typeable
2626import Data.ByteString (ByteString)
27+import qualified Data.List.NonEmpty as NE
28+import Data.Vector.Instances ()
29+
2730type StringType = Text
31+
32+type DatabaseName = String
2833
2934-- | Database atoms are the smallest, undecomposable units of a tuple. Common examples are integers, text, or unique identity keys.
3035data Atom = IntegerAtom Integer |
@@ -36,8 +41,9 @@ data Atom = IntegerAtom Integer |
3641 ByteStringAtom ByteString |
3742 BoolAtom Bool |
3843 RelationAtom Relation |
44+ RelationalExprAtom RelationalExpr | --used for returning inc deps
3945 ConstructedAtom DataConstructorName AtomType [Atom]
40− deriving (Eq, Show, Binary, Typeable, NFData, Generic)
46+ deriving (Eq, Show, Typeable, NFData, Generic, Read)
4147
4248instance Hashable Atom where
4349 hashWithSalt salt (ConstructedAtom dConsName _ atoms) = salt `hashWithSalt` atoms
@@ -51,16 +57,7 @@ instance Hashable Atom where
5157 hashWithSalt salt (ByteStringAtom bs) = salt `hashWithSalt` bs
5258 hashWithSalt salt (BoolAtom b) = salt `hashWithSalt` b
5359 hashWithSalt salt (RelationAtom r) = salt `hashWithSalt` r
54−
55−instance Binary UTCTime where
56− put utc = put $ toRational (utcTimeToPOSIXSeconds utc)
57− get = posixSecondsToUTCTime . fromRational <$> (get :: Get Rational)
58−
59−instance Binary Day where
60− put day = put $ toGregorian day
61− get = do
62− (y,m,d) <- get :: Get (Integer, Int, Int)
63− return (fromGregorian y m d)
60+ hashWithSalt salt (RelationalExprAtom re) = salt `hashWithSalt` re
6461
6562-- I suspect the definition of ConstructedAtomType with its name alone is insufficient to disambiguate the cases; for example, one could create a type named X, remove a type named X, and re-add it using different constructors. However, as long as requests are served from only one DatabaseContext at-a-time, the type name is unambiguous. This will become a problem for time-travel, however.
6663-- | The AtomType uniquely identifies the type of a atom.
@@ -74,12 +71,15 @@ data AtomType = IntAtomType |
7471 BoolAtomType |
7572 RelationAtomType Attributes |
7673 ConstructedAtomType TypeConstructorName TypeVarMap |
74+ RelationalExprAtomType |
7775 TypeVariableType TypeVarName
7876 --wildcard used in Atom Functions and tuples for data constructors which don't provide all arguments to the type constructor
79− deriving (Eq, NFData, Generic, Binary, Show)
77+ deriving (Eq, NFData, Generic, Show, Read, Hashable)
8078
8179instance Ord AtomType where
82− compare = undefined
80+ compare = undefined
81+
82+-- this should probably be an ordered dictionary in order to be able to round-trip these arguments
8383type TypeVarMap = M.Map TypeVarName AtomType
8484
8585instance Hashable TypeVarMap where
@@ -94,25 +94,37 @@ isRelationAtomType _ = False
9494type AttributeName = StringType
9595
9696-- | A relation's type is composed of attribute names and types.
97−data Attribute = Attribute AttributeName AtomType deriving (Eq, Show, Generic, NFData, Binary)
97+data Attribute = Attribute AttributeName AtomType deriving (Eq, Show, Read, Generic, NFData)
9898
9999instance Hashable Attribute where
100100 hashWithSalt salt (Attribute attrName _) = hashWithSalt salt attrName
101101
102+type AttributesHash = Int
103+
102104-- | 'Attributes' represent the head of a relation.
103−type Attributes = V.Vector Attribute
105+newtype Attributes = Attributes {
106+ attributesVec :: V.Vector Attribute
107+ --,attributesSet :: HS.HashSet Attribute --compare with this generated in heap profile and benchmarks
108+ }
109+ deriving (NFData, Read, Hashable, Generic)
110+
111+attributesSet :: Attributes -> HS.HashSet Attribute
112+attributesSet = HS.fromList . V.toList . attributesVec
113+
114+instance Show Attributes where
115+ show attrs = "attributesFromList [" <> L.intercalate ", " (map (\attr -> "(" <> show attr <> ")") (V.toList (attributesVec attrs))) <> "]"
116+
117+--when attribute ordering is irrelevant
118+instance Eq Attributes where
119+ attrsA == attrsB =
120+ attributesVec attrsA == attributesVec attrsB ||
121+ attributesSet attrsA == attributesSet attrsB
104122
105−-- | Equality function for a set of attributes.
106−attributesEqual :: Attributes -> Attributes -> Bool
107−attributesEqual attrs1 attrs2 = attrsAsSet attrs1 == attrsAsSet attrs2
108− where
109− attrsAsSet = HS.fromList . V.toList
110−
111123sortedAttributesIndices :: Attributes -> [(Int, Attribute)]
112−sortedAttributesIndices attrs = L.sortBy (\(_, Attribute name1 _) (_,Attribute name2 _) -> compare name1 name2) $ V.toList (V.indexed attrs)
124+sortedAttributesIndices attrs = L.sortBy (\(_, Attribute name1 _) (_,Attribute name2 _) -> compare name1 name2) $ V.toList (V.indexed (attributesVec attrs))
113125
114126-- | The relation's tuple set is the body of the relation.
115−newtype RelationTupleSet = RelationTupleSet { asList :: [RelationTuple] } deriving (Hashable, Show, Generic, Binary)
127+newtype RelationTupleSet = RelationTupleSet { asList :: [RelationTuple] } deriving (Hashable, Show, Generic, Read)
116128
117129instance Read Relation where
118130 readsPrec = error "relation read not supported"
@@ -128,8 +140,8 @@ instance NFData RelationTupleSet where rnf = genericRnf
128140instance Hashable RelationTuple where
129141 --sanity check the tuple for attribute and tuple counts
130142 --this bit me when tuples were being hashed before being verified
131− hashWithSalt salt (RelationTuple attrs tupVec) = if V.length attrs /= V.length tupVec then
132− error "invalid tuple: attributes and tuple count mismatch"
143+ hashWithSalt salt (RelationTuple attrs tupVec) = if V.length (attributesVec attrs) /= V.length tupVec then
144+ error ("invalid tuple: attributes and tuple count mismatch " <> show (attributesVec attrs, tupVec))
133145 else
134146 salt `hashWithSalt`
135147 sortedAttrs `hashWithSalt`
@@ -140,25 +152,23 @@ instance Hashable RelationTuple where
140152 sortedTupVec = V.map (\(index, _) -> tupVec V.! index) $ V.fromList sortedAttrsIndices
141153
142154-- | A tuple is a set of attributes mapped to their 'Atom' values.
143−data RelationTuple = RelationTuple Attributes (V.Vector Atom) deriving (Show, Generic)
144−
145−instance Binary RelationTuple
155+data RelationTuple = RelationTuple Attributes (V.Vector Atom) deriving (Show, Read, Generic)
146156
147157instance Eq RelationTuple where
148− (==) tuple1@(RelationTuple attrs1 _) tuple2@(RelationTuple attrs2 _) = attributesEqual attrs1 attrs2 && atomsEqual
158+ tuple1@(RelationTuple attrs1 _) == tuple2@(RelationTuple attrs2 _) =
159+ attrs1 == attrs2 && atomsEqual
149160 where
150− atomForAttribute attr (RelationTuple attrs tupVec) = case V.findIndex (== attr) attrs of
161+ atomForAttribute attr (RelationTuple attrs tupVec) = case V.findIndex (== attr) (attributesVec attrs) of
151162 Nothing -> Nothing
152163 Just index -> tupVec V.!? index
153− atomsEqual = V.all (== True) $ V.map (\attr -> atomForAttribute attr tuple1 == atomForAttribute attr tuple2) attrs1
164+ atomsEqual = V.all (== True) $ V.map (\attr -> atomForAttribute attr tuple1 == atomForAttribute attr tuple2) (attributesVec attrs1)
154165
155166instance NFData RelationTuple where rnf = genericRnf
156167
157−
158168data Relation = Relation Attributes RelationTupleSet deriving (Show, Generic,Typeable)
159169
160170instance Eq Relation where
161− Relation attrs1 tupSet1 == Relation attrs2 tupSet2 = attributesEqual attrs1 attrs2 && tupSet1 == tupSet2
171+ Relation attrs1 tupSet1 == Relation attrs2 tupSet2 = attrs1 == attrs2 && tupSet1 == tupSet2
162172
163173instance NFData Relation where rnf = genericRnf
164174
@@ -169,8 +179,6 @@ instance Hashable Relation where
169179 where
170180 sortedAttrs = map snd (sortedAttributesIndices attrs)
171181
172−instance Binary Relation
173−
174182-- | Used to represent the number of tuples in a relation.
175183data RelationCardinality = Countable | Finite Int deriving (Eq, Show, Generic, Ord)
176184
@@ -182,7 +190,7 @@ type RelationalExpr = RelationalExprBase ()
182190-- | A relational expression represents query (read) operations on a database.
183191data RelationalExprBase a =
184192 --- | Create a relation from tuple expressions.
185− MakeRelationFromExprs (Maybe [AttributeExprBase a]) [TupleExprBase a] |
193+ MakeRelationFromExprs (Maybe [AttributeExprBase a]) (TupleExprsBase a) |
186194 --- | Create and reference a relation from attributes and a tuple set.
187195 MakeStaticRelation Attributes RelationTupleSet |
188196 --- | Reference an existing relation in Haskell-space.
@@ -191,7 +199,7 @@ data RelationalExprBase a =
191199 --in Tutorial D, relational variables pick up the type of the first relation assigned to them
192200 --relational variables should also be able to be explicitly-typed like in Haskell
193201 --- | Reference a relation variable by its name.
194− RelationVariable RelVarName a |
202+ RelationVariable RelVarName a |
195203 --- | Create a projection over attribute names. (Note that the 'AttributeNames' structure allows for the names to be inverted.)
196204 Project (AttributeNamesBase a) (RelationalExprBase a) |
197205 --- | Create a union of two relational expressions. The expressions should have identical attributes.
@@ -214,11 +222,18 @@ data RelationalExprBase a =
214222 Extend (ExtendTupleExprBase a) (RelationalExprBase a) |
215223 --Summarize :: AtomExpr -> AttributeName -> RelationalExpr -> RelationalExpr -> RelationalExpr -- a special case of Extend
216224 --Evaluate relationalExpr with scoped views
217− With [(RelVarName,RelationalExprBase a)] (RelationalExprBase a)
218− deriving (Show, Eq, Generic, NFData)
219−
220−instance Binary RelationalExpr
221−
225+ With [(WithNameExprBase a, RelationalExprBase a)] (RelationalExprBase a)
226+ deriving (Show, Read, Eq, Generic, NFData, Foldable, Functor, Traversable)
227+
228+instance Hashable RelationalExpr
229+
230+data WithNameExprBase a = WithNameExpr RelVarName a
231+ deriving (Show, Read, Eq, Generic, NFData, Foldable, Functor, Traversable, Hashable)
232+
233+type WithNameExpr = WithNameExprBase ()
234+
235+type GraphRefWithNameExpr = WithNameExprBase GraphRefTransactionMarker
236+
222237type NotificationName = StringType
223238type Notifications = M.Map NotificationName Notification
224239
@@ -228,22 +243,22 @@ data Notification = Notification {
228243 reportOldExpr :: RelationalExpr, --run the expression in the pre-change context
229244 reportNewExpr :: RelationalExpr --run the expression in the post-change context
230245 }
231− deriving (Show, Eq, Binary, Generic, NFData)
246+ deriving (Show, Eq, Generic, NFData)
232247
233248type TypeVarName = StringType
234249
235250-- | Metadata definition for type constructors such as @data Either a b@.
236251data TypeConstructorDef = ADTypeConstructorDef TypeConstructorName [TypeVarName] |
237252 PrimitiveTypeConstructorDef TypeConstructorName AtomType
238− deriving (Show, Generic, Binary, Eq, NFData)
253+ deriving (Show, Generic, Eq, NFData, Hashable, Read)
239254
240255-- | Found in data constructors and type declarations: Left (Either Int Text) | Right Int
241256type TypeConstructor = TypeConstructorBase ()
242257data TypeConstructorBase a = ADTypeConstructor TypeConstructorName [TypeConstructor] |
243− PrimitiveTypeConstructor TypeConstructorName AtomType |
244− RelationAtomTypeConstructor [AttributeExprBase a] |
245− TypeVariable TypeVarName
246− deriving (Show, Generic, Binary, Eq, NFData)
258+ PrimitiveTypeConstructor TypeConstructorName AtomType |
259+ RelationAtomTypeConstructor [AttributeExprBase a] |
260+ TypeVariable TypeVarName
261+ deriving (Show, Generic, Eq, NFData, Hashable, Read)
247262
248263type TypeConstructorMapping = [(TypeConstructorDef, DataConstructorDefs)]
249264
@@ -253,16 +268,23 @@ type DataConstructorName = StringType
253268type AtomTypeName = StringType
254269
255270-- | Used to define a data constructor in a type constructor context such as @Left a | Right b@
256−data DataConstructorDef = DataConstructorDef DataConstructorName [DataConstructorDefArg] deriving (Eq, Show, Binary, Generic, NFData)
271+data DataConstructorDef = DataConstructorDef DataConstructorName [DataConstructorDefArg] deriving (Eq, Show, Generic, NFData, Hashable, Read)
257272
258273type DataConstructorDefs = [DataConstructorDef]
259274
260275data DataConstructorDefArg = DataConstructorDefTypeConstructorArg TypeConstructor |
261276 DataConstructorDefTypeVarNameArg TypeVarName
262− deriving (Show, Generic, Binary, Eq, NFData)
277+ deriving (Show, Generic, Eq, NFData, Hashable, Read)
263278
264279type InclusionDependencies = M.Map IncDepName InclusionDependency
265−type RelationVariables = M.Map RelVarName Relation
280+type RelationVariables = M.Map RelVarName GraphRefRelationalExpr
281+
282+data GraphRefTransactionMarker = TransactionMarker TransactionId |
283+ UncommittedContextMarker
284+ deriving (Eq, Show, Generic, NFData, Ord)
285+
286+-- a fundamental relational expr to which other relational expressions compile
287+type GraphRefRelationalExpr = RelationalExprBase GraphRefTransactionMarker
266288
267289type SchemaName = StringType
268290
@@ -270,17 +292,18 @@ type Subschemas = M.Map SchemaName Schema
270292
271293-- | Every transaction has one concrete database context and any number of isomorphic subschemas.
272294data Schemas = Schemas DatabaseContext Subschemas
295+ deriving (Generic)
273296
274297-- | The DatabaseContext is a snapshot of a database's evolving state and contains everything a database client can change over time.
275298-- I spent some time thinking about whether the VirtualDatabaseContext/Schema and DatabaseContext data constructors should be the same constructor, but that would allow relation variables to be created in a "virtual" context which would appear to defeat the isomorphisms of the contexts. It should be possible to switch to an alternative schema to view the same equivalent information without information loss. However, allowing all contexts to reference another context while maintaining its own relation variables, new types, etc. could be interesting from a security perspective. For example, if a user creates a new relvar in a virtual context, then does it necessarily appear in all linked contexts? After deliberation, I think the relvar should appear in *all* linked contexts to retain the isomorphic properties, even when the isomorphism is for a subset of the context. This hints that the IsoMorphs should allow for "fall-through"; that is, when a relvar is not defined in the virtual context (for morphing), then the lookup should fall through to the underlying context.
276299newtype Schema = Schema SchemaIsomorphs
277− deriving (Generic, Binary)
300+ deriving (Generic)
278301
279302data SchemaIsomorph = IsoRestrict RelVarName RestrictionPredicateExpr (RelVarName, RelVarName) |
280303 IsoRename RelVarName RelVarName |
281304 IsoUnion (RelVarName, RelVarName) RestrictionPredicateExpr RelVarName --maps two relvars to one relvar
282305 -- IsoTypeConstructor in morphAttrExpr
283− deriving (Generic, Binary, Show)
306+ deriving (Generic, Show)
284307
285308type SchemaIsomorphs = [SchemaIsomorph]
286309
@@ -296,24 +319,28 @@ data DatabaseContext = DatabaseContext {
296319type IncDepName = StringType
297320
298321-- | Inclusion dependencies represent every possible database constraint. Constraints enforce specific, arbitrarily-complex rules to which the database context's relation variables must adhere unconditionally.
299−data InclusionDependency = InclusionDependency RelationalExpr RelationalExpr deriving (Show, Eq, Generic, NFData)
300−
301−instance Binary InclusionDependency
322+data InclusionDependency = InclusionDependency RelationalExpr RelationalExpr deriving (Show, Eq, Generic, NFData, Hashable, Read)
302323
303324type AttributeNameAtomExprMap = M.Map AttributeName AtomExpr
304325
305326--used for returning information about individual expressions
306327type DatabaseContextExprName = StringType
307328
329+type DatabaseContextExpr = DatabaseContextExprBase ()
330+
331+instance Hashable DatabaseContextExpr
332+
333+type GraphRefDatabaseContextExpr = DatabaseContextExprBase GraphRefTransactionMarker
334+
308335-- | Database context expressions modify the database context.
309−data DatabaseContextExpr =
336+data DatabaseContextExprBase a =
310337 NoOperation |
311− Define RelVarName [AttributeExpr] |
338+ Define RelVarName [AttributeExprBase a] |
312339 Undefine RelVarName | --forget existence of relvar X
313− Assign RelVarName RelationalExpr |
314− Insert RelVarName RelationalExpr |
315− Delete RelVarName RestrictionPredicateExpr |
316− Update RelVarName AttributeNameAtomExprMap RestrictionPredicateExpr |
340+ Assign RelVarName (RelationalExprBase a) |
341+ Insert RelVarName (RelationalExprBase a) |
342+ Delete RelVarName (RestrictionPredicateExprBase a) |
343+ Update RelVarName AttributeNameAtomExprMap (RestrictionPredicateExprBase a) |
317344
318345 AddInclusionDependency IncDepName InclusionDependency |
319346 RemoveInclusionDependency IncDepName |
@@ -329,24 +356,36 @@ data DatabaseContextExpr =
329356
330357 RemoveDatabaseContextFunction DatabaseContextFunctionName |
331358
332− ExecuteDatabaseContextFunction DatabaseContextFunctionName [AtomExpr] |
359+ ExecuteDatabaseContextFunction DatabaseContextFunctionName [AtomExprBase a] |
333360
334− MultipleExpr [DatabaseContextExpr]
335− deriving (Show, Eq, Binary, Generic)
361+ MultipleExpr [DatabaseContextExprBase a]
362+ deriving (Show, Read, Eq, Generic, NFData)
363+
364+instance Hashable (M.Map AttributeName AtomExpr) where
365+ hashWithSalt salt m = salt `hashWithSalt` M.toList m
336366
337367type ObjModuleName = StringType
338368type ObjFunctionName = StringType
339369type Range = (Int,Int)
340370-- | Adding an atom function should be nominally a DatabaseExpr except for the fact that it cannot be performed purely. Thus, we create the DatabaseContextIOExpr.
341−data DatabaseContextIOExpr = AddAtomFunction AtomFunctionName [TypeConstructor] AtomFunctionBodyScript |
342− LoadAtomFunctions ObjModuleName ObjFunctionName FilePath |
343− AddDatabaseContextFunction DatabaseContextFunctionName [TypeConstructor] DatabaseContextFunctionBodyScript |
344− LoadDatabaseContextFunctions ObjModuleName ObjFunctionName FilePath |
345− CreateArbitraryRelation RelVarName [AttributeExpr] Range
346− deriving (Show, Eq, Generic, Binary)
371+data DatabaseContextIOExprBase a =
372+ AddAtomFunction AtomFunctionName [TypeConstructor] AtomFunctionBodyScript |
373+ LoadAtomFunctions ObjModuleName ObjFunctionName FilePath |
374+ AddDatabaseContextFunction DatabaseContextFunctionName [TypeConstructor] DatabaseContextFunctionBodyScript |
375+ LoadDatabaseContextFunctions ObjModuleName ObjFunctionName FilePath |
376+ CreateArbitraryRelation RelVarName [AttributeExprBase a] Range
377+ deriving (Show, Eq, Generic)
378+
379+type GraphRefDatabaseContextIOExpr = DatabaseContextIOExprBase GraphRefTransactionMarker
380+
381+type DatabaseContextIOExpr = DatabaseContextIOExprBase ()
347382
348383type RestrictionPredicateExpr = RestrictionPredicateExprBase ()
349384
385+instance Hashable RestrictionPredicateExpr
386+
387+type GraphRefRestrictionPredicateExpr = RestrictionPredicateExprBase GraphRefTransactionMarker
388+
350389-- | Restriction predicates are boolean algebra components which, when composed, indicate whether or not a tuple should be retained during a restriction (filtering) operation.
351390data RestrictionPredicateExprBase a =
352391 TruePredicate |
@@ -356,9 +395,7 @@ data RestrictionPredicateExprBase a =
356395 RelationalExprPredicate (RelationalExprBase a) | --type must be same as true and false relations (no attributes)
357396 AtomExprPredicate (AtomExprBase a) | --atom must evaluate to boolean
358397 AttributeEqualityPredicate AttributeName (AtomExprBase a) -- relationalexpr must result in relation with single tuple
359− deriving (Show, Eq, Generic, NFData)
360−
361−instance Binary RestrictionPredicateExpr
398+ deriving (Show, Read, Eq, Generic, NFData, Foldable, Functor, Traversable)
362399
363400-- child + parent links
364401-- | A transaction graph's head name references the leaves of the transaction graph and can be used during session creation to indicate at which point in the graph commits should persist.
@@ -368,32 +405,42 @@ type TransactionHeads = M.Map HeadName Transaction
368405
369406-- | The transaction graph is the global database's state which references every committed transaction.
370407data TransactionGraph = TransactionGraph TransactionHeads (S.Set Transaction)
371−
372−transactionsForGraph :: TransactionGraph -> S.Set Transaction
373−transactionsForGraph (TransactionGraph _ t) = t
408+ deriving Generic
374409
375410transactionHeadsForGraph :: TransactionGraph -> TransactionHeads
376−transactionHeadsForGraph (TransactionGraph heads _) = heads
411+transactionHeadsForGraph (TransactionGraph hs _) = hs
412+
413+transactionsForGraph :: TransactionGraph -> S.Set Transaction
414+transactionsForGraph (TransactionGraph _ ts) = ts
377415
378416-- | Every transaction has context-specific information attached to it.
379−data TransactionInfo = TransactionInfo TransactionId (S.Set TransactionId) UTCTime | -- 1 parent + n children
380− MergeTransactionInfo TransactionId TransactionId (S.Set TransactionId) UTCTime -- 2 parents, n children
381− deriving(Show, Generic)
382−
383−instance Binary TransactionInfo
417+-- The `TransactionDiff`s represent child/edge relationships to previous transactions (branches or continuations of the same branch).
418+data TransactionInfo = TransactionInfo {
419+ parents :: TransactionParents,
420+ stamp :: UTCTime,
421+ merkleHash :: MerkleHash
422+ } deriving (Show, Generic)
423+
424+type TransactionParents = NE.NonEmpty TransactionId
425+{-
426+data TransactionInfo = TransactionInfo TransactionId TransactionDiffs UTCTime | -- 1 parent + n children
427+ MergeTransactionInfo TransactionId TransactionId TransactionDiffs UTCTime -- 2 parents, n children
428+ deriving (Show, Generic)
429+-}
384430
385431-- | Every set of modifications made to the database are atomically committed to the transaction graph as a transaction.
386432type TransactionId = UUID
387433
388434data Transaction = Transaction TransactionId TransactionInfo Schemas
435+ deriving Generic
389436
390−--instance Binary Transaction
391−
437+-- | The disconnected transaction represents an in-progress workspace used by sessions before changes are committed. This is similar to git's "index". After a transaction is committed, it is "connected" in the transaction graph and can no longer be modified.
438+data DisconnectedTransaction = DisconnectedTransaction TransactionId Schemas DirtyFlag
439+--the database context expression represents a difference between the disconnected transaction and its immutable parent transaction- is this diff expr used at all?
440+
392441type DirtyFlag = Bool
393442
394−-- | The disconnected transaction represents an in-progress workspace used by sessions before changes are committed. This is similar to git's "index". After a transaction is committed, it is "connected" in the transaction graph and can no longer be modified.
395−data DisconnectedTransaction = DisconnectedTransaction TransactionId Schemas DirtyFlag --parentID, context- the context here represents the singular concrete context from the schema
396−--the dirty flag indicates that the database context has diverged from its parent's context
443+type TransactionDiffExpr = DatabaseContextExpr
397444
398445transactionId :: Transaction -> TransactionId
399446transactionId (Transaction tid _ _) = tid
@@ -409,24 +456,28 @@ instance Ord Transaction where
409456
410457type AtomExpr = AtomExprBase ()
411458
459+instance Hashable AtomExpr
460+
461+type GraphRefAtomExpr = AtomExprBase GraphRefTransactionMarker
462+
412463-- | An atom expression represents an action to take when extending a relation or when statically defining a relation or a new tuple.
413464data AtomExprBase a = AttributeAtomExpr AttributeName |
414465 NakedAtomExpr Atom |
415466 FunctionAtomExpr AtomFunctionName [AtomExprBase a] a |
416467 RelationAtomExpr (RelationalExprBase a) |
417468 ConstructedAtomExpr DataConstructorName [AtomExprBase a] a
418− deriving (Eq,Show,Generic, NFData)
469+ deriving (Eq, Show, Read, Generic, NFData, Foldable, Functor, Traversable)
419470
420−instance Binary AtomExpr
421−
422471-- | Used in tuple creation when creating a relation.
423472data ExtendTupleExprBase a = AttributeExtendTupleExpr AttributeName (AtomExprBase a)
424− deriving (Show, Eq, Generic, NFData)
473+ deriving (Show, Read, Eq, Generic, NFData, Foldable, Functor, Traversable)
425474
426−type ExtendTupleExpr = ExtendTupleExprBase ()
475+type ExtendTupleExpr = ExtendTupleExprBase ()
476+
477+instance Hashable ExtendTupleExpr
478+
479+type GraphRefExtendTupleExpr = ExtendTupleExprBase GraphRefTransactionMarker
427480
428−instance Binary ExtendTupleExpr
429−
430481--enumerates the list of functions available to be run as part of tuple expressions
431482type AtomFunctions = HS.HashSet AtomFunction
432483
@@ -437,6 +488,7 @@ type AtomFunctionBodyScript = StringType
437488type AtomFunctionBodyType = [Atom] -> Either AtomFunctionError Atom
438489
439490data AtomFunctionBody = AtomFunctionBody (Maybe AtomFunctionBodyScript) AtomFunctionBodyType
491+ deriving Generic
440492
441493instance NFData AtomFunctionBody where
442494 rnf (AtomFunctionBody mScript _) = rnf mScript
@@ -471,11 +523,17 @@ data AttributeNamesBase a = AttributeNames (S.Set AttributeName) |
471523 UnionAttributeNames (AttributeNamesBase a) (AttributeNamesBase a) |
472524 IntersectAttributeNames (AttributeNamesBase a) (AttributeNamesBase a) |
473525 RelationalExprAttributeNames (RelationalExprBase a) -- use attribute names from the relational expression's type
474− deriving (Eq, Show, Generic, NFData)
526+ deriving (Eq, Show, Read, Generic, NFData, Foldable, Functor, Traversable)
527+
528+instance Hashable AttributeNames
529+
530+instance Hashable (S.Set AttributeName) where
531+ hashWithSalt salt s = salt `hashWithSalt` S.toList s
475532
476−type AttributeNames = AttributeNamesBase ()
477−instance Binary AttributeNames
478−
533+type AttributeNames = AttributeNamesBase ()
534+
535+type GraphRefAttributeNames = AttributeNamesBase GraphRefTransactionMarker
536+
479537-- | The persistence strategy is a global database option which represents how to persist the database in the filesystem, if at all.
480538data PersistenceStrategy = NoPersistence | -- ^ no filesystem persistence/memory-only database
481539 MinimalPersistence FilePath | -- ^ fsync off, not crash-safe
@@ -483,19 +541,31 @@ data PersistenceStrategy = NoPersistence | -- ^ no filesystem persistence/memory
483541 deriving (Show, Read)
484542
485543type AttributeExpr = AttributeExprBase ()
544+type GraphRefAttributeExpr = AttributeExprBase GraphRefTransactionMarker
486545
487546-- | Create attributes dynamically.
488547data AttributeExprBase a = AttributeAndTypeNameExpr AttributeName TypeConstructor a |
489548 NakedAttributeExpr Attribute
490− deriving (Eq, Show, Generic, Binary, NFData)
549+ deriving (Eq, Show, Read, Generic, NFData, Foldable, Functor, Traversable, Hashable)
491550
492551-- | Dynamically create a tuple from attribute names and 'AtomExpr's.
493552newtype TupleExprBase a = TupleExpr (M.Map AttributeName (AtomExprBase a))
494− deriving (Eq, Show, Generic, NFData)
495−
496−instance Binary TupleExpr
497−
498−type TupleExpr = TupleExprBase ()
553+ deriving (Eq, Show, Read, Generic, NFData, Foldable, Functor, Traversable)
554+
555+instance Hashable TupleExpr
556+
557+type TupleExpr = TupleExprBase ()
558+
559+type GraphRefTupleExpr = TupleExprBase GraphRefTransactionMarker
560+
561+data TupleExprsBase a = TupleExprs a [TupleExprBase a]
562+ deriving (Eq, Show, Read, Generic, NFData, Foldable, Functor, Traversable)
563+
564+instance Hashable TupleExprs
565+
566+type GraphRefTupleExprs = TupleExprsBase GraphRefTransactionMarker
567+
568+type TupleExprs = TupleExprsBase ()
499569
500570data MergeStrategy =
501571 -- | After a union merge, the merge transaction is a result of union'ing relvars of the same name, introducing all uniquely-named relvars, union of constraints, union of atom functions, notifications, and types (unless the names and definitions collide, e.g. two types of the same name with different definitions)
@@ -504,7 +574,7 @@ data MergeStrategy =
504574 UnionPreferMergeStrategy HeadName |
505575 -- | Similar to the our/theirs merge strategy in git, the merge transaction's context is identical to that of the last transaction in the selected branch.
506576 SelectedBranchMergeStrategy HeadName
507− deriving (Eq, Show, Binary, Generic, NFData)
577+ deriving (Eq, Show, Generic, NFData)
508578
509579type DatabaseContextFunctionName = StringType
510580
@@ -541,7 +611,8 @@ attrTypeVars (Attribute _ aType) = case aType of
541611 DateTimeAtomType -> S.empty
542612 ByteStringAtomType -> S.empty
543613 BoolAtomType -> S.empty
544− (RelationAtomType attrs) -> S.unions (map attrTypeVars (V.toList attrs))
614+ RelationalExprAtomType -> S.empty
615+ (RelationAtomType attrs) -> S.unions (map attrTypeVars (V.toList (attributesVec attrs)))
545616 (ConstructedAtomType _ tvMap) -> M.keysSet tvMap
546617 (TypeVariableType nam) -> S.singleton nam
547618
@@ -564,7 +635,12 @@ atomTypeVars DayAtomType = S.empty
564635atomTypeVars DateTimeAtomType = S.empty
565636atomTypeVars ByteStringAtomType = S.empty
566637atomTypeVars BoolAtomType = S.empty
567−atomTypeVars (RelationAtomType attrs) = S.unions (map attrTypeVars (V.toList attrs))
638+atomTypeVars RelationalExprAtomType = S.empty
639+atomTypeVars (RelationAtomType attrs) = S.unions (map attrTypeVars (V.toList (attributesVec attrs)))
568640atomTypeVars (ConstructedAtomType _ tvMap) = M.keysSet tvMap
569641atomTypeVars (TypeVariableType nam) = S.singleton nam
570642
643+unimplemented :: HasCallStack => a
644+unimplemented = error "unimplemented"
645+
646+makeBaseFunctor ''RelationalExprBase
src/lib/ProjectM36/Client.hs+280−356
@@ -1,4 +1,4 @@
1−{-# LANGUAGE DeriveAnyClass, DeriveGeneric, ScopedTypeVariables, BangPatterns, PackageImports #-}
1+{-# LANGUAGE DeriveGeneric, ScopedTypeVariables, MonoLocalBinds, DerivingVia #-}
22{-|
33Module: ProjectM36.Client
44
@@ -9,6 +9,7 @@ module ProjectM36.Client
99 Connection(..),
1010 Port,
1111 Hostname,
12+ ServiceName,
1213 DatabaseName,
1314 ConnectionError(..),
1415 connectProjectM36,
@@ -43,19 +44,20 @@ module ProjectM36.Client
4344 defaultDatabaseName,
4445 defaultRemoteConnectionInfo,
4546 defaultHeadName,
47+ addClientNode,
4648 PersistenceStrategy(..),
4749 RelationalExpr,
4850 RelationalExprBase(..),
49− DatabaseContextExpr(..),
50− DatabaseContextIOExpr(..),
51+ DatabaseContextExprBase(..),
52+ DatabaseContextExpr,
53+ DatabaseContextIOExprBase(..),
54+ DatabaseContextIOExpr,
5155 Attribute(..),
5256 MergeStrategy(..),
5357 attributesFromList,
54− createNodeId,
5558 createSessionAtCommit,
5659 createSessionAtHead,
5760 closeSession,
58− addClientNode,
5961 callTestTimeout_,
6062 RelationCardinality(..),
6163 TransactionGraphOperator(..),
@@ -65,7 +67,6 @@ module ProjectM36.Client
6567 TransGraphRelationalExpr,
6668 TransactionIdLookup(..),
6769 TransactionIdHeadBacktrack(..),
68− NodeId(..),
6970 Atom(..),
7071 Session,
7172 SessionId,
@@ -78,6 +79,7 @@ module ProjectM36.Client
7879 databaseContextExprForUniqueKey,
7980 databaseContextExprForForeignKey,
8081 createScriptedAtomFunction,
82+ ProjectM36.Client.validateMerkleHashes,
8183 AttributeExprBase(..),
8284 TypeConstructorBase(..),
8385 TypeConstructorDef(..),
@@ -97,12 +99,14 @@ module ProjectM36.Client
9799 AtomType(..),
98100 Atomable(..),
99101 TupleExprBase(..),
102+ TupleExprsBase(..),
100103 AtomExprBase(..),
101104 RestrictionPredicateExprBase(..),
102105 withTransaction
103106 ) where
104107import ProjectM36.Base hiding (inclusionDependencies) --defined in this module as well
105108import qualified ProjectM36.Base as B
109+import ProjectM36.Serialise.Error ()
106110import ProjectM36.Error
107111import ProjectM36.Atomable
108112import ProjectM36.AtomFunction as AF
@@ -112,47 +116,35 @@ import qualified ProjectM36.DataFrame as DF
112116import ProjectM36.DatabaseContextFunction as DCF
113117import qualified ProjectM36.IsomorphicSchema as Schema
114118import Control.Monad.State
115−import Control.Monad.Trans.Reader
116119import qualified ProjectM36.RelationalExpression as RE
117120import ProjectM36.DatabaseContext (basicDatabaseContext)
118121import qualified ProjectM36.TransactionGraph as Graph
119−import ProjectM36.TransactionGraph
122+import ProjectM36.TransactionGraph as TG
120123import qualified ProjectM36.Transaction as Trans
121124import ProjectM36.TransactionGraph.Persist
122125import ProjectM36.Attribute
123−import ProjectM36.TransGraphRelationalExpression (TransGraphRelationalExpr, evalTransGraphRelationalExpr)
126+import ProjectM36.TransGraphRelationalExpression as TGRE (TransGraphRelationalExpr)
124127import ProjectM36.Persist (DiskSync(..))
125128import ProjectM36.FileLock
129+import ProjectM36.NormalizeExpr
126130import ProjectM36.Notifications
127131import ProjectM36.Server.RemoteCallTypes
128132import qualified ProjectM36.DisconnectedTransaction as Discon
129133import ProjectM36.Relation (typesAsRelation)
130134import ProjectM36.ScriptSession (initScriptSession, ScriptSession)
131135import qualified ProjectM36.Relation as R
132−import qualified ProjectM36.DatabaseContext as DBC
133136import Control.Exception.Base
134−import GHC.Conc.Sync
135−
136−import Network.Transport (Transport(closeTransport))
137−
138−#if MIN_VERSION_network_transport_tcp(0,6,0)
139−import Network.Transport.TCP (createTransport, defaultTCPParameters)
140−import Network.Transport.TCP.Internal (encodeEndPointAddress)
141−#else
142−import Network.Transport.TCP (encodeEndPointAddress, createTransport, defaultTCPParameters)
143−#endif
137+import Control.Concurrent.STM
138+import Control.Concurrent.Async
144139
145−import Control.Distributed.Process.Node (newLocalNode, initRemoteTable, runProcess, LocalNode, forkProcess, closeLocalNode)
146−import Control.Distributed.Process.Extras.Internal.Types (whereisRemote)
147−import Control.Distributed.Process.ManagedProcess.Client (call, safeCall)
148140import Data.Either (isRight)
149141import Data.UUID.V4 (nextRandom)
150142import Data.Word
151−import Control.Distributed.Process (ProcessId, Process, receiveWait, send, match, NodeId(..), reconnect)
143+import Data.Hashable
152144import Control.Exception (IOException, handle, AsyncException, throwIO, fromException, Exception)
153145import Control.Concurrent.MVar
146+import Codec.Winery hiding (Schema, schema)
154147import qualified Data.Map as M
155−import Control.Distributed.Process.Serializable (Serializable)
156148#if MIN_VERSION_stm_containers(1,0,0)
157149import qualified StmContainers.Map as StmMap
158150import qualified StmContainers.Set as StmSet
@@ -163,19 +155,19 @@ import qualified STMContainers.Set as StmSet
163155import qualified ProjectM36.Session as Sess
164156import ProjectM36.Session
165157import ProjectM36.Sessions
166−import "list-t" ListT
167−import Data.Binary (Binary)
168158import GHC.Generics (Generic)
169159import Control.DeepSeq (force)
170160import System.IO
171161import Data.Time.Clock
162+import qualified Network.RPC.Curryer.Client as RPC
163+import qualified Network.RPC.Curryer.Server as RPC
164+import Network.Socket (Socket, AddrInfo(..), getAddrInfo, defaultHints, AddrInfoFlag(..), SocketType(..), ServiceName, hostAddressToTuple, SockAddr(..))
165+import GHC.Conc (unsafeIOToSTM)
172166
173167type Hostname = String
174168
175169type Port = Word16
176170
177−type DatabaseName = String
178−
179171-- | The type for notifications callbacks in the client. When a registered notification fires due to a changed relational expression evaluation, the server propagates the notifications to the clients in the form of the callback.
180172type NotificationCallback = NotificationName -> EvaluatedNotification -> IO ()
181173
@@ -195,15 +187,16 @@ data RequestTimeoutException = RequestTimeoutException
195187
196188instance Exception RequestTimeoutException
197189
198−-- | Construct a 'ConnectionInfo' to describe how to make the 'Connection'. The database can be run within the current process or running remotely via distributed-process.
199−data ConnectionInfo = InProcessConnectionInfo PersistenceStrategy NotificationCallback [GhcPkgPath]|
200− RemoteProcessConnectionInfo DatabaseName NodeId NotificationCallback
190+-- | Construct a 'ConnectionInfo' to describe how to make the 'Connection'. The database can be run within the current process or running remotely via RPC.
191+data ConnectionInfo = InProcessConnectionInfo PersistenceStrategy NotificationCallback [GhcPkgPath] |
192+ RemoteConnectionInfo DatabaseName Hostname ServiceName NotificationCallback
201193
202194type EvaluatedNotifications = M.Map NotificationName EvaluatedNotification
203195
204196-- | Used for callbacks from the server when monitored changes have been made.
205197newtype NotificationMessage = NotificationMessage EvaluatedNotifications
206− deriving (Binary, Eq, Show, Generic)
198+ deriving (Eq, Show, Generic)
199+ deriving Serialise via WineryVariant NotificationMessage
207200
208201-- | When a notification is fired, the 'reportOldExpr' is evaluated in the commit's pre-change context while the 'reportNewExpr' is evaluated in the post-change context and they are returned along with the original notification.
209202data EvaluatedNotification = EvaluatedNotification {
@@ -211,13 +204,10 @@ data EvaluatedNotification = EvaluatedNotification {
211204 reportOldRelation :: Either RelationalError Relation,
212205 reportNewRelation :: Either RelationalError Relation
213206 }
214− deriving(Binary, Eq, Show, Generic)
207+ deriving (Eq, Show, Generic)
208+ deriving Serialise via WineryRecord EvaluatedNotification
215209
216210
217−-- | Create a 'NodeId' for use in connecting to a remote server using distributed-process.
218−createNodeId :: Hostname -> Port -> NodeId
219−createNodeId host port = NodeId $ encodeEndPointAddress host (show port) 1
220−
221211-- | Use this for connecting to remote servers on the default port.
222212defaultServerPort :: Port
223213defaultServerPort = 6543
@@ -232,130 +222,107 @@ defaultHeadName = "master"
232222
233223-- | Create a connection configuration which connects to the localhost on the default server port and default server database name. The configured notification callback is set to ignore all events.
234224defaultRemoteConnectionInfo :: ConnectionInfo
235−defaultRemoteConnectionInfo = RemoteProcessConnectionInfo defaultDatabaseName (createNodeId "127.0.0.1" defaultServerPort) emptyNotificationCallback
225+defaultRemoteConnectionInfo =
226+ RemoteConnectionInfo defaultDatabaseName defaultServerHostname (show defaultServerPort) emptyNotificationCallback
236227
237−-- | The 'Connection' represents either local or remote access to a database. All operations flow through the connection.
238−type ClientNodes = StmSet.Set ProcessId
239−
240−-- internal structure specific to in-process connections
241−data InProcessConnectionConf = InProcessConnectionConf {
242− ipPersistenceStrategy :: PersistenceStrategy,
243− ipClientNodes :: ClientNodes,
244− ipSessions :: Sessions,
245− ipTransactionGraph :: TVar TransactionGraph,
246− ipScriptSession :: Maybe ScriptSession,
247− ipLocalNode :: LocalNode,
248− ipTransport :: Transport, -- we hold onto this so that we can close it gracefully
249− ipLocks :: Maybe (LockFile, MVar LockFileHash) -- nothing when NoPersistence
250− }
228+defaultServerHostname :: Hostname
229+defaultServerHostname = "localhost"
251230
252−data RemoteProcessConnectionConf = RemoteProcessConnectionConf {
253− rLocalNode :: LocalNode,
254− rProcessId :: ProcessId, --remote processId
255− rTransport :: Transport --the TCP socket transport
256− }
231+newtype RemoteConnectionConf = RemoteConnectionConf RPC.Connection
257232
258233data Connection = InProcessConnection InProcessConnectionConf |
259− RemoteProcessConnection RemoteProcessConnectionConf
234+ RemoteConnection RemoteConnectionConf
260235
261236-- | There are several reasons why a connection can fail.
262237data ConnectionError = SetupDatabaseDirectoryError PersistenceError |
263238 IOExceptionError IOException |
264239 NoSuchDatabaseByNameError DatabaseName |
240+ DatabaseValidationError [MerkleValidationError] |
265241 LoginError
266242 deriving (Show, Eq, Generic)
267243
268244remoteDBLookupName :: DatabaseName -> String
269245remoteDBLookupName = (++) "db-"
270246
271−createLocalNode :: IO (LocalNode, Transport)
272−createLocalNode = do
273−#if MIN_VERSION_network_transport_tcp(0,6,0)
274− eLocalTransport <- createTransport "127.0.0.1" "0" (\sn -> ("127.0.0.1", sn)) defaultTCPParameters
275−#else
276− eLocalTransport <- createTransport "127.0.0.1" "0" defaultTCPParameters
277−#endif
278− case eLocalTransport of
279− Left err -> error ("failed to create transport: " ++ show err)
280− Right localTransport -> do
281− localNode <- newLocalNode localTransport initRemoteTable
282− pure (localNode, localTransport)
283−
284−notificationListener :: NotificationCallback -> Process ()
285−notificationListener callback = do
286− --pid <- getSelfPid
287− --liftIO $ putStrLn $ "LISTENER THREAD START " ++ show pid
288− _ <- forever $
289− receiveWait [
290− match (\(NotificationMessage eNots) ->
291− --say $ "NOTIFICATION: " ++ show eNots
292− -- when notifications are thrown, they are not adjusted for the current schema which could be problematic, but we don't have access to the current session here
293− liftIO $ mapM_ (uncurry callback) (M.toList eNots)
294− )
295− ]
296− --say "LISTENER THREAD EXIT"
297− pure ()
298−
299−startNotificationListener :: LocalNode -> NotificationCallback -> IO ProcessId
300−startNotificationListener localNode callback = forkProcess localNode (notificationListener callback)
301−
302247createScriptSession :: [String] -> IO (Maybe ScriptSession)
303248createScriptSession ghcPkgPaths = do
304249 eScriptSession <- initScriptSession ghcPkgPaths
305250 case eScriptSession of
306− Left err -> hPutStrLn stderr ("Failed to load scripting engine- scripting disabled: " ++ show err) >> pure Nothing --not a fatal error, but the scripting feature must be disabled
251+ Left err -> hPutStrLn stderr ("Warning: Haskell scripting disabled: " ++ show err) >> pure Nothing --not a fatal error, but the scripting feature must be disabled
307252 Right s -> pure (Just s)
308253
254+
309255-- | To create a 'Connection' to a remote or local database, create a 'ConnectionInfo' and call 'connectProjectM36'.
310256connectProjectM36 :: ConnectionInfo -> IO (Either ConnectionError Connection)
311257--create a new in-memory database/transaction graph
312258connectProjectM36 (InProcessConnectionInfo strat notificationCallback ghcPkgPaths) = do
313259 freshId <- nextRandom
314− stamp <- getCurrentTime
260+ tstamp <- getCurrentTime
315261 let bootstrapContext = basicDatabaseContext
316− freshGraph = bootstrapTransactionGraph stamp freshId bootstrapContext
262+ freshGraph = bootstrapTransactionGraph tstamp freshId bootstrapContext
317263 case strat of
318264 --create date examples graph for now- probably should be empty context in the future
319265 NoPersistence -> do
320266 graphTvar <- newTVarIO freshGraph
321267 clientNodes <- StmSet.newIO
322268 sessions <- StmMap.newIO
323− (localNode, transport) <- createLocalNode
324− notificationPid <- startNotificationListener localNode notificationCallback
325269 mScriptSession <- createScriptSession ghcPkgPaths
326−
270+ notifAsync <- startNotificationListener clientNodes notificationCallback
327271 let conn = InProcessConnection InProcessConnectionConf {
328272 ipPersistenceStrategy = strat,
329273 ipClientNodes = clientNodes,
330274 ipSessions = sessions,
331275 ipTransactionGraph = graphTvar,
332276 ipScriptSession = mScriptSession,
333− ipLocalNode = localNode,
334− ipTransport = transport,
335− ipLocks = Nothing}
336− addClientNode conn notificationPid
277+ ipLocks = Nothing,
278+ ipCallbackAsync = notifAsync
279+ }
337280 pure (Right conn)
338281 MinimalPersistence dbdir -> connectPersistentProjectM36 strat NoDiskSync dbdir freshGraph notificationCallback ghcPkgPaths
339282 CrashSafePersistence dbdir -> connectPersistentProjectM36 strat FsyncDiskSync dbdir freshGraph notificationCallback ghcPkgPaths
340283
341−connectProjectM36 (RemoteProcessConnectionInfo databaseName serverNodeId notificationCallback) = do
342− connStatus <- newEmptyMVar
343− (localNode, transport) <- createLocalNode
344− let dbName = remoteDBLookupName databaseName
345− --putStrLn $ "Connecting to " ++ show serverNodeId ++ " " ++ dbName
346− notificationListenerPid <- startNotificationListener localNode notificationCallback
347− runProcess localNode $ do
348− --even a failed connection retains an open socket!
349− mServerProcessId <- whereisRemote serverNodeId dbName
350− case mServerProcessId of
351− Nothing -> liftIO $ putMVar connStatus $ Left (NoSuchDatabaseByNameError databaseName)
352− Just serverProcessId -> do
353− loginConfirmation <- safeLogin (Login notificationListenerPid) serverProcessId
354− if not loginConfirmation then
355− liftIO $ putMVar connStatus (Left LoginError)
356− else
357− liftIO $ putMVar connStatus (Right $ RemoteProcessConnection RemoteProcessConnectionConf {rLocalNode = localNode, rProcessId = serverProcessId, rTransport = transport})
358− takeMVar connStatus
284+connectProjectM36 (RemoteConnectionInfo dbName hostName servicePort notificationCallback) = do
285+ --TODO- add notification callback thread
286+ let resolutionHints = defaultHints { addrFlags = [AI_NUMERICHOST, AI_NUMERICSERV],
287+ addrSocketType = Stream
288+ }
289+ resolved <- getAddrInfo (Just resolutionHints) (Just hostName) (Just servicePort)
290+ case resolved of
291+ [] -> error ("DNS resolution failed for" <> hostName <> ":" <> servicePort)
292+ addrInfo:_ -> do
293+ --supports IPv4 only for now
294+ let (SockAddrInet port addr) = addrAddress addrInfo
295+ notificationHandlers =
296+ [RPC.ClientAsyncRequestHandler $
297+ \(NotificationMessage notifications') ->
298+ forM_ (M.toList notifications') (uncurry notificationCallback)
299+ ]
300+ let connectExcHandler (e :: IOException) = pure $ Left (IOExceptionError e)
301+ eConn <- (Right <$> RPC.connect notificationHandlers (hostAddressToTuple addr) port) `catch` connectExcHandler
302+ case eConn of
303+ Left err -> pure (Left err)
304+ Right conn -> do
305+ eRet <- RPC.call conn (Login dbName)
306+ case eRet of
307+ Left err -> error (show err)
308+ Right False -> error "wtf"
309+ Right True ->
310+ --TODO handle connection errors!
311+ pure (Right (RemoteConnection (RemoteConnectionConf conn)))
312+
313+--convert RPC errors into exceptions
314+convertRPCErrors :: RPC.ConnectionError -> IO a
315+convertRPCErrors err =
316+ case err of
317+ RPC.TimeoutError -> throw RequestTimeoutException
318+ RPC.CodecError msg -> error $ "decoding message failed on server: " <> msg
319+ RPC.ExceptionError msg -> error $ "server threw exception: " <> msg
320+
321+addClientNode :: Connection -> RPC.Locking Socket -> IO ()
322+addClientNode (RemoteConnection _) _ = error "addClientNode called on remote connection"
323+addClientNode (InProcessConnection conf) lockSock = atomically (StmSet.insert clientInfo (ipClientNodes conf))
324+ where
325+ clientInfo = RemoteClientInfo lockSock
359326
360327connectPersistentProjectM36 :: PersistenceStrategy ->
361328 DiskSync ->
@@ -374,39 +341,47 @@ connectPersistentProjectM36 strat sync dbdir freshGraph notificationCallback ghc
374341 case graph of
375342 Left err' -> return $ Left (SetupDatabaseDirectoryError err')
376343 Right graph' -> do
377− tvarGraph <- newTVarIO graph'
378− sessions <- StmMap.newIO
379− clientNodes <- StmSet.newIO
380− (localNode, transport) <- createLocalNode
381− lockMVar <- newMVar digest
382− let conn = InProcessConnection InProcessConnectionConf {
344+ case TG.validateMerkleHashes graph' of
345+ Left merkleErrs -> pure (Left (DatabaseValidationError merkleErrs))
346+ Right _ -> do
347+ tvarGraph <- newTVarIO graph'
348+ sessions <- StmMap.newIO
349+ clientNodes <- StmSet.newIO
350+ lockMVar <- newMVar digest
351+ notifAsync <- startNotificationListener clientNodes notificationCallback
352+ let conn = InProcessConnection InProcessConnectionConf {
383353 ipPersistenceStrategy = strat,
384354 ipClientNodes = clientNodes,
385355 ipSessions = sessions,
386356 ipTransactionGraph = tvarGraph,
387357 ipScriptSession = mScriptSession,
388− ipLocalNode = localNode,
389− ipTransport = transport,
390− ipLocks = Just (lockFileH, lockMVar)
358+ ipLocks = Just (lockFileH, lockMVar),
359+ ipCallbackAsync = notifAsync
391360 }
361+ pure (Right conn)
362+
363+--startup local async process to handle notification callbacks
364+startNotificationListener :: ClientNodes -> NotificationCallback -> IO (Async ())
365+startNotificationListener cNodes notificationCallback = do
366+ inProcessClientInfo@(InProcessClientInfo notifMVar) <- InProcessClientInfo <$> newEmptyMVar
367+ atomically $ StmSet.insert inProcessClientInfo cNodes
368+ async $ forever $ do
369+ notifs <- takeMVar notifMVar
370+ forM_ (M.toList notifs) $ uncurry notificationCallback
392371
393− notificationPid <- startNotificationListener localNode notificationCallback
394− addClientNode conn notificationPid
395− pure (Right conn)
396−
397372-- | Create a new session at the transaction id and return the session's Id.
398373createSessionAtCommit :: Connection -> TransactionId -> IO (Either RelationalError SessionId)
399374createSessionAtCommit conn@(InProcessConnection _) commitId = do
400375 newSessionId <- nextRandom
401376 atomically $ createSessionAtCommit_ commitId newSessionId conn
402−createSessionAtCommit conn@(RemoteProcessConnection _) uuid = remoteCall conn (CreateSessionAtCommit uuid)
377+createSessionAtCommit conn@(RemoteConnection _) uuid = remoteCall conn (CreateSessionAtCommit uuid)
403378
404379createSessionAtCommit_ :: TransactionId -> SessionId -> Connection -> STM (Either RelationalError SessionId)
405380createSessionAtCommit_ commitId newSessionId (InProcessConnection conf) = do
406381 let sessions = ipSessions conf
407382 graphTvar = ipTransactionGraph conf
408383 graph <- readTVar graphTvar
409− case transactionForId commitId graph of
384+ case RE.transactionForId commitId graph of
410385 Left err -> pure (Left err)
411386 Right transaction -> do
412387 let freshDiscon = DisconnectedTransaction commitId (Trans.schemas transaction) False
@@ -416,7 +391,7 @@ createSessionAtCommit_ commitId newSessionId (InProcessConnection conf) = do
416391 Nothing -> do
417392 StmMap.insert (Session freshDiscon defaultSchemaName) newSessionId sessions
418393 pure $ Right newSessionId
419−createSessionAtCommit_ _ _ (RemoteProcessConnection _) = error "createSessionAtCommit_ called on remote connection"
394+createSessionAtCommit_ _ _ (RemoteConnection _) = error "createSessionAtCommit_ called on remote connection"
420395
421396-- | Call 'createSessionAtHead' with a transaction graph's head's name to create a new session pinned to that head. This function returns a 'SessionId' which can be used in other function calls to reference the point in the transaction graph.
422397createSessionAtHead :: Connection -> HeadName -> IO (Either RelationalError SessionId)
@@ -428,22 +403,18 @@ createSessionAtHead conn@(InProcessConnection conf) headn = do
428403 case transactionForHead headn graph of
429404 Nothing -> pure $ Left (NoSuchHeadNameError headn)
430405 Just trans -> createSessionAtCommit_ (transactionId trans) newSessionId conn
431−createSessionAtHead conn@(RemoteProcessConnection _) headn = remoteCall conn (CreateSessionAtHead headn)
432−
433−-- | Used internally for server connections to keep track of remote nodes for the purpose of sending notifications later.
434−addClientNode :: Connection -> ProcessId -> IO ()
435−addClientNode (RemoteProcessConnection _) _ = error "addClientNode called on remote connection"
436−addClientNode (InProcessConnection conf) newProcessId = atomically (StmSet.insert newProcessId (ipClientNodes conf))
406+createSessionAtHead conn@(RemoteConnection _) headn = remoteCall conn (CreateSessionAtHead headn)
437407
438408-- | Discards a session, eliminating any uncommitted changes present in the session.
439409closeSession :: SessionId -> Connection -> IO ()
440410closeSession sessionId (InProcessConnection conf) =
441411 atomically $ StmMap.delete sessionId (ipSessions conf)
442−closeSession sessionId conn@(RemoteProcessConnection _) = remoteCall conn (CloseSession sessionId)
412+closeSession sessionId conn@(RemoteConnection _) = remoteCall conn (CloseSession sessionId)
443413
444414-- | 'close' cleans up the database access connection and closes any relevant sockets.
445415close :: Connection -> IO ()
446416close (InProcessConnection conf) = do
417+ cancel (ipCallbackAsync conf)
447418 atomically $ do
448419 let sessions = ipSessions conf
449420#if MIN_VERSION_stm_containers(1,0,0)
@@ -452,22 +423,18 @@ close (InProcessConnection conf) = do
452423 StmMap.deleteAll sessions
453424#endif
454425 pure ()
455− closeLocalNode (ipLocalNode conf)
456− closeTransport (ipTransport conf)
457426 let mLocks = ipLocks conf
458427 case mLocks of
459428 Nothing -> pure ()
460429 Just (lockFileH, _) -> closeLockFile lockFileH
461430
462−close conn@(RemoteProcessConnection conf) = do
463− _ <- remoteCall conn Logout :: IO Bool
464− closeLocalNode (rLocalNode conf)
465− closeTransport (rTransport conf)
431+close (RemoteConnection (RemoteConnectionConf conn)) =
432+ RPC.close conn
466433
467434--used only by the server EntryPoints
468435closeRemote_ :: Connection -> IO ()
469436closeRemote_ (InProcessConnection _) = error "invalid call of closeRemote_ on InProcessConnection"
470−closeRemote_ (RemoteProcessConnection conf) = runProcess (rLocalNode conf) (reconnect (rProcessId conf))
437+closeRemote_ (RemoteConnection (RemoteConnectionConf conn)) = RPC.close conn
471438
472439 --we need to actually close the localNode's connection to the remote
473440--within the database server, we must catch and handle all exception lest they take down the database process- this handling might be different for other use-cases
@@ -478,35 +445,15 @@ excEither = handle handler
478445 where
479446 handler exc | Just (_ :: AsyncException) <- fromException exc = throwIO exc
480447 | otherwise = pure (Left (UnhandledExceptionError (show exc)))
481−
482−runProcessResult :: LocalNode -> Process a -> IO a
483−runProcessResult localNode proc = do
484− ret <- newEmptyMVar
485− runProcess localNode $ do
486− val <- proc
487− liftIO $ putMVar ret val
488− takeMVar ret
489−
490−safeLogin :: Login -> ProcessId -> Process Bool
491−safeLogin login procId = do
492− ret <- call procId login
493− case ret of
494− Left (_ :: ServerError) -> pure False
495− Right val -> pure val
496448
497−remoteCall :: (Serializable a, Serializable b) => Connection -> a -> IO b
449+
450+remoteCall :: (Serialise a, Serialise b) => Connection -> a -> IO b
498451remoteCall (InProcessConnection _ ) _ = error "remoteCall called on local connection"
499−remoteCall (RemoteProcessConnection conf) arg = runProcessResult localNode $ do
500− ret <- safeCall serverProcessId arg
501− case ret of
502− Left err -> error ("server died: " ++ show err)
503− Right ret' -> case ret' of
504− Left RequestTimeoutError -> liftIO (throwIO RequestTimeoutException)
505− Left (ProcessDiedError _) -> liftIO (throwIO RemoteProcessDiedException)
506− Right val -> pure val
507− where
508− localNode = rLocalNode conf
509− serverProcessId = rProcessId conf
452+remoteCall (RemoteConnection (RemoteConnectionConf rpcConn)) arg = do
453+ eRet <- RPC.call rpcConn arg
454+ case eRet of
455+ Left err -> convertRPCErrors err
456+ Right val -> pure val
510457
511458sessionForSessionId :: SessionId -> Sessions -> STM (Either RelationalError Session)
512459sessionForSessionId sessionId sessions =
@@ -541,7 +488,7 @@ currentSchemaName sessionId (InProcessConnection conf) = atomically $ do
541488 case eSession of
542489 Left err -> pure (Left err)
543490 Right session -> pure (Right (Sess.schemaName session))
544−currentSchemaName sessionId conn@(RemoteProcessConnection _) = remoteCall conn (RetrieveCurrentSchemaName sessionId)
491+currentSchemaName sessionId conn@(RemoteConnection _) = remoteCall conn (RetrieveCurrentSchemaName sessionId)
545492
546493-- | Switch to the named isomorphic schema.
547494setCurrentSchemaName :: SessionId -> Connection -> SchemaName -> IO (Either RelationalError ())
@@ -553,7 +500,7 @@ setCurrentSchemaName sessionId (InProcessConnection conf) sname = atomically $ d
553500 Right session -> case Sess.setSchemaName sname session of
554501 Left err -> pure (Left err)
555502 Right newSession -> StmMap.insert newSession sessionId sessions >> pure (Right ())
556−setCurrentSchemaName sessionId conn@(RemoteProcessConnection _) sname = remoteCall conn (ExecuteSetCurrentSchema sessionId sname)
503+setCurrentSchemaName sessionId conn@(RemoteConnection _) sname = remoteCall conn (ExecuteSetCurrentSchema sessionId sname)
557504
558505-- | Execute a relational expression in the context of the session and connection. Relational expressions are queries and therefore cannot alter the database.
559506executeRelationalExpr :: SessionId -> Connection -> RelationalExpr -> IO (Either RelationalError Relation)
@@ -569,14 +516,15 @@ executeRelationalExpr sessionId (InProcessConnection conf) expr = excEither $ at
569516 Right expr
570517 case expr' of
571518 Left err -> pure (Left err)
572− Right expr'' -> case optimizeRelationalExpr (Sess.concreteDatabaseContext session) expr'' of
573− Left err -> pure (Left err)
574− Right optExpr -> do
575− let evald = runReader (RE.evalRelationalExpr optExpr) (RE.mkRelationalExprState (Sess.concreteDatabaseContext session))
576− case evald of
577− Left err -> pure (Left err)
578− Right rel -> pure (force (Right rel)) -- this is necessary so that any undefined/error exceptions are spit out here
579−executeRelationalExpr sessionId conn@(RemoteProcessConnection _) relExpr = remoteCall conn (ExecuteRelationalExpr sessionId relExpr)
519+ Right expr'' -> do
520+ let graphTvar = ipTransactionGraph conf
521+ graph <- readTVar graphTvar
522+ let reEnv = RE.mkRelationalExprEnv (Sess.concreteDatabaseContext session) graph
523+ case optimizeAndEvalRelationalExpr reEnv expr'' of
524+ Right rel -> pure (force (Right rel)) -- this is necessary so that any undefined/error exceptions are spit out here
525+ Left err -> pure (Left err)
526+
527+executeRelationalExpr sessionId conn@(RemoteConnection _) relExpr = remoteCall conn (ExecuteRelationalExpr sessionId relExpr)
580528
581529-- | Execute a database context expression in the context of the session and connection. Database expressions modify the current session's disconnected transaction but cannot modify the transaction graph.
582530executeDatabaseContextExpr :: SessionId -> Connection -> DatabaseContextExpr -> IO (Either RelationalError ())
@@ -592,22 +540,25 @@ executeDatabaseContextExpr sessionId (InProcessConnection conf) expr = excEither
592540 Schema.processDatabaseContextExprInSchema schema expr
593541 case expr' of
594542 Left err -> pure (Left err)
595− Right expr'' -> case runState (do
596− eOptExpr <- applyStaticDatabaseOptimization expr''
597− case eOptExpr of
598− Left err -> pure (Left err)
599− Right optExpr ->
600− RE.evalDatabaseContextExpr optExpr) (RE.freshDatabaseState (Sess.concreteDatabaseContext session)) of
601− (Left err,_) -> pure (Left err)
602− (Right (), (_,_,False)) -> pure (Right ()) --optimization- if nothing was dirtied, nothing to do
603− (Right (), (!context',_,True)) -> do
604− let newDiscon = DisconnectedTransaction (Sess.parentId session) newSchemas True
605− newSubschemas = Schema.processDatabaseContextExprSchemasUpdate (Sess.subschemas session) expr
606− newSchemas = Schemas context' newSubschemas
607− newSession = Session newDiscon (Sess.schemaName session)
608− StmMap.insert newSession sessionId sessions
609− pure (Right ())
610−executeDatabaseContextExpr sessionId conn@(RemoteProcessConnection _) dbExpr = remoteCall conn (ExecuteDatabaseContextExpr sessionId dbExpr)
543+ Right expr'' -> do
544+ graph <- readTVar (ipTransactionGraph conf)
545+ let ctx = Sess.concreteDatabaseContext session
546+ env = RE.mkDatabaseContextEvalEnv transId graph
547+ transId = Sess.parentId session
548+ case RE.runDatabaseContextEvalMonad ctx env (optimizeAndEvalDatabaseContextExpr True expr'') of
549+ Left err -> pure (Left err)
550+ Right newState ->
551+ if not (RE.dbc_dirty newState) then --nothing dirtied, nothing to do
552+ pure (Right ())
553+ else do
554+ let newDiscon = DisconnectedTransaction (Sess.parentId session) newSchemas True
555+ context' = RE.dbc_context newState
556+ newSubschemas = Schema.processDatabaseContextExprSchemasUpdate (Sess.subschemas session) expr
557+ newSchemas = Schemas context' newSubschemas
558+ newSession = Session newDiscon (Sess.schemaName session)
559+ StmMap.insert newSession sessionId sessions
560+ pure (Right ())
561+executeDatabaseContextExpr sessionId conn@(RemoteConnection _) dbExpr = remoteCall conn (ExecuteDatabaseContextExpr sessionId dbExpr)
611562
612563-- | Similar to a git rebase, 'autoMergeToHead' atomically creates a temporary branch and merges it to the latest commit of the branch referred to by the 'HeadName' and commits the merge. This is useful to reduce incidents of 'TransactionIsNotAHeadError's but at the risk of merge errors (thus making it similar to rebasing). Alternatively, as an optimization, if a simple commit is possible (meaning that the head has not changed), then a fast-forward commit takes place instead.
613564autoMergeToHead :: SessionId -> Connection -> MergeStrategy -> HeadName -> IO (Either RelationalError ())
@@ -616,7 +567,7 @@ autoMergeToHead sessionId (InProcessConnection conf) strat headName' = do
616567 id1 <- nextRandom
617568 id2 <- nextRandom
618569 id3 <- nextRandom
619− stamp <- getCurrentTime
570+ tstamp <- getCurrentTime
620571 commitLock_ sessionId conf $ \graph -> do
621572 eSession <- sessionForSessionId sessionId sessions
622573 case eSession of
@@ -627,16 +578,16 @@ autoMergeToHead sessionId (InProcessConnection conf) strat headName' = do
627578 Just headTrans -> do
628579 --attempt fast-forward commit, if possible
629580 let graphInfo = if Sess.parentId session == transactionId headTrans then do
630− ret <- Graph.evalGraphOp stamp id1 (Sess.disconnectedTransaction session) graph Commit
581+ ret <- Graph.evalGraphOp tstamp id1 (Sess.disconnectedTransaction session) graph Commit
631582 pure (ret, [id1])
632583 else do
633− ret <- Graph.autoMergeToHead stamp (id1, id2, id3) (Sess.disconnectedTransaction session) headName' strat graph
584+ ret <- Graph.autoMergeToHead tstamp (id1, id2, id3) (Sess.disconnectedTransaction session) headName' strat graph
634585 pure (ret, [id1,id2,id3])
635586 case graphInfo of
636587 Left err -> pure (Left err)
637588 Right ((discon', graph'), transactionIdsAdded) ->
638589 pure (Right (discon', graph', transactionIdsAdded))
639−autoMergeToHead sessionId conn@(RemoteProcessConnection _) strat headName' = remoteCall conn (ExecuteAutoMergeToHead sessionId strat headName')
590+autoMergeToHead sessionId conn@(RemoteConnection _) strat headName' = remoteCall conn (ExecuteAutoMergeToHead sessionId strat headName')
640591
641592-- | Execute a database context IO-monad-based expression for the given session and connection. `DatabaseContextIOExpr`s modify the DatabaseContext but cannot be purely implemented.
642593--this is almost completely identical to executeDatabaseContextExpr above
@@ -648,38 +599,35 @@ executeDatabaseContextIOExpr sessionId (InProcessConnection conf) expr = excEith
648599 case eSession of
649600 Left err -> pure (Left err)
650601 Right session -> do
651− res <- RE.evalDatabaseContextIOExpr scriptSession (Sess.concreteDatabaseContext session) expr
602+ graph <- readTVarIO (ipTransactionGraph conf)
603+ let env = RE.DatabaseContextIOEvalEnv transId graph scriptSession
604+ transId = Sess.parentId session
605+ context = Sess.concreteDatabaseContext session
606+ res <- RE.runDatabaseContextIOEvalMonad env context (optimizeAndEvalDatabaseContextIOExpr expr)
652607 case res of
653608 Left err -> pure (Left err)
654− Right context' -> do
655− let newDiscon = DisconnectedTransaction (Sess.parentId session) newSchemas True
609+ Right newState -> do
610+ let newDiscon = DisconnectedTransaction (Sess.parentId session) newSchemas False
656611 newSchemas = Schemas context' (Sess.subschemas session)
657612 newSession = Session newDiscon (Sess.schemaName session)
613+ context' = RE.dbc_context newState
658614 atomically $ StmMap.insert newSession sessionId sessions
659615 pure (Right ())
660−executeDatabaseContextIOExpr sessionId conn@(RemoteProcessConnection _) dbExpr = remoteCall conn (ExecuteDatabaseContextIOExpr sessionId dbExpr)
616+executeDatabaseContextIOExpr sessionId conn@(RemoteConnection _) dbExpr = remoteCall conn (ExecuteDatabaseContextIOExpr sessionId dbExpr)
661617
662−{-
663−executeGraphExprSTM_ :: TransactionId -> SessionId -> Session -> Sessions -> TransactionGraphOperator -> TransactionGraph -> TVar TransactionGraph -> STM (Either RelationalError (TransactionGraph, DisconnectedTransaction)
664−executeGraphExprSTM_ freshId sessionId session sessions graphExpr graph graphTVar= do
665− case evalGraphOp freshId (Sess.disconnectedTransaction session) graph graphExpr of
666− Left err -> do
667− when updateGraphOnError (writeTVar graphTVar graph)
668− pure $ Left err
669− Right (discon', graph') -> do
670− writeTVar graphTVar graph'
671− let newSession = Session discon' (Sess.schemaName session)
672− STMMap.insert newSession sessionId sessions
673− pure $ Right graph'
674−-}
675−
676618-- process notifications for commits
677−executeCommitExprSTM_ :: DatabaseContext -> DatabaseContext -> ClientNodes -> STM (EvaluatedNotifications, ClientNodes)
678−executeCommitExprSTM_ oldContext newContext nodes = do
619+executeCommitExprSTM_
620+ :: TransactionGraph
621+ -> DatabaseContext
622+ -> DatabaseContext
623+ -> ClientNodes
624+ -> STM (EvaluatedNotifications, ClientNodes)
625+executeCommitExprSTM_ graph oldContext newContext nodes = do
679626 let nots = notifications oldContext
680− fireNots = notificationChanges nots oldContext newContext
627+ fireNots = notificationChanges nots graph oldContext newContext
681628 evaldNots = M.map mkEvaldNot fireNots
682− evalInContext expr ctx = runReader (RE.evalRelationalExpr expr) (RE.mkRelationalExprState ctx)
629+ evalInContext expr ctx = optimizeAndEvalRelationalExpr (RE.mkRelationalExprEnv ctx graph) expr
630+
683631 mkEvaldNot notif = EvaluatedNotification { notification = notif,
684632 reportOldRelation = evalInContext (reportOldExpr notif) oldContext,
685633 reportNewRelation = evalInContext (reportNewExpr notif) newContext}
@@ -694,103 +642,29 @@ executeGraphExpr :: SessionId -> Connection -> TransactionGraphOperator -> IO (E
694642executeGraphExpr sessionId (InProcessConnection conf) graphExpr = excEither $ do
695643 let sessions = ipSessions conf
696644 freshId <- nextRandom
697− stamp <- getCurrentTime
645+ tstamp <- getCurrentTime
698646 commitLock_ sessionId conf $ \updatedGraph -> do
699647 eSession <- sessionForSessionId sessionId sessions
700648 case eSession of
701649 Left err -> pure (Left err)
702650 Right session -> do
703651 let discon = Sess.disconnectedTransaction session
704− case evalGraphOp stamp freshId discon updatedGraph graphExpr of
652+ case evalGraphOp tstamp freshId discon updatedGraph graphExpr of
705653 Left err -> pure (Left err)
706654 Right (discon', graph') -> do
707655 --if freshId appears in the graph, then we need to pass it on
708− let transIds = [freshId | isRight (transactionForId freshId graph')]
656+ let transIds = [freshId | isRight (RE.transactionForId freshId graph')]
709657 pure (Right (discon', graph', transIds))
710−{-
711−executeGraphExpr sessionId (InProcessConnection conf) graphExpr = excEither $ do
712− let strat = ipPersistenceStrategy conf
713− clientNodes = ipClientNodes conf
714− sessions = ipSessions conf
715− graphTvar = ipTransactionGraph conf
716− mLockFileH = ipLocks conf
717− lockHandler body = case graphExpr of
718− Commit -> case mLockFileH of
719− Nothing -> body False
720− Just (lockFileH, lockMVar) -> let acquireLocks = do
721− lastWrittenDigest <- takeMVar lockMVar
722− lockFile lockFileH WriteLock
723− latestDigest <- readGraphTransactionIdDigest strat
724− pure (latestDigest /= lastWrittenDigest)
725−
726− releaseLocks _ = do
727− --still holding the lock- get the latest digest
728− gDigest <- readGraphTransactionIdDigest strat
729− unlockFile lockFileH
730− putMVar lockMVar gDigest
731− in bracket acquireLocks releaseLocks body
732− _ -> body False
733− freshId <- nextRandom
734− lockHandler $ \dbWrittenByOtherProcess -> do
735− --if the database file has been updated since we wrote it last, load it before trying to sync our version done- this can result in TransactionNotAHeadErrors
736− --read transaction data and compare to existing graph
737− --in the future, we can detect if updated transaction graph can be safely merged (such as with a transaction on a separate head) (rebase-able commits should force the user to rebase from the client to confirm that the action makes sense)
738− manip <- atomically $ do
739− eSession <- sessionForSessionId sessionId sessions
740− --handle graph update by other process
741− oldGraph <- readTVar graphTvar
742− case eSession of
743− Left err -> pure (Left err)
744− Right session -> do
745− let mScriptSession = ipScriptSession conf
746− dbdir = case strat of
747− MinimalPersistence x -> x
748− CrashSafePersistence x -> x
749− _ -> error "accessing dbdir on non-persisted connection"
750− eRefreshedGraph <- if dbWrittenByOtherProcess then
751− unsafeIOToSTM (transactionGraphLoad dbdir oldGraph mScriptSession)
752− else
753− pure (Right oldGraph)
754− case eRefreshedGraph of
755− Left err -> pure (Left (DatabaseLoadError err))
756− Right refreshedGraph -> do
757− --snip it
758− eGraph <- executeGraphExprSTM_ dbWrittenByOtherProcess freshId sessionId session sessions graphExpr refreshedGraph graphTvar
759− --snip it
760− case eGraph of
761− Left err -> pure (Left err)
762− Right newGraph -> do
763− --handle commit
764− if isCommit graphExpr then do
765− case transactionForId (Sess.parentId session) oldGraph of
766− Left err -> pure $ Left err
767− Right previousTrans -> do
768− (evaldNots, nodes) <- executeCommitExprSTM_ (Trans.concreteDatabaseContext previousTrans) (Sess.concreteDatabaseContext session) clientNodes
769− nodesToNotify <- toList (StmSet.stream nodes)
770− pure $ Right (evaldNots, nodesToNotify, newGraph)
771− else
772− pure $ Right (M.empty, [], newGraph)
773− case manip of
774− Left err -> return $ Just err
775− Right (notsToFire, nodesToNotify, newGraph) -> do
776− --update filesystem database, if necessary
777− processTransactionGraphPersistence strat newGraph
778− sendNotifications nodesToNotify (ipLocalNode conf) notsToFire
779− pure Nothing
780−-}
781−executeGraphExpr sessionId conn@(RemoteProcessConnection _) graphExpr = remoteCall conn (ExecuteGraphExpr sessionId graphExpr)
658+
659+executeGraphExpr sessionId conn@(RemoteConnection _) graphExpr = remoteCall conn (ExecuteGraphExpr sessionId graphExpr)
782660
783661-- | A trans-graph expression is a relational query executed against the entirety of a transaction graph.
784662executeTransGraphRelationalExpr :: SessionId -> Connection -> TransGraphRelationalExpr -> IO (Either RelationalError Relation)
785663executeTransGraphRelationalExpr _ (InProcessConnection conf) tgraphExpr = excEither . atomically $ do
786664 let graphTvar = ipTransactionGraph conf
787665 graph <- readTVar graphTvar
788− case evalTransGraphRelationalExpr tgraphExpr graph of
789− Left err -> pure (Left err)
790− Right relExpr -> case runReader (RE.evalRelationalExpr relExpr) (RE.mkRelationalExprState DBC.empty) of
791− Left err -> pure (Left err)
792− Right rel -> pure (force (Right rel))
793−executeTransGraphRelationalExpr sessionId conn@(RemoteProcessConnection _) tgraphExpr = remoteCall conn (ExecuteTransGraphRelationalExpr sessionId tgraphExpr)
666+ pure $ force $ optimizeAndEvalTransGraphRelationalExpr graph tgraphExpr
667+executeTransGraphRelationalExpr sessionId conn@(RemoteConnection _) tgraphExpr = remoteCall conn (ExecuteTransGraphRelationalExpr sessionId tgraphExpr)
794668
795669-- | Schema expressions manipulate the isomorphic schemas for the current 'DatabaseContext'.
796670executeSchemaExpr :: SessionId -> Connection -> Schema.SchemaExpr -> IO (Either RelationalError ())
@@ -801,32 +675,36 @@ executeSchemaExpr sessionId (InProcessConnection conf) schemaExpr = atomically $
801675 Left err -> pure (Left err)
802676 Right (session, _) -> do
803677 let subschemas' = subschemas session
804− case Schema.evalSchemaExpr schemaExpr (Sess.concreteDatabaseContext session) subschemas' of
678+ transId = Sess.parentId session
679+ context = Sess.concreteDatabaseContext session
680+ graph <- readTVar (ipTransactionGraph conf)
681+ case Schema.evalSchemaExpr schemaExpr context transId graph subschemas' of
805682 Left err -> pure (Left err)
806683 Right (newSubschemas, newContext) -> do
807684 --hm- maybe we should start using lenses
808685 let discon = Sess.disconnectedTransaction session
809686 newSchemas = Schemas newContext newSubschemas
810− newSession = Session (DisconnectedTransaction (Discon.parentId discon) newSchemas True) (Sess.schemaName session)
687+ newSession = Session (DisconnectedTransaction (Discon.parentId discon) newSchemas False) (Sess.schemaName session)
811688 StmMap.insert newSession sessionId sessions
812689 pure (Right ())
813−executeSchemaExpr sessionId conn@(RemoteProcessConnection _) schemaExpr = remoteCall conn (ExecuteSchemaExpr sessionId schemaExpr)
690+executeSchemaExpr sessionId conn@(RemoteConnection _) schemaExpr = remoteCall conn (ExecuteSchemaExpr sessionId schemaExpr)
814691
815692-- | After modifying a 'DatabaseContext', 'commit' the transaction to the transaction graph at the head which the session is referencing. This will also trigger checks for any notifications which need to be propagated.
816693commit :: SessionId -> Connection -> IO (Either RelationalError ())
817694commit sessionId conn@(InProcessConnection _) = executeGraphExpr sessionId conn Commit
818−commit sessionId conn@(RemoteProcessConnection _) = remoteCall conn (ExecuteGraphExpr sessionId Commit)
819−
820−sendNotifications :: [ProcessId] -> LocalNode -> EvaluatedNotifications -> IO ()
821−sendNotifications pids localNode nots = mapM_ sendNots pids
822− where
823− sendNots remoteClientPid =
824− unless (M.null nots) $ runProcess localNode $ send remoteClientPid (NotificationMessage nots)
825−
695+commit sessionId conn@(RemoteConnection _) = remoteCall conn (ExecuteGraphExpr sessionId Commit)
696+
697+sendNotifications :: [ClientInfo] -> EvaluatedNotifications -> IO ()
698+sendNotifications clients notifs =
699+ unless (M.null notifs) $ forM_ clients sender
700+ where
701+ sender (RemoteClientInfo sock) = RPC.sendMessage sock (NotificationMessage notifs)
702+ sender (InProcessClientInfo tvar) = putMVar tvar notifs
703+
826704-- | Discard any changes made in the current 'Session' and 'DatabaseContext'. This resets the disconnected transaction to reference the original database context of the parent transaction and is a very cheap operation.
827705rollback :: SessionId -> Connection -> IO (Either RelationalError ())
828706rollback sessionId conn@(InProcessConnection _) = executeGraphExpr sessionId conn Rollback
829−rollback sessionId conn@(RemoteProcessConnection _) = remoteCall conn (ExecuteGraphExpr sessionId Rollback)
707+rollback sessionId conn@(RemoteConnection _) = remoteCall conn (ExecuteGraphExpr sessionId Rollback)
830708
831709-- | Write the transaction graph to disk. This function can be used to incrementally write new transactions to disk.
832710processTransactionGraphPersistence :: PersistenceStrategy -> [TransactionId] -> TransactionGraph -> IO ()
@@ -842,7 +720,7 @@ readGraphTransactionIdDigest (CrashSafePersistence dbdir) = readGraphTransaction
842720-- | Return a relation whose type would match that of the relational expression if it were executed. This is useful for checking types and validating a relational expression's types.
843721typeForRelationalExpr :: SessionId -> Connection -> RelationalExpr -> IO (Either RelationalError Relation)
844722typeForRelationalExpr sessionId conn@(InProcessConnection _) relExpr = atomically $ typeForRelationalExprSTM sessionId conn relExpr
845−typeForRelationalExpr sessionId conn@(RemoteProcessConnection _) relExpr = remoteCall conn (ExecuteTypeForRelationalExpr sessionId relExpr)
723+typeForRelationalExpr sessionId conn@(RemoteConnection _) relExpr = remoteCall conn (ExecuteTypeForRelationalExpr sessionId relExpr)
846724
847725typeForRelationalExprSTM :: SessionId -> Connection -> RelationalExpr -> STM (Either RelationalError Relation)
848726typeForRelationalExprSTM sessionId (InProcessConnection conf) relExpr = do
@@ -857,7 +735,10 @@ typeForRelationalExprSTM sessionId (InProcessConnection conf) relExpr = do
857735 Schema.processRelationalExprInSchema schema relExpr
858736 case processed of
859737 Left err -> pure (Left err)
860− Right relExpr' -> pure $ runReader (RE.typeForRelationalExpr relExpr') (RE.mkRelationalExprState (Sess.concreteDatabaseContext session))
738+ Right relExpr' -> do
739+ graph <- readTVar (ipTransactionGraph conf)
740+ let reEnv = RE.mkRelationalExprEnv (Sess.concreteDatabaseContext session) graph
741+ pure $ RE.runRelationalExprM reEnv (RE.typeForRelationalExpr relExpr')
861742
862743typeForRelationalExprSTM _ _ _ = error "typeForRelationalExprSTM called on non-local connection"
863744
@@ -876,7 +757,7 @@ inclusionDependencies sessionId (InProcessConnection conf) = do
876757 else
877758 pure (Schema.inclusionDependenciesInSchema schema (B.inclusionDependencies context))
878759
879−inclusionDependencies sessionId conn@(RemoteProcessConnection _) = remoteCall conn (RetrieveInclusionDependencies sessionId)
760+inclusionDependencies sessionId conn@(RemoteConnection _) = remoteCall conn (RetrieveInclusionDependencies sessionId)
880761
881762typeConstructorMapping :: SessionId -> Connection -> IO (Either RelationalError TypeConstructorMapping)
882763typeConstructorMapping sessionId (InProcessConnection conf) = do
@@ -887,22 +768,27 @@ typeConstructorMapping sessionId (InProcessConnection conf) = do
887768 Left err -> pure $ Left err
888769 Right (session, _) -> --warning, no schema support for typeconstructors
889770 pure (Right (B.typeConstructorMapping (Sess.concreteDatabaseContext session)))
890−typeConstructorMapping sessionId conn@(RemoteProcessConnection _) = remoteCall conn (RetrieveTypeConstructorMapping sessionId)
771+typeConstructorMapping sessionId conn@(RemoteConnection _) = remoteCall conn (RetrieveTypeConstructorMapping sessionId)
891772
892773-- | Return an optimized database expression which is logically equivalent to the input database expression. This function can be used to determine which expression will actually be evaluated.
893−planForDatabaseContextExpr :: SessionId -> Connection -> DatabaseContextExpr -> IO (Either RelationalError DatabaseContextExpr)
774+planForDatabaseContextExpr :: SessionId -> Connection -> DatabaseContextExpr -> IO (Either RelationalError GraphRefDatabaseContextExpr)
894775planForDatabaseContextExpr sessionId (InProcessConnection conf) dbExpr = do
895776 let sessions = ipSessions conf
896777 atomically $ do
778+ graph <- readTVar (ipTransactionGraph conf)
897779 eSession <- sessionAndSchema sessionId sessions
898780 case eSession of
899781 Left err -> pure $ Left err
900− Right (session, _) -> if schemaName session == defaultSchemaName then
901− pure $ evalState (applyStaticDatabaseOptimization dbExpr) (RE.freshDatabaseState (Sess.concreteDatabaseContext session))
902− else -- don't show any optimization because the current optimization infrastructure relies on access to the base context- this probably underscores the need for each schema to have its own DatabaseContext, even if it is generated on-the-fly
903− pure (Right dbExpr)
904−
905−planForDatabaseContextExpr sessionId conn@(RemoteProcessConnection _) dbExpr = remoteCall conn (RetrievePlanForDatabaseContextExpr sessionId dbExpr)
782+ Right (session, _) ->
783+ if schemaName session == defaultSchemaName then do
784+ let ctx = Sess.concreteDatabaseContext session
785+ transId = Sess.parentId session
786+ gfExpr = runProcessExprM UncommittedContextMarker (processDatabaseContextExpr dbExpr)
787+ pure $ runGraphRefSOptDatabaseContextExprM transId ctx graph (optimizeGraphRefDatabaseContextExpr gfExpr)
788+ else -- don't show any optimization because the current optimization infrastructure relies on access to the base context- this probably underscores the need for each schema to have its own DatabaseContext, even if it is generated on-the-fly-}
789+ pure (Left NonConcreteSchemaPlanError)
790+
791+planForDatabaseContextExpr sessionId conn@(RemoteConnection _) dbExpr = remoteCall conn (RetrievePlanForDatabaseContextExpr sessionId dbExpr)
906792
907793-- | Return a relation which represents the current state of the global transaction graph. The attributes are
908794-- * current- boolean attribute representing whether or not the current session references this transaction
@@ -920,26 +806,29 @@ transactionGraphAsRelation sessionId (InProcessConnection conf) = do
920806 Right session ->
921807 graphAsRelation (Sess.disconnectedTransaction session) <$> readTVar tvar
922808
923−transactionGraphAsRelation sessionId conn@(RemoteProcessConnection _) = remoteCall conn (RetrieveTransactionGraph sessionId)
809+transactionGraphAsRelation sessionId conn@(RemoteConnection _) = remoteCall conn (RetrieveTransactionGraph sessionId)
924810
925811-- | Returns the names and types of the relation variables in the current 'Session'.
926812relationVariablesAsRelation :: SessionId -> Connection -> IO (Either RelationalError Relation)
927813relationVariablesAsRelation sessionId (InProcessConnection conf) = do
928814 let sessions = ipSessions conf
929815 atomically $ do
816+ graph <- readTVar (ipTransactionGraph conf)
930817 eSession <- sessionAndSchema sessionId sessions
931818 case eSession of
932819 Left err -> pure (Left err)
933820 Right (session, schema) -> do
934821 let context = Sess.concreteDatabaseContext session
935822 if Sess.schemaName session == defaultSchemaName then
936− pure $ R.relationVariablesAsRelation (relationVariables context)
823+ pure $ RE.relationVariablesAsRelation context graph
937824 else
938− case Schema.relationVariablesInSchema schema context of
825+ case Schema.relationVariablesInSchema schema of
939826 Left err -> pure (Left err)
940− Right relvars -> pure $ R.relationVariablesAsRelation relvars
827+ Right relvars -> do
828+ let schemaContext = context {relationVariables = relvars }
829+ pure $ RE.relationVariablesAsRelation schemaContext graph
941830
942−relationVariablesAsRelation sessionId conn@(RemoteProcessConnection _) = remoteCall conn (RetrieveRelationVariableSummary sessionId)
831+relationVariablesAsRelation sessionId conn@(RemoteConnection _) = remoteCall conn (RetrieveRelationVariableSummary sessionId)
943832
944833-- | Returns the names and types of the atom functions in the current 'Session'.
945834atomFunctionsAsRelation :: SessionId -> Connection -> IO (Either RelationalError Relation)
@@ -952,7 +841,7 @@ atomFunctionsAsRelation sessionId (InProcessConnection conf) = do
952841 Right (session, _) ->
953842 pure (AF.atomFunctionsAsRelation (atomFunctions (concreteDatabaseContext session)))
954843
955−atomFunctionsAsRelation sessionId conn@(RemoteProcessConnection _) = remoteCall conn (RetrieveAtomFunctionSummary sessionId)
844+atomFunctionsAsRelation sessionId conn@(RemoteConnection _) = remoteCall conn (RetrieveAtomFunctionSummary sessionId)
956845
957846databaseContextFunctionsAsRelation :: SessionId -> Connection -> IO (Either RelationalError Relation)
958847databaseContextFunctionsAsRelation sessionId (InProcessConnection conf) = do
@@ -964,7 +853,7 @@ databaseContextFunctionsAsRelation sessionId (InProcessConnection conf) = do
964853 Right (session, _) ->
965854 pure (DCF.databaseContextFunctionsAsRelation (dbcFunctions (concreteDatabaseContext session)))
966855
967−databaseContextFunctionsAsRelation sessionId conn@(RemoteProcessConnection _) = remoteCall conn (RetrieveDatabaseContextFunctionSummary sessionId)
856+databaseContextFunctionsAsRelation sessionId conn@(RemoteConnection _) = remoteCall conn (RetrieveDatabaseContextFunctionSummary sessionId)
968857
969858-- | Returns the transaction id for the connection's disconnected transaction committed parent transaction.
970859headTransactionId :: SessionId -> Connection -> IO (Either RelationalError TransactionId)
@@ -975,7 +864,7 @@ headTransactionId sessionId (InProcessConnection conf) = do
975864 case eSession of
976865 Left err -> pure (Left err)
977866 Right session -> pure $ Right (Sess.parentId session)
978−headTransactionId sessionId conn@(RemoteProcessConnection _) = remoteCall conn (RetrieveHeadTransactionId sessionId)
867+headTransactionId sessionId conn@(RemoteConnection _) = remoteCall conn (RetrieveHeadTransactionId sessionId)
979868
980869headNameSTM_ :: SessionId -> Sessions -> TVar TransactionGraph -> STM (Either RelationalError HeadName)
981870headNameSTM_ sessionId sessions graphTvar = do
@@ -983,7 +872,7 @@ headNameSTM_ sessionId sessions graphTvar = do
983872 eSession <- sessionForSessionId sessionId sessions
984873 case eSession of
985874 Left err -> pure (Left err)
986− Right session -> case transactionForId (Sess.parentId session) graph of
875+ Right session -> case RE.transactionForId (Sess.parentId session) graph of
987876 Left err -> pure (Left err)
988877 Right parentTrans -> case headNameForTransaction parentTrans graph of
989878 Nothing -> pure (Left UnknownHeadError)
@@ -995,7 +884,7 @@ headName sessionId (InProcessConnection conf) = do
995884 let sessions = ipSessions conf
996885 graphTvar = ipTransactionGraph conf
997886 atomically (headNameSTM_ sessionId sessions graphTvar)
998−headName sessionId conn@(RemoteProcessConnection _) = remoteCall conn (ExecuteHeadName sessionId)
887+headName sessionId conn@(RemoteConnection _) = remoteCall conn (ExecuteHeadName sessionId)
999888
1000889-- | Returns a listing of all available atom types.
1001890atomTypesAsRelation :: SessionId -> Connection -> IO (Either RelationalError Relation)
@@ -1009,7 +898,7 @@ atomTypesAsRelation sessionId (InProcessConnection conf) = do
1009898 case typesAsRelation (B.typeConstructorMapping (Sess.concreteDatabaseContext session)) of
1010899 Left err -> pure (Left err)
1011900 Right rel -> pure (Right rel)
1012−atomTypesAsRelation sessionId conn@(RemoteProcessConnection _) = remoteCall conn (RetrieveAtomTypesAsRelation sessionId)
901+atomTypesAsRelation sessionId conn@(RemoteConnection _) = remoteCall conn (RetrieveAtomTypesAsRelation sessionId)
1013902
1014903disconnectedTransactionIsDirty :: SessionId -> Connection -> IO (Either RelationalError Bool)
1015904disconnectedTransactionIsDirty sessionId (InProcessConnection conf) = do
@@ -1020,12 +909,12 @@ disconnectedTransactionIsDirty sessionId (InProcessConnection conf) = do
1020909 Left err -> pure (Left err)
1021910 Right session ->
1022911 pure (Right (isDirty session))
1023−disconnectedTransactionIsDirty sessionId conn@(RemoteProcessConnection _) = remoteCall conn (RetrieveSessionIsDirty sessionId)
912+disconnectedTransactionIsDirty sessionId conn@(RemoteConnection _) = remoteCall conn (RetrieveSessionIsDirty sessionId)
1024913
1025914--used only for testing- we expect this to throw an exception
1026915callTestTimeout_ :: SessionId -> Connection -> IO Bool
1027916callTestTimeout_ _ (InProcessConnection _) = error "bad testing call"
1028−callTestTimeout_ sessionId conn@(RemoteProcessConnection _) = remoteCall conn (TestTimeout sessionId)
917+callTestTimeout_ sessionId conn@(RemoteConnection _) = remoteCall conn (TestTimeout sessionId)
1029918
1030919--used in tests only
1031920transactionGraph_ :: Connection -> IO TransactionGraph
@@ -1095,11 +984,11 @@ commitLock_ sessionId conf stmBlock = do
1095984 writeTVar graphTvar graph'
1096985 let newSession = Session discon' (Sess.schemaName session)
1097986 StmMap.insert newSession sessionId sessions
1098− case transactionForId (Sess.parentId session) oldGraph of
987+ case RE.transactionForId (Sess.parentId session) oldGraph of
1099988 Left err -> pure $ Left err
1100989 Right previousTrans ->
1101990 if not (Prelude.null transactionIdsToPersist) then do
1102− (evaldNots, nodes) <- executeCommitExprSTM_ (Trans.concreteDatabaseContext previousTrans) (Sess.concreteDatabaseContext session) clientNodes
991+ (evaldNots, nodes) <- executeCommitExprSTM_ graph' (Trans.concreteDatabaseContext previousTrans) (Sess.concreteDatabaseContext session) clientNodes
1103992 nodesToNotify <- stmSetToList nodes
1104993 pure $ Right (evaldNots, nodesToNotify, graph', transactionIdsToPersist)
1105994 else pure (Right (M.empty, [], graph', []))
@@ -1110,15 +999,8 @@ commitLock_ sessionId conf stmBlock = do
1110999 Right (notsToFire, nodesToNotify, newGraph, transactionIdsToPersist) -> do
11111000 --update filesystem database, if necessary
11121001 processTransactionGraphPersistence strat transactionIdsToPersist newGraph
1113− sendNotifications nodesToNotify (ipLocalNode conf) notsToFire
1002+ sendNotifications nodesToNotify notsToFire
11141003 pure (Right ())
1115−{-
1116−writeDisconAndGraph_ :: TVar TransactionGraph -> SessionId -> Session -> Sessions -> DisconnectedTransaction -> TransactionGraph -> STM ()
1117−writeDisconAndGraph_ graphTvar sessionId session sessions discon graph = do
1118− writeTVar graphTvar graph
1119− let newSession = Session discon (Sess.schemaName session)
1120− StmMap.insert newSession sessionId sessions
1121−-}
11221004
11231005-- | Runs an IO monad, commits the result when the monad returns no errors, otherwise, rolls back the changes and the error.
11241006withTransaction :: SessionId -> Connection -> IO (Either RelationalError a) -> IO (Either RelationalError ()) -> IO (Either RelationalError a)
@@ -1160,12 +1042,54 @@ executeDataFrameExpr sessionId conn@(InProcessConnection _) dfExpr = do
11601042 case verified of
11611043 Left err -> pure (Left err)
11621044 Right attrs -> do
1163− let attrOrders = map (\(attr',order') -> DF.AttributeOrder (attributeName attr') order') (zip attrs orders)
1045+ let attrOrders = zipWith
1046+ (DF.AttributeOrder . attributeName)
1047+ attrs
1048+ orders
11641049 case DF.sortDataFrameBy attrOrders . DF.toDataFrame $ rel of
11651050 Left err -> pure (Left err)
11661051 Right dFrame -> do
11671052 let dFrame' = maybe dFrame (`DF.drop'` dFrame) (DF.offset dfExpr)
11681053 dFrame'' = maybe dFrame' (`DF.take'` dFrame') (DF.limit dfExpr)
11691054 pure (Right dFrame'')
1170−executeDataFrameExpr sessionId conn@(RemoteProcessConnection _) dfExpr = remoteCall conn (ExecuteDataFrameExpr sessionId dfExpr)
1055+executeDataFrameExpr sessionId conn@(RemoteConnection _) dfExpr = remoteCall conn (ExecuteDataFrameExpr sessionId dfExpr)
11711056
1057+validateMerkleHashes :: SessionId -> Connection -> IO (Either RelationalError ())
1058+validateMerkleHashes sessionId (InProcessConnection conf) = do
1059+ let sessions = ipSessions conf
1060+ atomically $ do
1061+ eSession <- sessionForSessionId sessionId sessions
1062+ case eSession of
1063+ Left err -> pure (Left err)
1064+ Right _ -> do
1065+ graph <- readTVar (ipTransactionGraph conf)
1066+ case Graph.validateMerkleHashes graph of
1067+ Left merkleErrs -> pure $ Left $ someErrors (map (\(MerkleValidationError tid expected actual) -> MerkleHashValidationError tid expected actual) merkleErrs)
1068+ Right () -> pure (Right ())
1069+validateMerkleHashes sessionId conn@RemoteConnection{} = remoteCall conn (ExecuteValidateMerkleHashes sessionId)
1070+
1071+type ClientNodes = StmSet.Set ClientInfo
1072+
1073+-- internal structure specific to in-process connections
1074+data InProcessConnectionConf = InProcessConnectionConf {
1075+ ipPersistenceStrategy :: PersistenceStrategy,
1076+ ipClientNodes :: ClientNodes,
1077+ ipSessions :: Sessions,
1078+ ipTransactionGraph :: TVar TransactionGraph,
1079+ ipScriptSession :: Maybe ScriptSession,
1080+ ipLocks :: Maybe (LockFile, MVar LockFileHash), -- nothing when NoPersistence
1081+ ipCallbackAsync :: Async ()
1082+ }
1083+
1084+-- clients may connect associate one socket/mvar with the server to register for change callbacks
1085+data ClientInfo = RemoteClientInfo (RPC.Locking Socket) |
1086+ InProcessClientInfo (MVar EvaluatedNotifications)
1087+
1088+instance Eq ClientInfo where
1089+ (RemoteClientInfo a) == (RemoteClientInfo b) = RPC.lockless a == RPC.lockless b
1090+ (InProcessClientInfo a) == (InProcessClientInfo b) = a == b
1091+ _ == _ = False
1092+
1093+instance Hashable ClientInfo where
1094+ hashWithSalt salt (RemoteClientInfo sock) = hashWithSalt salt (show (RPC.lockless sock))
1095+ hashWithSalt salt (InProcessClientInfo _) = hashWithSalt salt (1::Int)
src/lib/ProjectM36/Client/Simple.hs+2−1
@@ -25,7 +25,8 @@ module ProjectM36.Client.Simple (
2525 C.PersistenceStrategy(..),
2626 C.NotificationCallback,
2727 C.emptyNotificationCallback,
28− C.DatabaseContextExpr(..),
28+ C.DatabaseContextExprBase(..),
29+ C.DatabaseContextExpr,
2930 C.RelationalExprBase(..)
3031 ) where
3132
src/lib/ProjectM36/DataFrame.hs+24−14
@@ -1,8 +1,8 @@
1−{-# LANGUAGE DeriveGeneric, DeriveAnyClass #-}
1+{-# LANGUAGE DeriveGeneric, DerivingVia #-}
22{- A dataframe is a strongly-typed, ordered list of named tuples. A dataframe differs from a relation in that its tuples are ordered.-}
33module ProjectM36.DataFrame where
44import ProjectM36.Base
5−import ProjectM36.Attribute as A
5+import ProjectM36.Attribute as A hiding (drop)
66import ProjectM36.Error
77import qualified ProjectM36.Relation as R
88import ProjectM36.Relation.Show.Term
@@ -16,13 +16,19 @@ import qualified Data.List as L
1616import qualified Data.Set as S
1717import Data.Maybe
1818import qualified Data.Text as T
19−import Data.Binary
2019import Control.Arrow
20+#if __GLASGOW_HASKELL__ < 804
2121import Data.Monoid
22+#endif
2223
23−data AttributeOrderExpr = AttributeOrderExpr AttributeName Order deriving (Show, Generic, Binary)
24−data AttributeOrder = AttributeOrder AttributeName Order deriving (Show, Generic, Binary)
25−data Order = AscendingOrder | DescendingOrder deriving (Eq, Show, Generic, Binary)
24+data AttributeOrderExpr = AttributeOrderExpr AttributeName Order
25+ deriving (Show, Generic)
26+
27+data AttributeOrder = AttributeOrder AttributeName Order
28+ deriving (Show, Generic)
29+
30+data Order = AscendingOrder | DescendingOrder
31+ deriving (Eq, Show, Generic)
2632
2733ascending :: T.Text
2834ascending = "⬆"
@@ -37,9 +43,11 @@ data DataFrame = DataFrame {
3743 orders :: [AttributeOrder],
3844 attributes :: Attributes,
3945 tuples :: [DataFrameTuple]
40− } deriving (Show, Generic, Binary)
46+ }
47+ deriving (Show, Generic)
4148
42−data DataFrameTuple = DataFrameTuple Attributes (V.Vector Atom) deriving (Eq, Show, Generic, Binary)
49+data DataFrameTuple = DataFrameTuple Attributes (V.Vector Atom)
50+ deriving (Eq, Show, Generic)
4351
4452sortDataFrameBy :: [AttributeOrder] -> DataFrame -> Either RelationalError DataFrame
4553sortDataFrameBy attrOrders frame = do
@@ -73,7 +81,7 @@ compareTupleByOneAttributeName attr tuple1 tuple2 =
7381 Right atom2 -> compareAtoms atom1 atom2
7482
7583atomForAttributeName :: AttributeName -> DataFrameTuple -> Either RelationalError Atom
76−atomForAttributeName attrName (DataFrameTuple tupAttrs tupVec) = case V.findIndex (\attr -> attributeName attr == attrName) tupAttrs of
84+atomForAttributeName attrName (DataFrameTuple tupAttrs tupVec) = case V.findIndex (\attr -> attributeName attr == attrName) (attributesVec tupAttrs) of
7785 Nothing -> Left (NoSuchAttributeNamesError (S.singleton attrName))
7886 Just index -> case tupVec V.!? index of
7987 Nothing -> Left (NoSuchAttributeNamesError (S.singleton attrName))
@@ -120,17 +128,18 @@ data DataFrameExpr = DataFrameExpr {
120128 orderExprs :: [AttributeOrderExpr],
121129 offset :: Maybe Integer,
122130 limit :: Maybe Integer
123− } deriving (Show, Binary, Generic)
131+ }
132+ deriving (Show, Generic)
124133
125134dataFrameAsHTML :: DataFrame -> T.Text
126135-- web browsers don't display tables with empty cells or empty headers, so we have to insert some placeholders- it's not technically the same, but looks as expected in the browser
127136dataFrameAsHTML df
128− | length (tuples df) == 1 && L.null (attributes df) = style <>
137+ | length (tuples df) == 1 && A.null (attributes df) = style <>
129138 tablestart <>
130139 "<tr><th></th></tr>" <>
131140 "<tr><td></td></tr>" <>
132141 tablefooter <> "</table>"
133− | L.null (tuples df) && L.null (attributes df) = style <>
142+ | L.null (tuples df) && A.null (attributes df) = style <>
134143 tablestart <>
135144 "<tr><th></th></tr>" <>
136145 tablefooter <>
@@ -153,7 +162,7 @@ tuplesAsHTML = foldr folder ""
153162 folder tuple acc = acc <> tupleAsHTML tuple
154163
155164tupleAssocs :: DataFrameTuple -> [(AttributeName, Atom)]
156−tupleAssocs (DataFrameTuple attrVec tupVec) = V.toList $ V.map (first attributeName) (V.zip attrVec tupVec)
165+tupleAssocs (DataFrameTuple attrs tupVec) = V.toList $ V.map (first attributeName) (V.zip (attributesVec attrs) tupVec)
157166
158167
159168tupleAsHTML :: DataFrameTuple -> T.Text
@@ -161,10 +170,11 @@ tupleAsHTML tuple = "<tr>" <> T.concat (L.map tupleFrag (tupleAssocs tuple)) <>
161170 where
162171 tupleFrag tup = "<td>" <> atomAsHTML (snd tup) <> "</td>"
163172 atomAsHTML (RelationAtom rel) = RelHTML.relationAsHTML rel
173+ atomAsHTML (TextAtom t) = "&quot;" <> t <> "&quot;"
164174 atomAsHTML atom = atomToText atom
165175
166176attributesAsHTML :: Attributes -> [AttributeOrder] -> T.Text
167−attributesAsHTML attrs orders' = "<tr>" <> T.concat (map oneAttrHTML (V.toList attrs)) <> "</tr>"
177+attributesAsHTML attrs orders' = "<tr>" <> T.concat (map oneAttrHTML (A.toList attrs)) <> "</tr>"
168178 where
169179 oneAttrHTML attr = "<th>" <> prettyAttribute attr <> ordering (attributeName attr) <> "</th>"
170180 ordering attrName = " " <> case L.find (\(AttributeOrder nam _) -> nam == attrName) orders' of
src/lib/ProjectM36/DataTypes/Interval.hs+2
@@ -37,6 +37,7 @@ supportsInterval typ = case typ of
3737 BoolAtomType -> False
3838 RelationAtomType _ -> False
3939 ConstructedAtomType _ _ -> False --once we support an interval-style typeclass, we might enable this
40+ RelationalExprAtomType -> False
4041 TypeVariableType _ -> False
4142
4243supportsOrdering :: AtomType -> Bool
@@ -50,6 +51,7 @@ supportsOrdering typ = case typ of
5051 ByteStringAtomType -> False
5152 BoolAtomType -> False
5253 RelationAtomType _ -> False
54+ RelationalExprAtomType -> False
5355 ConstructedAtomType _ _ -> False --once we support an interval-style typeclass, we might enable this
5456 TypeVariableType _ -> False
5557
src/lib/ProjectM36/DataTypes/Primitive.hs+1
@@ -42,3 +42,4 @@ atomTypeForAtom (ByteStringAtom _) = ByteStringAtomType
4242atomTypeForAtom (BoolAtom _) = BoolAtomType
4343atomTypeForAtom (RelationAtom (Relation attrs _)) = RelationAtomType attrs
4444atomTypeForAtom (ConstructedAtom _ aType _) = aType
45+atomTypeForAtom (RelationalExprAtom _) = RelationalExprAtomType
src/lib/ProjectM36/DataTypes/Sorting.hs+1
@@ -24,6 +24,7 @@ isSortableAtomType typ = case typ of
2424 DateTimeAtomType -> True
2525 ByteStringAtomType -> False
2626 BoolAtomType -> True
27+ RelationalExprAtomType -> False
2728 RelationAtomType _ -> False
2829 ConstructedAtomType _ _ -> False
2930 TypeVariableType _ -> False
src/lib/ProjectM36/DatabaseContext.hs+24−5
@@ -1,11 +1,15 @@
11module ProjectM36.DatabaseContext where
22import ProjectM36.Base
3+import Control.Monad (void)
34import qualified Data.Map as M
45import qualified Data.HashSet as HS
56import ProjectM36.DataTypes.Basic
67import ProjectM36.AtomFunctions.Basic
7−import ProjectM36.DatabaseContextFunction
88import ProjectM36.Relation
9+import qualified Data.ByteString.Lazy as BL
10+import ProjectM36.AtomFunction as AF
11+import ProjectM36.DatabaseContextFunction as DBCF
12+import Codec.Winery
913
1014empty :: DatabaseContext
1115empty = DatabaseContext { inclusionDependencies = M.empty,
@@ -14,22 +18,37 @@ empty = DatabaseContext { inclusionDependencies = M.empty,
1418 atomFunctions = HS.empty,
1519 dbcFunctions = HS.empty,
1620 typeConstructorMapping = [] }
21+
22+-- | Remove TransactionId markers on GraphRefRelationalExpr
23+stripGraphRefRelationalExpr :: GraphRefRelationalExpr -> RelationalExpr
24+stripGraphRefRelationalExpr = void
1725
1826-- | convert an existing database context into its constituent expression.
1927databaseContextAsDatabaseContextExpr :: DatabaseContext -> DatabaseContextExpr
2028databaseContextAsDatabaseContextExpr context = MultipleExpr $ relVarsExprs ++ incDepsExprs ++ funcsExprs
2129 where
22− relVarsExprs = map (\(name, rel) -> Assign name (ExistingRelation rel)) (M.toList (relationVariables context))
30+ relVarsExprs = map (\(name, rel) -> Assign name (stripGraphRefRelationalExpr rel)) (M.toList (relationVariables context))
2331 incDepsExprs :: [DatabaseContextExpr]
2432 incDepsExprs = map (uncurry AddInclusionDependency) (M.toList (inclusionDependencies context))
25− funcsExprs = [] -- map (\func -> ) (HS.toList funcs) -- there are no databaseExprs to add atom functions yet
33+ funcsExprs = [] -- map (\func -> ) (HS.toList funcs) -- there are no databaseExprs to add atom functions yet-}
2634
2735basicDatabaseContext :: DatabaseContext
2836basicDatabaseContext = DatabaseContext { inclusionDependencies = M.empty,
29− relationVariables = M.fromList [("true", relationTrue),
30− ("false", relationFalse)],
37+ relationVariables = M.fromList [("true", ExistingRelation relationTrue),
38+ ("false", ExistingRelation relationFalse)],
3139 atomFunctions = basicAtomFunctions,
3240 dbcFunctions = basicDatabaseContextFunctions,
3341 notifications = M.empty,
3442 typeConstructorMapping = basicTypeConstructorMapping
3543 }
44+
45+--for building the Merkle hash
46+hashBytes :: DatabaseContext -> BL.ByteString
47+hashBytes ctx = BL.fromChunks [incDeps, rvs, nots, tConsMap] <> atomFs <> dbcFs
48+ where
49+ incDeps = serialise (inclusionDependencies ctx)
50+ rvs = serialise (relationVariables ctx)
51+ atomFs = HS.foldr (mappend . AF.hashBytes) mempty (atomFunctions ctx)
52+ dbcFs = HS.foldr (mappend . DBCF.hashBytes) mempty (dbcFunctions ctx)
53+ nots = serialise (notifications ctx)
54+ tConsMap = serialise (typeConstructorMapping ctx)
src/lib/ProjectM36/DatabaseContextFunction.hs+17−1
@@ -1,7 +1,9 @@
1+{-# LANGUAGE CPP #-}
12module ProjectM36.DatabaseContextFunction where
23--implements functions which operate as: [Atom] -> DatabaseContextExpr -> Either RelationalError DatabaseContextExpr
34import ProjectM36.Base
45import ProjectM36.Error
6+import ProjectM36.Serialise.Base ()
57import ProjectM36.Attribute as A
68import ProjectM36.Relation
79import ProjectM36.AtomType
@@ -9,6 +11,8 @@ import qualified Data.HashSet as HS
911import qualified Data.Map as M
1012import ProjectM36.ScriptSession
1113import qualified Data.Text as T
14+import qualified Data.ByteString.Lazy as BL
15+import Codec.Winery
1216
1317emptyDatabaseContextFunction :: DatabaseContextFunctionName -> DatabaseContextFunction
1418emptyDatabaseContextFunction name = DatabaseContextFunction {
@@ -61,7 +65,11 @@ createScriptedDatabaseContextFunction :: DatabaseContextFunctionName -> [TypeCon
6165createScriptedDatabaseContextFunction funcName argsIn retArg = AddDatabaseContextFunction funcName (argsIn ++ [databaseContextFunctionReturnType retArg])
6266
6367loadDatabaseContextFunctions :: ModName -> FuncName -> FilePath -> IO (Either LoadSymbolError [DatabaseContextFunction])
68+#ifdef PM36_HASKELL_SCRIPTING
6469loadDatabaseContextFunctions = loadFunction
70+#else
71+loadDatabaseContextFunctions _ _ _ = pure (Left LoadSymbolError)
72+#endif
6573
6674databaseContextFunctionsAsRelation :: DatabaseContextFunctions -> Either RelationalError Relation
6775databaseContextFunctionsAsRelation dbcFuncs = mkRelationFromList attrs tups
@@ -72,4 +80,12 @@ databaseContextFunctionsAsRelation dbcFuncs = mkRelationFromList attrs tups
7280 dbcFuncToTuple func = [TextAtom (dbcFuncName func),
7381 TextAtom (dbcTextType (dbcFuncType func))]
7482 dbcTextType typ = T.intercalate " -> " (map prettyAtomType typ ++ ["DatabaseContext", "DatabaseContext"])
75−
83+
84+-- for merkle hash
85+hashBytes :: DatabaseContextFunction -> BL.ByteString
86+hashBytes func = BL.fromChunks [fname, ftype, fbody]
87+ where
88+ fname = serialise (dbcFuncName func)
89+ ftype = serialise (dbcFuncType func)
90+ fbody = case dbcFuncBody func of
91+ DatabaseContextFunctionBody mBody _ -> serialise mBody
src/lib/ProjectM36/DatabaseContextFunctionError.hs+1−2
@@ -1,9 +1,8 @@
11{-# LANGUAGE DeriveGeneric, DeriveAnyClass #-}
22module ProjectM36.DatabaseContextFunctionError where
33import GHC.Generics
4−import Data.Binary
54import Control.DeepSeq
65
76{-# ANN module ("HLint: ignore Use newtype instead of data" :: String) #-}
87data DatabaseContextFunctionError = DatabaseContextFunctionUserError String
9− deriving (Generic, Eq, Show, Binary, NFData)
8+ deriving (Generic, Eq, Show, NFData)
src/lib/ProjectM36/DatabaseContextFunctionUtils.hs+15−8
@@ -3,13 +3,20 @@ import ProjectM36.RelationalExpression
33import ProjectM36.Base
44import ProjectM36.DatabaseContextFunctionError
55import ProjectM36.Error
6−import Control.Monad.State
7−import Control.Monad.Trans.Reader
6+import ProjectM36.StaticOptimizer
87
9−executeDatabaseContextExpr :: DatabaseContextExpr -> DatabaseContext -> Either DatabaseContextFunctionError DatabaseContext
10−executeDatabaseContextExpr expr context = case runState (evalDatabaseContextExpr expr) (freshDatabaseState context) of
11− (Right (), (context', _, _)) -> pure context'
12− (Left err, _) -> error (show err)
8+executeDatabaseContextExpr :: DatabaseContextExpr -> TransactionId -> TransactionGraph -> DatabaseContext -> Either DatabaseContextFunctionError DatabaseContext
9+executeDatabaseContextExpr expr transId graph context' =
10+ case run of
11+ Right st -> pure (dbc_context st)
12+ Left err -> error (show err)
13+ where
14+ env = mkDatabaseContextEvalEnv transId graph
15+ run = runDatabaseContextEvalMonad context' env (optimizeAndEvalDatabaseContextExpr True expr)
1316
14−executeRelationalExpr :: RelationalExpr -> DatabaseContext -> Either RelationalError Relation
15−executeRelationalExpr expr context = runReader (evalRelationalExpr expr) (mkRelationalExprState context)
17+executeRelationalExpr :: RelationalExpr -> DatabaseContext -> TransactionGraph -> Either RelationalError Relation
18+executeRelationalExpr expr context graph =
19+ run
20+ where
21+ env = mkRelationalExprEnv context graph
22+ run = optimizeAndEvalRelationalExpr env expr
src/lib/ProjectM36/DateExamples.hs+3−3
@@ -16,9 +16,9 @@ dateExamples = empty { inclusionDependencies = dateIncDeps,
1616 atomFunctions = basicAtomFunctions,
1717 typeConstructorMapping = basicTypeConstructorMapping }
1818 where -- these must be lower case now that data constructors are in play
19− dateRelVars = M.fromList [("s", suppliers),
20− ("p", products),
21− ("sp", supplierProducts)]
19+ dateRelVars = M.fromList [("s", ExistingRelation suppliers),
20+ ("p", ExistingRelation products),
21+ ("sp", ExistingRelation supplierProducts)]
2222 suppliers = suppliersRel
2323 products = productsRel
2424 supplierProducts = supplierProductsRel
src/lib/ProjectM36/DisconnectedTransaction.hs+7−1
@@ -8,4 +8,10 @@ schemas :: DisconnectedTransaction -> Schemas
88schemas (DisconnectedTransaction _ s _) = s
99
1010parentId :: DisconnectedTransaction -> TransactionId
11−parentId (DisconnectedTransaction pid _ _) = pid
11+parentId (DisconnectedTransaction pid _ _) = pid
12+
13+isDirty :: DisconnectedTransaction -> Bool
14+isDirty (DisconnectedTransaction _ _ flag) = flag
15+
16+freshTransaction :: TransactionId -> Schemas -> DisconnectedTransaction
17+freshTransaction tid schemas' = DisconnectedTransaction tid schemas' False
src/lib/ProjectM36/Error.hs+24−14
@@ -1,6 +1,7 @@
11{-# LANGUAGE DeriveGeneric, DeriveAnyClass #-}
22module ProjectM36.Error where
33import ProjectM36.Base
4+import ProjectM36.MerkleHash
45import ProjectM36.DatabaseContextFunctionError
56import ProjectM36.AtomFunctionError
67import qualified Data.Set as S
@@ -8,7 +9,6 @@ import Control.DeepSeq (NFData, rnf)
89import Control.DeepSeq.Generics (genericRnf)
910import GHC.Generics (Generic)
1011import qualified Data.Text as T
11−import Data.Binary
1212import Data.Typeable
1313import Control.Exception
1414
@@ -81,7 +81,7 @@ data RelationalError = NoSuchAttributeNamesError (S.Set AttributeName)
8181 | RelationValuedAttributesNotSupportedError [AttributeName]
8282 | NotificationNameInUseError NotificationName
8383 | NotificationNameNotInUseError NotificationName
84− | ImportError T.Text -- really? This should be broken out into some other error type- this has nothing to do with relational algebra
84+ | ImportError ImportError'
8585 | ExportError T.Text
8686 | UnhandledExceptionError String
8787 | MergeTransactionError MergeError
@@ -96,14 +96,21 @@ data RelationalError = NoSuchAttributeNamesError (S.Set AttributeName)
9696 | SchemaCreationError SchemaError
9797
9898 | ImproperDatabaseStateError
99−
99+
100+ | NonConcreteSchemaPlanError
101+
102+ | NoUncommittedContextInEvalError
103+ | TupleExprsReferenceMultipleMarkersError
104+
105+ | MerkleHashValidationError TransactionId MerkleHash MerkleHash
106+
100107 | MultipleErrors [RelationalError]
101− deriving (Show,Eq,Generic,Binary,Typeable, NFData)
108+ deriving (Show,Eq,Generic,Typeable, NFData)
102109
103110data PersistenceError = InvalidDirectoryError FilePath |
104111 MissingTransactionError TransactionId |
105112 WrongDatabaseFormatVersionError String String
106− deriving (Show, Eq, Generic, Binary, NFData)
113+ deriving (Show, Eq, Generic, NFData)
107114
108115--collapse list of errors into normal error- if there is just one, just return one
109116someErrors :: [RelationalError] -> RelationalError
@@ -121,7 +128,7 @@ data MergeError = SelectedHeadMismatchMergeError |
121128 StrategyViolatesComponentMergeError | --failed merge in inc deps, relvars, etc.
122129 StrategyViolatesRelationVariableMergeError |
123130 StrategyViolatesTypeConstructorMergeError
124− deriving (Show, Eq, Generic, Binary, Typeable)
131+ deriving (Show, Eq, Generic, Typeable)
125132
126133instance NFData MergeError where rnf = genericRnf
127134
@@ -129,17 +136,20 @@ data ScriptCompilationError = TypeCheckCompilationError String String | --expect
129136 SyntaxErrorCompilationError String |
130137 ScriptCompilationDisabledError |
131138 OtherScriptCompilationError String
132− deriving (Show, Eq, Generic, Binary, Typeable, NFData)
139+ deriving (Show, Eq, Generic, Typeable, NFData)
133140
134141instance Exception ScriptCompilationError
135142
136143data SchemaError = RelVarReferencesMissing (S.Set RelVarName) |
137144 RelVarInReferencedMoreThanOnce RelVarName |
138145 RelVarOutReferencedMoreThanOnce RelVarName
139− deriving (Show, Eq, Generic, Binary, Typeable, NFData)
140−
141−
142−-- errors returned from the distributed-process call handlers
143−data ServerError = RequestTimeoutError |
144− ProcessDiedError String
145− deriving (Generic, Binary, Eq)
146+ deriving (Show, Eq, Generic, Typeable, NFData)
147+
148+
149+data ImportError' = InvalidSHA256Error T.Text
150+ | SHA256MismatchError T.Text T.Text
151+ | InvalidFileURIError T.Text
152+ | ImportFileDecodeError T.Text
153+ | ImportFileError T.Text
154+ | ImportDownloadError T.Text
155+ deriving (Show, Eq, Generic, Typeable, NFData)
src/lib/ProjectM36/FileLock.hs+1−1
@@ -1,4 +1,4 @@
1−{-# LANGUAGE CPP, NamedFieldPuns #-}
1+{-# LANGUAGE CPP #-}
22--cross-platform file locking utilizing POSIX file locking on Unix/Linux and Windows file locking
33--hackage's System.FileLock doesn't support POSIX advisory locks nor locking file based on file descriptors, hence this needless rewrite
44module ProjectM36.FileLock where
src/lib/ProjectM36/GraphRefRelationalExpr.hsnew file+45
@@ -0,0 +1,45 @@
1+module ProjectM36.GraphRefRelationalExpr where
2+--evaluate relational expressions across the entire transaction graph to support cross-transaction referencing
3+import ProjectM36.Base
4+import qualified Data.Set as S
5+
6+--import Debug.Trace
7+
8+data SingularTransactionRef = SingularTransactionRef GraphRefTransactionMarker |
9+ MultipleTransactionsRef |
10+ NoTransactionsRef
11+ deriving (Eq, Show)
12+
13+instance Semigroup SingularTransactionRef where
14+ NoTransactionsRef <> x = x
15+ MultipleTransactionsRef <> _ = MultipleTransactionsRef
16+ SingularTransactionRef tidA <> s@(SingularTransactionRef tidB) =
17+ if tidA == tidB then
18+ s
19+ else
20+ MultipleTransactionsRef
21+ s@SingularTransactionRef{} <> NoTransactionsRef = s
22+ _ <> MultipleTransactionsRef = MultipleTransactionsRef
23+
24+instance Monoid SingularTransactionRef where
25+ mempty = NoTransactionsRef
26+
27+-- | return `Just transid` if this GraphRefRelationalExpr refers to just one transaction in the graph. This is useful for determining if certain optimizations can apply.
28+singularTransaction :: Foldable t => t GraphRefTransactionMarker -> SingularTransactionRef
29+singularTransaction expr
30+ | S.null transSet = NoTransactionsRef
31+ | S.size transSet == 1 = SingularTransactionRef (head (S.toList transSet))
32+ | otherwise = MultipleTransactionsRef
33+ where
34+ transSet = foldr S.insert S.empty expr
35+
36+-- | Return True if two 'GraphRefRelationalExpr's both refer exclusively to the same transaction (or none at all).
37+inSameTransaction :: GraphRefRelationalExpr -> GraphRefRelationalExpr -> Maybe GraphRefTransactionMarker
38+inSameTransaction exprA exprB = case (stA, stB) of
39+ (SingularTransactionRef tA, SingularTransactionRef tB) | tA == tB -> Just tA
40+ _ -> Nothing
41+ where stA = singularTransaction exprA
42+ stB = singularTransaction exprB
43+
44+singularTransactions :: (Foldable f, Foldable t) => f (t GraphRefTransactionMarker) -> SingularTransactionRef
45+singularTransactions = foldMap singularTransaction
src/lib/ProjectM36/InclusionDependency.hs+5−6
@@ -4,17 +4,16 @@ import ProjectM36.Attribute
44import ProjectM36.Error
55import ProjectM36.Relation
66import qualified Data.Map as M
7−import qualified Data.Text as T
87
98inclusionDependenciesAsRelation :: InclusionDependencies -> Either RelationalError Relation
109inclusionDependenciesAsRelation incDeps =
1110 mkRelationFromList attrs (map incDepAsAtoms (M.toList incDeps))
1211 where
1312 attrs = attributesFromList [Attribute "name" TextAtomType,
14− Attribute "sub" TextAtomType,
15− Attribute "super" TextAtomType
13+ Attribute "sub" RelationalExprAtomType,
14+ Attribute "super" RelationalExprAtomType
1615 ]
1716 incDepAsAtoms (name, InclusionDependency exprA exprB) = [TextAtom name,
18− TextAtom (T.pack (show exprA)),
19− TextAtom (T.pack (show exprB))]
20−
17+ RelationalExprAtom exprA,
18+ RelationalExprAtom exprB]
19+
src/lib/ProjectM36/IsomorphicSchema.hs+26−27
@@ -1,20 +1,20 @@
1−{-# LANGUAGE DeriveGeneric, DeriveAnyClass, LambdaCase #-}
1+{-# LANGUAGE DeriveGeneric, LambdaCase, DerivingVia #-}
22module ProjectM36.IsomorphicSchema where
33import ProjectM36.Base
44import ProjectM36.Error
55import ProjectM36.MiscUtils
6−import ProjectM36.RelationalExpression
76import ProjectM36.Relation
7+import ProjectM36.NormalizeExpr
8+import ProjectM36.RelationalExpression
89import qualified ProjectM36.AttributeNames as AN
910import Control.Monad
10−import Control.Monad.State
11−import Control.Monad.Trans.Reader
1211import GHC.Generics
13−import Data.Binary
1412import qualified Data.Map as M
1513import qualified Data.Set as S
1614import qualified Data.List as L
15+#if __GLASGOW_HASKELL__ < 804
1716import Data.Monoid
17+#endif
1818-- isomorphic schemas offer bi-directional functors between two schemas
1919
2020--TODO: note that renaming a relvar should alter any stored isomorphisms as well
@@ -27,8 +27,7 @@ import Data.Monoid
2727
2828data SchemaExpr = AddSubschema SchemaName SchemaIsomorphs |
2929 RemoveSubschema SchemaName
30− deriving (Generic, Binary, Show)
31−
30+ deriving (Generic, Show)
3231
3332isomorphs :: Schema -> SchemaIsomorphs
3433isomorphs (Schema i) = i
@@ -254,15 +253,15 @@ inclusionDependencyInSchema schema (InclusionDependency rexprA rexprB) = do
254253inclusionDependenciesInSchema :: Schema -> InclusionDependencies -> Either RelationalError InclusionDependencies
255254inclusionDependenciesInSchema schema incDeps = M.fromList <$> mapM (\(depName, dep) -> inclusionDependencyInSchema schema dep >>= \newDep -> pure (depName, newDep)) (M.toList incDeps)
256255
257−relationVariablesInSchema :: Schema -> DatabaseContext -> Either RelationalError RelationVariables
258−relationVariablesInSchema schema@(Schema morphs) context = foldM transform M.empty morphs
256+relationVariablesInSchema :: Schema -> Either RelationalError RelationVariables
257+relationVariablesInSchema schema@(Schema morphs) = foldM transform M.empty morphs
259258 where
260259 transform newRvMap morph = do
261260 let rvNames = isomorphInRelVarNames morph
262261 rvAssocs <- mapM (\rv -> do
263262 expr' <- processRelationalExprInSchema schema (RelationVariable rv ())
264− rel <- runReader (evalRelationalExpr expr') (RelationalExprStateElems context)
265− pure (rv, rel)) rvNames
263+ let gfExpr = runProcessExprM UncommittedContextMarker (processRelationalExpr expr')
264+ pure (rv, gfExpr)) rvNames
266265 pure (M.union newRvMap (M.fromList rvAssocs))
267266
268267
@@ -310,24 +309,24 @@ createIncDepsForIsomorph sname (IsoRestrict origRv predi (rvTrue, rvFalse)) = le
310309createIncDepsForIsomorph _ _ = M.empty
311310
312311-- in the case of IsoRestrict, the database context should be updated with the restriction so that if the restriction does not hold, then the schema cannot be created
313−evalSchemaExpr :: SchemaExpr -> DatabaseContext -> Subschemas -> Either RelationalError (Subschemas, DatabaseContext)
314−evalSchemaExpr (AddSubschema sname morphs) context sschemas =
312+evalSchemaExpr :: SchemaExpr -> DatabaseContext -> TransactionId -> TransactionGraph -> Subschemas -> Either RelationalError (Subschemas, DatabaseContext)
313+evalSchemaExpr (AddSubschema sname morphs) context transId graph sschemas =
315314 if M.member sname sschemas then
316315 Left (SubschemaNameInUseError sname)
317− else case valid of
318− Just err -> Left (SchemaCreationError err)
319− Nothing ->
320− let newSchemas = M.insert sname newSchema sschemas
321− moreIncDeps = foldr (\morph acc -> M.union acc (createIncDepsForIsomorph sname morph)) M.empty morphs
322− incDepExprs = MultipleExpr (map (uncurry AddInclusionDependency) (M.toList moreIncDeps))
323− in
324− case runState (evalDatabaseContextExpr incDepExprs) (context, M.empty, False) of
325− (Left err, _) -> Left err
326− (Right (), (newContext,_,_)) -> pure (newSchemas, newContext) --need to propagate dirty flag here
327− where
328− newSchema = Schema morphs
329− valid = validateSchema newSchema context
330−evalSchemaExpr (RemoveSubschema sname) context sschemas = if M.member sname sschemas then
316+ else
317+ case validateSchema (Schema morphs) context of
318+ Just err -> Left (SchemaCreationError err)
319+ Nothing -> do
320+ let newSchemas = M.insert sname newSchema sschemas
321+ newSchema = Schema morphs
322+ moreIncDeps = foldr (\morph acc -> M.union acc (createIncDepsForIsomorph sname morph)) M.empty morphs
323+ incDepExprs = MultipleExpr (map (uncurry AddInclusionDependency) (M.toList moreIncDeps))
324+ dbenv = mkDatabaseContextEvalEnv transId graph
325+ dbstate <- runDatabaseContextEvalMonad context dbenv (evalGraphRefDatabaseContextExpr incDepExprs)
326+ pure (newSchemas, dbc_context dbstate)
327+--need to propagate dirty flag here
328+
329+evalSchemaExpr (RemoveSubschema sname) context _ _ sschemas = if M.member sname sschemas then
331330 pure (M.delete sname sschemas, context)
332331 else
333332 Left (SubschemaNameNotInUseError sname)
src/lib/ProjectM36/Key.hs+2
@@ -2,7 +2,9 @@ module ProjectM36.Key where
22import ProjectM36.Base
33import ProjectM36.Relation
44import qualified Data.Set as S
5+#if __GLASGOW_HASKELL__ < 804
56import Data.Monoid
7+#endif
68
79{-
810keys can be implemented using inclusion dependencies as well: the count of the projection of the keys' attributes must be equal to the count of the tuples- p. 120 Database in Depth
src/lib/ProjectM36/MerkleHash.hsnew file+9
@@ -0,0 +1,9 @@
1+{-# LANGUAGE GeneralizedNewtypeDeriving, DeriveGeneric, DerivingVia #-}
2+module ProjectM36.MerkleHash where
3+import Data.ByteString (ByteString)
4+import GHC.Generics
5+import Control.DeepSeq (NFData)
6+
7+newtype MerkleHash = MerkleHash { _unMerkleHash :: ByteString }
8+ deriving (Show, Eq, Generic, Monoid, Semigroup, NFData)
9+
src/lib/ProjectM36/NormalizeExpr.hsnew file+132
@@ -0,0 +1,132 @@
1+-- | Functions to convert all types of expresions into their GraphRef- equivalents.
2+module ProjectM36.NormalizeExpr where
3+import ProjectM36.Base
4+import Control.Monad.Trans.Reader as R
5+import qualified Data.Map as M
6+
7+--used to process/normalize exprs to their respective graph ref forms
8+type ProcessExprM a = Reader GraphRefTransactionMarker a
9+
10+type CurrentTransactionId = TransactionId
11+
12+runProcessExprM :: GraphRefTransactionMarker -> ProcessExprM a -> a
13+runProcessExprM mtid m = runReader m mtid
14+
15+askMarker :: ProcessExprM GraphRefTransactionMarker
16+askMarker = R.ask
17+
18+-- convert a RelationalExpr into a GraphRefRelationalExpr using the current trans Id
19+processRelationalExpr :: RelationalExpr -> ProcessExprM GraphRefRelationalExpr
20+processRelationalExpr (MakeRelationFromExprs mAttrs tupleExprs) = do
21+ mAttrs' <- case mAttrs of
22+ Nothing -> pure Nothing
23+ Just mAttrs'' -> Just <$> mapM processAttributeExpr mAttrs''
24+ MakeRelationFromExprs mAttrs' <$> processTupleExprs tupleExprs
25+processRelationalExpr (MakeStaticRelation attrs tupSet) = pure (MakeStaticRelation attrs tupSet)
26+processRelationalExpr (ExistingRelation rel) = pure (ExistingRelation rel)
27+--requires current trans id and graph
28+processRelationalExpr (RelationVariable rv ()) = RelationVariable rv <$> askMarker
29+processRelationalExpr (Project attrNames expr) = Project <$> processAttributeNames attrNames <*> processRelationalExpr expr
30+processRelationalExpr (Union exprA exprB) = Union <$> processRelationalExpr exprA <*> processRelationalExpr exprB
31+processRelationalExpr (Join exprA exprB) = Join <$> processRelationalExpr exprA <*> processRelationalExpr exprB
32+processRelationalExpr (Rename attrA attrB expr) =
33+ Rename attrA attrB <$> processRelationalExpr expr
34+processRelationalExpr (Difference exprA exprB) = Difference <$> processRelationalExpr exprA <*> processRelationalExpr exprB
35+processRelationalExpr (Group attrNames attrName expr) = Group <$> processAttributeNames attrNames <*> pure attrName <*> processRelationalExpr expr
36+processRelationalExpr (Ungroup attrName expr) = Ungroup attrName <$> processRelationalExpr expr
37+processRelationalExpr (Restrict pred' expr) = Restrict <$> processRestrictionPredicateExpr pred' <*> processRelationalExpr expr
38+processRelationalExpr (Equals exprA exprB) =
39+ Equals <$> processRelationalExpr exprA <*> processRelationalExpr exprB
40+processRelationalExpr (NotEquals exprA exprB) =
41+ NotEquals <$> processRelationalExpr exprA <*> processRelationalExpr exprB
42+processRelationalExpr (Extend extendExpr expr) =
43+ Extend <$> processExtendTupleExpr extendExpr <*> processRelationalExpr expr
44+processRelationalExpr (With macros expr) =
45+ With <$> mapM (\(wnexpr, macroExpr) -> (,) <$> processWithNameExpr wnexpr <*> processRelationalExpr macroExpr) macros <*> processRelationalExpr expr
46+
47+processWithNameExpr :: WithNameExpr -> ProcessExprM GraphRefWithNameExpr
48+processWithNameExpr (WithNameExpr rvname ()) =
49+ WithNameExpr rvname <$> askMarker
50+
51+processAttributeNames :: AttributeNames -> ProcessExprM GraphRefAttributeNames
52+processAttributeNames (AttributeNames nameSet) = pure $ AttributeNames nameSet
53+processAttributeNames (InvertedAttributeNames attrNameSet) =
54+ pure $ InvertedAttributeNames attrNameSet
55+processAttributeNames (UnionAttributeNames attrNamesA attrNamesB) = UnionAttributeNames <$> processAttributeNames attrNamesA <*> processAttributeNames attrNamesB
56+processAttributeNames (IntersectAttributeNames attrNamesA attrNamesB) = IntersectAttributeNames <$> processAttributeNames attrNamesA <*> processAttributeNames attrNamesB
57+processAttributeNames (RelationalExprAttributeNames expr) = RelationalExprAttributeNames <$> processRelationalExpr expr
58+
59+processDatabaseContextExpr :: DatabaseContextExpr -> ProcessExprM GraphRefDatabaseContextExpr
60+processDatabaseContextExpr expr =
61+ case expr of
62+ NoOperation -> pure NoOperation
63+ Define nam attrExprs -> Define nam <$> mapM processAttributeExpr attrExprs
64+ Undefine nam -> pure (Undefine nam)
65+ Assign nam rexpr -> Assign nam <$> processRelationalExpr rexpr
66+ Insert nam rexpr -> Insert nam <$> processRelationalExpr rexpr
67+ Delete nam pred' -> Delete nam <$> processRestrictionPredicateExpr pred'
68+ Update nam attrMap pred' -> Update nam attrMap <$> processRestrictionPredicateExpr pred'
69+
70+ AddInclusionDependency nam dep -> pure (AddInclusionDependency nam dep)
71+ RemoveInclusionDependency nam -> pure (RemoveInclusionDependency nam)
72+ AddNotification nam exprA exprB exprC -> pure (AddNotification nam exprA exprB exprC)
73+ RemoveNotification nam -> pure (RemoveNotification nam)
74+ AddTypeConstructor tyDef consDefs -> pure (AddTypeConstructor tyDef consDefs)
75+ RemoveTypeConstructor tyName -> pure (RemoveTypeConstructor tyName)
76+
77+ RemoveAtomFunction aFuncName -> pure (RemoveAtomFunction aFuncName)
78+ RemoveDatabaseContextFunction funcName -> pure (RemoveDatabaseContextFunction funcName)
79+ ExecuteDatabaseContextFunction funcName atomExprs -> ExecuteDatabaseContextFunction funcName <$> mapM processAtomExpr atomExprs
80+ MultipleExpr exprs -> MultipleExpr <$> mapM processDatabaseContextExpr exprs
81+
82+processDatabaseContextIOExpr :: DatabaseContextIOExpr -> ProcessExprM GraphRefDatabaseContextIOExpr
83+processDatabaseContextIOExpr (AddAtomFunction f tcs sc) =
84+ pure (AddAtomFunction f tcs sc)
85+processDatabaseContextIOExpr (LoadAtomFunctions mod' fun file) =
86+ pure (LoadAtomFunctions mod' fun file)
87+processDatabaseContextIOExpr (AddDatabaseContextFunction mod' fun path) =
88+ pure (AddDatabaseContextFunction mod' fun path)
89+processDatabaseContextIOExpr (LoadDatabaseContextFunctions mod' fun path) =
90+ pure (LoadDatabaseContextFunctions mod' fun path)
91+processDatabaseContextIOExpr (CreateArbitraryRelation rvName attrExprs range) =
92+ CreateArbitraryRelation rvName <$> mapM processAttributeExpr attrExprs <*> pure range
93+
94+processRestrictionPredicateExpr :: RestrictionPredicateExpr -> ProcessExprM GraphRefRestrictionPredicateExpr
95+processRestrictionPredicateExpr TruePredicate = pure TruePredicate
96+processRestrictionPredicateExpr (AndPredicate a b) = AndPredicate <$> processRestrictionPredicateExpr a <*> processRestrictionPredicateExpr b
97+processRestrictionPredicateExpr (OrPredicate a b) = OrPredicate <$> processRestrictionPredicateExpr a <*> processRestrictionPredicateExpr b
98+processRestrictionPredicateExpr (NotPredicate a) = NotPredicate <$> processRestrictionPredicateExpr a
99+processRestrictionPredicateExpr (RelationalExprPredicate expr) =
100+ RelationalExprPredicate <$> processRelationalExpr expr
101+processRestrictionPredicateExpr (AtomExprPredicate expr) =
102+ AtomExprPredicate <$> processAtomExpr expr
103+processRestrictionPredicateExpr (AttributeEqualityPredicate nam expr) =
104+ AttributeEqualityPredicate nam <$> processAtomExpr expr
105+
106+processExtendTupleExpr :: ExtendTupleExpr -> ProcessExprM GraphRefExtendTupleExpr
107+processExtendTupleExpr (AttributeExtendTupleExpr nam atomExpr) =
108+ AttributeExtendTupleExpr nam <$> processAtomExpr atomExpr
109+
110+processAtomExpr :: AtomExpr -> ProcessExprM GraphRefAtomExpr
111+processAtomExpr (AttributeAtomExpr nam) = pure $ AttributeAtomExpr nam
112+processAtomExpr (NakedAtomExpr atom) = pure $ NakedAtomExpr atom
113+processAtomExpr (FunctionAtomExpr fName atomExprs ()) =
114+ FunctionAtomExpr fName <$> mapM processAtomExpr atomExprs <*> askMarker
115+processAtomExpr (RelationAtomExpr expr) = RelationAtomExpr <$> processRelationalExpr expr
116+processAtomExpr (ConstructedAtomExpr dConsName atomExprs ()) = ConstructedAtomExpr dConsName <$> mapM processAtomExpr atomExprs <*> askMarker
117+
118+processTupleExprs :: TupleExprs -> ProcessExprM GraphRefTupleExprs
119+processTupleExprs (TupleExprs () tupleExprs) = do
120+ marker <- askMarker
121+ TupleExprs marker <$> mapM processTupleExpr tupleExprs
122+
123+processTupleExpr :: TupleExpr -> ProcessExprM GraphRefTupleExpr
124+processTupleExpr (TupleExpr tMap) =
125+ TupleExpr . M.fromList <$> mapM (\(k,v) -> (,) k <$> processAtomExpr v) (M.toList tMap)
126+
127+--convert AttributeExpr to GraphRefAttributeExpr
128+processAttributeExpr :: AttributeExpr -> ProcessExprM GraphRefAttributeExpr
129+processAttributeExpr (AttributeAndTypeNameExpr nam tCons ()) =
130+ AttributeAndTypeNameExpr nam tCons <$> askMarker
131+processAttributeExpr (NakedAttributeExpr attr) = pure $ NakedAttributeExpr attr
132+
src/lib/ProjectM36/Notifications.hs+12−7
@@ -1,17 +1,22 @@
11module ProjectM36.Notifications where
22import ProjectM36.Base
3+import ProjectM36.Error
34import ProjectM36.RelationalExpression
4−import Control.Monad.Trans.Reader
5+import ProjectM36.StaticOptimizer
56import qualified Data.Map as M
67import Data.Either (isRight)
78
89-- | Returns the notifications which should be triggered based on the transition from the first 'DatabaseContext' to the second 'DatabaseContext'.
9−notificationChanges :: Notifications -> DatabaseContext -> DatabaseContext -> Notifications
10−notificationChanges nots context1 context2 = M.filter notificationFilter nots
10+notificationChanges :: Notifications -> TransactionGraph -> DatabaseContext -> DatabaseContext -> Notifications
11+notificationChanges nots graph context1 context2 = M.filter notificationFilter nots
1112 where
12− notificationFilter (Notification chExpr _ _) = let oldChangeEval = evalChangeExpr chExpr (RelationalExprStateElems context1)
13− newChangeEval = evalChangeExpr chExpr (RelationalExprStateElems context2) in
14− oldChangeEval /= newChangeEval && isRight oldChangeEval
15− evalChangeExpr chExpr = runReader (evalRelationalExpr chExpr)
13+ notificationFilter (Notification chExpr _ _) = oldChangeEval /= newChangeEval && isRight oldChangeEval
14+ where
15+ oldChangeEval = evalChangeExpr chExpr (mkRelationalExprEnv context1 graph)
16+ newChangeEval = evalChangeExpr chExpr (mkRelationalExprEnv context2 graph)
17+
18+ evalChangeExpr :: RelationalExpr -> RelationalExprEnv -> Either RelationalError Relation
19+ evalChangeExpr chExpr env =
20+ optimizeAndEvalRelationalExpr env chExpr
1621
1722
src/lib/ProjectM36/Persist.hs+3−4
@@ -36,7 +36,6 @@ import Foreign.C
3636#endif
3737
3838import System.IO (withFile, IOMode(WriteMode), Handle)
39−import qualified Data.ByteString.Lazy as BS
4039import qualified Data.ByteString as BS'
4140import qualified Data.Text.Encoding as TE
4241
@@ -100,10 +99,10 @@ syncDirectory :: DiskSync -> FilePath -> IO ()
10099syncDirectory FsyncDiskSync path = directoryFsync path
101100syncDirectory NoDiskSync _ = pure ()
102101
103−writeBSFileSync :: DiskSync -> FilePath -> BS.ByteString -> IO ()
102+writeBSFileSync :: DiskSync -> FilePath -> BS'.ByteString -> IO ()
104103writeBSFileSync sync path bstring =
105104 withFile path WriteMode $ \handle -> do
106− BS.hPut handle bstring
105+ BS'.hPut handle bstring
107106 syncHandle sync handle
108107
109108directoryFsync :: FilePath -> IO ()
@@ -131,4 +130,4 @@ fdCount = do
131130 fds <- getDirectoryContents FDDIR
132131 pure ((length fds) - 2)
133132--not supported on non-linux
134−#endif
133+#endif
src/lib/ProjectM36/Relation.hs+19−40
@@ -4,14 +4,11 @@ import qualified Data.Set as S
44import qualified Data.HashSet as HS
55import Control.Monad
66import qualified Data.Vector as V
7−import qualified Data.Map as M
8−import ProjectM36.AtomType
97import ProjectM36.Base
108import ProjectM36.Tuple
119import qualified ProjectM36.Attribute as A
1210import ProjectM36.TupleSet
1311import ProjectM36.Error
14−import ProjectM36.MiscUtils
1512--import qualified Control.Parallel.Strategies as P
1613import qualified ProjectM36.TypeConstructorDef as TCD
1714import qualified ProjectM36.DataConstructorDef as DCD
@@ -19,7 +16,6 @@ import qualified Data.Text as T
1916import Data.Either (isRight)
2017import System.Random.Shuffle
2118import Control.Monad.Random
22−import Data.List (sort)
2319
2420attributes :: Relation -> Attributes
2521attributes (Relation attrs _ ) = attrs
@@ -37,7 +33,7 @@ atomTypeForName :: AttributeName -> Relation -> Either RelationalError AtomType
3733atomTypeForName attrName (Relation attrs _) = A.atomTypeForAttributeName attrName attrs
3834
3935mkRelationFromList :: Attributes -> [[Atom]] -> Either RelationalError Relation
40−mkRelationFromList attrs atomMatrix =
36+mkRelationFromList attrs atomMatrix = do
4137 Relation attrs <$> mkTupleSetFromList attrs atomMatrix
4238
4339emptyRelationWithAttrs :: Attributes -> Relation
@@ -45,11 +41,6 @@ emptyRelationWithAttrs attrs = Relation attrs emptyTupleSet
4541
4642mkRelation :: Attributes -> RelationTupleSet -> Either RelationalError Relation
4743mkRelation attrs tupleSet =
48− --check that all attributes are unique- this cannot be done when creating attributes because the check can become expensive
49− let duplicateAttrNames = dupes (sort (map A.attributeName (V.toList attrs))) in
50− if not (null duplicateAttrNames) then
51− Left (DuplicateAttributeNamesError (S.fromList duplicateAttrNames))
52− else
5344 --check that all tuples have the same keys
5445 --check that all tuples have keys (1-N) where N is the attribute count
5546 case verifyTupleSet attrs tupleSet of
@@ -95,13 +86,12 @@ union (Relation attrs1 tupSet1) (Relation attrs2 tupSet2) =
9586 else
9687 Right $ Relation attrs1 newtuples
9788 where
98− newtuples = RelationTupleSet $ HS.toList . HS.fromList $ asList tupSet1 ++ map (reorderTuple attrs1) (asList tupSet2)
99−
100−project :: S.Set AttributeName -> Relation -> Either RelationalError Relation
89+ newtuples = tupleSetUnion attrs1 tupSet1 tupSet2
90+
91+project :: S.Set AttributeName -> Relation -> Either RelationalError Relation
10192project attrNames rel@(Relation _ tupSet) = do
10293 newAttrs <- A.projectionAttributesForNames attrNames (attributes rel)
103− let newAttrNameSet = A.attributeNameSet newAttrs
104− newTupleList = map (tupleProject newAttrNameSet) (asList tupSet)
94+ newTupleList <- mapM (tupleProject newAttrs) (asList tupSet)
10595 pure (Relation newAttrs (RelationTupleSet (HS.toList (HS.fromList newTupleList))))
10696
10797rename :: AttributeName -> AttributeName -> Relation -> Either RelationalError Relation
@@ -156,7 +146,7 @@ group groupAttrNames newAttrName rel = do
156146 groupProjectionAttributes <- A.projectionAttributesForNames groupAttrNames (attributes rel)
157147 let groupAttr = Attribute newAttrName (RelationAtomType groupProjectionAttributes)
158148 matchingRelTuple tupIn = case imageRelationFor tupIn rel of
159− Right rel2 -> RelationTuple (V.singleton groupAttr) (V.singleton (RelationAtom rel2))
149+ Right rel2 -> RelationTuple (A.singleton groupAttr) (V.singleton (RelationAtom rel2))
160150 Left _ -> undefined
161151 mogrifier tupIn = pure (tupleExtend tupIn (matchingRelTuple tupIn))
162152 newAttrs = A.addAttribute groupAttr nonGroupProjectionAttributes
@@ -170,7 +160,8 @@ restrictEq :: RelationTuple -> Relation -> Either RelationalError Relation
170160restrictEq tuple = restrict rfilter
171161 where
172162 rfilter :: RelationTuple -> Either RelationalError Bool
173− rfilter tupleIn = pure (tupleIntersection tuple tupleIn == tuple)
163+ rfilter tupleIn = do
164+ pure (tupleIntersection tuple tupleIn == tuple)
174165
175166-- unwrap relation-valued attribute
176167-- return error if relval attrs and nongroup attrs overlap
@@ -192,13 +183,13 @@ ungroup relvalAttrName rel = case attributesForRelval relvalAttrName rel of
192183tupleUngroup :: AttributeName -> Attributes -> RelationTuple -> Either RelationalError Relation
193184tupleUngroup relvalAttrName newAttrs tuple = do
194185 relvalRelation <- relationForAttributeName relvalAttrName tuple
186+ let nonGroupAttrs = A.intersection newAttrs (tupleAttributes tuple)
187+ nonGroupTupleProjection <- tupleProject nonGroupAttrs tuple
188+ let folder tupleIn acc = case acc of
189+ Left err -> Left err
190+ Right accRel ->
191+ union accRel $ Relation newAttrs (RelationTupleSet [tupleExtend nonGroupTupleProjection tupleIn])
195192 relFold folder (Right $ Relation newAttrs emptyTupleSet) relvalRelation
196− where
197− nonGroupTupleProjection = tupleProject nonGroupAttrNames tuple
198− nonGroupAttrNames = A.attributeNameSet newAttrs
199− folder tupleIn acc = case acc of
200− Left err -> Left err
201− Right accRel -> union accRel $ Relation newAttrs (RelationTupleSet [tupleExtend nonGroupTupleProjection tupleIn])
202193
203194attributesForRelval :: AttributeName -> Relation -> Either RelationalError Attributes
204195attributesForRelval relvalAttrName (Relation attrs _) = do
@@ -253,7 +244,8 @@ relMap mapper (Relation attrs tupleSet) =
253244
254245relMogrify :: (RelationTuple -> Either RelationalError RelationTuple) -> Attributes -> Relation -> Either RelationalError Relation
255246relMogrify mapper newAttributes (Relation _ tupSet) = do
256− newTuples <- mapM mapper (asList tupSet)
247+ newTuples <- mapM (fmap (reorderTuple newAttributes) . mapper) (asList tupSet)
248+
257249 mkRelationFromTuples newAttributes newTuples
258250
259251relFold :: (RelationTuple -> a -> a) -> a -> Relation -> a
@@ -299,25 +291,12 @@ typesAsRelation types = mkRelationFromTuples attrs tuples
299291 dConsType = RelationAtomType subAttrs
300292 tuples = map mkTypeConsDescription types
301293
302− mkTypeConsDescription (tCons, dConsList) = RelationTuple attrs (V.fromList [TextAtom (TCD.name tCons), mkDataConsRelation dConsList])
294+ mkTypeConsDescription (tCons, dConsList) =
295+ RelationTuple attrs (V.fromList [TextAtom (TCD.name tCons), mkDataConsRelation dConsList])
303296
304297 mkDataConsRelation dConsList = case mkRelationFromTuples subAttrs $ map (\dCons -> RelationTuple subAttrs (V.singleton $ TextAtom $ T.intercalate " " (DCD.name dCons:map (T.pack . show) (DCD.fields dCons)))) dConsList of
305298 Left err -> error ("mkRelationFromTuples pooped " ++ show err)
306299 Right rel -> RelationAtom rel
307−
308−-- | Return a Relation describing the relation variables.
309−relationVariablesAsRelation :: M.Map RelVarName Relation -> Either RelationalError Relation
310−relationVariablesAsRelation relVarMap = mkRelationFromList attrs tups
311− where
312− subrelAttrs = A.attributesFromList [Attribute "attribute" TextAtomType, Attribute "type" TextAtomType]
313− attrs = A.attributesFromList [Attribute "name" TextAtomType,
314− Attribute "attributes" (RelationAtomType subrelAttrs)]
315− tups = map relVarToAtomList (M.toList relVarMap)
316− relVarToAtomList (rvName, rel) = [TextAtom rvName, attributesToRel (attributes rel)]
317− attributesToRel attrl = case mkRelationFromList subrelAttrs (map attrAtoms (V.toList attrl)) of
318− Left err -> error ("relationVariablesAsRelation pooped " ++ show err)
319− Right rel -> RelationAtom rel
320− attrAtoms a = [TextAtom (A.attributeName a), TextAtom (prettyAtomType (A.atomType a))]
321300
322301-- | Randomly resort the tuples. This is useful for emphasizing that two relations are equal even when they are printed to the console in different orders.
323302randomizeTupleOrder :: MonadRandom m => Relation -> m Relation
@@ -330,4 +309,4 @@ oneTuple (Relation _ (RelationTupleSet [])) = Nothing
330309oneTuple (Relation _ (RelationTupleSet (x:_))) = Just x
331310
332311tuplesList :: Relation -> [RelationTuple]
333−tuplesList (Relation _ tupleSet) = asList tupleSet
312+tuplesList (Relation _ tupleSet) = asList tupleSet
src/lib/ProjectM36/Relation/Parse/CSV.hs+7−3
@@ -38,8 +38,7 @@ csvAsRelation attrs tConsMap inString = case APBL.parse (csvWithHeader csvDecode
3838 let strHeader = V.map decodeUtf8 headerRaw
3939 strMapRecords = V.map convertMap vecMapsRaw
4040 convertMap hmap = HM.fromList $ L.map (decodeUtf8 *** (T.unpack . decodeUtf8)) (HM.toList hmap)
41− attrNames = V.map A.attributeName attrs
42− attrNameSet = S.fromList (V.toList attrNames)
41+ attrNameSet = A.attributeNameSet attrs
4342 headerSet = S.fromList (V.toList strHeader)
4443 parseAtom attrName aType textIn = case APT.parseOnly (parseCSVAtomP attrName tConsMap aType <* APT.endOfInput) textIn of
4544 Left err -> Left (ParseError (T.pack err))
@@ -47,7 +46,7 @@ csvAsRelation attrs tConsMap inString = case APBL.parse (csvWithHeader csvDecode
4746 makeTupleList :: HM.HashMap AttributeName String -> [Either CsvImportError Atom]
4847 makeTupleList tupMap = V.toList $ V.map (\attr ->
4948 either (Left . AttributeMappingError) Right $
50− parseAtom (A.attributeName attr) (A.atomType attr) (T.pack $ tupMap HM.! A.attributeName attr)) attrs
49+ parseAtom (A.attributeName attr) (A.atomType attr) (T.pack $ tupMap HM.! A.attributeName attr)) (attributesVec attrs)
5150 if attrNameSet == headerSet then do
5251 tupleList <- mapM sequence $ V.toList (V.map makeTupleList strMapRecords)
5352 case mkRelationFromList attrs tupleList of
@@ -83,6 +82,11 @@ parseCSVAtomP _ _ BoolAtomType = do
8382 case readMaybe bString of
8483 Nothing -> fail ("invalid BoolAtom string: " ++ bString)
8584 Just b -> pure (Right (BoolAtom b))
85+parseCSVAtomP _ _ RelationalExprAtomType = do
86+ reString <- T.unpack <$> takeToEndOfData
87+ case readMaybe reString of
88+ Nothing -> fail ("invalid RelationalExprAtom string: " ++ reString)
89+ Just b -> pure (Right (RelationalExprAtom b))
8690parseCSVAtomP attrName tConsMap typ@(ConstructedAtomType _ tvmap)
8791 | isIntervalAtomType typ = do
8892 begin <- (APT.char '[' >> pure False) <|> (APT.char '(' >> pure True)
src/lib/ProjectM36/Relation/Show/CSV.hs+5−5
@@ -1,7 +1,7 @@
11{-# OPTIONS_GHC -fno-warn-orphans #-}
22module ProjectM36.Relation.Show.CSV where
33import ProjectM36.Base
4−import ProjectM36.Attribute
4+import ProjectM36.Attribute as A
55import Data.Csv
66import ProjectM36.Tuple
77import qualified Data.ByteString.Lazy as BS
@@ -17,13 +17,13 @@ relationAsCSV (Relation attrs tupleSet)
1717 | relValAttrs /= [] =
1818 Left $ RelationValuedAttributesNotSupportedError (map attributeName relValAttrs)
1919 --check that there is at least one attribute
20− | V.null attrs =
20+ | A.null attrs =
2121 Left $ TupleAttributeCountMismatchError 0
2222 | otherwise =
2323 Right $ encodeByName bsAttrNames $ map RecordRelationTuple (asList tupleSet)
2424 where
25− relValAttrs = V.toList $ V.filter (isRelationAtomType . atomType) attrs
26− bsAttrNames = V.map (TE.encodeUtf8 . attributeName) attrs
25+ relValAttrs = V.toList $ V.filter (isRelationAtomType . atomType) (attributesVec attrs)
26+ bsAttrNames = V.map (TE.encodeUtf8 . attributeName) (attributesVec attrs)
2727
2828{-
2929instance ToRecord RelationTuple where
@@ -36,7 +36,7 @@ instance ToNamedRecord RecordRelationTuple where
3636 toNamedRecord rTuple = namedRecord $ map (\(k,v) -> TE.encodeUtf8 k .= RecordAtom v) (tupleAssocs $ unTuple rTuple)
3737
3838instance DefaultOrdered RecordRelationTuple where
39− headerOrder (RecordRelationTuple tuple) = V.map (TE.encodeUtf8 . attributeName) (tupleAttributes tuple)
39+ headerOrder (RecordRelationTuple tuple) = V.map (TE.encodeUtf8 . attributeName) (attributesVec (tupleAttributes tuple))
4040
4141newtype RecordAtom = RecordAtom {unAtom :: Atom}
4242
src/lib/ProjectM36/Relation/Show/HTML.hs+5−2
@@ -3,16 +3,18 @@ import ProjectM36.Base
33import ProjectM36.Relation
44import ProjectM36.Tuple
55import ProjectM36.Atom
6+import ProjectM36.Attribute as A
67import ProjectM36.AtomType
78import qualified Data.List as L
89import Data.Text (Text, pack)
910import qualified Data.Text as T
1011import qualified Data.Text.IO as TIO
12+#if __GLASGOW_HASKELL__ < 804
1113import Data.Monoid
12−import qualified Data.Vector as V
14+#endif
1315
1416attributesAsHTML :: Attributes -> Text
15−attributesAsHTML attrs = "<tr>" <> T.concat (map oneAttrHTML (V.toList attrs)) <> "</tr>"
17+attributesAsHTML attrs = "<tr>" <> T.concat (map oneAttrHTML (A.toList attrs)) <> "</tr>"
1618 where
1719 oneAttrHTML attr = "<th>" <> prettyAttribute attr <> "</th>"
1820
@@ -51,6 +53,7 @@ tupleAsHTML tuple = "<tr>" <> T.concat (L.map tupleFrag (tupleAssocs tuple)) <>
5153 where
5254 tupleFrag tup = "<td>" <> atomAsHTML (snd tup) <> "</td>"
5355 atomAsHTML (RelationAtom rel) = relationAsHTML rel
56+ atomAsHTML (TextAtom t) = "&quot;" <> t <> "&quot;"
5457 atomAsHTML atom = atomToText atom
5558
5659tupleSetAsHTML :: RelationTupleSet -> Text
src/lib/ProjectM36/Relation/Show/Term.hs+5
@@ -9,7 +9,11 @@ import ProjectM36.Attribute hiding (null)
99import qualified Data.List as L
1010import qualified Data.Text as T
1111import Control.Arrow hiding (left)
12+import Data.ByteString.Base64 as B64
13+import qualified Data.Text.Encoding as TE
14+#if __GLASGOW_HASKELL__ < 804
1215import Data.Monoid
16+#endif
1317import ProjectM36.WCWidth --guess the width that the character will appear as in the terminal
1418
1519boxV :: StringType
@@ -95,6 +99,7 @@ showAtom :: Int -> Atom -> StringType
9599showAtom _ (RelationAtom rel) = renderTable $ relationAsTable rel
96100showAtom level (ConstructedAtom dConsName _ atoms) = showParens (level >= 1 && not (null atoms)) $ T.concat (L.intersperse " " (dConsName : map (showAtom 1) atoms))
97101showAtom _ (TextAtom t) = "\"" <> t <> "\""
102+showAtom _ (ByteStringAtom bs) = TE.decodeUtf8 (B64.encode bs)
98103showAtom _ atom = atomToText atom
99104
100105renderTable :: Table -> StringType
src/lib/ProjectM36/RelationalExpression.hs+1047−657
@@ -1,34 +1,53 @@
11{-# LANGUAGE ScopedTypeVariables #-}
2+{-# LANGUAGE FlexibleInstances #-}
3+{-# LANGUAGE FlexibleContexts #-}
4+{-# LANGUAGE OverloadedStrings #-}
25module ProjectM36.RelationalExpression where
36import ProjectM36.Relation
47import ProjectM36.Tuple
58import ProjectM36.TupleSet
69import ProjectM36.Base
10+import qualified Data.UUID as U
711import ProjectM36.Error
812import ProjectM36.AtomType
9−import ProjectM36.Attribute (emptyAttributes)
13+import ProjectM36.Attribute (emptyAttributes, attributesFromList)
1014import ProjectM36.ScriptSession
1115import ProjectM36.DataTypes.Primitive
1216import ProjectM36.AtomFunction
1317import ProjectM36.DatabaseContextFunction
1418import ProjectM36.Arbitrary
19+import ProjectM36.GraphRefRelationalExpr
20+import ProjectM36.Transaction
1521import qualified ProjectM36.Attribute as A
1622import qualified Data.Map as M
1723import qualified Data.HashSet as HS
1824import qualified Data.Set as S
1925import Control.Monad.State hiding (join)
20−import Control.Exception
26+import Data.Bifunctor (second)
2127import Data.Maybe
2228import Data.Either
2329import Data.Char (isUpper)
30+import Data.Time
31+import qualified Data.List.NonEmpty as NE
32+import Data.Functor.Identity
2433import qualified Data.Text as T
2534import qualified Data.Vector as V
2635import qualified ProjectM36.TypeConstructorDef as TCD
27−import Control.Monad.Trans.Except
28−import Control.Monad.Trans.Reader
36+import qualified Control.Monad.RWS.Strict as RWS
37+import Control.Monad.RWS.Strict (RWST, execRWST, runRWST)
38+import Control.Monad.Except hiding (join)
39+import Control.Monad.Trans.Except (except)
40+import Control.Monad.Reader as R hiding (join)
41+import ProjectM36.NormalizeExpr
42+import ProjectM36.WithNameExpr
2943import Test.QuickCheck
30−import GHC
44+import qualified Data.Functor.Foldable as Fold
45+import Control.Applicative
46+#ifdef PM36_HASKELL_SCRIPTING
47+import GHC hiding (getContext)
48+import Control.Exception
3149import GHC.Paths
50+#endif
3251
3352data DatabaseContextExprDetails = CountUpdatedTuples
3453
@@ -45,32 +64,63 @@ databaseContextExprDetailsFunc CountUpdatedTuples _ relIn = Relation attrs newTu
4564 Right ts -> ts
4665
4766-- | Used to start a fresh database state for a new database context expression.
48−freshDatabaseState :: DatabaseContext -> DatabaseStateElems
49−freshDatabaseState ctx = (ctx, M.empty, False) --future work: propagate return accumulator
67+mkDatabaseContextEvalState :: DatabaseContext -> DatabaseContextEvalState
68+mkDatabaseContextEvalState context = DatabaseContextEvalState {
69+ dbc_context = context,
70+ dbc_accum = M.empty,
71+ dbc_dirty = False
72+ } --future work: propagate return accumulator
5073
5174-- we need to pass around a higher level RelationTuple and Attributes in order to solve #52
52−data RelationalExprStateElems = RelationalExprStateTupleElems DatabaseContext RelationTuple | -- used when fully evaluating a relexpr
53− RelationalExprStateAttrsElems DatabaseContext Attributes | --used when evaluating the type of a relexpr
54− RelationalExprStateElems DatabaseContext --used by default at the top level of evaluation
55−
56−instance Show RelationalExprStateElems where
57− show (RelationalExprStateTupleElems _ tup) = "RelationalExprStateTupleElems " ++ show tup
58− show (RelationalExprStateAttrsElems _ attrs) = "RelationalExprStateAttrsElems" ++ show attrs
59− show (RelationalExprStateElems _) = "RelationalExprStateElems"
60−
61−mkRelationalExprState :: DatabaseContext -> RelationalExprStateElems
62−mkRelationalExprState = RelationalExprStateElems
63−
64−mergeTuplesIntoRelationalExprState :: RelationTuple -> RelationalExprStateElems -> RelationalExprStateElems
65−mergeTuplesIntoRelationalExprState tupIn (RelationalExprStateElems ctx) = RelationalExprStateTupleElems ctx tupIn
66−mergeTuplesIntoRelationalExprState _ st@(RelationalExprStateAttrsElems _ _) = st
67−mergeTuplesIntoRelationalExprState tupIn (RelationalExprStateTupleElems ctx existingTuple) = let mergedTupMap = M.union (tupleToMap tupIn) (tupleToMap existingTuple) in
68− RelationalExprStateTupleElems ctx (mkRelationTupleFromMap mergedTupMap)
75+data RelationalExprEnv = RelationalExprEnv {
76+ re_context :: DatabaseContext,
77+ re_graph :: TransactionGraph,
78+ re_extra :: Maybe (Either RelationTuple Attributes)
79+ }
80+
81+envTuple :: GraphRefRelationalExprEnv -> RelationTuple
82+envTuple e = fromLeft emptyTuple (fromMaybe (Left emptyTuple) (gre_extra e))
83+
84+envAttributes :: GraphRefRelationalExprEnv -> Attributes
85+envAttributes e = fromRight emptyAttributes (fromMaybe (Right emptyAttributes) (gre_extra e))
6986
70−mergeAttributesIntoRelationalExprState :: Attributes -> RelationalExprStateElems -> RelationalExprStateElems
71−mergeAttributesIntoRelationalExprState attrs (RelationalExprStateElems ctx) = RelationalExprStateAttrsElems ctx attrs
72−mergeAttributesIntoRelationalExprState _ st@(RelationalExprStateTupleElems _ _) = st
73−mergeAttributesIntoRelationalExprState attrsIn (RelationalExprStateAttrsElems ctx attrs) = RelationalExprStateAttrsElems ctx (A.union attrsIn attrs)
87+instance Show RelationalExprEnv where
88+ show e@RelationalExprEnv{} = "RelationalExprEnv " ++ show (re_extra e)
89+
90+--used to eval relationalexpr
91+type RelationalExprM a = ReaderT RelationalExprEnv (ExceptT RelationalError Identity) a
92+
93+runRelationalExprM :: RelationalExprEnv -> RelationalExprM a -> Either RelationalError a
94+runRelationalExprM env m = runIdentity (runExceptT (runReaderT m env))
95+
96+reGraph :: RelationalExprM TransactionGraph
97+reGraph = asks re_graph
98+
99+reContext :: RelationalExprM DatabaseContext
100+reContext = asks re_context
101+
102+mkRelationalExprEnv :: DatabaseContext -> TransactionGraph -> RelationalExprEnv
103+mkRelationalExprEnv ctx graph =
104+ RelationalExprEnv
105+ { re_context = ctx,
106+ re_graph = graph,
107+ re_extra = Nothing }
108+
109+askEnv :: GraphRefRelationalExprM GraphRefRelationalExprEnv
110+askEnv = R.ask
111+
112+mergeTuplesIntoGraphRefRelationalExprEnv :: RelationTuple -> GraphRefRelationalExprEnv -> GraphRefRelationalExprEnv
113+mergeTuplesIntoGraphRefRelationalExprEnv tupIn env =
114+ env { gre_extra = new_elems }
115+ where
116+ new_elems = Just (Left newTuple)
117+ mergedTupMap = M.union (tupleToMap tupIn) (tupleToMap (envTuple env))
118+ newTuple = mkRelationTupleFromMap mergedTupMap
119+
120+mergeAttributesIntoGraphRefRelationalExprEnv :: Attributes -> GraphRefRelationalExprEnv -> GraphRefRelationalExprEnv
121+mergeAttributesIntoGraphRefRelationalExprEnv attrsIn e = e { gre_extra = newattrs }
122+ where
123+ newattrs = Just (Right (A.union attrsIn (envAttributes e)))
74124
75125type ResultAccumName = StringType
76126
@@ -80,447 +130,403 @@ data ResultAccum = ResultAccum { resultAccumFunc :: ResultAccumFunc,
80130 resultAccumResult :: Relation
81131 }
82132
83−type DatabaseStateElems = (DatabaseContext, M.Map ResultAccumName ResultAccum, DirtyFlag)
133+data DatabaseContextEvalState = DatabaseContextEvalState {
134+ dbc_context :: DatabaseContext, --new, alterable context for a new transaction
135+ dbc_accum :: M.Map ResultAccumName ResultAccum,
136+ dbc_dirty :: DirtyFlag
137+ }
84138
85−type DatabaseState a = State DatabaseStateElems a
139+data DatabaseContextEvalEnv = DatabaseContextEvalEnv
140+ { dce_transId :: TransactionId,
141+ dce_graph :: TransactionGraph
142+ }
86143
87−getStateContext :: DatabaseState DatabaseContext
88−getStateContext = do
89− (ctx,_, _) <- get
90− pure ctx
91−
92−putStateContext :: DatabaseContext -> DatabaseState ()
93−putStateContext ctx = do
94− (_, accum, _) <- get
95− put (ctx, accum, True)
96−
97−type RelationalExprState a = Reader RelationalExprStateElems a
98−
99−stateElemsContext :: RelationalExprStateElems -> DatabaseContext
100−stateElemsContext (RelationalExprStateTupleElems ctx _) = ctx
101−stateElemsContext (RelationalExprStateElems ctx) = ctx
102−stateElemsContext (RelationalExprStateAttrsElems ctx _) = ctx
103−
104−setStateElemsContext :: RelationalExprStateElems -> DatabaseContext -> RelationalExprStateElems
105−setStateElemsContext (RelationalExprStateTupleElems _ tup) ctx = RelationalExprStateTupleElems ctx tup
106−setStateElemsContext (RelationalExprStateElems _) ctx = RelationalExprStateElems ctx
107−setStateElemsContext (RelationalExprStateAttrsElems _ attrs) ctx = RelationalExprStateAttrsElems ctx attrs
108−
109−--relvar state is needed in evaluation of relational expression but only as read-only in order to extract current relvar values
110−evalRelationalExpr :: RelationalExpr -> RelationalExprState (Either RelationalError Relation)
111−evalRelationalExpr (RelationVariable name _) = do
112− relvarTable <- fmap (relationVariables . stateElemsContext) ask
113− return $ case M.lookup name relvarTable of
114− Just res -> Right res
115− Nothing -> Left $ RelVarNotDefinedError name
116−
117−evalRelationalExpr (Project attrNames expr) = do
118− eAttrNameSet <- evalAttributeNames attrNames expr
119− case eAttrNameSet of
120− Left err -> pure (Left err)
121− Right attrNameSet -> do
122− rel <- evalRelationalExpr expr
123− case rel of
124− Right rel2 -> pure $ project attrNameSet rel2
125− Left err -> pure $ Left err
126−
127−evalRelationalExpr (Union exprA exprB) = do
128− relA <- evalRelationalExpr exprA
129− relB <- evalRelationalExpr exprB
130− case relA of
131− Left err -> return $ Left err
132− Right relA2 -> case relB of
133− Left err -> return $ Left err
134− Right relB2 -> return $ union relA2 relB2
135−
136−evalRelationalExpr (Join exprA exprB) = do
137− relA <- evalRelationalExpr exprA
138− relB <- evalRelationalExpr exprB
139− case relA of
140− Left err -> return $ Left err
141− Right relA2 -> case relB of
142− Left err -> return $ Left err
143− Right relB2 -> return $ join relA2 relB2
144−
145−evalRelationalExpr (Difference exprA exprB) = do
146− relA <- evalRelationalExpr exprA
147− relB <- evalRelationalExpr exprB
148− case relA of
149− Left err -> return $ Left err
150− Right relA2 -> case relB of
151− Left err -> return $ Left err
152− Right relB2 -> return $ difference relA2 relB2
153−
154−evalRelationalExpr (MakeStaticRelation attributeSet tupleSet) =
155− case mkRelation attributeSet tupleSet of
156− Right rel -> return $ Right rel
157− Left err -> return $ Left err
144+mkDatabaseContextEvalEnv :: TransactionId -> TransactionGraph -> DatabaseContextEvalEnv
145+mkDatabaseContextEvalEnv = DatabaseContextEvalEnv
146+
147+type DatabaseContextEvalMonad a = RWST DatabaseContextEvalEnv () DatabaseContextEvalState (ExceptT RelationalError Identity) a
148+
149+runDatabaseContextEvalMonad :: DatabaseContext -> DatabaseContextEvalEnv -> DatabaseContextEvalMonad () -> Either RelationalError DatabaseContextEvalState
150+runDatabaseContextEvalMonad ctx env m = runIdentity (runExceptT (fst <$> execRWST m env freshEnv))
151+ where
152+ freshEnv = mkDatabaseContextEvalState ctx
158153
159−evalRelationalExpr (MakeRelationFromExprs mAttrExprs tupleExprs) = do
160− currentContext <- fmap stateElemsContext ask
161− let tConss = typeConstructorMapping currentContext
162− -- if the mAttrExprs is Nothing, then we should attempt to infer the tuple attributes from the first tuple itself- note that this is not always possible
163− runExceptT $ do
164− mAttrs <- case mAttrExprs of
165− Just _ ->
166− Just . A.attributesFromList <$> mapM (either throwE pure . evalAttrExpr tConss) (fromMaybe [] mAttrExprs)
167− Nothing -> pure Nothing
168− tuples <- mapM (liftE . evalTupleExpr mAttrs) tupleExprs
169− let attrs = fromMaybe firstTupleAttrs mAttrs
170− firstTupleAttrs = if null tuples then A.emptyAttributes else tupleAttributes (head tuples)
171− either throwE pure (mkRelation attrs (RelationTupleSet tuples))
172−
173−evalRelationalExpr (ExistingRelation rel) = pure (Right rel)
174154
175−evalRelationalExpr (Rename oldAttrName newAttrName relExpr) = do
176− evald <- evalRelationalExpr relExpr
177− case evald of
178− Right rel -> return $ rename oldAttrName newAttrName rel
179− Left err -> return $ Left err
155+dbcTransId :: DatabaseContextEvalMonad TransactionId
156+dbcTransId = dce_transId <$> RWS.ask
180157
181−evalRelationalExpr (Group oldAttrNames newAttrName relExpr) = do
182− eOldAttrNameSet <- evalAttributeNames oldAttrNames relExpr
183− case eOldAttrNameSet of
184− Left err -> pure (Left err)
185− Right oldAttrNameSet -> do
186− evald <- evalRelationalExpr relExpr
187− case evald of
188− Right rel -> return $ group oldAttrNameSet newAttrName rel
189− Left err -> return $ Left err
190−
191−evalRelationalExpr (Ungroup attrName relExpr) = do
192− evald <- evalRelationalExpr relExpr
193− case evald of
194− Right rel -> return $ ungroup attrName rel
195− Left err -> return $ Left err
196−
197−evalRelationalExpr (Restrict predicateExpr relExpr) = do
198− evald <- evalRelationalExpr relExpr
199− case evald of
200− Left err -> return $ Left err
201− Right rel -> do
202− eFilterFunc <- predicateRestrictionFilter (attributes rel) predicateExpr
203− case eFilterFunc of
204− Left err -> return $ Left err
205− Right filterfunc ->
206− pure (restrict filterfunc rel)
207−
208−evalRelationalExpr (Equals relExprA relExprB) = do
209− evaldA <- evalRelationalExpr relExprA
210− evaldB <- evalRelationalExpr relExprB
211− case evaldA of
212− Left err -> return $ Left err
213− Right relA -> case evaldB of
214− Left err -> return $ Left err
215− Right relB -> return $ Right $ if relA == relB then relationTrue else relationFalse
216−
217−evalRelationalExpr (With views mainExpr) = do
218− rstate <- ask
158+dbcGraph :: DatabaseContextEvalMonad TransactionGraph
159+dbcGraph = dce_graph <$> RWS.ask
160+
161+dbcRelationalExprEnv :: DatabaseContextEvalMonad RelationalExprEnv
162+dbcRelationalExprEnv =
163+ mkRelationalExprEnv <$> getStateContext <*> dbcGraph
164+
165+getStateContext :: DatabaseContextEvalMonad DatabaseContext
166+getStateContext = gets dbc_context
167+
168+putStateContext :: DatabaseContext -> DatabaseContextEvalMonad ()
169+putStateContext ctx' = do
170+ s <- get
171+ put (s {dbc_context = ctx', dbc_dirty = True})
172+
173+-- | The context is optionally passed down along in cases where the current context is uncommitted.
174+data GraphRefRelationalExprEnv =
175+ GraphRefRelationalExprEnv {
176+ gre_context :: Maybe DatabaseContext,
177+ gre_graph :: TransactionGraph,
178+ gre_extra :: Maybe (Either RelationTuple Attributes)
179+ }
219180
220− let addScopedView ctx (vname,vexpr) = if vname `M.member` relationVariables ctx then
221− Left (RelVarAlreadyDefinedError vname)
222− else
223− case runState (evalDatabaseContextExpr (Assign vname vexpr)) (freshDatabaseState ctx) of
224− (Left err,_) -> Left err
225− (Right (), (ctx',_,_)) -> Right ctx'
226−
227− case foldM addScopedView (stateElemsContext rstate) views of
228− Left err -> return $ Left err
229− Right ctx'' -> do
230− let evalMainExpr expr = runReader (evalRelationalExpr expr) (RelationalExprStateElems ctx'')
231− case evalMainExpr mainExpr of
232− Left err -> return $ Left err
233− Right rel -> return $ Right rel
234−
235−--warning: copy-pasta from above- refactor
236−evalRelationalExpr (NotEquals relExprA relExprB) = do
237− evaldA <- evalRelationalExpr relExprA
238− evaldB <- evalRelationalExpr relExprB
239− case evaldA of
240− Left err -> return $ Left err
241− Right relA -> case evaldB of
242− Left err -> return $ Left err
243− Right relB -> return $ Right $ if relA /= relB then relationTrue else relationFalse
244−
245−-- extending a relation adds a single attribute with the results of the per-tuple expression evaluated
246−evalRelationalExpr (Extend tupleExpression relExpr) = do
247− rstate <- ask
248− let evald = runReader (evalRelationalExpr relExpr) rstate
249− case evald of
250− Left err -> pure (Left err)
251− Right rel -> do
252− tupProc <- extendTupleExpressionProcessor rel tupleExpression
253− case tupProc of
254− Left err -> pure (Left err)
255− Right (newAttrs, tupProc') -> pure $ relMogrify tupProc' newAttrs rel
181+type GraphRefRelationalExprM a = ReaderT GraphRefRelationalExprEnv (ExceptT RelationalError Identity) a
182+
183+gfTransForId :: TransactionId -> GraphRefRelationalExprM Transaction
184+gfTransForId tid = do
185+ graph <- gfGraph
186+ lift $ except $ transactionForId tid graph
187+
188+gfDatabaseContextForMarker :: GraphRefTransactionMarker -> GraphRefRelationalExprM DatabaseContext
189+gfDatabaseContextForMarker (TransactionMarker transId) = concreteDatabaseContext <$> gfTransForId transId
190+gfDatabaseContextForMarker UncommittedContextMarker = do
191+ mctx <- gre_context <$> askEnv
192+ case mctx of
193+ Nothing -> throwError NoUncommittedContextInEvalError
194+ Just ctx -> pure ctx
195+
196+runGraphRefRelationalExprM :: GraphRefRelationalExprEnv -> GraphRefRelationalExprM a -> Either RelationalError a
197+runGraphRefRelationalExprM env m = runIdentity (runExceptT (runReaderT m env))
198+
199+freshGraphRefRelationalExprEnv :: Maybe DatabaseContext -> TransactionGraph -> GraphRefRelationalExprEnv
200+freshGraphRefRelationalExprEnv mctx graph = GraphRefRelationalExprEnv {
201+ gre_context = mctx,
202+ gre_graph = graph,
203+ gre_extra = Nothing
204+ }
205+
206+gfGraph :: GraphRefRelationalExprM TransactionGraph
207+gfGraph = asks gre_graph
208+
209+envContext :: RelationalExprEnv -> DatabaseContext
210+envContext = re_context
211+
212+setEnvContext :: RelationalExprEnv -> DatabaseContext -> RelationalExprEnv
213+setEnvContext e ctx = e { re_context = ctx }
256214
257215--helper function to process relation variable creation/assignment
258−setRelVar :: RelVarName -> Relation -> DatabaseState (Either RelationalError ())
259−setRelVar relVarName rel = do
216+setRelVar :: RelVarName -> GraphRefRelationalExpr -> DatabaseContextEvalMonad ()
217+setRelVar relVarName relExpr = do
260218 currentContext <- getStateContext
261− let newRelVars = M.insert relVarName rel $ relationVariables currentContext
219+ --prevent recursive relvar definition by resolving references to relvars in previous states
220+ relExpr' <- resolve relExpr
221+ let newRelVars = M.insert relVarName relExpr' $ relationVariables currentContext
262222 potentialContext = currentContext { relationVariables = newRelVars }
263−
264− case checkConstraints potentialContext of
265− Left err -> pure (Left err)
266− Right _ -> do
267− putStateContext potentialContext
268− return (Right ())
223+ --optimization: if the relexpr is unchanged, skip the update
224+ if M.lookup relVarName (relationVariables currentContext) == Just relExpr then
225+ pure ()
226+ else do
227+ --determine when to check constraints
228+ graph <- dbcGraph
229+ tid <- dbcTransId
230+ case checkConstraints potentialContext tid graph of
231+ Left err -> dbErr err
232+ Right _ -> putStateContext potentialContext
233+
234+--fast-path insertion- we already know that the previous relvar validated correctly, so we can validate just the relation that is being inserted for attribute matches- without this, even a single tuple relation inserted causes the entire relation to be re-validated unnecessarily
235+--insertIntoRelVar :: RelVarName -> GraphRefRelationalExpr -> DatabaseContextEvalMonad ()
269236
270237-- it is not an error to delete a relvar which does not exist, just like it is not an error to insert a pre-existing tuple into a relation
271−deleteRelVar :: RelVarName -> DatabaseState (Either RelationalError ())
238+deleteRelVar :: RelVarName -> DatabaseContextEvalMonad ()
272239deleteRelVar relVarName = do
273240 currContext <- getStateContext
274241 let relVars = relationVariables currContext
275242 if M.notMember relVarName relVars then
276− pure (Right ())
243+ pure ()
277244 else do
278245 let newRelVars = M.delete relVarName relVars
279246 newContext = currContext { relationVariables = newRelVars }
280247 putStateContext newContext
281− pure (Right ())
248+ pure ()
282249
283−evalDatabaseContextExpr :: DatabaseContextExpr -> DatabaseState (Either RelationalError ())
284−evalDatabaseContextExpr NoOperation = pure (Right ())
250+evalGraphRefDatabaseContextExpr :: GraphRefDatabaseContextExpr -> DatabaseContextEvalMonad ()
251+evalGraphRefDatabaseContextExpr NoOperation = pure ()
285252
286−evalDatabaseContextExpr (Define relVarName attrExprs) = do
253+evalGraphRefDatabaseContextExpr (Define relVarName attrExprs) = do
254+ context <- getStateContext
287255 relvars <- fmap relationVariables getStateContext
288256 tConss <- fmap typeConstructorMapping getStateContext
289− let eAttrs = map (evalAttrExpr tConss) attrExprs
290− attrErrs = lefts eAttrs
291− attrsList = rights eAttrs
292− if not (null attrErrs) then
293− pure (Left (someErrors attrErrs))
294− else do
295− let atomTypeErrs = lefts $ map ((`validateAtomType` tConss) . A.atomType) attrsList
296− if not (null atomTypeErrs) then
297− pure (Left (someErrors atomTypeErrs))
298− else
299− case M.member relVarName relvars of
300− True -> pure (Left (RelVarAlreadyDefinedError relVarName))
301− False -> setRelVar relVarName emptyRelation >> pure (Right ())
257+ graph <- dbcGraph
258+ let eAttrs = runGraphRefRelationalExprM gfEnv (mapM evalGraphRefAttrExpr attrExprs)
259+ gfEnv = freshGraphRefRelationalExprEnv (Just context) graph
260+ case eAttrs of
261+ Left err -> dbErr err
262+ Right attrsList -> do
263+ lift $ except $ validateAttributes tConss (A.attributesFromList attrsList)
264+ case M.member relVarName relvars of
265+ True -> dbErr (RelVarAlreadyDefinedError relVarName)
266+ False -> setRelVar relVarName (ExistingRelation emptyRelation)
302267 where
303268 attrs = A.attributesFromList attrsList
304269 emptyRelation = Relation attrs emptyTupleSet
305270
306−evalDatabaseContextExpr (Undefine relVarName) = deleteRelVar relVarName
271+evalGraphRefDatabaseContextExpr (Undefine relVarName) = deleteRelVar relVarName
307272
308−evalDatabaseContextExpr (Assign relVarName expr) = do
309− -- in the future, it would be nice to get types from the RelationalExpr instead of needing to evaluate it
273+evalGraphRefDatabaseContextExpr (Assign relVarName expr) = do
274+ graph <- re_graph <$> dbcRelationalExprEnv
310275 context <- getStateContext
311− let existingRelVar = M.lookup relVarName relVarTable
312− relVarTable = relationVariables context
313− value = runReader (evalRelationalExpr expr) (RelationalExprStateElems context)
314− case value of
315− Left err -> pure (Left err)
316− Right rel -> case existingRelVar of
317− Nothing -> setRelVar relVarName rel
318− Just existingRel -> let expectedAttributes = attributes existingRel
319− foundAttributes = attributes rel in
320− if A.attributesEqual expectedAttributes foundAttributes then
321− setRelVar relVarName rel
322− else
323− pure (Left (RelationTypeMismatchError expectedAttributes foundAttributes))
324−
325−evalDatabaseContextExpr (Insert relVarName relExpr) = do
326− context <- getStateContext
327− let unionexp = Union relExpr rv
328− rv = RelationVariable relVarName ()
329− unioned = runReader (evalRelationalExpr unionexp) (RelationalExprStateElems context)
330− origRel = runReader (evalRelationalExpr rv) (RelationalExprStateElems context)
331− case unioned of
332− Left err -> pure (Left err)
333− Right unioned' -> case origRel of
334− Left err -> pure (Left err)
335− Right origRel' -> if cardinality unioned' == cardinality origRel' then --no tuples actually inserted
336− pure (Right ())
337− else
338− evalDatabaseContextExpr $ Assign relVarName (ExistingRelation unioned')
339−
340−evalDatabaseContextExpr (Delete relVarName predicate) = do
341− context <- getStateContext
342− let rv = RelationVariable relVarName ()
343− let updatedRel = runReader (evalRelationalExpr (Restrict (NotPredicate predicate) rv)) (RelationalExprStateElems context)
344− origRel = runReader (evalRelationalExpr rv) (RelationalExprStateElems context)
345− case updatedRel of
346− Left err -> pure (Left err)
347− Right updatedRel' -> case origRel of
348− Left err -> pure (Left err)
349− Right origRel' -> if cardinality origRel' == cardinality updatedRel' then
350− pure (Right ())
351− else
352− setRelVar relVarName updatedRel'
276+ let existingRelVar = M.lookup relVarName (relationVariables context)
277+ reEnv = freshGraphRefRelationalExprEnv (Just context) graph
278+ eNewExprType = runGraphRefRelationalExprM reEnv (typeForGraphRefRelationalExpr expr)
279+ case existingRelVar of
280+ Nothing -> do
281+ case runGraphRefRelationalExprM reEnv (typeForGraphRefRelationalExpr expr) of
282+ Left err -> dbErr err
283+ Right reltype -> do
284+ lift $ except $ validateAttributes (typeConstructorMapping context) (attributes reltype)
285+ setRelVar relVarName expr
286+ Just existingRel -> do
287+ let eExpectedType = runGraphRefRelationalExprM reEnv (typeForGraphRefRelationalExpr existingRel)
288+ case eExpectedType of
289+ Left err -> dbErr err
290+ Right expectedType ->
291+ case eNewExprType of
292+ Left err -> dbErr err
293+ Right newExprType -> do
294+ if newExprType == expectedType then do
295+ lift $ except $ validateAttributes (typeConstructorMapping context) (attributes newExprType)
296+ setRelVar relVarName expr
297+ else
298+ dbErr (RelationTypeMismatchError (attributes expectedType) (attributes newExprType))
353299
300+evalGraphRefDatabaseContextExpr (Insert relVarName relExpr) = do
301+ gfExpr <- relVarByName relVarName
302+ let optExpr = applyUnionCollapse (Union
303+ relExpr
304+ gfExpr)
305+ evalGraphRefDatabaseContextExpr (Assign relVarName optExpr)
306+
307+evalGraphRefDatabaseContextExpr (Delete relVarName predicate) = do
308+ gfExpr <- relVarByName relVarName
309+ let optExpr = applyRestrictionCollapse (Restrict (NotPredicate predicate) gfExpr)
310+ setRelVar relVarName optExpr
311+
354312--union of restricted+updated portion and the unrestricted+unupdated portion
355−evalDatabaseContextExpr (Update relVarName atomExprMap restrictionPredicateExpr) = do
313+evalGraphRefDatabaseContextExpr (Update relVarName atomExprMap pred') = do
314+ rvExpr <- relVarByName relVarName
315+ graph <- re_graph <$> dbcRelationalExprEnv
356316 context <- getStateContext
357− let relVarTable = relationVariables context
358− case M.lookup relVarName relVarTable of
359− Nothing -> pure (Left (RelVarNotDefinedError relVarName))
360− Just rel ->
361− case runReader (predicateRestrictionFilter (attributes rel) restrictionPredicateExpr) (RelationalExprStateElems context) of
362− Left err -> pure (Left err)
363− Right predicateFunc -> do
364− let ret = do
365− restrictedPortion <- restrict predicateFunc rel
366− if cardinality restrictedPortion == Finite 0 then
367− pure Nothing
368− else do
369− unrestrictedPortion <- restrict (predicateFunc >=> (pure . not)) rel
370− updatedPortion <- relMap (updateTupleWithAtomExprs atomExprMap context) restrictedPortion
371− updatedRel <- updatedPortion `union` unrestrictedPortion
372− pure (Just updatedRel)
373− case ret of
374− Left err -> pure (Left err)
375− Right Nothing -> pure (Right ())
376− Right (Just updatedRel) -> setRelVar relVarName updatedRel
317+ let reEnv = freshGraphRefRelationalExprEnv (Just context) graph
318+ --get the current attributes name in the relvar to ensure that we don't conflict when renaming
319+ eExprType = runGraphRefRelationalExprM reEnv (typeForGraphRefRelationalExpr rvExpr)
320+ exprType' <- case eExprType of
321+ Left err -> throwError err
322+ Right t -> pure t
323+ let unrestrictedPortion = Restrict (NotPredicate pred') rvExpr
324+ tmpAttr = tmpAttrC 1
325+ tmpAttrC :: Int -> AttributeName -> AttributeName
326+ tmpAttrC c attr =
327+ let tmpAttrName = "_tmp_" <> T.pack (show c) <> attr in
328+ if tmpAttrName `S.member` A.attributeNameSet (attributes exprType') then
329+ tmpAttrC (c+1) attr
330+ else
331+ tmpAttrName
332+ updateAttr nam atomExpr = Extend (AttributeExtendTupleExpr (tmpAttr nam) atomExpr)
333+ projectAndRename attr expr = Rename (tmpAttr attr) attr (Project (InvertedAttributeNames (S.singleton attr)) expr)
334+ restrictedPortion = Restrict pred' rvExpr
335+ updated = foldr (\(oldname, atomExpr) accum ->
336+ let procAtomExpr = runProcessExprM UncommittedContextMarker (processAtomExpr atomExpr) in
337+ updateAttr oldname procAtomExpr accum
338+ ) restrictedPortion (M.toList atomExprMap)
339+ -- the atomExprMap could reference other attributes, so we must perform multi-pass folds
340+ updatedPortion = foldr projectAndRename updated (M.keys atomExprMap)
341+ setRelVar relVarName (Union unrestrictedPortion updatedPortion)
377342
378−evalDatabaseContextExpr (AddInclusionDependency newDepName newDep) = do
343+evalGraphRefDatabaseContextExpr (AddInclusionDependency newDepName newDep) = do
379344 currContext <- getStateContext
345+ transId <- dbcTransId
346+ graph <- dbcGraph
380347 let currDeps = inclusionDependencies currContext
381348 newDeps = M.insert newDepName newDep currDeps
382349 if M.member newDepName currDeps then
383− pure (Left (InclusionDependencyNameInUseError newDepName))
350+ dbErr (InclusionDependencyNameInUseError newDepName)
384351 else do
385352 let potentialContext = currContext { inclusionDependencies = newDeps }
386− case checkConstraints potentialContext of
387− Left err -> pure (Left err)
388− Right _ -> do
353+ -- if the potential context passes all constraints, then save it
354+ -- potential optimization: validate only the new constraint- all old constraints must already hold
355+ case checkConstraints potentialContext transId graph of
356+ Left err -> dbErr err
357+ Right _ ->
389358 putStateContext potentialContext
390− return (Right ())
391359
392−evalDatabaseContextExpr (RemoveInclusionDependency depName) = do
360+evalGraphRefDatabaseContextExpr (RemoveInclusionDependency depName) = do
393361 currContext <- getStateContext
394362 let currDeps = inclusionDependencies currContext
395363 newDeps = M.delete depName currDeps
396364 if M.notMember depName currDeps then
397− pure (Left (InclusionDependencyNameNotInUseError depName))
398− else do
365+ dbErr (InclusionDependencyNameNotInUseError depName)
366+ else
399367 putStateContext $ currContext {inclusionDependencies = newDeps }
400− return (Right ())
401368
402369-- | Add a notification which will send the resultExpr when triggerExpr changes between commits.
403−evalDatabaseContextExpr (AddNotification notName triggerExpr resultOldExpr resultNewExpr) = do
370+evalGraphRefDatabaseContextExpr (AddNotification notName triggerExpr resultOldExpr resultNewExpr) = do
404371 currentContext <- getStateContext
405372 let nots = notifications currentContext
406373 if M.member notName nots then
407− pure (Left (NotificationNameInUseError notName))
374+ dbErr (NotificationNameInUseError notName)
408375 else do
409376 let newNotifications = M.insert notName newNotification nots
410377 newNotification = Notification { changeExpr = triggerExpr,
411378 reportOldExpr = resultOldExpr,
412379 reportNewExpr = resultNewExpr}
413380 putStateContext $ currentContext { notifications = newNotifications }
414− return (Right ())
415381
416−evalDatabaseContextExpr (RemoveNotification notName) = do
382+evalGraphRefDatabaseContextExpr (RemoveNotification notName) = do
417383 currentContext <- getStateContext
418384 let nots = notifications currentContext
419385 if M.notMember notName nots then
420− pure (Left (NotificationNameNotInUseError notName))
386+ dbErr (NotificationNameNotInUseError notName)
421387 else do
422388 let newNotifications = M.delete notName nots
423389 putStateContext $ currentContext { notifications = newNotifications }
424− pure (Right ())
390+
425391
426392-- | Adds type and data constructors to the database context.
427393-- validate that the type *and* constructor names are unique! not yet implemented!
428−evalDatabaseContextExpr (AddTypeConstructor tConsDef dConsDefList) = do
394+evalGraphRefDatabaseContextExpr (AddTypeConstructor tConsDef dConsDefList) = do
429395 currentContext <- getStateContext
430396 let oldTypes = typeConstructorMapping currentContext
431397 tConsName = TCD.name tConsDef
432398 -- validate that the constructor's types exist
433− case validateTypeConstructorDef tConsDef dConsDefList of
434− errs@(_:_) -> pure (Left (someErrors errs))
435− [] | T.null tConsName || not (isUpper (T.head tConsName)) -> pure (Left (InvalidAtomTypeName tConsName))
436− | isJust (findTypeConstructor tConsName oldTypes) -> pure (Left (AtomTypeNameInUseError tConsName))
399+ case validateTypeConstructorDef tConsDef dConsDefList oldTypes of
400+ Left err -> throwError err
401+ Right () | T.null tConsName || not (isUpper (T.head tConsName)) -> dbErr (InvalidAtomTypeName tConsName)
402+ | isJust (findTypeConstructor tConsName oldTypes) -> dbErr (AtomTypeNameInUseError tConsName)
437403 | otherwise -> do
438404 let newTypes = oldTypes ++ [(tConsDef, dConsDefList)]
439405 putStateContext $ currentContext { typeConstructorMapping = newTypes }
440− pure (Right ())
441406
442407-- | Removing the atom constructor prevents new atoms of the type from being created. Existing atoms of the type remain. Thus, the atomTypes list in the DatabaseContext need not be all-inclusive.
443−evalDatabaseContextExpr (RemoveTypeConstructor tConsName) = do
408+evalGraphRefDatabaseContextExpr (RemoveTypeConstructor tConsName) = do
444409 currentContext <- getStateContext
445410 let oldTypes = typeConstructorMapping currentContext
446411 if isNothing (findTypeConstructor tConsName oldTypes) then
447− pure (Left (AtomTypeNameNotInUseError tConsName))
412+ dbErr (AtomTypeNameNotInUseError tConsName)
448413 else do
449414 let newTypes = filter (\(tCons, _) -> TCD.name tCons /= tConsName) oldTypes
450415 putStateContext $ currentContext { typeConstructorMapping = newTypes }
451− pure (Right ())
452416
453−evalDatabaseContextExpr (MultipleExpr exprs) = do
417+evalGraphRefDatabaseContextExpr (MultipleExpr exprs) =
454418 --the multiple expressions must pass the same context around- not the old unmodified context
455− evald <- forM exprs evalDatabaseContextExpr
456− --some lifting magic needed here
457− case lefts evald of
458− [] -> pure (Right ())
459− errs -> pure (Left (someErrors errs))
460−
461−evalDatabaseContextExpr (RemoveAtomFunction funcName) = do
419+ mapM_ evalGraphRefDatabaseContextExpr exprs
420+
421+evalGraphRefDatabaseContextExpr (RemoveAtomFunction funcName) = do
462422 currentContext <- getStateContext
463423 let atomFuncs = atomFunctions currentContext
464424 case atomFunctionForName funcName atomFuncs of
465− Left err -> pure (Left err)
466− Right realFunc -> if isScriptedAtomFunction realFunc then do
467− let updatedFuncs = HS.delete realFunc atomFuncs
468− putStateContext (currentContext {atomFunctions = updatedFuncs })
469− pure (Right ())
470− else
471− pure (Left (PrecompiledFunctionRemoveError funcName))
425+ Left err -> dbErr err
426+ Right realFunc ->
427+ if isScriptedAtomFunction realFunc then do
428+ let updatedFuncs = HS.delete realFunc atomFuncs
429+ putStateContext (currentContext {atomFunctions = updatedFuncs })
430+ else
431+ dbErr (PrecompiledFunctionRemoveError funcName)
472432
473−evalDatabaseContextExpr (RemoveDatabaseContextFunction funcName) = do
433+evalGraphRefDatabaseContextExpr (RemoveDatabaseContextFunction funcName) = do
474434 context <- getStateContext
475435 let dbcFuncs = dbcFunctions context
476436 case databaseContextFunctionForName funcName dbcFuncs of
477− Left err -> pure (Left err)
478− Right realFunc -> if isScriptedDatabaseContextFunction realFunc then do
479− let updatedFuncs = HS.delete realFunc dbcFuncs
480− putStateContext (context { dbcFunctions = updatedFuncs })
481− pure (Right ())
482− else
483− pure (Left (PrecompiledFunctionRemoveError funcName))
437+ Left err -> dbErr err
438+ Right realFunc ->
439+ if isScriptedDatabaseContextFunction realFunc then do
440+ let updatedFuncs = HS.delete realFunc dbcFuncs
441+ putStateContext (context { dbcFunctions = updatedFuncs })
442+ else
443+ dbErr (PrecompiledFunctionRemoveError funcName)
484444
485−evalDatabaseContextExpr (ExecuteDatabaseContextFunction funcName atomArgExprs) = do
445+evalGraphRefDatabaseContextExpr (ExecuteDatabaseContextFunction funcName atomArgExprs) = do
486446 context <- getStateContext
447+ graph <- dbcGraph
487448 --resolve atom arguments
488− let relExprState = mkRelationalExprState context
489− eAtomTypes = map (\atomExpr -> runReader (typeFromAtomExpr emptyAttributes atomExpr) relExprState) atomArgExprs
449+ let eAtomTypes = mapM (runGraphRefRelationalExprM gfEnv . typeForGraphRefAtomExpr emptyAttributes) atomArgExprs
490450 eFunc = databaseContextFunctionForName funcName (dbcFunctions context)
451+ gfEnv = freshGraphRefRelationalExprEnv (Just context) graph
491452 case eFunc of
492− Left err -> pure (Left err)
453+ Left err -> dbErr err
493454 Right func -> do
494455 let expectedArgCount = length (dbcFuncType func)
495456 actualArgCount = length atomArgExprs
496457 if expectedArgCount /= actualArgCount then
497− pure (Left (FunctionArgumentCountMismatchError expectedArgCount actualArgCount))
458+ dbErr (FunctionArgumentCountMismatchError expectedArgCount actualArgCount)
498459 else
499460 --check that the atom types are valid
500− case lefts eAtomTypes of
501− _:_ -> pure (Left (someErrors (lefts eAtomTypes)))
502− [] -> do
503− let atomTypes = rights eAtomTypes
504− let mValidTypes = map (\(expType, actType) -> case atomTypeVerify expType actType of
505− Left err -> Just err
506− Right _ -> Nothing) (zip (dbcFuncType func) atomTypes)
507− typeErrors = catMaybes mValidTypes
508− eAtomArgs = map (\arg -> runReader (evalAtomExpr emptyTuple arg) relExprState) atomArgExprs
461+ case eAtomTypes of
462+ Left err -> dbErr err
463+ Right atomTypes -> do
464+ let mValidTypes = zipWith (\ expType actType
465+ -> case atomTypeVerify expType actType of
466+ Left err -> Just err
467+ Right _ -> Nothing)
468+ (dbcFuncType func) atomTypes
469+ typeErrors = catMaybes mValidTypes
470+ eAtomArgs = map (runGraphRefRelationalExprM gfEnv . evalGraphRefAtomExpr emptyTuple) atomArgExprs
509471 if length (lefts eAtomArgs) > 1 then
510− pure (Left (someErrors (lefts eAtomArgs)))
472+ dbErr (someErrors (lefts eAtomArgs))
511473 else if not (null typeErrors) then
512− pure (Left (someErrors typeErrors))
474+ dbErr (someErrors typeErrors)
513475 else
514476 case evalDatabaseContextFunction func (rights eAtomArgs) context of
515− Left err -> pure (Left err)
516− Right newContext -> putStateContext newContext >> pure (Right ())
517−
518−evalDatabaseContextIOExpr :: Maybe ScriptSession -> DatabaseContext -> DatabaseContextIOExpr -> IO (Either RelationalError DatabaseContext)
519−evalDatabaseContextIOExpr mScriptSession currentContext (AddAtomFunction funcName funcType script) =
520− case mScriptSession of
521− Nothing -> pure (Left (ScriptError ScriptCompilationDisabledError))
522− Just scriptSession -> do
523− res <- try $ runGhc (Just libdir) $ do
477+ Left err -> dbErr err
478+ Right newContext -> putStateContext newContext
479+data DatabaseContextIOEvalEnv = DatabaseContextIOEvalEnv
480+ { dbcio_transId :: TransactionId,
481+ dbcio_graph :: TransactionGraph,
482+ dbcio_mScriptSession :: Maybe ScriptSession
483+ }
484+
485+type DatabaseContextIOEvalMonad a = RWST DatabaseContextIOEvalEnv () DatabaseContextEvalState IO a
486+
487+runDatabaseContextIOEvalMonad :: DatabaseContextIOEvalEnv -> DatabaseContext -> DatabaseContextIOEvalMonad (Either RelationalError ()) -> IO (Either RelationalError DatabaseContextEvalState)
488+runDatabaseContextIOEvalMonad env ctx m = do
489+ res <- runRWST m env freshState
490+ case res of
491+ (Left err,_,_) -> pure (Left err)
492+ (Right (),s,_) -> pure (Right s)
493+ where
494+ freshState = mkDatabaseContextEvalState ctx
495+
496+requireScriptSession :: DatabaseContextIOEvalMonad (Either RelationalError ScriptSession)
497+requireScriptSession = do
498+ env <- RWS.ask
499+ case dbcio_mScriptSession env of
500+ Nothing -> pure $ Left $ ScriptError ScriptCompilationDisabledError
501+ Just ss -> pure (Right ss)
502+
503+putDBCIOContext :: DatabaseContext -> DatabaseContextIOEvalMonad (Either RelationalError ())
504+putDBCIOContext ctx = do
505+ RWS.modify (\dbstate -> dbstate { dbc_context = ctx})
506+ pure (Right ())
507+
508+getDBCIOContext :: DatabaseContextIOEvalMonad DatabaseContext
509+getDBCIOContext = dbc_context <$> RWS.get
510+
511+getDBCIORelationalExprEnv :: DatabaseContextIOEvalMonad RelationalExprEnv
512+getDBCIORelationalExprEnv = do
513+ context <- getDBCIOContext
514+ mkRelationalExprEnv context . dbcio_graph <$> RWS.ask
515+
516+evalGraphRefDatabaseContextIOExpr :: GraphRefDatabaseContextIOExpr -> DatabaseContextIOEvalMonad (Either RelationalError ())
517+#if !defined(PM36_HASKELL_SCRIPTING)
518+evalGraphRefDatabaseContextIOExpr AddAtomFunction{} = pure (Left (ScriptError ScriptCompilationDisabledError))
519+evalGraphRefDatabaseContextIOExpr AddDatabaseContextFunction{} = pure (Left (ScriptError ScriptCompilationDisabledError))
520+evalGraphRefDatabaseContextIOExpr LoadAtomFunctions{} = pure (Left (ScriptError ScriptCompilationDisabledError))
521+evalGraphRefDatabaseContextIOExpr LoadDatabaseContextFunctions{} = pure (Left (ScriptError ScriptCompilationDisabledError))
522+#else
523+evalGraphRefDatabaseContextIOExpr (AddAtomFunction funcName funcType script) = do
524+ eScriptSession <- requireScriptSession
525+ currentContext <- getDBCIOContext
526+ case eScriptSession of
527+ Left err -> pure (Left err)
528+ Right scriptSession -> do
529+ res <- liftIO $ try $ runGhc (Just libdir) $ do
524530 setSession (hscEnv scriptSession)
525531 let atomFuncs = atomFunctions currentContext
526532 case extractAtomFunctionType funcType of
@@ -546,12 +552,13 @@ evalDatabaseContextIOExpr mScriptSession currentContext (AddAtomFunction funcNam
546552 Left (exc :: SomeException) -> pure $ Left (ScriptError (OtherScriptCompilationError (show exc)))
547553 Right eContext -> case eContext of
548554 Left err -> pure (Left err)
549− Right context' -> pure (Right context')
550−
551−evalDatabaseContextIOExpr mScriptSession currentContext (AddDatabaseContextFunction funcName funcType script) =
552− case mScriptSession of
553− Nothing -> pure (Left (ScriptError ScriptCompilationDisabledError))
554− Just scriptSession -> do
555+ Right context' -> putDBCIOContext context'
556+evalGraphRefDatabaseContextIOExpr (AddDatabaseContextFunction funcName funcType script) = do
557+ eScriptSession <- requireScriptSession
558+ currentContext <- getDBCIOContext
559+ case eScriptSession of
560+ Left err -> pure (Left err)
561+ Right scriptSession -> do
555562 --validate that the function signature is of the form x -> y -> ... -> DatabaseContext -> DatabaseContext
556563 let last2Args = reverse (take 2 (reverse funcType))
557564 atomArgs = take (length funcType - 2) funcType
@@ -561,7 +568,7 @@ evalDatabaseContextIOExpr mScriptSession currentContext (AddDatabaseContextFunct
561568 if last2Args /= [ADTypeConstructor "DatabaseContext" [], dbContextTypeCons] then
562569 pure (Left (ScriptError (TypeCheckCompilationError expectedType actualType)))
563570 else do
564− res <- try $ runGhc (Just libdir) $ do
571+ res <- liftIO $ try $ runGhc (Just libdir) $ do
565572 setSession (hscEnv scriptSession)
566573 eCompiledFunc <- compileScript (dbcFunctionBodyType scriptSession) script
567574 pure $ case eCompiledFunc of
@@ -586,67 +593,86 @@ evalDatabaseContextIOExpr mScriptSession currentContext (AddDatabaseContextFunct
586593 Left (exc :: SomeException) -> pure $ Left (ScriptError (OtherScriptCompilationError (show exc)))
587594 Right eContext -> case eContext of
588595 Left err -> pure (Left err)
589− Right context' -> pure (Right context')
590−evalDatabaseContextIOExpr _ currentContext (LoadAtomFunctions modName funcName modPath) = do
591− eLoadFunc <- loadAtomFunctions (T.unpack modName) (T.unpack funcName) modPath
596+ Right context' -> putDBCIOContext context'
597+evalGraphRefDatabaseContextIOExpr (LoadAtomFunctions modName funcName modPath) = do
598+ currentContext <- getDBCIOContext
599+ eLoadFunc <- liftIO $ loadAtomFunctions (T.unpack modName) (T.unpack funcName) modPath
592600 case eLoadFunc of
593601 Left LoadSymbolError -> pure (Left LoadFunctionError)
594602 Right atomFunctionListFunc -> let newContext = currentContext { atomFunctions = mergedFuncs }
595603 mergedFuncs = HS.union (atomFunctions currentContext) (HS.fromList atomFunctionListFunc)
596− in pure (Right newContext)
597−evalDatabaseContextIOExpr _ currentContext (LoadDatabaseContextFunctions modName funcName modPath) = do
598− eLoadFunc <- loadDatabaseContextFunctions (T.unpack modName) (T.unpack funcName) modPath
604+ in putDBCIOContext newContext
605+evalGraphRefDatabaseContextIOExpr (LoadDatabaseContextFunctions modName funcName modPath) = do
606+ currentContext <- getDBCIOContext
607+ eLoadFunc <- liftIO $ loadDatabaseContextFunctions (T.unpack modName) (T.unpack funcName) modPath
599608 case eLoadFunc of
600609 Left LoadSymbolError -> pure (Left LoadFunctionError)
601610 Right dbcListFunc -> let newContext = currentContext { dbcFunctions = mergedFuncs }
602611 mergedFuncs = HS.union (dbcFunctions currentContext) (HS.fromList dbcListFunc)
603− in pure (Right newContext)
604−
605−evalDatabaseContextIOExpr _ currentContext (CreateArbitraryRelation relVarName attrExprs range) =
612+ in putDBCIOContext newContext
613+#endif
614+evalGraphRefDatabaseContextIOExpr (CreateArbitraryRelation relVarName attrExprs range) = do
606615 --Define
607− case runState ( evalDatabaseContextExpr (Define relVarName attrExprs)) (freshDatabaseState currentContext) of
608− (Left err,_) -> pure (Left err)
609− (Right (), elems@(ctx,_,_)) -> do
616+ currentContext <- getDBCIOContext
617+ env <- RWS.ask
618+ --create graph ref expr
619+ let gfExpr = Define relVarName attrExprs
620+ evalEnv = mkDatabaseContextEvalEnv (dbcio_transId env) (dbcio_graph env)
621+ graph = dbcio_graph env
622+ case runDatabaseContextEvalMonad currentContext evalEnv (evalGraphRefDatabaseContextExpr gfExpr) of
623+ Left err -> pure (Left err)
624+ Right dbstate -> do
610625 --Assign
611626 let existingRelVar = M.lookup relVarName relVarTable
612− relVarTable = relationVariables ctx
627+ relVarTable = relationVariables (dbc_context dbstate)
613628 case existingRelVar of
614629 Nothing -> pure $ Left (RelVarNotDefinedError relVarName)
615630 Just existingRel -> do
616− let expectedAttributes = attributes existingRel
617− let tcMap = typeConstructorMapping ctx
618− eitherRel <- generate $ runReaderT (arbitraryRelation expectedAttributes range) tcMap
619− case eitherRel of
620− Left err -> pure $ Left err
621− Right rel ->
622− case runState (setRelVar relVarName rel) elems of
623− (Left err,_) -> pure (Left err)
624− (Right (), (ctx',_,_)) -> pure $ Right ctx'
625−
626−updateTupleWithAtomExprs :: M.Map AttributeName AtomExpr -> DatabaseContext -> RelationTuple -> Either RelationalError RelationTuple
627−updateTupleWithAtomExprs exprMap context tupIn = do
628− --resolve all atom exprs
629− atomsAssoc <- mapM (\(attrName, atomExpr) -> do
630− atom <- runReader (evalAtomExpr tupIn atomExpr) (RelationalExprStateElems context)
631− pure (attrName, atom)
632− ) (M.toList exprMap)
633− pure (updateTupleWithAtoms (M.fromList atomsAssoc) tupIn)
631+ let gfEnv = freshGraphRefRelationalExprEnv (Just currentContext) graph
632+ case runGraphRefRelationalExprM gfEnv (typeForGraphRefRelationalExpr existingRel) of
633+ Left err -> pure (Left err)
634+ Right relType -> do
635+ let expectedAttributes = attributes relType
636+ tcMap = typeConstructorMapping (dbc_context dbstate)
637+ eitherRel <- liftIO $ generate $ runReaderT (arbitraryRelation expectedAttributes range) tcMap
638+ case eitherRel of
639+ Left err -> pure $ Left err
640+ Right rel ->
641+ case runDatabaseContextEvalMonad currentContext evalEnv (setRelVar relVarName (ExistingRelation rel)) of
642+ Left err -> pure (Left err)
643+ Right dbstate' -> putDBCIOContext (dbc_context dbstate')
634644
635645--run verification on all constraints
636−checkConstraints :: DatabaseContext -> Either RelationalError ()
637−checkConstraints context =
646+checkConstraints :: DatabaseContext -> TransactionId -> TransactionGraph -> Either RelationalError ()
647+checkConstraints context transId graph@(TransactionGraph graphHeads transSet) = do
638648 mapM_ (uncurry checkIncDep) (M.toList deps)
639649 where
650+ potentialGraph = TransactionGraph graphHeads (S.insert tempTrans transSet)
651+ tempStamp = UTCTime { utctDay = fromGregorian 2000 1 1,
652+ utctDayTime = secondsToDiffTime 0 }
653+ tempSchemas = Schemas context M.empty
654+ tempTrans = Transaction U.nil tempTransInfo tempSchemas
655+ tempTransInfo = TransactionInfo { parents = transId NE.:| [],
656+ stamp = tempStamp,
657+ merkleHash = mempty
658+ }
659+
640660 deps = inclusionDependencies context
641− eval expr = evalReader (evalRelationalExpr expr)
642− evalReader f = runReader f (RelationalExprStateElems context)
661+ -- no optimization available here, really? perhaps the optimizer should be passed down to here or the eval function should be passed through the environment
643662 checkIncDep depName (InclusionDependency subsetExpr supersetExpr) = do
663+ let process = runProcessExprM UncommittedContextMarker
664+ gfSubsetExpr = process (processRelationalExpr subsetExpr)
665+ gfSupersetExpr = process (processRelationalExpr supersetExpr)
644666 --if both expressions are of a single-attribute (such as with a simple foreign key), the names of the attributes are irrelevant (they need not match) because the expression is unambiguous, but special-casing this to rename the attribute automatically would not be orthogonal behavior and probably cause confusion. Instead, special case the error to make it clear.
645− typeSub <- evalReader (typeForRelationalExpr subsetExpr)
646− typeSuper <- evalReader (typeForRelationalExpr supersetExpr)
667+ let gfEnv = freshGraphRefRelationalExprEnv (Just context) graph
668+ runGfRel = runGraphRefRelationalExprM gfEnv
669+ typeSub <- runGfRel (typeForGraphRefRelationalExpr gfSubsetExpr)
670+ typeSuper <- runGfRel (typeForGraphRefRelationalExpr gfSupersetExpr)
647671 when (typeSub /= typeSuper) (Left (RelationTypeMismatchError (attributes typeSub) (attributes typeSuper)))
648− let checkExpr = Equals supersetExpr (Union subsetExpr supersetExpr)
649− case eval checkExpr of
672+ let checkExpr = Equals gfSupersetExpr (Union gfSubsetExpr gfSupersetExpr)
673+ gfEvald = runGraphRefRelationalExprM gfEnv' (evalGraphRefRelationalExpr checkExpr)
674+ gfEnv' = freshGraphRefRelationalExprEnv (Just context) potentialGraph
675+ case gfEvald of
650676 Left err -> Left err
651677 Right resultRel -> if resultRel == relationTrue then
652678 pure ()
@@ -656,91 +682,81 @@ checkConstraints context =
656682-- the type of a relational expression is equal to the relation attribute set returned from executing the relational expression; therefore, the type can be cheaply derived by evaluating a relational expression and ignoring and tuple processing
657683-- furthermore, the type of a relational expression is the resultant header of the evaluated empty-tupled relation
658684
659−typeForRelationalExpr :: RelationalExpr -> RelationalExprState (Either RelationalError Relation)
685+typeForRelationalExpr :: RelationalExpr -> RelationalExprM Relation
660686typeForRelationalExpr expr = do
661− rstate <- ask
662− let context = stateElemsContext rstate
663687 --replace the relationVariables context element with a cloned set of relation devoid of tuples
664− let context' = contextWithEmptyTupleSets context
665− rstate' = setStateElemsContext rstate context'
666688 --evalRelationalExpr could still return an existing relation with tuples, so strip them
667− pure $ case runReader (evalRelationalExpr expr) rstate' of
668− Left err -> Left err
669− Right typeRel -> Right (relationWithEmptyTupleSet typeRel)
670−
671−--returns a database context with all tuples removed
672−--this is useful for type checking and optimization
673−contextWithEmptyTupleSets :: DatabaseContext -> DatabaseContext
674−contextWithEmptyTupleSets contextIn = contextIn { relationVariables = relVars }
675− where
676− relVars = M.map (\rel -> Relation (attributes rel) emptyTupleSet) (relationVariables contextIn)
689+ graph <- reGraph
690+ context <- reContext
691+ let gfExpr = runProcessExprM UncommittedContextMarker (processRelationalExpr expr)
692+ gfEnv = freshGraphRefRelationalExprEnv (Just context) graph
693+ runGf = runGraphRefRelationalExprM gfEnv (typeForGraphRefRelationalExpr gfExpr)
694+ lift $ except runGf
677695
678696liftE :: (Monad m) => m (Either a b) -> ExceptT a m b
679697liftE v = do
680698 y <- lift v
681699 case y of
682− Left err -> throwE err
700+ Left err -> throwError err
683701 Right val -> pure val
684702
685703{- used for restrictions- take the restrictionpredicate and return the corresponding filter function -}
686−predicateRestrictionFilter :: Attributes -> RestrictionPredicateExpr -> RelationalExprState (Either RelationalError RestrictionFilter)
687−predicateRestrictionFilter attrs (AndPredicate expr1 expr2) =
688− runExceptT $ do
689− expr1v <- liftE (predicateRestrictionFilter attrs expr1)
690− expr2v <- liftE (predicateRestrictionFilter attrs expr2)
691− pure (\x -> do
692− ev1 <- expr1v x
693− ev2 <- expr2v x
694− pure (ev1 && ev2))
704+predicateRestrictionFilter :: Attributes -> GraphRefRestrictionPredicateExpr -> GraphRefRelationalExprM RestrictionFilter
705+predicateRestrictionFilter attrs (AndPredicate expr1 expr2) = do
706+ expr1v <- predicateRestrictionFilter attrs expr1
707+ expr2v <- predicateRestrictionFilter attrs expr2
708+ pure (\x -> do
709+ ev1 <- expr1v x
710+ ev2 <- expr2v x
711+ pure (ev1 && ev2))
695712
696−predicateRestrictionFilter attrs (OrPredicate expr1 expr2) =
697− runExceptT $ do
698− expr1v <- liftE (predicateRestrictionFilter attrs expr1)
699− expr2v <- liftE (predicateRestrictionFilter attrs expr2)
713+predicateRestrictionFilter attrs (OrPredicate expr1 expr2) = do
714+ expr1v <- predicateRestrictionFilter attrs expr1
715+ expr2v <- predicateRestrictionFilter attrs expr2
700716 pure (\x -> do
701717 ev1 <- expr1v x
702718 ev2 <- expr2v x
703719 pure (ev1 || ev2))
704720
705−predicateRestrictionFilter _ TruePredicate = pure (Right (\_ -> pure True))
721+predicateRestrictionFilter _ TruePredicate = pure (\_ -> pure True)
706722
707−predicateRestrictionFilter attrs (NotPredicate expr) =
708− runExceptT $ do
709− exprv <- liftE (predicateRestrictionFilter attrs expr)
710− pure (fmap not . exprv)
723+predicateRestrictionFilter attrs (NotPredicate expr) = do
724+ exprv <- predicateRestrictionFilter attrs expr
725+ pure (fmap not . exprv)
711726
712727--optimization opportunity: if the subexpression does not reference attributes in the top-level expression, then it need only be evaluated once, statically, outside the tuple filter- see historical implementation here
713728predicateRestrictionFilter _ (RelationalExprPredicate relExpr) = do
714− rstate <- ask
715− pure (Right (\tup -> case runReader (evalRelationalExpr relExpr) (mergeTuplesIntoRelationalExprState tup rstate) of
729+ renv <- askEnv
730+ let eval :: RelationTuple -> Either RelationalError Relation
731+ eval tup =
732+ let gfEnv = mergeTuplesIntoGraphRefRelationalExprEnv tup renv in
733+ runGraphRefRelationalExprM gfEnv (evalGraphRefRelationalExpr relExpr)
734+ pure (\tup -> case eval tup of
716735 Left err -> Left err
717736 Right rel -> if arity rel /= 0 then
718737 Left (PredicateExpressionError "Relational restriction filter must evaluate to 'true' or 'false'")
719738 else
720− pure (rel == relationTrue)))
739+ pure (rel == relationTrue))
721740
722741predicateRestrictionFilter attrs (AttributeEqualityPredicate attrName atomExpr) = do
723− rstate <- ask
724− let (attrs', ctxtup') = case rstate of
725− RelationalExprStateElems _ -> (attrs, emptyTuple)
726− RelationalExprStateAttrsElems _ _ -> (attrs, emptyTuple)
727− RelationalExprStateTupleElems _ ctxtup -> (A.union attrs (tupleAttributes ctxtup), ctxtup)
728− runExceptT $ do
729− atomExprType <- liftE (typeFromAtomExpr attrs' atomExpr)
730− attr <- either throwE pure $ case A.attributeForName attrName attrs of
742+ env <- askEnv
743+ let attrs' = A.union attrs (envAttributes env)
744+ ctxtup' = envTuple env
745+ atomExprType <- typeForGraphRefAtomExpr attrs' atomExpr
746+ attr <- lift $ except $ case A.attributeForName attrName attrs of
731747 Right attr -> Right attr
732748 Left (NoSuchAttributeNamesError _) -> case A.attributeForName attrName (tupleAttributes ctxtup') of
733749 Right ctxattr -> Right ctxattr
734750 Left err2@(NoSuchAttributeNamesError _) -> Left err2
735751 Left err -> Left err
736752 Left err -> Left err
737− if atomExprType /= A.atomType attr then
738− throwE (TupleAttributeTypeMismatchError (A.attributesFromList [attr]))
739− else
753+ if atomExprType /= A.atomType attr then
754+ throwError (TupleAttributeTypeMismatchError (A.attributesFromList [attr]))
755+ else
740756 pure $ \tupleIn -> let evalAndCmp atomIn = case atomEvald of
741757 Right atomCmp -> atomCmp == atomIn
742758 Left _ -> False
743− atomEvald = runReader (evalAtomExpr tupleIn atomExpr) rstate
759+ atomEvald = runGraphRefRelationalExprM env (evalGraphRefAtomExpr tupleIn atomExpr)
744760 in
745761 pure $ case atomForAttributeName attrName tupleIn of
746762 Left (NoSuchAttributeNamesError _) -> case atomForAttributeName attrName ctxtup' of
@@ -751,16 +767,15 @@ predicateRestrictionFilter attrs (AttributeEqualityPredicate attrName atomExpr)
751767-- in the future, it would be useful to do typechecking on the attribute and atom expr filters in advance
752768predicateRestrictionFilter attrs (AtomExprPredicate atomExpr) = do
753769 --merge attrs into the state attributes
754− rstate <- ask
755− runExceptT $ do
756− aType <- liftE (typeFromAtomExpr attrs atomExpr)
757− if aType /= BoolAtomType then
758− throwE (AtomTypeMismatchError aType BoolAtomType)
759− else
770+ renv <- askEnv
771+ aType <- typeForGraphRefAtomExpr attrs atomExpr
772+ if aType /= BoolAtomType then
773+ throwError (AtomTypeMismatchError aType BoolAtomType)
774+ else
760775 pure (\tupleIn ->
761− case runReader (evalAtomExpr tupleIn atomExpr) rstate of
762− Left err -> Left err
763− Right boolAtomValue -> pure (boolAtomValue == BoolAtom True))
776+ case runGraphRefRelationalExprM renv (evalGraphRefAtomExpr tupleIn atomExpr) of
777+ Left err -> Left err
778+ Right boolAtomValue -> pure (boolAtomValue == BoolAtom True))
764779
765780tupleExprCheckNewAttrName :: AttributeName -> Relation -> Either RelationalError Relation
766781tupleExprCheckNewAttrName attrName rel = if isRight (attributeForName attrName rel) then
@@ -768,235 +783,610 @@ tupleExprCheckNewAttrName attrName rel = if isRight (attributeForName attrName r
768783 else
769784 Right rel
770785
771−extendTupleExpressionProcessor :: Relation -> ExtendTupleExpr -> RelationalExprState (Either RelationalError (Attributes, RelationTuple -> Either RelationalError RelationTuple))
772−extendTupleExpressionProcessor relIn (AttributeExtendTupleExpr newAttrName atomExpr) = do
773− rstate <- ask
786+extendGraphRefTupleExpressionProcessor :: Relation -> GraphRefExtendTupleExpr -> GraphRefRelationalExprM (Attributes, RelationTuple -> Either RelationalError RelationTuple)
787+extendGraphRefTupleExpressionProcessor relIn (AttributeExtendTupleExpr newAttrName atomExpr) =
788+-- renv <- askEnv
774789 -- check that the attribute name is not in use
775790 case tupleExprCheckNewAttrName newAttrName relIn of
776− Left err -> pure (Left err)
777− Right _ -> runExceptT $ do
778− atomExprType <- liftE (typeFromAtomExpr (attributes relIn) atomExpr)
779− atomExprType' <- liftE (verifyAtomExprTypes relIn atomExpr atomExprType)
791+ Left err -> throwError err
792+ Right _ -> do
793+ atomExprType <- typeForGraphRefAtomExpr (attributes relIn) atomExpr
794+ atomExprType' <- verifyGraphRefAtomExprTypes relIn atomExpr atomExprType
780795 let newAttrs = A.attributesFromList [Attribute newAttrName atomExprType']
781796 newAndOldAttrs = A.addAttributes (attributes relIn) newAttrs
782− pure (newAndOldAttrs, \tup -> let substate = mergeTuplesIntoRelationalExprState tup rstate in case runReader (evalAtomExpr tup atomExpr) substate of
783− Left err -> Left err
784− Right atom -> Right (tupleAtomExtend newAttrName atom tup)
797+ env <- ask
798+ pure (newAndOldAttrs, \tup -> do
799+ let gfEnv = mergeTuplesIntoGraphRefRelationalExprEnv tup env
800+ atom <- runGraphRefRelationalExprM gfEnv (evalGraphRefAtomExpr tup atomExpr)
801+ Right (tupleAtomExtend newAttrName atom tup)
785802 )
786803
787−evalAtomExpr :: RelationTuple -> AtomExpr -> RelationalExprState (Either RelationalError Atom)
788−evalAtomExpr tupIn (AttributeAtomExpr attrName) = case atomForAttributeName attrName tupIn of
789− Right atom -> pure (Right atom)
790− err@(Left (NoSuchAttributeNamesError _)) -> do
791− rstate <- ask
792− case rstate of
793− RelationalExprStateElems _ -> pure err
794− RelationalExprStateAttrsElems _ _ -> pure err
795− RelationalExprStateTupleElems _ ctxtup -> pure (atomForAttributeName attrName ctxtup)
796− Left err -> pure (Left err)
797−evalAtomExpr _ (NakedAtomExpr atom) = pure (Right atom)
798−evalAtomExpr tupIn (FunctionAtomExpr funcName arguments ()) = do
799− argTypes <- mapM (typeFromAtomExpr (tupleAttributes tupIn)) arguments
800− context <- fmap stateElemsContext ask
801− runExceptT $ do
802− let functions = atomFunctions context
803− func <- either throwE pure (atomFunctionForName funcName functions)
804− let expectedArgCount = length (atomFuncType func) - 1
805− actualArgCount = length argTypes
806− safeInit [] = [] -- different behavior from normal init
807− safeInit xs = init xs
808− if expectedArgCount /= actualArgCount then
809− throwE (FunctionArgumentCountMismatchError expectedArgCount actualArgCount)
810− else do
804+evalGraphRefAtomExpr :: RelationTuple -> GraphRefAtomExpr -> GraphRefRelationalExprM Atom
805+evalGraphRefAtomExpr tupIn (AttributeAtomExpr attrName) =
806+ case atomForAttributeName attrName tupIn of
807+ Right atom -> pure atom
808+ Left err@(NoSuchAttributeNamesError _) -> do
809+ env <- askEnv
810+ case gre_extra env of
811+ Nothing -> throwError err
812+ Just (Left ctxtup) -> lift $ except $ atomForAttributeName attrName ctxtup
813+ Just (Right _) -> throwError err
814+ Left err -> throwError err
815+evalGraphRefAtomExpr _ (NakedAtomExpr atom) = pure atom
816+evalGraphRefAtomExpr tupIn (FunctionAtomExpr funcName arguments tid) = do
817+ argTypes <- mapM (typeForGraphRefAtomExpr (tupleAttributes tupIn)) arguments
818+ context <- gfDatabaseContextForMarker tid
819+ let functions = atomFunctions context
820+ func <- lift $ except (atomFunctionForName funcName functions)
821+ let expectedArgCount = length (atomFuncType func) - 1
822+ actualArgCount = length argTypes
823+ safeInit [] = [] -- different behavior from normal init
824+ safeInit xs = init xs
825+ if expectedArgCount /= actualArgCount then
826+ throwError (FunctionArgumentCountMismatchError expectedArgCount actualArgCount)
827+ else do
811828 let zippedArgs = zip (safeInit (atomFuncType func)) argTypes
812− mapM_ (\(expType, eActType) -> do
813− actType <- either throwE pure eActType
814− either throwE pure (atomTypeVerify expType actType)) zippedArgs
815− evaldArgs <- mapM (liftE . evalAtomExpr tupIn) arguments
829+ mapM_ (\(expType, actType) ->
830+ lift $ except (atomTypeVerify expType actType)) zippedArgs
831+ evaldArgs <- mapM (evalGraphRefAtomExpr tupIn) arguments
816832 case evalAtomFunction func evaldArgs of
817− Left err -> throwE (AtomFunctionUserError err)
833+ Left err -> throwError (AtomFunctionUserError err)
818834 Right result -> do
819835 --validate that the result matches the expected type
820− _ <- either throwE pure (atomTypeVerify (last (atomFuncType func)) (atomTypeForAtom result))
836+ _ <- lift $ except (atomTypeVerify (last (atomFuncType func)) (atomTypeForAtom result))
821837 pure result
822−evalAtomExpr tupIn (RelationAtomExpr relExpr) = do
838+evalGraphRefAtomExpr tupIn (RelationAtomExpr relExpr) = do
823839 --merge existing state tuple context into new state tuple context to support an arbitrary number of levels, but new attributes trounce old attributes
824− rstate <- ask
825− runExceptT $ do
826− let newState = mergeTuplesIntoRelationalExprState tupIn rstate
827− relAtom <- either throwE pure (runReader (evalRelationalExpr relExpr) newState)
828− pure (RelationAtom relAtom)
829−evalAtomExpr tupIn cons@(ConstructedAtomExpr dConsName dConsArgs ()) = runExceptT $ do
830− rstate <- lift ask
831− let newState = mergeTuplesIntoRelationalExprState tupIn rstate
832− aType <- either throwE pure (runReader (typeFromAtomExpr (tupleAttributes tupIn) cons) newState)
833− argAtoms <- mapM (\arg -> either throwE pure (runReader (evalAtomExpr tupIn arg) newState)) dConsArgs
840+ env <- ask
841+ let gfEnv = mergeTuplesIntoGraphRefRelationalExprEnv tupIn env
842+ relAtom <- lift $ except $ runGraphRefRelationalExprM gfEnv (evalGraphRefRelationalExpr relExpr)
843+ pure (RelationAtom relAtom)
844+evalGraphRefAtomExpr tupIn cons@(ConstructedAtomExpr dConsName dConsArgs _) = do --why is the tid unused here? suspicious
845+ let mergeEnv = mergeTuplesIntoGraphRefRelationalExprEnv tupIn
846+ aType <- local mergeEnv (typeForGraphRefAtomExpr (tupleAttributes tupIn) cons)
847+ argAtoms <- local mergeEnv $
848+ mapM (evalGraphRefAtomExpr tupIn) dConsArgs
834849 pure (ConstructedAtom dConsName aType argAtoms)
835850
836−typeFromAtomExpr :: Attributes -> AtomExpr -> RelationalExprState (Either RelationalError AtomType)
837−typeFromAtomExpr attrs (AttributeAtomExpr attrName) = do
838− rstate <- ask
851+typeForGraphRefAtomExpr :: Attributes -> GraphRefAtomExpr -> GraphRefRelationalExprM AtomType
852+typeForGraphRefAtomExpr attrs (AttributeAtomExpr attrName) = do
853+ renv <- askEnv
839854 case A.atomTypeForAttributeName attrName attrs of
840− Right aType -> pure (Right aType)
841− Left err@(NoSuchAttributeNamesError _) -> case rstate of
842− RelationalExprStateAttrsElems _ attrs' -> case A.attributeForName attrName attrs' of
843− Left err' -> pure (Left err')
844− Right attr -> pure (Right (A.atomType attr))
845− RelationalExprStateElems _ -> pure (Left err)
846− RelationalExprStateTupleElems _ tup -> case atomForAttributeName attrName tup of
847− Left err' -> pure (Left err')
848− Right atom -> pure (Right (atomTypeForAtom atom))
849− Left err -> pure (Left err)
850−typeFromAtomExpr _ (NakedAtomExpr atom) = pure (Right (atomTypeForAtom atom))
851−typeFromAtomExpr attrs (FunctionAtomExpr funcName atomArgs _) = do
852− context <- fmap stateElemsContext ask
853− let funcs = atomFunctions context
855+ Right aType -> pure aType
856+ Left err@(NoSuchAttributeNamesError _) ->
857+ let envTup = envTuple renv
858+ envAttrs = envAttributes renv in
859+ case A.attributeForName attrName envAttrs of
860+ Right attr -> pure (A.atomType attr)
861+ Left _ -> case atomForAttributeName attrName envTup of
862+ Right atom -> pure (atomTypeForAtom atom)
863+ Left _ -> --throwError (traceStack (show ("typeForGRAtomExpr", attrs, envTup)) err)
864+ throwError err
865+ Left err -> throwError err
866+
867+typeForGraphRefAtomExpr _ (NakedAtomExpr atom) = pure (atomTypeForAtom atom)
868+typeForGraphRefAtomExpr attrs (FunctionAtomExpr funcName atomArgs transId) = do
869+ funcs <- atomFunctions <$> gfDatabaseContextForMarker transId
854870 case atomFunctionForName funcName funcs of
855− Left err -> pure (Left err)
871+ Left err -> throwError err
856872 Right func -> do
857873 let funcRetType = last (atomFuncType func)
858874 funcArgTypes = init (atomFuncType func)
859− eArgTypes <- mapM (typeFromAtomExpr attrs) atomArgs
860− case lefts eArgTypes of
861− errs@(_:_) -> pure (Left (someErrors errs))
862− [] -> do
863− let eTvMap = resolveTypeVariables funcArgTypes argTypes
864− argTypes = rights eArgTypes
865− case eTvMap of
866− Left err -> pure (Left err)
867− Right tvMap -> pure (resolveFunctionReturnValue funcName tvMap funcRetType)
868−typeFromAtomExpr attrs (RelationAtomExpr relExpr) = runExceptT $ do
869− rstate <- lift ask
870− relType <- either throwE pure (runReader (typeForRelationalExpr relExpr) (mergeAttributesIntoRelationalExprState attrs rstate))
875+ argTypes <- mapM (typeForGraphRefAtomExpr attrs) atomArgs
876+ let eTvMap = resolveTypeVariables funcArgTypes argTypes
877+ case eTvMap of
878+ Left err -> throwError err
879+ Right tvMap -> lift $ except $ resolveFunctionReturnValue funcName tvMap funcRetType
880+typeForGraphRefAtomExpr attrs (RelationAtomExpr relExpr) = do
881+ relType <- R.local (mergeAttributesIntoGraphRefRelationalExprEnv attrs) (typeForGraphRefRelationalExpr relExpr)
871882 pure (RelationAtomType (attributes relType))
872883-- grab the type of the data constructor, then validate that the args match the expected types
873−typeFromAtomExpr attrs (ConstructedAtomExpr dConsName dConsArgs _) =
874− runExceptT $ do
875− argsTypes <- mapM (liftE . typeFromAtomExpr attrs) dConsArgs
876− context <- fmap stateElemsContext (lift ask)
877− either throwE pure (atomTypeForDataConstructor (typeConstructorMapping context) dConsName argsTypes)
884+typeForGraphRefAtomExpr attrs (ConstructedAtomExpr dConsName dConsArgs tid) =
885+ do
886+ argsTypes <- mapM (typeForGraphRefAtomExpr attrs) dConsArgs
887+ tConsMap <- typeConstructorMapping <$> gfDatabaseContextForMarker tid
888+ lift $ except $ atomTypeForDataConstructor tConsMap dConsName argsTypes
878889
879890-- | Validate that the type of the AtomExpr matches the expected type.
880−verifyAtomExprTypes :: Relation -> AtomExpr -> AtomType -> RelationalExprState (Either RelationalError AtomType)
881−verifyAtomExprTypes relIn (AttributeAtomExpr attrName) expectedType = runExceptT $ do
882− rstate <- lift ask
891+verifyGraphRefAtomExprTypes :: Relation -> GraphRefAtomExpr -> AtomType -> GraphRefRelationalExprM AtomType
892+verifyGraphRefAtomExprTypes relIn (AttributeAtomExpr attrName) expectedType = do
893+ env <- askEnv
883894 case A.atomTypeForAttributeName attrName (attributes relIn) of
884− Right aType -> either throwE pure (atomTypeVerify expectedType aType)
885− (Left err@(NoSuchAttributeNamesError _)) -> case rstate of
886− RelationalExprStateTupleElems _ _ -> throwE err
887− RelationalExprStateElems _ -> throwE err
888− RelationalExprStateAttrsElems _ attrs -> case A.attributeForName attrName attrs of
889− Left err' -> throwE err'
890− Right attrType -> either throwE pure (atomTypeVerify expectedType (A.atomType attrType))
891− Left err -> throwE err
892−verifyAtomExprTypes _ (NakedAtomExpr atom) expectedType = pure (atomTypeVerify expectedType (atomTypeForAtom atom))
893−verifyAtomExprTypes relIn (FunctionAtomExpr funcName funcArgExprs _) expectedType = do
894− rstate <- ask
895+ Right aType -> lift $ except $ atomTypeVerify expectedType aType
896+ (Left err@(NoSuchAttributeNamesError _)) ->
897+ let attrs' = envAttributes env in
898+ if attrs' == emptyAttributes then
899+ throwError err
900+ else
901+ case A.attributeForName attrName attrs' of
902+ Left err' -> throwError err'
903+ Right attrType -> lift $ except $ atomTypeVerify expectedType (A.atomType attrType)
904+ Left err -> throwError err
905+
906+verifyGraphRefAtomExprTypes _ (NakedAtomExpr atom) expectedType =
907+ lift $ except $ atomTypeVerify expectedType (atomTypeForAtom atom)
908+verifyGraphRefAtomExprTypes relIn (FunctionAtomExpr funcName funcArgExprs tid) expectedType = do
909+ context <- gfDatabaseContextForMarker tid
895910 let functions = atomFunctions context
896− context = stateElemsContext rstate
897− runExceptT $ do
898− func <- either throwE pure (atomFunctionForName funcName functions)
899− let expectedArgTypes = atomFuncType func
900− funcArgTypes <- mapM (\(atomExpr,expectedType2,argCount) -> case runReader (verifyAtomExprTypes relIn atomExpr expectedType2) rstate of
901− Left (AtomTypeMismatchError expSubType actSubType) -> throwE (AtomFunctionTypeError funcName argCount expSubType actSubType)
902− Left err -> throwE err
903− Right x -> pure x
904− ) $ zip3 funcArgExprs expectedArgTypes [1..]
905− if length funcArgTypes /= length expectedArgTypes - 1 then
906− throwE (AtomTypeCountError funcArgTypes expectedArgTypes)
911+ func <- lift $ except $ atomFunctionForName funcName functions
912+ let expectedArgTypes = atomFuncType func
913+ funcArgVerifier (atomExpr, expectedType2, argCount) = do
914+ let handler :: RelationalError -> GraphRefRelationalExprM AtomType
915+ handler (AtomTypeMismatchError expSubType actSubType) = throwError (AtomFunctionTypeError funcName argCount expSubType actSubType)
916+ handler err = throwError err
917+ verifyGraphRefAtomExprTypes relIn atomExpr expectedType2 `catchError` handler
918+ funcArgTypes <- mapM funcArgVerifier $ zip3 funcArgExprs expectedArgTypes [1..]
919+ if length funcArgTypes /= length expectedArgTypes - 1 then
920+ throwError (AtomTypeCountError funcArgTypes expectedArgTypes)
907921 else
908− either throwE pure (atomTypeVerify expectedType (last expectedArgTypes))
909−verifyAtomExprTypes relIn (RelationAtomExpr relationExpr) expectedType = runExceptT $ do
910− rstate <- lift ask
911− relType <- either throwE pure (runReader (typeForRelationalExpr relationExpr) (mergeAttributesIntoRelationalExprState (attributes relIn) rstate))
912− either throwE pure (atomTypeVerify expectedType (RelationAtomType (attributes relType)))
913−verifyAtomExprTypes rel cons@ConstructedAtomExpr{} expectedType = runExceptT $ do
914− cType <- liftE (typeFromAtomExpr (attributes rel) cons)
915− either throwE pure (atomTypeVerify expectedType cType)
922+ lift $ except $ atomTypeVerify expectedType (last expectedArgTypes)
923+verifyGraphRefAtomExprTypes relIn (RelationAtomExpr relationExpr) expectedType =
924+ do
925+ let mergedAttrsEnv e = mergeAttributesIntoGraphRefRelationalExprEnv (attributes relIn) e
926+ relType <- R.local mergedAttrsEnv (typeForGraphRefRelationalExpr relationExpr)
927+ lift $ except $ atomTypeVerify expectedType (RelationAtomType (attributes relType))
928+verifyGraphRefAtomExprTypes rel cons@ConstructedAtomExpr{} expectedType = do
929+ cType <- typeForGraphRefAtomExpr (attributes rel) cons
930+ lift $ except $ atomTypeVerify expectedType cType
916931
917932-- | Look up the type's name and create a new attribute.
918−evalAttrExpr :: TypeConstructorMapping -> AttributeExpr -> Either RelationalError Attribute
919−evalAttrExpr aTypes (AttributeAndTypeNameExpr attrName tCons ()) = do
920− aType <- atomTypeForTypeConstructorValidate True tCons aTypes M.empty
921− validateAtomType aType aTypes
922− Right (Attribute attrName aType)
933+evalGraphRefAttrExpr :: GraphRefAttributeExpr -> GraphRefRelationalExprM Attribute
934+evalGraphRefAttrExpr (AttributeAndTypeNameExpr attrName tCons transId) = do
935+ tConsMap <- typeConstructorMapping <$> gfDatabaseContextForMarker transId
936+ aType <- lift $ except $ atomTypeForTypeConstructorValidate True tCons tConsMap M.empty
937+ lift $ except $ validateAtomType aType tConsMap
938+ pure $ Attribute attrName aType
923939
924−evalAttrExpr _ (NakedAttributeExpr attr) = Right attr
925−
926−evalTupleExpr :: Maybe Attributes -> TupleExpr -> RelationalExprState (Either RelationalError RelationTuple)
927−evalTupleExpr mAttrs (TupleExpr tupMap) = do
928− context <- fmap stateElemsContext ask
929− runExceptT $ do
940+evalGraphRefAttrExpr (NakedAttributeExpr attr) = pure attr
941+
942+-- for tuple type concrete resolution (Nothing ==> Maybe Int) when the attributes hint is Nothing, we need to first process all the tuples, then extract the concrete types on a per-attribute basis, then reprocess the tuples to include the concrete types
943+evalGraphRefTupleExprs :: Maybe Attributes -> GraphRefTupleExprs -> GraphRefRelationalExprM [RelationTuple]
944+evalGraphRefTupleExprs _ (TupleExprs _ []) = pure []
945+evalGraphRefTupleExprs mAttrs (TupleExprs fixedMarker tupleExprL) = do
946+ tuples <- mapM (evalGraphRefTupleExpr mAttrs) tupleExprL
947+ finalAttrs <- case mAttrs of
948+ Just attrs -> pure attrs
949+ Nothing ->
950+ case tuples of
951+ [] -> pure emptyAttributes
952+ (headTuple:tailTuples) -> do
953+ --gather up resolved atom types or throw an error if an attribute cannot be made concrete from the inferred types- this could still fail if the type cannot be inferred (e.g. from [Nothing, Nothing])
954+ let
955+ processTupleAttrs (tupAttr, accAttr) =
956+ --if the attribute is a constructedatomtype, we can recurse into it to potentially resolve type variables
957+ if isResolvedAttribute accAttr && tupAttr == accAttr then
958+ pure accAttr
959+ else
960+ lift $ except $ resolveAttributes accAttr tupAttr
961+ mostResolvedTypes <-
962+ foldM (\acc tup -> do
963+ let zipped = zip (V.toList . attributesVec $ tupleAttributes tup) acc
964+ accNames = S.fromList $ map A.attributeName acc
965+ tupNames = A.attributeNameSet (tupleAttributes tup)
966+ attrNamesDiff = S.union (S.difference accNames tupNames) (S.difference tupNames accNames)
967+ unless (null attrNamesDiff) (throwError (AttributeNamesMismatchError attrNamesDiff))
968+ nextTupleAttrs <- mapM processTupleAttrs zipped
969+ let diff = A.attributesDifference (A.attributesFromList nextTupleAttrs) (A.attributesFromList acc)
970+ if diff == A.emptyAttributes then
971+ pure nextTupleAttrs
972+ else
973+ throwError (TupleAttributeTypeMismatchError diff)
974+ ) (V.toList . attributesVec $ tupleAttributes headTuple) tailTuples
975+ pure (A.attributesFromList mostResolvedTypes)
976+ --strategy: if all the tuple expr transaction markers refer to one location, then we can pass the type constructor mapping from that location, otherwise, we cannot assume that the types are the same
977+ tConsMap <- case singularTransactions tupleExprL of
978+ SingularTransactionRef commonTransId ->
979+ typeConstructorMapping <$> gfDatabaseContextForMarker commonTransId
980+ NoTransactionsRef ->
981+ typeConstructorMapping <$> gfDatabaseContextForMarker fixedMarker
982+ -- if there are multiple transaction markers in the TupleExprs, then we can't assume a single type constructor mapping- this could be improved in the future, but if all the tuples are fully resolved, then we don't need further resolution
983+ _ -> throwError TupleExprsReferenceMultipleMarkersError
984+ lift $ except $ validateAttributes tConsMap finalAttrs
985+ mapM (lift . except . resolveTypesInTuple finalAttrs tConsMap) tuples
986+
987+
988+--resolveAttributes (Attribute "gonk" (ConstructedAtomType "Either" (fromList [("a",IntegerAtomType),("b",TypeVariableType "b")]))) (Attribute "gonk" (ConstructedAtomType "Either" (fromList [("a",TypeVariableType "a"),("b",TextAtomType)])))
989+
990+evalGraphRefTupleExpr :: Maybe Attributes -> GraphRefTupleExpr -> GraphRefRelationalExprM RelationTuple
991+evalGraphRefTupleExpr mAttrs (TupleExpr tupMap) = do
930992 -- it's not possible for AtomExprs in tuple constructors to reference other Attributes' atoms due to the necessary order-of-operations (need a tuple to pass to evalAtomExpr)- it may be possible with some refactoring of type usage or delayed evaluation- needs more thought, but not a priority
931993 -- I could adjust this logic so that when the attributes are not specified (Nothing), then I can attempt to extract the attributes from the tuple- the type resolution will blow up if an ambiguous data constructor is used (Left 4) and this should allow simple cases to "relation{tuple{a 4}}" to be processed
932− let attrs = fromMaybe A.emptyAttributes mAttrs
933− attrAtoms <- mapM (\(attrName, aExpr) -> do
934− --provided when the relation header is available
935− let eExpectedAtomType = A.atomTypeForAttributeName attrName attrs
936− unresolvedType <- liftE (typeFromAtomExpr attrs aExpr)
937− resolvedType <- case eExpectedAtomType of
994+ let attrs = fromMaybe A.emptyAttributes mAttrs
995+ resolveOneAtom (attrName, aExpr) =
996+ do
997+ --provided when the relation header is available
998+ let eExpectedAtomType = A.atomTypeForAttributeName attrName attrs
999+ unresolvedType <- typeForGraphRefAtomExpr attrs aExpr
1000+ resolvedType <- case eExpectedAtomType of
9381001 Left _ -> pure unresolvedType
939− Right typeHint -> either throwE pure (resolveAtomType typeHint unresolvedType)
1002+ Right typeHint -> lift $ except $ resolveAtomType typeHint unresolvedType
9401003 --resolve atom typevars based on resolvedType?
941− newAtom <- liftE (evalAtomExpr emptyTuple aExpr)
942− pure (attrName, newAtom, resolvedType)
943− ) (M.toList tupMap)
944− let tupAttrs = A.attributesFromList $ map (\(attrName, _, aType) -> Attribute attrName aType) attrAtoms
945− atoms = V.fromList $ map (\(_, atom, _) -> atom) attrAtoms
946− tup = mkRelationTuple tupAttrs atoms
947− tConss = typeConstructorMapping context
948− finalAttrs = fromMaybe tupAttrs mAttrs
1004+ newAtom <- evalGraphRefAtomExpr emptyTuple aExpr
1005+ pure (attrName, newAtom, resolvedType)
1006+ attrAtoms <- mapM resolveOneAtom (M.toList tupMap)
1007+ let tupAttrs = A.attributesFromList $ map (\(attrName, _, aType) -> Attribute attrName aType) attrAtoms
1008+ atoms = V.fromList $ map (\(_, atom, _) -> atom) attrAtoms
1009+ tup = mkRelationTuple tupAttrs atoms
1010+ finalAttrs = fromMaybe tupAttrs mAttrs
9491011 --verify that the attributes match
950− when (A.attributeNameSet finalAttrs /= A.attributeNameSet tupAttrs) $ throwE (TupleAttributeTypeMismatchError tupAttrs)
951− tup' <- either throwE pure (resolveTypesInTuple finalAttrs tConss (reorderTuple finalAttrs tup))
952− _ <- either throwE pure (validateTuple tup' tConss)
953− pure tup'
954−
955−evalAttributeNames :: AttributeNames -> RelationalExpr -> RelationalExprState (Either RelationalError (S.Set AttributeName))
956−evalAttributeNames attrNames expr = do
957− eExprType <- typeForRelationalExpr expr
958− case eExprType of
959− Left err -> pure (Left err)
960− Right exprTyp -> do
961− let typeNameSet = S.fromList (V.toList (A.attributeNames (attributes exprTyp)))
962− case attrNames of
963− AttributeNames names ->
964− case A.projectionAttributesForNames names (attributes exprTyp) of
965− Left err -> pure (Left err)
966− Right attrs -> pure (Right (S.fromList (V.toList (A.attributeNames attrs))))
1012+ when (A.attributeNameSet finalAttrs /= A.attributeNameSet tupAttrs) $ throwError (TupleAttributeTypeMismatchError tupAttrs)
1013+ --we can't resolve types here- they have to be resolved at the atom level where the graph ref is held
1014+ --tup' <- lift $ except (resolveTypesInTuple finalAttrs tConss (reorderTuple finalAttrs tup))
1015+ let tup' = reorderTuple finalAttrs tup
1016+ --TODO: restore type resolution
1017+-- _ <- lift $ except (validateTuple tup' tConss)
1018+ pure tup'
1019+
1020+--temporary implementation until we have a proper planner+executor
1021+evalGraphRefRelationalExpr :: GraphRefRelationalExpr -> GraphRefRelationalExprM Relation
1022+evalGraphRefRelationalExpr (MakeRelationFromExprs mAttrExprs tupleExprs) = do
1023+ mAttrs <- case mAttrExprs of
1024+ Just _ ->
1025+ Just . A.attributesFromList <$> mapM evalGraphRefAttrExpr (fromMaybe [] mAttrExprs)
1026+ Nothing -> pure Nothing
1027+ tuples <- evalGraphRefTupleExprs mAttrs tupleExprs
1028+ let attrs = fromMaybe firstTupleAttrs mAttrs
1029+ firstTupleAttrs = if null tuples then A.emptyAttributes else tupleAttributes (head tuples)
1030+ lift $ except $ mkRelation attrs (RelationTupleSet tuples)
1031+evalGraphRefRelationalExpr (MakeStaticRelation attributeSet tupleSet) =
1032+ lift $ except $ mkRelation attributeSet tupleSet
1033+evalGraphRefRelationalExpr (ExistingRelation rel) = pure rel
1034+evalGraphRefRelationalExpr (RelationVariable name tid) = do
1035+ ctx <- gfDatabaseContextForMarker tid
1036+ case M.lookup name (relationVariables ctx) of
1037+ Nothing -> throwError (RelVarNotDefinedError name)
1038+ Just rv -> evalGraphRefRelationalExpr rv
1039+evalGraphRefRelationalExpr (Project attrNames expr) = do
1040+ attrNameSet <- evalGraphRefAttributeNames attrNames expr
1041+ rel <- evalGraphRefRelationalExpr expr
1042+ lift $ except $ project attrNameSet rel
1043+evalGraphRefRelationalExpr (Union exprA exprB) = do
1044+ relA <- evalGraphRefRelationalExpr exprA
1045+ relB <- evalGraphRefRelationalExpr exprB
1046+ lift $ except $ union relA relB
1047+evalGraphRefRelationalExpr (Join exprA exprB) = do
1048+ relA <- evalGraphRefRelationalExpr exprA
1049+ relB <- evalGraphRefRelationalExpr exprB
1050+ lift $ except $ join relA relB
1051+evalGraphRefRelationalExpr (Rename oldName newName expr) = do
1052+ rel <- evalGraphRefRelationalExpr expr
1053+ lift $ except $ rename oldName newName rel
1054+evalGraphRefRelationalExpr (Difference exprA exprB) = do
1055+ relA <- evalGraphRefRelationalExpr exprA
1056+ relB <- evalGraphRefRelationalExpr exprB
1057+ lift $ except $ difference relA relB
1058+evalGraphRefRelationalExpr (Group groupAttrNames newAttrName expr) = do
1059+ groupNames <- evalGraphRefAttributeNames groupAttrNames expr
1060+ rel <- evalGraphRefRelationalExpr expr
1061+ lift $ except $ group groupNames newAttrName rel
1062+evalGraphRefRelationalExpr (Ungroup groupAttrName expr) = do
1063+ rel <- evalGraphRefRelationalExpr expr
1064+ lift $ except $ ungroup groupAttrName rel
1065+evalGraphRefRelationalExpr (Restrict predExpr expr) = do
1066+ rel <- evalGraphRefRelationalExpr expr
1067+ filt <- predicateRestrictionFilter (attributes rel) predExpr
1068+ lift $ except $ restrict filt rel
1069+evalGraphRefRelationalExpr (Equals exprA exprB) = do
1070+ relA <- evalGraphRefRelationalExpr exprA
1071+ relB <- evalGraphRefRelationalExpr exprB
1072+ pure $ if relA == relB then relationTrue else relationFalse
1073+evalGraphRefRelationalExpr (NotEquals exprA exprB) = do
1074+ relA <- evalGraphRefRelationalExpr exprA
1075+ relB <- evalGraphRefRelationalExpr exprB
1076+ pure $ if relA == relB then relationFalse else relationTrue
1077+evalGraphRefRelationalExpr (Extend extendTupleExpr expr) = do
1078+ rel <- evalGraphRefRelationalExpr expr
1079+ (newAttrs, tupProc) <- extendGraphRefTupleExpressionProcessor rel extendTupleExpr
1080+ lift $ except $ relMogrify tupProc newAttrs rel
1081+evalGraphRefRelationalExpr expr@With{} =
1082+ --strategy A: add relation variables to the contexts in the graph
1083+ --strategy B: drop in macros in place (easier programmatically)
1084+ --strategy B implementation
1085+ evalGraphRefRelationalExpr (substituteWithNameMacros [] expr)
1086+
1087+dbContextForTransId :: TransactionId -> TransactionGraph -> Either RelationalError DatabaseContext
1088+dbContextForTransId tid graph = do
1089+ trans <- transactionForId tid graph
1090+ pure (concreteDatabaseContext trans)
1091+
1092+transactionForId :: TransactionId -> TransactionGraph -> Either RelationalError Transaction
1093+transactionForId tid graph
1094+ | tid == U.nil =
1095+ Left RootTransactionTraversalError
1096+ | S.null matchingTrans =
1097+ Left $ NoSuchTransactionError tid
1098+ | otherwise =
1099+ Right $ head (S.toList matchingTrans)
1100+ where
1101+ matchingTrans = S.filter (\(Transaction idMatch _ _) -> idMatch == tid) (transactionsForGraph graph)
1102+
1103+typeForGraphRefRelationalExpr :: GraphRefRelationalExpr -> GraphRefRelationalExprM Relation
1104+typeForGraphRefRelationalExpr (MakeStaticRelation attrs _) = lift $ except $ mkRelation attrs emptyTupleSet
1105+typeForGraphRefRelationalExpr (ExistingRelation rel) = pure (emptyRelationWithAttrs (attributes rel))
1106+typeForGraphRefRelationalExpr (MakeRelationFromExprs mAttrExprs tupleExprs) = do
1107+ mAttrs <- case mAttrExprs of
1108+ Just attrExprs -> do
1109+ attrs <- mapM evalGraphRefAttributeExpr attrExprs
1110+ pure (Just (attributesFromList attrs))
1111+ Nothing -> pure Nothing
1112+ tuples <- evalGraphRefTupleExprs mAttrs tupleExprs
1113+ let retAttrs = case tuples of
1114+ (tup:_) -> tupleAttributes tup
1115+ [] -> fromMaybe A.emptyAttributes mAttrs
1116+ pure $ emptyRelationWithAttrs retAttrs
1117+
1118+typeForGraphRefRelationalExpr (RelationVariable rvName tid) = do
1119+ relVars <- relationVariables <$> gfDatabaseContextForMarker tid
1120+ case M.lookup rvName relVars of
1121+ Nothing -> throwError (RelVarNotDefinedError rvName)
1122+ Just rvExpr ->
1123+ typeForGraphRefRelationalExpr rvExpr
1124+typeForGraphRefRelationalExpr (Project attrNames expr) = do
1125+ exprType' <- typeForGraphRefRelationalExpr expr
1126+ projectionAttrs <- evalGraphRefAttributeNames attrNames expr
1127+ lift $ except $ project projectionAttrs exprType'
1128+typeForGraphRefRelationalExpr (Union exprA exprB) = do
1129+ exprA' <- typeForGraphRefRelationalExpr exprA
1130+ exprB' <- typeForGraphRefRelationalExpr exprB
1131+ lift $ except $ union exprA' exprB'
1132+typeForGraphRefRelationalExpr (Join exprA exprB) = do
1133+ exprA' <- typeForGraphRefRelationalExpr exprA
1134+ exprB' <- typeForGraphRefRelationalExpr exprB
1135+ lift $ except $ join exprA' exprB'
1136+typeForGraphRefRelationalExpr (Rename oldAttr newAttr expr) = do
1137+ expr' <- typeForGraphRefRelationalExpr expr
1138+ lift $ except $ rename oldAttr newAttr expr'
1139+typeForGraphRefRelationalExpr (Difference exprA exprB) = do
1140+ exprA' <- typeForGraphRefRelationalExpr exprA
1141+ exprB' <- typeForGraphRefRelationalExpr exprB
1142+ lift $ except $ difference exprA' exprB'
1143+typeForGraphRefRelationalExpr (Group groupNames attrName expr) = do
1144+ expr' <- typeForGraphRefRelationalExpr expr
1145+ groupNames' <- evalGraphRefAttributeNames groupNames expr
1146+ lift $ except $ group groupNames' attrName expr'
1147+typeForGraphRefRelationalExpr (Ungroup groupAttrName expr) = do
1148+ expr' <- typeForGraphRefRelationalExpr expr
1149+ lift $ except $ ungroup groupAttrName expr'
1150+typeForGraphRefRelationalExpr (Restrict pred' expr) = do
1151+ expr' <- typeForGraphRefRelationalExpr expr
1152+ filt <- predicateRestrictionFilter (attributes expr') pred'
1153+ lift $ except $ restrict filt expr'
1154+typeForGraphRefRelationalExpr Equals{} =
1155+ pure relationFalse
1156+typeForGraphRefRelationalExpr NotEquals{} =
1157+ pure relationFalse
1158+typeForGraphRefRelationalExpr (Extend extendTupleExpr expr) = do
1159+ rel <- typeForGraphRefRelationalExpr expr
1160+ evalGraphRefRelationalExpr (Extend extendTupleExpr (ExistingRelation rel))
1161+typeForGraphRefRelationalExpr expr@(With withs _) = do
1162+ let expr' = substituteWithNameMacros [] expr
1163+ checkMacroName (WithNameExpr macroName tid) = do
1164+ rvs <- relationVariables <$> gfDatabaseContextForMarker tid
1165+ case M.lookup macroName rvs of
1166+ Just _ -> lift $ except $ Left (RelVarAlreadyDefinedError macroName) --this error does not include the transaction marker, but should be good enough to identify the cause
1167+ Nothing -> pure ()
1168+ mapM_ (checkMacroName . fst) withs
1169+ typeForGraphRefRelationalExpr expr'
1170+
1171+evalGraphRefAttributeNames :: GraphRefAttributeNames -> GraphRefRelationalExpr -> GraphRefRelationalExprM (S.Set AttributeName)
1172+evalGraphRefAttributeNames attrNames expr = do
1173+ exprType' <- typeForGraphRefRelationalExpr expr
1174+ let typeNameSet = S.fromList (V.toList (A.attributeNames (attributes exprType')))
1175+ case attrNames of
1176+ AttributeNames names ->
1177+ case A.projectionAttributesForNames names (attributes exprType') of
1178+ Left err -> throwError err
1179+ Right attrs -> pure (S.fromList (V.toList (A.attributeNames attrs)))
9671180
968− InvertedAttributeNames names -> do
1181+ InvertedAttributeNames names -> do
9691182 let nonExistentAttributeNames = A.attributeNamesNotContained names typeNameSet
9701183 if not (S.null nonExistentAttributeNames) then
971− pure (Left (AttributeNamesMismatchError nonExistentAttributeNames))
1184+ throwError $ AttributeNamesMismatchError nonExistentAttributeNames
9721185 else
973− pure (Right (A.nonMatchingAttributeNameSet names typeNameSet))
1186+ pure (A.nonMatchingAttributeNameSet names typeNameSet)
9741187
975− UnionAttributeNames namesA namesB -> do
976− eNameSetA <- evalAttributeNames namesA expr
977− case eNameSetA of
978− Left err -> pure (Left err)
979− Right nameSetA -> do
980− eNameSetB <- evalAttributeNames namesB expr
981− case eNameSetB of
982− Left err -> pure (Left err)
983− Right nameSetB ->
984− pure (Right (S.union nameSetA nameSetB))
1188+ UnionAttributeNames namesA namesB -> do
1189+ nameSetA <- evalGraphRefAttributeNames namesA expr
1190+ nameSetB <- evalGraphRefAttributeNames namesB expr
1191+ pure (S.union nameSetA nameSetB)
9851192
986− IntersectAttributeNames namesA namesB -> do
987− eNameSetA <- evalAttributeNames namesA expr
988− case eNameSetA of
989− Left err -> pure (Left err)
990− Right nameSetA -> do
991− eNameSetB <- evalAttributeNames namesB expr
992− case eNameSetB of
993− Left err -> pure (Left err)
994− Right nameSetB ->
995− pure (Right (S.intersection nameSetA nameSetB))
1193+ IntersectAttributeNames namesA namesB -> do
1194+ nameSetA <- evalGraphRefAttributeNames namesA expr
1195+ nameSetB <- evalGraphRefAttributeNames namesB expr
1196+ pure (S.intersection nameSetA nameSetB)
9961197
997− RelationalExprAttributeNames attrExpr -> do
998− eAttrExprType <- typeForRelationalExpr attrExpr
999− case eAttrExprType of
1000− Left err -> pure (Left err)
1001− Right attrExprType -> pure (Right (A.attributeNameSet (attributes attrExprType)))
1002−
1198+ RelationalExprAttributeNames attrExpr -> do
1199+ attrExprType <- typeForGraphRefRelationalExpr attrExpr
1200+ pure (A.attributeNameSet (attributes attrExprType))
1201+
1202+evalGraphRefAttributeExpr :: GraphRefAttributeExpr -> GraphRefRelationalExprM Attribute
1203+evalGraphRefAttributeExpr (AttributeAndTypeNameExpr attrName tCons tid) = do
1204+ tConsMap <- typeConstructorMapping <$> gfDatabaseContextForMarker tid
1205+ case atomTypeForTypeConstructorValidate True tCons tConsMap M.empty of
1206+ Left err -> throwError err
1207+ Right aType -> do
1208+ case validateAtomType aType tConsMap of
1209+ Left err -> throwError err
1210+ Right _ -> pure (Attribute attrName aType)
1211+evalGraphRefAttributeExpr (NakedAttributeExpr attr) = pure attr
1212+
1213+mkEmptyRelVars :: RelationVariables -> RelationVariables
1214+mkEmptyRelVars = M.map mkEmptyRelVar
1215+ where
1216+ mkEmptyRelVar expr@MakeRelationFromExprs{} = expr --do not truncate here because we might lose essential type information in emptying the tuples
1217+ mkEmptyRelVar (MakeStaticRelation attrs _) = MakeStaticRelation attrs emptyTupleSet
1218+ mkEmptyRelVar (ExistingRelation rel) = ExistingRelation (emptyRelationWithAttrs (attributes rel))
1219+ mkEmptyRelVar rv@RelationVariable{} = Restrict (NotPredicate TruePredicate) rv
1220+ mkEmptyRelVar (Project attrNames expr) = Project attrNames (mkEmptyRelVar expr)
1221+ mkEmptyRelVar (Union exprA exprB) = Union (mkEmptyRelVar exprA) (mkEmptyRelVar exprB)
1222+ mkEmptyRelVar (Join exprA exprB) = Join (mkEmptyRelVar exprA) (mkEmptyRelVar exprB)
1223+ mkEmptyRelVar (Rename nameA nameB expr) = Rename nameA nameB (mkEmptyRelVar expr)
1224+ mkEmptyRelVar (Difference exprA exprB) = Difference (mkEmptyRelVar exprA) (mkEmptyRelVar exprB)
1225+ mkEmptyRelVar (Group attrNames attrName expr) = Group attrNames attrName (mkEmptyRelVar expr)
1226+ mkEmptyRelVar (Ungroup attrName expr) = Ungroup attrName (mkEmptyRelVar expr)
1227+ mkEmptyRelVar (Restrict pred' expr) = Restrict pred' (mkEmptyRelVar expr)
1228+ mkEmptyRelVar (Equals exprA exprB) = Equals (mkEmptyRelVar exprA) (mkEmptyRelVar exprB)
1229+ mkEmptyRelVar (NotEquals exprA exprB) = NotEquals (mkEmptyRelVar exprA) (mkEmptyRelVar exprB)
1230+ mkEmptyRelVar (Extend extTuple expr) = Extend extTuple (mkEmptyRelVar expr)
1231+ mkEmptyRelVar (With macros expr) = With (map (second mkEmptyRelVar) macros) (mkEmptyRelVar expr)
1232+
1233+
1234+dbErr :: RelationalError -> DatabaseContextEvalMonad ()
1235+dbErr err = lift (except (Left err))
1236+
1237+-- | Return a Relation describing the relation variables.
1238+relationVariablesAsRelation :: DatabaseContext -> TransactionGraph -> Either RelationalError Relation
1239+relationVariablesAsRelation ctx graph = do
1240+ let subrelAttrs = A.attributesFromList [Attribute "attribute" TextAtomType, Attribute "type" TextAtomType]
1241+ attrs = A.attributesFromList [Attribute "name" TextAtomType,
1242+ Attribute "attributes" (RelationAtomType subrelAttrs)]
1243+ relVars = relationVariables ctx
1244+ mkRvDesc (rvName, gfExpr) = do
1245+ let gfEnv = freshGraphRefRelationalExprEnv (Just ctx) graph
1246+ gfType <- runGraphRefRelationalExprM gfEnv (typeForGraphRefRelationalExpr gfExpr)
1247+ pure (rvName, gfType)
1248+ relVarToAtomList (rvName, rel) = [TextAtom rvName, attributesToRel (attributesVec (attributes rel))]
1249+ attrAtoms a = [TextAtom (A.attributeName a), TextAtom (prettyAtomType (A.atomType a))]
1250+ attributesToRel attrl = case mkRelationFromList subrelAttrs (map attrAtoms (V.toList attrl)) of
1251+ Left err -> error ("relationVariablesAsRelation pooped " ++ show err)
1252+ Right rel -> RelationAtom rel
1253+ rvs <- mapM mkRvDesc (M.toList relVars)
1254+ let tups = map relVarToAtomList rvs
1255+ mkRelationFromList attrs tups
1256+
1257+-- | An unoptimized variant of evalGraphRefRelationalExpr for testing.
1258+evalRelationalExpr :: RelationalExpr -> RelationalExprM Relation
1259+evalRelationalExpr expr = do
1260+ graph <- reGraph
1261+ context <- reContext
1262+ let expr' = runProcessExprM UncommittedContextMarker (processRelationalExpr expr)
1263+ gfEnv = freshGraphRefRelationalExprEnv (Just context) graph
1264+ case runGraphRefRelationalExprM gfEnv (evalGraphRefRelationalExpr expr') of
1265+ Left err -> throwError err
1266+ Right rel -> pure rel
1267+
1268+class (MonadError RelationalError m, Monad m) => DatabaseContextM m where
1269+ getContext :: m DatabaseContext
1270+
1271+instance DatabaseContextM (ReaderT GraphRefRelationalExprEnv (ExceptT RelationalError Identity)) where
1272+ getContext = gfDatabaseContextForMarker UncommittedContextMarker
1273+
1274+instance DatabaseContextM (RWST DatabaseContextEvalEnv () DatabaseContextEvalState (ExceptT RelationalError Identity)) where
1275+ getContext = getStateContext
1276+
1277+relVarByName :: DatabaseContextM m => RelVarName -> m GraphRefRelationalExpr
1278+relVarByName rvName = do
1279+ relvars <- relationVariables <$> getContext
1280+ case M.lookup rvName relvars of
1281+ Nothing -> throwError (RelVarNotDefinedError rvName)
1282+ Just gfexpr -> pure gfexpr
1283+
1284+-- | resolve UncommittedTransactionMarker whenever possible- this is important in the DatabaseContext in order to mitigate self-referencing loops for updates
1285+class ResolveGraphRefTransactionMarker a where
1286+ resolve :: a -> DatabaseContextEvalMonad a
1287+
1288+-- s := s union t
1289+instance ResolveGraphRefTransactionMarker GraphRefRelationalExpr where
1290+ resolve (MakeRelationFromExprs mAttrs tupleExprs) =
1291+ MakeRelationFromExprs mAttrs <$> resolve tupleExprs
1292+ resolve orig@MakeStaticRelation{} = pure orig
1293+ resolve orig@ExistingRelation{} = pure orig
1294+ resolve orig@(RelationVariable rvName UncommittedContextMarker) = do
1295+ rvMap <- relationVariables <$> getStateContext
1296+ case M.lookup rvName rvMap of
1297+ Nothing -> pure orig
1298+ Just resolvedRv -> resolve resolvedRv
1299+ resolve orig@RelationVariable{} = pure orig
1300+ resolve (Project attrNames relExpr) = Project <$> resolve attrNames <*> resolve relExpr
1301+ resolve (Union exprA exprB) = Union <$> resolve exprA <*> resolve exprB
1302+ resolve (Join exprA exprB) = Join <$> resolve exprA <*> resolve exprB
1303+ resolve (Rename attrA attrB expr) = Rename attrA attrB <$> resolve expr
1304+ resolve (Difference exprA exprB) = Difference <$> resolve exprA <*> resolve exprB
1305+ resolve (Group namesA nameB expr) = Group <$> resolve namesA <*> pure nameB <*> resolve expr
1306+ resolve (Ungroup nameA expr) = Ungroup nameA <$> resolve expr
1307+ resolve (Restrict restrictExpr relExpr) = Restrict <$> resolve restrictExpr <*> resolve relExpr
1308+ resolve (Equals exprA exprB) = Equals <$> resolve exprA <*> resolve exprB
1309+ resolve (NotEquals exprA exprB) = NotEquals <$> resolve exprA <*> resolve exprB
1310+ resolve (Extend extendExpr relExpr) = Extend <$> resolve extendExpr <*> resolve relExpr
1311+ resolve (With withExprs relExpr) = With <$> mapM (\(nam, expr) -> (,) <$> resolve nam <*> resolve expr) withExprs <*> resolve relExpr
1312+
1313+instance ResolveGraphRefTransactionMarker GraphRefTupleExprs where
1314+ resolve (TupleExprs marker tupleExprs) =
1315+ TupleExprs marker <$> mapM resolve tupleExprs
1316+
1317+instance ResolveGraphRefTransactionMarker GraphRefTupleExpr where
1318+ resolve (TupleExpr tupMap) = do
1319+ tupMap' <- mapM (\(attrName, expr) -> (,) attrName <$> resolve expr ) (M.toList tupMap)
1320+ pure (TupleExpr (M.fromList tupMap'))
1321+
1322+instance ResolveGraphRefTransactionMarker GraphRefAttributeNames where
1323+ resolve orig@AttributeNames{} = pure orig
1324+ resolve orig@InvertedAttributeNames{} = pure orig
1325+ resolve (UnionAttributeNames namesA namesB) = UnionAttributeNames <$> resolve namesA <*> resolve namesB
1326+ resolve (IntersectAttributeNames namesA namesB) = IntersectAttributeNames <$> resolve namesA <*> resolve namesB
1327+ resolve (RelationalExprAttributeNames expr) = RelationalExprAttributeNames <$> resolve expr
1328+
1329+instance ResolveGraphRefTransactionMarker GraphRefRestrictionPredicateExpr where
1330+ resolve TruePredicate = pure TruePredicate
1331+ resolve (AndPredicate exprA exprB) = AndPredicate <$> resolve exprA <*> resolve exprB
1332+ resolve (OrPredicate exprA exprB) = OrPredicate <$> resolve exprA <*> resolve exprB
1333+ resolve (NotPredicate expr) = NotPredicate <$> resolve expr
1334+ resolve (RelationalExprPredicate expr) = RelationalExprPredicate <$> resolve expr
1335+ resolve (AtomExprPredicate expr) = AtomExprPredicate <$> resolve expr
1336+ resolve (AttributeEqualityPredicate nam expr)= AttributeEqualityPredicate nam <$> resolve expr
1337+
1338+instance ResolveGraphRefTransactionMarker GraphRefExtendTupleExpr where
1339+ resolve (AttributeExtendTupleExpr nam atomExpr) = AttributeExtendTupleExpr nam <$> resolve atomExpr
1340+
1341+instance ResolveGraphRefTransactionMarker GraphRefWithNameExpr where
1342+ resolve orig@WithNameExpr{} = pure orig -- match uncommitted marker?
1343+
1344+instance ResolveGraphRefTransactionMarker GraphRefAtomExpr where
1345+ resolve orig@AttributeAtomExpr{} = pure orig
1346+ resolve orig@NakedAtomExpr{} = pure orig
1347+ resolve (FunctionAtomExpr nam atomExprs marker) =
1348+ FunctionAtomExpr nam <$> mapM resolve atomExprs <*> pure marker
1349+ resolve (RelationAtomExpr expr) = RelationAtomExpr <$> resolve expr
1350+ resolve (ConstructedAtomExpr dConsName atomExprs marker) =
1351+ ConstructedAtomExpr dConsName <$> mapM resolve atomExprs <*> pure marker
1352+
1353+--convert series of simple Union queries into MakeStaticRelation
1354+-- this is especially useful for long, nested applications of Union with simple tuples
1355+-- Union (MakeRelation x y) (MakeRelation x y') -> MakeRelation x (y + y')
1356+
1357+--MakeRelationFromExprs Nothing (TupleExprs UncommittedContextMarker [TupleExpr (fromList [("name", NakedAtomExpr (TextAtom "steve"))])])
1358+
1359+applyUnionCollapse :: GraphRefRelationalExpr -> GraphRefRelationalExpr
1360+applyUnionCollapse = Fold.cata opt
1361+ where
1362+ opt :: RelationalExprBaseF GraphRefTransactionMarker GraphRefRelationalExpr -> GraphRefRelationalExpr
1363+ opt (UnionF exprA exprB) | exprA == exprB = exprA
1364+ opt (UnionF
1365+ exprA@(MakeRelationFromExprs mAttrs1 tupExprs1)
1366+ exprB@(MakeRelationFromExprs mAttrs2 tupExprs2)) | tupExprs1 == tupExprs2 = MakeRelationFromExprs (mAttrs1 <|> mAttrs2) tupExprs1
1367+ | tupExprsNull tupExprs1 = exprB
1368+ | tupExprsNull tupExprs2 = exprA
1369+ opt x = Fold.embed x
1370+ tupExprsNull (TupleExprs _ []) = True
1371+ tupExprsNull _ = False
1372+
1373+
1374+--UPDATE optimization- find matching where clause in "lower" levels of renaming
1375+--update x where y=1 set (x:=5,z:=10); update x where y=1 set(x:=6,z:=11)
1376+-- =>
1377+-- update x where y=1 set (x:=6,z:=11)
1378+-- future opt: match individual attributes update x where y=1 set (x:=5); update x where y=1 set (z:=11) => update x where y=1 set (x:=5,z:=11)
1379+
1380+--strategy: try to collapse the top-level update (union (restrict pred MakeRelationFromExpr) expr) if it contains the same predicate and resultant relation
1381+
1382+--DELETE optimization
1383+-- if a restriction matches a previous restriction, combine them
1384+-- O(1) since it only scans at the top level, critical in benchmarks generating redundant deletions
1385+applyRestrictionCollapse :: GraphRefRelationalExpr -> GraphRefRelationalExpr
1386+applyRestrictionCollapse orig@(Restrict npred@(NotPredicate _) expr) =
1387+ case expr of
1388+ orig'@(Restrict npred'@(NotPredicate _) _) | npred == npred' -> orig'
1389+ _ -> orig
1390+applyRestrictionCollapse expr = expr
1391+
1392+
src/lib/ProjectM36/ScriptSession.hs+72−44
@@ -1,8 +1,12 @@
1−{-# LANGUAGE MagicHash, UnboxedTuples #-}
1+{-# LANGUAGE UnboxedTuples, KindSignatures, DataKinds #-}
2+#ifdef PM36_HASKELL_SCRIPTING
3+{-# LANGUAGE MagicHash #-}
4+#endif
25module ProjectM36.ScriptSession where
36
7+#ifdef PM36_HASKELL_SCRIPTING
48import ProjectM36.Error
5−
9+import GHC
610import Control.Exception
711import Control.Monad
812import System.IO.Error
@@ -13,9 +17,8 @@ import System.FilePath
1317import System.Info (os, arch)
1418import Data.Text (Text, unpack)
1519import Data.Maybe
16−
17−import GHC
1820import GHC.Paths (libdir)
21+import System.Environment
1922#if __GLASGOW_HASKELL__ >= 800
2023import GHC.LanguageExtensions
2124import GHCi.ObjLink
@@ -33,25 +36,41 @@ import Unsafe.Coerce
3336#if __GLASGOW_HASKELL__ >= 802
3437import Type
3538#elif __GLASGOW_HASKELL__ >= 710
36−import Type hiding (pprTyThing)
39+import Type hiding (pprTyThing)
3740#else
3841#endif
39−
4042import GHC.Exts (addrToAny#)
4143import GHC.Ptr (Ptr(..))
4244import Encoding
45+#endif
46+
4347
4448data ScriptSession = ScriptSession {
45− hscEnv :: HscEnv,
49+#ifdef PM36_HASKELL_SCRIPTING
50+ hscEnv :: HscEnv,
4651 atomFunctionBodyType :: Type,
4752 dbcFunctionBodyType :: Type
53+#endif
4854 }
49−
50−newtype ScriptSessionError = ScriptSessionLoadError GhcException
55+
56+#ifdef PM36_HASKELL_SCRIPTING
57+data ScriptSessionError = ScriptSessionLoadError GhcException
58+ | ScriptingDisabled
5159 deriving (Show)
60+#else
61+data ScriptSessionError = ScriptingDisabled
62+ deriving (Show)
63+#endif
64+
65+data LoadSymbolError = LoadSymbolError
66+type ModName = String
67+type FuncName = String
5268
5369-- | Configure a GHC environment/session which we will use for all script compilation.
5470initScriptSession :: [String] -> IO (Either ScriptSessionError ScriptSession)
71+#if !defined(PM36_HASKELL_SCRIPTING)
72+initScriptSession _ = pure (Left ScriptingDisabled)
73+#else
5574initScriptSession ghcPkgPaths = do
5675 --for the sake of convenience, for developers' builds, include the local cabal sandbox package database and the cabal new-build package database
5776 eHomeDir <- tryJust (guard . isDoesNotExistError) getHomeDirectory
@@ -60,28 +79,30 @@ initScriptSession ghcPkgPaths = do
6079 handleGhcException excHandler $ runGhc (Just libdir) $ do
6180 dflags <- getSessionDynFlags
6281 let ghcVersion = projectVersion dflags
82+ -- get nix packages dir, if available
83+ mNixLibDir <- liftIO $ lookupEnv "NIX_GHC_LIBDIR"
6384
6485 sandboxPkgPaths <- liftIO $ concat <$> mapM glob [
65− "./dist-newstyle/packagedb/ghc-" ++ ghcVersion,
86+ --"./dist-newstyle/packagedb/ghc-" ++ ghcVersion, --rely on cabal 3's ghc.environment install: "cabal install --lib project-m36"
6687 ".cabal-sandbox/*ghc-" ++ ghcVersion ++ "-packages.conf.d",
6788 ".stack-work/install/*/*/" ++ ghcVersion ++ "/pkgdb",
6889 ".stack-work/install/*/pkgdb/", --windows stack build
6990 "C:/sr/snapshots/b201cfe6/pkgdb", --windows stack build- ideally, we could run `stack path --snapshot-pkg-db, but this is sufficient to pass CI
70− homeDir </> ".stack/snapshots/*/*/" ++ ghcVersion ++ "/pkgdb",
71− homeDir </> ".cabal/store/ghc-" ++ ghcVersion ++ "/package.db"
91+ homeDir </> ".stack/snapshots/*/*/" ++ ghcVersion ++ "/pkgdb"
92+ --homeDir </> ".cabal/store/ghc-" ++ ghcVersion ++ "/package.db"
7293 ]
73−
74− let localPkgPaths = map PkgConfFile (ghcPkgPaths ++ sandboxPkgPaths)
75−
76− let dflags' = applyGopts . applyXopts $ dflags { hscTarget = HscInterpreted ,
77− ghcLink = LinkInMemory,
94+
95+ let localPkgPaths = map PkgConfFile (ghcPkgPaths ++ sandboxPkgPaths ++ maybeToList mNixLibDir)
96+
97+ let dflags' = applyGopts . applyXopts $ dflags { hscTarget = HscInterpreted ,
98+ ghcLink = LinkInMemory,
7899 safeHaskell = Sf_Trustworthy,
79100 safeInfer = True,
80101 safeInferred = True,
81102 --verbosity = 3,
82−#if __GLASGOW_HASKELL__ >= 800
103+#if __GLASGOW_HASKELL__ >= 800
83104 trustFlags = map TrustPackage required_packages,
84−#endif
105+#endif
85106 packageFlags = packageFlags dflags ++ packages,
86107#if __GLASGOW_HASKELL__ >= 802
87108 packageDBFlags = map PackageDB localPkgPaths
@@ -94,11 +115,11 @@ initScriptSession ghcPkgPaths = do
94115 applyXopts flags = foldl xopt_set flags xopts
95116#if __GLASGOW_HASKELL__ >= 800
96117 xopts = [OverloadedStrings, ExtendedDefaultRules, ImplicitPrelude, ScopedTypeVariables]
97−#else
118+#else
98119 xopts = [Opt_OverloadedStrings, Opt_ExtendedDefaultRules, Opt_ImplicitPrelude, Opt_ScopedTypeVariables]
99120#endif
100121 gopts = [] --[Opt_DistrustAllPackages, Opt_PackageTrust]
101− required_packages = ["base",
122+ required_packages = ["base",
102123 "containers",
103124 "Glob",
104125 "directory",
@@ -107,8 +128,6 @@ initScriptSession ghcPkgPaths = do
107128 "uuid",
108129 "vector",
109130 "text",
110− "binary",
111− "vector-binary-instances",
112131 "time",
113132 "project-m36",
114133 "bytestring"]
@@ -120,20 +139,33 @@ initScriptSession ghcPkgPaths = do
120139 --liftIO $ traceShowM (showSDoc dflags' (ppr packages))
121140 _ <- setSessionDynFlags dflags'
122141 let safeImportDecl mn mQual = ImportDecl {
123−#if __GLASGOW_HASKELL__ >= 802
142+#if __GLASGOW_HASKELL__ >= 802
124143 ideclSourceSrc = NoSourceText,
125144#else
126145 ideclSourceSrc = Nothing,
127146#endif
147+
148+#if __GLASGOW_HASKELL__ >= 810
149+ ideclExt = noExtField,
150+#elif __GLASGOW_HASKELL__ >= 806
151+ ideclExt = NoExt,
152+#endif
128153 ideclName = noLoc mn,
129154 ideclPkgQual = Nothing,
130155 ideclSource = False,
131156 ideclSafe = True,
132157 ideclImplicit = False,
158+#if __GLASGOW_HASKELL__ >= 810
159+ ideclQualified = if isJust mQual then QualifiedPre else NotQualified,
160+#else
133161 ideclQualified = isJust mQual,
162+#endif
134163 ideclAs = mQual,
135164 ideclHiding = Nothing
136165 }
166+#if __GLASGOW_HASKELL__ >= 806
167+ :: ImportDecl (GhcPass (c :: Pass))
168+#endif
137169 unqualifiedModules = map (\modn -> IIDecl $ safeImportDecl (mkModuleName modn) Nothing) [
138170 "Prelude",
139171 "Data.Map",
@@ -150,7 +182,7 @@ initScriptSession ghcPkgPaths = do
150182 mkModName = noLoc . mkModuleName
151183#else
152184 mkModName = mkModuleName
153−#endif
185+#endif
154186 qualifiedModules = map (\(modn, qualNam) -> IIDecl $ safeImportDecl (mkModuleName modn) (Just (mkModName qualNam))) [
155187 ("Data.Text", "T")
156188 ]
@@ -163,8 +195,8 @@ initScriptSession ghcPkgPaths = do
163195addImport :: String -> Ghc ()
164196addImport moduleNam = do
165197 ctx <- getContext
166− setContext ( (IIDecl $ simpleImportDecl (mkModuleName moduleNam)) : ctx )
167−
198+ setContext (IIDecl (simpleImportDecl (mkModuleName moduleNam)) : ctx)
199+
168200showType :: DynFlags -> Type -> String
169201showType dflags ty = showSDocForUser dflags alwaysQualify (pprTypeForUser ty)
170202
@@ -189,41 +221,36 @@ compileScript funcType script = do
189221 mErr <- typeCheckScript funcType script
190222 case mErr of
191223 Just err -> pure (Left err)
192− Nothing ->
224+ Nothing ->
193225 --catch exception here
194226 --we could potentially wrap the script with Atom pattern matching so that the script doesn't have to do it, but the change to an Atom ADT should make it easier. Still, it would be nice if the script didn't have to handle a list of arguments, for example.
195227 -- we can't use dynCompileExpr here because
196228 Right . unsafeCoerce <$> compileExpr sScript
197−
198−typeCheckScript :: Type -> Text -> Ghc (Maybe ScriptCompilationError)
229+
230+typeCheckScript :: Type -> Text -> Ghc (Maybe ScriptCompilationError)
199231typeCheckScript expectedType inp = do
200− dflags <- getSessionDynFlags
232+ dflags <- getSessionDynFlags
201233 --catch exception for SyntaxError
202234#if __GLASGOW_HASKELL__ >= 802
203− funcType <- GHC.exprType TM_Inst (unpack inp)
204−#else
235+ funcType <- GHC.exprType TM_Inst (unpack inp)
236+#else
205237 funcType <- GHC.exprType (unpack inp)
206238#endif
207− --liftIO $ putStrLn $ showType dflags expectedType ++ ":::" ++ showType dflags funcType
239+ --liftIO $ putStrLn $ showType dflags expectedType ++ ":::" ++ showType dflags funcType
208240 if eqType funcType expectedType then
209241 pure Nothing
210242 else
211243 pure (Just (TypeCheckCompilationError (showType dflags expectedType) (showType dflags funcType)))
212−
244+
213245mangleSymbol :: Maybe String -> String -> String -> String
214246mangleSymbol pkg module' valsym =
215247 prefixUnderscore ++
216248 maybe "" (\p -> zEncodeString p ++ "_") pkg ++
217249 zEncodeString module' ++ "_" ++ zEncodeString valsym ++ "_closure"
218−
219−type ModName = String
220−type FuncName = String
221−
222−data LoadSymbolError = LoadSymbolError
223250
224251loadFunction :: ModName -> FuncName -> FilePath -> IO (Either LoadSymbolError a)
225252loadFunction modName funcName objPath = do
226−#if __GLASGOW_HASKELL__ >= 802
253+#if __GLASGOW_HASKELL__ >= 802
227254 initObjLinker RetainCAFs
228255#else
229256 initObjLinker
@@ -235,8 +262,8 @@ loadFunction modName funcName objPath = do
235262 Nothing -> pure (Left LoadSymbolError)
236263 Just (Ptr addr) -> case addrToAny# addr of
237264 (# hval #) -> pure (Right hval)
238−
239−prefixUnderscore :: String
265+
266+prefixUnderscore :: String
240267prefixUnderscore =
241268 case (os,arch) of
242269 ("mingw32","x86_64") -> ""
@@ -244,4 +271,5 @@ prefixUnderscore =
244271 ("mingw32",_) -> "_"
245272 ("darwin",_) -> "_"
246273 ("cygwin",_) -> "_"
247− _ -> ""
274+ _ -> ""
275+#endif
src/lib/ProjectM36/Serialise/AtomFunctionError.hsnew file+7
@@ -0,0 +1,7 @@
1+{-# LANGUAGE DerivingVia, StandaloneDeriving #-}
2+{-# OPTIONS_GHC -fno-warn-orphans #-}
3+module ProjectM36.Serialise.AtomFunctionError where
4+import Codec.Winery
5+import ProjectM36.AtomFunctionError
6+
7+deriving via WineryVariant AtomFunctionError instance Serialise AtomFunctionError
src/lib/ProjectM36/Serialise/Base.hsnew file+85
@@ -0,0 +1,85 @@
1+{-# LANGUAGE StandaloneDeriving, DerivingVia, TypeApplications, TypeSynonymInstances, ScopedTypeVariables #-}
2+{-# OPTIONS_GHC -fno-warn-orphans #-}
3+--Serialise instances for ProjectM36.Base data types- orphan instance city
4+module ProjectM36.Serialise.Base where
5+import Codec.Winery hiding (Schema)
6+import Codec.Winery.Internal
7+import Control.Monad
8+import ProjectM36.Base
9+import ProjectM36.MerkleHash
10+import Data.UUID
11+import Data.Proxy
12+import Data.Word
13+import ProjectM36.Attribute as A
14+import qualified Data.List.NonEmpty as NE
15+import qualified Data.Vector as V
16+import Data.Time.Calendar (Day,toGregorian,fromGregorian)
17+
18+deriving via WineryVariant Atom instance Serialise Atom
19+deriving via WineryVariant AtomType instance Serialise AtomType
20+deriving via WineryVariant Attribute instance Serialise Attribute
21+deriving via WineryVariant RelationTupleSet instance Serialise RelationTupleSet
22+deriving via WineryVariant RelationTuple instance Serialise RelationTuple
23+deriving via WineryVariant Relation instance Serialise Relation
24+deriving via WineryVariant RelationCardinality instance Serialise RelationCardinality
25+deriving via WineryVariant (RelationalExprBase a) instance Serialise a => Serialise (RelationalExprBase a)
26+deriving via WineryVariant (WithNameExprBase a) instance Serialise a => Serialise (WithNameExprBase a)
27+deriving via WineryVariant Notification instance Serialise Notification
28+deriving via WineryVariant TypeConstructorDef instance Serialise TypeConstructorDef
29+deriving via WineryVariant (TypeConstructorBase a) instance Serialise a => Serialise (TypeConstructorBase a)
30+deriving via WineryVariant DataConstructorDef instance Serialise DataConstructorDef
31+deriving via WineryVariant DataConstructorDefArg instance Serialise DataConstructorDefArg
32+deriving via WineryVariant GraphRefTransactionMarker instance Serialise GraphRefTransactionMarker
33+deriving via WineryVariant SchemaIsomorph instance Serialise SchemaIsomorph
34+deriving via WineryVariant InclusionDependency instance Serialise InclusionDependency
35+deriving via WineryVariant (DatabaseContextExprBase a) instance Serialise a => Serialise (DatabaseContextExprBase a)
36+deriving via WineryVariant (DatabaseContextIOExprBase a) instance Serialise a => Serialise (DatabaseContextIOExprBase a)
37+deriving via WineryVariant (RestrictionPredicateExprBase a) instance Serialise a => Serialise (RestrictionPredicateExprBase a)
38+deriving via WineryVariant TransactionInfo instance Serialise TransactionInfo
39+deriving via WineryVariant (AtomExprBase a) instance Serialise a => Serialise (AtomExprBase a)
40+deriving via WineryVariant MerkleHash instance Serialise MerkleHash
41+deriving via WineryVariant (AttributeExprBase a) instance Serialise a => Serialise (AttributeExprBase a)
42+deriving via WineryVariant (TupleExprsBase a) instance Serialise a => Serialise (TupleExprsBase a)
43+deriving via WineryVariant (TupleExprBase a) instance Serialise a => Serialise (TupleExprBase a)
44+deriving via WineryVariant (AttributeNamesBase a) instance Serialise a => Serialise (AttributeNamesBase a)
45+deriving via WineryVariant (ExtendTupleExprBase a) instance Serialise a => Serialise (ExtendTupleExprBase a)
46+deriving via WineryVariant Schema instance Serialise Schema
47+deriving via WineryVariant MergeStrategy instance Serialise MergeStrategy
48+
49+fromWordsTup :: (Word32, Word32, Word32, Word32) -> TransactionId
50+fromWordsTup (a,b,c,d) = fromWords a b c d
51+
52+instance Serialise TransactionId where
53+ schemaGen _ = getSchema (Proxy @(Word32, Word32, Word32, Word32))
54+ toBuilder uuid = toBuilder (toWords uuid)
55+ extractor = fromWordsTup <$> extractor
56+ decodeCurrent = fromWordsTup <$> decodeCurrent
57+
58+instance Serialise a => Serialise (NE.NonEmpty a) where
59+ schemaGen _ = SVector <$> getSchema (Proxy @a)
60+ toBuilder xs = varInt (length xs) <> foldMap toBuilder xs
61+ extractor = NE.fromList . V.toList <$> extractListBy extractor --use nonempty instead to replace error with winery error
62+ decodeCurrent = do
63+ n <- decodeVarInt
64+ l <- replicateM n decodeCurrent
65+ pure (NE.fromList l)
66+
67+fromGregorianTup :: (Integer, Int, Int) -> Day
68+fromGregorianTup (a, b, c) = fromGregorian a b c
69+
70+instance Serialise Day where
71+ schemaGen _ = getSchema (Proxy @(Integer, Int, Int))
72+ toBuilder day = toBuilder (toGregorian day)
73+ extractor = fromGregorianTup <$> extractor
74+ decodeCurrent = fromGregorianTup <$> decodeCurrent
75+
76+instance Serialise Attributes where
77+ schemaGen _ = SVector <$> getSchema (Proxy @Attribute)
78+ toBuilder attrs = varInt (V.length (attributesVec attrs)) <> foldMap toBuilder (V.toList (attributesVec attrs))
79+ extractor =
80+ attributesFromList . V.toList <$> extractListBy extractor
81+
82+ decodeCurrent = do
83+ n <- decodeVarInt
84+ l <- replicateM n decodeCurrent
85+ pure (A.attributesFromList l)
src/lib/ProjectM36/Serialise/DataFrame.hsnew file+13
@@ -0,0 +1,13 @@
1+{-# LANGUAGE DerivingVia, StandaloneDeriving #-}
2+{-# OPTIONS_GHC -fno-warn-orphans #-}
3+module ProjectM36.Serialise.DataFrame where
4+import Codec.Winery
5+import ProjectM36.DataFrame
6+import ProjectM36.Serialise.Base ()
7+
8+deriving via WineryVariant AttributeOrderExpr instance Serialise AttributeOrderExpr
9+deriving via WineryVariant AttributeOrder instance Serialise AttributeOrder
10+deriving via WineryVariant Order instance Serialise Order
11+deriving via WineryRecord DataFrame instance Serialise DataFrame
12+deriving via WineryVariant DataFrameTuple instance Serialise DataFrameTuple
13+deriving via WineryRecord DataFrameExpr instance Serialise DataFrameExpr
src/lib/ProjectM36/Serialise/DatabaseContextFunctionError.hsnew file+7
@@ -0,0 +1,7 @@
1+{-# LANGUAGE DerivingVia, StandaloneDeriving #-}
2+{-# OPTIONS_GHC -fno-warn-orphans #-}
3+module ProjectM36.Serialise.DatabaseContextFunctionError where
4+import Codec.Winery
5+import ProjectM36.DatabaseContextFunctionError
6+
7+deriving via WineryVariant DatabaseContextFunctionError instance Serialise DatabaseContextFunctionError
src/lib/ProjectM36/Serialise/Error.hsnew file+15
@@ -0,0 +1,15 @@
1+{-# LANGUAGE DerivingVia, StandaloneDeriving #-}
2+{-# OPTIONS_GHC -fno-warn-orphans #-}
3+module ProjectM36.Serialise.Error where
4+import ProjectM36.Error
5+import Codec.Winery
6+import ProjectM36.Serialise.Base ()
7+import ProjectM36.Serialise.AtomFunctionError ()
8+import ProjectM36.Serialise.DatabaseContextFunctionError ()
9+
10+deriving via WineryVariant RelationalError instance Serialise RelationalError
11+deriving via WineryVariant MergeError instance Serialise MergeError
12+deriving via WineryVariant ScriptCompilationError instance Serialise ScriptCompilationError
13+deriving via WineryVariant PersistenceError instance Serialise PersistenceError
14+deriving via WineryVariant SchemaError instance Serialise SchemaError
15+deriving via WineryVariant ImportError' instance Serialise ImportError'
src/lib/ProjectM36/Serialise/IsomorphicSchema.hsnew file+7
@@ -0,0 +1,7 @@
1+{-# LANGUAGE StandaloneDeriving, DerivingVia, TypeSynonymInstances, ScopedTypeVariables #-}
2+{-# OPTIONS_GHC -fno-warn-orphans #-}
3+module ProjectM36.Serialise.IsomorphicSchema where
4+import Codec.Winery
5+import ProjectM36.IsomorphicSchema
6+
7+deriving via WineryVariant SchemaExpr instance Serialise SchemaExpr
src/lib/ProjectM36/Serialise/MergeError.hsnew file+1
@@ -0,0 +1 @@
1+
src/lib/ProjectM36/Server.hs+166−88
@@ -7,76 +7,119 @@ import ProjectM36.Server.RemoteCallTypes
77import ProjectM36.Server.Config (ServerConfig(..))
88import ProjectM36.FSType
99
10−import Control.Monad.IO.Class (liftIO)
11−import Network.Transport.TCP (createTransport, defaultTCPParameters)
12−import Network.Transport (EndPointAddress(..), newEndPoint, address)
13−import Control.Distributed.Process.Node (initRemoteTable, runProcess, newLocalNode, initRemoteTable)
14−import Control.Distributed.Process.Extras.Time (Delay(..))
15−import Control.Distributed.Process (Process, register, getSelfPid)
16−import Control.Distributed.Process.ManagedProcess (defaultProcess, UnhandledMessagePolicy(..), ProcessDefinition(..), handleCall, serve, InitHandler, InitResult(..))
17−import Control.Concurrent.MVar (putMVar, MVar)
10+import Control.Concurrent.MVar (MVar)
1811import System.IO (stderr, hPutStrLn)
1912import System.FilePath (takeDirectory)
2013import System.Directory (doesDirectoryExist)
14+import Network.RPC.Curryer.Server
15+import Network.Socket
16+import qualified StmContainers.Map as StmMap
17+import Control.Concurrent.STM
2118
22−-- the state should be a mapping of remote connection to the disconnected transaction- the graph should be the same, so discon must be removed from the stm tuple
23−--trying to refactor this for less repetition is very challenging because the return type cannot be polymorphic or the distributed-process call gets confused and drops messages
24−serverDefinition :: Bool -> Timeout -> ProcessDefinition Connection
25−serverDefinition testBool ti = defaultProcess {
26− apiHandlers = [
27− handleCall (\conn (ExecuteHeadName sessionId) -> handleExecuteHeadName ti sessionId conn),
28− handleCall (\conn (ExecuteRelationalExpr sessionId expr) -> handleExecuteRelationalExpr ti sessionId conn expr),
29− handleCall (\conn (ExecuteDataFrameExpr sessionId expr) -> handleExecuteDataFrameExpr ti sessionId conn expr),
30− handleCall (\conn (ExecuteDatabaseContextExpr sessionId expr) -> handleExecuteDatabaseContextExpr ti sessionId conn expr),
31− handleCall (\conn (ExecuteDatabaseContextIOExpr sessionId expr) -> handleExecuteDatabaseContextIOExpr ti sessionId conn expr),
32− handleCall (\conn (ExecuteGraphExpr sessionId expr) -> handleExecuteGraphExpr ti sessionId conn expr),
33− handleCall (\conn (ExecuteTransGraphRelationalExpr sessionId expr) -> handleExecuteTransGraphRelationalExpr ti sessionId conn expr),
34− handleCall (\conn (ExecuteTypeForRelationalExpr sessionId expr) -> handleExecuteTypeForRelationalExpr ti sessionId conn expr),
35− handleCall (\conn (RetrieveInclusionDependencies sessionId) -> handleRetrieveInclusionDependencies ti sessionId conn),
36− handleCall (\conn (RetrievePlanForDatabaseContextExpr sessionId dbExpr) -> handleRetrievePlanForDatabaseContextExpr ti sessionId conn dbExpr),
37− handleCall (\conn (RetrieveHeadTransactionId sessionId) -> handleRetrieveHeadTransactionId ti sessionId conn),
38− handleCall (\conn (RetrieveTransactionGraph sessionId) -> handleRetrieveTransactionGraph ti sessionId conn),
39− handleCall (\conn (Login procId) -> handleLogin ti conn procId),
40− handleCall (\conn (CreateSessionAtHead headn) -> handleCreateSessionAtHead ti conn headn),
41− handleCall (\conn (CreateSessionAtCommit commitId) -> handleCreateSessionAtCommit ti conn commitId),
42− handleCall (\conn (CloseSession sessionId) -> handleCloseSession ti sessionId conn),
43− handleCall (\conn (RetrieveAtomTypesAsRelation sessionId) -> handleRetrieveAtomTypesAsRelation ti sessionId conn),
44− handleCall (\conn (RetrieveRelationVariableSummary sessionId) -> handleRetrieveRelationVariableSummary ti sessionId conn),
45− handleCall (\conn (RetrieveAtomFunctionSummary sessionId) -> handleRetrieveAtomFunctionSummary ti sessionId conn),
46− handleCall (\conn (RetrieveDatabaseContextFunctionSummary sessionId) -> handleRetrieveDatabaseContextFunctionSummary ti sessionId conn),
47− handleCall (\conn (RetrieveCurrentSchemaName sessionId) -> handleRetrieveCurrentSchemaName ti sessionId conn),
48− handleCall (\conn (ExecuteSchemaExpr sessionId schemaExpr) -> handleExecuteSchemaExpr ti sessionId conn schemaExpr),
49− handleCall (\conn (RetrieveSessionIsDirty sessionId) -> handleRetrieveSessionIsDirty ti sessionId conn),
50− handleCall (\conn (ExecuteAutoMergeToHead sessionId strat headName') -> handleExecuteAutoMergeToHead ti sessionId conn strat headName'),
51− handleCall (\conn (RetrieveTypeConstructorMapping sessionId) -> handleRetrieveTypeConstructorMapping ti sessionId conn),
52− handleCall (\conn Logout -> handleLogout ti conn)
53− ] ++ testModeHandlers,
54− unhandledMessagePolicy = Terminate
55− --unhandledMessagePolicy = Log
56− }
57− where
58− testModeHandlers = if not testBool then
59− []
60− else
61− [handleCall (\conn (TestTimeout sessionId) -> handleTestTimeout ti sessionId conn)]
62−
63−
64−initServer :: InitHandler (Connection, DatabaseName, Maybe (MVar EndPointAddress), EndPointAddress) Connection
65−initServer (conn, dbname, mAddressMVar, saddress) = do
66− registerDB dbname
67− case mAddressMVar of
68− Nothing -> pure ()
69− Just addressMVar -> liftIO $ putMVar addressMVar saddress
70− --traceShowM ("server started on " ++ show saddress)
71− pure $ InitOk conn Infinity
19+type TestMode = Bool
7220
73−registerDB :: DatabaseName -> Process ()
74−registerDB dbname = do
75− self <- getSelfPid
76− let dbname' = remoteDBLookupName dbname
77− register dbname' self
78− --liftIO $ putStrLn $ "registered " ++ (show self) ++ " " ++ dbname'
79−
21+requestHandlers :: TestMode -> Maybe Timeout -> RequestHandlers ServerState
22+requestHandlers testFlag ti =
23+ [
24+ RequestHandler (\sState (Login dbName) -> do
25+ addClientLogin dbName sState
26+ conn <- getConn sState
27+ handleLogin conn (connectionSocket sState)),
28+ RequestHandler (\sState Logout -> do
29+ conn <- getConn sState
30+ handleLogout ti conn),
31+ RequestHandler $ \sState (ExecuteHeadName sessionId) -> do
32+ --socket -> dbname --maybe create a socket->client state mapping in the server state, too
33+ conn <- getConn sState
34+ handleExecuteHeadName ti sessionId conn,
35+ RequestHandler (\sState (ExecuteRelationalExpr sessionId expr) -> do
36+ conn <- getConn sState
37+ handleExecuteRelationalExpr ti sessionId conn expr),
38+ RequestHandler (\sState (ExecuteDataFrameExpr sessionId expr) -> do
39+ conn <- getConn sState
40+ handleExecuteDataFrameExpr ti sessionId conn expr),
41+ RequestHandler (\sState (ExecuteDatabaseContextExpr sessionId expr) -> do
42+ conn <- getConn sState
43+ handleExecuteDatabaseContextExpr ti sessionId conn expr),
44+ RequestHandler (\sState (ExecuteDatabaseContextIOExpr sessionId expr) -> do
45+ conn <- getConn sState
46+ handleExecuteDatabaseContextIOExpr ti sessionId conn expr),
47+ RequestHandler (\sState (ExecuteGraphExpr sessionId expr) -> do
48+ conn <- getConn sState
49+ handleExecuteGraphExpr ti sessionId conn expr),
50+ RequestHandler (\sState (ExecuteTransGraphRelationalExpr sessionId expr) -> do
51+ conn <- getConn sState
52+ handleExecuteTransGraphRelationalExpr ti sessionId conn expr),
53+ RequestHandler (\sState (ExecuteTypeForRelationalExpr sessionId expr) -> do
54+ conn <- getConn sState
55+ handleExecuteTypeForRelationalExpr ti sessionId conn expr),
56+ RequestHandler (\sState (RetrieveInclusionDependencies sessionId) -> do
57+ conn <- getConn sState
58+ handleRetrieveInclusionDependencies ti sessionId conn),
59+ RequestHandler (\sState (RetrievePlanForDatabaseContextExpr sessionId dbExpr) -> do
60+ conn <- getConn sState
61+ handleRetrievePlanForDatabaseContextExpr ti sessionId conn dbExpr),
62+ RequestHandler (\sState (RetrieveHeadTransactionId sessionId) -> do
63+ conn <- getConn sState
64+ handleRetrieveHeadTransactionId ti sessionId conn),
65+ RequestHandler (\sState (RetrieveTransactionGraph sessionId) -> do
66+ conn <- getConn sState
67+ handleRetrieveTransactionGraph ti sessionId conn),
68+ RequestHandler (\sState (CreateSessionAtHead headn) -> do
69+ conn <- getConn sState
70+ handleCreateSessionAtHead ti conn headn),
71+ RequestHandler (\sState (CreateSessionAtCommit commitId) -> do
72+ conn <- getConn sState
73+ handleCreateSessionAtCommit ti conn commitId),
74+ RequestHandler (\sState (CloseSession sessionId) -> do
75+ conn <- getConn sState
76+ handleCloseSession sessionId conn),
77+ RequestHandler (\sState (RetrieveAtomTypesAsRelation sessionId) -> do
78+ conn <- getConn sState
79+ handleRetrieveAtomTypesAsRelation ti sessionId conn),
80+ RequestHandler (\sState (RetrieveRelationVariableSummary sessionId) -> do
81+ conn <- getConn sState
82+ handleRetrieveRelationVariableSummary ti sessionId conn),
83+ RequestHandler (\sState (RetrieveAtomFunctionSummary sessionId) -> do
84+ conn <- getConn sState
85+ handleRetrieveAtomFunctionSummary ti sessionId conn),
86+ RequestHandler (\sState (RetrieveDatabaseContextFunctionSummary sessionId) -> do
87+ conn <- getConn sState
88+ handleRetrieveDatabaseContextFunctionSummary ti sessionId conn), RequestHandler (\sState (RetrieveCurrentSchemaName sessionId) -> do
89+ conn <- getConn sState
90+ handleRetrieveCurrentSchemaName ti sessionId conn),
91+ RequestHandler (\sState (ExecuteSchemaExpr sessionId schemaExpr) -> do
92+ conn <- getConn sState
93+ handleExecuteSchemaExpr ti sessionId conn schemaExpr),
94+ RequestHandler (\sState (RetrieveSessionIsDirty sessionId) -> do
95+ conn <- getConn sState
96+ handleRetrieveSessionIsDirty ti sessionId conn),
97+ RequestHandler (\sState (ExecuteAutoMergeToHead sessionId strat headName') -> do
98+ conn <- getConn sState
99+ handleExecuteAutoMergeToHead ti sessionId conn strat headName'),
100+ RequestHandler (\sState (RetrieveTypeConstructorMapping sessionId) -> do
101+ conn <- getConn sState
102+ handleRetrieveTypeConstructorMapping ti sessionId conn),
103+ RequestHandler (\sState (ExecuteValidateMerkleHashes sessionId) -> do
104+ conn <- getConn sState
105+ handleValidateMerkleHashes ti sessionId conn)
106+ ] ++ if testFlag then testModeHandlers ti else []
107+
108+getConn :: ConnectionState ServerState -> IO Connection
109+getConn connState = do
110+ let sock = lockless (connectionSocket connState)
111+ sState = connectionServerState connState
112+ mConn <- connectionForClient sock sState
113+ case mConn of
114+ Nothing -> error "failed to find socket in client map"
115+ Just conn -> pure conn
116+
117+testModeHandlers :: Maybe Timeout -> RequestHandlers ServerState
118+testModeHandlers ti = [RequestHandler (\sState (TestTimeout sessionId) -> do
119+ conn <- getConn sState
120+ handleTestTimeout ti sessionId conn)]
121+
122+
80123-- | A notification callback which logs the notification to stderr and does nothing else.
81124loggingNotificationCallback :: NotificationCallback
82125loggingNotificationCallback notName evaldNot = hPutStrLn stderr $ "Notification received \"" ++ show notName ++ "\": " ++ show evaldNot
@@ -101,9 +144,47 @@ checkFSType performCheck strat =
101144checkFSErrorMsg :: String
102145checkFSErrorMsg = "The filesystem does not support journaling so writes may not be crash-safe. Use --disable-fscheck to disable this fatal error."
103146
147+-- Sockets do not implement hashable, so we just use their string values as keys
148+type SocketString = String
149+
150+data ServerState =
151+ ServerState {
152+ --map available databases to local database configurations
153+ stateDBMap :: StmMap.Map DatabaseName Connection,
154+ --map clients to database names- after logging in, clients are afixed to specific database names
155+ stateClientMap :: StmMap.Map SocketString DatabaseName
156+ }
157+
158+-- add a client socket to the database mapping
159+addClientLogin :: DatabaseName -> ConnectionState ServerState -> IO ()
160+addClientLogin dbName cState = do
161+ let clientMap = stateClientMap (connectionServerState cState)
162+ sock = lockless (connectionSocket cState)
163+ atomically $ do
164+ mVal <- StmMap.lookup (show sock) clientMap
165+ case mVal of
166+ Nothing -> StmMap.insert dbName (show sock) clientMap
167+ Just _ -> pure () --TODO: throw exception- user already logged in
168+
169+connectionForClient :: Socket -> ServerState -> IO (Maybe Connection)
170+connectionForClient sock sState =
171+ atomically $ do
172+ mdbname <- StmMap.lookup (show sock) (stateClientMap sState)
173+ case mdbname of
174+ Nothing -> pure Nothing
175+ Just dbname ->
176+ StmMap.lookup dbname (stateDBMap sState)
177+
178+initialServerState :: DatabaseName -> Connection -> IO ServerState
179+initialServerState dbName conn =
180+ atomically $ do
181+ dbmap <- StmMap.new
182+ clientMap <- StmMap.new
183+ StmMap.insert conn dbName dbmap
184+ pure (ServerState { stateDBMap = dbmap, stateClientMap = clientMap })
104185-- | A synchronous function to start the project-m36 daemon given an appropriate 'ServerConfig'. Note that this function only returns if the server exits. Returns False if the daemon exited due to an error. If the second argument is not Nothing, the port is put after the server is ready to service the port.
105−launchServer :: ServerConfig -> Maybe (MVar EndPointAddress) -> IO Bool
106−launchServer daemonConfig mAddressMVar = do
186+launchServer :: ServerConfig -> Maybe (MVar SockAddr) -> IO Bool
187+launchServer daemonConfig mAddr = do
107188 checkFSResult <- checkFSType (checkFS daemonConfig) (persistenceStrategy daemonConfig)
108189 if not checkFSResult then do
109190 hPutStrLn stderr checkFSErrorMsg
@@ -116,24 +197,21 @@ launchServer daemonConfig mAddressMVar = do
116197 pure False
117198 Right conn -> do
118199 let hostname = bindHost daemonConfig
119− port = bindPort daemonConfig
120−#if MIN_VERSION_network_transport_tcp(0,6,0)
121− etransport <- createTransport hostname (show port) (\nam -> (hostname, nam)) defaultTCPParameters
122−#else
123− etransport <- createTransport hostname (show port) defaultTCPParameters
124−#endif
125− case etransport of
126− Left err -> error ("failed to create transport: " ++ show err)
127− Right transport -> do
128− eEndpoint <- newEndPoint transport
129− case eEndpoint of
130− Left err -> hPutStrLn stderr ("Failed to create transport: " ++ show err) >> pure False
131− Right endpoint -> do
132− localTCPNode <- newLocalNode transport initRemoteTable
133− --traceShowM ("newLocalNode in Server " ++ show (localNodeId localTCPNode))
134− runProcess localTCPNode $ do
135− let testBool = testMode daemonConfig
136− reqTimeout = perRequestTimeout daemonConfig
137− serve (conn, databaseName daemonConfig, mAddressMVar, address endpoint) initServer (serverDefinition testBool reqTimeout)
138− liftIO $ putStrLn "serve returned"
139− pure True
200+ port = fromIntegral (bindPort daemonConfig)
201+
202+
203+ --curryer only supports IPv4 for now
204+ let addrHints = defaultHints { addrSocketType = Stream, addrFamily = AF_INET }
205+ hostAddrs <- getAddrInfo (Just addrHints) (Just hostname) Nothing
206+ case hostAddrs of
207+ [] -> hPutStrLn stderr ("Failed to resolve: " <> hostname) >> pure False
208+ (AddrInfo _ _ _ _ (SockAddrInet _ addr32) _):_ -> do
209+ let hostAddr = hostAddressToTuple addr32
210+ mTimeout = fromIntegral <$> case perRequestTimeout daemonConfig of
211+ 0 -> Nothing
212+ v -> Just v
213+
214+ sState <- initialServerState (databaseName daemonConfig) conn
215+ serve (requestHandlers (testMode daemonConfig) mTimeout) sState hostAddr port mAddr
216+ _ -> error "unsupported socket addressing mode (IPv4 only currently)"
217+
src/lib/ProjectM36/Server/Config.hs+6
@@ -12,6 +12,12 @@ data ServerConfig = ServerConfig { persistenceStrategy :: PersistenceStrategy,
1212 }
1313 deriving (Show)
1414
15+data WebsocketServerConfig = WebsocketServerConfig { wsServerConfig :: ServerConfig,
16+ tlsCertificatePath :: Maybe String,
17+ tlsKeyPath :: Maybe String
18+ }
19+ deriving (Show)
20+
1521defaultServerConfig :: ServerConfig
1622defaultServerConfig = ServerConfig { persistenceStrategy = NoPersistence,
1723 checkFS = True,
src/lib/ProjectM36/Server/EntryPoints.hs+126−153
@@ -1,173 +1,146 @@
1+{-# LANGUAGE MonoLocalBinds #-}
12module ProjectM36.Server.EntryPoints where
23import ProjectM36.Base hiding (inclusionDependencies)
34import ProjectM36.IsomorphicSchema
45import ProjectM36.Client as C
5−import ProjectM36.Error
6−import ProjectM36.DataFrame
7−import Control.Distributed.Process (Process, ProcessId)
8−import Control.Distributed.Process.ManagedProcess (ProcessReply)
9−import Control.Distributed.Process.ManagedProcess.Server (reply)
10−import Control.Distributed.Process.Async (async, task, waitCancelTimeout, AsyncResult(..))
11−import Control.Distributed.Process.Serializable (Serializable)
12−import Control.Monad.IO.Class (liftIO)
136import Data.Map
147import Control.Concurrent (threadDelay)
8+import Network.RPC.Curryer.Server
9+import System.Timeout hiding (Timeout)
10+import Network.Socket
11+import Control.Exception
1512
16−timeoutOrDie :: Serializable a => Timeout -> IO a -> Process (Either ServerError a)
17−timeoutOrDie micros act =
18− if micros == 0 then
19− liftIO act >>= \x -> pure (Right x)
20− else do
21− asyncUnit <- async (task (liftIO act))
22− asyncRes <- waitCancelTimeout micros asyncUnit
23− case asyncRes of
24− AsyncDone x -> pure (Right x)
25− AsyncCancelled -> pure (Left RequestTimeoutError)
26− AsyncFailed reason -> pure (Left (ProcessDiedError (show reason)))
27− AsyncLinkFailed reason -> pure (Left (ProcessDiedError (show reason)))
28− AsyncPending -> pure (Left (ProcessDiedError "process pending"))
29−
30−type Timeout = Int
31−
32−type Reply a = Process (ProcessReply (Either ServerError a) Connection)
33−
34−handleExecuteRelationalExpr :: Timeout -> SessionId -> Connection -> RelationalExpr -> Reply (Either RelationalError Relation)
35−handleExecuteRelationalExpr ti sessionId conn expr = do
36− ret <- timeoutOrDie ti (executeRelationalExpr sessionId conn expr)
37− reply ret conn
13+timeoutOrDie :: Maybe Timeout -> IO a -> IO (Maybe a)
14+timeoutOrDie mMicros act =
15+ case mMicros of
16+ Nothing -> Just <$> act
17+ Just micros ->
18+ timeout (fromIntegral micros) act
3819
39−handleExecuteDataFrameExpr :: Timeout -> SessionId -> Connection -> DataFrameExpr -> Reply (Either RelationalError DataFrame)
40−handleExecuteDataFrameExpr ti sessionId conn expr = do
41− ret <- timeoutOrDie ti (executeDataFrameExpr sessionId conn expr)
42− reply ret conn
43−
44−handleExecuteDatabaseContextExpr :: Timeout -> SessionId -> Connection -> DatabaseContextExpr -> Reply (Either RelationalError ())
45−handleExecuteDatabaseContextExpr ti sessionId conn dbexpr = do
46− ret <- timeoutOrDie ti (executeDatabaseContextExpr sessionId conn dbexpr)
47− reply ret conn
48−
49−handleExecuteDatabaseContextIOExpr :: Timeout -> SessionId -> Connection -> DatabaseContextIOExpr -> Reply (Either RelationalError ())
50−handleExecuteDatabaseContextIOExpr ti sessionId conn dbexpr = do
51− ret <- timeoutOrDie ti (executeDatabaseContextIOExpr sessionId conn dbexpr)
52− reply ret conn
53−
54−handleExecuteHeadName :: Timeout -> SessionId -> Connection -> Reply (Either RelationalError HeadName)
55−handleExecuteHeadName ti sessionId conn = do
56− ret <- timeoutOrDie ti (headName sessionId conn)
57− reply ret conn
58−
59−handleLogin :: Timeout -> Connection -> ProcessId -> Reply Bool
60−handleLogin ti conn newClientProcessId = do
61− ret <- timeoutOrDie ti (addClientNode conn newClientProcessId)
20+timeoutRelErr :: Maybe Timeout -> IO (Either RelationalError a) -> IO (Either RelationalError a)
21+timeoutRelErr mMicros act = do
22+ ret <- timeoutOrDie mMicros act
6223 case ret of
63− Right () -> reply (Right True) conn
64− Left err -> reply (Left err) conn
65−
66−handleExecuteGraphExpr :: Timeout -> SessionId -> Connection -> TransactionGraphOperator -> Reply (Either RelationalError ())
67−handleExecuteGraphExpr ti sessionId conn graphExpr = do
68− ret <- timeoutOrDie ti (executeGraphExpr sessionId conn graphExpr)
69− reply ret conn
70−
71−handleExecuteTransGraphRelationalExpr :: Timeout -> SessionId -> Connection -> TransGraphRelationalExpr -> Reply (Either RelationalError Relation)
72−handleExecuteTransGraphRelationalExpr ti sessionId conn graphExpr = do
73− ret <- timeoutOrDie ti (executeTransGraphRelationalExpr sessionId conn graphExpr)
74− reply ret conn
24+ Nothing -> throw TimeoutException
25+ Just v -> pure v
26+
7527
76−handleExecuteTypeForRelationalExpr :: Timeout -> SessionId -> Connection -> RelationalExpr -> Reply (Either RelationalError Relation)
77−handleExecuteTypeForRelationalExpr ti sessionId conn relExpr = do
78− ret <- timeoutOrDie ti (typeForRelationalExpr sessionId conn relExpr)
79− reply ret conn
80−
81−handleRetrieveInclusionDependencies :: Timeout -> SessionId -> Connection -> Reply (Either RelationalError (Map IncDepName InclusionDependency))
82−handleRetrieveInclusionDependencies ti sessionId conn = do
83− ret <- timeoutOrDie ti (inclusionDependencies sessionId conn)
84− reply ret conn
85−
86−handleRetrievePlanForDatabaseContextExpr :: Timeout -> SessionId -> Connection -> DatabaseContextExpr -> Reply (Either RelationalError DatabaseContextExpr)
87−handleRetrievePlanForDatabaseContextExpr ti sessionId conn dbExpr = do
88− ret <- timeoutOrDie ti (planForDatabaseContextExpr sessionId conn dbExpr)
89− reply ret conn
90−
91−handleRetrieveTransactionGraph :: Timeout -> SessionId -> Connection -> Reply (Either RelationalError Relation)
92−handleRetrieveTransactionGraph ti sessionId conn = do
93− ret <- timeoutOrDie ti (transactionGraphAsRelation sessionId conn)
94− reply ret conn
95−
96−handleRetrieveHeadTransactionId :: Timeout -> SessionId -> Connection -> Reply (Either RelationalError TransactionId)
97−handleRetrieveHeadTransactionId ti sessionId conn = do
98− ret <- timeoutOrDie ti (headTransactionId sessionId conn)
99− reply ret conn
100−
101−handleCreateSessionAtCommit :: Timeout -> Connection -> TransactionId -> Reply (Either RelationalError SessionId)
102−handleCreateSessionAtCommit ti conn commitId = do
103− ret <- timeoutOrDie ti (createSessionAtCommit conn commitId)
104− reply ret conn
105−
106−handleCreateSessionAtHead :: Timeout -> Connection -> HeadName -> Reply (Either RelationalError SessionId)
107−handleCreateSessionAtHead ti conn headn = do
108− ret <- timeoutOrDie ti (createSessionAtHead conn headn)
109− reply ret conn
110−
111−handleCloseSession :: Timeout -> SessionId -> Connection -> Reply ()
112−handleCloseSession ti sessionId conn = do
113− ret <- timeoutOrDie ti (closeSession sessionId conn)
114− case ret of
115− Right () -> reply (Right ()) conn
116− Left err -> reply (Left err) conn
28+handleExecuteRelationalExpr :: Maybe Timeout -> SessionId -> Connection -> RelationalExpr -> IO (Either RelationalError Relation)
29+handleExecuteRelationalExpr ti sessionId conn expr =
30+ timeoutRelErr ti (executeRelationalExpr sessionId conn expr)
31+
32+handleExecuteDataFrameExpr :: Maybe Timeout -> SessionId -> Connection -> DataFrameExpr -> IO (Either RelationalError DataFrame)
33+handleExecuteDataFrameExpr ti sessionId conn expr =
34+ timeoutRelErr ti (executeDataFrameExpr sessionId conn expr)
35+
36+handleExecuteDatabaseContextExpr :: Maybe Timeout -> SessionId -> Connection -> DatabaseContextExpr -> IO (Either RelationalError ())
37+handleExecuteDatabaseContextExpr ti sessionId conn dbexpr =
38+ timeoutRelErr ti (executeDatabaseContextExpr sessionId conn dbexpr)
39+
40+handleExecuteDatabaseContextIOExpr :: Maybe Timeout -> SessionId -> Connection -> DatabaseContextIOExpr -> IO (Either RelationalError ())
41+handleExecuteDatabaseContextIOExpr ti sessionId conn dbexpr =
42+ timeoutRelErr ti (executeDatabaseContextIOExpr sessionId conn dbexpr)
43+
44+handleExecuteHeadName :: Maybe Timeout -> SessionId -> Connection -> IO (Either RelationalError HeadName)
45+handleExecuteHeadName ti sessionId conn =
46+ timeoutRelErr ti (headName sessionId conn)
47+
48+handleLogin :: Connection -> Locking Socket -> IO Bool
49+handleLogin conn lockSock = do
50+ addClientNode conn lockSock
51+ pure True
52+
53+handleExecuteGraphExpr :: Maybe Timeout -> SessionId -> Connection -> TransactionGraphOperator -> IO (Either RelationalError ())
54+handleExecuteGraphExpr ti sessionId conn graphExpr =
55+ timeoutRelErr ti (executeGraphExpr sessionId conn graphExpr)
56+
57+handleExecuteTransGraphRelationalExpr :: Maybe Timeout -> SessionId -> Connection -> TransGraphRelationalExpr -> IO (Either RelationalError Relation)
58+handleExecuteTransGraphRelationalExpr ti sessionId conn graphExpr =
59+ timeoutRelErr ti (executeTransGraphRelationalExpr sessionId conn graphExpr)
60+
61+handleExecuteTypeForRelationalExpr :: Maybe Timeout -> SessionId -> Connection -> RelationalExpr -> IO (Either RelationalError Relation)
62+handleExecuteTypeForRelationalExpr ti sessionId conn relExpr =
63+ timeoutRelErr ti (typeForRelationalExpr sessionId conn relExpr)
64+
65+handleRetrieveInclusionDependencies :: Maybe Timeout -> SessionId -> Connection -> IO (Either RelationalError (Map IncDepName InclusionDependency))
66+handleRetrieveInclusionDependencies ti sessionId conn =
67+ timeoutRelErr ti (inclusionDependencies sessionId conn)
68+
69+handleRetrievePlanForDatabaseContextExpr :: Maybe Timeout -> SessionId -> Connection -> DatabaseContextExpr -> IO (Either RelationalError GraphRefDatabaseContextExpr)
70+handleRetrievePlanForDatabaseContextExpr ti sessionId conn dbExpr =
71+ timeoutRelErr ti (planForDatabaseContextExpr sessionId conn dbExpr)
72+
73+handleRetrieveTransactionGraph :: Maybe Timeout -> SessionId -> Connection -> IO (Either RelationalError Relation)
74+handleRetrieveTransactionGraph ti sessionId conn =
75+ timeoutRelErr ti (transactionGraphAsRelation sessionId conn)
76+
77+handleRetrieveHeadTransactionId :: Maybe Timeout -> SessionId -> Connection -> IO (Either RelationalError TransactionId)
78+handleRetrieveHeadTransactionId ti sessionId conn =
79+ timeoutRelErr ti (headTransactionId sessionId conn)
11780
118−handleRetrieveAtomTypesAsRelation :: Timeout -> SessionId -> Connection -> Reply (Either RelationalError Relation)
119−handleRetrieveAtomTypesAsRelation ti sessionId conn = do
120− ret <- timeoutOrDie ti (atomTypesAsRelation sessionId conn)
121− reply ret conn
81+handleCreateSessionAtCommit :: Maybe Timeout -> Connection -> TransactionId -> IO (Either RelationalError SessionId)
82+handleCreateSessionAtCommit ti conn commitId =
83+ timeoutRelErr ti (createSessionAtCommit conn commitId)
84+
85+handleCreateSessionAtHead :: Maybe Timeout -> Connection -> HeadName -> IO (Either RelationalError SessionId)
86+handleCreateSessionAtHead ti conn headn =
87+ timeoutRelErr ti (createSessionAtHead conn headn)
88+
89+handleCloseSession :: SessionId -> Connection -> IO ()
90+handleCloseSession =
91+ closeSession
92+
93+handleRetrieveAtomTypesAsRelation :: Maybe Timeout -> SessionId -> Connection -> IO (Either RelationalError Relation)
94+handleRetrieveAtomTypesAsRelation ti sessionId conn =
95+ timeoutRelErr ti (atomTypesAsRelation sessionId conn)
12296
12397-- | Returns a relation which lists the names of relvars in the current session as well as its types.
124−handleRetrieveRelationVariableSummary :: Timeout -> SessionId -> Connection -> Reply (Either RelationalError Relation)
125−handleRetrieveRelationVariableSummary ti sessionId conn = do
126− ret <- timeoutOrDie ti (relationVariablesAsRelation sessionId conn)
127− reply ret conn
128−
129−handleRetrieveAtomFunctionSummary :: Timeout -> SessionId -> Connection -> Reply (Either RelationalError Relation)
130−handleRetrieveAtomFunctionSummary ti sessionId conn = do
131− ret <- timeoutOrDie ti (atomFunctionsAsRelation sessionId conn)
132− reply ret conn
133−
134−handleRetrieveDatabaseContextFunctionSummary :: Timeout -> SessionId -> Connection -> Reply (Either RelationalError Relation)
135−handleRetrieveDatabaseContextFunctionSummary ti sessionId conn = do
136− ret <- timeoutOrDie ti (databaseContextFunctionsAsRelation sessionId conn)
137− reply ret conn
138−
139−handleRetrieveCurrentSchemaName :: Timeout -> SessionId -> Connection -> Reply (Either RelationalError SchemaName)
140−handleRetrieveCurrentSchemaName ti sessionId conn = do
141− ret <- timeoutOrDie ti (currentSchemaName sessionId conn)
142− reply ret conn
98+handleRetrieveRelationVariableSummary :: Maybe Timeout -> SessionId -> Connection -> IO (Either RelationalError Relation)
99+handleRetrieveRelationVariableSummary ti sessionId conn =
100+ timeoutRelErr ti (relationVariablesAsRelation sessionId conn)
101+
102+handleRetrieveAtomFunctionSummary :: Maybe Timeout -> SessionId -> Connection -> IO (Either RelationalError Relation)
103+handleRetrieveAtomFunctionSummary ti sessionId conn =
104+ timeoutRelErr ti (atomFunctionsAsRelation sessionId conn)
105+
106+handleRetrieveDatabaseContextFunctionSummary :: Maybe Timeout -> SessionId -> Connection -> IO (Either RelationalError Relation)
107+handleRetrieveDatabaseContextFunctionSummary ti sessionId conn =
108+ timeoutRelErr ti (databaseContextFunctionsAsRelation sessionId conn)
109+
110+handleRetrieveCurrentSchemaName :: Maybe Timeout -> SessionId -> Connection -> IO (Either RelationalError SchemaName)
111+handleRetrieveCurrentSchemaName ti sessionId conn =
112+ timeoutRelErr ti (currentSchemaName sessionId conn)
143113
144−handleExecuteSchemaExpr :: Timeout -> SessionId -> Connection -> SchemaExpr -> Reply (Either RelationalError ())
145−handleExecuteSchemaExpr ti sessionId conn schemaExpr = do
146− ret <- timeoutOrDie ti (executeSchemaExpr sessionId conn schemaExpr)
147− reply ret conn
114+handleExecuteSchemaExpr :: Maybe Timeout -> SessionId -> Connection -> SchemaExpr -> IO (Either RelationalError ())
115+handleExecuteSchemaExpr ti sessionId conn schemaExpr =
116+ timeoutRelErr ti (executeSchemaExpr sessionId conn schemaExpr)
148117
149−handleLogout :: Timeout -> Connection -> Reply Bool
150−handleLogout _ =
118+handleLogout :: Maybe Timeout -> Connection -> IO Bool
119+handleLogout _ _ =
151120 --liftIO $ closeRemote_ conn
152− reply (pure True)
121+ pure True
153122
154−handleTestTimeout :: Timeout -> SessionId -> Connection -> Reply Bool
155−handleTestTimeout ti _ conn = do
156− ret <- timeoutOrDie ti (threadDelay 100000 >> pure True)
157− reply ret conn
123+handleTestTimeout :: Maybe Timeout -> SessionId -> Connection -> IO Bool
124+handleTestTimeout ti _ _ = do
125+ ret <- timeoutRelErr ti (threadDelay 100000 >> pure (Right ()))
126+ case ret of
127+ Right () -> pure True
128+ Left _ -> pure False
158129
159−handleRetrieveSessionIsDirty :: Timeout -> SessionId -> Connection -> Reply (Either RelationalError Bool)
160−handleRetrieveSessionIsDirty ti sessionId conn = do
161− ret <- timeoutOrDie ti (disconnectedTransactionIsDirty sessionId conn)
162− reply ret conn
163−
164−handleExecuteAutoMergeToHead :: Timeout -> SessionId -> Connection -> MergeStrategy -> HeadName -> Reply (Either RelationalError ())
165−handleExecuteAutoMergeToHead ti sessionId conn strat headName' = do
166− ret <- timeoutOrDie ti (autoMergeToHead sessionId conn strat headName')
167− reply ret conn
130+
131+
132+handleRetrieveSessionIsDirty :: Maybe Timeout -> SessionId -> Connection -> IO (Either RelationalError Bool)
133+handleRetrieveSessionIsDirty ti sessionId conn =
134+ timeoutRelErr ti (disconnectedTransactionIsDirty sessionId conn)
135+
136+handleExecuteAutoMergeToHead :: Maybe Timeout -> SessionId -> Connection -> MergeStrategy -> HeadName -> IO (Either RelationalError ())
137+handleExecuteAutoMergeToHead ti sessionId conn strat headName' =
138+ timeoutRelErr ti (autoMergeToHead sessionId conn strat headName')
168139
169−handleRetrieveTypeConstructorMapping :: Timeout -> SessionId -> Connection -> Reply (Either RelationalError TypeConstructorMapping)
170−handleRetrieveTypeConstructorMapping ti sessionId conn = do
171− ret <- timeoutOrDie ti (C.typeConstructorMapping sessionId conn)
172− reply ret conn
140+handleRetrieveTypeConstructorMapping :: Maybe Timeout -> SessionId -> Connection -> IO (Either RelationalError TypeConstructorMapping)
141+handleRetrieveTypeConstructorMapping ti sessionId conn =
142+ timeoutRelErr ti (C.typeConstructorMapping sessionId conn)
173143
144+handleValidateMerkleHashes :: Maybe Timeout -> SessionId -> Connection -> IO (Either RelationalError ())
145+handleValidateMerkleHashes ti sessionId conn =
146+ timeoutRelErr ti (C.validateMerkleHashes sessionId conn)
src/lib/ProjectM36/Server/ParseArgs.hs+40−15
@@ -3,7 +3,9 @@ import ProjectM36.Base
33import ProjectM36.Client
44import Options.Applicative
55import ProjectM36.Server.Config
6+#if __GLASGOW_HASKELL__ < 804
67import Data.Monoid
8+#endif
79
810parseArgsWithDefaults :: ServerConfig -> Parser ServerConfig
911parseArgsWithDefaults defaults = ServerConfig <$>
@@ -15,14 +17,14 @@ parseArgsWithDefaults defaults = ServerConfig <$>
1517 many parseGhcPkgPath <*>
1618 parseTimeout (perRequestTimeout defaults) <*>
1719 parseTestMode
18−
20+
1921parsePersistenceStrategy :: Parser PersistenceStrategy
2022parsePersistenceStrategy = CrashSafePersistence <$> (dbdirOpt <* fsyncOpt) <|>
2123 MinimalPersistence <$> dbdirOpt <|>
2224 pure NoPersistence
23− where
24− dbdirOpt = strOption (short 'd' <>
25− long "database-directory" <>
25+ where
26+ dbdirOpt = strOption (short 'd' <>
27+ long "database-directory" <>
2628 metavar "DIRECTORY" <>
2729 showDefaultWith show
2830 )
@@ -32,46 +34,69 @@ parsePersistenceStrategy = CrashSafePersistence <$> (dbdirOpt <* fsyncOpt) <|>
3234
3335parseTestMode :: Parser Bool
3436parseTestMode = flag True False (long "test-mode" <> hidden)
35−
36−parseCheckFS :: Parser Bool
37+
38+parseCheckFS :: Parser Bool
3739parseCheckFS = flag True False (long "disable-fscheck" <>
3840 help "Disable filesystem check for journaling.")
39−
41+
4042parseDatabaseName :: Parser DatabaseName
4143parseDatabaseName = strOption (short 'n' <>
4244 long "database" <>
4345 metavar "DATABASE_NAME")
4446
45−parseHostname :: Hostname -> Parser Hostname
47+parseHostname :: Hostname -> Parser Hostname
4648parseHostname defHostname = strOption (short 'h' <>
4749 long "hostname" <>
4850 metavar "HOST_NAME" <>
4951 value defHostname)
50−
51−parsePort :: Port -> Parser Port
52+
53+parsePort :: Port -> Parser Port
5254parsePort defPort = option auto (short 'p' <>
5355 long "port" <>
5456 metavar "PORT_NUMBER" <>
5557 value defPort)
56−
58+
5759parseGhcPkgPath :: Parser String
5860parseGhcPkgPath = strOption (long "ghc-pkg-dir" <>
5961 metavar "GHC_PACKAGE_DIRECTORY")
60−
61−parseTimeout :: Int -> Parser Int
62+
63+parseTimeout :: Int -> Parser Int
6264parseTimeout defTimeout = option auto (long "timeout" <>
6365 metavar "MICROSECONDS" <>
6466 value defTimeout)
6567
6668parseConfig :: IO ServerConfig
6769parseConfig = parseConfigWithDefaults defaultServerConfig
68−
70+
6971parseConfigWithDefaults :: ServerConfig -> IO ServerConfig
7072parseConfigWithDefaults defaults = execParser (info (parseArgsWithDefaults defaults <**> helpOption) idm)
7173
74+parseWSConfigWithDefaults :: ServerConfig -> IO WebsocketServerConfig
75+parseWSConfigWithDefaults defaults = execParser (info (parseWSArgsWithDefaults defaults <**> helpOption) idm)
76+
77+parseWSArgsWithDefaults :: ServerConfig -> Parser WebsocketServerConfig
78+parseWSArgsWithDefaults defaults = WebsocketServerConfig <$>
79+ parseArgsWithDefaults defaults <*>
80+ parseTlsCertificatePath <*>
81+ parseTlsKeyPath
82+
83+
84+parseTlsCertificatePath :: Parser (Maybe String)
85+parseTlsCertificatePath = optional $ strOption (long "tls-certificate-path" <>
86+ metavar "TLS_CERTIFICATE_PATH")
87+
88+parseTlsKeyPath :: Parser (Maybe String)
89+parseTlsKeyPath = optional $ strOption (long "tls-key-path" <>
90+ metavar "TLS_KEY_PATH")
7291
7392helpOption :: Parser (a -> a)
74−helpOption = abortOption ShowHelpText $ mconcat
93+helpOption = abortOption helpText $ mconcat
7594 [ long "help"
7695 , help "Show this help text"
7796 , hidden ]
97+ where
98+#if MIN_VERSION_optparse_applicative(0,16,0)
99+ helpText = ShowHelpText Nothing
100+#else
101+ helpText = ShowHelpText
102+#endif
src/lib/ProjectM36/Server/RemoteCallTypes.hs+67−35
@@ -1,4 +1,4 @@
1−{-# LANGUAGE DeriveAnyClass, DeriveGeneric #-}
1+{-# LANGUAGE DeriveGeneric, DerivingVia, CPP #-}
22module ProjectM36.Server.RemoteCallTypes where
33import ProjectM36.Base
44import ProjectM36.IsomorphicSchema
@@ -6,66 +6,98 @@ import ProjectM36.TransactionGraph
66import ProjectM36.DataFrame
77import ProjectM36.TransGraphRelationalExpression
88import ProjectM36.Session
9+import ProjectM36.Serialise.DataFrame ()
10+import ProjectM36.Serialise.IsomorphicSchema ()
911import GHC.Generics
10−import Data.Binary
11−import Control.Distributed.Process (ProcessId)
12+import Codec.Winery
13+
14+#define RPCData(typeName) deriving Generic \
15+ deriving Serialise via WineryVariant typeName
1216
1317{-# ANN module ("HLint: ignore Use newtype instead of data" :: String) #-}
1418-- | The initial login message. The argument should be the process id of the initiating client. This ProcessId will receive notification callbacks.
15−data Login = Login ProcessId
16− deriving (Binary, Generic)
19+data Login = Login DatabaseName
20+ RPCData(Login)
1721
1822data Logout = Logout
19− deriving (Binary, Generic)
20−data ExecuteRelationalExpr = ExecuteRelationalExpr SessionId RelationalExpr
21− deriving (Binary, Generic)
23+ RPCData(Logout)
24+
25+data ExecuteRelationalExpr = ExecuteRelationalExpr SessionId RelationalExpr
26+ RPCData(ExecuteRelationalExpr)
27+
2228data ExecuteDataFrameExpr = ExecuteDataFrameExpr SessionId DataFrameExpr
23− deriving (Binary, Generic)
29+ RPCData(ExecuteDataFrameExpr)
30+
2431data ExecuteDatabaseContextExpr = ExecuteDatabaseContextExpr SessionId DatabaseContextExpr
25− deriving (Binary, Generic)
32+ RPCData(ExecuteDatabaseContextExpr)
33+
2634data ExecuteDatabaseContextIOExpr = ExecuteDatabaseContextIOExpr SessionId DatabaseContextIOExpr
27− deriving (Binary, Generic)
35+ RPCData(ExecuteDatabaseContextIOExpr)
36+
2837data ExecuteGraphExpr = ExecuteGraphExpr SessionId TransactionGraphOperator
29− deriving (Binary, Generic)
38+ RPCData(ExecuteGraphExpr)
39+
3040data ExecuteTransGraphRelationalExpr = ExecuteTransGraphRelationalExpr SessionId TransGraphRelationalExpr
31− deriving (Binary, Generic)
41+ RPCData(ExecuteTransGraphRelationalExpr)
42+
3243data ExecuteHeadName = ExecuteHeadName SessionId
33− deriving (Binary, Generic)
44+ RPCData(ExecuteHeadName)
45+
3446data ExecuteTypeForRelationalExpr = ExecuteTypeForRelationalExpr SessionId RelationalExpr
35− deriving (Binary, Generic)
36−data ExecuteSchemaExpr = ExecuteSchemaExpr SessionId SchemaExpr
37− deriving (Binary, Generic)
47+ RPCData(ExecuteTypeForRelationalExpr)
48+
49+data ExecuteSchemaExpr = ExecuteSchemaExpr SessionId SchemaExpr RPCData(ExecuteSchemaExpr)
50+
3851data ExecuteSetCurrentSchema = ExecuteSetCurrentSchema SessionId SchemaName
39− deriving (Binary, Generic)
52+ RPCData(ExecuteSetCurrentSchema)
53+
4054data RetrieveInclusionDependencies = RetrieveInclusionDependencies SessionId
41− deriving (Binary, Generic)
55+ RPCData(RetrieveInclusionDependencies)
56+
4257data RetrievePlanForDatabaseContextExpr = RetrievePlanForDatabaseContextExpr SessionId DatabaseContextExpr
43− deriving (Binary, Generic)
58+ RPCData(RetrievePlanForDatabaseContextExpr)
59+
4460data RetrieveTransactionGraph = RetrieveTransactionGraph SessionId
45− deriving (Binary, Generic)
61+ RPCData(RetrieveTransactionGraph)
62+
4663data RetrieveHeadTransactionId = RetrieveHeadTransactionId SessionId
47− deriving (Binary, Generic)
64+ RPCData(RetrieveHeadTransactionId)
65+
4866data CreateSessionAtCommit = CreateSessionAtCommit TransactionId
49− deriving (Binary, Generic)
67+ RPCData(CreateSessionAtCommit)
68+
5069data CreateSessionAtHead = CreateSessionAtHead HeadName
51− deriving (Binary, Generic)
70+ RPCData(CreateSessionAtHead)
71+
5272data CloseSession = CloseSession SessionId
53− deriving (Binary, Generic)
73+ RPCData(CloseSession)
74+
5475data RetrieveAtomTypesAsRelation = RetrieveAtomTypesAsRelation SessionId
55− deriving (Binary, Generic)
76+ RPCData(RetrieveAtomTypesAsRelation)
77+
5678data RetrieveRelationVariableSummary = RetrieveRelationVariableSummary SessionId
57− deriving (Binary, Generic)
79+ RPCData(RetrieveRelationVariableSummary)
80+
5881data RetrieveAtomFunctionSummary = RetrieveAtomFunctionSummary SessionId
59− deriving (Binary, Generic)
82+ RPCData(RetrieveAtomFunctionSummary)
83+
6084data RetrieveDatabaseContextFunctionSummary = RetrieveDatabaseContextFunctionSummary SessionId
61− deriving (Binary, Generic)
85+ RPCData(RetrieveDatabaseContextFunctionSummary)
86+
6287data RetrieveCurrentSchemaName = RetrieveCurrentSchemaName SessionId
63− deriving (Binary, Generic)
88+ RPCData(RetrieveCurrentSchemaName)
89+
6490data TestTimeout = TestTimeout SessionId
65− deriving (Binary, Generic)
66−data RetrieveSessionIsDirty = RetrieveSessionIsDirty SessionId
67− deriving (Binary, Generic)
91+ RPCData(TestTimeout)
92+
93+data RetrieveSessionIsDirty = RetrieveSessionIsDirty SessionId
94+ RPCData(RetrieveSessionIsDirty)
95+
6896data ExecuteAutoMergeToHead = ExecuteAutoMergeToHead SessionId MergeStrategy HeadName
69− deriving (Binary, Generic)
97+ RPCData(ExecuteAutoMergeToHead)
98+
7099data RetrieveTypeConstructorMapping = RetrieveTypeConstructorMapping SessionId
71− deriving (Binary, Generic)
100+ RPCData(RetrieveTypeConstructorMapping)
101+
102+data ExecuteValidateMerkleHashes = ExecuteValidateMerkleHashes SessionId
103+ RPCData(ExecuteValidateMerkleHashes)
src/lib/ProjectM36/Session.hs+3−2
@@ -3,6 +3,7 @@ import ProjectM36.Base
33import Data.UUID
44import qualified Data.Map as M
55import ProjectM36.Error
6+import qualified ProjectM36.DisconnectedTransaction as Discon
67
78type SessionId = UUID
89
@@ -18,7 +19,7 @@ disconnectedTransaction :: Session -> DisconnectedTransaction
1819disconnectedTransaction (Session discon _) = discon
1920
2021isDirty :: Session -> DirtyFlag
21−isDirty (Session (DisconnectedTransaction _ _ dirtyFlag) _) = dirtyFlag
22+isDirty (Session discon _) = Discon.isDirty discon
2223
2324concreteDatabaseContext :: Session -> DatabaseContext
2425concreteDatabaseContext (Session (DisconnectedTransaction _ (Schemas context _) _) _) = context
@@ -40,4 +41,4 @@ setSchemaName sname session = if sname == defaultSchemaName || M.member sname (s
4041 pure (Session (disconnectedTransaction session) sname)
4142 else
4243 Left (SubschemaNameNotInUseError sname)
43−
44+
src/lib/ProjectM36/Sessions.hs+3−4
@@ -8,16 +8,17 @@ import qualified StmContainers.Set as StmSet
88import qualified STMContainers.Map as StmMap
99import qualified STMContainers.Set as StmSet
1010#endif
11−import "list-t" ListT
1211import ProjectM36.Attribute
1312import ProjectM36.Base
1413import ProjectM36.Session
1514import ProjectM36.Relation
1615import ProjectM36.Error
1716import qualified Data.UUID as U
18−import qualified Control.Foldl as Foldl
1917#if MIN_VERSION_stm_containers(1,0,0)
18+import qualified Control.Foldl as Foldl
2019import qualified DeferredFolds.UnfoldlM as UF
20+#else
21+import "list-t" ListT
2122#endif
2223
2324type Sessions = StmMap.Map SessionId Session
@@ -46,5 +47,3 @@ sessionsAsRelation sessions = do
4647 let atomMatrix = map (\(sessionId, session) -> [uuidAtom sessionId, uuidAtom (parentId session)]) sessionAssocs
4748 pure $ mkRelationFromList (attributesFromList [Attribute "sessionid" TextAtomType,
4849 Attribute "parentCommit" TextAtomType]) atomMatrix
49−
50−
src/lib/ProjectM36/Shortcuts.hsnew file+247
@@ -0,0 +1,247 @@
1+{-# OPTIONS_GHC -fno-warn-orphans #-}
2+{-# LANGUAGE ScopedTypeVariables #-}
3+{-# LANGUAGE TypeApplications #-}
4+{-# LANGUAGE FlexibleInstances #-}
5+{-# LANGUAGE MultiParamTypeClasses #-}
6+{-# LANGUAGE TypeFamilies #-}
7+{-# LANGUAGE ExtendedDefaultRules #-}
8+{-# LANGUAGE ExistentialQuantification #-}
9+{-# LANGUAGE FlexibleContexts #-}
10+{-# LANGUAGE GADTs #-}
11+{-# LANGUAGE UndecidableInstances #-}
12+module ProjectM36.Shortcuts where
13+-- users need OverloadedLabels, OverloadedLists, and default(Int,Text) to use these shortcuts.
14+import Data.Text hiding (foldl, map)
15+import ProjectM36.Base
16+import ProjectM36.Relation
17+import ProjectM36.Atomable
18+import Prelude hiding ((!!))
19+import Data.Proxy
20+import GHC.OverloadedLabels
21+import GHC.TypeLits hiding (Text)
22+import qualified Data.Text as T
23+import qualified Data.Map as M
24+import qualified Data.Set as S
25+import GHC.Exts (IsList(..))
26+import Data.Convertible
27+
28+default (Text)
29+
30+instance IsList (AttributeNamesBase ()) where
31+ type Item (AttributeNamesBase ()) = AttributeName
32+ fromList = AttributeNames . S.fromList
33+ toList (AttributeNames ns) = S.toList ns
34+ toList _ = error "needs AttributeNames"
35+
36+instance IsList (TupleExprsBase ()) where
37+ type Item TupleExprs = TupleExpr
38+ fromList ts = TupleExprs () ts
39+ toList (TupleExprs _ ts) = ts
40+
41+instance IsList TupleExpr where
42+ type Item TupleExpr = (AttributeName, AtomExpr)
43+ fromList attributeValues = TupleExpr (M.fromList attributeValues)
44+ toList (TupleExpr attributeValues) = M.toList attributeValues
45+
46+
47+-- #xxx :: Text
48+instance KnownSymbol x => IsLabel x Text where
49+ fromLabel = T.pack $ symbolVal @x Proxy
50+
51+-- #relvarName :: RelationalExpr
52+instance KnownSymbol x => IsLabel x RelationalExpr where
53+ fromLabel = RelationVariable (T.pack $ symbolVal @x Proxy) ()
54+
55+-- *Main> #a Int :: AttributeExpr
56+-- NakedAttributeExpr (Attribute "a" IntAtomType)
57+-- *Main> #a (Attr @[Int]) :: AttributeExpr
58+-- NakedAttributeExpr (Attribute "a" (ConstructedAtomType "List" (fromList [("a",IntAtomType)])))
59+-- can't offer a Relation atomtype -- don't know how to express a Relation type in haskell type. Maybe something a HList of (Text, a) ?
60+--
61+-- ps. I don't understand the usage of "AttributeAndTypeNameExpr AttributeName TypeConstructor a"
62+instance (KnownSymbol x, Atomable a)=> IsLabel x (HaskAtomType a -> AttributeExpr) where
63+ fromLabel = (NakedAttributeExpr . Attribute name) . toAtomType''
64+ where name = T.pack $ symbolVal @x Proxy
65+
66+-- (#a 1) :: ExtendTupleExpr
67+-- no need for :=
68+instance (Convertible a AtomExpr, KnownSymbol x) => IsLabel x (a -> ExtendTupleExpr) where
69+ fromLabel x = AttributeExtendTupleExpr name (convert x)
70+ where name = T.pack $ symbolVal @x Proxy
71+
72+-- #name AtomExpr
73+-- ex. tuple [ #name 3 ]
74+-- default(Text) is needed in client code to avoid `no Atomable Char`
75+instance (Convertible a AtomExpr, KnownSymbol x) => IsLabel x (a -> (AttributeName, AtomExpr)) where
76+ fromLabel = \x -> (name, convert x)
77+ where name = T.pack $ symbolVal @x Proxy
78+
79+-- *Main> #a [1] :: AtomExpr
80+-- FunctionAtomExpr "a" [NakedAtomExpr (IntegerAtom 1)] ()
81+--
82+-- This usage is not working in RestrictionPredicateExpr and AttributeExtendTupleExpr. Use f "a" [1] instead.
83+instance (KnownSymbol x, Convertible a AtomExpr) => IsLabel x ([a] -> AtomExpr) where
84+ fromLabel = \as' -> FunctionAtomExpr name (map convert as') ()
85+ where name = T.pack $ symbolVal @x Proxy
86+
87+instance (KnownSymbol x) => IsLabel x AtomExpr where
88+ fromLabel = AttributeAtomExpr name
89+ where name = T.pack $ symbolVal @x Proxy
90+
91+
92+data HaskAtomType a where
93+ Int :: HaskAtomType Int
94+ Integer :: HaskAtomType Integer
95+ Double :: HaskAtomType Double
96+ Text :: HaskAtomType Text
97+-- Day :: HaskAtomType Day
98+-- DateTime :: HaskAtomType DateTime
99+-- ByteString :: HaskAtomType ByteString
100+ Bool :: HaskAtomType Bool
101+ Attr :: Atomable a => HaskAtomType a -- a Proxy-like value for type application.
102+
103+toAtomType'' :: Atomable a => HaskAtomType a -> AtomType
104+toAtomType'' (_ :: HaskAtomType a) = toAtomType (Proxy @a)
105+
106+-- usage: relation [tuple [#a 1, #b "b"], tuple [#a 2, #b "b"]]
107+relation :: [TupleExpr] -> RelationalExpr
108+relation ts = MakeRelationFromExprs Nothing (TupleExprs () ts)
109+
110+relation' :: [AttributeExprBase ()] -> [TupleExpr] -> RelationalExpr
111+relation' as' ts = MakeRelationFromExprs (Just as') (TupleExprs () ts)
112+
113+-- usage: tuple [#name "Mike",#age 6]
114+tuple :: [(AttributeName, AtomExpr)] -> TupleExprBase ()
115+tuple as' = TupleExpr (M.fromList as')
116+
117+-- #a rename [#b `as` #c]
118+rename :: RelationalExpr -> [(AttributeName,AttributeName)] -> RelationalExpr
119+rename relExpr renameList = case renameList of
120+ [] -> Restrict TruePredicate relExpr
121+ renames ->
122+ foldl (\acc (old,new) -> Rename old new acc) relExpr renames
123+
124+--project !!
125+-- #a !! [#b,#c]
126+infix 9 !!
127+(!!) :: RelationalExpr -> AttributeNames -> RelationalExpr
128+relExpr !! xs = Project xs relExpr
129+
130+--join ><
131+-- #a >< #b
132+(><) :: RelationalExpr -> RelationalExpr -> RelationalExpr
133+a >< b = Join a b
134+
135+allBut :: AttributeNames -> AttributeNames
136+allBut (AttributeNames ns) = InvertedAttributeNames ns
137+allBut _ = error "give allBut something other than attribute names."
138+
139+allFrom :: RelationalExpr -> AttributeNames
140+allFrom = RelationalExprAttributeNames
141+
142+as :: AttributeNames -> AttributeName -> (AttributeNames, AttributeName)
143+as = (,)
144+
145+-- #a `group` ([#b,#c] `as` #d)
146+group :: RelationalExpr -> (AttributeNames, AttributeName) -> RelationalExpr
147+group relExpr (aNames, aName) = Group aNames aName relExpr
148+
149+-- #a `ungroup` #b
150+ungroup :: RelationalExpr -> AttributeName -> RelationalExpr
151+ungroup relExpr aName = Ungroup aName relExpr
152+
153+-- *Main> #a #:= true #: ( #b (f "count" [1,2]))
154+-- Assign "a" (Extend (AttributeExtendTupleExpr "b" (FunctionAtomExpr "count" [NakedAtomExpr (IntegerAtom 1),NakedAtomExpr (IntegerAtom 2)] ())) (ExistingRelation (Relation attributesFromList [] (RelationTupleSet {asList = [RelationTuple attributesFromList [] []]}))))
155+(#:) :: RelationalExpr -> ExtendTupleExpr -> RelationalExpr
156+a #: b = Extend b a
157+infix 8 #:
158+
159+instance Convertible AtomExpr AtomExpr where
160+ safeConvert n = Right n
161+
162+instance Convertible RelVarName AtomExpr where
163+ safeConvert n = Right $ RelationAtomExpr (RelationVariable n ())
164+
165+instance Convertible RelationalExpr AtomExpr where
166+ safeConvert relExpr = Right $ RelationAtomExpr relExpr
167+
168+instance Convertible RelVarName RelationalExpr where
169+ safeConvert n = Right $ RelationVariable n ()
170+
171+-- @ in tutd
172+-- (@@) "aaa"
173+(@@) :: AttributeName -> AtomExpr
174+(@@) = AttributeAtomExpr
175+
176+-- works in RestrictedPredicateExpr and AttributeExtendTupleExpr
177+-- usage: f "gte" [1]
178+f :: Convertible a AtomExpr => AtomFunctionName -> [a] -> AtomExpr
179+f n as' = FunctionAtomExpr n (map convert as') ()
180+
181+-- DatabaseContextExpr
182+-- define
183+(#::) :: RelVarName -> [AttributeExpr] -> DatabaseContextExpr
184+s #:: xs = Define s xs
185+infix 5 #::
186+
187+-- assign
188+(#:=) :: RelVarName -> RelationalExpr -> DatabaseContextExpr
189+s #:= r = Assign s r
190+infix 5 #:=
191+
192+class Boolean a b where
193+ (&&&) :: a -> b -> RestrictionPredicateExpr
194+ infixl 6 &&&
195+ (|||) :: a -> b -> RestrictionPredicateExpr
196+ infixl 5 |||
197+
198+-- where: @~ mimics the restriction symbol in algebra
199+-- usage: true #: (#a 1) @~ #a ?= 1 &&& not' false ||| (f "gte" [1])
200+(@~) :: Convertible a RestrictionPredicateExpr => RelationalExpr -> a -> RelationalExpr
201+(@~) relExpr resPreExpr = Restrict (convert resPreExpr) relExpr
202+infix 4 @~
203+
204+true :: RelationalExpr
205+true = ExistingRelation relationTrue
206+
207+false :: RelationalExpr
208+false = ExistingRelation relationFalse
209+
210+trueP :: RestrictionPredicateExprBase a
211+trueP = TruePredicate
212+
213+falseP :: RestrictionPredicateExprBase a
214+falseP = NotPredicate TruePredicate
215+
216+(?=) :: Convertible a AtomExpr => AttributeName -> a -> RestrictionPredicateExpr
217+(?=) name a = AttributeEqualityPredicate name (convert a)
218+infix 9 ?=
219+
220+not' :: Convertible a RestrictionPredicateExpr => a -> RestrictionPredicateExpr
221+not' = NotPredicate . convert
222+
223+instance (Convertible a RestrictionPredicateExpr, Convertible b RestrictionPredicateExpr) => Boolean a b where
224+ a &&& b = AndPredicate (convert a) (convert b)
225+ a ||| b = OrPredicate (convert a) (convert b)
226+
227+instance {-# Incoherent #-} Atomable a => Convertible a RestrictionPredicateExpr where
228+ safeConvert n = Right $ AtomExprPredicate $ toAtomExpr . toAtom $ n
229+
230+instance {-# Incoherent #-} Convertible RelationalExpr RestrictionPredicateExpr where
231+ safeConvert a = Right $ RelationalExprPredicate a
232+
233+instance {-# Incoherent #-} Convertible AtomExpr RestrictionPredicateExpr where
234+ safeConvert a = Right $ AtomExprPredicate a
235+
236+instance {-# Incoherent #-} Convertible RestrictionPredicateExpr RestrictionPredicateExpr where
237+ safeConvert a = Right a
238+
239+instance {-# Incoherent #-} Atomable a => Convertible a AtomExpr where
240+ safeConvert n = Right $ toAtomExpr . toAtom $ n
241+
242+toAtomExpr :: Atom -> AtomExpr
243+toAtomExpr (ConstructedAtom n _ xs) = ConstructedAtomExpr n (toAtomExpr <$> xs) ()
244+toAtomExpr a = NakedAtomExpr a
245+
246+
247+
src/lib/ProjectM36/StaticOptimizer.hs+370−249
@@ -1,289 +1,402 @@
1+{-# LANGUAGE FlexibleInstances #-}
2+{-# LANGUAGE FlexibleContexts #-}
13module ProjectM36.StaticOptimizer where
24import ProjectM36.Base
3−import ProjectM36.RelationalExpression
5+import ProjectM36.GraphRefRelationalExpr
46import ProjectM36.Relation
7+import ProjectM36.RelationalExpression
8+import ProjectM36.TransGraphRelationalExpression as TGRE hiding (askGraph)
59import ProjectM36.Error
10+import ProjectM36.Transaction
11+import ProjectM36.NormalizeExpr
612import qualified ProjectM36.Attribute as A
713import qualified ProjectM36.AttributeNames as AS
814import ProjectM36.TupleSet
915import Control.Monad.State
10−import Data.Either (rights, lefts)
11−import Control.Monad.Trans.Reader
16+import Control.Monad.Reader
17+import Control.Monad.Except
18+import Control.Monad.Trans.Except
19+import Data.Functor.Identity
1220import qualified Data.Map as M
1321import qualified Data.Set as S
1422
1523-- the static optimizer performs optimizations which need not take any specific-relation statistics into account
16−optimizeRelationalExpr :: DatabaseContext -> RelationalExpr -> Either RelationalError RelationalExpr
17−optimizeRelationalExpr context expr = runReader (optimizeRelationalExprReader expr) (mkRelationalExprState context)
18−
19−optimizeRelationalExprReader :: RelationalExpr -> RelationalExprState (Either RelationalError RelationalExpr)
20−optimizeRelationalExprReader expr = do
21− eOptExpr <- applyStaticRelationalOptimization expr
24+
25+data GraphRefSOptRelationalExprEnv =
26+ GraphRefSOptRelationalExprEnv
27+ {
28+ ore_graph :: TransactionGraph,
29+ ore_mcontext :: Maybe DatabaseContext
30+ }
31+
32+type GraphRefSOptRelationalExprM a = ReaderT GraphRefSOptRelationalExprEnv (ExceptT RelationalError Identity) a
33+
34+data GraphRefSOptDatabaseContextExprEnv =
35+ GraphRefSOptDatabaseContextExprEnv
36+ {
37+ odce_graph :: TransactionGraph,
38+ odce_context :: DatabaseContext, --not optional for DatabaseContextExpr evaluation
39+ odce_transId :: TransactionId -- parent if context is committed- needed because MultipleExpr optimization requires running the DatabaseContextExprs (with empty relvars)
40+ }
41+
42+type GraphRefSOptDatabaseContextExprM a = ReaderT GraphRefSOptDatabaseContextExprEnv (ExceptT RelationalError Identity) a
43+
44+-- | A temporary function to be replaced by IO-based implementation.
45+optimizeAndEvalRelationalExpr :: RelationalExprEnv -> RelationalExpr -> Either RelationalError Relation
46+optimizeAndEvalRelationalExpr env expr = do
47+ let gfExpr = runProcessExprM UncommittedContextMarker (processRelationalExpr expr) -- references parent tid instead of context! options- I could add the context to the graph with a new transid or implement an evalRelationalExpr in RE.hs to use the context (which is what I had previously)
48+ graph = re_graph env
49+ ctx = re_context env
50+ gfEnv = freshGraphRefRelationalExprEnv (Just ctx) graph
51+ optExpr <- runGraphRefSOptRelationalExprM (Just ctx) (re_graph env) (fullOptimizeGraphRefRelationalExpr gfExpr)
52+ runGraphRefRelationalExprM gfEnv (evalGraphRefRelationalExpr optExpr)
53+
54+class Monad m => AskGraphContext m where
55+ askGraph :: m TransactionGraph
56+ askContext :: m DatabaseContext
57+
58+instance AskGraphContext (ReaderT GraphRefSOptDatabaseContextExprEnv (ExceptT RelationalError Identity)) where
59+ askGraph = asks odce_graph
60+ askContext = asks odce_context
61+
62+instance AskGraphContext (ReaderT GraphRefSOptRelationalExprEnv (ExceptT RelationalError Identity)) where
63+ askGraph = asks ore_graph
64+ askContext = do
65+ mctx <- asks ore_mcontext
66+ case mctx of
67+ Nothing -> throwError NoUncommittedContextInEvalError
68+ Just ctx -> pure ctx
69+
70+askTransId :: GraphRefSOptDatabaseContextExprM TransactionId
71+askTransId = asks odce_transId
72+
73+askMaybeContext :: GraphRefSOptRelationalExprM (Maybe DatabaseContext)
74+askMaybeContext = asks ore_mcontext
75+
76+optimizeDatabaseContextExpr :: DatabaseContextExpr -> GraphRefSOptDatabaseContextExprM GraphRefDatabaseContextExpr
77+optimizeDatabaseContextExpr expr = do
78+ let gfExpr = runProcessExprM UncommittedContextMarker (processDatabaseContextExpr expr)
79+ optimizeGraphRefDatabaseContextExpr gfExpr
80+
81+optimizeAndEvalDatabaseContextExpr :: Bool -> DatabaseContextExpr -> DatabaseContextEvalMonad ()
82+optimizeAndEvalDatabaseContextExpr optimize expr = do
83+ graph <- asks dce_graph
84+ transId <- asks dce_transId
85+ context <- getStateContext
86+ let gfExpr = runProcessExprM UncommittedContextMarker (processDatabaseContextExpr expr)
87+ eOptExpr = if optimize then
88+ runGraphRefSOptDatabaseContextExprM transId context graph (optimizeGraphRefDatabaseContextExpr gfExpr)
89+ else
90+ pure gfExpr
91+ case eOptExpr of
92+ Left err -> throwError err
93+ Right optExpr -> evalGraphRefDatabaseContextExpr optExpr
94+
95+
96+optimizeAndEvalTransGraphRelationalExpr :: TransactionGraph -> TransGraphRelationalExpr -> Either RelationalError Relation
97+optimizeAndEvalTransGraphRelationalExpr graph tgExpr = do
98+ gfExpr <- TGRE.process (TransGraphEvalEnv graph) tgExpr
99+ optExpr <- runGraphRefSOptRelationalExprM Nothing graph (fullOptimizeGraphRefRelationalExpr gfExpr)
100+ let gfEnv = freshGraphRefRelationalExprEnv Nothing graph
101+ runGraphRefRelationalExprM gfEnv (evalGraphRefRelationalExpr optExpr)
102+
103+optimizeAndEvalDatabaseContextIOExpr :: DatabaseContextIOExpr -> DatabaseContextIOEvalMonad (Either RelationalError ())
104+optimizeAndEvalDatabaseContextIOExpr expr = do
105+ transId <- asks dbcio_transId
106+ ctx <- getDBCIOContext
107+ graph <- asks dbcio_graph
108+ let gfExpr = runProcessExprM UncommittedContextMarker (processDatabaseContextIOExpr expr)
109+ eOptExpr = runGraphRefSOptDatabaseContextExprM transId ctx graph (optimizeDatabaseContextIOExpr gfExpr)
22110 case eOptExpr of
23111 Left err -> pure (Left err)
24112 Right optExpr ->
25− applyStaticJoinElimination (applyStaticRestrictionPushdown (applyStaticRestrictionCollapse optExpr))
113+ evalGraphRefDatabaseContextIOExpr optExpr
114+
115+{-
116+runStaticOptimizerMonad :: RelationalExprEnv -> StaticOptimizerMonad a -> Either RelationalError a
117+runStaticOptimizerMonad env m = runIdentity (runExceptT (runReaderT m env))
118+-}
119+
120+runGraphRefSOptRelationalExprM ::
121+ Maybe DatabaseContext ->
122+ TransactionGraph ->
123+ GraphRefSOptRelationalExprM a ->
124+ Either RelationalError a
125+runGraphRefSOptRelationalExprM mctx graph m = runIdentity (runExceptT (runReaderT m env))
126+ where
127+ env = GraphRefSOptRelationalExprEnv {
128+ ore_graph = graph,
129+ ore_mcontext = mctx
130+ }
131+
132+
133+runGraphRefSOptDatabaseContextExprM ::
134+ TransactionId ->
135+ DatabaseContext ->
136+ TransactionGraph ->
137+ GraphRefSOptDatabaseContextExprM a ->
138+ Either RelationalError a
139+runGraphRefSOptDatabaseContextExprM tid ctx graph m =
140+ runIdentity (runExceptT (runReaderT m env))
141+ where
142+ env = GraphRefSOptDatabaseContextExprEnv {
143+ odce_graph = graph,
144+ odce_context = ctx,
145+ odce_transId = tid
146+ }
147+
148+optimizeGraphRefRelationalExpr' ::
149+ Maybe DatabaseContext ->
150+ TransactionGraph ->
151+ GraphRefRelationalExpr ->
152+ Either RelationalError GraphRefRelationalExpr
153+optimizeGraphRefRelationalExpr' mctx graph expr =
154+ runIdentity (runExceptT (runReaderT (optimizeGraphRefRelationalExpr expr) env))
155+ where
156+ env = GraphRefSOptRelationalExprEnv {
157+ ore_graph = graph,
158+ ore_mcontext = mctx
159+ }
160+
161+-- | optimize relational expression within database context expr monad
162+liftGraphRefRelExpr :: GraphRefSOptRelationalExprM a -> GraphRefSOptDatabaseContextExprM a
163+liftGraphRefRelExpr m = do
164+ context <- asks odce_context
165+ graph <- asks odce_graph
166+ lift $ except $ runGraphRefSOptRelationalExprM (Just context) graph m
167+
168+fullOptimizeGraphRefRelationalExpr :: GraphRefRelationalExpr -> GraphRefSOptRelationalExprM GraphRefRelationalExpr
169+fullOptimizeGraphRefRelationalExpr expr = do
170+ optExpr <- optimizeGraphRefRelationalExpr expr
171+ let optExpr' = applyStaticRestrictionPushdown (applyStaticRestrictionCollapse optExpr)
172+ applyStaticJoinElimination optExpr'
26173
27−optimizeDatabaseContextExpr :: DatabaseContext -> DatabaseContextExpr -> Either RelationalError DatabaseContextExpr
28−optimizeDatabaseContextExpr context dbExpr = evalState (applyStaticDatabaseOptimization dbExpr) (freshDatabaseState context)
29174-- apply optimizations which merely remove steps to become no-ops: example: projection of a relation across all of its attributes => original relation
30175
31176--should optimizations offer the possibility to pure errors? If they perform the up-front type-checking, maybe so
32−applyStaticRelationalOptimization :: RelationalExpr -> RelationalExprState (Either RelationalError RelationalExpr)
33−applyStaticRelationalOptimization e@(MakeStaticRelation _ _) = pure $ Right e
177+optimizeGraphRefRelationalExpr :: GraphRefRelationalExpr -> GraphRefSOptRelationalExprM GraphRefRelationalExpr
178+optimizeGraphRefRelationalExpr e@(MakeStaticRelation _ _) = pure e
34179
35−applyStaticRelationalOptimization e@(MakeRelationFromExprs _ _) = pure $ Right e
180+optimizeGraphRefRelationalExpr e@MakeRelationFromExprs{} = pure e
36181
37−applyStaticRelationalOptimization e@(ExistingRelation _) = pure $ Right e
182+optimizeGraphRefRelationalExpr e@(ExistingRelation _) = pure e
38183
39−applyStaticRelationalOptimization e@(RelationVariable _ _) = pure $ Right e
184+optimizeGraphRefRelationalExpr e@(RelationVariable _ _) = pure e
40185
41186--remove project of attributes which removes no attributes
42−applyStaticRelationalOptimization (Project attrNameSet expr) = do
43− relType <- typeForRelationalExpr expr
187+optimizeGraphRefRelationalExpr (Project attrNameSet expr) = do
188+ graph <- askGraph
189+ mctx <- askMaybeContext
190+ let relType = runGraphRefRelationalExprM gfEnv (typeForGraphRefRelationalExpr expr)
191+ gfEnv = freshGraphRefRelationalExprEnv mctx graph
44192 case relType of
45− Left err -> pure $ Left err
193+ Left err -> throwError err
46194 Right relType2
47− | AS.all == attrNameSet ->
48− applyStaticRelationalOptimization expr
195+ | AS.all == attrNameSet ->
196+ optimizeGraphRefRelationalExpr expr
49197 | AttributeNames (attributeNames relType2) == attrNameSet ->
50− applyStaticRelationalOptimization expr
198+ optimizeGraphRefRelationalExpr expr
51199 | otherwise -> do
52− optimizedSubExpression <- applyStaticRelationalOptimization expr
53− case optimizedSubExpression of
54− Left err -> pure $ Left err
55− Right optSubExpr -> pure (Right (Project attrNameSet optSubExpr))
200+ optSubExpr <- optimizeGraphRefRelationalExpr expr
201+ pure (Project attrNameSet optSubExpr)
56202
57−applyStaticRelationalOptimization (Union exprA exprB) = do
58− eOptExprA <- applyStaticRelationalOptimization exprA
59− eOptExprB <- applyStaticRelationalOptimization exprB
60− case eOptExprA of
61− Left err -> pure $ Left err
62− Right optExprA -> case eOptExprB of
63− Left err -> pure $ Left err
64− Right optExprB -> -- (x where pred1) union (x where pred2) -> (x where pred1 or pred2)
65− case (optExprA, optExprB) of
66− (Restrict predA (RelationVariable nameA ()),
67− Restrict predB (RelationVariable nameB ())) | nameA == nameB -> pure (Right (Restrict (AndPredicate predA predB) (RelationVariable nameA ())))
203+optimizeGraphRefRelationalExpr (Union exprA exprB) = do
204+ optExprA <- optimizeGraphRefRelationalExpr exprA
205+ optExprB <- optimizeGraphRefRelationalExpr exprB
206+ -- (x where pred1) union (x where pred2) -> (x where pred1 or pred2)
207+ case (optExprA, optExprB) of
208+ (Restrict predA (RelationVariable nameA sA),
209+ Restrict predB (RelationVariable nameB sB)) | nameA == nameB && sA == sB -> pure (Restrict (AndPredicate predA predB) (RelationVariable nameA sA))
210+ (exprA', exprB') | isEmptyRelationExpr exprA' -> pure exprB'
211+ | isEmptyRelationExpr exprB' -> pure exprA'
68212 _ -> if optExprA == optExprB then
69− pure (Right optExprA)
213+ pure optExprA
70214 else
71− pure $ Right $ Union optExprA optExprB
215+ pure $ Union optExprA optExprB
72216
73−applyStaticRelationalOptimization (Join exprA exprB) = do
74− eOptExprA <- applyStaticRelationalOptimization exprA
75− eOptExprB <- applyStaticRelationalOptimization exprB
76− case eOptExprA of
77− Left err -> pure $ Left err
78− Right optExprA -> case eOptExprB of
79− Left err -> pure $ Left err
80− Right optExprB ->
81− -- if the relvars to join are the same but with predicates, then just AndPredicate the predicates
82− case (optExprA, optExprB) of
83− (Restrict predA (RelationVariable nameA ()),
84− Restrict predB (RelationVariable nameB ())) | nameA == nameB -> pure (Right (Restrict (AndPredicate predA predB) (RelationVariable nameA ())))
217+optimizeGraphRefRelationalExpr (Join exprA exprB) = do
218+ optExprA <- optimizeGraphRefRelationalExpr exprA
219+ optExprB <- optimizeGraphRefRelationalExpr exprB
220+ -- if the relvars to join are the same but with predicates, then just AndPredicate the predicates
221+ case (optExprA, optExprB) of
222+ (Restrict predA (RelationVariable nameA sA),
223+ Restrict predB (RelationVariable nameB sB)) | nameA == nameB && sA == sB -> pure (Restrict (AndPredicate predA predB) (RelationVariable nameA sA))
85224 _ -> if optExprA == optExprB then --A join A == A
86− pure (Right optExprA)
225+ pure optExprA
87226 else
88− pure (Right (Join optExprA optExprB))
227+ pure (Join optExprA optExprB)
89228
90−applyStaticRelationalOptimization (Difference exprA exprB) = do
91− optExprA <- applyStaticRelationalOptimization exprA
92− optExprB <- applyStaticRelationalOptimization exprB
93− case optExprA of
94− Left err -> pure $ Left err
95− Right optExprA2 -> case optExprB of
96− Left err -> pure $ Left err
97− Right optExprB2 -> if optExprA == optExprB then do --A difference A == A where false
98− eEmptyRel <- typeForRelationalExpr optExprA2
99− case eEmptyRel of
100− Left err -> pure (Left err)
101− Right emptyRel -> pure (Right (ExistingRelation emptyRel))
102− else
103− pure $ Right (Difference optExprA2 optExprB2)
229+optimizeGraphRefRelationalExpr (Difference exprA exprB) = do
230+ graph <- askGraph
231+ context <- askMaybeContext
232+ optExprA <- optimizeGraphRefRelationalExpr exprA
233+ optExprB <- optimizeGraphRefRelationalExpr exprB
234+ if optExprA == optExprB then do --A difference A == A where false
235+ let eEmptyRel = runGraphRefRelationalExprM gfEnv (typeForGraphRefRelationalExpr optExprA)
236+ gfEnv = freshGraphRefRelationalExprEnv context graph
237+ case eEmptyRel of
238+ Left err -> throwError err
239+ Right emptyRel -> pure (ExistingRelation emptyRel)
240+ else
241+ pure (Difference optExprA optExprB)
104242
105−applyStaticRelationalOptimization e@Rename{} = pure $ Right e
243+optimizeGraphRefRelationalExpr e@Rename{} = pure e
106244
107−applyStaticRelationalOptimization (Group oldAttrNames newAttrName expr) =
108− pure $ Right $ Group oldAttrNames newAttrName expr
245+optimizeGraphRefRelationalExpr (Group oldAttrNames newAttrName expr) =
246+ pure $ Group oldAttrNames newAttrName expr
109247
110−applyStaticRelationalOptimization (Ungroup attrName expr) =
111− pure $ Right $ Ungroup attrName expr
248+optimizeGraphRefRelationalExpr (Ungroup attrName expr) =
249+ pure $ Ungroup attrName expr
112250
113251--remove restriction of nothing
114−applyStaticRelationalOptimization (Restrict predicate expr) = do
252+optimizeGraphRefRelationalExpr (Restrict predicate expr) = do
253+ graph <- askGraph
254+ mctx <- askMaybeContext
115255 optimizedPredicate <- applyStaticPredicateOptimization predicate
116256 case optimizedPredicate of
117− Left err -> pure $ Left err
118− Right optimizedPredicate2
119− | isTrueExpr optimizedPredicate2 -> applyStaticRelationalOptimization expr -- remove predicate entirely
120− | isFalseExpr optimizedPredicate2 -> do -- replace where false predicate with empty relation with attributes from relexpr
121− attributesRel <- typeForRelationalExpr expr
257+ optimizedPredicate' | isTrueExpr optimizedPredicate' -> optimizeGraphRefRelationalExpr expr -- remove predicate entirely
258+ optimizedPredicate' | isFalseExpr optimizedPredicate' -> do -- replace where false predicate with empty relation with attributes from relexpr
259+ let attributesRel = runGraphRefRelationalExprM gfEnv (typeForGraphRefRelationalExpr expr)
260+ gfEnv = freshGraphRefRelationalExprEnv mctx graph
122261 case attributesRel of
123− Left err -> pure $ Left err
124− Right attributesRelA -> pure $ Right $ MakeStaticRelation (attributes attributesRelA) emptyTupleSet
262+ Left err -> throwError err
263+ Right attributesRelA -> pure $ MakeStaticRelation (attributes attributesRelA) emptyTupleSet
125264 | otherwise -> do
126− optimizedSubExpression <- applyStaticRelationalOptimization expr
127− case optimizedSubExpression of
128− Left err -> pure $ Left err
129− Right optSubExpr -> pure $ Right $ Restrict optimizedPredicate2 optSubExpr
265+ optSubExpr <- optimizeGraphRefRelationalExpr expr
266+ pure $ Restrict optimizedPredicate' optSubExpr
130267
131−applyStaticRelationalOptimization e@(Equals _ _) = pure $ Right e
268+optimizeGraphRefRelationalExpr e@(Equals _ _) = pure e
132269
133−applyStaticRelationalOptimization e@(NotEquals _ _) = pure $ Right e
270+optimizeGraphRefRelationalExpr e@(NotEquals _ _) = pure e
134271
135−applyStaticRelationalOptimization e@(Extend _ _) = pure $ Right e
272+optimizeGraphRefRelationalExpr e@(Extend _ _) = pure e
136273
137−applyStaticRelationalOptimization e@(With _ _) = pure $ Right e
274+optimizeGraphRefRelationalExpr e@(With _ _) = pure e
138275
139−applyStaticDatabaseOptimization :: DatabaseContextExpr -> DatabaseState (Either RelationalError DatabaseContextExpr)
140−applyStaticDatabaseOptimization x@NoOperation = pure $ Right x
141−applyStaticDatabaseOptimization x@(Define _ _) = pure $ Right x
276+-- database context expr
277+optimizeGraphRefDatabaseContextExpr :: GraphRefDatabaseContextExpr -> GraphRefSOptDatabaseContextExprM GraphRefDatabaseContextExpr
278+optimizeGraphRefDatabaseContextExpr x@NoOperation = pure x
279+optimizeGraphRefDatabaseContextExpr x@(Define _ _) = pure x
142280
143−applyStaticDatabaseOptimization x@(Undefine _) = pure $ Right x
281+optimizeGraphRefDatabaseContextExpr x@(Undefine _) = pure x
144282
145−applyStaticDatabaseOptimization (Assign name expr) = do
146− context <- getStateContext
147− let optimizedExpr = optimizeRelationalExpr context expr
148− case optimizedExpr of
149− Left err -> pure $ Left err
150− Right optimizedExpr2 -> pure $ Right (Assign name optimizedExpr2)
283+optimizeGraphRefDatabaseContextExpr (Assign name expr) = do
284+ optExpr <- liftGraphRefRelExpr (fullOptimizeGraphRefRelationalExpr expr)
285+ pure $ Assign name optExpr
151286
152−applyStaticDatabaseOptimization (Insert targetName expr) = do
153− context <- getStateContext
154− let optimizedExpr = optimizeRelationalExpr context expr
155− case optimizedExpr of
156− Left err -> pure $ Left err
157− Right optimizedExpr2 -> if isEmptyRelationExpr optimizedExpr2 then -- if we are trying to insert an empty relation, do nothing
158− pure (Right NoOperation)
159− else
160− case optimizedExpr2 of
161− -- if the target relvar and the insert relvar are the same, there is nothing to do
162− -- insert s s -> NoOperation
163− RelationVariable insName () | insName == targetName -> pure (Right NoOperation)
164− _ -> pure $ Right (Insert targetName optimizedExpr2)
287+optimizeGraphRefDatabaseContextExpr (Insert targetName expr) = do
288+ optimizedExpr <- liftGraphRefRelExpr (fullOptimizeGraphRefRelationalExpr expr)
289+ if isEmptyRelationExpr optimizedExpr then -- if we are trying to insert an empty relation, do nothing
290+ pure NoOperation
291+ else
292+ case optimizedExpr of
293+ -- if the target relvar and the insert relvar are the same, there is nothing to do
294+ -- insert s s -> NoOperation
295+ RelationVariable insName _ | insName == targetName -> pure NoOperation
296+ _ -> pure (Insert targetName optimizedExpr)
165297
166−applyStaticDatabaseOptimization (Delete name predicate) = do
167− context <- getStateContext
168− let optimizedPredicate = runReader (applyStaticPredicateOptimization predicate) (RelationalExprStateElems context)
169− case optimizedPredicate of
170− Left err -> pure $ Left err
171− Right optimizedPredicate2 -> pure $ Right (Delete name optimizedPredicate2)
298+optimizeGraphRefDatabaseContextExpr (Delete name predicate) =
299+ Delete name <$> liftGraphRefRelExpr (applyStaticPredicateOptimization predicate)
172300
173−applyStaticDatabaseOptimization (Update name upmap predicate) = do
174− context <- getStateContext
175− let optimizedPredicate = runReader (applyStaticPredicateOptimization predicate) (RelationalExprStateElems context)
176− case optimizedPredicate of
177− Left err -> pure $ Left err
178− Right optimizedPredicate2 -> pure $ Right (Update name upmap optimizedPredicate2)
301+optimizeGraphRefDatabaseContextExpr (Update name upmap predicate) =
302+ Update name upmap <$> liftGraphRefRelExpr (applyStaticPredicateOptimization predicate)
179303
180−applyStaticDatabaseOptimization dep@(AddInclusionDependency _ _) = pure $ Right dep
304+optimizeGraphRefDatabaseContextExpr dep@(AddInclusionDependency _ _) = pure dep
181305
182−applyStaticDatabaseOptimization (RemoveInclusionDependency name) = pure $ Right (RemoveInclusionDependency name)
306+optimizeGraphRefDatabaseContextExpr (RemoveInclusionDependency name) = pure (RemoveInclusionDependency name)
183307
184−applyStaticDatabaseOptimization (AddNotification name triggerExpr resultOldExpr resultNewExpr) = do
185− context <- getStateContext
186− let eTriggerExprOpt = optimizeRelationalExpr context triggerExpr
187− case eTriggerExprOpt of
188− Left err -> pure $ Left err
189− Right triggerExprOpt -> --it doesn't make sense to optimize queries when we don't have their proper contexts
190− pure (Right (AddNotification name triggerExprOpt resultOldExpr resultNewExpr))
308+optimizeGraphRefDatabaseContextExpr (AddNotification name triggerExpr resultOldExpr resultNewExpr) =
309+ --we can't optimize these expressions until they run
310+ pure (AddNotification name triggerExpr resultOldExpr resultNewExpr)
191311
192−applyStaticDatabaseOptimization notif@(RemoveNotification _) = pure (Right notif)
312+optimizeGraphRefDatabaseContextExpr notif@(RemoveNotification _) = pure notif
193313
194−applyStaticDatabaseOptimization c@(AddTypeConstructor _ _) = pure (Right c)
195−applyStaticDatabaseOptimization c@(RemoveTypeConstructor _) = pure (Right c)
196−applyStaticDatabaseOptimization c@(RemoveAtomFunction _) = pure (Right c)
197−applyStaticDatabaseOptimization c@(RemoveDatabaseContextFunction _) = pure (Right c)
198−applyStaticDatabaseOptimization c@(ExecuteDatabaseContextFunction _ _) = pure (Right c)
314+optimizeGraphRefDatabaseContextExpr c@(AddTypeConstructor _ _) = pure c
315+optimizeGraphRefDatabaseContextExpr c@(RemoveTypeConstructor _) = pure c
316+optimizeGraphRefDatabaseContextExpr c@(RemoveAtomFunction _) = pure c
317+optimizeGraphRefDatabaseContextExpr c@(RemoveDatabaseContextFunction _) = pure c
318+optimizeGraphRefDatabaseContextExpr c@(ExecuteDatabaseContextFunction _ _) = pure c
199319
200320--optimization: from pgsql lists- check for join condition referencing foreign key- if join projection project away the referenced table, then it does not need to be scanned
201321
202322--applyStaticDatabaseOptimization (MultipleExpr exprs) = pure $ Right $ MultipleExpr exprs
203323--for multiple expressions, we must evaluate
204−applyStaticDatabaseOptimization (MultipleExpr exprs) = do
205− context <- getStateContext
206− let optExprs = evalState substateRunner (contextWithEmptyTupleSets context, M.empty, False)
207− let errors = lefts optExprs
208− if not (null errors) then
209− pure $ Left (head errors)
210− else
211− pure $ Right $ MultipleExpr (rights optExprs)
212− where
213− substateRunner = forM exprs $ \expr -> do
214− --a previous expression could create a relvar, we don't want to miss it, so we clear the tuples and execute the expression to get an empty relation in the relvar
215− _ <- evalDatabaseContextExpr expr
216− applyStaticDatabaseOptimization expr
217− --this error handling could be improved with some lifting presumably
218− --restore original context
219−
220−applyStaticPredicateOptimization :: RestrictionPredicateExpr -> RelationalExprState (Either RelationalError RestrictionPredicateExpr)
324+optimizeGraphRefDatabaseContextExpr (MultipleExpr exprs) = do
325+ --a previous expression in the exprs list could create a relvar; we don't want to miss it, so we clear the tuples and execute the expression to get an empty relation in the relvar
326+ context <- askContext
327+ graph <- askGraph
328+ parentId <- askTransId
329+
330+ let emptyRvs ctx = ctx { relationVariables = mkEmptyRelVars (relationVariables ctx) }
331+ dbcEnv = mkDatabaseContextEvalEnv parentId graph
332+ folder (ctx, expracc) expr = do
333+ --optimize the expr and run it against empty relvars to add it to the context
334+ case runGraphRefSOptDatabaseContextExprM parentId ctx graph (optimizeGraphRefDatabaseContextExpr expr) of
335+ Left err -> throwError err
336+ Right optExpr ->
337+ case runDatabaseContextEvalMonad ctx dbcEnv (evalGraphRefDatabaseContextExpr optExpr) of
338+ Left err -> throwError err
339+ Right dbcState ->
340+ pure (emptyRvs $ dbc_context dbcState, expracc ++ [optExpr])
341+
342+ (_, exprs') <- foldM folder (context,[]) exprs
343+ pure (MultipleExpr exprs')
344+
345+applyStaticPredicateOptimization :: GraphRefRestrictionPredicateExpr -> GraphRefSOptRelationalExprM GraphRefRestrictionPredicateExpr
221346applyStaticPredicateOptimization predi = do
222− eOptPred <- case predi of
347+ optPred <- case predi of
223348-- where x and x => where x
224349 AndPredicate pred1 pred2 -> do
225− eOptPred1 <- applyStaticPredicateOptimization pred1
226− case eOptPred1 of
227− Left err -> pure (Left err)
228− Right optPred1 -> do
229− eOptPred2 <- applyStaticPredicateOptimization pred2
230− case eOptPred2 of
231− Left err -> pure (Left err)
232− Right optPred2 ->
233− if optPred1 == optPred2 then
234− pure (Right optPred1)
235− else
236− pure (Right (AndPredicate optPred1 optPred2))
350+ optPredA <- applyStaticPredicateOptimization pred1
351+ optPredB <- applyStaticPredicateOptimization pred2
352+ if optPredA == optPredB then
353+ pure optPredA
354+ else
355+ pure (AndPredicate optPredA optPredB)
237356-- where x or x => where x
238357 OrPredicate pred1 pred2 -> do
239− eOptPred1 <- applyStaticPredicateOptimization pred1
240− case eOptPred1 of
241− Left err -> pure (Left err)
242− Right optPred1 -> do
243− eOptPred2 <- applyStaticPredicateOptimization pred2
244− case eOptPred2 of
245− Left err -> pure (Left err)
246− Right optPred2 | optPred1 == optPred2 -> pure (Right optPred1)
247− | isTrueExpr optPred1 -> pure (Right optPred1) -- True or x -> True
248− | isTrueExpr optPred2 -> pure (Right optPred2)
249− | otherwise -> pure (Right (OrPredicate optPred1 optPred2))
358+ optPredA <- applyStaticPredicateOptimization pred1
359+ optPredB <- applyStaticPredicateOptimization pred2
360+ if (optPredA == optPredB) || isTrueExpr optPredA then
361+ pure optPredA
362+ else if isTrueExpr optPredB then
363+ pure optPredB
364+ else
365+ pure (OrPredicate optPredA optPredB)
250366 AttributeEqualityPredicate attrNameA (AttributeAtomExpr attrNameB) ->
251367 if attrNameA == attrNameB then
252− pure (Right TruePredicate)
368+ pure TruePredicate
253369 else
254− pure (Right predi)
255− AttributeEqualityPredicate{} -> pure (Right predi)
256− TruePredicate -> pure $ Right predi
257− NotPredicate{} -> pure $ Right predi
258− RelationalExprPredicate{} -> pure (Right predi)
259− AtomExprPredicate{} -> pure (Right predi)
260− case eOptPred of
261− Left err -> pure (Left err)
262− Right optPred ->
263− let attrMap = findStaticRestrictionPredicates optPred in
264− pure (Right (replaceStaticAtomExprs optPred attrMap))
370+ pure predi
371+ AttributeEqualityPredicate{} -> pure predi
372+ TruePredicate -> pure predi
373+ NotPredicate{} -> pure predi
374+ RelationalExprPredicate{} -> pure predi
375+ AtomExprPredicate{} -> pure predi
376+ let attrMap = findStaticRestrictionPredicates optPred
377+ pure (replaceStaticAtomExprs optPred attrMap)
265378
266379--determines if an atom expression is tautologically true
267−isTrueExpr :: RestrictionPredicateExpr -> Bool
380+isTrueExpr :: RestrictionPredicateExprBase a -> Bool
268381isTrueExpr TruePredicate = True
269382isTrueExpr (AtomExprPredicate (NakedAtomExpr (BoolAtom True))) = True
270383isTrueExpr _ = False
271384
272385--determines if an atom expression is tautologically false
273−isFalseExpr :: RestrictionPredicateExpr -> Bool
386+isFalseExpr :: RestrictionPredicateExprBase a -> Bool
274387isFalseExpr (NotPredicate expr) = isTrueExpr expr
275388isFalseExpr (AtomExprPredicate (NakedAtomExpr (BoolAtom False))) = True
276389isFalseExpr _ = False
277390
278391-- determine if the created relation can statically be determined to be empty
279−isEmptyRelationExpr :: RelationalExpr -> Bool
280−isEmptyRelationExpr (MakeRelationFromExprs _ []) = True
392+isEmptyRelationExpr :: RelationalExprBase a -> Bool
393+isEmptyRelationExpr (MakeRelationFromExprs _ (TupleExprs _ [])) = True
281394isEmptyRelationExpr (MakeStaticRelation _ tupSet) = null (asList tupSet)
282395isEmptyRelationExpr (ExistingRelation rel) = rel == emptyRelationWithAttrs (attributes rel)
283396isEmptyRelationExpr _ = False
284397
285398--transitive static variable optimization
286−replaceStaticAtomExprs :: RestrictionPredicateExpr -> M.Map AttributeName AtomExpr -> RestrictionPredicateExpr
399+replaceStaticAtomExprs :: GraphRefRestrictionPredicateExpr -> M.Map AttributeName GraphRefAtomExpr -> GraphRefRestrictionPredicateExpr
287400replaceStaticAtomExprs predIn replaceMap = case predIn of
288401 AttributeEqualityPredicate newAttrName (AttributeAtomExpr matchName) -> case M.lookup matchName replaceMap of
289402 Nothing -> predIn
@@ -296,7 +409,7 @@ replaceStaticAtomExprs predIn replaceMap = case predIn of
296409 RelationalExprPredicate{} -> predIn
297410 AtomExprPredicate{} -> predIn
298411-- used for transitive attribute optimization- only works on statically-determined atoms for now- in the future, this could work for all AtomExprs which don't reference attributes
299−findStaticRestrictionPredicates :: RestrictionPredicateExpr -> M.Map AttributeName AtomExpr
412+findStaticRestrictionPredicates :: GraphRefRestrictionPredicateExpr -> M.Map AttributeName GraphRefAtomExpr
300413findStaticRestrictionPredicates (AttributeEqualityPredicate attrName atomExpr) =
301414 case atomExpr of
302415 val@NakedAtomExpr{} -> M.singleton attrName val
@@ -320,60 +433,65 @@ isStaticAtomExpr FunctionAtomExpr{} = False
320433isStaticAtomExpr RelationAtomExpr{} = False
321434
322435--if the projection of a join only uses the attributes from one of the expressions and there is a foreign key relationship between the expressions, we know that the join is inconsequential and can be removed
323−applyStaticJoinElimination :: RelationalExpr -> RelationalExprState (Either RelationalError RelationalExpr)
436+applyStaticJoinElimination :: GraphRefRelationalExpr -> GraphRefSOptRelationalExprM GraphRefRelationalExpr
324437applyStaticJoinElimination expr@(Project attrNameSet (Join exprA exprB)) = do
325− relState <- ask
326− eProjType <- typeForRelationalExpr expr
327− eTypeA <- typeForRelationalExpr exprA
328− eTypeB <- typeForRelationalExpr exprB
329− case eProjType of
330− Left err -> pure (Left err)
331− Right projType ->
332− case eTypeA of
333− Left err -> pure (Left err)
334− Right typeA ->
335− case eTypeB of
336− Left err -> pure (Left err)
337− Right typeB -> do
338− let matchesProjectionAttributes
339− | attrNames projType `S.isSubsetOf` attrNames typeA =
340− Just ((exprA, typeA), (exprB, typeB))
341− | attrNames projType `S.isSubsetOf` attrNames typeB =
342− Just ((exprB, typeB), (exprA, typeA))
343− | otherwise =
344− Nothing
345− attrNames = A.attributeNameSet . attributes
346− case matchesProjectionAttributes of
347− Nothing -> -- this optimization does not apply
348− pure (Right expr)
349− Just ((joinedExpr, joinedType), (unjoinedExpr, _)) -> do
350− --scan inclusion dependencies for a foreign key relationship
351− incDeps <- inclusionDependencies . stateElemsContext <$> ask
352− let fkConstraint = foldM isFkConstraint False incDeps
353− --search for matching fk constraint
354− isFkConstraint acc (InclusionDependency (Project subattrNames subrv) (Project _ superrv)) =
355− case runReader (evalAttributeNames subattrNames expr) relState of
356− Left _ -> pure acc
357− Right subAttrNameSet ->
358− pure (acc || (joinedExpr == subrv &&
359− unjoinedExpr == superrv &&
360− -- the fk attribute is one of the projection attributes
361− A.attributeNamesContained subAttrNameSet (A.attributeNameSet (attributes joinedType))
438+ graph <- askGraph
439+ case inSameTransaction exprA exprB of
440+ -- the sub exprs are in different transactions or none at all, so we cannot extract inclusion dependencies across transaction boundaries
441+ Nothing -> pure expr
442+ Just marker -> do
443+ commonContext <- case marker of
444+ UncommittedContextMarker -> askContext
445+ TransactionMarker tid -> concreteDatabaseContext <$> lift (except (transactionForId tid graph))
446+ let typeForExpr e = lift $ except $ runGraphRefRelationalExprM gfEnv (typeForGraphRefRelationalExpr e)
447+ gfEnv = freshGraphRefRelationalExprEnv (Just commonContext) graph
448+
449+ projType <- typeForExpr expr
450+ typeA <- typeForExpr exprA
451+ typeB <- typeForExpr exprB
452+ let matchesProjectionAttributes
453+ | attrNames projType `S.isSubsetOf` attrNames typeA =
454+ Just ((exprA, typeA), (exprB, typeB))
455+ | attrNames projType `S.isSubsetOf` attrNames typeB =
456+ Just ((exprB, typeB), (exprA, typeA))
457+ | otherwise =
458+ Nothing
459+ attrNames = A.attributeNameSet . attributes
460+ case matchesProjectionAttributes of
461+ Nothing -> -- this optimization does not apply
462+ pure expr
463+ Just ((joinedExpr, joinedType), (unjoinedExpr, _)) -> do
464+ --lookup transaction
465+ --scan inclusion dependencies for a foreign key relationship
466+ let incDeps = inclusionDependencies commonContext
467+ fkConstraint = foldM isFkConstraint False incDeps
468+ --search for matching fk constraint
469+ isFkConstraint acc (InclusionDependency (Project subAttrNames subrv) (Project _ superrv)) = do
470+ let gfSubAttrNames = processM (processAttributeNames subAttrNames)
471+ gfSubRv = processM (processRelationalExpr subrv)
472+ gfSuperRv = processM (processRelationalExpr superrv)
473+ processM = runProcessExprM marker
474+ case runGraphRefRelationalExprM gfEnv (evalGraphRefAttributeNames gfSubAttrNames expr) of
475+ Left _ -> pure acc
476+ Right subAttrNameSet ->
477+ pure (acc || (joinedExpr == gfSubRv &&
478+ unjoinedExpr == gfSuperRv &&
479+ -- the fk attribute is one of the projection attributes
480+ A.attributeNamesContained subAttrNameSet (A.attributeNameSet (attributes joinedType))
362481 ))
363− isFkConstraint acc _ = pure acc
364− case fkConstraint of
365− Right True -> --join elimination optimization applies
366− applyStaticRelationalOptimization (Project attrNameSet joinedExpr)
367− Right False -> --join elimination optimization does not apply
368− pure (Right expr)
369− Left err ->
370− pure (Left err)
482+ isFkConstraint acc _ = pure acc
483+ case fkConstraint of
484+ Right True -> --join elimination optimization applies
485+ optimizeGraphRefRelationalExpr (Project attrNameSet joinedExpr)
486+ Right False -> --join elimination optimization does not apply
487+ pure expr
488+ Left err -> throwError err
371489
372−applyStaticJoinElimination expr = pure (Right expr)
490+applyStaticJoinElimination expr = pure expr
373491
374492--restriction collapse converts chained restrictions into (Restrict (And pred1 pred2 pred3...))
375493 --this optimization should be fairly uncontroversial- performing a tuple scan once is cheaper than twice- parallelization can still take place
376−applyStaticRestrictionCollapse :: RelationalExpr -> RelationalExpr
494+applyStaticRestrictionCollapse :: GraphRefRelationalExpr -> GraphRefRelationalExpr
377495applyStaticRestrictionCollapse expr =
378496 case expr of
379497 MakeRelationFromExprs _ _ -> expr
@@ -410,14 +528,14 @@ applyStaticRestrictionCollapse expr =
410528 andPreds = foldr (\(Restrict subpred _) acc -> AndPredicate acc subpred) firstPred (tail restrictions) in
411529 Restrict andPreds optFinalExpr
412530
413−sequentialRestrictions :: RelationalExpr -> [RelationalExpr]
531+sequentialRestrictions :: RelationalExprBase a -> [RelationalExprBase a]
414532sequentialRestrictions expr@(Restrict _ subexpr) = expr:sequentialRestrictions subexpr
415533sequentialRestrictions _ = []
416534
417535--restriction pushdown only really makes sense for tuple-oriented storage schemes where performing a restriction before projection can cut down on the intermediate storage needed to store the data before the projection
418536-- x{proj} where c1 -> (x where c1){proj} #project on fewer tuples
419537-- (x union y) where c -> (x where c) union (y where c) #with a selective restriction, fewer tuples will need to be joined
420−applyStaticRestrictionPushdown :: RelationalExpr -> RelationalExpr
538+applyStaticRestrictionPushdown :: GraphRefRelationalExpr -> GraphRefRelationalExpr
421539applyStaticRestrictionPushdown expr = case expr of
422540 MakeRelationFromExprs _ _ -> expr
423541 MakeStaticRelation _ _ -> expr
@@ -454,4 +572,7 @@ applyStaticRestrictionPushdown expr = case expr of
454572 Extend n sub ->
455573 Extend n (applyStaticRestrictionPushdown sub)
456574
457−
575+-- no optimizations available
576+optimizeDatabaseContextIOExpr :: GraphRefDatabaseContextIOExpr -> GraphRefSOptDatabaseContextExprM GraphRefDatabaseContextIOExpr
577+optimizeDatabaseContextIOExpr = pure
578+
src/lib/ProjectM36/TransGraphRelationalExpression.hs+133−135
@@ -1,182 +1,180 @@
1−{-# LANGUAGE TypeSynonymInstances, FlexibleInstances #-}
1+{-# LANGUAGE FlexibleInstances #-}
22{-# OPTIONS_GHC -fno-warn-orphans #-}
33--really, a better name for this module could be "TransTransactionGraphRelationalExpr", but that name is too long
44module ProjectM36.TransGraphRelationalExpression where
55import ProjectM36.Base
66import ProjectM36.TransactionGraph
7−import ProjectM36.Transaction
8−import ProjectM36.RelationalExpression
97import ProjectM36.Error
10−import ProjectM36.Tuple
11−import ProjectM36.AtomType
128import qualified Data.Map as M
139import Control.Monad.Trans.Reader
14−import Data.Binary
10+import Control.Monad.Trans.Class
11+import Control.Monad.Trans.Except
12+import Data.Functor.Identity
1513
1614-- | The TransGraphRelationalExpression is equivalent to a relational expression except that relation variables can reference points in the transaction graph (at previous points in time).
1715type TransGraphRelationalExpr = RelationalExprBase TransactionIdLookup
1816
19−instance Binary TransGraphRelationalExpr
20−
2117type TransGraphAttributeNames = AttributeNamesBase TransactionIdLookup
2218
23−instance Binary TransGraphAttributeNames
24−
2519type TransGraphExtendTupleExpr = ExtendTupleExprBase TransactionIdLookup
2620
27−instance Binary TransGraphExtendTupleExpr
28−
2921type TransGraphTupleExpr = TupleExprBase TransactionIdLookup
3022
31−instance Binary TransGraphTupleExpr
23+type TransGraphTupleExprs = TupleExprsBase TransactionIdLookup
3224
3325type TransGraphRestrictionPredicateExpr = RestrictionPredicateExprBase TransactionIdLookup
3426
35−instance Binary TransGraphRestrictionPredicateExpr
36−
3727type TransGraphAtomExpr = AtomExprBase TransactionIdLookup
3828
39−instance Binary TransGraphAtomExpr
40−
4129type TransGraphAttributeExpr = AttributeExprBase TransactionIdLookup
4230
31+type TransGraphWithNameExpr = WithNameExprBase TransactionIdLookup
32+
33+newtype TransGraphEvalEnv = TransGraphEvalEnv {
34+ tge_graph :: TransactionGraph
35+ }
36+
37+type TransGraphEvalMonad a = ReaderT TransGraphEvalEnv (ExceptT RelationalError Identity) a
38+
39+process :: TransGraphEvalEnv -> TransGraphRelationalExpr -> Either RelationalError GraphRefRelationalExpr
40+process env texpr = runIdentity (runExceptT (runReaderT (processTransGraphRelationalExpr texpr) env))
41+
42+liftE :: Either RelationalError a -> TransGraphEvalMonad a
43+liftE = lift . except
44+
45+askGraph :: TransGraphEvalMonad TransactionGraph
46+askGraph = tge_graph <$> ask
47+
48+findTransId :: TransactionIdLookup -> TransGraphEvalMonad GraphRefTransactionMarker
49+findTransId tlook = TransactionMarker . transactionId <$> findTrans tlook
50+
51+findTrans :: TransactionIdLookup -> TransGraphEvalMonad Transaction
52+findTrans tlook = do
53+ graph <- askGraph
54+ liftE $ lookupTransaction graph tlook
55+
4356-- OUTDATED a previous attempt at this function attempted to convert TransGraphRelationalExpr to RelationalExpr by resolving the transaction lookups. However, there is no way to resolve a FunctionAtomExpr to an Atom without fully evaluating the higher levels (TupleExpr, etc.). An anonymous function expression cannot be serialized, so that workaround is out. Still, I suspect we can reuse the existing static optimizer logic to work on both structures. The current conversion reduces the chance of whole-query optimization due to full-evaluation on top of full-evaluation, so this function would benefit from some re-design.
44−evalTransGraphRelationalExpr :: TransGraphRelationalExpr -> TransactionGraph -> Either RelationalError RelationalExpr
45−evalTransGraphRelationalExpr (MakeRelationFromExprs mAttrExprs tupleExprs) graph = do
46− tupleExprs' <- mapM (evalTransGraphTupleExpr graph) tupleExprs
57+processTransGraphRelationalExpr :: TransGraphRelationalExpr -> TransGraphEvalMonad GraphRefRelationalExpr
58+processTransGraphRelationalExpr (MakeRelationFromExprs mAttrExprs tupleExprs) = do
59+ tupleExprs' <- processTransGraphTupleExprs tupleExprs
4760 case mAttrExprs of
4861 Nothing -> pure (MakeRelationFromExprs Nothing tupleExprs')
4962 Just attrExprs -> do
50− attrExprs' <- mapM (evalTransGraphAttributeExpr graph) attrExprs
63+ attrExprs' <- mapM processTransGraphAttributeExpr attrExprs
5164 pure (MakeRelationFromExprs (Just attrExprs') tupleExprs')
52−evalTransGraphRelationalExpr (MakeStaticRelation attrs tupSet) _ = pure (MakeStaticRelation attrs tupSet)
53−evalTransGraphRelationalExpr (ExistingRelation rel) _ = pure (ExistingRelation rel)
54−evalTransGraphRelationalExpr (RelationVariable rvname transLookup) graph = do
55− trans <- lookupTransaction graph transLookup
56− rel <- runReader (evalRelationalExpr (RelationVariable rvname ())) (RelationalExprStateElems (concreteDatabaseContext trans))
57− pure (ExistingRelation rel)
58−evalTransGraphRelationalExpr (Project transAttrNames expr) graph = do
59− expr' <- evalTransGraphRelationalExpr expr graph
60− attrNames <- evalTransAttributeNames transAttrNames graph
61− pure (Project attrNames expr')
62−evalTransGraphRelationalExpr (Union exprA exprB) graph = do
63− exprA' <- evalTransGraphRelationalExpr exprA graph
64− exprB' <- evalTransGraphRelationalExpr exprB graph
65− pure (Union exprA' exprB')
66−evalTransGraphRelationalExpr (Join exprA exprB) graph = do
67− exprA' <- evalTransGraphRelationalExpr exprA graph
68− exprB' <- evalTransGraphRelationalExpr exprB graph
69− pure (Join exprA' exprB')
70−evalTransGraphRelationalExpr (Rename attrName1 attrName2 expr) graph = do
71− let expr' = evalTransGraphRelationalExpr expr graph
72− Rename attrName1 attrName2 <$> expr'
73−evalTransGraphRelationalExpr (Difference exprA exprB) graph = do
74− exprA' <- evalTransGraphRelationalExpr exprA graph
75− exprB' <- evalTransGraphRelationalExpr exprB graph
76− pure (Difference exprA' exprB')
77−evalTransGraphRelationalExpr (Group transAttrNames attrName expr) graph = do
78− expr' <- evalTransGraphRelationalExpr expr graph
79− attrNames <- evalTransAttributeNames transAttrNames graph
80− pure (Group attrNames attrName expr')
81−evalTransGraphRelationalExpr (Ungroup attrName expr) graph = do
82− let expr' = evalTransGraphRelationalExpr expr graph
83− Ungroup attrName <$> expr'
84−evalTransGraphRelationalExpr (Restrict predicateExpr expr) graph = do
85− expr' <- evalTransGraphRelationalExpr expr graph
86− predicateExpr' <- evalTransGraphRestrictionPredicateExpr predicateExpr graph
87− pure (Restrict predicateExpr' expr')
88−evalTransGraphRelationalExpr (Equals exprA exprB) graph = do
89− exprA' <- evalTransGraphRelationalExpr exprA graph
90− exprB' <- evalTransGraphRelationalExpr exprB graph
65+processTransGraphRelationalExpr (MakeStaticRelation attrs tupSet) = pure (MakeStaticRelation attrs tupSet)
66+processTransGraphRelationalExpr (ExistingRelation rel) = pure (ExistingRelation rel)
67+processTransGraphRelationalExpr (RelationVariable rvname transLookup) =
68+ RelationVariable rvname <$> findTransId transLookup
69+processTransGraphRelationalExpr (Project transAttrNames expr) =
70+ Project <$> processTransGraphAttributeNames transAttrNames <*> processTransGraphRelationalExpr expr
71+processTransGraphRelationalExpr (Union exprA exprB) =
72+ Union <$> processTransGraphRelationalExpr exprA <*> processTransGraphRelationalExpr exprB
73+processTransGraphRelationalExpr (Join exprA exprB) =
74+ Join <$> processTransGraphRelationalExpr exprA <*> processTransGraphRelationalExpr exprB
75+processTransGraphRelationalExpr (Rename attrName1 attrName2 expr) =
76+ Rename attrName1 attrName2 <$> processTransGraphRelationalExpr expr
77+processTransGraphRelationalExpr (Difference exprA exprB) =
78+ Difference <$> processTransGraphRelationalExpr exprA <*> processTransGraphRelationalExpr exprB
79+processTransGraphRelationalExpr (Group transAttrNames attrName expr) =
80+ Group <$>
81+ processTransGraphAttributeNames transAttrNames <*>
82+ pure attrName <*>
83+ processTransGraphRelationalExpr expr
84+processTransGraphRelationalExpr (Ungroup attrName expr) =
85+ Ungroup attrName <$> processTransGraphRelationalExpr expr
86+processTransGraphRelationalExpr (Restrict predicateExpr expr) =
87+ Restrict <$> evalTransGraphRestrictionPredicateExpr predicateExpr <*>
88+ processTransGraphRelationalExpr expr
89+processTransGraphRelationalExpr (Equals exprA exprB) = do
90+ exprA' <- processTransGraphRelationalExpr exprA
91+ exprB' <- processTransGraphRelationalExpr exprB
9192 pure (Equals exprA' exprB')
92−evalTransGraphRelationalExpr (NotEquals exprA exprB) graph = do
93− exprA' <- evalTransGraphRelationalExpr exprA graph
94− exprB' <- evalTransGraphRelationalExpr exprB graph
93+processTransGraphRelationalExpr (NotEquals exprA exprB) = do
94+ exprA' <- processTransGraphRelationalExpr exprA
95+ exprB' <- processTransGraphRelationalExpr exprB
9596 pure (NotEquals exprA' exprB')
96−evalTransGraphRelationalExpr (Extend extendExpr expr) graph = do
97− extendExpr' <- evalTransGraphExtendTupleExpr extendExpr graph
98− expr' <- evalTransGraphRelationalExpr expr graph
97+processTransGraphRelationalExpr (Extend extendExpr expr) = do
98+ extendExpr' <- processTransGraphExtendTupleExpr extendExpr
99+ expr' <- processTransGraphRelationalExpr expr
99100 pure (Extend extendExpr' expr')
100−evalTransGraphRelationalExpr (With views expr) graph = do
101− evaldViews <- mapM (\(vname, vexpr) -> do
102− vexpr' <- evalTransGraphRelationalExpr vexpr graph
103− pure (vname, vexpr')
101+processTransGraphRelationalExpr (With views expr) = do
102+ evaldViews <- mapM (\(wnexpr, vexpr) -> do
103+ wnexpr' <- processTransGraphWithNameExpr wnexpr
104+ vexpr' <- processTransGraphRelationalExpr vexpr
105+ pure (wnexpr', vexpr')
104106 ) views
105− expr' <- evalTransGraphRelationalExpr expr graph
107+ expr' <- processTransGraphRelationalExpr expr
106108 pure (With evaldViews expr')
107−
108−evalTransGraphTupleExpr :: TransactionGraph -> TransGraphTupleExpr -> Either RelationalError TupleExpr
109−evalTransGraphTupleExpr graph (TupleExpr attrMap) = do
109+
110+processTransGraphTupleExprs :: TransGraphTupleExprs -> TransGraphEvalMonad GraphRefTupleExprs
111+processTransGraphTupleExprs (TupleExprs marker texprs) =
112+ TupleExprs <$> findTransId marker <*> mapM processTransGraphTupleExpr texprs
113+
114+processTransGraphTupleExpr :: TransGraphTupleExpr -> TransGraphEvalMonad GraphRefTupleExpr
115+processTransGraphTupleExpr (TupleExpr attrMap) = do
110116 let attrAssoc = mapM (\(attrName, atomExpr) -> do
111− aExpr <- evalTransGraphAtomExpr graph atomExpr
117+ aExpr <- processTransGraphAtomExpr atomExpr
112118 pure (attrName, aExpr)
113119 ) (M.toList attrMap)
114120 TupleExpr . M.fromList <$> attrAssoc
115121
116−evalTransGraphAtomExpr :: TransactionGraph -> TransGraphAtomExpr -> Either RelationalError AtomExpr
117−evalTransGraphAtomExpr _ (AttributeAtomExpr aname) = pure $ AttributeAtomExpr aname
118−evalTransGraphAtomExpr _ (NakedAtomExpr atom) = pure $ NakedAtomExpr atom
119−evalTransGraphAtomExpr graph (FunctionAtomExpr funcName args tLookup) = do
120− trans <- lookupTransaction graph tLookup
121− --I can't return a FunctionAtomExpr because the function needs to be resolved at a specific context
122− args' <- mapM (evalTransGraphAtomExpr graph) args
123− atom <- runReader (evalAtomExpr emptyTuple (FunctionAtomExpr funcName args' ())) (RelationalExprStateElems (concreteDatabaseContext trans))
124− pure (NakedAtomExpr atom)
125−evalTransGraphAtomExpr graph (RelationAtomExpr expr) = do
126− let expr' = evalTransGraphRelationalExpr expr graph
127− RelationAtomExpr <$> expr'
128−evalTransGraphAtomExpr graph (ConstructedAtomExpr dConsName args tLookup) = do
129− trans <- lookupTransaction graph tLookup
130− args' <- mapM (evalTransGraphAtomExpr graph) args
131− atom <- runReader (evalAtomExpr emptyTuple (ConstructedAtomExpr dConsName args' ())) (RelationalExprStateElems (concreteDatabaseContext trans))
132− pure (NakedAtomExpr atom)
133−
134−evalTransGraphRestrictionPredicateExpr :: TransGraphRestrictionPredicateExpr -> TransactionGraph -> Either RelationalError RestrictionPredicateExpr
135−evalTransGraphRestrictionPredicateExpr TruePredicate _ = pure TruePredicate
136−evalTransGraphRestrictionPredicateExpr (AndPredicate exprA exprB) graph = do
137− exprA' <- evalTransGraphRestrictionPredicateExpr exprA graph
138− exprB' <- evalTransGraphRestrictionPredicateExpr exprB graph
122+processTransGraphAtomExpr :: TransGraphAtomExpr -> TransGraphEvalMonad GraphRefAtomExpr
123+processTransGraphAtomExpr (AttributeAtomExpr aname) = pure $ AttributeAtomExpr aname
124+processTransGraphAtomExpr (NakedAtomExpr atom) = pure $ NakedAtomExpr atom
125+processTransGraphAtomExpr (FunctionAtomExpr funcName args tLookup) =
126+ FunctionAtomExpr funcName <$> mapM processTransGraphAtomExpr args <*> findTransId tLookup
127+processTransGraphAtomExpr (RelationAtomExpr expr) =
128+ RelationAtomExpr <$> processTransGraphRelationalExpr expr
129+processTransGraphAtomExpr (ConstructedAtomExpr dConsName args tLookup) =
130+ ConstructedAtomExpr dConsName <$> mapM processTransGraphAtomExpr args <*> findTransId tLookup
131+evalTransGraphRestrictionPredicateExpr :: TransGraphRestrictionPredicateExpr -> TransGraphEvalMonad GraphRefRestrictionPredicateExpr
132+evalTransGraphRestrictionPredicateExpr TruePredicate = pure TruePredicate
133+evalTransGraphRestrictionPredicateExpr (AndPredicate exprA exprB) = do
134+ exprA' <- evalTransGraphRestrictionPredicateExpr exprA
135+ exprB' <- evalTransGraphRestrictionPredicateExpr exprB
139136 pure (AndPredicate exprA' exprB')
140−evalTransGraphRestrictionPredicateExpr (OrPredicate exprA exprB) graph = do
141− exprA' <- evalTransGraphRestrictionPredicateExpr exprA graph
142− exprB' <- evalTransGraphRestrictionPredicateExpr exprB graph
137+evalTransGraphRestrictionPredicateExpr (OrPredicate exprA exprB) = do
138+ exprA' <- evalTransGraphRestrictionPredicateExpr exprA
139+ exprB' <- evalTransGraphRestrictionPredicateExpr exprB
143140 pure (OrPredicate exprA' exprB')
144−evalTransGraphRestrictionPredicateExpr (NotPredicate expr) graph = do
145− let expr' = evalTransGraphRestrictionPredicateExpr expr graph
141+evalTransGraphRestrictionPredicateExpr (NotPredicate expr) = do
142+ let expr' = evalTransGraphRestrictionPredicateExpr expr
146143 NotPredicate <$> expr'
147−evalTransGraphRestrictionPredicateExpr (RelationalExprPredicate expr) graph = do
148− let expr' = evalTransGraphRelationalExpr expr graph
144+evalTransGraphRestrictionPredicateExpr (RelationalExprPredicate expr) = do
145+ let expr' = processTransGraphRelationalExpr expr
149146 RelationalExprPredicate <$> expr'
150−evalTransGraphRestrictionPredicateExpr (AtomExprPredicate expr) graph = do
151− let expr' = evalTransGraphAtomExpr graph expr
147+evalTransGraphRestrictionPredicateExpr (AtomExprPredicate expr) = do
148+ let expr' = processTransGraphAtomExpr expr
152149 AtomExprPredicate <$> expr'
153−evalTransGraphRestrictionPredicateExpr (AttributeEqualityPredicate attrName expr) graph = do
154− let expr' = evalTransGraphAtomExpr graph expr
150+evalTransGraphRestrictionPredicateExpr (AttributeEqualityPredicate attrName expr) = do
151+ let expr' = processTransGraphAtomExpr expr
155152 AttributeEqualityPredicate attrName <$> expr'
156153
157−evalTransGraphExtendTupleExpr :: TransGraphExtendTupleExpr -> TransactionGraph -> Either RelationalError ExtendTupleExpr
158−evalTransGraphExtendTupleExpr (AttributeExtendTupleExpr attrName expr) graph = do
159− let expr' = evalTransGraphAtomExpr graph expr
160− AttributeExtendTupleExpr attrName <$> expr'
161−
162−evalTransGraphAttributeExpr :: TransactionGraph -> TransGraphAttributeExpr -> Either RelationalError AttributeExpr
163−evalTransGraphAttributeExpr graph (AttributeAndTypeNameExpr attrName tCons tLookup) = do
164− trans <- lookupTransaction graph tLookup
165− aType <- atomTypeForTypeConstructor tCons (typeConstructorMapping (concreteDatabaseContext trans)) M.empty
166− pure (NakedAttributeExpr (Attribute attrName aType))
167−evalTransGraphAttributeExpr _ (NakedAttributeExpr attr) = pure (NakedAttributeExpr attr)
168−
169−evalTransAttributeNames :: TransGraphAttributeNames -> TransactionGraph -> Either RelationalError AttributeNames
170−evalTransAttributeNames (AttributeNames names) _ = Right (AttributeNames names)
171−evalTransAttributeNames (InvertedAttributeNames names) _ = Right (InvertedAttributeNames names)
172−evalTransAttributeNames (UnionAttributeNames namesA namesB) graph = do
173− nA <- evalTransAttributeNames namesA graph
174− nB <- evalTransAttributeNames namesB graph
175− Right (UnionAttributeNames nA nB)
176−evalTransAttributeNames (IntersectAttributeNames namesA namesB) graph = do
177− nA <- evalTransAttributeNames namesA graph
178− nB <- evalTransAttributeNames namesB graph
179− Right (IntersectAttributeNames nA nB)
180−evalTransAttributeNames (RelationalExprAttributeNames expr) graph = do
181− evaldExpr <- evalTransGraphRelationalExpr expr graph
182− Right (RelationalExprAttributeNames evaldExpr)
154+processTransGraphExtendTupleExpr :: TransGraphExtendTupleExpr -> TransGraphEvalMonad GraphRefExtendTupleExpr
155+processTransGraphExtendTupleExpr (AttributeExtendTupleExpr attrName expr) =
156+ AttributeExtendTupleExpr attrName <$> processTransGraphAtomExpr expr
157+
158+processTransGraphAttributeExpr :: TransGraphAttributeExpr -> TransGraphEvalMonad GraphRefAttributeExpr
159+processTransGraphAttributeExpr (AttributeAndTypeNameExpr attrName tCons tLookup) =
160+ AttributeAndTypeNameExpr attrName tCons <$> findTransId tLookup
161+processTransGraphAttributeExpr (NakedAttributeExpr attr) = pure (NakedAttributeExpr attr)
162+
163+processTransGraphAttributeNames :: TransGraphAttributeNames -> TransGraphEvalMonad GraphRefAttributeNames
164+processTransGraphAttributeNames (AttributeNames names) = pure (AttributeNames names)
165+processTransGraphAttributeNames (InvertedAttributeNames names) = pure (InvertedAttributeNames names)
166+processTransGraphAttributeNames (UnionAttributeNames namesA namesB) = do
167+ nA <- processTransGraphAttributeNames namesA
168+ nB <- processTransGraphAttributeNames namesB
169+ pure (UnionAttributeNames nA nB)
170+processTransGraphAttributeNames (IntersectAttributeNames namesA namesB) = do
171+ nA <- processTransGraphAttributeNames namesA
172+ nB <- processTransGraphAttributeNames namesB
173+ pure (IntersectAttributeNames nA nB)
174+processTransGraphAttributeNames (RelationalExprAttributeNames expr) = do
175+ evaldExpr <- processTransGraphRelationalExpr expr
176+ pure (RelationalExprAttributeNames evaldExpr)
177+
178+processTransGraphWithNameExpr :: TransGraphWithNameExpr -> TransGraphEvalMonad GraphRefWithNameExpr
179+processTransGraphWithNameExpr (WithNameExpr rvname tlookup) =
180+ WithNameExpr rvname <$> findTransId tlookup
src/lib/ProjectM36/Transaction.hs+24−16
@@ -3,28 +3,24 @@ import ProjectM36.Base
33import qualified Data.Set as S
44import qualified Data.UUID as U
55import Data.Time.Clock
6+import qualified Data.List.NonEmpty as NE
67
7−transactionTimestamp :: Transaction -> UTCTime
8−transactionTimestamp (Transaction _ (TransactionInfo _ _ stamp) _) = stamp
9−transactionTimestamp (Transaction _ (MergeTransactionInfo _ _ _ stamp) _) = stamp
8+parentIds :: Transaction -> S.Set TransactionId
9+parentIds (Transaction _ tinfo _) = S.fromList (NE.toList (parents tinfo))
1010
11−transactionParentIds :: Transaction -> S.Set TransactionId
12−transactionParentIds (Transaction _ (TransactionInfo pId _ _) _) = S.singleton pId
13−transactionParentIds (Transaction _ (MergeTransactionInfo pId1 pId2 _ _) _) = S.fromList [pId1, pId2]
11+rootParent :: TransactionParents
12+rootParent = singleParent U.nil
1413
15−transactionChildIds :: Transaction -> S.Set TransactionId
16−transactionChildIds (Transaction _ (TransactionInfo _ children _) _) = children
17−transactionChildIds (Transaction _ (MergeTransactionInfo _ _ children _) _) = children
18−
19−-- | Create a new transaction which is identical to the original except that a new set of child transaction ids is added.
20−transactionSetChildren :: Transaction -> S.Set TransactionId -> Transaction
21−transactionSetChildren t@(Transaction _ (TransactionInfo pId _ stamp) schemas') childIds = Transaction (transactionId t) (TransactionInfo pId childIds stamp) schemas'
22−transactionSetChildren t@(Transaction _ (MergeTransactionInfo pId1 pId2 _ stamp) schemas') childIds = Transaction (transactionId t) (MergeTransactionInfo pId1 pId2 childIds stamp) schemas'
14+singleParent :: TransactionId -> TransactionParents
15+singleParent tid = tid NE.:| []
2316
2417-- | Return the same transaction but referencing only the specific child transactions. This is useful when traversing a graph and returning a subgraph. This doesn't filter parent transactions because it assumes a head-to-root traversal.
2518filterTransactionInfoTransactions :: S.Set TransactionId -> TransactionInfo -> TransactionInfo
26−filterTransactionInfoTransactions filterIds (TransactionInfo parentId childIds stamp) = TransactionInfo (filterParent parentId filterIds) (S.intersection childIds filterIds) stamp
27−filterTransactionInfoTransactions filterIds (MergeTransactionInfo parentIdA parentIdB childIds stamp) = MergeTransactionInfo (filterParent parentIdA filterIds) (filterParent parentIdB filterIds) (S.intersection childIds filterIds) stamp
19+filterTransactionInfoTransactions filterIds tinfo =
20+ tinfo { parents = case
21+ NE.filter (`S.member` filterIds) (parents tinfo) of
22+ [] -> rootParent
23+ xs -> NE.fromList xs}
2824
2925filterParent :: TransactionId -> S.Set TransactionId -> TransactionId
3026filterParent parentId validIds = if S.member parentId validIds then parentId else U.nil
@@ -44,3 +40,15 @@ schemas (Transaction _ _ schemas') = schemas'
4440-- | Returns all subschemas which are isomorphic or sub-isomorphic to the concrete schema.
4541subschemas :: Transaction -> Subschemas
4642subschemas (Transaction _ _ (Schemas _ sschemas)) = sschemas
43+
44+fresh :: TransactionId -> UTCTime -> Schemas -> Transaction
45+fresh freshId stamp' = Transaction freshId tinfo
46+ where
47+ tinfo = TransactionInfo {parents = rootParent,
48+ stamp = stamp',
49+ merkleHash = mempty
50+ }
51+
52+timestamp :: Transaction -> UTCTime
53+timestamp (Transaction _ tinfo _) = stamp tinfo
54+
src/lib/ProjectM36/Transaction/Persist.hs+61−52
@@ -1,3 +1,4 @@
1+{-# LANGUAGE TypeApplications #-}
12module ProjectM36.Transaction.Persist where
23import ProjectM36.Base
34import ProjectM36.Error
@@ -7,20 +8,19 @@ import ProjectM36.AtomFunction
78import ProjectM36.Persist (writeBSFileSync, DiskSync, renameSync)
89import qualified Data.Map as M
910import qualified Data.HashSet as HS
10−import qualified Data.Binary as B
11−--import qualified Data.ByteString as BS
1211import System.FilePath
1312import System.Directory
1413import qualified Data.Text as T
1514import Control.Monad
1615import ProjectM36.ScriptSession
1716import ProjectM36.AtomFunctions.Basic (precompiledAtomFunctions)
18−import Control.Exception
17+import Codec.Winery
18+
19+#ifdef PM36_HASKELL_SCRIPTING
1920import GHC
21+import Control.Exception
2022import GHC.Paths
21−import Codec.Compression.GZip
22−import qualified Data.ByteString as BS
23−import qualified Data.ByteString.Lazy as BSL
23+#endif
2424
2525getDirectoryNames :: FilePath -> IO [FilePath]
2626getDirectoryNames path =
@@ -36,8 +36,8 @@ transactionDir dbdir transId = dbdir </> show transId
3636transactionInfoPath :: FilePath -> FilePath
3737transactionInfoPath transdir = transdir </> "info"
3838
39−relvarsDir :: FilePath -> FilePath
40−relvarsDir transdir = transdir </> "relvars"
39+relvarsPath :: FilePath -> FilePath
40+relvarsPath transdir = transdir </> "relvars"
4141
4242incDepsDir :: FilePath -> FilePath
4343incDepsDir transdir = transdir </> "incdeps"
@@ -62,7 +62,7 @@ readTransaction dbdir transId mScriptSession = do
6262 return $ Left $ MissingTransactionError transId
6363 else do
6464 relvars <- readRelVars transDir
65− transInfo <- B.decodeFile (transactionInfoPath transDir)
65+ transInfo <- readFileDeserialise (transactionInfoPath transDir)
6666 incDeps <- readIncDeps transDir
6767 typeCons <- readTypeConstructorMapping transDir
6868 sschemas <- readSubschemas transDir
@@ -85,76 +85,75 @@ writeTransaction sync dbdir trans = do
8585 transDirExists <- doesDirectoryExist finalTransDir
8686 unless transDirExists $ do
8787 --create sub directories
88− mapM_ createDirectory [tempTransDir, relvarsDir tempTransDir, incDepsDir tempTransDir, dbcFuncsDir tempTransDir]
88+ mapM_ createDirectory [tempTransDir, incDepsDir tempTransDir, dbcFuncsDir tempTransDir]
8989 writeRelVars sync tempTransDir (relationVariables context)
9090 writeIncDeps sync tempTransDir (inclusionDependencies context)
9191 writeAtomFuncs sync tempTransDir (atomFunctions context)
9292 writeDBCFuncs sync tempTransDir (dbcFunctions context)
9393 writeTypeConstructorMapping sync tempTransDir (typeConstructorMapping context)
9494 writeSubschemas sync tempTransDir (subschemas trans)
95− B.encodeFile (transactionInfoPath tempTransDir) (transactionInfo trans)
95+ writeFileSerialise (transactionInfoPath tempTransDir) (transactionInfo trans)
9696 --move the temp directory to final location
9797 renameSync sync tempTransDir finalTransDir
98−
99−writeRelVar :: DiskSync -> FilePath -> (RelVarName, Relation) -> IO ()
100−writeRelVar sync transDir (relvarName, rel) = do
101− let relvarPath = relvarsDir transDir </> T.unpack relvarName
102− writeBSFileSync sync relvarPath (compress (B.encode rel))
103−
104−writeRelVars :: DiskSync -> FilePath -> M.Map RelVarName Relation -> IO ()
105−writeRelVars sync transDir relvars = mapM_ (writeRelVar sync transDir) $ M.toList relvars
106−
107−readRelVars :: FilePath -> IO (M.Map RelVarName Relation)
108−readRelVars transDir = do
109− let relvarsPath = relvarsDir transDir
110− relvarNames <- getDirectoryNames relvarsPath
111− let relvars = mapM (\name -> do
112− rel <- B.decode . decompress . BSL.fromStrict <$> BS.readFile (relvarsPath </> name)
113− return (T.pack name, rel)) relvarNames
114− M.fromList <$> relvars
98+
99+writeRelVars :: DiskSync -> FilePath -> RelationVariables -> IO ()
100+writeRelVars sync transDir relvars = do
101+ let path = relvarsPath transDir
102+ writeBSFileSync sync path (serialise relvars)
103+
104+readRelVars :: FilePath -> IO RelationVariables
105+readRelVars transDir =
106+ readFileDeserialise (relvarsPath transDir)
115107
116108writeAtomFuncs :: DiskSync -> FilePath -> AtomFunctions -> IO ()
117109writeAtomFuncs sync transDir funcs = do
118110 let atomFuncPath = atomFuncsPath transDir
119− writeBSFileSync sync atomFuncPath (B.encode $ map (\f -> (atomFuncType f, atomFuncName f, atomFunctionScript f)) (HS.toList funcs))
111+ writeBSFileSync sync atomFuncPath (serialise $ map (\f -> (atomFuncType f, atomFuncName f, atomFunctionScript f)) (HS.toList funcs))
120112
121113--all the atom functions are in one file
122114readAtomFuncs :: FilePath -> Maybe ScriptSession -> IO AtomFunctions
123115readAtomFuncs transDir mScriptSession = do
124− atomFuncsList <- B.decodeFile (atomFuncsPath transDir)
116+ atomFuncsList <- readFileDeserialise (atomFuncsPath transDir)
125117 --only Haskell script functions can be serialized
126118 --we always return the pre-compiled functions
127119 funcs <- mapM (\(funcType, funcName, mFuncScript) -> loadAtomFunc precompiledAtomFunctions mScriptSession funcName funcType mFuncScript) atomFuncsList
128120 pure (HS.union precompiledAtomFunctions (HS.fromList funcs))
129121
130122loadAtomFunc :: AtomFunctions -> Maybe ScriptSession -> AtomFunctionName -> [AtomType] -> Maybe AtomFunctionBodyScript -> IO AtomFunction
131−loadAtomFunc precompiledFuncs mScriptSession funcName funcType mFuncScript = case mFuncScript of
123+loadAtomFunc precompiledFuncs _mScriptSession funcName _funcType mFuncScript = case mFuncScript of
132124 --handle pre-compiled case- pull it from the precompiled list
133125 Nothing -> case atomFunctionForName funcName precompiledFuncs of
134126 --WARNING: possible landmine here if we remove a precompiled atom function in the future, then the transaction cannot be restored
135127 Left _ -> error ("expected precompiled atom function: " ++ T.unpack funcName)
136128 Right realFunc -> pure realFunc
137129 --handle a real Haskell scripted function- compile and load
138− Just funcScript ->
139− case mScriptSession of
130+ Just _funcScript ->
131+#ifdef PM36_HASKELL_SCRIPTING
132+ case _mScriptSession of
140133 Nothing -> error "attempted to read serialized AtomFunction without scripting enabled"
141134 Just scriptSession -> do
142135 --risk of GHC exception during compilation here
143136 eCompiledScript <- runGhc (Just libdir) $ do
144137 setSession (hscEnv scriptSession)
145− compileScript (atomFunctionBodyType scriptSession) funcScript
138+ compileScript (atomFunctionBodyType scriptSession) _funcScript
146139 case eCompiledScript of
147140 Left err -> throwIO err
148141 Right compiledScript -> pure AtomFunction { atomFuncName = funcName,
149− atomFuncType = funcType,
150− atomFuncBody = AtomFunctionBody (Just funcScript) compiledScript }
142+ atomFuncType = _funcType,
143+ atomFuncBody = AtomFunctionBody (Just _funcScript) compiledScript }
144+#else
145+ error "Haskell scripting is disabled"
146+#endif
151147
152148--if the script session is enabled, compile the script, otherwise, hard error!
153149
154150readAtomFunc :: FilePath -> AtomFunctionName -> Maybe ScriptSession -> AtomFunctions -> IO AtomFunction
151+#if !defined(PM36_HASKELL_SCRIPTING)
152+readAtomFunc _ _ _ _ = error "Haskell scripting is disabled"
153+#else
155154readAtomFunc transDir funcName mScriptSession precompiledFuncs = do
156155 let atomFuncPath = atomFuncsPath transDir
157− (funcType, mFuncScript) <- B.decodeFile atomFuncPath
156+ (funcType, mFuncScript) <- readFileDeserialise @([AtomType],Maybe T.Text) atomFuncPath
158157 case mFuncScript of
159158 --handle pre-compiled case- pull it from the precompiled list
160159 Nothing -> case atomFunctionForName funcName precompiledFuncs of
@@ -162,7 +161,8 @@ readAtomFunc transDir funcName mScriptSession precompiledFuncs = do
162161 Left _ -> error ("expected precompiled atom function: " ++ T.unpack funcName)
163162 Right realFunc -> pure realFunc
164163 --handle a real Haskell scripted function- compile and load
165− Just funcScript ->
164+ Just funcScript ->
165+
166166 case mScriptSession of
167167 Nothing -> error "attempted to read serialized AtomFunction without scripting enabled"
168168 Just scriptSession -> do
@@ -175,6 +175,7 @@ readAtomFunc transDir funcName mScriptSession precompiledFuncs = do
175175 Right compiledScript -> pure AtomFunction { atomFuncName = funcName,
176176 atomFuncType = funcType,
177177 atomFuncBody = AtomFunctionBody (Just funcScript) compiledScript }
178+#endif
178179
179180
180181writeDBCFuncs :: DiskSync -> FilePath -> DatabaseContextFunctions -> IO ()
@@ -183,7 +184,7 @@ writeDBCFuncs sync transDir funcs = mapM_ (writeDBCFunc sync transDir) (HS.toLis
183184writeDBCFunc :: DiskSync -> FilePath -> DatabaseContextFunction -> IO ()
184185writeDBCFunc sync transDir func = do
185186 let dbcFuncPath = dbcFuncsDir transDir </> T.unpack (dbcFuncName func)
186− writeBSFileSync sync dbcFuncPath (B.encode (dbcFuncType func, databaseContextFunctionScript func))
187+ writeBSFileSync sync dbcFuncPath (serialise (dbcFuncType func, databaseContextFunctionScript func))
187188
188189readDBCFuncs :: FilePath -> Maybe ScriptSession -> IO DatabaseContextFunctions
189190readDBCFuncs transDir mScriptSession = do
@@ -193,30 +194,38 @@ readDBCFuncs transDir mScriptSession = do
193194 let funcs = mapM ((\name -> readDBCFunc transDir name mScriptSession precompiledDatabaseContextFunctions) . T.pack) funcNames
194195 HS.union basicDatabaseContextFunctions . HS.fromList <$> funcs
195196
196−readDBCFunc :: FilePath -> DatabaseContextFunctionName -> Maybe ScriptSession -> DatabaseContextFunctions -> IO DatabaseContextFunction
197+readDBCFunc :: FilePath -> DatabaseContextFunctionName -> Maybe ScriptSession -> DatabaseContextFunctions -> IO DatabaseContextFunction
198+#if !defined(PM36_HASKELL_SCRIPTING)
199+readDBCFunc transDir funcName _ precompiledFuncs = do
200+#else
197201readDBCFunc transDir funcName mScriptSession precompiledFuncs = do
202+#endif
198203 let dbcFuncPath = dbcFuncsDir transDir </> T.unpack funcName
199− (funcType, mFuncScript) <- B.decodeFile dbcFuncPath
204+ (_funcType, mFuncScript) <- readFileDeserialise @([AtomType], Maybe T.Text) dbcFuncPath
200205 case mFuncScript of
201206 Nothing -> case databaseContextFunctionForName funcName precompiledFuncs of
202207 Left _ -> error ("expected precompiled dbc function: " ++ T.unpack funcName)
203208 Right realFunc -> pure realFunc --return precompiled function
204− Just funcScript ->
209+ Just _funcScript ->
210+#ifdef PM36_HASKELL_SCRIPTING
205211 case mScriptSession of
206212 Nothing -> error "attempted to read serialized AtomFunction without scripting enabled"
207213 Just scriptSession -> do
208214 eCompiledScript <- runGhc (Just libdir) $ do
209215 setSession (hscEnv scriptSession)
210− compileScript (dbcFunctionBodyType scriptSession) funcScript
216+ compileScript (dbcFunctionBodyType scriptSession) _funcScript
211217 case eCompiledScript of
212218 Left err -> throwIO err
213219 Right compiledScript -> pure DatabaseContextFunction { dbcFuncName = funcName,
214− dbcFuncType = funcType,
215− dbcFuncBody = DatabaseContextFunctionBody (Just funcScript) compiledScript}
220+ dbcFuncType = _funcType,
221+ dbcFuncBody = DatabaseContextFunctionBody (Just _funcScript) compiledScript}
222+#else
223+ error "Haskell scripting is disabled"
224+#endif
216225
217226writeIncDep :: DiskSync -> FilePath -> (IncDepName, InclusionDependency) -> IO ()
218227writeIncDep sync transDir (incDepName, incDep) =
219− writeBSFileSync sync (incDepsDir transDir </> T.unpack incDepName) $ B.encode incDep
228+ writeBSFileSync sync (incDepsDir transDir </> T.unpack incDepName) $ serialise incDep
220229
221230writeIncDeps :: DiskSync -> FilePath -> M.Map IncDepName InclusionDependency -> IO ()
222231writeIncDeps sync transDir incdeps = mapM_ (writeIncDep sync transDir) $ M.toList incdeps
@@ -224,7 +233,7 @@ writeIncDeps sync transDir incdeps = mapM_ (writeIncDep sync transDir) $ M.toLis
224233readIncDep :: FilePath -> IncDepName -> IO (IncDepName, InclusionDependency)
225234readIncDep transDir incdepName = do
226235 let incDepPath = incDepsDir transDir </> T.unpack incdepName
227− incDepData <- B.decodeFile incDepPath
236+ incDepData <- readFileDeserialise incDepPath
228237 pure (incdepName, incDepData)
229238
230239readIncDeps :: FilePath -> IO (M.Map IncDepName InclusionDependency)
@@ -236,20 +245,20 @@ readIncDeps transDir = do
236245readSubschemas :: FilePath -> IO Subschemas
237246readSubschemas transDir = do
238247 let sschemasPath = subschemasPath transDir
239− B.decodeFile sschemasPath
248+ readFileDeserialise sschemasPath
240249
241250writeSubschemas :: DiskSync -> FilePath -> Subschemas -> IO ()
242251writeSubschemas sync transDir sschemas = do
243252 let sschemasPath = subschemasPath transDir
244− writeBSFileSync sync sschemasPath (B.encode sschemas)
253+ writeBSFileSync sync sschemasPath (serialise sschemas)
245254
246255writeTypeConstructorMapping :: DiskSync -> FilePath -> TypeConstructorMapping -> IO ()
247256writeTypeConstructorMapping sync path types = let atPath = typeConsPath path in
248− writeBSFileSync sync atPath $ B.encode types
257+ writeBSFileSync sync atPath $ serialise types
249258
250259readTypeConstructorMapping :: FilePath -> IO TypeConstructorMapping
251260readTypeConstructorMapping path = do
252261 let atPath = typeConsPath path
253− B.decodeFile atPath
262+ readFileDeserialise atPath
263+
254264
255−
src/lib/ProjectM36/Transaction/Type.hsnew file+8
@@ -0,0 +1,8 @@
1+module ProjectM36.Transaction where
2+import ProjectM36.Base
3+
4+uid :: Transaction -> TransactionId
5+uid (Transaction uid _ _) = uid
6+
7+info :: Transaction -> TransactionInfo
8+info (Transaction _ info _) = info
src/lib/ProjectM36/TransactionDiffs.hsnew file+12
@@ -0,0 +1,12 @@
1+module ProjectM36.TransactionDiffs where
2+import ProjectM36.Base
3+import Data.List.NonEmpty
4+import Data.UUID as U
5+
6+{-
7+root :: TransactionDiffs
8+root = single U.nil NoOperation
9+
10+single :: TransactionId -> TransactionDiffExpr -> TransactionDiffs
11+single tid expr = (tid, expr) :| []
12+-}
src/lib/ProjectM36/TransactionGraph.hs+238−148
@@ -1,46 +1,52 @@
1−{-# LANGUAGE DeriveAnyClass, DeriveGeneric #-}
1+{-# LANGUAGE DeriveGeneric, CPP, FlexibleContexts, DerivingVia #-}
22module ProjectM36.TransactionGraph where
33import ProjectM36.Base
44import ProjectM36.Error
55import ProjectM36.Transaction
6+import ProjectM36.TransactionInfo as TI
67import ProjectM36.Relation
78import ProjectM36.TupleSet
89import ProjectM36.Tuple
910import ProjectM36.RelationalExpression
1011import ProjectM36.TransactionGraph.Merge
12+import ProjectM36.MerkleHash
1113import qualified ProjectM36.DisconnectedTransaction as Discon
14+import qualified ProjectM36.Attribute as A
1215
16+import Codec.Winery
17+import Control.Monad.Except hiding (join)
18+import Control.Monad.Reader hiding (join)
1319import qualified Data.Vector as V
14−import qualified ProjectM36.Attribute as A
1520import qualified Data.UUID as U
1621import qualified Data.Set as S
1722import qualified Data.Map as M
18−import Control.Monad
23+import qualified Data.List.NonEmpty as NE
1924import Data.Time.Clock
2025import qualified Data.Text as T
2126import GHC.Generics
22−import Data.Binary
2327import Data.Either (lefts, rights, isRight)
28+#if __GLASGOW_HASKELL__ < 804
2429import Data.Monoid
30+#endif
2531import Control.Arrow
2632import Data.Maybe
27−
28−{-
29−--import Debug.Trace
30−import Control.Monad.Reader
31−import qualified ProjectM36.DisconnectedTransaction as D
32−-}
33+import Data.UUID.V4
34+import qualified Data.ByteString.Lazy as BL
35+import ProjectM36.DatabaseContext as DBC
36+import Crypto.Hash.SHA256
3337
3438-- | Record a lookup for a specific transaction in the graph.
3539data TransactionIdLookup = TransactionIdLookup TransactionId |
3640 TransactionIdHeadNameLookup HeadName [TransactionIdHeadBacktrack]
37− deriving (Show, Eq, Binary, Generic)
41+ deriving (Show, Eq, Generic)
42+ deriving Serialise via WineryVariant TransactionIdLookup
3843
3944-- | Used for git-style head backtracking such as topic~3^2.
40−data TransactionIdHeadBacktrack = TransactionIdHeadParentBacktrack Int | -- ^ git equivalent of ~: walk back n parents, arbitrarily choosing a parent when a choice must be made
45+data TransactionIdHeadBacktrack = TransactionIdHeadParentBacktrack Int | -- ^ git equivalent of ~v: walk back n parents, arbitrarily choosing a parent when a choice must be made
4146 TransactionIdHeadBranchBacktrack Int | -- ^ git equivalent of ^: walk back one parent level to the nth arbitrarily-chosen parent
4247 TransactionStampHeadBacktrack UTCTime -- ^ git equivalent of 'git-rev-list -n 1 --before X' find the first transaction which was created before the timestamp
43− deriving (Show, Eq, Binary, Generic)
48+ deriving (Show, Eq, Generic)
49+ deriving Serialise via WineryVariant TransactionIdHeadBacktrack
4450
4551
4652-- | Operators which manipulate a transaction graph and which transaction the current 'Session' is based upon.
@@ -52,22 +58,32 @@ data TransactionGraphOperator = JumpToHead HeadName |
5258 MergeTransactions MergeStrategy HeadName HeadName |
5359 Commit |
5460 Rollback
55− deriving (Eq, Show, Binary, Generic)
61+ deriving (Eq, Show, Generic)
62+ deriving Serialise via WineryVariant TransactionGraphOperator
5663
5764isCommit :: TransactionGraphOperator -> Bool
5865isCommit Commit = True
5966isCommit _ = False
6067
61−data ROTransactionGraphOperator = ShowGraph
68+data ROTransactionGraphOperator = ShowGraph | ValidateMerkleHashes
6269 deriving Show
6370
6471bootstrapTransactionGraph :: UTCTime -> TransactionId -> DatabaseContext -> TransactionGraph
65−bootstrapTransactionGraph stamp freshId context = TransactionGraph bootstrapHeads bootstrapTransactions
72+bootstrapTransactionGraph stamp' freshId context = TransactionGraph bootstrapHeads bootstrapTransactions
6673 where
6774 bootstrapHeads = M.singleton "master" freshTransaction
6875 newSchemas = Schemas context M.empty
69− freshTransaction = Transaction freshId (TransactionInfo U.nil S.empty stamp) newSchemas
70− bootstrapTransactions = S.singleton freshTransaction
76+ freshTransaction = fresh freshId stamp' newSchemas
77+ hashedTransaction = Transaction freshId ((transactionInfo freshTransaction) { merkleHash = calculateMerkleHash freshTransaction emptyTransactionGraph }) newSchemas
78+ bootstrapTransactions = S.singleton hashedTransaction
79+
80+-- | Create a transaction graph from a context.
81+freshTransactionGraph :: DatabaseContext -> IO (TransactionGraph, TransactionId)
82+freshTransactionGraph ctx = do
83+ now <- getCurrentTime
84+ freshId <- nextRandom
85+ pure (bootstrapTransactionGraph now freshId ctx, freshId)
86+
7187
7288emptyTransactionGraph :: TransactionGraph
7389emptyTransactionGraph = TransactionGraph M.empty S.empty
@@ -86,75 +102,79 @@ headNameForTransaction transaction (TransactionGraph heads _) = if M.null matchi
86102 where
87103 matchingTrans = M.filter (transaction ==) heads
88104
89−transactionForId :: TransactionId -> TransactionGraph -> Either RelationalError Transaction
90−transactionForId tid graph
91− | tid == U.nil =
92− Left RootTransactionTraversalError
93− | S.null matchingTrans =
94− Left $ NoSuchTransactionError tid
95− | otherwise =
96− Right $ head (S.toList matchingTrans)
97− where
98− matchingTrans = S.filter (\(Transaction idMatch _ _) -> idMatch == tid) (transactionsForGraph graph)
99−
100105transactionsForIds :: S.Set TransactionId -> TransactionGraph -> Either RelationalError (S.Set Transaction)
101106transactionsForIds idSet graph =
102107 S.fromList <$> forM (S.toList idSet) (`transactionForId` graph)
103108
104−isRootTransaction :: Transaction -> TransactionGraph -> Bool
105−isRootTransaction (Transaction _ (TransactionInfo pId _ _) _) _ = U.null pId
106−isRootTransaction (Transaction _ MergeTransactionInfo{} _) _ = False
109+-- | A root transaction terminates a graph and has no parents.
110+isRootTransaction :: Transaction -> Bool
111+isRootTransaction trans = parentIds trans == S.singleton U.nil
112+
113+rootTransactions :: TransactionGraph -> S.Set Transaction
114+rootTransactions graph = S.filter isRootTransaction (transactionsForGraph graph)
107115
108116-- the first transaction has no parent - all other do have parents- merges have two parents
109117parentTransactions :: Transaction -> TransactionGraph -> Either RelationalError (S.Set Transaction)
110−parentTransactions (Transaction _ (TransactionInfo pId _ _) _) graph =
111− S.singleton <$> transactionForId pId graph
112−
113−
114−parentTransactions (Transaction _ (MergeTransactionInfo pId1 pId2 _ _) _ ) graph = transactionsForIds (S.fromList [pId1, pId2]) graph
115−
118+parentTransactions trans = transactionsForIds (parentIds trans)
116119
117120childTransactions :: Transaction -> TransactionGraph -> Either RelationalError (S.Set Transaction)
118−childTransactions (Transaction _ (TransactionInfo _ children _) _) = transactionsForIds children
119−childTransactions (Transaction _ (MergeTransactionInfo _ _ children _) _) = transactionsForIds children
121+childTransactions trans graph = transactionsForIds childIds graph
122+ where
123+ childIds = S.map transactionId (S.filter filt (transactionsForGraph graph))
124+ filt trans' = S.member (transactionId trans) (parentIds trans')
120125
121126-- create a new commit and add it to the heads
122127-- technically, the new head could be added to an existing commit, but by adding a new commit, the new head is unambiguously linked to a new commit (with a context indentical to its parent)
123128addBranch :: UTCTime -> TransactionId -> HeadName -> TransactionId -> TransactionGraph -> Either RelationalError (Transaction, TransactionGraph)
124−addBranch stamp newId newBranchName branchPointId graph = do
129+addBranch stamp' newId newBranchName branchPointId graph = do
125130 parentTrans <- transactionForId branchPointId graph
126− let newTrans = Transaction newId (TransactionInfo branchPointId S.empty stamp) (schemas parentTrans)
131+ let newTrans = Transaction newId (TI.singleParent branchPointId stamp') (schemas parentTrans)
127132 addTransactionToGraph newBranchName newTrans graph
128133
129134--adds a disconnected transaction to a transaction graph at some head
130135addDisconnectedTransaction :: UTCTime -> TransactionId -> HeadName -> DisconnectedTransaction -> TransactionGraph -> Either RelationalError (Transaction, TransactionGraph)
131−addDisconnectedTransaction stamp newId headName (DisconnectedTransaction parentId schemas' _) = addTransactionToGraph headName (Transaction newId (TransactionInfo parentId S.empty stamp) schemas')
132−
133−
136+addDisconnectedTransaction stamp' newId headName (DisconnectedTransaction parentId schemas' _) graph = addTransactionToGraph headName newTrans' graph
137+ where
138+ newTrans = Transaction newId newTInfo schemas'
139+ newTInfo = TI.singleParent parentId stamp'
140+ newTrans' = Transaction newId (newTInfo { merkleHash = newHash }) schemas'
141+ newHash = calculateMerkleHash newTrans graph--lookup parents in graph to calculate
142+--LOOP
134143addTransactionToGraph :: HeadName -> Transaction -> TransactionGraph -> Either RelationalError (Transaction, TransactionGraph)
135144addTransactionToGraph headName newTrans graph = do
136− let parentIds = transactionParentIds newTrans
137− childIds = transactionChildIds newTrans
145+ let parentIds' = parentIds newTrans
138146 newId = transactionId newTrans
139147 validateIds ids = mapM (`transactionForId` graph) (S.toList ids)
140− addChildTransaction trans = transactionSetChildren trans (S.insert newId (transactionChildIds trans))
148+ childTs <- childTransactions newTrans graph
141149 --validate that the parent transactions are in the graph
142− _ <- validateIds parentIds
143− when (S.size parentIds < 1) (Left $ NewTransactionMissingParentError newId)
150+ _ <- validateIds parentIds'
151+ when (S.size parentIds' < 1) (Left $ NewTransactionMissingParentError newId)
144152 --if the headName already exists, ensure that it refers to a parent
145153 case transactionForHead headName graph of
146154 Nothing -> pure () -- any headName is OK
147− Just trans -> when (S.notMember (transactionId trans) parentIds) (Left (HeadNameSwitchingHeadProhibitedError headName))
155+ Just trans -> when (S.notMember (transactionId trans) parentIds') (Left (HeadNameSwitchingHeadProhibitedError headName))
148156 --validate that the transaction has no children
149− unless (S.null childIds) (Left $ NewTransactionMayNotHaveChildrenError newId)
157+ unless (S.null childTs) (Left $ NewTransactionMayNotHaveChildrenError newId)
150158 --validate that the trasaction's id is unique
151159 when (isRight (transactionForId newId graph)) (Left (TransactionIdInUseError newId))
152− --update the parent transactions to point to the new transaction
153− parents <- mapM (`transactionForId` graph) (S.toList parentIds)
154− let updatedParents = S.map addChildTransaction (S.fromList parents)
155− updatedTransSet = S.insert newTrans (S.union updatedParents (transactionsForGraph graph))
156− updatedHeads = M.insert headName newTrans (transactionHeadsForGraph graph)
157− pure (newTrans, TransactionGraph updatedHeads updatedTransSet)
160+ --replace all references to UncommittedTransactionMarker to new transaction id
161+ let newTrans' = newTransUncommittedReplace newTrans
162+ updatedTransSet = S.insert newTrans' (transactionsForGraph graph)
163+ updatedHeads = M.insert headName newTrans' (transactionHeadsForGraph graph)
164+ pure (newTrans', TransactionGraph updatedHeads updatedTransSet)
165+
166+--replace all occurrences of the uncommitted context marker
167+newTransUncommittedReplace :: Transaction -> Transaction
168+newTransUncommittedReplace trans@(Transaction tid tinfo (Schemas ctx sschemas)) =
169+ Transaction tid tinfo (Schemas fixedContext sschemas)
170+ where
171+ uncommittedReplace UncommittedContextMarker = TransactionMarker tid
172+ uncommittedReplace marker = marker
173+ relvars = relationVariables (concreteDatabaseContext trans)
174+ fixedRelvars = M.map (fmap uncommittedReplace) relvars
175+ fixedContext = ctx { relationVariables = fixedRelvars }
176+
177+
158178
159179validateGraph :: TransactionGraph -> Maybe [RelationalError]
160180validateGraph graph@(TransactionGraph _ transSet) = do
@@ -226,7 +246,7 @@ evalGraphOp _ _ discon graph (WalkBackToTime backTime) = do
226246 case transactionForId jumpDest graph of
227247 Left err -> Left err
228248 Right trans -> do
229− let disconnectedTrans = DisconnectedTransaction (transactionId trans) (schemas trans) False
249+ let disconnectedTrans = Discon.freshTransaction (transactionId trans) (schemas trans)
230250 Right (disconnectedTrans, graph)
231251
232252-- add new head pointing to branchPoint
@@ -244,15 +264,15 @@ evalGraphOp newId discon@(DisconnectedTransaction parentId disconContext) graph
244264
245265-- create a new commit and add it to the heads
246266-- technically, the new head could be added to an existing commit, but by adding a new commit, the new head is unambiguously linked to a new commit (with a context indentical to its parent)
247−evalGraphOp stamp newId (DisconnectedTransaction parentId schemas' _) graph (Branch newBranchName) = do
248− let newDiscon = DisconnectedTransaction newId schemas' False
249− case addBranch stamp newId newBranchName parentId graph of
267+evalGraphOp stamp' newId (DisconnectedTransaction parentId schemas' _) graph (Branch newBranchName) = do
268+ let newDiscon = Discon.freshTransaction newId schemas'
269+ case addBranch stamp' newId newBranchName parentId graph of
250270 Left err -> Left err
251271 Right (_, newGraph) -> Right (newDiscon, newGraph)
252272
253273-- add the disconnected transaction to the graph
254274-- affects graph and disconnectedtransaction- the new disconnectedtransaction's parent is the freshly committed transaction
255−evalGraphOp stamp newTransId discon@(DisconnectedTransaction parentId schemas' _) graph Commit = case transactionForId parentId graph of
275+evalGraphOp stamp' newTransId discon@(DisconnectedTransaction parentId schemas' _) graph Commit = case transactionForId parentId graph of
256276 Left err -> Left err
257277 Right parentTransaction -> case headNameForTransaction parentTransaction graph of
258278 Nothing -> Left $ TransactionIsNotAHeadError parentId
@@ -260,17 +280,20 @@ evalGraphOp stamp newTransId discon@(DisconnectedTransaction parentId schemas' _
260280 Left err-> Left err
261281 Right (_, updatedGraph) -> Right (newDisconnectedTrans, updatedGraph)
262282 where
263− newDisconnectedTrans = DisconnectedTransaction newTransId schemas' False
264− maybeUpdatedGraph = addDisconnectedTransaction stamp newTransId headName discon graph
283+ newDisconnectedTrans = Discon.freshTransaction newTransId schemas'
284+ maybeUpdatedGraph = addDisconnectedTransaction stamp' newTransId headName discon graph
265285
266286-- refresh the disconnected transaction, return the same graph
267287evalGraphOp _ _ (DisconnectedTransaction parentId _ _) graph Rollback = case transactionForId parentId graph of
268288 Left err -> Left err
269289 Right parentTransaction -> Right (newDiscon, graph)
270290 where
271− newDiscon = DisconnectedTransaction parentId (schemas parentTransaction) False
291+ newDiscon = Discon.freshTransaction parentId (schemas parentTransaction)
272292
273−evalGraphOp stamp newId (DisconnectedTransaction parentId _ _) graph (MergeTransactions mergeStrategy headNameA headNameB) = mergeTransactions stamp newId parentId mergeStrategy (headNameA, headNameB) graph
293+evalGraphOp stamp' newId (DisconnectedTransaction parentId _ _) graph (MergeTransactions mergeStrategy headNameA headNameB) =
294+ runGraphRefRelationalExprM env $ mergeTransactions stamp' newId parentId mergeStrategy (headNameA, headNameB)
295+ where
296+ env = freshGraphRefRelationalExprEnv Nothing graph
274297
275298evalGraphOp _ _ discon graph@(TransactionGraph graphHeads transSet) (DeleteBranch branchName) = case transactionForHead branchName graph of
276299 Nothing -> Left (NoSuchHeadNameError branchName)
@@ -283,6 +306,7 @@ graphAsRelation (DisconnectedTransaction parentId _ _) graph@(TransactionGraph _
283306 mkRelationFromList attrs tupleMatrix
284307 where
285308 attrs = A.attributesFromList [Attribute "id" TextAtomType,
309+ Attribute "hash" ByteStringAtomType,
286310 Attribute "stamp" DateTimeAtomType,
287311 Attribute "parents" (RelationAtomType parentAttributes),
288312 Attribute "current" BoolAtomType,
@@ -292,7 +316,8 @@ graphAsRelation (DisconnectedTransaction parentId _ _) graph@(TransactionGraph _
292316 tupleGenerator transaction = case transactionParentsRelation transaction graph of
293317 Left err -> Left err
294318 Right parentTransRel -> Right [TextAtom $ T.pack $ show (transactionId transaction),
295− DateTimeAtom (transactionTimestamp transaction),
319+ ByteStringAtom $ _unMerkleHash (merkleHash (transactionInfo transaction)),
320+ DateTimeAtom (timestamp transaction),
296321 RelationAtom parentTransRel,
297322 BoolAtom $ parentId == transactionId transaction,
298323 TextAtom $ fromMaybe "" (headNameForTransaction transaction graph)
@@ -300,7 +325,7 @@ graphAsRelation (DisconnectedTransaction parentId _ _) graph@(TransactionGraph _
300325
301326transactionParentsRelation :: Transaction -> TransactionGraph -> Either RelationalError Relation
302327transactionParentsRelation trans graph =
303− if isRootTransaction trans graph then
328+ if isRootTransaction trans then
304329 mkRelation attrs emptyTupleSet
305330 else do
306331 parentTransSet <- parentTransactions trans graph
@@ -319,39 +344,47 @@ evalROGraphOp discon graph ShowGraph = do
319344-}
320345
321346-- | Execute the merge strategy against the transactions, returning a new transaction which can be then added to the transaction graph
322−createMergeTransaction :: UTCTime -> TransactionId -> MergeStrategy -> TransactionGraph -> (Transaction, Transaction) -> Either MergeError Transaction
323−createMergeTransaction stamp newId (SelectedBranchMergeStrategy selectedBranch) graph t2@(trans1, trans2) = do
324− let selectedTrans = validateHeadName selectedBranch graph t2
325− Transaction newId (MergeTransactionInfo (transactionId trans1) (transactionId trans2) S.empty stamp) . schemas <$> selectedTrans
347+createMergeTransaction :: UTCTime -> TransactionId -> MergeStrategy -> (Transaction, Transaction) -> GraphRefRelationalExprM Transaction
348+createMergeTransaction stamp' newId (SelectedBranchMergeStrategy selectedBranch) t2@(trans1, trans2) = do
349+ graph <- gfGraph
350+ selectedTrans <- validateHeadName selectedBranch graph t2
351+ pure $ addMerkleHash graph $
352+ Transaction newId (TransactionInfo {
353+ parents = NE.fromList [transactionId trans1,
354+ transactionId trans2],
355+ stamp = stamp',
356+ merkleHash = mempty }) (schemas selectedTrans)
326357
327358-- merge functions, relvars, individually
328−createMergeTransaction stamp newId strat@UnionMergeStrategy graph t2 = createUnionMergeTransaction stamp newId strat graph t2
359+createMergeTransaction stamp' newId strat@UnionMergeStrategy t2 =
360+ createUnionMergeTransaction stamp' newId strat t2
329361
330362-- merge function, relvars, but, on error, just take the component from the preferred branch
331−createMergeTransaction stamp newId strat@(UnionPreferMergeStrategy _) graph t2 = createUnionMergeTransaction stamp newId strat graph t2
363+createMergeTransaction stamp' newId strat@(UnionPreferMergeStrategy _) t2 =
364+ createUnionMergeTransaction stamp' newId strat t2
332365
333366-- | Returns the correct Transaction for the branch name in the graph and ensures that it is one of the two transaction arguments in the tuple.
334−validateHeadName :: HeadName -> TransactionGraph -> (Transaction, Transaction) -> Either MergeError Transaction
367+validateHeadName :: HeadName -> TransactionGraph -> (Transaction, Transaction) -> GraphRefRelationalExprM Transaction
335368validateHeadName headName graph (t1, t2) =
336369 case transactionForHead headName graph of
337− Nothing -> Left SelectedHeadMismatchMergeError
370+ Nothing -> throwError (MergeTransactionError SelectedHeadMismatchMergeError)
338371 Just trans -> if trans /= t1 && trans /= t2 then
339− Left SelectedHeadMismatchMergeError
372+ throwError (MergeTransactionError SelectedHeadMismatchMergeError)
340373 else
341− Right trans
374+ pure trans
342375
343376-- Algorithm: start at one transaction and work backwards up the parents. If there is a node we have not yet visited as a child, then walk that up to its head. If that branch contains the goal transaction, then we have completed a valid subgraph traversal.
344377subGraphOfFirstCommonAncestor :: TransactionGraph -> TransactionHeads -> Transaction -> Transaction -> S.Set Transaction -> Either RelationalError TransactionGraph
345−subGraphOfFirstCommonAncestor origGraph resultHeads currentTrans goalTrans traverseSet = do
346− let currentid = transactionId currentTrans
378+subGraphOfFirstCommonAncestor origGraph resultHeads currentTrans' goalTrans traverseSet = do
379+ let currentid = transactionId currentTrans'
347380 goalid = transactionId goalTrans
348− if currentTrans == goalTrans then
381+ if currentTrans' == goalTrans then
349382 Right (TransactionGraph resultHeads traverseSet) -- add filter
350383 --catch root transaction to improve error?
351384 else do
352− currentTransChildren <- S.fromList <$> mapM (`transactionForId` origGraph) (S.toList (transactionChildIds currentTrans))
353− let searchChildren = S.difference (S.insert currentTrans traverseSet) currentTransChildren
354− searchChild start = pathToTransaction origGraph start goalTrans (S.insert currentTrans traverseSet)
385+ currentTransChildren <- childTransactions currentTrans' origGraph
386+ let searchChildren = S.difference (S.insert currentTrans' traverseSet) currentTransChildren
387+ searchChild start' = pathToTransaction origGraph start' goalTrans (S.insert currentTrans' traverseSet)
355388 childSearches = map searchChild (S.toList searchChildren)
356389 errors = lefts childSearches
357390 pathsFound = rights childSearches
@@ -360,17 +393,16 @@ subGraphOfFirstCommonAncestor origGraph resultHeads currentTrans goalTrans trave
360393 unless (null realErrors) (Left (head realErrors))
361394 -- if no paths found, search the parent
362395 if null pathsFound then
363− case oneParent currentTrans of
396+ case oneParent currentTrans' of
364397 Left RootTransactionTraversalError -> Left (NoCommonTransactionAncestorError currentid goalid)
365398 Left err -> Left err
366399 Right currentTransParent ->
367− subGraphOfFirstCommonAncestor origGraph resultHeads currentTransParent goalTrans (S.insert currentTrans traverseSet)
400+ subGraphOfFirstCommonAncestor origGraph resultHeads currentTransParent goalTrans (S.insert currentTrans' traverseSet)
368401 else -- we found a path
369402 Right (TransactionGraph resultHeads (S.unions (traverseSet : pathsFound)))
370403 where
371− oneParent (Transaction _ (TransactionInfo parentId _ _) _) = transactionForId parentId origGraph
372− oneParent (Transaction _ (MergeTransactionInfo parentId _ _ _) _) = transactionForId parentId origGraph
373−
404+ oneParent (Transaction _ tinfo _) = transactionForId (NE.head (parents tinfo)) origGraph
405+
374406-- | Search from a past graph point to all following heads for a specific transaction. If found, return the transaction path, otherwise a RelationalError.
375407pathToTransaction :: TransactionGraph -> Transaction -> Transaction -> S.Set Transaction -> Either RelationalError (S.Set Transaction)
376408pathToTransaction graph currentTransaction targetTransaction accumTransSet = do
@@ -378,11 +410,11 @@ pathToTransaction graph currentTransaction targetTransaction accumTransSet = do
378410 if transactionId targetTransaction == transactionId currentTransaction then
379411 Right accumTransSet
380412 else do
381− currentTransChildren <- mapM (`transactionForId` graph) (S.toList (transactionChildIds currentTransaction))
413+ currentTransChildren <- childTransactions currentTransaction graph
382414 if null currentTransChildren then
383415 Left (FailedToFindTransactionError targetId)
384416 else do
385− let searches = map (\t -> pathToTransaction graph t targetTransaction (S.insert t accumTransSet)) currentTransChildren
417+ let searches = map (\t -> pathToTransaction graph t targetTransaction (S.insert t accumTransSet)) (S.toList currentTransChildren)
386418 let realErrors = filter (/= FailedToFindTransactionError targetId) (lefts searches)
387419 paths = rights searches
388420 if not (null realErrors) then -- found some real errors
@@ -392,35 +424,39 @@ pathToTransaction graph currentTransaction targetTransaction accumTransSet = do
392424 else --we have some paths!
393425 Right (S.unions paths)
394426
395−mergeTransactions :: UTCTime -> TransactionId -> TransactionId -> MergeStrategy -> (HeadName, HeadName) -> TransactionGraph -> Either RelationalError (DisconnectedTransaction, TransactionGraph)
396−mergeTransactions stamp newId parentId mergeStrategy (headNameA, headNameB) graph = do
427+mergeTransactions :: UTCTime -> TransactionId -> TransactionId -> MergeStrategy -> (HeadName, HeadName) -> GraphRefRelationalExprM (DisconnectedTransaction, TransactionGraph)
428+mergeTransactions stamp' newId parentId mergeStrategy (headNameA, headNameB) = do
429+ graph <- gfGraph
397430 let transactionForHeadErr name = case transactionForHead name graph of
398− Nothing -> Left (NoSuchHeadNameError name)
399− Just t -> Right t
400− transA <- transactionForHeadErr headNameA
401− transB <- transactionForHeadErr headNameB
402− disconParent <- transactionForId parentId graph
431+ Nothing -> throwError (NoSuchHeadNameError name)
432+ Just t -> pure t
433+ runE e = case e of
434+ Left e' -> throwError e'
435+ Right v -> pure v
436+ transA <- transactionForHeadErr headNameA
437+ transB <- transactionForHeadErr headNameB
438+ disconParent <- gfTransForId parentId
403439 let subHeads = M.filterWithKey (\k _ -> k `elem` [headNameA, headNameB]) (transactionHeadsForGraph graph)
404− subGraph <- subGraphOfFirstCommonAncestor graph subHeads transA transB S.empty
405− subGraph' <- filterSubGraph subGraph subHeads
406− case createMergeTransaction stamp newId mergeStrategy subGraph' (transA, transB) of
407− Left err -> Left (MergeTransactionError err)
408− Right mergedTrans -> case checkConstraints (concreteDatabaseContext mergedTrans) of
409− Left err -> Left err
410− Right _ -> case headNameForTransaction disconParent graph of
411− Nothing -> Left (TransactionIsNotAHeadError parentId)
440+ subGraph <- runE $ subGraphOfFirstCommonAncestor graph subHeads transA transB S.empty
441+ subGraph' <- runE $ filterSubGraph subGraph subHeads
442+ mergedTrans <- local (const (freshGraphRefRelationalExprEnv Nothing subGraph')) $ createMergeTransaction stamp' newId mergeStrategy (transA, transB)
443+ case headNameForTransaction disconParent graph of
444+ Nothing -> throwError (TransactionIsNotAHeadError parentId)
412445 Just headName -> do
413− (newTrans, newGraph) <- addTransactionToGraph headName mergedTrans graph
414− let newGraph' = TransactionGraph (transactionHeadsForGraph newGraph) (transactionsForGraph newGraph)
415− newDiscon = DisconnectedTransaction newId (schemas newTrans) False
416− pure (newDiscon, newGraph')
446+ (newTrans, newGraph) <- runE $ addTransactionToGraph headName mergedTrans graph
447+ case checkConstraints (concreteDatabaseContext mergedTrans) newId graph of
448+ Left err -> throwError err
449+ Right _ -> do
450+ let newGraph' = TransactionGraph (transactionHeadsForGraph newGraph) (transactionsForGraph newGraph)
451+ newDiscon = Discon.freshTransaction newId (schemas newTrans)
452+ pure (newDiscon, newGraph')
417453
418454--TEMPORARY COPY/PASTE
419455showTransactionStructureX :: Transaction -> TransactionGraph -> String
420456showTransactionStructureX trans graph = headInfo ++ " " ++ show (transactionId trans) ++ " " ++ parentTransactionsInfo
421457 where
422458 headInfo = maybe "" show (headNameForTransaction trans graph)
423− parentTransactionsInfo = if isRootTransaction trans graph then "root" else case parentTransactions trans graph of
459+ parentTransactionsInfo = if isRootTransaction trans then "root" else case parentTransactions trans graph of
424460 Left err -> show err
425461 Right parentTransSet -> concat $ S.toList $ S.map (show . transactionId) parentTransSet
426462
@@ -439,25 +475,29 @@ filterSubGraph graph heads = Right $ TransactionGraph newHeads newTransSet
439475 newHeads = M.map (filterTransaction validIds) heads
440476
441477--helper function for commonalities in union merge
442−createUnionMergeTransaction :: UTCTime -> TransactionId -> MergeStrategy -> TransactionGraph -> (Transaction, Transaction) -> Either MergeError Transaction
443−createUnionMergeTransaction stamp newId strategy graph (t1,t2) = do
478+createUnionMergeTransaction :: UTCTime -> TransactionId -> MergeStrategy -> (Transaction, Transaction) -> GraphRefRelationalExprM Transaction
479+createUnionMergeTransaction stamp' newId strategy (t1,t2) = do
444480 let contextA = concreteDatabaseContext t1
445481 contextB = concreteDatabaseContext t2
446−
482+ liftMergeE x = case x of
483+ Left e -> throwError (MergeTransactionError e)
484+ Right t -> pure t
485+
486+ graph <- gfGraph
447487 preference <- case strategy of
448488 UnionMergeStrategy -> pure PreferNeither
449489 UnionPreferMergeStrategy preferBranch ->
450490 case transactionForHead preferBranch graph of
451− Nothing -> Left (PreferredHeadMissingMergeError preferBranch)
491+ Nothing -> throwError (MergeTransactionError (PreferredHeadMissingMergeError preferBranch))
452492 Just preferredTrans -> pure $ if t1 == preferredTrans then PreferFirst else PreferSecond
453− badStrat -> Left (InvalidMergeStrategyError badStrat)
493+ badStrat -> throwError (MergeTransactionError (InvalidMergeStrategyError badStrat))
454494
455− incDeps <- unionMergeMaps preference (inclusionDependencies contextA) (inclusionDependencies contextB)
495+ incDeps <- liftMergeE $ unionMergeMaps preference (inclusionDependencies contextA) (inclusionDependencies contextB)
456496 relVars <- unionMergeRelVars preference (relationVariables contextA) (relationVariables contextB)
457− atomFuncs <- unionMergeAtomFunctions preference (atomFunctions contextA) (atomFunctions contextB)
458− notifs <- unionMergeMaps preference (notifications contextA) (notifications contextB)
459− types <- unionMergeTypeConstructorMapping preference (typeConstructorMapping contextA) (typeConstructorMapping contextB)
460− dbcFuncs <- unionMergeDatabaseContextFunctions preference (dbcFunctions contextA) (dbcFunctions contextB)
497+ atomFuncs <- liftMergeE $ unionMergeAtomFunctions preference (atomFunctions contextA) (atomFunctions contextB)
498+ notifs <- liftMergeE $ unionMergeMaps preference (notifications contextA) (notifications contextB)
499+ types <- liftMergeE $ unionMergeTypeConstructorMapping preference (typeConstructorMapping contextA) (typeConstructorMapping contextB)
500+ dbcFuncs <- liftMergeE $ unionMergeDatabaseContextFunctions preference (dbcFunctions contextA) (dbcFunctions contextB)
461501 -- TODO: add merge of subschemas
462502 let newContext = DatabaseContext {
463503 inclusionDependencies = incDeps,
@@ -468,7 +508,12 @@ createUnionMergeTransaction stamp newId strategy graph (t1,t2) = do
468508 typeConstructorMapping = types
469509 }
470510 newSchemas = Schemas newContext (subschemas t1)
471− pure (Transaction newId (MergeTransactionInfo (transactionId t1) (transactionId t2) S.empty stamp) newSchemas)
511+ pure $ addMerkleHash graph $
512+ Transaction newId (TransactionInfo {
513+ parents = NE.fromList [transactionId t1,
514+ transactionId t2],
515+ stamp = stamp',
516+ merkleHash = mempty }) newSchemas
472517
473518lookupTransaction :: TransactionGraph -> TransactionIdLookup -> Either RelationalError Transaction
474519lookupTransaction graph (TransactionIdLookup tid) = transactionForId tid graph
@@ -485,56 +530,57 @@ backtrackGraph :: TransactionGraph -> TransactionId -> TransactionIdHeadBacktrac
485530-- tilde, step back one parent link- if a choice must be made, choose the "first" link arbitrarily
486531backtrackGraph graph currentTid (TransactionIdHeadParentBacktrack steps) = do
487532 trans <- transactionForId currentTid graph
488− let parents = S.toAscList (transactionParentIds trans)
489− if length parents < 1 then
490− Left RootTransactionTraversalError
491− else do
492− parentTrans <- transactionForId (head parents) graph
493− if steps == 1 then
494− pure (transactionId parentTrans)
495− else
496− backtrackGraph graph (transactionId parentTrans) (TransactionIdHeadParentBacktrack (steps - 1))
533+
534+ let parentIds' = S.toAscList (parentIds trans)
535+ case parentIds' of
536+ [] -> Left RootTransactionTraversalError
537+ firstParentId:_ -> do
538+ parentTrans <- transactionForId firstParentId graph
539+ if steps == 1 then
540+ pure (transactionId parentTrans)
541+ else
542+ backtrackGraph graph (transactionId parentTrans) (TransactionIdHeadParentBacktrack (steps - 1))
497543
498544backtrackGraph graph currentTid (TransactionIdHeadBranchBacktrack steps) = do
499545 trans <- transactionForId currentTid graph
500− let parents = transactionParentIds trans
501− if S.size parents < 1 then
546+ let parentIds' = parentIds trans
547+ if S.size parentIds' < 1 then
502548 Left RootTransactionTraversalError
503− else if S.size parents < steps then
504− Left (ParentCountTraversalError (S.size parents) steps)
549+ else if S.size parentIds' < steps then
550+ Left (ParentCountTraversalError (S.size parentIds') steps)
505551 else
506− pure (S.elemAt (steps - 1) parents)
552+ pure (S.elemAt (steps - 1) parentIds')
507553
508−backtrackGraph graph currentTid btrack@(TransactionStampHeadBacktrack stamp) = do
554+backtrackGraph graph currentTid btrack@(TransactionStampHeadBacktrack stamp') = do
509555 trans <- transactionForId currentTid graph
510− let parents = transactionParentIds trans
511− if transactionTimestamp trans <= stamp then
556+ let parentIds' = parentIds trans
557+ if timestamp trans <= stamp' then
512558 pure currentTid
513− else if S.null parents then
559+ else if S.null parentIds' then
514560 Left RootTransactionTraversalError
515561 else
516− let arbitraryParent = head (S.toList parents) in
562+ let arbitraryParent = head (S.toList parentIds') in
517563 backtrackGraph graph arbitraryParent btrack
518564
519565-- | Create a temporary branch for commit, merge the result to head, delete the temporary branch. This is useful to atomically commit a transaction, avoiding a TransactionIsNotHeadError but trading it for a potential MergeError.
520566--this is not a GraphOp because it combines multiple graph operations
521567autoMergeToHead :: UTCTime -> (TransactionId, TransactionId, TransactionId) -> DisconnectedTransaction -> HeadName -> MergeStrategy -> TransactionGraph -> Either RelationalError (DisconnectedTransaction, TransactionGraph)
522−autoMergeToHead stamp (tempBranchTransId, tempCommitTransId, mergeTransId) discon mergeToHeadName strat graph = do
568+autoMergeToHead stamp' (tempBranchTransId, tempCommitTransId, mergeTransId) discon mergeToHeadName strat graph = do
523569 let tempBranchName = "mergebranch_" <> U.toText tempBranchTransId
524570 --create the temp branch
525− (discon', graph') <- evalGraphOp stamp tempBranchTransId discon graph (Branch tempBranchName)
571+ (discon', graph') <- evalGraphOp stamp' tempBranchTransId discon graph (Branch tempBranchName)
526572
527573 --commit to the new branch- possible future optimization: don't require fsync for this- create a temp commit type
528− (discon'', graph'') <- evalGraphOp stamp tempCommitTransId discon' graph' Commit
574+ (discon'', graph'') <- evalGraphOp stamp' tempCommitTransId discon' graph' Commit
529575
530576 --jump to merge head
531− (discon''', graph''') <- evalGraphOp stamp tempBranchTransId discon'' graph'' (JumpToHead mergeToHeadName)
577+ (discon''', graph''') <- evalGraphOp stamp' tempBranchTransId discon'' graph'' (JumpToHead mergeToHeadName)
532578
533579 --create the merge
534− (discon'''', graph'''') <- evalGraphOp stamp mergeTransId discon''' graph''' (MergeTransactions strat tempBranchName mergeToHeadName)
580+ (discon'''', graph'''') <- evalGraphOp stamp' mergeTransId discon''' graph''' (MergeTransactions strat tempBranchName mergeToHeadName)
535581
536582 --delete the temp branch
537− (discon''''', graph''''') <- evalGraphOp stamp tempBranchTransId discon'''' graph'''' (DeleteBranch tempBranchName)
583+ (discon''''', graph''''') <- evalGraphOp stamp' tempBranchTransId discon'''' graph'''' (DeleteBranch tempBranchName)
538584 {-
539585 let rel = runReader (evalRelationalExpr (RelationVariable "s" ())) (mkRelationalExprState $ D.concreteDatabaseContext discon'''')
540586 traceShowM rel
@@ -542,4 +588,48 @@ autoMergeToHead stamp (tempBranchTransId, tempCommitTransId, mergeTransId) disco
542588
543589 pure (discon''''', graph''''')
544590
591+
592+addMerkleHash :: TransactionGraph -> Transaction -> Transaction
593+addMerkleHash graph trans = Transaction (transactionId trans) newInfo (schemas trans)
594+ where
595+ newInfo = (transactionInfo trans) { merkleHash = calculateMerkleHash trans graph }
545596
597+-- the new hash includes the parents' ids, the current id, and the hash of the context, and the merkle hashes of the parent transactions
598+calculateMerkleHash :: Transaction -> TransactionGraph -> MerkleHash
599+calculateMerkleHash trans graph = MerkleHash $ hashlazy (BL.fromChunks [transIds,
600+ schemasBytes
601+ ] <> dbcBytes <> parentMerkleHashes)
602+ where
603+ parentMerkleHashes = BL.fromChunks $ map (_unMerkleHash . getMerkleHash) parentTranses
604+ parentTranses =
605+ case transactionsForIds (parentIds trans) graph of
606+ Left RootTransactionTraversalError -> []
607+ Left e -> error ("failed to find transaction in Merkle hash construction: " ++ show e)
608+ Right t -> S.toList t
609+ getMerkleHash t = merkleHash (transactionInfo t)
610+ transIds = serialise (transactionId trans : S.toList (parentIds trans))
611+ dbcBytes = DBC.hashBytes (concreteDatabaseContext trans)
612+ schemasBytes = serialise (subschemas trans)
613+
614+validateMerkleHash :: Transaction -> TransactionGraph -> Either MerkleValidationError ()
615+validateMerkleHash trans graph =
616+ if expectedHash /= actualHash then
617+ Left (MerkleValidationError (transactionId trans) expectedHash actualHash)
618+ else
619+ pure ()
620+ where
621+ expectedHash = merkleHash (transactionInfo trans)
622+ actualHash = calculateMerkleHash trans graph
623+
624+data MerkleValidationError = MerkleValidationError TransactionId MerkleHash MerkleHash
625+ deriving (Show, Eq, Generic)
626+
627+validateMerkleHashes :: TransactionGraph -> Either [MerkleValidationError] ()
628+validateMerkleHashes graph =
629+ if null errs then pure () else Left errs
630+ where
631+ errs = S.foldr validateTrans [] (transactionsForGraph graph)
632+ validateTrans trans acc =
633+ case validateMerkleHash trans graph of
634+ Left err -> err : acc
635+ _ -> acc
src/lib/ProjectM36/TransactionGraph/Merge.hs+16−12
@@ -2,10 +2,11 @@
22module ProjectM36.TransactionGraph.Merge where
33import ProjectM36.Base
44import ProjectM36.Error
5+import ProjectM36.RelationalExpression
6+import Control.Monad.Except hiding (join)
57import qualified Data.Set as S
68import qualified Data.Map as M
79import qualified ProjectM36.TypeConstructorDef as TCD
8−import ProjectM36.Relation
910import Control.Monad (foldM)
1011import qualified Data.HashSet as HS
1112
@@ -22,19 +23,22 @@ unionMergeMaps prefer mapA mapB = case prefer of
2223 Left StrategyViolatesComponentMergeError
2324
2425-- perform the merge even if the attributes are different- is this what we want? Obviously, we need finer-grained merge options.
25−unionMergeRelation :: MergePreference -> Relation -> Relation -> Either MergeError Relation
26−unionMergeRelation prefer relA relB = case relA `union` relB of
27− Right unionRel -> pure unionRel
28− Left (AttributeNamesMismatchError _) -> preferredRelVar
29− Left _ -> Left StrategyViolatesRelationVariableMergeError
30− where
31− preferredRelVar = case prefer of
32− PreferFirst -> Right relA
33− PreferSecond -> Right relB
34− PreferNeither -> Left StrategyViolatesRelationVariableMergeError
26+unionMergeRelation :: MergePreference -> GraphRefRelationalExpr -> GraphRefRelationalExpr -> GraphRefRelationalExprM GraphRefRelationalExpr
27+unionMergeRelation prefer relA relB = do
28+ let unioned = Union relA relB
29+ mergeErr = MergeTransactionError StrategyViolatesRelationVariableMergeError
30+ preferredRelVar =
31+ case prefer of
32+ PreferFirst -> pure relA
33+ PreferSecond -> pure relB
34+ PreferNeither -> throwError mergeErr
35+ handler AttributeNamesMismatchError{} = preferredRelVar
36+ handler _err' = throwError mergeErr
37+ --typecheck first?
38+ (evalGraphRefRelationalExpr unioned >> pure (Union relA relB)) `catchError` handler
3539
3640--try to execute unions against the relvars contents -- if a relvar only appears in one context, include it
37−unionMergeRelVars :: MergePreference -> RelationVariables -> RelationVariables -> Either MergeError RelationVariables
41+unionMergeRelVars :: MergePreference -> RelationVariables -> RelationVariables -> GraphRefRelationalExprM RelationVariables
3842unionMergeRelVars prefer relvarsA relvarsB = do
3943 let allNames = S.toList (S.union (M.keysSet relvarsA) (M.keysSet relvarsB))
4044 foldM (\acc name -> do
src/lib/ProjectM36/TransactionGraph/Persist.hs+8−5
@@ -1,8 +1,8 @@
11module ProjectM36.TransactionGraph.Persist where
22import ProjectM36.Error
3−import ProjectM36.TransactionGraph
43import ProjectM36.Transaction
54import ProjectM36.Transaction.Persist
5+import ProjectM36.RelationalExpression
66import ProjectM36.Base
77import ProjectM36.ScriptSession
88import ProjectM36.Persist (writeFileSync, renameSync, DiskSync)
@@ -24,7 +24,9 @@ import Control.Exception.Base
2424import qualified Data.ByteString as BS
2525import qualified Data.Text.Encoding as TE
2626import Data.ByteString (ByteString)
27+#if __GLASGOW_HASKELL__ < 804
2728import Data.Monoid
29+#endif
2830import qualified Crypto.Hash.SHA256 as SHA256
2931import Control.Arrow
3032import Data.Time.Clock
@@ -192,12 +194,12 @@ writeGraphTransactionIdFile sync destDirectory (TransactionGraph _ transSet) = w
192194 uuidInfo = T.intercalate "\n" graphLines
193195 digest = SHA256.hash (encodeUtf8 uuidInfo)
194196 graphLines = S.toList $ S.map graphLine transSet
195− epochTime = realToFrac . utcTimeToPOSIXSeconds . transactionTimestamp :: Transaction -> Double
197+ epochTime = realToFrac . utcTimeToPOSIXSeconds . timestamp :: Transaction -> Double
196198 graphLine trans = U.toText (transactionId trans)
197199 <> " "
198200 <> T.pack (show (epochTime trans))
199201 <> " "
200− <> T.intercalate " " (S.toList (S.map U.toText $ transactionParentIds trans))
202+ <> T.intercalate " " (S.toList (S.map U.toText $ parentIds trans))
201203
202204readGraphTransactionIdFileDigest :: FilePath -> IO LockFileHash
203205readGraphTransactionIdFileDigest dbdir = do
@@ -207,8 +209,8 @@ readGraphTransactionIdFileDigest dbdir = do
207209readGraphTransactionIdFile :: FilePath -> IO (Either PersistenceError [(TransactionId, UTCTime, [TransactionId])])
208210readGraphTransactionIdFile dbdir = do
209211 --read in all transactions' uuids
210− let grapher line = let tid:epochText:parentIds = T.words line in
211− (readUUID tid, readEpoch epochText, map readUUID parentIds)
212+ let grapher line = let tid:epochText:parentIds' = T.words line in
213+ (readUUID tid, readEpoch epochText, map readUUID parentIds')
212214 readUUID uuidText = fromMaybe (error "failed to read uuid") (U.fromText uuidText)
213215 readEpoch t = posixSecondsToUTCTime (realToFrac (either (error "failed to read epoch") fst (double t)))
214216 Right . map grapher . T.lines <$> readUTF8FileOrError (transactionLogPath dbdir)
@@ -223,3 +225,4 @@ readUTF8FileOrError pathIn = do
223225 case TE.decodeUtf8' fileBytes of
224226 Left err -> error (show err)
225227 Right utf8Bytes -> pure utf8Bytes
228+
src/lib/ProjectM36/TransactionGraph/Show.hs+3−4
@@ -1,17 +1,16 @@
11module ProjectM36.TransactionGraph.Show where
22import ProjectM36.Base
33import ProjectM36.TransactionGraph
4−import ProjectM36.Transaction
54import qualified Data.Set as S
65
76showTransactionStructure :: Transaction -> TransactionGraph -> String
8−showTransactionStructure trans graph = headInfo ++ " " ++ show (transactionId trans) ++ " p" ++ parentTransactionsInfo ++ " c" ++ childTransactionsInfo
7+showTransactionStructure trans graph = headInfo ++ " " ++ show (transactionId trans) ++ " p" ++ parentTransactionsInfo
98 where
109 headInfo = maybe "" show (headNameForTransaction trans graph)
11− parentTransactionsInfo = if isRootTransaction trans graph then "root" else case parentTransactions trans graph of
10+ parentTransactionsInfo = if isRootTransaction trans then "root" else case parentTransactions trans graph of
1211 Left err -> show err
1312 Right parentTransSet -> concat $ S.toList $ S.map (show . transactionId) parentTransSet
14− childTransactionsInfo = show (S.toList (transactionChildIds trans))
13+
1514
1615showGraphStructure :: TransactionGraph -> String
1716showGraphStructure graph@(TransactionGraph _ transSet) = S.foldr folder "" transSet
src/lib/ProjectM36/TransactionGraph/Types.hsnew file+12
@@ -0,0 +1,12 @@
1+module ProjectM36.TransactionGraph.Types where
2+import ProjectM36.Base
3+
4+transactions :: TransactionGraph -> S.Set Transaction
5+transactions (TransactionGraph _ t) = t
6+
7+transactionHeads :: TransactionGraph -> TransactionHeads
8+transactionHeads (TransactionGraph heads _) = heads
9+
10+transactionInfoDiffs :: TransactionInfo -> TransactionDiffs
11+transactionInfoDiffs (TransactionInfo _ d _) = d
12+transactionInfoDiffs (MergeTransactionInfo _ _ d _ ) = d
src/lib/ProjectM36/TransactionInfo.hsnew file+12
@@ -0,0 +1,12 @@
1+module ProjectM36.TransactionInfo where
2+import ProjectM36.Base
3+import Data.Time.Clock
4+import qualified Data.List.NonEmpty as NE
5+
6+-- | Create a TransactionInfo with just one parent transaction ID.
7+singleParent :: TransactionId -> UTCTime -> TransactionInfo
8+singleParent tid stamp' = TransactionInfo {
9+ parents = tid NE.:| [],
10+ stamp = stamp',
11+ merkleHash = mempty }
12+
src/lib/ProjectM36/Tuple.hs+47−33
@@ -1,7 +1,7 @@
11module ProjectM36.Tuple where
22import ProjectM36.Base
33import ProjectM36.Error
4−import ProjectM36.Attribute
4+import ProjectM36.Attribute as A
55import ProjectM36.Atom
66import ProjectM36.AtomType
77import ProjectM36.DataTypes.Primitive
@@ -15,19 +15,19 @@ import Control.Arrow
1515import Data.Maybe
1616
1717emptyTuple :: RelationTuple
18−emptyTuple = RelationTuple V.empty V.empty
18+emptyTuple = RelationTuple mempty mempty
1919
2020tupleSize :: RelationTuple -> Int
21−tupleSize (RelationTuple tupAttrs _) = V.length tupAttrs
21+tupleSize (RelationTuple tupAttrs _) = arity tupAttrs
2222
2323tupleAttributeNameSet :: RelationTuple -> S.Set AttributeName
24−tupleAttributeNameSet (RelationTuple tupAttrs _) = S.fromList $ V.toList $ V.map attributeName tupAttrs
24+tupleAttributeNameSet (RelationTuple tupAttrs _) = attributeNameSet tupAttrs
2525
2626tupleAttributes :: RelationTuple -> Attributes
2727tupleAttributes (RelationTuple tupAttrs _) = tupAttrs
2828
2929tupleAssocs :: RelationTuple -> [(AttributeName, Atom)]
30−tupleAssocs (RelationTuple attrVec tupVec) = V.toList $ V.map (first attributeName) (V.zip attrVec tupVec)
30+tupleAssocs (RelationTuple attrs tupVec) = V.toList $ V.map (first attributeName) (V.zip (attributesVec attrs) tupVec)
3131
3232orderedTupleAssocs :: RelationTuple -> [(AttributeName, Atom)]
3333orderedTupleAssocs tup@(RelationTuple attrVec _) = map (\attr -> (attributeName attr, atomForAttr (attributeName attr))) oAttrs
@@ -42,7 +42,7 @@ tupleAtoms :: RelationTuple -> V.Vector Atom
4242tupleAtoms (RelationTuple _ tupVec) = tupVec
4343
4444atomForAttributeName :: AttributeName -> RelationTuple -> Either RelationalError Atom
45−atomForAttributeName attrName (RelationTuple tupAttrs tupVec) = case V.findIndex (\attr -> attributeName attr == attrName) tupAttrs of
45+atomForAttributeName attrName (RelationTuple tupAttrs tupVec) = case V.findIndex (\attr -> attributeName attr == attrName) (attributesVec tupAttrs) of
4646 Nothing -> Left (NoSuchAttributeNamesError (S.singleton attrName))
4747 Just index -> case tupVec V.!? index of
4848 Nothing -> Left (NoSuchAttributeNamesError (S.singleton attrName))
@@ -59,7 +59,7 @@ vectorIndicesForAttributeNames attrNameVec attrs = if not $ V.null unknownAttrNa
5959 Right $ V.map mapper attrNameVec
6060 where
6161 unknownAttrNames = V.filter (`V.notElem` attributeNames attrs) attrNameVec
62− mapper attrName = fromMaybe (error "logic failure in vectorIndicesForAttributeNames") (V.elemIndex attrName (V.map attributeName attrs))
62+ mapper attrName = fromMaybe (error "logic failure in vectorIndicesForAttributeNames") (V.elemIndex attrName (attributeNames attrs))
6363
6464
6565relationForAttributeName :: AttributeName -> RelationTuple -> Either RelationalError Relation
@@ -86,10 +86,10 @@ mkRelationTuples attrs = map mapper
8686 mapper = mkRelationTuple attrs
8787
8888mkRelationTupleFromMap :: M.Map AttributeName Atom -> RelationTuple
89−mkRelationTupleFromMap attrMap = RelationTuple attrs (V.map (\attrName -> attrMap M.! attrName) attrNames)
89+mkRelationTupleFromMap attrMap = RelationTuple (attributesFromList attrs) (V.map (attrMap M.!) (V.fromList attrNames))
9090 where
91− attrNames = V.fromList (M.keys attrMap)
92− attrs = V.map (\attrName -> Attribute attrName (atomTypeForAtom (attrMap M.! attrName))) attrNames
91+ attrNames = M.keys attrMap
92+ attrs = map (\attrName -> Attribute attrName (atomTypeForAtom (attrMap M.! attrName))) attrNames
9393
9494--return error if attribute names match but their types do not
9595singleTupleSetJoin :: Attributes -> RelationTuple -> RelationTupleSet -> Either RelationalError [RelationTuple]
@@ -120,8 +120,8 @@ singleTupleJoin joinedAttrs tup1@(RelationTuple tupAttrs1 _) tup2@(RelationTuple
120120 return $ Just $ RelationTuple joinedAttrs newVec
121121 where
122122 keysIntersection = V.map attributeName attrsIntersection
123− attrsIntersection = V.filter (`V.elem` tupAttrs1) tupAttrs2
124− newVec = V.map (findAtomForAttributeName . attributeName) joinedAttrs
123+ attrsIntersection = V.filter (`V.elem` attributesVec tupAttrs1) (attributesVec tupAttrs2)
124+ newVec = V.map (findAtomForAttributeName . attributeName) (attributesVec joinedAttrs)
125125 --search both tuples for the attribute
126126 findAtomForAttributeName attrName = head $ rights $ fmap (atomForAttributeName attrName) [tup1, tup2]
127127
@@ -138,23 +138,31 @@ vectorUnion v1 v2 = V.foldr folder v1 v2
138138tupleExtend :: RelationTuple -> RelationTuple -> RelationTuple
139139tupleExtend (RelationTuple tupAttrs1 tupVec1) (RelationTuple tupAttrs2 tupVec2) = RelationTuple newAttrs newVec
140140 where
141− newAttrs = tupAttrs1 V.++ tupAttrs2
142− newVec = tupVec1 V.++ tupVec2
141+ newAttrs = tupAttrs1 <> tupAttrs2
142+ newVec = tupVec1 <> tupVec2
143143
144144tupleAtomExtend :: AttributeName -> Atom -> RelationTuple -> RelationTuple
145145tupleAtomExtend newAttrName atom tupIn = tupleExtend tupIn newTup
146146 where
147− newTup = RelationTuple (V.singleton $ Attribute newAttrName (atomTypeForAtom atom)) (V.singleton atom)
147+ newTup = RelationTuple (A.singleton $ Attribute newAttrName (atomTypeForAtom atom)) (V.singleton atom)
148148
149−--this could be cheaper- it may not be wortwhile to update all the tuples for projection, but then the attribute management must be slightly different- perhaps the attributes should be a vector of association tuples [(name, index)]
150−tupleProject :: S.Set AttributeName -> RelationTuple -> RelationTuple
149+{-tupleProject :: S.Set AttributeName -> RelationTuple -> RelationTuple
151150tupleProject projectAttrs (RelationTuple attrs tupVec) = RelationTuple newAttrs newTupVec
152151 where
153− deleteIndices = V.findIndices (\attr -> S.notMember (attributeName attr) projectAttrs) attrs
152+ deleteIndices = V.findIndices (\attr -> S.notMember (attributeName attr) projectAttrs) (attributesVec attrs)
154153 indexDeleter = V.ifilter (\index _ -> V.notElem index deleteIndices)
155− newAttrs = indexDeleter attrs
154+ newAttrs = case A.projectionAttributesForNames projectAttrs attrs of
155+ Left err -> error (show (err, projectAttrs, attrs))
156+ Right attrs' -> attrs'
156157 newTupVec = indexDeleter tupVec
157−
158+-}
159+-- remember that the attributes order matters
160+tupleProject :: Attributes -> RelationTuple -> Either RelationalError RelationTuple
161+tupleProject projectAttrs tup = do
162+ newTupVec <- foldM (\acc attr ->
163+ V.snoc acc <$> atomForAttributeName (attributeName attr) tup
164+ ) V.empty (attributesVec projectAttrs)
165+ pure $ reorderTuple projectAttrs (RelationTuple projectAttrs newTupVec)
158166--return the attributes and atoms which are equal in both vectors
159167--semi-join
160168tupleIntersection :: RelationTuple -> RelationTuple -> RelationTuple
@@ -162,12 +170,14 @@ tupleIntersection tuple1 tuple2 = RelationTuple newAttrs newTupVec
162170 where
163171 attrs1 = tupleAttributes tuple1
164172 attrs2 = tupleAttributes tuple2
165− matchingIndices = V.findIndices (\attr -> V.elem attr attrs2 &&
166− atomForAttributeName (attributeName attr) tuple1 ==
167− atomForAttributeName (attributeName attr) tuple2
168− ) attrs1
173+ intersectAttrs = A.intersection attrs1 attrs2
174+ matchingIndices = V.findIndices (\attr -> A.member attr intersectAttrs &&
175+ atomForAttributeName (attributeName attr) tuple1 ==
176+ atomForAttributeName (attributeName attr) tuple2) (attributesVec attrs1)
169177 indexFilter = V.ifilter (\index _ -> V.elem index matchingIndices)
170− newAttrs = indexFilter attrs1
178+ newAttrs = case A.projectionAttributesForNames (A.attributeNameSet intersectAttrs) attrs1 of
179+ Left _ -> mempty
180+ Right attrs' -> attrs'
171181 newTupVec = indexFilter (tupleAtoms tuple1)
172182
173183-- | An optimized form of tuple update which updates vectors efficiently.
@@ -175,19 +185,20 @@ updateTupleWithAtoms :: M.Map AttributeName Atom -> RelationTuple -> RelationTup
175185updateTupleWithAtoms updateMap (RelationTuple attrs tupVec) = RelationTuple attrs newVec
176186 where
177187 updateKeysSet = M.keysSet updateMap
178− updateKeysIVec = V.filter (\(_,attr) -> S.member (attributeName attr) updateKeysSet) (V.indexed attrs)
188+ updateKeysIVec = V.filter (\(_,attr) -> S.member (attributeName attr) updateKeysSet) (V.indexed (attributesVec attrs))
179189 newVec = V.update tupVec updateVec
180190 updateVec = V.map (\(index, attr) -> (index, updateMap M.! attributeName attr)) updateKeysIVec
181191
182192tupleToMap :: RelationTuple -> M.Map AttributeName Atom
183193tupleToMap (RelationTuple attrs tupVec) = M.fromList assocList
184194 where
185− assocList = V.toList $ V.map (\(index, attr) -> (attributeName attr, tupVec V.! index)) (V.indexed attrs)
195+ assocList = V.toList $ V.map (\(index, attr) -> (attributeName attr, tupVec V.! index)) (V.indexed (attributesVec attrs))
186196
197+-- | Validate that the tuple has the correct attributes in the correct order
187198verifyTuple :: Attributes -> RelationTuple -> Either RelationalError RelationTuple
188−verifyTuple attrs tuple = let attrsTypes = V.map atomType attrs
199+verifyTuple attrs tuple = let attrsTypes = A.atomTypes attrs
189200 tupleTypes = V.map atomTypeForAtom (tupleAtoms tuple) in
190− if V.length attrs /= V.length tupleTypes then
201+ if A.arity attrs /= V.length tupleTypes then
191202 Left $ TupleAttributeCountMismatchError 0
192203 else do
193204 mapM_ (uncurry atomTypeVerify) (V.zip attrsTypes tupleTypes)
@@ -196,15 +207,18 @@ verifyTuple attrs tuple = let attrsTypes = V.map atomType attrs
196207--two tuples can be equal but the vectors of attributes could be out-of-order
197208--reorder if necessary- this is useful during relMogrify so that all the relation's tuples have identical atom/attribute ordering
198209reorderTuple :: Attributes -> RelationTuple -> RelationTuple
199−reorderTuple attrs tupIn = if tupleAttributes tupIn == attrs then
210+reorderTuple attrs tupIn = if attributesAndOrderEqual (tupleAttributes tupIn) attrs then
200211 tupIn
201212 else
202− RelationTuple attrs (V.map mapper attrs)
213+ RelationTuple attrs (V.map mapper (attributesVec attrs))
203214 where
204215 mapper attr = case atomForAttributeName (attributeName attr) tupIn of
205− Left err -> error ("logic bug in reorderTuple: " ++ show err)
216+ Left err -> error ("logic bug in reorderTuple: " ++ show err <> show tupIn)
206217 Right atom -> atom
207218
208219--used in Generics derivation for ADTs without named attributes
209220trimTuple :: Int -> RelationTuple -> RelationTuple
210−trimTuple index (RelationTuple attrs vals) = RelationTuple (V.drop index attrs) (V.drop index vals)
221+trimTuple index (RelationTuple attrs vals) =
222+ RelationTuple newAttrs (V.drop index vals)
223+ where
224+ newAttrs = A.drop index attrs
src/lib/ProjectM36/TupleSet.hs+7
@@ -31,3 +31,10 @@ mkTupleSet attrs tuples = verifyTupleSet attrs (RelationTupleSet tuples)
3131
3232mkTupleSetFromList :: Attributes -> [[Atom]] -> Either RelationalError RelationTupleSet
3333mkTupleSetFromList attrs atomMatrix = mkTupleSet attrs $ map (mkRelationTuple attrs . V.fromList) atomMatrix
34+
35+
36+-- | Union two tuplesets while reordering their attribute/atom mapping properly.
37+tupleSetUnion :: Attributes -> RelationTupleSet -> RelationTupleSet -> RelationTupleSet
38+tupleSetUnion targetAttrs tupSet1 tupSet2 = RelationTupleSet $ HS.toList . HS.fromList $ reorder (asList tupSet1) ++ reorder (asList tupSet2)
39+ where
40+ reorder = map (reorderTuple targetAttrs)
src/lib/ProjectM36/Tupleable.hs+112−32
@@ -4,19 +4,41 @@
44{-# LANGUAGE ScopedTypeVariables #-}
55{-# LANGUAGE TypeOperators #-}
66{-# LANGUAGE UndecidableInstances #-}
7−
8−module ProjectM36.Tupleable where
7+{-# LANGUAGE CPP #-}
8+
9+module ProjectM36.Tupleable
10+ ( toInsertExpr
11+ , toDefineExpr
12+ , tupleAssocsEqualityPredicate
13+ , partitionByAttributes
14+ , toUpdateExpr
15+ , toDeleteExpr
16+ , validateAttributes
17+ , Tupleable(..)
18+
19+ -- * Generics
20+ , genericToTuple
21+ , genericFromTuple
22+ , genericToAttributes
23+ , TupleableG(..)
24+ -- ** Options
25+ , defaultTupleableOptions
26+ , TupleableOptions()
27+ , fieldModifier
28+ ) where
929
1030import Data.Foldable
1131import Data.List (partition)
1232import qualified Data.Map as Map
33+#if __GLASGOW_HASKELL__ < 804
1334import Data.Monoid
35+#endif
1436import Data.Proxy
1537import qualified Data.Text as T
1638import qualified Data.Vector as V
1739import GHC.Generics
1840import ProjectM36.Atomable
19−import ProjectM36.Attribute hiding (null)
41+import ProjectM36.Attribute as A hiding (null, toList)
2042import ProjectM36.Base
2143import ProjectM36.DataTypes.Primitive
2244import ProjectM36.Error
@@ -67,7 +89,7 @@ toInsertExpr vals rvName = do
6789
6890-- | Convert a 'Tupleable' to a create a 'Define' expression which can be used to create an empty relation variable. Use 'toInsertExpr' to insert the actual tuple data. This function is typically used with 'Data.Proxy'.
6991toDefineExpr :: forall a proxy. Tupleable a => proxy a -> RelVarName -> DatabaseContextExpr
70−toDefineExpr _ rvName = Define rvName (map NakedAttributeExpr (V.toList attrs))
92+toDefineExpr _ rvName = Define rvName (map NakedAttributeExpr (V.toList (attributesVec attrs)))
7193 where
7294 attrs = toAttributes (Proxy :: Proxy a)
7395
@@ -118,56 +140,110 @@ validateAttributes actualAttrs expectedAttrs val
118140 where
119141 nonMatchingAttrs = attributeNamesNotContained actualAttrs expectedAttrs
120142
121−
143+-- | Types that can be converted to and from 'RelationTuple'.
144+--
145+-- deriving without customization:
146+--
147+-- > data Example = Example
148+-- > { foo :: Integer
149+-- > , bar :: Text
150+-- > }
151+-- > deriving (Generic)
152+-- >
153+-- > instance Tupleable Example
154+--
155+-- deriving with customization using "ProjectM36.Tupleable.Deriving":
156+--
157+-- > data Example = Example
158+-- > { exampleFoo :: Integer
159+-- > , exampleBar :: Text
160+-- > }
161+-- > deriving stock (Generic)
162+-- > deriving (Tupleable)
163+-- > via Codec (Field (DropPrefix "example" >>> CamelCase)) Example
122164class Tupleable a where
123165 toTuple :: a -> RelationTuple
124166
125167 fromTuple :: RelationTuple -> Either RelationalError a
126168
127− toAttributes :: proxy a -> Attributes
169+ toAttributes :: Proxy a -> Attributes
128170
129171 default toTuple :: (Generic a, TupleableG (Rep a)) => a -> RelationTuple
130− toTuple v = toTupleG (from v)
172+ toTuple = genericToTuple defaultTupleableOptions
131173
132174 default fromTuple :: (Generic a, TupleableG (Rep a)) => RelationTuple -> Either RelationalError a
133− fromTuple tup = to <$> fromTupleG tup
175+ fromTuple = genericFromTuple defaultTupleableOptions
176+
177+ default toAttributes :: (Generic a, TupleableG (Rep a)) => Proxy a -> Attributes
178+ toAttributes = genericToAttributes defaultTupleableOptions
179+
180+-- | Options that influence deriving behavior.
181+newtype TupleableOptions = TupleableOptions {
182+ -- | A function that translates record field names into attribute names.
183+ fieldModifier :: T.Text -> T.Text
184+ }
185+
186+-- | The default options for deriving Tupleable instances.
187+--
188+-- These options can be customized by using record update syntax. For example,
189+--
190+-- > defaultTupleableOptions
191+-- > { fieldModifier = \fieldName ->
192+-- > case Data.Text.stripPrefix "example" fieldName of
193+-- > Nothing -> fieldName
194+-- > Just attributeName -> attributeName
195+-- > }
196+--
197+-- will result in record field names being translated into attribute names by
198+-- removing the prefix "example" from the field names.
199+defaultTupleableOptions :: TupleableOptions
200+defaultTupleableOptions = TupleableOptions {
201+ fieldModifier = id
202+ }
203+
204+genericToTuple :: (Generic a, TupleableG (Rep a)) => TupleableOptions -> a -> RelationTuple
205+genericToTuple opts v = toTupleG opts (from v)
206+
207+genericFromTuple :: (Generic a, TupleableG (Rep a)) => TupleableOptions -> RelationTuple -> Either RelationalError a
208+genericFromTuple opts tup = to <$> fromTupleG opts tup
134209
135− default toAttributes :: (Generic a, TupleableG (Rep a)) => proxy a -> Attributes
136− toAttributes _ = toAttributesG (from (undefined :: a))
210+genericToAttributes :: forall a. (Generic a, TupleableG (Rep a)) => TupleableOptions -> Proxy a -> Attributes
211+genericToAttributes opts _ = toAttributesG opts (from (undefined :: a))
137212
138213class TupleableG g where
139− toTupleG :: g a -> RelationTuple
140− toAttributesG :: g a -> Attributes
141− fromTupleG :: RelationTuple -> Either RelationalError (g a)
214+ toTupleG :: TupleableOptions -> g a -> RelationTuple
215+ toAttributesG :: TupleableOptions -> g a -> Attributes
216+ fromTupleG :: TupleableOptions -> RelationTuple -> Either RelationalError (g a)
142217 isRecordTypeG :: g a -> Bool
143218
144219--data type metadata
145220instance (Datatype c, TupleableG a) => TupleableG (M1 D c a) where
146− toTupleG (M1 v) = toTupleG v
147− toAttributesG (M1 v) = toAttributesG v
148− fromTupleG v = M1 <$> fromTupleG v
221+ toTupleG opts (M1 v) = toTupleG opts v
222+ toAttributesG opts (M1 v) = toAttributesG opts v
223+ fromTupleG opts v = M1 <$> fromTupleG opts v
149224 isRecordTypeG (M1 v) = isRecordTypeG v
150225
151226--constructor metadata
152227instance (Constructor c, TupleableG a, AtomableG a) => TupleableG (M1 C c a) where
153− toTupleG (M1 v) = RelationTuple attrs atoms
228+ toTupleG opts (M1 v) = RelationTuple attrs atoms
154229 where
155− attrsToCheck = toAttributesG v
156− counter = V.generate (V.length attrsToCheck) id
157− attrs = V.zipWith (\num attr@(Attribute name typ) -> if T.null name then
230+ attrsToCheck = toAttributesG opts v
231+ counter = V.generate (arity attrsToCheck) id
232+ attrs = attributesFromList (V.toList attrsV)
233+ attrsV = V.zipWith (\num attr@(Attribute name typ) -> if T.null name then
158234 Attribute ("attr" <> T.pack (show (num + 1))) typ
159235 else
160− attr) counter attrsToCheck
236+ attr) counter (attributesVec attrsToCheck)
161237 atoms = V.fromList (toAtomsG v)
162− toAttributesG (M1 v) = toAttributesG v
163− fromTupleG tup = M1 <$> fromTupleG tup
238+ toAttributesG opts (M1 v) = toAttributesG opts v
239+ fromTupleG opts tup = M1 <$> fromTupleG opts tup
164240 isRecordTypeG (M1 v) = isRecordTypeG v
165241
166242-- product types
167243instance (TupleableG a, TupleableG b) => TupleableG (a :*: b) where
168244 toTupleG = error "toTupleG"
169− toAttributesG ~(x :*: y) = toAttributesG x V.++ toAttributesG y --a bit of extra laziness prevents whnf so that we can use toAttributes (undefined :: Test2T Int Int) without throwing an exception
170− fromTupleG tup = (:*:) <$> fromTupleG tup <*> fromTupleG processedTuple
245+ toAttributesG opts ~(x :*: y) = toAttributesG opts x <> toAttributesG opts y --a bit of extra laziness prevents whnf so that we can use toAttributes (undefined :: Test2T Int Int) without throwing an exception
246+ fromTupleG opts tup = (:*:) <$> fromTupleG opts tup <*> fromTupleG opts processedTuple
171247 where
172248 processedTuple = if isRecordTypeG (undefined :: a x) then
173249 tup
@@ -178,18 +254,22 @@ instance (TupleableG a, TupleableG b) => TupleableG (a :*: b) where
178254--selector/record
179255instance (Selector c, AtomableG a) => TupleableG (M1 S c a) where
180256 toTupleG = error "toTupleG"
181− toAttributesG m@(M1 v) = V.singleton (Attribute name aType)
257+ toAttributesG opts m@(M1 v) = A.singleton (Attribute modifiedName aType)
182258 where
183259 name = T.pack (selName m)
260+ modifiedName = if T.null name then
261+ name
262+ else
263+ fieldModifier opts name
184264 aType = toAtomTypeG v
185− fromTupleG tup = if null name then -- non-record type, just pull off the first tuple item
265+ fromTupleG opts tup = if null name then -- non-record type, just pull off the first tuple item
186266 M1 <$> atomv (V.head (tupleAtoms tup))
187267 else do
188− atom <- atomForAttributeName (T.pack name) tup
268+ atom <- atomForAttributeName (fieldModifier opts (T.pack name)) tup
189269 val <- atomv atom
190270 pure (M1 val)
191271 where
192− expectedAtomType = atomType (V.head (toAttributesG (undefined :: M1 S c a x)))
272+ expectedAtomType = atomType (V.head (attributesVec (toAttributesG opts (undefined :: M1 S c a x))))
193273 atomv atom = maybe (Left (AtomTypeMismatchError
194274 expectedAtomType
195275 (atomTypeForAtom atom)
@@ -200,8 +280,8 @@ instance (Selector c, AtomableG a) => TupleableG (M1 S c a) where
200280--constructors with no arguments
201281--basically useless but orthoganal to relationTrue
202282instance TupleableG U1 where
203− toTupleG _= emptyTuple
204− toAttributesG _ = emptyAttributes
205− fromTupleG _ = pure U1
283+ toTupleG _ _ = emptyTuple
284+ toAttributesG _ _ = emptyAttributes
285+ fromTupleG _ _ = pure U1
206286 isRecordTypeG _ = False
207287
src/lib/ProjectM36/Tupleable/Deriving.hsnew file+229
@@ -0,0 +1,229 @@
1+{-# LANGUAGE ScopedTypeVariables #-}
2+{-# LANGUAGE TypeOperators #-}
3+{-# LANGUAGE KindSignatures #-}
4+{-# LANGUAGE DataKinds #-}
5+{-# LANGUAGE FlexibleContexts #-}
6+{-# LANGUAGE UndecidableInstances #-}
7+
8+-- | Newtypes for deriving Tupleable instances with customization using
9+-- @DerivingVia@.
10+--
11+-- Inspired by
12+-- [Dhall.Deriving](https://hackage.haskell.org/package/dhall-1.33.1/docs/Dhall-Deriving.html)
13+-- which in turn was inspired by Matt Parson's blog post
14+-- [Mirror Mirror: Reflection and Encoding Via](https://www.parsonsmatt.org/2020/02/04/mirror_mirror.html).
15+--
16+-- required extensions:
17+--
18+-- * DerivingVia
19+-- * DeriveGenerics
20+-- * TypeOperators (for @('<<<')@ and @('>>>')@)
21+-- * DataKinds (for types that take a string argument)
22+
23+module ProjectM36.Tupleable.Deriving
24+ ( -- * DerivingVia Newtype
25+ Codec(..)
26+
27+ -- * Type-level Options
28+ , ModifyOptions(..)
29+ , Field
30+
31+ -- * Type-level 'T.Text' -> 'T.Text' Functions
32+ , ModifyText(..)
33+ , AddPrefix
34+ , DropPrefix
35+ , AddSuffix
36+ , DropSuffix
37+ , UpperCase
38+ , LowerCase
39+ , TitleCase
40+ , CamelCase
41+ , PascalCase
42+ , SnakeCase
43+ , SpinalCase
44+ , TrainCase
45+
46+ -- * Composition
47+ , AsIs
48+ , type (<<<)
49+ , type (>>>)
50+
51+ -- * Re-Exports
52+ , Generic
53+ , module ProjectM36.Tupleable
54+ ) where
55+import Data.Maybe (fromMaybe)
56+import Data.Proxy
57+import qualified Data.Text as T
58+import Data.Text.Manipulate
59+import GHC.TypeLits
60+import GHC.Generics (Generic, Rep)
61+import ProjectM36.Tupleable
62+
63+
64+-- | A newtype wrapper to allow for easier deriving of 'Tupleable' instances
65+-- with customization.
66+--
67+-- The @tag@ type variable can be used to specify options for converting the
68+-- datatype to and from a 'RelationTuple'. For example,
69+--
70+-- > data Example = Example
71+-- > { exampleFoo :: Int
72+-- > , exampleBar :: Int
73+-- > }
74+-- > deriving stock (Generic)
75+-- > deriving (Tupleable)
76+-- > via Codec (Field (DropPrefix "example" >>> CamelCase)) Example
77+--
78+-- will derive an instance of 'Tupleable' where field names are translated into
79+-- attribute names by dropping the prefix @"example"@ and then converting the
80+-- result to camelCase. So @"exampleFoo"@ becomes @"foo"@ and @"exampleBar"@
81+-- becomes @"bar"@.
82+--
83+-- Requires the @DerivingGeneric@ and @DerivingVia@ extensions to be enabled.
84+newtype Codec tag a = Codec { unCodec :: a }
85+
86+instance (ModifyOptions tag, Generic a, TupleableG (Rep a)) => Tupleable (Codec tag a) where
87+ toTuple v = genericToTuple opts (unCodec v)
88+ where
89+ opts = modifyOptions (Proxy :: Proxy tag) defaultTupleableOptions
90+
91+ fromTuple tup = Codec <$> genericFromTuple opts tup
92+ where
93+ opts = modifyOptions (Proxy :: Proxy tag) defaultTupleableOptions
94+
95+ toAttributes _ = genericToAttributes opts (Proxy :: Proxy a)
96+ where
97+ opts = modifyOptions (Proxy :: Proxy tag) defaultTupleableOptions
98+
99+-- | Types that can be used as tags for 'Codec'.
100+class ModifyOptions a where
101+ modifyOptions :: proxy a -> TupleableOptions -> TupleableOptions
102+
103+-- | Change how record field names are translated into attribute names. For
104+-- example,
105+--
106+-- > Field SnakeCase
107+--
108+-- will translate the field name @fooBar@ into the attribute name @foo_bar@.
109+data Field a
110+
111+instance ModifyText a => ModifyOptions (Field a) where
112+ modifyOptions _ opts = opts { fieldModifier = newFieldModifier }
113+ where
114+ newFieldModifier = modifyText (Proxy :: Proxy a) . fieldModifier opts
115+
116+-- | Types that can be used in options that modify 'T.Text' such as in 'Field'.
117+class ModifyText a where
118+ modifyText :: proxy a -> T.Text -> T.Text
119+
120+-- | Add a prefix. @AddPrefix "foo"@ will transform @"bar"@ into @"foobar"@.
121+data AddPrefix (prefix :: Symbol)
122+
123+instance KnownSymbol prefix => ModifyText (AddPrefix prefix) where
124+ modifyText _ oldText = prefixText <> oldText
125+ where
126+ prefixText = T.pack (symbolVal (Proxy :: Proxy prefix))
127+
128+-- | Drop a prefix. @DropPrefix "bar"@ will transform @"foobar"@ into @"foo"@.
129+data DropPrefix (prefix :: Symbol)
130+
131+instance KnownSymbol prefix => ModifyText (DropPrefix prefix) where
132+ modifyText _ oldText = fromMaybe oldText (T.stripPrefix prefixText oldText)
133+ where
134+ prefixText = T.pack (symbolVal (Proxy :: Proxy prefix))
135+
136+-- | Add a suffix. @AddSuffix "bar"@ will transform @"foo"@ into @"foobar"@.
137+data AddSuffix (suffix :: Symbol)
138+
139+instance KnownSymbol suffix => ModifyText (AddSuffix suffix) where
140+ modifyText _ oldText = oldText <> suffixText
141+ where
142+ suffixText = T.pack (symbolVal (Proxy :: Proxy suffix))
143+
144+-- | Drop a suffix. @DropSuffix "bar"@ will transform @"foobar"@ into @"foo"@.
145+data DropSuffix (suffix :: Symbol)
146+
147+instance KnownSymbol suffix => ModifyText (DropSuffix suffix) where
148+ modifyText _ oldText = fromMaybe oldText (T.stripSuffix suffixText oldText)
149+ where
150+ suffixText = T.pack (symbolVal (Proxy :: Proxy suffix))
151+
152+-- | Convert to UPPERCASE. Will transform @"foobar"@ into @\"FOOBAR\"@.
153+data UpperCase
154+
155+instance ModifyText UpperCase where
156+ modifyText _ = T.toUpper
157+
158+-- | Convert to lowercase. Will transform @\"FOOBAR\"@ into @"foobar"@.
159+data LowerCase
160+
161+instance ModifyText LowerCase where
162+ modifyText _ = T.toLower
163+
164+-- | Convert to Title Case. Will transform @"fooBar"@ into @\"Foo Bar\"@.
165+data TitleCase
166+
167+instance ModifyText TitleCase where
168+ modifyText _ = toTitle
169+
170+-- | Convert to camelCase. Will transform @"foo_bar"@ into @"fooBar"@.
171+data CamelCase
172+
173+instance ModifyText CamelCase where
174+ modifyText _ = toCamel
175+
176+-- | Convert to PascalCase. Will transform @"foo_bar"@ into @\"FooBar\"@.
177+data PascalCase
178+
179+instance ModifyText PascalCase where
180+ modifyText _ = toPascal
181+
182+-- | Convert to snake_case. Will transform @"fooBar"@ into @"foo_bar"@.
183+data SnakeCase
184+
185+instance ModifyText SnakeCase where
186+ modifyText _ = toSnake
187+
188+-- | Convert to spinal-case. will transform @"fooBar"@ into @"foo-bar"@.
189+data SpinalCase
190+
191+instance ModifyText SpinalCase where
192+ modifyText _ = toSpinal
193+
194+-- | Convert to Train-Case. Will transform @"fooBar"@ into @\"Foo-Bar\"@.
195+data TrainCase
196+
197+instance ModifyText TrainCase where
198+ modifyText _ = toTrain
199+
200+-- | Identity option.
201+type AsIs = ()
202+
203+instance ModifyOptions () where
204+ modifyOptions _ = id
205+
206+instance ModifyText () where
207+ modifyText _ = id
208+
209+-- | Right to left composition.
210+--
211+-- Requires the @TypeOperators@ extension to be enabled.
212+data a <<< b
213+
214+instance (ModifyOptions a, ModifyOptions b) => ModifyOptions (a <<< b) where
215+ modifyOptions _ = modifyOptions (Proxy :: Proxy a) . modifyOptions (Proxy :: Proxy b)
216+
217+instance (ModifyText a, ModifyText b) => ModifyText (a <<< b) where
218+ modifyText _ = modifyText (Proxy :: Proxy a) . modifyText (Proxy :: Proxy b)
219+
220+-- | Left to right composition.
221+--
222+-- Requires the @TypeOperators@ extension to be enabled.
223+data a >>> b
224+
225+instance (ModifyOptions a, ModifyOptions b) => ModifyOptions (a >>> b) where
226+ modifyOptions _ = modifyOptions (Proxy :: Proxy b) . modifyOptions (Proxy :: Proxy a)
227+
228+instance (ModifyText a, ModifyText b) => ModifyText (a >>> b) where
229+ modifyText _ = modifyText (Proxy :: Proxy b) . modifyText (Proxy :: Proxy a)
src/lib/ProjectM36/WithNameExpr.hsnew file+86
@@ -0,0 +1,86 @@
1+module ProjectM36.WithNameExpr where
2+import ProjectM36.Base
3+
4+-- substitute all instances of With-based macros to remove macro context
5+-- ideally, we would use a different relational expr type to "prove" that the with macros can no longer exist
6+type WithNameAssocs = [(GraphRefWithNameExpr, GraphRefRelationalExpr)]
7+-- | Drop macros into the relational expression wherever they are referenced.
8+substituteWithNameMacros ::
9+ WithNameAssocs ->
10+ GraphRefRelationalExpr ->
11+ GraphRefRelationalExpr
12+substituteWithNameMacros _ e@MakeRelationFromExprs{} = e
13+substituteWithNameMacros _ e@MakeStaticRelation{} = e
14+substituteWithNameMacros _ e@ExistingRelation{} = e
15+substituteWithNameMacros macros e@(RelationVariable rvname tid) =
16+ let
17+ macroFilt (WithNameExpr macroName macroTid, _) = rvname == macroName && tid== macroTid in
18+ case filter macroFilt macros of
19+ [] -> e
20+ [(_,replacement)] -> replacement
21+ _ -> error "more than one macro matched!"
22+substituteWithNameMacros macros (Project attrs expr) =
23+ Project attrs (substituteWithNameMacros macros expr)
24+substituteWithNameMacros macros (Union exprA exprB) =
25+ Union (substituteWithNameMacros macros exprA) (substituteWithNameMacros macros exprB)
26+substituteWithNameMacros macros (Join exprA exprB) =
27+ Join (substituteWithNameMacros macros exprA) (substituteWithNameMacros macros exprB)
28+substituteWithNameMacros macros (Rename attrA attrB expr) =
29+ Rename attrA attrB (substituteWithNameMacros macros expr)
30+substituteWithNameMacros macros (Difference exprA exprB) =
31+ Difference (substituteWithNameMacros macros exprA) (substituteWithNameMacros macros exprB)
32+substituteWithNameMacros macros (Group attrs attr expr) =
33+ Group attrs attr (substituteWithNameMacros macros expr)
34+substituteWithNameMacros macros (Ungroup attr expr) =
35+ Ungroup attr (substituteWithNameMacros macros expr)
36+substituteWithNameMacros macros (Restrict pred' expr) =
37+ Restrict (substituteWithNameMacrosRestrictionPredicate macros pred') (substituteWithNameMacros macros expr)
38+substituteWithNameMacros macros (Equals exprA exprB) =
39+ Equals (substituteWithNameMacros macros exprA) (substituteWithNameMacros macros exprB)
40+substituteWithNameMacros macros (NotEquals exprA exprB) =
41+ NotEquals (substituteWithNameMacros macros exprA) (substituteWithNameMacros macros exprB)
42+substituteWithNameMacros macros (Extend extendTup expr) =
43+ Extend (substituteWitNameMacrosExtendTupleExpr macros extendTup) (substituteWithNameMacros macros expr)
44+substituteWithNameMacros macros (With moreMacros expr) =
45+ --collect and update nested with exprs
46+ let newMacros = foldr macroFolder macros moreMacros
47+ macroFolder (wnexpr, mexpr) acc =
48+ let subExpr = substituteWithNameMacros macros mexpr in
49+ filter (\(w,_) -> w /= wnexpr) acc ++ [(wnexpr, subExpr)] in
50+ --scan for a match- if it exists, replace it (representing a with clause at a lower level
51+ substituteWithNameMacros newMacros expr
52+
53+
54+substituteWithNameMacrosRestrictionPredicate :: WithNameAssocs -> GraphRefRestrictionPredicateExpr -> GraphRefRestrictionPredicateExpr
55+substituteWithNameMacrosRestrictionPredicate macros pred' =
56+ let sub = substituteWithNameMacrosRestrictionPredicate macros in
57+ case pred' of
58+ TruePredicate -> pred'
59+ AndPredicate exprA exprB ->
60+ AndPredicate (sub exprA) (sub exprB)
61+ OrPredicate exprA exprB ->
62+ OrPredicate (sub exprA) (sub exprB)
63+ NotPredicate expr ->
64+ NotPredicate (sub expr)
65+ RelationalExprPredicate reexpr ->
66+ RelationalExprPredicate (substituteWithNameMacros macros reexpr)
67+ AtomExprPredicate atomExpr ->
68+ AtomExprPredicate (substituteWithNameMacrosAtomExpr macros atomExpr)
69+ AttributeEqualityPredicate attrName atomExpr ->
70+ AttributeEqualityPredicate attrName (substituteWithNameMacrosAtomExpr macros atomExpr)
71+
72+substituteWitNameMacrosExtendTupleExpr :: WithNameAssocs -> GraphRefExtendTupleExpr -> GraphRefExtendTupleExpr
73+substituteWitNameMacrosExtendTupleExpr macros (AttributeExtendTupleExpr attrName atomExpr) =
74+ AttributeExtendTupleExpr attrName (substituteWithNameMacrosAtomExpr macros atomExpr)
75+
76+substituteWithNameMacrosAtomExpr :: WithNameAssocs -> GraphRefAtomExpr -> GraphRefAtomExpr
77+substituteWithNameMacrosAtomExpr macros atomExpr =
78+ case atomExpr of
79+ e@AttributeAtomExpr{} -> e
80+ e@NakedAtomExpr{} -> e
81+ FunctionAtomExpr fname atomExprs tid ->
82+ FunctionAtomExpr fname (map (substituteWithNameMacrosAtomExpr macros) atomExprs) tid
83+ RelationAtomExpr reExpr ->
84+ RelationAtomExpr (substituteWithNameMacros macros reExpr)
85+ ConstructedAtomExpr dconsName atomExprs tid ->
86+ ConstructedAtomExpr dconsName (map (substituteWithNameMacrosAtomExpr macros) atomExprs) tid
stack.ghc8.0.yamldeleted−50
@@ -1,50 +0,0 @@
1−# This file was automatically generated by stack init
2−# For more information, see: http://docs.haskellstack.org/en/stable/yaml_configuration/
3−
4−# Specifies the GHC version and set of packages available (e.g., lts-3.5, nightly-2015-09-21, ghc-7.10.2)
5−resolver: lts-8.5
6−
7−# Local packages, usually specified by relative directory name
8−packages:
9−- '.'
10−# Packages to be pulled from upstream that are not in the resolver (e.g., acme-missiles-0.3)
11−extra-deps:
12−- data-accessor-transformers-0.2.1.7
13−- data-interval-1.2.0
14−- extended-reals-0.2.1.0
15−- gnuplot-0.5.4.1
16−- text-1.2.2.1
17−- aeson-1.2.1.00
18−- distributed-process-0.6.6
19−- distributed-process-async-0.2.4
20−- distributed-process-client-server-0.2.3
21−- distributed-process-extras-0.3.2
22−- deferred-folds-0.6.12
23−- rset-1.0.0
24−
25−# Override default flag values for local packages and extra-deps
26−flags: {}
27−
28−# Extra package databases containing global packages
29−extra-package-dbs: []
30−
31−# Control whether we use the GHC we find on the path
32−# system-ghc: true
33−
34−# Require a specific version of stack, using version ranges
35−# require-stack-version: -any # Default
36−# require-stack-version: >= 1.0.0
37−
38−# Override the architecture used by stack, especially useful on Windows
39−# arch: i386
40−# arch: x86_64
41−
42−# Extra directories used by stack for building
43−# extra-include-dirs: [/path/to/dir]
44−# extra-lib-dirs: [/path/to/dir]
45−
46−# Allow a newer minor version of GHC than the snapshot specifies
47−# compiler-check: newer-minor
48−
49−allow-newer: true
50−
stack.ghc8.10.yamlnew file+19
@@ -0,0 +1,19 @@
1+resolver: lts-17.13
2+packages:
3+ - "."
4+
5+extra-deps:
6+ - git: https://github.com/agentm/curryer.git
7+ commit: 74ecaac619ad1165a4517d5c0f4e530493bda130
8+ - git: https://github.com/composewell/streamly.git
9+ commit: ac3af8749194f1788704dda8667d0b3807075cc2
10+ - fast-builder-0.1.2.1
11+ - rset-1.0.0
12+ - winery-1.3.2
13+ - barbies-th-0.1.8
14+ - base16-bytestring-1.0.1.0
15+
16+flags:
17+ project-m36:
18+ stack: true
19+# allow-newer: true
stack.ghc8.4.yaml → stack.ghc8.6.yamlrenamed+26−17
@@ -2,29 +2,39 @@
22# For more information, see: http://docs.haskellstack.org/en/stable/yaml_configuration/
33
44# Specifies the GHC version and set of packages available (e.g., lts-3.5, nightly-2015-09-21, ghc-7.10.2)
5−resolver: lts-12.11
5+resolver: lts-14.27
66
77# Local packages, usually specified by relative directory name
88packages:
9−- '.'
9+ - "."
1010# Packages to be pulled from upstream that are not in the resolver (e.g., acme-missiles-0.3)
1111extra-deps:
12−- data-accessor-transformers-0.2.1.7
13−- data-interval-1.2.0
14−- extended-reals-0.2.1.0
15−- gnuplot-0.5.5.3
16−- aeson-1.2.1.00
17−- distributed-process-0.7.4
18−- distributed-process-async-0.2.4.1
19−- distributed-process-client-server-0.2.3
20−- distributed-process-extras-0.3.2
21−#- deferred-folds-0.9.7.1
22−- rset-1.0.0
23−- hashable-time-0.2.0.2
24−- network-transport-tcp-0.6.0
12+ - git: https://github.com/agentm/curryer.git
13+ commit: 74ecaac619ad1165a4517d5c0f4e530493bda130
14+ - git: https://github.com/composewell/streamly.git
15+ commit: ac3af8749194f1788704dda8667d0b3807075cc2
16+ - fast-builder-0.1.2.1
17+ - winery-1.3.2
18+ - barbies-2.0.2.0
19+ - barbies-th-0.1.7
20+ - extended-reals-0.2.3.0
21+ - data-interval-2.0.1
22+ - stm-containers-1.1.0.4
23+ - stm-hamt-1.2.0.4
24+ - rset-1.0.0
25+ - hashable-time-0.2.0.2
26+ - network-transport-tcp-0.6.0
27+ - megaparsec-7.0.5
28+ - prettyprinter-1.7.0
29+ - prettyprinter-ansi-terminal-1.1.2
30+ - fusion-plugin-types-0.1.0
31+ - base16-bytestring-1.0.1.0
32+ - modern-uri-0.3.4.0
33+ - cryptohash-sha256-0.11.102.0
34+ - http-types-0.12.3
2535
2636# Override default flag values for local packages and extra-deps
27−flags:
37+flags:
2838 project-m36:
2939 stack: true
3040
@@ -50,4 +60,3 @@ extra-package-dbs: []
5060# compiler-check: newer-minor
5161
5262allow-newer: true
53−
stack.ghc8.2.yaml → stack.ghc8.8.yamlrenamed+26−15
@@ -2,27 +2,39 @@
22# For more information, see: http://docs.haskellstack.org/en/stable/yaml_configuration/
33
44# Specifies the GHC version and set of packages available (e.g., lts-3.5, nightly-2015-09-21, ghc-7.10.2)
5−resolver: lts-11.20
5+resolver: lts-16.4
66
77# Local packages, usually specified by relative directory name
88packages:
9−- '.'
9+ - "."
1010# Packages to be pulled from upstream that are not in the resolver (e.g., acme-missiles-0.3)
1111extra-deps:
12−- data-accessor-transformers-0.2.1.7
13−- data-interval-1.2.0
14−- extended-reals-0.2.1.0
15−- gnuplot-0.5.4.1
16−- text-1.2.2.1
17−- aeson-1.2.1.00
18−- distributed-process-0.7.3
19−- distributed-process-async-0.2.4.1
20−- distributed-process-client-server-0.2.3
21−- distributed-process-extras-0.3.2
22−- rset-1.0.0
12+ - git: https://github.com/agentm/curryer.git
13+ commit: 74ecaac619ad1165a4517d5c0f4e530493bda130
14+ - git: https://github.com/composewell/streamly.git
15+ commit: ac3af8749194f1788704dda8667d0b3807075cc2
16+ - fast-builder-0.1.2.1
17+ - winery-1.3.2
18+ - barbies-2.0.2.0
19+ - barbies-th-0.1.7
20+ - extended-reals-0.2.3.0
21+ - data-interval-2.0.1
22+ - stm-containers-1.1.0.4
23+ - stm-hamt-1.2.0.4
24+ - rset-1.0.0
25+ - hashable-time-0.2.0.2
26+ - network-transport-tcp-0.7.0
27+ - megaparsec-7.0.5
28+ - network-2.8.0.1
29+ - primitive-extras-0.8
30+ - primitive-unlifted-0.1.3.0
31+ - prettyprinter-1.7.0
32+ - prettyprinter-ansi-terminal-1.1.2
33+ - base16-bytestring-1.0.1.0
34+ - modern-uri-0.3.4.0
2335
2436# Override default flag values for local packages and extra-deps
25−flags:
37+flags:
2638 project-m36:
2739 stack: true
2840
@@ -48,4 +60,3 @@ extra-package-dbs: []
4860# compiler-check: newer-minor
4961
5062allow-newer: true
51−
test/Client/Simple.hs+1−2
@@ -9,7 +9,6 @@ import System.IO.Temp
99import System.FilePath
1010import ProjectM36.TupleSet
1111import ProjectM36.Attribute
12−import qualified Data.Vector as V
1312import qualified Data.Map as M
1413
1514main :: IO ()
@@ -59,7 +58,7 @@ testSimpleCommitFailure = TestCase $ do
5958 execute $ Assign "x" (ExistingRelation relationTrue)
6059 --cause error
6160 execute $ Assign "x" (MakeStaticRelation failAttrs emptyTupleSet)
62− let expectedErr = Left (RelError (RelationTypeMismatchError V.empty failAttrs))
61+ let expectedErr = Left (RelError (RelationTypeMismatchError mempty failAttrs))
6362 assertEqual "dbc error" expectedErr err
6463
6564-- #176 default merge couldn't handle Update
test/IsomorphicSchema.hs+37−27
@@ -4,13 +4,13 @@ import ProjectM36.Error
44import ProjectM36.IsomorphicSchema
55import ProjectM36.Relation
66import ProjectM36.RelationalExpression
7+import ProjectM36.TransactionGraph
8+import ProjectM36.StaticOptimizer
79import qualified ProjectM36.DatabaseContext as DBC
810import qualified ProjectM36.Attribute as A
911import System.Exit
1012import qualified Data.Map as M
1113import qualified Data.Set as S
12−import Control.Monad.State
13−import Control.Monad.Trans.Reader
1414
1515testList :: Test
1616testList = TestList [testIsoRename, testIsoRestrict, testIsoUnion, testSchemaValidation]
@@ -36,7 +36,7 @@ assertMaybe x msg = case x of
3636testSchemaValidation :: Test
3737testSchemaValidation = TestCase $ do
3838 let potentialSchema = DBC.basicDatabaseContext {
39− relationVariables = M.singleton "anotherRel" relationTrue
39+ relationVariables = M.singleton "anotherRel" (ExistingRelation relationTrue)
4040 }
4141 -- missing relvars failure
4242 morphs = [IsoRename "true" "true", IsoRename "false" "false"]
@@ -50,15 +50,17 @@ testSchemaValidation = TestCase $ do
5050testIsoRename :: Test
5151testIsoRename = TestCase $ do
5252 -- create a schema with two relvars and rename one while the other remains the same in the isomorphic schema
53− let schemaA = mkRelationalExprState DBC.empty {
54− relationVariables = M.fromList [("employee", relationTrue),
55− ("department", relationFalse)]
53+ let ctx = DBC.empty {
54+ relationVariables = M.fromList [("employee", ExistingRelation relationTrue),
55+ ("department", ExistingRelation relationFalse)]
5656 }
57− isomorphsAtoB = [IsoRename "emp" "employee",
57+ (graph, _) <- freshTransactionGraph ctx
58+ let isomorphsAtoB = [IsoRename "emp" "employee",
5859 IsoRename "department" "department"]
59− unionExpr = Union (RelationVariable "emp" ()) (RelationVariable "department" ())
60+ unionExpr = Union (RelationVariable "emp" ()) (RelationVariable "department" ())
61+ env = mkRelationalExprEnv ctx graph
6062 relExpr <- assertEither (applyRelationalExprSchemaIsomorphs isomorphsAtoB unionExpr)
61− let relResult = runReader (evalRelationalExpr relExpr) schemaA
63+ let relResult = optimizeAndEvalRelationalExpr env relExpr
6264 assertEqual "employee relation morph" (Right relationTrue) relResult
6365
6466testIsoRestrict :: Test
@@ -67,62 +69,70 @@ testIsoRestrict = TestCase $ do
6769 -- the virtual schema has an employee
6870 let empattrs = A.attributesFromList [Attribute "name" TextAtomType,
6971 Attribute "boss" TextAtomType]
72+ (graph, transId) <- freshTransactionGraph DBC.empty
7073 emprel <- assertEither $ mkRelationFromList empattrs
7174 [[TextAtom "Steve", TextAtom ""],
7275 [TextAtom "Cindy", TextAtom "Steve"],
7376 [TextAtom "Sam", TextAtom "Steve"]]
7477 let predicate = AttributeEqualityPredicate "boss" (NakedAtomExpr (TextAtom ""))
75− bossRel <- assertEither $ runReader (evalRelationalExpr (Restrict predicate (ExistingRelation emprel))) (mkRelationalExprState DBC.empty)
76− nonBossRel <- assertEither $ runReader (evalRelationalExpr (Restrict (NotPredicate predicate) (ExistingRelation emprel))) (mkRelationalExprState DBC.empty)
78+ reenv = mkRelationalExprEnv DBC.empty graph
79+ bossRel <- assertEither $ runRelationalExprM reenv (evalRelationalExpr (Restrict predicate (ExistingRelation emprel)))
80+ nonBossRel <- assertEither $ runRelationalExprM reenv (evalRelationalExpr (Restrict (NotPredicate predicate) (ExistingRelation emprel)))
7781
78− let schemaA = mkRelationalExprState DBC.empty {
79− relationVariables = M.fromList [("nonboss", nonBossRel),
80− ("boss", bossRel)]
82+ let schemaA = mkRelationalExprEnv baseContext graph
83+ baseContext = DBC.empty {
84+ relationVariables = M.fromList [("nonboss", ExistingRelation nonBossRel),
85+ ("boss", ExistingRelation bossRel)]
8186 }
82−
8387 isomorphsAtoB = [IsoRestrict "employee" predicate ("boss", "nonboss")]
8488 bossq = RelationVariable "boss" ()
8589 nonbossq = RelationVariable "nonboss" ()
8690 employeeq = RelationVariable "employee" ()
8791 unionq = Union bossq nonbossq
8892 empExpr <- assertEither (applyRelationalExprSchemaIsomorphs isomorphsAtoB employeeq)
89− let empResult = runReader (evalRelationalExpr empExpr) schemaA
90− unionResult = runReader (evalRelationalExpr unionq) schemaA
93+ let empResult = evalRelExpr (evalRelationalExpr empExpr)
94+ unionResult = evalRelExpr (evalRelationalExpr unionq)
95+ evalRelExpr = runRelationalExprM schemaA
9196 assertEqual "boss/nonboss isorestrict" unionResult empResult
9297 --execute database context expr
9398 bobRel <- assertEither (mkRelationFromList empattrs [[TextAtom "Bob", TextAtom ""]])
9499 let schemaBInsertExpr = Insert "employee" (ExistingRelation bobRel)
95100 schemaBInsertExpr' <- assertEither (processDatabaseContextExprInSchema (Schema isomorphsAtoB) schemaBInsertExpr)
96− let (postInsertContext,_,_) = execState (evalDatabaseContextExpr schemaBInsertExpr') (freshDatabaseState (stateElemsContext schemaA))
97− expectedRel = runReader (evalRelationalExpr (Union (RelationVariable "boss" ()) (RelationVariable "nonboss" ()))) (mkRelationalExprState postInsertContext)
101+ let Right dbcState = evalDBCExpr schemaBInsertExpr'
102+ postInsertContext = dbc_context dbcState
103+ evalDBCExpr expr' = runDatabaseContextEvalMonad baseContext dbcenv (optimizeAndEvalDatabaseContextExpr False expr')
104+ dbcenv = mkDatabaseContextEvalEnv transId graph
105+ expectedRel = runRelationalExprM postInsertEnv (evalRelationalExpr (Union (RelationVariable "boss" ()) (RelationVariable "nonboss" ())))
106+ postInsertEnv = mkRelationalExprEnv postInsertContext graph
98107 --execute the expression against the schema and compare against the base context
99108 processedExpr <- assertEither (processRelationalExprInSchema (Schema isomorphsAtoB) (RelationVariable "employee" ()))
100− let processedRel = runReader (evalRelationalExpr processedExpr) (mkRelationalExprState postInsertContext)
109+ let processedRel = runRelationalExprM postInsertEnv (evalRelationalExpr processedExpr)
101110 assertEqual "insert bob boss" expectedRel processedRel
102111
103112testIsoUnion :: Test
104113testIsoUnion = TestCase $ do
105114 --create motors relation which is split into low-power (<50 horsepower) and high-power (>=50 horsepower) motors
106115 --the schema is contains the split relvars
116+ (graph, _) <- freshTransactionGraph DBC.empty
107117 motorsRel <- assertEither $ mkRelationFromList (A.attributesFromList [Attribute "name" TextAtomType,
108118 Attribute "power" IntegerAtomType])
109119 [[TextAtom "Puny", IntegerAtom 10],
110120 [TextAtom "Scooter", IntegerAtom 49],
111121 [TextAtom "Auto", IntegerAtom 200],
112122 [TextAtom "Tractor", IntegerAtom 500]]
113− let baseSchema = mkRelationalExprState DBC.basicDatabaseContext {
114− relationVariables = M.singleton "motor" motorsRel
115− }
123+ let env = mkRelationalExprEnv DBC.basicDatabaseContext {
124+ relationVariables = M.singleton "motor" (ExistingRelation motorsRel)
125+ } graph
116126 splitPredicate = AtomExprPredicate (FunctionAtomExpr "lt" [AttributeAtomExpr "power", NakedAtomExpr (IntegerAtom 50)] ())
117127 splitIsomorphs = [IsoUnion ("lowpower", "highpower") splitPredicate "motor",
118128 IsoRename "true" "true",
119129 IsoRename "false" "false"]
120− lowmotors = runReader (evalRelationalExpr (Restrict splitPredicate (RelationVariable "motor" ()))) baseSchema
121− highmotors = runReader (evalRelationalExpr (Restrict (NotPredicate splitPredicate) (RelationVariable "motor" ()))) baseSchema
122− relResult expr = runReader (evalRelationalExpr expr) baseSchema
130+ lowmotors = runRelationalExprM env (evalRelationalExpr (Restrict splitPredicate (RelationVariable "motor" ())))
131+ highmotors = runRelationalExprM env (evalRelationalExpr (Restrict (NotPredicate splitPredicate) (RelationVariable "motor" ())))
132+ relResult expr = runRelationalExprM env (evalRelationalExpr expr)
123133 lowpowerExpr <- assertEither (processRelationalExprInSchema (Schema splitIsomorphs) (RelationVariable "lowpower" ()))
124134 lowpowerRel <- assertEither (relResult lowpowerExpr)
125135 highpowerExpr <- assertEither (processRelationalExprInSchema (Schema splitIsomorphs) (RelationVariable "highpower" ()))
126136 highpowerRel <- assertEither (relResult highpowerExpr)
127137 assertEqual "lowpower relation difference" (Right lowpowerRel) lowmotors
128− assertEqual "highpower relation difference" (Right highpowerRel) highmotors
138+ assertEqual "highpower relation difference" (Right highpowerRel) highmotors
test/Relation/Atomable.hs+74−16
@@ -1,8 +1,7 @@
11--Test Atomable typeclass which allows users to use existing Haskell datatypes to marshal them to and from the database as ConstructedAtoms.
2−{-# LANGUAGE DeriveGeneric, DeriveAnyClass, OverloadedStrings #-}
2+{-# LANGUAGE DeriveGeneric, DeriveAnyClass, OverloadedStrings, TypeApplications, DerivingVia #-}
33import Test.HUnit
44import ProjectM36.Client
5−import Data.Binary
65import Control.DeepSeq
76import System.Exit
87import TutorialD.Interpreter.TestBase
@@ -13,49 +12,83 @@ import Data.Time.Calendar (fromGregorian)
1312import Data.Text
1413import qualified Data.Map as M
1514import Data.Proxy
15+import Codec.Winery
1616
1717{-# ANN module ("Hlint: ignore Use newtype instead of data" :: String) #-}
1818data Test1T = Test1C Integer
19− deriving (Generic, Show, Eq, Binary, NFData, Atomable)
19+ deriving (Generic, Show, Eq, NFData, Atomable)
20+ deriving Serialise via WineryVariant Test1T
2021
2122data Test2T x = Test2C x
22− deriving (Show, Generic, Eq, Binary, NFData, Atomable)
23+ deriving (Show, Generic, Eq, NFData, Atomable)
24+ deriving Serialise via WineryVariant (Test2T x)
2325
2426data Test3T = Test3C Integer Integer
25− deriving (Show, Generic, Eq, Binary, NFData, Atomable)
27+ deriving (Show, Generic, Eq, NFData, Atomable)
28+ deriving Serialise via WineryVariant Test3T
2629
2730data Test4T = Test4Ca Integer |
2831 Test4Cb Integer
29− deriving (Show, Generic, Eq, Binary, NFData, Atomable)
32+ deriving (Show, Generic, Eq, NFData, Atomable)
33+ deriving Serialise via WineryVariant Test4T
3034
3135data TestListT = TestListC [Integer]
32− deriving (Show, Generic, Eq, Binary, NFData, Atomable)
36+ deriving (Show, Generic, Eq, NFData, Atomable)
37+ deriving Serialise via WineryVariant TestListT
3338
3439data TestNonEmptyT = TestNonEmptyC [Integer]
35− deriving (Show, Generic, Eq, Binary, NFData, Atomable)
40+ deriving (Show, Generic, Eq, NFData, Atomable)
41+ deriving Serialise via WineryVariant TestNonEmptyT
3642
3743data Test5T = Test5C {
3844 con1 :: Integer,
3945 con2 :: Integer
40− } deriving (Show, Generic, Eq, Binary, NFData, Atomable)
46+ } deriving (Show, Generic, Eq, NFData, Atomable)
47+ deriving Serialise via WineryRecord Test5T
4148
4249data Test6T = Test6C (Maybe Integer)
43− deriving (Show, Generic, Eq, Binary, NFData, Atomable)
50+ deriving (Show, Generic, Eq, NFData, Atomable)
51+ deriving Serialise via WineryVariant Test6T
4452
4553data Test7T = Test7C (Either Integer Integer)
46− deriving (Show, Generic, Eq, Binary, NFData, Atomable)
54+ deriving (Show, Generic, Eq, NFData, Atomable)
55+ deriving Serialise via WineryVariant Test7T
4756
4857data Test8T = Test8C Test1T
49− deriving (Show, Generic, Eq, Binary, NFData, Atomable)
50−
58+ deriving (Show, Generic, Eq, NFData, Atomable)
59+ deriving Serialise via WineryVariant Test8T
60+
61+data User = User
62+ { userFirstName :: Text
63+ , userLastName :: Text
64+ } deriving (Eq, Ord, Show, Generic, NFData, Atomable)
65+ deriving Serialise via WineryRecord User
66+
67+data Test9_4T = Test9_4C {
68+ f9_41 :: Int,
69+ f9_42 :: Int,
70+ f9_43 :: Int,
71+ f9_44 :: Int }
72+ deriving (Show, Generic, Eq, NFData, Atomable)
73+ deriving Serialise via WineryRecord Test9_4T
74+
75+data Test9_5T = Test9_5C {
76+ f9_51 :: Int,
77+ f9_52 :: Int,
78+ f9_53 :: Int,
79+ f9_54 :: Int,
80+ f9_55 :: Int
81+ }
82+ deriving (Show, Generic, Eq, NFData, Atomable)
83+ deriving Serialise via WineryRecord Test9_5T
84+
5185main :: IO ()
5286main = do
5387 tcounts <- runTestTT testList
5488 if errors tcounts + failures tcounts > 0 then exitFailure else exitSuccess
5589
5690testList :: Test
57−testList = TestList [testHaskell2DB, testADT1, testADT2, testADT3, testADT4, testADT5, testBasicMarshaling, testListInstance, testNonEmptyInstance, testADT6Maybe, testADT7Either, testNonPrimitiveValues]
58−
91+testList = TestList [testHaskell2DB, testADT1, testADT2, testADT3, testADT4, testADT5, testBasicMarshaling, testSimpleList, testListInstance, testNonEmptyInstance, testADT6Maybe, testADT7Either, testNonPrimitiveValues, testRecordType, testManyFields]
5992
6093-- test some basic data types like int, day, etc.
6194testBasicMarshaling :: Test
@@ -84,7 +117,7 @@ testHaskell2DB = TestCase $ do
84117 let createRelExpr = Assign "x" rel
85118
86119 rel = MakeRelationFromExprs Nothing
87− [TupleExpr (M.singleton "a1" (NakedAtomExpr atomVal))]
120+ (TupleExprs () [TupleExpr (M.singleton "a1" (NakedAtomExpr atomVal))])
88121 atomVal = toAtom exampleVal
89122 exampleVal = Test1C 10
90123 checkExecuteDatabaseContextExpr sessionId dbconn createRelExpr
@@ -140,6 +173,12 @@ testListInstance = TestCase $ do
140173 let example = TestListC [3,4,5]
141174 assertEqual "List instance" example (fromAtom (toAtom example))
142175
176+testSimpleList :: Test
177+testSimpleList = TestCase $ do
178+ let example = toAtom @[Integer] [1,2,3]
179+ expected = ConstructedAtom "Cons" (ConstructedAtomType "List" (M.fromList [("a",IntegerAtomType)])) [IntegerAtom 1,ConstructedAtom "Cons" (ConstructedAtomType "List" (M.fromList [("a",IntegerAtomType)])) [IntegerAtom 2,ConstructedAtom "Cons" (ConstructedAtomType "List" (M.fromList [("a",IntegerAtomType)])) [IntegerAtom 3,ConstructedAtom "Empty" (ConstructedAtomType "List" (M.fromList [("a",IntegerAtomType)])) []]]]
180+ assertEqual "simple list" expected example
181+
143182testNonEmptyInstance :: Test
144183testNonEmptyInstance = TestCase $ do
145184 let example = TestNonEmptyC [3,4,5]
@@ -149,3 +188,22 @@ testNonPrimitiveValues :: Test
149188testNonPrimitiveValues = TestCase $ do
150189 let example = Test8C (Test1C 3)
151190 assertEqual "non-primitive values" example (fromAtom (toAtom example))
191+
192+testRecordType :: Test
193+testRecordType = TestCase $ do
194+ let example = User { userFirstName = "Bob"
195+ ,userLastName = "Smith"
196+ }
197+ assertEqual "User record" example (fromAtom (toAtom example))
198+ let expected = AddTypeConstructor (ADTypeConstructorDef "User" []) [DataConstructorDef "User" [DataConstructorDefTypeConstructorArg (PrimitiveTypeConstructor "Text" TextAtomType),DataConstructorDefTypeConstructorArg (PrimitiveTypeConstructor "Text" TextAtomType)]]
199+
200+ assertEqual "User record to database context expr" expected (toAddTypeExpr (Proxy :: Proxy User))
201+
202+--test both odd and even product types with more than 2 fields
203+testManyFields :: Test
204+testManyFields = TestCase $ do
205+ let example4 = Test9_4C 1 2 3 4
206+ assertEqual "four fields product type" example4 (fromAtom (toAtom example4))
207+
208+ let example5 = Test9_5C 1 2 3 4 5
209+ assertEqual "five fields product type" example5 (fromAtom (toAtom example5))
test/Relation/Basic.hs+24−17
@@ -3,13 +3,11 @@ import ProjectM36.Base
33import ProjectM36.Relation
44import ProjectM36.Error
55import ProjectM36.DateExamples
6−import ProjectM36.TupleSet
7−import ProjectM36.Attribute hiding (null, attributeNames)
86import ProjectM36.DataTypes.Primitive
97import ProjectM36.RelationalExpression
8+import ProjectM36.TransactionGraph
109import ProjectM36.Tuple
1110import qualified ProjectM36.DatabaseContext as DBC
12−import Control.Monad.Trans.Reader
1311import qualified ProjectM36.Attribute as A
1412import qualified Data.Map as M
1513import qualified Data.Vector as V
@@ -25,8 +23,8 @@ testList = TestList [testRelation "relationTrue" relationTrue, testRelation "rel
2523 testRelation "products" productsRel,
2624 testRelation "supplierProducts" supplierProductsRel,
2725 testMkRelationFromExprsBadAttrs,
28− testDuplicateAttributes,
29− testExistingRelationType
26+ testExistingRelationType,
27+ testReorderTuple
3028 ]
3129
3230main :: IO ()
@@ -64,8 +62,8 @@ validateAttrTypesMatchTupleAttrTypes rel@(Relation attrs tupSet) = foldr (\tuple
6462 tupleAtomCheck tuple = V.all (== True) (attrChecks tuple)
6563 attrChecks tuple = V.map (\attr -> case atomForAttributeName (A.attributeName attr) tuple of
6664 Left _ -> False
67− Right atom -> (Right $ atomTypeForAtom atom) ==
68− A.atomTypeForAttributeName (A.attributeName attr) attrs) (attributes rel)
65+ Right atom -> Right (atomTypeForAtom atom) ==
66+ A.atomTypeForAttributeName (A.attributeName attr) attrs) (attributesVec (attributes rel))
6967
7068simpleRel :: Relation
7169simpleRel = case mkRelation attrs tupleSet of
@@ -94,19 +92,28 @@ testMkRelation1 = TestCase $ assertEqual "key mismatch" expectedError (mkRelatio
9492
9593testMkRelationFromExprsBadAttrs :: Test
9694testMkRelationFromExprsBadAttrs = TestCase $ do
97− let context = DBC.empty
98− case runReader (evalRelationalExpr (MakeRelationFromExprs (Just [AttributeAndTypeNameExpr "badAttr1" (PrimitiveTypeConstructor "Int" IntAtomType) ()]) [TupleExpr (M.singleton "badAttr2" (NakedAtomExpr (IntAtom 1)))])) (mkRelationalExprState context) of
95+ let context = DBC.empty
96+ (graph,_) <- freshTransactionGraph context
97+ let reenv = mkRelationalExprEnv context graph
98+ reExpr = MakeRelationFromExprs (Just [AttributeAndTypeNameExpr "badAttr1" (PrimitiveTypeConstructor "Int" IntAtomType) ()]) (TupleExprs () [TupleExpr (M.singleton "badAttr2" (NakedAtomExpr (IntAtom 1)))])
99+ evald = runRelationalExprM reenv (evalRelationalExpr reExpr)
100+ case evald of
99101 Left err -> assertEqual "tuple type mismatch" (TupleAttributeTypeMismatchError (A.attributesFromList [Attribute "badAttr2" IntAtomType])) err
100102 Right _ -> assertFailure "expected tuple type mismatch"
101103
102−--creating an empty relation with duplicate attribute names should fail
103−testDuplicateAttributes :: Test
104−testDuplicateAttributes = TestCase $ do
105− let eRel = mkRelation attrs emptyTupleSet
106− attrs = attributesFromList [Attribute "a" IntAtomType, Attribute "a" TextAtomType]
107− assertEqual "duplicate attribute names" (Left (DuplicateAttributeNamesError (S.singleton "a"))) eRel
108−
109104testExistingRelationType :: Test
110105testExistingRelationType = TestCase $ do
111− let typeResult = runReader (typeForRelationalExpr (ExistingRelation relationTrue)) (RelationalExprStateElems DBC.empty)
106+ (graph, _) <- freshTransactionGraph dateExamples
107+ let typeResult = runRelationalExprM reenv (typeForRelationalExpr (ExistingRelation relationTrue))
108+ reenv = mkRelationalExprEnv dateExamples graph
112109 assertEqual "ExistingRelation with tuples type" (Right relationFalse) typeResult
110+
111+-- | Ensure that tuple reordering honors the
112+testReorderTuple :: Test
113+testReorderTuple = TestCase $ do
114+ let tup1 = mkRelationTuple attrs1 (V.fromList [IntAtom 4, TextAtom "test"])
115+ attrs1 = A.attributesFromList [Attribute "a" IntAtomType, Attribute "b" TextAtomType]
116+ attrs2 = A.attributesFromList [Attribute "b" TextAtomType, Attribute "a" IntAtomType]
117+ actual = reorderTuple attrs2 tup1
118+ expected = mkRelationTuple attrs2 (V.fromList [TextAtom "test", IntAtom 4])
119+ assertEqual "reorderTuple" expected actual
test/Relation/Export/CSV.hs+23−18
@@ -1,3 +1,5 @@
1+{-# LANGUAGE CPP #-}
2+
13import ProjectM36.Base
24import ProjectM36.Relation.Show.CSV
35import ProjectM36.Relation.Parse.CSV
@@ -11,7 +13,11 @@ import System.Exit
1113import Test.HUnit
1214import Data.Time.Calendar
1315import Data.Time.Clock
16+
17+#if __GLASGOW_HASKELL__ < 804
1418import Data.Monoid
19+#endif
20+
1521{-
1622import qualified Data.Text.Lazy as TL
1723import qualified Data.Text.Lazy.Encoding as TE
@@ -19,9 +25,9 @@ import ProjectM36.Relation.Show.Term
1925import qualified Data.ByteString.Lazy as BS
2026-}
2127
22−main :: IO ()
23−main = do
24− tcounts <- runTestTT $ TestList [testCSVExport,
28+main :: IO ()
29+main = do
30+ tcounts <- runTestTT $ TestList [testCSVExport,
2531 testADTExport]
2632 if errors tcounts + failures tcounts > 0 then exitFailure else exitSuccess
2733
@@ -31,8 +37,8 @@ assertEither x = do
3137 case res of
3238 Left err -> assertFailure (show err) >> undefined
3339 Right val -> pure val
34−
35−testADTExport :: Test
40+
41+testADTExport :: Test
3642testADTExport = TestCase $ do
3743 let adtCSV = "a\nCons 4 (Cons 5 Empty)\n"
3844 attrs = A.attributesFromList [Attribute "a" (listAtomType IntegerAtomType)]
@@ -40,17 +46,17 @@ testADTExport = TestCase $ do
4046 case csvAsRelation attrs basicTypeConstructorMapping adtCSV of
4147 Left err -> assertFailure ("import failure: " <> show err)
4248 Right rel -> assertEqual "import cons list" expectedRel (Right rel)
43−
49+
4450--round-trip various atom types through CSV export/import
4551testCSVExport :: Test
4652testCSVExport = TestCase $ do
4753 now <- getCurrentTime
48− testInterval <- assertEither $ pure (createInterval
49− (DateTimeAtom now)
54+ testInterval <- assertEither $ pure (createInterval
55+ (DateTimeAtom now)
5056 (DateTimeAtom (addUTCTime 86400 now))
5157 True
5258 False)
53− let attrs = A.attributesFromList [Attribute "textattr" TextAtomType,
59+ let attrs = A.attributesFromList [Attribute "textattr" TextAtomType,
5460 Attribute "integerattr" IntegerAtomType,
5561 Attribute "dayattr" DayAtomType,
5662 Attribute "datetimeattr" DateTimeAtomType,
@@ -61,8 +67,8 @@ testCSVExport = TestCase $ do
6167 ]
6268 sampleByteString = "\1\0\244\34\150"
6369 relOrErr = mkRelationFromList attrs [
64− [TextAtom "text atom with \"quote\"",
65− IntegerAtom 123,
70+ [TextAtom "text atom with \"quote\"",
71+ IntegerAtom 123,
6672 DayAtom (fromGregorian 2017 4 10),
6773 DateTimeAtom now,
6874 ByteStringAtom sampleByteString,
@@ -70,19 +76,19 @@ testCSVExport = TestCase $ do
7076 listCons TextAtomType [TextAtom "text1", TextAtom "text2"],
7177 testInterval
7278 ],
73− [TextAtom "second text atom with 漢字",
74− IntegerAtom 314,
79+ [TextAtom "second text atom with 漢字",
80+ IntegerAtom 314,
7581 DayAtom (fromGregorian 1001 6 28),
7682 DateTimeAtom (addUTCTime 360 now),
77− ByteStringAtom sampleByteString,
83+ ByteStringAtom sampleByteString,
7884 listCons IntegerAtomType [IntegerAtom 10, IntegerAtom 11, IntegerAtom 12],
7985 listCons TextAtomType [TextAtom "text5\"", TextAtom "text6\r\n"],
8086 testInterval
8187 ]]
82−
83− case relOrErr of
88+
89+ case relOrErr of
8490 Left err -> assertFailure $ "export relation creation failure: " ++ show err
85− Right rel ->
91+ Right rel ->
8692 case relationAsCSV rel of
8793 Left err -> assertFailure $ "export failed: " ++ show err
8894 Right csvData ->
@@ -91,4 +97,3 @@ testCSVExport = TestCase $ do
9197 case csvAsRelation attrs basicTypeConstructorMapping csvData of -- import csv data back to relation
9298 Left err -> assertFailure $ "re-import failed: " ++ show err
9399 Right rel' -> assertEqual "relation CSV comparison" rel rel'
94−
test/Relation/StaticOptimizer.hs+76−51
@@ -1,13 +1,12 @@
11import ProjectM36.Base
22import ProjectM36.Relation
3−import ProjectM36.RelationalExpression
3+import ProjectM36.TransactionGraph
44import ProjectM36.DateExamples
5−import ProjectM36.Error
65import ProjectM36.TupleSet
76import ProjectM36.StaticOptimizer
7+import ProjectM36.DatabaseContext as DBC
88import System.Exit
99import Control.Monad.State
10−import Control.Monad.Trans.Reader
1110import Test.HUnit
1211import qualified Data.Set as S
1312
@@ -16,100 +15,126 @@ main = do
1615 tcounts <- runTestTT (TestList tests)
1716 if errors tcounts + failures tcounts > 0 then exitFailure else exitSuccess
1817 where
19− tests = relationOptTests ++ databaseOptTests ++ [testTransitiveOptimization,
20− testImpossiblePredicates,
21− testJoinElimination,
22− testRestrictionPredicateCollapse,
23− testPushDownRestrictionPredicate]
24− optDBCTest = map (\(name, expr, unopt) -> TestCase $ assertEqual name expr (evalState (applyStaticDatabaseOptimization unopt) (freshDatabaseState dateExamples)))
25− relvar nam = RelationVariable nam ()
26− startState = mkRelationalExprState dateExamples
27− optRelTest = map (\(name, expr, unopt) -> TestCase $ assertEqual name expr (runReader (applyStaticRelationalOptimization unopt) startState))
28− relationOptTests = optRelTest [
29− ("StaticProject", Right $ relvar "s", Project (AttributeNames (attributeNames suppliersRel)) (relvar "s")),
30− ("StaticUnion", Right $ relvar "s", Union (relvar "s") (relvar "s")),
31− ("StaticJoin", Right $ relvar "s", Join (relvar "s") (relvar "s"))
32− ]
33− databaseOptTests = optDBCTest [
34− ("StaticAssign",
35− Right $ Assign "z" (relvar "s"),
36− Assign "z" (Restrict TruePredicate (relvar "s"))
37− ),
38− ("StaticMultipleExpr",
39− Right $ MultipleExpr [Assign "z" (relvar "s"),
40− Assign "z" (relvar "s")],
41− MultipleExpr [Assign "z" (Restrict TruePredicate (relvar "s")),
42− Assign "z" (Restrict TruePredicate (relvar "s"))])
43− ]
18+ tests = [testTransitiveOptimization,
19+ testImpossiblePredicates,
20+ testJoinElimination,
21+ testRestrictionPredicateCollapse,
22+ testPushDownRestrictionPredicate,
23+ testOptimizeRelationalExpr,
24+ testOptimizeDatabaseContextExpr]
25+
26+testOptimizeDatabaseContextExpr :: Test
27+testOptimizeDatabaseContextExpr = TestCase $ do
28+ (graph, transId) <- freshTransactionGraph DBC.empty
29+ let relvar nam = RelationVariable nam ()
30+ relvarId nam = RelationVariable nam UncommittedContextMarker
31+ testInfos = [
32+ ("StaticAssign",
33+ Right $ Assign "z" (relvarId "s"),
34+ Assign "z" (Restrict TruePredicate (relvar "s"))
35+ ),
36+ ("StaticMultipleExpr",
37+ Right $ MultipleExpr [Assign "z" (relvarId "s"),
38+ Assign "z" (relvarId "s")],
39+ MultipleExpr [Assign "z" (Restrict TruePredicate (relvar "s")),
40+ Assign "z" (Restrict TruePredicate (relvar "s"))])
41+ ]
42+ forM_ testInfos $ \(name, expectedExpr, unoptExpr) -> do
43+ let optExpr = runGraphRefSOptDatabaseContextExprM transId dateExamples graph (optimizeDatabaseContextExpr unoptExpr)
44+ assertEqual name expectedExpr optExpr
4445
4546testTransitiveOptimization :: Test
4647testTransitiveOptimization = TestCase $ do
48+ (graph, _) <- freshTransactionGraph dateExamples
4749 let expr atomexpr = AndPredicate (AttributeEqualityPredicate "a" (NakedAtomExpr (IntegerAtom 300))) (AttributeEqualityPredicate "b" atomexpr)
4850 exprIn = expr (AttributeAtomExpr "a")
4951 exprOut = expr (NakedAtomExpr (IntegerAtom 300))
50− assertEqual "transitive property" (Right exprOut) (runReader (applyStaticPredicateOptimization exprIn) (RelationalExprStateElems dateExamples))
51−
52−optRelExpr :: RelationalExpr -> Either RelationalError RelationalExpr
53−optRelExpr expr = runReader (applyStaticRelationalOptimization expr) (RelationalExprStateElems dateExamples)
52+ optExpr = runGraphRefSOptRelationalExprM Nothing graph (applyStaticPredicateOptimization exprIn)
53+ assertEqual "transitive property" (Right exprOut) optExpr
54+
55+
56+testOptimizeRelationalExpr :: Test
57+testOptimizeRelationalExpr = TestCase $ do
58+ (graph, _) <- freshTransactionGraph dateExamples
59+ let relvarId nam = RelationVariable nam UncommittedContextMarker
60+ relationOptTests = [
61+ ("StaticProject",
62+ Right $ relvarId "s",
63+ Project (AttributeNames (attributeNames suppliersRel)) (relvarId "s")),
64+ ("StaticUnion",
65+ Right $ relvarId "s",
66+ Union (relvarId "s") (relvarId "s")),
67+ ("StaticJoin",
68+ Right $ relvarId "s",
69+ Join (relvarId "s") (relvarId "s"))
70+ ]
71+ forM_ relationOptTests $ \(name, expr, unoptExpr) -> do
72+ let optExpr = runGraphRefSOptRelationalExprM (Just dateExamples) graph (optimizeGraphRefRelationalExpr unoptExpr)
73+ assertEqual name expr optExpr
5474
5575testImpossiblePredicates :: Test
5676testImpossiblePredicates = TestCase $ do
77+ (graph, _) <- freshTransactionGraph dateExamples
5778 let tautTrue = Restrict (AtomExprPredicate (NakedAtomExpr (BoolAtom True))) rel
5879 tautTrue2 = Restrict TruePredicate rel
5980 tautFalse = Restrict (AtomExprPredicate (NakedAtomExpr (BoolAtom False))) rel
6081 tautFalse2 = Restrict (NotPredicate TruePredicate) rel
6182 emptyRel = MakeStaticRelation (attributes suppliersRel) emptyTupleSet
62− rel = RelationVariable "s" ()
83+ rel = RelationVariable "s" UncommittedContextMarker
84+ optRelExpr expr = optimizeGraphRefRelationalExpr' (Just dateExamples) graph expr
6385 assertEqual "remove tautology where true" (Right rel) (optRelExpr tautTrue)
6486 assertEqual "remove tautology where true2" (Right rel) (optRelExpr tautTrue2)
6587 assertEqual "remove tautology where false" (Right emptyRel) (optRelExpr tautFalse)
6688 assertEqual "remove tautology where false2" (Right emptyRel) (optRelExpr tautFalse2)
67−
68−optJoinExpr :: RelationalExpr -> Either RelationalError RelationalExpr
69−optJoinExpr expr = runReader (applyStaticJoinElimination expr) (RelationalExprStateElems dateExamples)
7089
7190testJoinElimination :: Test
7291testJoinElimination = TestCase $ do
92+ (graph, _) <- freshTransactionGraph dateExamples
93+ let marker = UncommittedContextMarker
94+ optJoinExpr expr = runGraphRefSOptRelationalExprM (Just dateExamples) graph (applyStaticJoinElimination expr)
95+ relvar rv = RelationVariable rv marker
96+
7397 -- (s join sp){s#,qty,p#} == sp
74− let unoptExpr = Project (AttributeNames (S.fromList ["p#", "qty", "s#"])) (Join (RelationVariable "sp" ()) (RelationVariable "s" ()))
75− assertEqual "remove extraneous join" (Right (RelationVariable "sp" ())) (optJoinExpr unoptExpr)
98+ let unoptExpr = Project (AttributeNames (S.fromList ["p#", "qty", "s#"])) (Join (relvar "sp") (relvar "s"))
99+ assertEqual "remove extraneous join" (Right (relvar "sp")) (optJoinExpr unoptExpr)
76100
77101-- (sp join s){s#,qty,p#} == sp --flip relvar names
78− let unoptExpr2 = Project (AttributeNames (S.fromList ["p#", "qty", "s#"])) (Join (RelationVariable "s" ()) (RelationVariable "sp" ()))
79− assertEqual "remove extraneous join2" (Right (RelationVariable "sp" ())) (optJoinExpr unoptExpr2)
102+ let unoptExpr2 = Project (AttributeNames (S.fromList ["p#", "qty", "s#"])) (Join (relvar "s") (relvar "sp"))
103+ assertEqual "remove extraneous join2" (Right (relvar "sp")) (optJoinExpr unoptExpr2)
80104
81105-- (sp join s){s#,qty,sname} != sp - attribute from s included
82− let expr3 = Project (AttributeNames (S.fromList ["p#", "qty", "sname"])) (Join (RelationVariable "sp" ()) (RelationVariable "s" ()))
106+ let expr3 = Project (AttributeNames (S.fromList ["p#", "qty", "sname"])) (Join (relvar "sp") (relvar "s"))
83107 assertEqual "retain join" (Right expr3) (optJoinExpr expr3)
84108
85109 -- (sp join s){qty} != sp --projection does not include foreign key attribute
86− let expr4 = Project (AttributeNames (S.singleton "qty")) (Join (RelationVariable "sp" ()) (RelationVariable "s" ()))
110+ let expr4 = Project (AttributeNames (S.singleton "qty")) (Join (relvar "sp") (relvar "s"))
87111 assertEqual "retain join2" (Right expr4) (optJoinExpr expr4)
88112
89113 -- (sp join s){s#,qty} == sp - a subset of attributes in the projection are in the foreign key
90− let expr5 = Project (AttributeNames (S.fromList ["s#", "qty"])) (Join (RelationVariable "sp" ()) (RelationVariable "s" ()))
91− let expect5 = Project (AttributeNames (S.fromList ["s#", "qty"])) (RelationVariable "sp" ())
114+ let expr5 = Project (AttributeNames (S.fromList ["s#", "qty"])) (Join (relvar "sp") (relvar "s"))
115+ let expect5 = Project (AttributeNames (S.fromList ["s#", "qty"])) (relvar "sp")
92116 assertEqual "remove extraneous join (attribute subset)" (Right expect5) (optJoinExpr expr5)
93117
94118 -- (s join p){s#,p#} != sp -- no foreign key
95− let expr6 = Project (AttributeNames (S.fromList ["s#", "p#"])) (Join (RelationVariable "s" ()) (RelationVariable "p" ()))
119+ let expr6 = Project (AttributeNames (S.fromList ["s#", "p#"])) (Join (relvar "s") (relvar "p"))
96120 assertEqual "retain join- no foreign key" (Right expr6) (optJoinExpr expr6)
97121
98122 -- (s join p){s#,qty,p#,sname} != sp -- all sp attributes plus one s attributes
99− let expr7 = Project (AttributeNames (S.fromList ["s#", "p#", "qty", "sname"])) (Join (RelationVariable "s" ()) (RelationVariable "sp" ()))
123+ let expr7 = Project (AttributeNames (S.fromList ["s#", "p#", "qty", "sname"])) (Join (relvar "s") (relvar "sp"))
100124 assertEqual "retain join- attributes from both relvars" (Right expr7) (optJoinExpr expr7)
101125
102126testRestrictionPredicateCollapse :: Test
103127testRestrictionPredicateCollapse = TestCase $ do
104128 let expr1 = Restrict (NotPredicate TruePredicate) rv
105− rv = RelationVariable "a" ()
129+ rv = RelationVariable "a" UncommittedContextMarker
130+ relvar name = RelationVariable name UncommittedContextMarker
106131 assertEqual "one restriction" expr1 (applyStaticRestrictionCollapse expr1)
107132
108133 let attrEqualsPred = AttributeEqualityPredicate "x" (NakedAtomExpr (IntAtom 3))
109− expr2 = Restrict TruePredicate (Restrict attrEqualsPred (RelationVariable "a" ()))
110− assertEqual "two restrictions" (Restrict (AndPredicate TruePredicate attrEqualsPred) (RelationVariable "a" ())) (applyStaticRestrictionCollapse expr2)
134+ expr2 = Restrict TruePredicate (Restrict attrEqualsPred (relvar "a"))
135+ assertEqual "two restrictions" (Restrict (AndPredicate TruePredicate attrEqualsPred) (relvar "a")) (applyStaticRestrictionCollapse expr2)
111136
112− let expr3 = Restrict pred1 (Restrict pred2 (Restrict pred3 (RelationVariable "a" ())))
137+ let expr3 = Restrict pred1 (Restrict pred2 (Restrict pred3 (relvar "a")))
113138 pred1 = NotPredicate TruePredicate
114139 pred2 = attrEqualsPred
115140 pred3 = AtomExprPredicate (NakedAtomExpr (BoolAtom True))
@@ -123,7 +148,7 @@ testRestrictionPredicateCollapse = TestCase $ do
123148testPushDownRestrictionPredicate :: Test
124149testPushDownRestrictionPredicate = TestCase $ do
125150 -- (s union relation{tuple{city "Boston", s# "S6", sname "Stevens", status 50}}) where status = 30 == (s where status=30) union (relation{tuple{city "Boston", s# "S6", sname "Stevens", status 50}} where status=30)
126− let rvs = RelationVariable "s" ()
151+ let rvs = RelationVariable "s" UncommittedContextMarker
127152 let status30 = AttributeEqualityPredicate "status" (NakedAtomExpr (IntAtom 30))
128153 relationsOrError = do
129154 stevens <- mkRelationFromList (attributes suppliersRel) [[TextAtom "S6", TextAtom "Stevens", IntegerAtom 50, TextAtom "Boston"]]
test/Relation/Tupleable.hs+188−10
@@ -1,19 +1,29 @@
1−{-# LANGUAGE DeriveGeneric, FlexibleInstances, FlexibleContexts, TypeOperators, DeriveAnyClass #-}
1+{-# LANGUAGE
2+ DeriveGeneric
3+ , FlexibleInstances
4+ , FlexibleContexts
5+ , DeriveAnyClass
6+ , ScopedTypeVariables
7+ , TypeApplications
8+ , DataKinds
9+ , TypeOperators
10+ , AllowAmbiguousTypes
11+ , DerivingVia
12+ #-}
213import Test.HUnit
3−import ProjectM36.Tupleable
14+import ProjectM36.Tupleable.Deriving
415import ProjectM36.Atomable
5−import ProjectM36.Attribute
16+import ProjectM36.Attribute as A
617import ProjectM36.Error
7−import Data.Binary
818import ProjectM36.Base
919import Control.DeepSeq (NFData)
10−import GHC.Generics
1120import qualified Data.Vector as V
1221import qualified Data.Map as M
1322import qualified Data.Text as T
1423import qualified Data.Set as S
1524import System.Exit
1625import Data.Proxy
26+import Codec.Winery
1727
1828{-# ANN module ("Hlint: ignore Use newtype instead of data" :: String) #-}
1929
@@ -21,35 +31,43 @@ data Test1T = Test1C {
2131 attrA :: Integer
2232 }
2333 deriving (Generic, Eq, Show)
34+ deriving Serialise via WineryRecord Test1T
2435
2536data Test2T = Test2C {
2637 attrB :: Integer,
2738 attrC :: Integer
2839 }
2940 deriving (Generic, Eq, Show)
41+ deriving Serialise via WineryRecord Test2T
3042
3143data Test3T = Test3C Integer
3244 deriving (Generic, Eq, Show)
45+ deriving Serialise via WineryVariant Test3T
3346
3447data Test4T = Test4C
3548 deriving (Generic, Eq, Show)
49+ deriving Serialise via WineryVariant Test4T
3650
3751data Test5T = Test5C1 Integer |
3852 Test5C2 Integer
3953 deriving (Generic, Eq, Show)
54+ deriving Serialise via WineryVariant Test5T
4055
4156data Test6T = Test6C T.Text Integer Double
4257 deriving (Generic, Eq, Show)
4358
4459data Test7A = Test7AC Integer
45− deriving (Generic, Show, Eq, Binary, NFData, Atomable)
60+ deriving (Generic, Show, Eq, NFData, Atomable)
61+ deriving Serialise via WineryVariant Test7A
4662
4763
4864data Test7T = Test7C Test7A
4965 deriving (Generic, Show, Eq)
66+ deriving Serialise via WineryVariant Test7T
5067
5168data Test8T = Test8C
5269 deriving (Generic, Show, Eq)
70+ deriving Serialise via WineryVariant Test8T
5371
5472data Test9T = Test9C
5573 {
@@ -58,6 +76,15 @@ data Test9T = Test9C
5876 attr9C :: Double
5977 }
6078 deriving (Generic, Show, Eq)
79+ deriving Serialise via WineryRecord Test9T
80+
81+data Test10T = Test10C {
82+ longAttrNameA10 :: Integer,
83+ long_attr_name_b10 :: Integer,
84+ longMixed_attr_NameC10 :: Integer
85+ }
86+ deriving (Generic, Show, Eq)
87+ deriving Serialise via WineryRecord Test10T
6188
6289instance Tupleable Test1T
6390
@@ -83,7 +110,7 @@ main = do
83110 if errors tcounts + failures tcounts > 0 then exitFailure else exitSuccess
84111
85112testList :: Test
86−testList = TestList [testADT1, testADT2, testADT3, testADT4, testADT6, testADT7, testADT8, testInsertExpr, testDefineExpr, testUpdateExpr, testUpdateExprEmptyAttrs, testDeleteExpr, testUpdateExprWrongAttr, testReorderedTuple]
113+testList = TestList [testADT1, testADT2, testADT3, testADT4, testADT6, testADT7, testADT8 ,testInsertExpr, testDefineExpr, testUpdateExpr, testUpdateExprEmptyAttrs, testDeleteExpr, testUpdateExprWrongAttr, testReorderedTuple, testAddPrefixField, testDropPrefixField, testAddSuffixField, testDropSuffixField, testUpperCaseField, testLowerCaseField, testTitleCaseField, testCamelCaseField, testPascalCaseField, testSnakeCaseField, testSpinalCaseField, testTrainCaseField, testAsIsCodec, testAsIsField, testComposeRLCodec, testComposeRLField, testComposeLRCodec, testComposeLRField]
87114
88115testADT1 :: Test
89116testADT1 = TestCase $ assertEqual "one record constructor" (Right example) (fromTuple (toTuple example))
@@ -121,7 +148,7 @@ testADT7 :: Test
121148testADT7 = TestCase $ do
122149 let example = Test7C (Test7AC 3)
123150 assertEqual "atom type" (Right example) (fromTuple (toTuple example))
124− let expectedAttrs = V.singleton (Attribute "" (ConstructedAtomType "Test7A" M.empty))
151+ let expectedAttrs = A.singleton (Attribute "" (ConstructedAtomType "Test7A" M.empty))
125152 assertEqual "adt atomtype" expectedAttrs (toAttributes (Proxy :: Proxy Test7T))
126153
127154testADT8 :: Test
@@ -195,8 +222,159 @@ testDeleteExpr = TestCase $ do
195222testReorderedTuple :: Test
196223testReorderedTuple = TestCase $ do
197224 let tupleRev :: RelationTuple -> RelationTuple
198− tupleRev (RelationTuple v1 v2) = RelationTuple (V.reverse v1) (V.reverse v2)
225+ tupleRev (RelationTuple v1 v2) = RelationTuple (revAttrs v1) (V.reverse v2)
226+ revAttrs attrs = A.attributesFromList (reverse (A.toList attrs))
199227 expected = Test2C {attrB = 3,
200228 attrC = 4}
201229 actual = fromTuple . tupleRev . toTuple $ expected
202− assertEqual "reordered tuple" (Right expected) actual
230+ assertEqual "reordered tuple" (Right expected) actual
231+
232+testCodec :: forall tag. ModifyOptions tag => String -> [AttributeName] -> Test
233+testCodec msg expected = TestCase $
234+ assertEqual msg (S.fromList expected) actual
235+ where
236+ actual = attributeNameSet $ toAttributes (Proxy :: Proxy (Codec tag Test10T))
237+
238+testAddPrefixField :: Test
239+testAddPrefixField = testCodec
240+ @(Field (AddPrefix "prefix_"))
241+ "codec field add prefix attributes"
242+ ["prefix_longAttrNameA10",
243+ "prefix_long_attr_name_b10",
244+ "prefix_longMixed_attr_NameC10"]
245+
246+testDropPrefixField :: Test
247+testDropPrefixField = testCodec
248+ @(Field (DropPrefix "long"))
249+ "codec field drop prefix"
250+ ["AttrNameA10",
251+ "_attr_name_b10",
252+ "Mixed_attr_NameC10"]
253+
254+testAddSuffixField :: Test
255+testAddSuffixField = testCodec
256+ @(Field (AddSuffix "_suffix"))
257+ "codec field add suffix"
258+ ["longAttrNameA10_suffix",
259+ "long_attr_name_b10_suffix",
260+ "longMixed_attr_NameC10_suffix"]
261+
262+testDropSuffixField :: Test
263+testDropSuffixField = testCodec
264+ @(Field (DropSuffix "10"))
265+ "codec field drop suffix"
266+ ["longAttrNameA",
267+ "long_attr_name_b",
268+ "longMixed_attr_NameC"]
269+
270+testUpperCaseField :: Test
271+testUpperCaseField = testCodec
272+ @(Field UpperCase)
273+ "codec field uppercase"
274+ ["LONGATTRNAMEA10",
275+ "LONG_ATTR_NAME_B10",
276+ "LONGMIXED_ATTR_NAMEC10"]
277+
278+testLowerCaseField :: Test
279+testLowerCaseField = testCodec
280+ @(Field LowerCase)
281+ "codec field lowercase"
282+ ["longattrnamea10",
283+ "long_attr_name_b10",
284+ "longmixed_attr_namec10"]
285+
286+testTitleCaseField :: Test
287+testTitleCaseField = testCodec
288+ @(Field TitleCase)
289+ "codec field title case"
290+ ["Long Attr Name A10",
291+ "Long Attr Name B10",
292+ "Long Mixed Attr Name C10"]
293+
294+testCamelCaseField :: Test
295+testCamelCaseField = testCodec
296+ @(Field CamelCase)
297+ "codec field camel case"
298+ ["longAttrNameA10",
299+ "longAttrNameB10",
300+ "longMixedAttrNameC10"]
301+
302+testPascalCaseField :: Test
303+testPascalCaseField = testCodec
304+ @(Field PascalCase)
305+ "codec field pascal case"
306+ ["LongAttrNameA10",
307+ "LongAttrNameB10",
308+ "LongMixedAttrNameC10"]
309+
310+testSnakeCaseField :: Test
311+testSnakeCaseField = testCodec
312+ @(Field SnakeCase)
313+ "codec field snake case"
314+ ["long_attr_name_a10",
315+ "long_attr_name_b10",
316+ "long_mixed_attr_name_c10"]
317+
318+testSpinalCaseField :: Test
319+testSpinalCaseField = testCodec
320+ @(Field SpinalCase)
321+ "codec field spinal case"
322+ ["long-attr-name-a10",
323+ "long-attr-name-b10",
324+ "long-mixed-attr-name-c10"]
325+
326+testTrainCaseField :: Test
327+testTrainCaseField = testCodec
328+ @(Field TrainCase)
329+ "codec field train case"
330+ ["Long-Attr-Name-A10",
331+ "Long-Attr-Name-B10",
332+ "Long-Mixed-Attr-Name-C10"]
333+
334+testAsIsCodec :: Test
335+testAsIsCodec = testCodec
336+ @AsIs
337+ "codec as is"
338+ ["longAttrNameA10",
339+ "long_attr_name_b10",
340+ "longMixed_attr_NameC10"]
341+
342+testAsIsField :: Test
343+testAsIsField = testCodec
344+ @(Field AsIs)
345+ "codec field as is"
346+ ["longAttrNameA10",
347+ "long_attr_name_b10",
348+ "longMixed_attr_NameC10"]
349+
350+testComposeRLCodec :: Test
351+testComposeRLCodec = testCodec
352+ @(Field UpperCase <<< Field (DropPrefix "long"))
353+ "codec (<<<)"
354+ ["ATTRNAMEA10",
355+ "_ATTR_NAME_B10",
356+ "MIXED_ATTR_NAMEC10"]
357+
358+testComposeRLField :: Test
359+testComposeRLField = testCodec
360+ @(Field (UpperCase <<< DropPrefix "long"))
361+ "codec field (<<<)"
362+ ["ATTRNAMEA10",
363+ "_ATTR_NAME_B10",
364+ "MIXED_ATTR_NAMEC10"]
365+
366+testComposeLRCodec :: Test
367+testComposeLRCodec = testCodec
368+ @(Field (DropPrefix "long") >>> Field UpperCase)
369+ "codec (>>>)"
370+ ["ATTRNAMEA10",
371+ "_ATTR_NAME_B10",
372+ "MIXED_ATTR_NAMEC10"]
373+
374+testComposeLRField :: Test
375+testComposeLRField = testCodec
376+ @(Field (DropPrefix "long" >>> UpperCase))
377+ "codec field (>>>)"
378+ ["ATTRNAMEA10",
379+ "_ATTR_NAME_B10",
380+ "MIXED_ATTR_NAMEC10"]
test/Server/Main.hs+24−23
@@ -5,7 +5,6 @@ test client/server interaction
55import Test.HUnit
66import ProjectM36.Client
77import qualified ProjectM36.Client as C
8−import ProjectM36.Server.EntryPoints
98import ProjectM36.Server
109import ProjectM36.Server.Config
1110import ProjectM36.Relation
@@ -14,16 +13,8 @@ import ProjectM36.IsomorphicSchema
1413import ProjectM36.Base
1514
1615import System.Exit
17−
16+import Network.Socket (SockAddr(..))
1817import Control.Concurrent
19−import Network.Transport (EndPointAddress)
20−
21−#if MIN_VERSION_network_transport_tcp(0,6,0)
22−import Network.Transport.TCP.Internal (encodeEndPointAddress, decodeEndPointAddress)
23−#else
24−import Network.Transport.TCP (encodeEndPointAddress, decodeEndPointAddress)
25−#endif
26−
2718import Data.Either (isRight)
2819import Control.Exception
2920import System.IO.Temp
@@ -32,6 +23,8 @@ import System.FilePath
3223import System.Directory
3324#endif
3425
26+type Timeout = Int
27+
3528testList :: SessionId -> Connection -> MVar () -> Test
3629testList sessionId conn notificationTestMVar = TestList $ serverTests ++ sessionTests
3730 where
@@ -49,7 +42,7 @@ testList sessionId conn notificationTestMVar = TestList $ serverTests ++ session
4942 testRelationVariableSummary,
5043 testNotification notificationTestMVar
5144 ]
52− serverTests = [testRequestTimeout, testFileDescriptorCount]
45+ serverTests = [testRequestTimeout, testFileDescriptorCount, testClientConnectFail]
5346
5447main :: IO ()
5548main = do
@@ -69,11 +62,9 @@ main = do
6962testDatabaseName :: DatabaseName
7063testDatabaseName = "test"
7164
72−testConnection :: EndPointAddress -> MVar () -> IO (Either ConnectionError (SessionId, Connection))
73−testConnection serverAddress mvar = do
74− let Just (host, service, _) = decodeEndPointAddress serverAddress
75− serverAddress' = encodeEndPointAddress host service 1
76− let connInfo = RemoteProcessConnectionInfo testDatabaseName (NodeId serverAddress') (testNotificationCallback mvar)
65+testConnection :: Port -> MVar () -> IO (Either ConnectionError (SessionId, Connection))
66+testConnection serverPort mvar = do
67+ let connInfo = RemoteConnectionInfo testDatabaseName "127.0.0.1" (show serverPort) (testNotificationCallback mvar)
7768 --putStrLn ("testConnection: " ++ show serverAddress)
7869 eConn <- connectProjectM36 connInfo
7970 case eConn of
@@ -85,7 +76,7 @@ testConnection serverAddress mvar = do
8576 Right sessionId -> pure $ Right (sessionId, conn)
8677
8778-- | A version of 'launchServer' which returns the port on which the server is listening on a secondary thread
88−launchTestServer :: Timeout -> IO (EndPointAddress, ThreadId)
79+launchTestServer :: Timeout -> IO (Port, ThreadId)
8980launchTestServer ti = do
9081 addressMVar <- newEmptyMVar
9182 tid <- forkIO $
@@ -94,13 +85,14 @@ launchTestServer ti = do
9485 persistenceStrategy = CrashSafePersistence (tempdir </> "db"),
9586 perRequestTimeout = ti,
9687 testMode = True,
97− bindPort = 0
88+ bindPort = 0,
89+ checkFS = False --not stricly needed for these tests
9890 }
9991
10092 launchServer config (Just addressMVar) >> pure ()
101− endPointAddress <- takeMVar addressMVar
93+ (SockAddrInet port _) <- takeMVar addressMVar
10294 --liftIO $ putStrLn ("launched server on " ++ show endPointAddress)
103− pure (endPointAddress, tid)
95+ pure (fromIntegral port, tid)
10496
10597testRelationalExpr :: SessionId -> Connection -> Test
10698testRelationalExpr sessionId conn = TestCase $ do
@@ -146,10 +138,11 @@ testPlanForDatabaseContextExpr sessionId conn = TestCase $ do
146138 let attrExprs = [AttributeAndTypeNameExpr "x" (PrimitiveTypeConstructor "Int" IntAtomType) ()]
147139 testrv = "testrv"
148140 dbExpr = Define testrv attrExprs
141+ expected = Define testrv [AttributeAndTypeNameExpr "x" (PrimitiveTypeConstructor "Int" IntAtomType) UncommittedContextMarker]
149142 planResult <- planForDatabaseContextExpr sessionId conn dbExpr
150143 case planResult of
151144 Left err -> assertFailure (show err)
152− Right plan -> assertEqual "planForDatabaseContextExpr failure" dbExpr plan
145+ Right plan -> assertEqual "planForDatabaseContextExpr failure" expected plan
153146
154147testTransactionGraphAsRelation :: SessionId -> Connection -> Test
155148testTransactionGraphAsRelation sessionId conn = TestCase $ do
@@ -215,7 +208,7 @@ testRequestTimeout = TestCase $ do
215208 Left err -> putStrLn ("failed to connect: " ++ show err) >> exitFailure
216209 Right (session, testConn) -> do
217210 res <- catchJust (\exc -> if exc == RequestTimeoutException then Just exc else Nothing) (callTestTimeout_ session testConn) (const (pure False))
218− assertBool "exception was not thrown" (not res)
211+ assertBool "timeout exception was not thrown" (not res)
219212 killThread serverTid
220213
221214testFileDescriptorCount :: Test
@@ -244,4 +237,12 @@ fdCount = do
244237#else
245238--pass on non-linux platforms
246239testFileDescriptorCount = TestCase (pure ())
247−#endif
240+#endif
241+
242+testClientConnectFail :: Test
243+testClientConnectFail = TestCase $ do
244+ let connInfo = RemoteConnectionInfo "nonexistentdb" "127.0.0.1" "7777" emptyNotificationCallback
245+ eConn <- connectProjectM36 connInfo
246+ case eConn of
247+ Left (IOExceptionError _) -> pure ()
248+ _ -> assertFailure "connection failure failed"
test/Server/WebSocket.hs+8−12
@@ -18,12 +18,6 @@ import Data.Aeson
1818import qualified Data.Map as M
1919import qualified Data.ByteString.Lazy as BS
2020import ProjectM36.Relation
21−#if MIN_VERSION_network_transport_tcp(0,6,0)
22−import Network.Transport.TCP.Internal (decodeEndPointAddress)
23−#else
24−import Network.Transport.TCP (decodeEndPointAddress)
25−#endif
26−
2721
2822--start the websocket server
2923-- run some tutoriald against it
@@ -32,16 +26,17 @@ launchTestServer :: IO (PortNumber, DatabaseName)
3226launchTestServer = do
3327 addressMVar <- newEmptyMVar
3428 let config = defaultServerConfig { databaseName = testDatabaseName,
35− bindPort = 0 }
29+ bindPort = 0,
30+ checkFS = False}
3631 testDatabaseName = "test"
3732 -- start normal server
3833 _ <- forkIO (launchServer config (Just addressMVar) >> pure ())
39− serverAddress <- takeMVar addressMVar
34+ (SockAddrInet dbPort _) <- takeMVar addressMVar
4035 let wsServerHost = "127.0.0.1"
4136 wsServerPort = 8889
42− Just (dbHost, dbPort, _) = decodeEndPointAddress serverAddress
37+ dbHost = "127.0.0.1"
4338 -- start websocket server proxy -- runServer doesn't support returning an arbitrary socket
44− _ <- forkIO (WS.runServer wsServerHost wsServerPort (websocketProxyServer (read dbPort) dbHost))
39+ _ <- forkIO (WS.runServer wsServerHost wsServerPort (websocketProxyServer (fromIntegral dbPort) dbHost))
4540 --wait for socket to be listening
4641 waitForListenSocket 5 (fromIntegral wsServerPort)
4742 pure (fromIntegral wsServerPort, testDatabaseName)
@@ -56,13 +51,14 @@ waitForListenSocket secondsToTry port =
5651 if secondsToTry <= 0 then
5752 throw WaitForSocketListenException
5853 else do
59− hostaddr <- inet_addr "127.0.0.1"
54+ --hostaddr <- inet_addr "127.0.0.1"
55+ hostaddr:_ <- getAddrInfo Nothing (Just "127.0.0.1") (Just (show port))
6056 sock <- socket AF_INET Stream defaultProtocol
6157 let handler :: IOException -> IO ()
6258 handler _ = do
6359 threadDelay 1000000
6460 waitForListenSocket (secondsToTry - 1) port
65− catch (connect sock (SockAddrInet port hostaddr)) handler
61+ catch (connect sock (addrAddress hostaddr)) handler
6662
6763main :: IO ()
6864main = do
test/TransactionGraph/Merge.hs+70−39
@@ -4,15 +4,28 @@ import ProjectM36.Base
44import ProjectM36.Attribute
55import ProjectM36.Relation
66import ProjectM36.Transaction
7+import ProjectM36.TransactionInfo as TI
78import ProjectM36.TransactionGraph
89import ProjectM36.Error
910import ProjectM36.Key
1011import qualified ProjectM36.DisconnectedTransaction as Discon
1112import qualified ProjectM36.DatabaseContext as DBC
1213import ProjectM36.RelationalExpression
14+import ProjectM36.StaticOptimizer
1315
1416import qualified Data.ByteString.Lazy as BS
1517import System.Exit
18+
19+
20+
21+
22+
23+
24+
25+
26+
27+
28+
1629import Data.Word
1730import qualified Data.UUID as U
1831import qualified Data.Set as S
@@ -21,8 +34,6 @@ import Data.Maybe
2134import Data.Time.Clock
2235import Data.Time.Calendar
2336
24−import Control.Monad.State
25−
2637{-# ANN module ("HLint: ignore Reduce duplication" :: String) #-}
2738
2839testTime :: UTCTime
@@ -62,8 +73,8 @@ basicTransactionGraph = do
6273 uuidB = fakeUUID 11
6374 uuidRoot = fakeUUID 1
6475 rootContext = concreteDatabaseContext rootTrans
65− (_, bsGraph') <- addTransaction "branchA" (createTrans uuidA (TransactionInfo uuidRoot S.empty testTime) rootContext) bsGraph
66− (_, bsGraph'') <- addTransaction "branchB" (createTrans uuidB (TransactionInfo uuidRoot S.empty testTime) rootContext) bsGraph'
76+ (_, bsGraph') <- addTransaction "branchA" (createTrans uuidA (TI.singleParent uuidRoot testTime) rootContext) bsGraph
77+ (_, bsGraph'') <- addTransaction "branchB" (createTrans uuidB (TI.singleParent uuidRoot testTime) rootContext) bsGraph'
6778 pure bsGraph''
6879
6980addTransaction :: HeadName -> Transaction -> TransactionGraph -> IO (Transaction, TransactionGraph)
@@ -107,7 +118,7 @@ testSubGraphToFirstAncestorSnipBranch = TestCase $ do
107118 baseGraph <- basicTransactionGraph
108119 transA <- assertMaybe (transactionForHead "branchA" baseGraph) "failed to get branchA"
109120 transB <- assertMaybe (transactionForHead "branchB" baseGraph) "failed to get branchB"
110− (_, graph) <- addTransaction "branchC" (createTrans (fakeUUID 12) (TransactionInfo (fakeUUID 1) S.empty testTime) (concreteDatabaseContext transA)) baseGraph
121+ (_, graph) <- addTransaction "branchC" (createTrans (fakeUUID 12) (TI.singleParent (fakeUUID 1) testTime) (concreteDatabaseContext transA)) baseGraph
111122 subgraph <- assertEither $ subGraphOfFirstCommonAncestor graph (transactionHeadsForGraph baseGraph) transA transB S.empty
112123 assertGraph subgraph
113124 let graphEq graphArg = S.map transactionId (transactionsForGraph graphArg)
@@ -121,16 +132,18 @@ testSubGraphToFirstAncestorMoreTransactions = TestCase $ do
121132
122133-- add another relvar to branchB
123134 branchBTrans <- assertMaybe (transactionForHead "branchB" graph) "failed to get branchB head"
124− (updatedBranchBContext,_,_) <- case runState (evalDatabaseContextExpr (Assign "branchBOnlyRelvar" (ExistingRelation relationTrue))) (freshDatabaseState (concreteDatabaseContext branchBTrans)) of
125− (Left err, _) -> assertFailure (show err) >> undefined
126− (Right (), context) -> pure context
127− (_, graph') <- addTransaction "branchB" (createTrans (fakeUUID 3) (TransactionInfo (transactionId branchBTrans) S.empty testTime) updatedBranchBContext) graph
135+ let env = mkDatabaseContextEvalEnv (transactionId branchBTrans) graph
136+ branchBContext = concreteDatabaseContext branchBTrans
137+ updatedBranchBContext <- case runDatabaseContextEvalMonad branchBContext env (optimizeAndEvalDatabaseContextExpr True (Assign "branchBOnlyRelvar" (ExistingRelation relationTrue))) of
138+ Left err -> assertFailure (show err) >> undefined
139+ Right st -> pure $ dbc_context st
140+ (_, graph') <- addTransaction "branchB" (createTrans (fakeUUID 3) (TI.singleParent (transactionId branchBTrans) testTime) updatedBranchBContext) graph
128141 branchBTrans' <- assertMaybe (transactionForHead "branchB" graph') "failed to get branchB head"
129142 assertEqual "branchB id 3" (fakeUUID 3) (transactionId branchBTrans')
130143
131144 -- add another transaction to branchA
132145 branchATrans <- assertMaybe (transactionForHead "branchA" graph) "failed to get branchA head"
133− (_, graph'') <- addTransaction "branchA" (createTrans (fakeUUID 4) (TransactionInfo (transactionId branchATrans) S.empty testTime) (concreteDatabaseContext branchATrans)) graph'
146+ (_, graph'') <- addTransaction "branchA" (createTrans (fakeUUID 4) (TI.singleParent (transactionId branchATrans) testTime) (concreteDatabaseContext branchATrans)) graph'
134147 branchATrans' <- assertMaybe (transactionForHead "branchA" graph'') "failed to get branchA head"
135148 assertEqual "branchA id 4" (fakeUUID 4) (transactionId branchATrans')
136149
@@ -148,12 +161,15 @@ testSelectedBranchMerge = TestCase $ do
148161
149162 -- add another relvar to branchB
150163 branchBTrans <- assertMaybe (transactionForHead "branchB" graph) "failed to get branchB head"
151− (updatedBranchBContext,_,_) <- case runState (evalDatabaseContextExpr (Assign "branchBOnlyRelvar" (ExistingRelation relationTrue))) (freshDatabaseState (concreteDatabaseContext branchBTrans)) of
152− (Left err, _) -> assertFailure (show err) >> undefined
153− (Right (), context) -> pure context
154− (_, graph') <- addTransaction "branchB" (createTrans (fakeUUID 3) (TransactionInfo (transactionId branchBTrans) S.empty testTime) updatedBranchBContext) graph
164+ let env = mkDatabaseContextEvalEnv (transactionId branchBTrans) graph
165+ branchBContext = concreteDatabaseContext branchBTrans
166+ updatedBranchBContext <- case runDatabaseContextEvalMonad branchBContext env (optimizeAndEvalDatabaseContextExpr True (Assign "branchBOnlyRelvar" (ExistingRelation relationTrue))) of
167+ Left err -> assertFailure (show err) >> undefined
168+ Right st -> pure (dbc_context st)
169+ (_, graph') <- addTransaction "branchB" (createTrans (fakeUUID 3) (TI.singleParent (transactionId branchBTrans) testTime) updatedBranchBContext) graph
155170 --create the merge transaction in the graph
156− let eGraph' = mergeTransactions testTime (fakeUUID 4) (fakeUUID 10) (SelectedBranchMergeStrategy "branchA") ("branchA", "branchB") graph'
171+ let eGraph' = runGraphRefRelationalExprM gfEnv $ mergeTransactions testTime (fakeUUID 4) (fakeUUID 10) (SelectedBranchMergeStrategy "branchA") ("branchA", "branchB")
172+ gfEnv = freshGraphRefRelationalExprEnv Nothing graph'
157173
158174 (_, graph'') <- assertEither eGraph'
159175
@@ -175,18 +191,22 @@ testUnionPreferMergeStrategy = TestCase $ do
175191 branchBTrans <- assertMaybe (transactionForHead "branchB" graph) "branchBTrans"
176192 branchBRelVar <- assertEither $ mkRelationFromList (attributesFromList [Attribute "conflict" IntAtomType]) []
177193 let branchAContext = (concreteDatabaseContext branchATrans) {relationVariables = M.insert conflictRelVarName branchARelVar (relationVariables (concreteDatabaseContext branchATrans))}
178− branchARelVar = relationTrue
179− branchBContext = (concreteDatabaseContext branchBTrans) {relationVariables = M.insert conflictRelVarName branchBRelVar (relationVariables (concreteDatabaseContext branchBTrans))}
180− conflictRelVarName = "conflictRelVar"
194+ branchARelVar = ExistingRelation relationTrue
195+ branchBContext = (concreteDatabaseContext branchBTrans) {relationVariables = M.insert conflictRelVarName (ExistingRelation branchBRelVar) (relationVariables (concreteDatabaseContext branchBTrans))}
196+ conflictRelVarName = "conflictRelVar"
181197
182− (_, graph') <- addTransaction "branchA" (createTrans (fakeUUID 3) (TransactionInfo (transactionId branchATrans) S.empty testTime) branchAContext) graph
183− (_, graph'') <- addTransaction "branchB" (createTrans (fakeUUID 4) (TransactionInfo (transactionId branchBTrans) S.empty testTime) branchBContext) graph'
198+ (_, graph') <- addTransaction "branchA" (createTrans (fakeUUID 3) (TI.singleParent (transactionId branchATrans) testTime) branchAContext) graph
199+ (_, graph'') <- addTransaction "branchB" (createTrans (fakeUUID 4) (TI.singleParent (transactionId branchBTrans) testTime) branchBContext) graph'
184200 -- validate that the conflict is hidden because we preferred a branch
185− let merged = mergeTransactions testTime (fakeUUID 5) (fakeUUID 3) (UnionPreferMergeStrategy "branchB") ("branchA", "branchB") graph''
201+ let merged = runGraphRefRelationalExprM env $ mergeTransactions testTime (fakeUUID 5) (fakeUUID 3) (UnionPreferMergeStrategy "branchB") ("branchA", "branchB")
202+ env = freshGraphRefRelationalExprEnv Nothing graph''
186203 case merged of
187204 Left err -> assertFailure ("expected merge success: " ++ show err)
188− Right (discon, _) ->
189− assertEqual "branchB relvar preferred in conflict" (Just branchBRelVar) (M.lookup conflictRelVarName (relationVariables (Discon.concreteDatabaseContext discon)))
205+ Right (discon, _) -> do
206+ let Just rvExpr = M.lookup conflictRelVarName (relationVariables (Discon.concreteDatabaseContext discon))
207+ reEnv = freshGraphRefRelationalExprEnv (Just (Discon.concreteDatabaseContext discon)) graph
208+ let eRvRel = runGraphRefRelationalExprM reEnv (evalGraphRefRelationalExpr rvExpr)
209+ assertEqual "branchB relvar preferred in conflict" (Right branchBRelVar) eRvRel
190210
191211-- try various individual component conflicts and check for merge failure
192212testUnionMergeStrategy :: Test
@@ -201,31 +221,41 @@ testUnionMergeStrategy = TestCase $ do
201221
202222 let updatedBranchBContext = (concreteDatabaseContext branchBTrans) {relationVariables = M.insert branchBOnlyRelVarName branchBOnlyRelVar (relationVariables (concreteDatabaseContext branchBTrans)) }
203223 updatedBranchAContext = (concreteDatabaseContext branchATrans) {inclusionDependencies = M.insert branchAOnlyIncDepName branchAOnlyIncDep (inclusionDependencies (concreteDatabaseContext branchATrans)) }
204− branchBOnlyRelVar = relationTrue
224+ branchBOnlyRelVar = ExistingRelation relationTrue
205225 branchAOnlyIncDepName = "branchAOnlyIncDep"
206226 branchBOnlyRelVarName = "branchBOnlyRelVar"
207227 branchAOnlyIncDep = InclusionDependency (ExistingRelation relationTrue) (ExistingRelation relationTrue)
208− (_, graph') <- addTransaction "branchB" (createTrans (fakeUUID 3) (TransactionInfo (transactionId branchBTrans) S.empty testTime) updatedBranchBContext) graph
209− (discon, _) <- assertEither $ mergeTransactions testTime (fakeUUID 5) (fakeUUID 10) UnionMergeStrategy ("branchA", "branchB") graph'
210− assertEqual "branchBOnlyRelVar should appear in the merge" (M.lookup branchBOnlyRelVarName (relationVariables (Discon.concreteDatabaseContext discon))) (Just relationTrue)
211− (_, graph'') <- addTransaction "branchA" (createTrans (fakeUUID 4) (TransactionInfo (transactionId branchATrans) S.empty testTime) updatedBranchAContext) graph'
212− let eMergeGraph = mergeTransactions testTime (fakeUUID 5) (fakeUUID 3) UnionMergeStrategy ("branchA", "branchB") graph''
228+ (_, graph') <- addTransaction "branchB" (createTrans (fakeUUID 3) (TI.singleParent (transactionId branchBTrans) testTime) updatedBranchBContext) graph
229+ let env = freshGraphRefRelationalExprEnv Nothing graph'
230+ (discon, _) <- assertEither $ runGraphRefRelationalExprM env $ mergeTransactions testTime (fakeUUID 5) (fakeUUID 10) UnionMergeStrategy ("branchA", "branchB")
231+ let Just rvExpr = M.lookup branchBOnlyRelVarName (relationVariables (Discon.concreteDatabaseContext discon))
232+ Right rvRel = runGraphRefRelationalExprM reEnv (evalGraphRefRelationalExpr rvExpr)
233+ reEnv = freshGraphRefRelationalExprEnv (Just (Discon.concreteDatabaseContext discon)) graph
234+
235+ assertEqual "branchBOnlyRelVar should appear in the merge" relationTrue rvRel
236+ (_, graph'') <- addTransaction "branchA" (createTrans (fakeUUID 4) (TI.singleParent (transactionId branchATrans) testTime) updatedBranchAContext) graph'
237+ let eMergeGraph = runGraphRefRelationalExprM gfEnv $ mergeTransactions testTime (fakeUUID 5) (fakeUUID 3) UnionMergeStrategy ("branchA", "branchB")
238+ gfEnv = freshGraphRefRelationalExprEnv Nothing graph''
213239 case eMergeGraph of
214240 Left err -> assertFailure ("expected merge success: " ++ show err)
215241 Right (_, mergeGraph) -> do
216242 -- check that the new merge transaction has the correct parents
217243 mergeTrans <- assertEither $ transactionForId (fakeUUID 5) mergeGraph
218244 let mergeContext = concreteDatabaseContext mergeTrans
219− assertEqual "merge transaction parents" (transactionParentIds mergeTrans) (S.fromList [fakeUUID 3, fakeUUID 4])
245+ assertEqual "merge transaction parents" (parentIds mergeTrans) (S.fromList [fakeUUID 3, fakeUUID 4])
220246 -- check that the new merge tranasction has elements from both A and B branches
221− assertEqual "merge transaction relvars" (Just relationTrue) (M.lookup branchBOnlyRelVarName (relationVariables mergeContext))
247+ let Just rvExpr' = M.lookup branchBOnlyRelVarName (relationVariables mergeContext)
248+ Right rvRel' = runGraphRefRelationalExprM reEnv' (evalGraphRefRelationalExpr rvExpr')
249+ reEnv' = freshGraphRefRelationalExprEnv (Just mergeContext) graph
250+ assertEqual "merge transaction relvars" relationTrue rvRel'
222251 assertEqual "merge transaction incdeps" (Just branchAOnlyIncDep) (M.lookup branchAOnlyIncDepName (inclusionDependencies mergeContext))
223252 -- test an expected conflict- add branchBOnlyRelVar with same name but different attributes
224253 conflictRelVar <- assertEither $ mkRelationFromList (attributesFromList [Attribute "conflict" IntAtomType]) []
225− let conflictContextA = updatedBranchAContext {relationVariables = M.insert branchBOnlyRelVarName conflictRelVar (relationVariables updatedBranchAContext) }
254+ let conflictContextA = updatedBranchAContext {relationVariables = M.insert branchBOnlyRelVarName (ExistingRelation conflictRelVar) (relationVariables updatedBranchAContext) }
226255 conflictBranchATrans <- assertMaybe (transactionForHead "branchA" graph'') "retrieving head transaction for expected conflict"
227− (_, graph''') <- addTransaction "branchA" (createTrans (fakeUUID 6) (TransactionInfo (transactionId conflictBranchATrans) S.empty testTime) conflictContextA) graph''
228− let failingMerge = mergeTransactions testTime (fakeUUID 5) (fakeUUID 3) UnionMergeStrategy ("branchA", "branchB") graph'''
256+ (_, graph''') <- addTransaction "branchA" (createTrans (fakeUUID 6) (TI.singleParent (transactionId conflictBranchATrans) testTime) conflictContextA) graph''
257+ let failingMerge = runGraphRefRelationalExprM gfEnv' $ mergeTransactions testTime (fakeUUID 5) (fakeUUID 3) UnionMergeStrategy ("branchA", "branchB")
258+ gfEnv' = freshGraphRefRelationalExprEnv Nothing graph'''
229259 case failingMerge of
230260 Right _ -> assertFailure "expected merge failure"
231261 Left err -> assertEqual "merge failure" err (MergeTransactionError StrategyViolatesRelationVariableMergeError)
@@ -244,20 +274,21 @@ testUnionMergeIncDepViolation = TestCase $ do
244274 rvName = "x"
245275 Right branchArv = eRel 2
246276 Right branchBrv = eRel 3
247− branchAContext = (concreteDatabaseContext branchBTrans) {relationVariables = M.singleton rvName branchArv}
248− branchBContext = (concreteDatabaseContext branchBTrans) {relationVariables = M.singleton rvName branchBrv,
277+ branchAContext = (concreteDatabaseContext branchBTrans) {relationVariables = M.singleton rvName (ExistingRelation branchArv)}
278+ branchBContext = (concreteDatabaseContext branchBTrans) {relationVariables = M.singleton rvName (ExistingRelation branchBrv),
249279 inclusionDependencies = M.singleton incDepName incDep}
250280 incDepName = "x_key"
251281 incDep = inclusionDependencyForKey (AttributeNames (S.singleton "x")) (RelationVariable "x" ())
252282
253283
254284 --add the rv in new commits to both branches
255− (_, graph') <- addTransaction "branchB" (createTrans (fakeUUID 3) (TransactionInfo (transactionId branchBTrans) S.empty testTime) branchBContext) graph
285+ (_, graph') <- addTransaction "branchB" (createTrans (fakeUUID 3) (TI.singleParent (transactionId branchBTrans) testTime) branchBContext) graph
256286
257− (_, graph'') <- addTransaction "branchA" (createTrans (fakeUUID 4) (TransactionInfo (transactionId branchATrans) S.empty testTime) branchAContext) graph'
287+ (_, graph'') <- addTransaction "branchA" (createTrans (fakeUUID 4) (TI.singleParent (transactionId branchATrans) testTime) branchAContext) graph'
258288
259289 --check that the union merge fails due to a violated constraint
260− let eMerge = mergeTransactions testTime (fakeUUID 5) (fakeUUID 3) UnionMergeStrategy ("branchA", "branchB") graph''
290+ let eMerge = runGraphRefRelationalExprM env $ mergeTransactions testTime (fakeUUID 5) (fakeUUID 3) UnionMergeStrategy ("branchA", "branchB")
291+ env = freshGraphRefRelationalExprEnv Nothing graph''
261292 case eMerge of
262293 Left (InclusionDependencyCheckError incDepName') -> assertEqual "incdep violation name" incDepName incDepName'
263294 Left err -> assertFailure ("other error: " ++ show err)
test/TransactionGraph/Persist.hs+79−15
@@ -1,14 +1,14 @@
1+{-# LANGUAGE CPP #-}
12import Test.HUnit
23import ProjectM36.Base
34import ProjectM36.Persist (DiskSync(NoDiskSync))
45import ProjectM36.TransactionGraph.Persist
5−import ProjectM36.TransactionGraph
6+import ProjectM36.TransactionGraph as TG
67import ProjectM36.Transaction
78import ProjectM36.DateExamples
8−import ProjectM36.Client
9−import ProjectM36.Relation
109import System.IO.Temp
1110import System.Exit
11+import System.Directory
1212import Data.Either
1313import Data.UUID.V4 (nextRandom)
1414import System.FilePath
@@ -17,6 +17,9 @@ import qualified Data.Map as M
1717import qualified Data.Set as S
1818import Data.Time.Clock
1919import Data.Time.Calendar
20+import ProjectM36.Client as C
21+import ProjectM36.Relation
22+import ProjectM36.Transaction.Persist
2023
2124main :: IO ()
2225main = do
@@ -26,11 +29,12 @@ main = do
2629testList :: Test
2730testList = TestList [testBootstrapDB,
2831 testDBSimplePersistence,
29− testFunctionPersistence]
32+ testFunctionPersistence,
33+ testMerkleHashValidation]
3034
3135
32−stamp :: UTCTime
33−stamp = UTCTime (fromGregorian 1980 01 01) (secondsToDiffTime 1000)
36+stamp' :: UTCTime
37+stamp' = UTCTime (fromGregorian 1980 01 01) (secondsToDiffTime 1000)
3438
3539{- bootstrap a database, ensure that it can be read -}
3640testBootstrapDB :: Test
@@ -38,7 +42,7 @@ testBootstrapDB = TestCase $ withSystemTempDirectory "m36testdb" $ \tempdir -> d
3842 let dbdir = tempdir </> "dbdir"
3943 freshId <- nextRandom
4044
41− _ <- bootstrapDatabaseDir NoDiskSync dbdir (bootstrapTransactionGraph stamp freshId dateExamples)
45+ _ <- bootstrapDatabaseDir NoDiskSync dbdir (bootstrapTransactionGraph stamp' freshId dateExamples)
4246 loadedGraph <- transactionGraphLoad dbdir emptyTransactionGraph Nothing
4347 assertBool "transactionGraphLoad" $ isRight loadedGraph
4448
@@ -48,17 +52,17 @@ testDBSimplePersistence = TestCase $ withSystemTempDirectory "m36testdb" $ \temp
4852 let dbdir = tempdir </> "dbdir"
4953 freshId <- nextRandom
5054
51− let graph = bootstrapTransactionGraph stamp freshId dateExamples
55+ let graph = bootstrapTransactionGraph stamp' freshId dateExamples
5256 _ <- bootstrapDatabaseDir NoDiskSync dbdir graph
5357 case transactionForHead "master" graph of
5458 Nothing -> assertFailure "Failed to retrieve head transaction for master branch."
5559 Just headTrans ->
56− case interpretDatabaseContextExpr (concreteDatabaseContext headTrans) "x:=s" of
60+ case interpretDatabaseContextExpr (concreteDatabaseContext headTrans) (transactionId headTrans) graph "x:=s" of
5761 Left err -> assertFailure (show err)
5862 Right context' -> do
5963 freshId' <- nextRandom
60− let newdiscon = DisconnectedTransaction (transactionId headTrans) (Schemas context' M.empty) True
61− addTrans = addDisconnectedTransaction stamp freshId' "master" newdiscon graph
64+ let newdiscon = DisconnectedTransaction (transactionId headTrans) (Schemas context' M.empty) False
65+ addTrans = addDisconnectedTransaction stamp' freshId' "master" newdiscon graph
6266 --add a transaction to the graph
6367 case addTrans of
6468 Left err -> assertFailure (show err)
@@ -71,11 +75,69 @@ testDBSimplePersistence = TestCase $ withSystemTempDirectory "m36testdb" $ \temp
7175 case graphErr of
7276 Left err -> assertFailure (show err)
7377 Right graph'' -> assertBool "graph equality" (mapEq graph'' == mapEq graph')
74−
78+
79+testMerkleHashValidation :: Test
80+testMerkleHashValidation = TestCase $
81+ -- add a commit and validate the hashes successfully
82+ withSystemTempDirectory "m36testdb" $ \tempdir -> do
83+ let dbdir = tempdir </> "dbdir"
84+ connInfo = InProcessConnectionInfo (MinimalPersistence dbdir) emptyNotificationCallback []
85+ conn <- assertIOEither $ connectProjectM36 connInfo
86+ sess <- assertIOEither $ createSessionAtHead conn "master"
87+ Right _ <- executeDatabaseContextExpr sess conn (Assign "x" (ExistingRelation relationTrue))
88+ Right _ <- commit sess conn
89+ val <- C.validateMerkleHashes sess conn
90+ assertEqual "merkle success" (Right ()) val
91+
92+ --read graph from disk
93+ conn' <- assertIOEither $ connectProjectM36 connInfo
94+ sess' <- assertIOEither $ createSessionAtHead conn' "master"
95+
96+ val' <- C.validateMerkleHashes sess' conn'
97+ assertEqual "merkle read again success" (Right ()) val'
98+
99+ --alter the on-disk representation and check that the hash validation fails
100+ eGraph <- transactionGraphLoad dbdir emptyTransactionGraph Nothing
101+ case eGraph of
102+ Left err -> assertFailure $ "failed to load graph" ++ show err
103+ Right graph -> do
104+ let trans = transactionHeadsForGraph graph M.! "master"
105+ updatedTrans = Transaction (transactionId trans) (transactionInfo trans) updatedSchemas
106+ transactionDir' = dbdir </> show (transactionId trans)
107+ updatedSchemas =
108+ case schemas trans of
109+ Schemas ctx sschemas ->
110+ let updatedContext = ctx {
111+ relationVariables = M.insert "malicious" (ExistingRelation relationFalse) (relationVariables ctx)
112+ } in
113+ Schemas updatedContext sschemas
114+ maliciousGraph = TransactionGraph malHeads malTransSet
115+ malHeads = M.insert "master" updatedTrans (transactionHeadsForGraph graph)
116+ malTransSet = S.insert updatedTrans (transactionsForGraph graph)
117+ malMerkleHash = calculateMerkleHash updatedTrans maliciousGraph
118+ regMerkleHash = merkleHash (transactionInfo trans)
119+ --validate and fail
120+ let val'' = TG.validateMerkleHashes maliciousGraph
121+ assertEqual "loaded graph merkle hashes" (Left [MerkleValidationError (transactionId trans) regMerkleHash malMerkleHash]) val''
122+ --delete existing transaction directory
123+ removeDirectoryRecursive transactionDir'
124+ writeTransaction NoDiskSync dbdir updatedTrans
125+
126+ --read graph from disk
127+ eConnFail <- connectProjectM36 connInfo
128+ case eConnFail of
129+ Left err ->
130+ assertEqual "open connection merkle validation" (DatabaseValidationError [MerkleValidationError (transactionId trans) regMerkleHash malMerkleHash]) err
131+ Right _ -> assertFailure "open connection validation"
132+
133+
75134
76135--only Haskell-scripted dbc and atom functions can be serialized
77136testFunctionPersistence :: Test
78−testFunctionPersistence = TestCase $
137+#if !defined(PM36_HASKELL_SCRIPTING)
138+testFunctionPersistence = TestCase $ pure ()
139+#else
140+testFunctionPersistence = TestCase $
79141 withSystemTempDirectory "m36testdb" $ \tempdir -> do
80142 let dbdir = tempdir </> "dbdir"
81143 connInfo = InProcessConnectionInfo (MinimalPersistence dbdir) emptyNotificationCallback []
@@ -93,10 +155,12 @@ testFunctionPersistence = TestCase $
93155 conn2 <- assertIOEither $ connectProjectM36 connInfo
94156 sess2 <- assertIOEither $ createSessionAtHead conn2 "master"
95157
96− res <- executeRelationalExpr sess2 conn2 (MakeRelationFromExprs Nothing [TupleExpr (M.singleton "a" (FunctionAtomExpr "testdisk" [NakedAtomExpr (IntAtom 3)] ()))])
158+ res <- executeRelationalExpr sess2 conn2 (MakeRelationFromExprs Nothing (TupleExprs () [TupleExpr (M.singleton "a" (FunctionAtomExpr "testdisk" [NakedAtomExpr (IntAtom 3)] ()))]))
97159 let expectedRel = mkRelationFromList (attributesFromList [Attribute "a" IntAtomType]) [[IntAtom 3]]
98160 assertEqual "testdisk dbc function run" expectedRel res
99−
161+
162+#endif
163+
100164assertIOEither :: (Show a) => IO (Either a b) -> IO b
101165assertIOEither x = do
102166 ret <- x
test/TutorialD/Interpreter/AtomFunctionScript.hs+25−17
@@ -1,25 +1,32 @@
1−import TutorialD.Interpreter.TestBase
1+{-# LANGUAGE CPP #-}
22import System.Exit
33import Test.HUnit
4+#ifdef PM36_HASKELL_SCRIPTING
5+import TutorialD.Interpreter.TestBase
46import ProjectM36.Client
57import ProjectM36.Relation
68import ProjectM36.DataTypes.Maybe
79import qualified Data.Vector as V
810import qualified Data.Map as M
11+#endif
912
1013{-# ANN module ("HLint: ignore Reduce duplication" :: String) #-}
1114main :: IO ()
1215main = do
13− tcounts <- runTestTT (TestList [testBasicAtomFunction,
14− testExceptionAtomFunction,
15− testErrorAtomFunction,
16− testNoArgumentAtomFunction,
17− testArgumentTypeMismatch,
18− testPolymorphicReturnType,
19− testScriptedTypeVariable
20− ])
16+ tcounts <- runTestTT (TestList [
17+#ifdef PM36_HASKELL_SCRIPTING
18+ testBasicAtomFunction,
19+ testExceptionAtomFunction,
20+ testErrorAtomFunction,
21+ testNoArgumentAtomFunction,
22+ testArgumentTypeMismatch,
23+ testPolymorphicReturnType,
24+ testScriptedTypeVariable
25+#endif
26+ ])
2127 if errors tcounts + failures tcounts > 0 then exitFailure else exitSuccess
2228
29+#ifdef PM36_HASKELL_SCRIPTING
2330--add an atom function and run it
2431testBasicAtomFunction :: Test
2532testBasicAtomFunction = TestCase $ do
@@ -29,7 +36,7 @@ testBasicAtomFunction = TestCase $ do
2936 funcAtomExpr = FunctionAtomExpr "mkTest" [NakedAtomExpr (IntegerAtom 3)] ()
3037 tupleExprs = [TupleExpr (M.singleton "x" funcAtomExpr)]
3138 expectedResult = mkRelationFromList (V.fromList attrs) [[IntegerAtom 3]]
32− result <- executeRelationalExpr sess conn (MakeRelationFromExprs (Just (map NakedAttributeExpr attrs)) tupleExprs)
39+ result <- executeRelationalExpr sess conn (MakeRelationFromExprs (Just (map NakedAttributeExpr attrs)) (TupleExprs () tupleExprs))
3340
3441 assertEqual "simple atom function equality" expectedResult result
3542
@@ -40,7 +47,7 @@ testExceptionAtomFunction = TestCase $ do
4047 executeTutorialD sess conn "addatomfunction \"mkTest\" Integer -> Either AtomFunctionError Integer \"\"\"(\\(IntegerAtom x:xs) -> (error (show 1))) :: [Atom] -> Either AtomFunctionError Atom\"\"\""
4148 let attrs = [Attribute "x" IntegerAtomType]
4249 funcAtomExpr = FunctionAtomExpr "mkTest" [NakedAtomExpr (IntegerAtom 3)] ()
43− tupleExprs = [TupleExpr (M.singleton "x" funcAtomExpr)]
50+ tupleExprs = TupleExprs () [TupleExpr (M.singleton "x" funcAtomExpr)]
4451 result <- executeRelationalExpr sess conn (MakeRelationFromExprs (Just (map NakedAttributeExpr attrs)) tupleExprs)
4552 assertBool "catch error exception from script" (case result of
4653 Left (UnhandledExceptionError _) -> True
@@ -57,7 +64,7 @@ testNoArgumentAtomFunction = TestCase $ do
5764 executeTutorialD sess conn "addatomfunction \"mkTest\" Either AtomFunctionError Integer \"\"\"(\\x -> pure (IntegerAtom 5)) :: [Atom] -> Either AtomFunctionError Atom\"\"\""
5865 let attrs = [Attribute "x" IntegerAtomType]
5966 funcAtomExpr = FunctionAtomExpr "mkTest" [] ()
60− tupleExprs = [TupleExpr (M.singleton "x" funcAtomExpr)]
67+ tupleExprs = TupleExprs () [TupleExpr (M.singleton "x" funcAtomExpr)]
6168 expectedResult = mkRelationFromList (V.fromList attrs) [[IntegerAtom 5]]
6269 result <- executeRelationalExpr sess conn (MakeRelationFromExprs (Just (map NakedAttributeExpr attrs)) tupleExprs)
6370 assertEqual "no argument scripted function" expectedResult result
@@ -66,7 +73,7 @@ testArgumentTypeMismatch :: Test
6673testArgumentTypeMismatch = TestCase $ do
6774 (sess, conn) <- dateExamplesConnection emptyNotificationCallback
6875 executeTutorialD sess conn "addatomfunction \"mkTest\" Integer -> Either AtomFunctionError Integer \"\"\"(\\(IntegerAtom x:_) -> pure $ TextAtom \"wrong type\") :: [Atom] -> Either AtomFunctionError Atom\"\"\""
69− let tupleExprs = [TupleExpr (M.singleton "x" funcAtomExpr)]
76+ let tupleExprs = TupleExprs () [TupleExpr (M.singleton "x" funcAtomExpr)]
7077 funcAtomExpr = FunctionAtomExpr "mkTest" [NakedAtomExpr (IntegerAtom 3)] ()
7178 attrs = [Attribute "x" IntegerAtomType]
7279 expectedResult = Left (AtomTypeMismatchError IntegerAtomType TextAtomType)
@@ -80,7 +87,7 @@ testPolymorphicReturnType = TestCase $ do
8087 let funcAtomExpr = FunctionAtomExpr "fromMaybe" [NakedAtomExpr (IntegerAtom 5),
8188 NakedAtomExpr maybeAtom] ()
8289 maybeAtom = ConstructedAtom "Just" (maybeAtomType IntegerAtomType) [IntegerAtom 3]
83− relExpr = MakeRelationFromExprs Nothing [TupleExpr (M.singleton "x" funcAtomExpr)]
90+ relExpr = MakeRelationFromExprs Nothing (TupleExprs () [TupleExpr (M.singleton "x" funcAtomExpr)])
8491 mRelType <- typeForRelationalExpr sess conn relExpr
8592 case mRelType of
8693 Left err -> assertFailure (show err)
@@ -94,7 +101,7 @@ testPolymorphicReturnType = TestCase $ do
94101 let failFuncAtomExpr = FunctionAtomExpr "fromMaybe" [NakedAtomExpr (IntegerAtom 5),
95102 NakedAtomExpr mismatchAtom] ()
96103 mismatchAtom = ConstructedAtom "Just" (maybeAtomType TextAtomType) [TextAtom "fail"]
97− failRelExpr = MakeRelationFromExprs Nothing [TupleExpr (M.singleton "x" failFuncAtomExpr)]
104+ failRelExpr = MakeRelationFromExprs Nothing (TupleExprs () [TupleExpr (M.singleton "x" failFuncAtomExpr)])
98105 mFailRes <- executeRelationalExpr sess conn failRelExpr
99106 let expectedErr = Left (AtomFunctionTypeVariableMismatch "a" IntegerAtomType TextAtomType)
100107 assertEqual "expected type variable mismatch" expectedErr mFailRes
@@ -106,9 +113,10 @@ testScriptedTypeVariable = TestCase $ do
106113 executeTutorialD sess conn "addatomfunction \"idTest\" a -> Either AtomFunctionError a \"(\\\\(x:_) -> pure x) :: [Atom] -> Either AtomFunctionError Atom\""
107114 let attrs = [Attribute "x" IntegerAtomType]
108115 funcAtomExpr = FunctionAtomExpr "idTest" [NakedAtomExpr (IntegerAtom 3)] ()
109− tupleExprs = [TupleExpr (M.singleton "x" funcAtomExpr)]
116+ tupleExprs = TupleExprs () [TupleExpr (M.singleton "x" funcAtomExpr)]
110117 expectedResult = mkRelationFromList (V.fromList attrs) [[IntegerAtom 3]]
111118 result <- executeRelationalExpr sess conn (MakeRelationFromExprs (Just (map NakedAttributeExpr attrs)) tupleExprs)
112119
113120 assertEqual "id function equality" expectedResult result
114−
121+
122+#endif
test/TutorialD/Interpreter/DatabaseContextFunctionScript.hs+14−7
@@ -1,19 +1,26 @@
1−import TutorialD.Interpreter.TestBase
1+{-# LANGUAGE CPP #-}
22import System.Exit
33import Test.HUnit
4+#ifdef PM36_HASKELL_SCRIPTING
5+import TutorialD.Interpreter.TestBase
46import ProjectM36.Client
57import ProjectM36.Relation
68import qualified Data.Text as T
9+#endif
710
811main :: IO ()
912main = do
10− tcounts <- runTestTT (TestList [testBasicDBCFunction,
11− testErrorDBCFunction,
12− testExceptionDBCFunction,
13− testDBCFunctionWithAtomArguments
13+ tcounts <- runTestTT (TestList [
14+#ifdef PM36_HASKELL_SCRIPTING
15+ testBasicDBCFunction,
16+ testErrorDBCFunction,
17+ testExceptionDBCFunction,
18+ testDBCFunctionWithAtomArguments
19+#endif
1420 ])
1521 if errors tcounts + failures tcounts > 0 then exitFailure else exitSuccess
1622
23+#ifdef PM36_HASKELL_SCRIPTING
1724testBasicDBCFunction :: Test
1825testBasicDBCFunction = TestCase $ do
1926 (sess, conn) <- dateExamplesConnection emptyNotificationCallback
@@ -38,7 +45,7 @@ testExceptionDBCFunction = TestCase $ do
3845 (sess, conn) <- dateExamplesConnection emptyNotificationCallback
3946 let addfunc = "adddatabasecontextfunction \"bomb\" DatabaseContext -> Either DatabaseContextFunctionError DatabaseContext \"\"\"(\\[] _ -> error \"boom\") :: [Atom] -> DatabaseContext -> Either DatabaseContextFunctionError DatabaseContext\"\"\""
4047 executeTutorialD sess conn addfunc
41− expectTutorialDErr sess conn (\err -> "UnhandledExceptionError" `T.isPrefixOf` err) "execute bomb()"
48+ expectTutorialDErr sess conn ("UnhandledExceptionError" `T.isPrefixOf`) "execute bomb()"
4249
4350
4451testDBCFunctionWithAtomArguments :: Test
@@ -55,4 +62,4 @@ testDBCFunctionWithAtomArguments = TestCase $ do
5562 assertEqual "person relation" expectedPerson result
5663 expectTutorialDErr sess conn (T.isPrefixOf "AtomTypeMismatchError") "execute multiArgFunc(\"fail\", \"fail\")"
5764
58−
65+#endif
test/TutorialD/Interpreter/Import/ImportTest.hsnew file+47
@@ -0,0 +1,47 @@
1+import Test.HUnit
2+import ProjectM36.Base
3+import TutorialD.Interpreter.Import.TutorialD
4+import System.Exit
5+import qualified Data.Text as T
6+import System.IO.Temp
7+import System.FilePath
8+import qualified Data.Map as M
9+import System.IO
10+import System.Directory
11+import qualified Data.ByteString as BS
12+import qualified Data.Text.Encoding as TE
13+import Text.URI hiding (makeAbsolute)
14+
15+main :: IO ()
16+main = do
17+ tcounts <- runTestTT $ TestList [testTutdFileImport
18+ ,testTutdHTTPSImport
19+ ]
20+ if errors tcounts + failures tcounts > 0 then exitFailure else exitSuccess
21+
22+testTutdFileImport :: Test
23+testTutdFileImport = TestCase $
24+ withSystemTempFile "m.tutd" $ \tempPath handle -> do
25+ BS.hPut handle (TE.encodeUtf8 "x:=relation{tuple{a 5,b \"spam\"}}; y:=relation{tuple{b \"漢字\"}}")
26+ hClose handle
27+ let expectedExpr = MultipleExpr [
28+ Assign "x" (MakeRelationFromExprs Nothing
29+ $ TupleExprs () [TupleExpr (M.fromList [("a", NakedAtomExpr $ IntegerAtom 5),
30+ ("b", NakedAtomExpr $ TextAtom "spam")])]),
31+ Assign "y" (MakeRelationFromExprs Nothing
32+ $ TupleExprs () [TupleExpr (M.fromList [("b", NakedAtomExpr (TextAtom "漢字"))])])]
33+ --on Windows, the file URI should not include the drive letter "/c/Users..." -> "/Users"
34+ let uri = "file://" <> map (\c -> if c == '\\' then '/' else c) ( joinDrive "/" (dropDrive tempPath))
35+ fileURI <- mkURI (T.pack uri)
36+ imported <- importTutorialDFromFile fileURI Nothing
37+ assertEqual "import tutd" (Right expectedExpr) imported
38+
39+testTutdHTTPSImport :: Test
40+testTutdHTTPSImport = TestCase $ do
41+ uri <- mkURI "https://raw.githubusercontent.com/agentm/project-m36/master/test/TutorialD/Interpreter/Import/httpimporttest.tutd"
42+ let hash = "effe32b247586dc3ac0079fc241b9618d41d189afcaeb7907edbe5a8b45992a4"
43+ expected = Right (MultipleExpr [Assign "x" (RelationVariable "true" ()),Assign "y" (RelationVariable "false" ())])
44+ actual <- importTutorialDViaHTTP uri (Just hash)
45+ assertEqual "github https" expected actual
46+
47+
test/TutorialD/Interpreter/Import/TutorialD.hsdeleted−29
@@ -1,29 +0,0 @@
1−import Test.HUnit
2−import ProjectM36.Base
3−import TutorialD.Interpreter.Import.TutorialD
4−import System.Exit
5−import System.IO.Temp
6−import qualified Data.Map as M
7−import System.IO
8−import qualified Data.ByteString as BS
9−import qualified Data.Text.Encoding as TE
10−
11−main :: IO ()
12−main = do
13− tcounts <- runTestTT $ TestList [testTutdImport]
14− if errors tcounts + failures tcounts > 0 then exitFailure else exitSuccess
15−
16−testTutdImport :: Test
17−testTutdImport = TestCase $
18− withSystemTempFile "m.tutd" $ \tempPath handle -> do
19− BS.hPut handle (TE.encodeUtf8 "x:=relation{tuple{a 5,b \"spam\"}}; y:=relation{tuple{b \"漢字\"}}")
20− hClose handle
21− let expectedExpr = MultipleExpr [
22− Assign "x" (MakeRelationFromExprs Nothing
23− [TupleExpr (M.fromList [("a", NakedAtomExpr $ IntegerAtom 5),
24− ("b", NakedAtomExpr $ TextAtom "spam")])]),
25− Assign "y" (MakeRelationFromExprs Nothing
26− [TupleExpr (M.fromList [("b", NakedAtomExpr (TextAtom "漢字"))])])]
27− imported <- importTutorialD tempPath
28− assertEqual "import tutd" (Right expectedExpr) imported
29−
test/TutorialD/Interpreter/Import/httpimporttest.tutdnew file+2
@@ -0,0 +1,2 @@
1+x:=true;
2+y:=false;
test/TutorialD/Interpreter/TestBase.hs+10−13
@@ -2,16 +2,14 @@ module TutorialD.Interpreter.TestBase where
22import ProjectM36.Client
33import TutorialD.Interpreter
44import TutorialD.Interpreter.Base
5−import qualified ProjectM36.Base as Base
65import ProjectM36.DateExamples
6+import ProjectM36.DatabaseContext
77import Test.HUnit
8−import qualified Data.Map as M
98import Data.Text
109
1110dateExamplesConnection :: NotificationCallback -> IO (SessionId, Connection)
1211dateExamplesConnection callback = do
1312 dbconn <- connectProjectM36 (InProcessConnectionInfo NoPersistence callback [])
14− let incDeps = Base.inclusionDependencies dateExamples
1513 case dbconn of
1614 Left err -> error (show err)
1715 Right conn -> do
@@ -19,8 +17,7 @@ dateExamplesConnection callback = do
1917 case eSessionId of
2018 Left err -> error (show err)
2119 Right sessionId -> do
22− mapM_ (\(rvName,rvRel) -> executeDatabaseContextExpr sessionId conn (Assign rvName (Base.ExistingRelation rvRel))) (M.toList (Base.relationVariables dateExamples))
23− mapM_ (\(idName,incDep) -> executeDatabaseContextExpr sessionId conn (AddInclusionDependency idName incDep)) (M.toList incDeps)
20+ executeDatabaseContextExpr sessionId conn (databaseContextAsDatabaseContextExpr dateExamples) >>= eitherFail
2421 --skipping atom functions for now- there are no atom function manipulation operators yet
2522 commit sessionId conn >>= eitherFail
2623 pure (sessionId, conn)
@@ -31,13 +28,13 @@ executeTutorialD sessionId conn tutd = case parseTutorialD tutd of
3128 Right parsed -> do
3229 result <- evalTutorialD sessionId conn UnsafeEvaluation parsed
3330 case result of
34− QuitResult -> putStrLn "yyy" >> assertFailure "quit?"
35− DisplayResult _ -> putStrLn "xxx" >> assertFailure "display?"
36− DisplayIOResult _ -> putStrLn "z" >> assertFailure "displayIO?"
37− DisplayRelationResult _ -> putStrLn "Y" >> assertFailure "displayrelation?"
38− DisplayDataFrameResult _ -> putStrLn "DF" >> assertFailure "displaydataframe?"
39− DisplayParseErrorResult _ _ -> putStrLn "X" >> assertFailure "displayparseerrorresult?"
40− DisplayErrorResult err -> putStrLn "asd" >> assertFailure (show tutd ++ ": " ++ show err)
31+ QuitResult -> assertFailure "quit?"
32+ DisplayResult _ -> assertFailure "display?"
33+ DisplayIOResult _ -> assertFailure "displayIO?"
34+ DisplayRelationResult _ -> assertFailure "displayrelation?"
35+ DisplayDataFrameResult _ -> assertFailure "displaydataframe?"
36+ DisplayParseErrorResult _ _ -> assertFailure "displayparseerrorresult?"
37+ DisplayErrorResult err -> assertFailure (show tutd ++ ": " ++ show err)
4138 QuietSuccessResult -> pure ()
4239
4340expectTutorialDErr :: SessionId -> Connection -> (Text -> Bool) -> Text -> IO ()
@@ -52,7 +49,7 @@ expectTutorialDErr sessionId conn matchFunc tutd = case parseTutorialD tutd of
5249 DisplayRelationResult _ -> assertFailure "displayrelation?"
5350 DisplayDataFrameResult _ -> assertFailure "displaydataframe?"
5451 DisplayParseErrorResult _ _ -> assertFailure "displayparseerrorresult?"
55− DisplayErrorResult err -> assertBool ("match error on: " ++ unpack err) (matchFunc err)
52+ DisplayErrorResult err -> assertBool (unpack tutd ++ " match error on: " ++ unpack err) (matchFunc err)
5653 QuietSuccessResult -> pure ()
5754
5855eitherFail :: Either RelationalError a -> IO ()
test/TutorialD/Interpreter.hs → test/TutorialD/InterpreterTest.hsrenamed+115−27
@@ -9,6 +9,7 @@ import ProjectM36.TupleSet
99import ProjectM36.Error
1010import ProjectM36.DatabaseContext
1111import ProjectM36.AtomFunctions.Primitive
12+import ProjectM36.RelationalExpression
1213import ProjectM36.DataTypes.Either
1314import ProjectM36.DataTypes.Interval
1415import ProjectM36.DataTypes.NonEmptyList
@@ -39,8 +40,9 @@ main = do
3940 tcounts <- runTestTT (TestList tests)
4041 if errors tcounts + failures tcounts > 0 then exitFailure else exitSuccess
4142 where
42− tests = map (\(tutd, expected) -> TestCase $ assertTutdEqual basicDatabaseContext expected tutd) simpleRelTests ++
43− map (\(tutd, expected) -> TestCase $ assertTutdEqual dateExamples expected tutd) dateExampleRelTests ++ [
43+ tests = [
44+ simpleRelTests,
45+ dateExampleRelTests,
4446 transactionGraphBasicTest,
4547 transactionGraphAddCommitTest,
4648 transactionRollbackTest,
@@ -73,9 +75,22 @@ main = do
7375 testNonEmptyListType,
7476 testUnresolvedAtomTypes,
7577 testWithClause,
76− testAtomFunctionArgumentMismatch
78+ testAtomFunctionArgumentMismatch,
79+ testInvalidDataConstructor,
80+ testBasicList,
81+ testRelationDeclarationMismatch,
82+ testInvalidTuples,
83+ testSelfReferencingUncommittedContext,
84+ testUnionAndIntersectionAttributeExprs
7785 ]
78− simpleRelTests = [("x:=true", Right relationTrue),
86+
87+simpleRelTests :: Test
88+simpleRelTests = TestCase $ do
89+ (graph, transId) <- freshTransactionGraph dateExamples
90+ mapM_ (\(tutd, expected) ->
91+ assertTutdEqual basicDatabaseContext transId graph expected tutd) testTups
92+ where
93+ testTups = [("x:=true", Right relationTrue),
7994 ("x:=false", Right relationFalse),
8095 ("x:=true union false", Right relationTrue),
8196 ("x:=true minus false", Right relationTrue),
@@ -108,31 +123,39 @@ main = do
108123 ("x:=relation{tuple{a 5}} : {b:=6}", mkRelationFromTuples simpleDAttributes [RelationTuple simpleDAttributes (V.fromList [IntegerAtom 5, IntegerAtom 6])]),
109124 ("x:=relation{tuple{a 5}} : {b:=add(@a,5)}", mkRelationFromTuples simpleDAttributes [RelationTuple simpleDAttributes (V.fromList [IntegerAtom 5, IntegerAtom 10])]),
110125 ("x:=relation{tuple{a 5}} : {b:=add(@a,\"spam\")}", Left (AtomFunctionTypeError "add" 2 IntegerAtomType TextAtomType)),
111− ("x:=relation{tuple{a 5}} : {b:=add(add(@a,2),5)}", mkRelationFromTuples simpleDAttributes [RelationTuple simpleDAttributes (V.fromList [IntegerAtom 5, IntegerAtom 12])])
126+ ("x:=relation{tuple{a 5}} : {b:=add(add(@a,2),5)}", mkRelationFromTuples simpleDAttributes [RelationTuple simpleDAttributes (V.fromList [IntegerAtom 5, IntegerAtom 12])]),
127+ ("x:=false:{a:=1,b:=2}", mkRelationFromTuples simpleDAttributes [])
112128 ]
113129 simpleAAttributes = A.attributesFromList [Attribute "a" IntegerAtomType]
114130 simpleBAttributes = A.attributesFromList [Attribute "d" IntegerAtomType]
115131 simpleCAttributes = A.attributesFromList [Attribute "a" TextAtomType, Attribute "b" IntegerAtomType]
116132 simpleDAttributes = A.attributesFromList [Attribute "a" IntegerAtomType, Attribute "b" IntegerAtomType]
117− maybeTextAtomType = ConstructedAtomType "Maybe" (M.singleton "a" TextAtomType)
133+ simpleProjectionAttributes = A.attributesFromList [Attribute "c" IntegerAtomType]
134+ nestedRelationAttributes = A.attributesFromList [Attribute "a" IntegerAtomType, Attribute "b" (RelationAtomType $ A.attributesFromList [Attribute "a" IntegerAtomType])]
135+
136+dateExampleRelTests :: Test
137+dateExampleRelTests = TestCase $ do
138+ (graph, transId) <- freshTransactionGraph dateExamples
139+ mapM_ (\(tutd, expected) ->
140+ assertTutdEqual dateExamples transId graph expected tutd) testTups
141+ where
142+ simpleEitherIntTextAttributes = A.attributesFromList [Attribute "a" (eitherAtomType IntegerAtomType TextAtomType)]
118143 maybeIntegerAtomType = ConstructedAtomType "Maybe" (M.singleton "a" IntegerAtomType)
144+ maybeTextAtomType = ConstructedAtomType "Maybe" (M.singleton "a" TextAtomType)
119145 simpleMaybeTextAttributes = A.attributesFromList [Attribute "a" maybeTextAtomType]
120146 simpleMaybeIntAttributes = A.attributesFromList [Attribute "a" maybeIntegerAtomType]
121− simpleEitherIntTextAttributes = A.attributesFromList [Attribute "a" (eitherAtomType IntegerAtomType TextAtomType)]
122− simpleProjectionAttributes = A.attributesFromList [Attribute "c" IntegerAtomType]
123− nestedRelationAttributes = A.attributesFromList [Attribute "a" IntegerAtomType, Attribute "b" (RelationAtomType $ A.attributesFromList [Attribute "a" IntegerAtomType])]
124− extendTestAttributes = A.attributesFromList [Attribute "a" IntegerAtomType, Attribute "b" $ RelationAtomType (R.attributes suppliersRel)]
125147 byteStringAttributes = A.attributesFromList [Attribute "y" ByteStringAtomType]
126− groupCountAttrs = A.attributesFromList [Attribute "z" IntegerAtomType]
127148 minMaxAttrs = A.attributesFromList [Attribute "s#" TextAtomType, Attribute "z" IntegerAtomType]
149+ groupCountAttrs = A.attributesFromList [Attribute "z" IntegerAtomType]
128150 updateParisPlus10 = relMap (\tuple -> do
129151 statusAtom <- atomForAttributeName "status" tuple
130152 cityAtom <- atomForAttributeName "city" tuple
131153 if cityAtom == TextAtom "Paris" then
132154 Right $ updateTupleWithAtoms (M.singleton "status" (IntegerAtom (castInteger statusAtom + 10))) tuple
133155 else Right tuple) suppliersRel
134− dateExampleRelTests = [("x:=s where true", Right suppliersRel),
135− ("x:=s where city = \"London\"", restrict (\tuple -> pure $ atomForAttributeName "city" tuple == (Right $ TextAtom "London")) suppliersRel),
156+ extendTestAttributes = A.attributesFromList [Attribute "a" IntegerAtomType, Attribute "b" $ RelationAtomType (R.attributes suppliersRel)]
157+ testTups = [("x:=s where true", Right suppliersRel),
158+ ("x:=s where city = \"London\"", restrict (\tuple -> pure $ atomForAttributeName "city" tuple == Right (TextAtom "London")) suppliersRel),
136159 ("x:=s where false", Right $ Relation (R.attributes suppliersRel) emptyTupleSet),
137160 ("x:=p where color=\"Blue\" and city=\"Paris\"", mkRelationFromList (R.attributes productsRel) [[TextAtom "P5", TextAtom "Cam", TextAtom "Blue", IntegerAtom 12, TextAtom "Paris"]]),
138161 ("a:=s; update a (status:=50); x:=a{status}", mkRelation (A.attributesFromList [Attribute "status" IntegerAtomType]) (RelationTupleSet [mkRelationTuple (A.attributesFromList [Attribute "status" IntegerAtomType]) (V.fromList [IntegerAtom 50])])),
@@ -140,7 +163,7 @@ main = do
140163 --atom function tests
141164 ("x:=((s : {status2 := add(10,@status)}) where status2=add(10,@status)){city,s#,sname,status}", Right suppliersRel),
142165 ("x:=relation{tuple{a 5}} : {b:=s}", mkRelation extendTestAttributes (RelationTupleSet [mkRelationTuple extendTestAttributes (V.fromList [IntegerAtom 5, RelationAtom suppliersRel])])),
143− ("x:=s; update x where sname=\"Blake\" (city:=\"Boston\")", relMap (\tuple -> if atomForAttributeName "sname" tuple == (Right $ TextAtom "Blake") then Right $ updateTupleWithAtoms (M.singleton "city" (TextAtom "Boston")) tuple else Right tuple) suppliersRel),
166+ ("x:=s; update x where sname=\"Blake\" (city:=\"Boston\")", relMap (\tuple -> if atomForAttributeName "sname" tuple == Right (TextAtom "Blake") then Right $ updateTupleWithAtoms (M.singleton "city" (TextAtom "Boston")) tuple else Right tuple) suppliersRel),
144167 ("x:=s; update x where city=\"Paris\" (status:=add(@status,10))", updateParisPlus10),
145168 --relatom function tests
146169 ("x:=((s group ({city} as y)):{z:=count(@y)}){z}", mkRelation groupCountAttrs (RelationTupleSet [mkRelationTuple groupCountAttrs (V.singleton $ IntegerAtom 1)])),
@@ -174,14 +197,17 @@ main = do
174197 ("x:=relation{tuple{a fromGregorian(2017,05,30)}}", mkRelationFromList (A.attributesFromList [Attribute "a" DayAtomType]) [[DayAtom (fromGregorian 2017 05 30)]])
175198 ]
176199
177−assertTutdEqual :: DatabaseContext -> Either RelationalError Relation -> Text -> Assertion
178−assertTutdEqual databaseContext expected tutd = assertEqual (unpack tutd) expected interpreted
200+assertTutdEqual :: DatabaseContext -> TransactionId -> TransactionGraph -> Either RelationalError Relation -> Text -> Assertion
201+assertTutdEqual databaseContext transId graph expected tutd = assertEqual (unpack tutd) expected interpreted
179202 where
180− interpreted = case interpretDatabaseContextExpr databaseContext tutd of
203+ interpreted = case interpretDatabaseContextExpr databaseContext transId graph tutd of
181204 Left err -> Left err
182205 Right context -> case M.lookup "x" (relationVariables context) of
183206 Nothing -> Left $ RelVarNotDefinedError "x"
184− Just rel -> Right rel
207+ Just relExpr -> do
208+ let env = freshGraphRefRelationalExprEnv (Just context) graph
209+ runGraphRefRelationalExprM env (evalGraphRefRelationalExpr relExpr)
210+
185211
186212transactionGraphBasicTest :: Test
187213transactionGraphBasicTest = TestCase $ do
@@ -209,7 +235,7 @@ transactionGraphAddCommitTest = TestCase $ do
209235 commit sessionId dbconn >>= eitherFail
210236 discon <- disconnectedTransaction_ sessionId dbconn
211237 let context = Discon.concreteDatabaseContext discon
212− assertEqual "ensure x was added" (M.lookup "x" (relationVariables context)) (Just suppliersRel)
238+ assertEqual "ensure x was added" (M.lookup "x" (relationVariables context)) (Just (ExistingRelation suppliersRel))
213239
214240transactionRollbackTest :: Test
215241transactionRollbackTest = TestCase $ do
@@ -251,12 +277,16 @@ transactionBranchTest = TestCase $ do
251277
252278-- test that overlapping attribute names with different types fail with an error
253279failJoinTest :: Test
254−failJoinTest = TestCase $ assertTutdEqual basicDatabaseContext err "x:=relation{tuple{test 4}} join relation{tuple{test \"test\"}}"
280+failJoinTest = TestCase $ do
281+ (graph, transId) <- freshTransactionGraph dateExamples
282+ assertTutdEqual basicDatabaseContext transId graph err "x:=relation{tuple{test 4}} join relation{tuple{test \"test\"}}"
255283 where
256284 err = Left (TupleAttributeTypeMismatchError (A.attributesFromList [Attribute "test" IntegerAtomType]))
257285
258286simpleJoinTest :: Test
259−simpleJoinTest = TestCase $ assertTutdEqual dateExamples joinedRel "x:=s join sp"
287+simpleJoinTest = TestCase $ do
288+ (graph, transId) <- freshTransactionGraph dateExamples
289+ assertTutdEqual dateExamples transId graph joinedRel "x:=s join sp"
260290 where
261291 attrs = A.attributesFromList [Attribute "city" TextAtomType,
262292 Attribute "qty" IntegerAtomType,
@@ -332,7 +362,7 @@ testComments :: Test
332362testComments = TestCase $ do
333363 (sessionId, dbconn) <- dateExamplesConnection emptyNotificationCallback
334364 mapM_ (executeTutorialD sessionId dbconn) [
335− ":branch testbranch --test comment\n",
365+ ":branch testbranch --test comment",
336366 ":jumphead {- test comment -} master"]
337367
338368-- create a graph and query from two disparate contexts
@@ -383,7 +413,9 @@ testTransGraphRelationalExpr = TestCase $ do
383413 _ -> assertFailure "failed to delete branch"
384414
385415testMultiAttributeRename :: Test
386−testMultiAttributeRename = TestCase $ assertTutdEqual dateExamples renamedRel "x:=s rename {city as town, status as price} where false"
416+testMultiAttributeRename = TestCase $ do
417+ (graph, transId) <- freshTransactionGraph dateExamples
418+ assertTutdEqual dateExamples transId graph renamedRel "x:=s rename {city as town, status as price} where false"
387419 where
388420 sattrs = attributesFromList [Attribute "town" TextAtomType,
389421 Attribute "sname" TextAtomType,
@@ -468,16 +500,22 @@ testEmptyCommits = TestCase $ do
468500 assertEqual "empty insert empty commit" (Right False) dirty'
469501 Right () <- commit sessionId dbconn
470502
471− --update no tuples
503+ --update no tuples- since we defer the restriction, we can only assume the context is dirty, perhaps the constraint checker could offer an optimization here
472504 Right () <- executeDatabaseContextExpr sessionId dbconn (Update "s" (M.singleton "sname" (NakedAtomExpr (TextAtom "Bob"))) (AttributeEqualityPredicate "sname" (NakedAtomExpr (TextAtom "Mike"))))
473505 dirty'' <- disconnectedTransactionIsDirty sessionId dbconn
474− assertEqual "empty update empty commit" (Right False) dirty''
506+ assertEqual "empty update empty commit" (Right True) dirty''
507+ Right () <- commit sessionId dbconn
508+
509+ --assign the same rel expr
510+ Right () <- executeDatabaseContextExpr sessionId dbconn (Assign "true" (ExistingRelation relationTrue))
511+ sameREdirty <- disconnectedTransactionIsDirty sessionId dbconn
512+ assertEqual "same relexpr assigned" (Right False) sameREdirty
475513 Right () <- commit sessionId dbconn
476514
477515 --delete no tuples
478516 Right () <- executeDatabaseContextExpr sessionId dbconn (Delete "s" (AttributeEqualityPredicate "sname" (NakedAtomExpr (TextAtom "Mike"))))
479517 dirty''' <- disconnectedTransactionIsDirty sessionId dbconn
480− assertEqual "empty delete empty commit" (Right False) dirty'''
518+ assertEqual "empty delete empty commit" (Right True) dirty'''
481519
482520testIntervalAtom :: Test
483521testIntervalAtom = TestCase $ do
@@ -507,7 +545,7 @@ testListConstructedAtom = TestCase $ do
507545testTypeChecker :: Test
508546testTypeChecker = TestCase $ do
509547 (sessionId, dbconn) <- dateExamplesConnection emptyNotificationCallback
510− let err1 = "AtomFunctionTypeError \"max\" 1 (RelationAtomType [Attribute \"_\" IntegerAtomType]) IntegerAtomType"
548+ let err1 = "AtomFunctionTypeError \"max\" 1"
511549 expectTutorialDErr sessionId dbconn (T.isPrefixOf err1) "x:=relation{tuple{a 0}}:{b:=max(@a)}"
512550
513551--exercise expression parser
@@ -627,6 +665,10 @@ testWithClause = TestCase $ do
627665 executeTutorialD sessionId dbconn "x:=with (x as s) x"
628666 eX <- executeRelationalExpr sessionId dbconn (RelationVariable "x" ())
629667 assertEqual "with x as s" (Right suppliersRel) eX
668+
669+ executeTutorialD sessionId dbconn "y:=with(a as true) (with (b as a) b)"
670+ eY <- executeRelationalExpr sessionId dbconn (RelationVariable "y" ())
671+ assertEqual "nested with" (Right relationTrue) eY
630672
631673 let err1 = "RelVarAlreadyDefinedError"
632674 expectTutorialDErr sessionId dbconn (T.isPrefixOf err1) "x:=with (s as s) s"
@@ -642,3 +684,49 @@ testAtomFunctionArgumentMismatch = TestCase $ do
642684 --wrong argument count
643685 let err2 = "FunctionArgumentCountMismatchError"
644686 expectTutorialDErr sessionId dbconn (T.isPrefixOf err2) "x:=relation{tuple{a 5}} where ^gt(@a,1,3)"
687+
688+testInvalidDataConstructor :: Test
689+testInvalidDataConstructor = TestCase $ do
690+ --test that a referenced TypeConstructor in a DataConstructor definition matches the expected count of arguments
691+ (sessionId, dbconn) <- dateExamplesConnection emptyNotificationCallback
692+ let err1 = "ConstructedAtomArgumentCountMismatchError"
693+ expectTutorialDErr sessionId dbconn (T.isPrefixOf err1) "data TestT = TestT Maybe Int"
694+
695+testBasicList :: Test
696+testBasicList = TestCase $ do
697+ (sessionId, dbconn) <- dateExamplesConnection emptyNotificationCallback
698+ executeTutorialD sessionId dbconn "x := relation{tuple{ a (Cons 1 (Cons 2 Empty)) }}"
699+
700+testRelationDeclarationMismatch :: Test
701+testRelationDeclarationMismatch = TestCase $ do
702+ (sessionId, dbconn) <- dateExamplesConnection emptyNotificationCallback
703+ expectTutorialDErr sessionId dbconn (T.isPrefixOf "AtomTypeMismatchError") "data A a = A a | B | C; a := relation{a A Integer}{tuple{a A \"1\"}}"
704+
705+--generate errors when the tuples in a new relation don't match
706+testInvalidTuples :: Test
707+testInvalidTuples = TestCase $ do
708+ (sessionId, dbconn) <- dateExamplesConnection emptyNotificationCallback
709+ expectTutorialDErr sessionId dbconn (T.isPrefixOf "AttributeNamesMismatchError") ":showexpr relation{tuple{a 1},tuple{b 2}}"
710+ expectTutorialDErr sessionId dbconn (T.isPrefixOf "AttributeNamesMismatchError") ":showexpr relation{tuple{a 1},tuple{a 2, b 3}}"
711+-- expectTutorialDErr sessionId dbconn (T.isPrefixOf "ParseErrorBundle") ":showexpr relation{tuple{a 2, a 3}}" --parse failure can't be validated with this function
712+
713+testSelfReferencingUncommittedContext :: Test
714+testSelfReferencingUncommittedContext = TestCase $ do
715+ (sessionId, dbconn) <- dateExamplesConnection emptyNotificationCallback
716+ executeTutorialD sessionId dbconn "s:=s union s"
717+ eS <- executeRelationalExpr sessionId dbconn (RelationVariable "s" ())
718+ _ <- rollback sessionId dbconn
719+ eSorig <- executeRelationalExpr sessionId dbconn (RelationVariable "s" ())
720+ assertEqual "s=s'" eSorig eS
721+
722+testUnionAndIntersectionAttributeExprs :: Test
723+testUnionAndIntersectionAttributeExprs = TestCase $ do
724+ (sessionId, dbconn) <- dateExamplesConnection emptyNotificationCallback
725+ executeTutorialD sessionId dbconn "x:=s{intersection of {all but sname} {sname}}"
726+ xRel <- executeRelationalExpr sessionId dbconn (RelationVariable "x" ())
727+ assertEqual "intersection attrs" (Right relationTrue) xRel
728+
729+ executeTutorialD sessionId dbconn "y:=s{union of {all but sname} {sname}}"
730+ yRel <- executeRelationalExpr sessionId dbconn (RelationVariable "y" ())
731+ assertEqual "union attrs" (Right suppliersRel) yRel
732+
test/TutorialD/PrinterTest.hsnew file+47
@@ -0,0 +1,47 @@
1+{-# LANGUAGE OverloadedStrings #-}
2+import Test.HUnit
3+import ProjectM36.Base
4+import System.Exit
5+import Data.Text.Prettyprint.Doc
6+import Data.Map (fromList)
7+import TutorialD.Printer ()
8+import TutorialD.Interpreter.RelationalExpr
9+import Text.Megaparsec
10+import Data.Text (pack)
11+
12+testList :: Test
13+testList = TestList [
14+ testPretty "true" (RelationVariable "true" ()),
15+ testPretty "relation{tuple{a 3, b \"x\"}, tuple{a 4, b \"y\"}}" (MakeRelationFromExprs Nothing (TupleExprs () [TupleExpr (fromList [("a",NakedAtomExpr (IntegerAtom 3)),("b",NakedAtomExpr (TextAtom "x"))]),TupleExpr (fromList [("a",NakedAtomExpr (IntegerAtom 4)),("b",NakedAtomExpr (TextAtom "y"))])])),
16+ testPretty "true:{a:=1, b:=1}" (Extend (AttributeExtendTupleExpr "b" (NakedAtomExpr (IntegerAtom 1))) (Extend (AttributeExtendTupleExpr "a" (NakedAtomExpr (IntegerAtom 1))) (RelationVariable "true" ()))),
17+ testPretty "relation{tuple{a fromGregorian(2014, 2, 4)}}" (MakeRelationFromExprs Nothing (TupleExprs () [TupleExpr (fromList [("a",FunctionAtomExpr "fromGregorian" [NakedAtomExpr (IntegerAtom 2014),NakedAtomExpr (IntegerAtom 2),NakedAtomExpr (IntegerAtom 4)] ())])])),
18+ testPretty "relation{tuple{a bytestring(\"dGVzdGRhdGE=\")}}" (MakeRelationFromExprs Nothing (TupleExprs () [TupleExpr (fromList [("a",FunctionAtomExpr "bytestring" [NakedAtomExpr (TextAtom "dGVzdGRhdGE=")] ())])])),
19+ testPretty "relation{tuple{a t}}" (MakeRelationFromExprs Nothing (TupleExprs () [TupleExpr (fromList [("a",NakedAtomExpr (BoolAtom True))])])),
20+ testPretty "relation{tuple{a Cons 4 (Cons 5 Empty)}}" (MakeRelationFromExprs Nothing (TupleExprs () [TupleExpr (fromList [("a",ConstructedAtomExpr "Cons" [NakedAtomExpr (IntegerAtom 4),ConstructedAtomExpr "Cons" [NakedAtomExpr (IntegerAtom 5),ConstructedAtomExpr "Empty" [] ()] ()] ())])])),
21+ testPretty "relation{a Int, b Text, c Bool}{}" (MakeRelationFromExprs (Just [AttributeAndTypeNameExpr "a" (ADTypeConstructor "Int" []) (),AttributeAndTypeNameExpr "b" (ADTypeConstructor "Text" []) (),AttributeAndTypeNameExpr "c" (ADTypeConstructor "Bool" []) ()]) (TupleExprs () [])),
22+ testPretty "relation{a relation{b Int}}{}" (MakeRelationFromExprs (Just [AttributeAndTypeNameExpr "a" (RelationAtomTypeConstructor [AttributeAndTypeNameExpr "b" (ADTypeConstructor "Int" []) ()]) ()]) (TupleExprs () []))
23+ ]
24+
25+main :: IO ()
26+main = do
27+ tcounts <- runTestTT testList
28+ if errors tcounts + failures tcounts > 0 then exitFailure else exitSuccess
29+
30+testPretty :: String -> RelationalExpr -> Test
31+testPretty tutdStr relExprADT =
32+ TestCase $ do
33+ let relExprStr = show (pretty relExprADT)
34+ print relExprStr
35+ roundTrip <- parseRelExpr relExprStr
36+ {-tutdIn <- parseRelExpr tutdStr
37+ print ("tutd parsed", tutdIn)-}
38+ assertEqual ("pretty ADT " <> tutdStr) tutdStr relExprStr
39+ assertEqual ("round-trip " <> tutdStr) relExprADT roundTrip
40+
41+--round trip tutoriald
42+parseRelExpr :: String -> IO RelationalExpr
43+parseRelExpr tutdStr =
44+ case parse relExprP "test" (pack tutdStr) of
45+ Left err ->
46+ assertFailure (show err)
47+ Right parsed -> pure parsed
test/scripts.hs+5−2
@@ -4,6 +4,8 @@ import TutorialD.Interpreter.Import.TutorialD
44import System.Directory
55import Data.List (isSuffixOf)
66import System.Exit
7+import qualified Data.Text as T
8+import Text.URI
79
810testList :: IO Test
911testList = do
@@ -20,7 +22,8 @@ main = do
2022
2123testScript :: FilePath -> Test
2224testScript tutdFile = TestCase $ do
23− eImport <- importTutorialD tutdFile
25+ fileURI <- mkURI (T.pack ("file://" <> tutdFile))
26+ eImport <- importTutorialDFromFile fileURI Nothing
2427 case eImport of
2528 Left err -> assertFailure ("tutd import failure in " ++ tutdFile ++ ": " ++ show err)
26− Right _ -> pure ()
29+ Right _ -> pure ()