on master help sign in
Merge pull request #1 from agentm/master
debd1f9YuMingLiao
.appveyor.yml+4−2
@@ -16,6 +16,8 @@ clone_depth: 2
16environment:
16environment:
17 global:
17 global:
18 STACK_ROOT: "c:\\sr"
18 STACK_ROOT: "c:\\sr"
19+ matrix:
20+ - YAML: "stack.ghc8.6.yaml"
19
21
20platform:
22platform:
21 - x64
23 - x64
@@ -29,9 +31,9 @@ test_script:
29 - stack setup > nul
31 - stack setup > nul
30# The ugly echo "" hack is to avoid complaints about 0 being an invalid file
32# The ugly echo "" hack is to avoid complaints about 0 being an invalid file
31# descriptor
33# descriptor
32− - echo "" | stack --no-terminal test
34+ - echo "" | stack --stack-yaml %YAML% --no-terminal test
33# - 7z.exe a -t7z -m0=lzma -mx=9 -mfb=64 -md=32m -ms=on project-m36.7z .stack-work\install\*\bin\project-m36-server.exe .stack-work\install\*\bin\project-m36-websocket-server.exe .stack-work\install\*\bin\tutd.exe .stack-work\install\*\bin\project-m36-server.exe
35# - 7z.exe a -t7z -m0=lzma -mx=9 -mfb=64 -md=32m -ms=on project-m36.7z .stack-work\install\*\bin\project-m36-server.exe .stack-work\install\*\bin\project-m36-websocket-server.exe .stack-work\install\*\bin\tutd.exe .stack-work\install\*\bin\project-m36-server.exe
34
36
35#artifacts:
37#artifacts:
36# - path: project-m36.7z
38# - path: project-m36.7z
37−# name: project-m36.7z
39+# name: project-m36.7z
.github/workflows/ci.yamlnew file+29
@@ -0,0 +1,29 @@
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@v10
11+ with:
12+ skip_adding_nixpkgs_channel: true
13+ - uses: cachix/cachix-action@v6
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+ run: echo ${{secrets.DOCKERHUB_PASSWORD}} | docker login --username ${{secrets.DOCKERHUB_USER}} --password-stdin
22+ - name: docker tag with version
23+ run: docker tag project-m36:latest projectm36/project-m36:$(awk '/^Version:/ {print $2}' project-m36.cabal)
24+ if: ${{ github.ref == 'refs/heads/master' }}
25+ - name: docker tag latest
26+ run: docker tag project-m36:latest projectm36/project-m36:latest
27+ if: ${{ github.ref == 'refs/heads/master' }}
28+ - run: docker push projectm36/project-m36
29+ if: ${{ github.ref == 'refs/heads/master' }}
.travis.yml+10−10
@@ -16,16 +16,16 @@ cache:
16matrix:
16matrix:
17 fast_finish: true
17 fast_finish: true
18 include:
18 include:
19− - env: CACHE_NAME=7.10.3 STACK_YAML=stack.ghc7.10.yaml
19+ - env: CACHE_NAME=8.4.4 STACK_YAML=stack.ghc8.4.yaml
20− compiler: ": #stack 7.10.3"
20+ compiler: ": #stack 8.4.4"
21
21
22− - env: CACHE_NAME=8.0.2 STACK_YAML=stack.yaml
22+ - env: CACHE_NAME=8.6.5 STACK_YAML=stack.ghc8.6.yaml
23− compiler: ": #stack 8.0.2"
23+ compiler: ": #stack 8.6.5"
24
24
25− - env: CACHE_NAME=osx-8.0.2 STACK_YAML=stack.yaml
25+ - env: CACHE_NAME=osx-8.6.5 STACK_YAML=stack.ghc8.6.yaml
26 os: osx
26 os: osx
27− os_image: xcode7.3
27+ osx_image: xcode11
28− compiler: ": #stack 8.0.2"
28+ compiler: ": #stack 8.6.5"
29
29
30before_script:
30before_script:
31 - unset CC
31 - unset CC
@@ -43,13 +43,13 @@ script:
43 stack --no-terminal --jobs=2 --system-ghc test
43 stack --no-terminal --jobs=2 --system-ghc test
44 - |
44 - |
45 #Run HLint
45 #Run HLint
46− if [[ "$(uname)" = "Linux" ]]; then
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
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
48 fi
49 - |
49 - |
50 #Run Haddock
50 #Run Haddock
51− if [[ "$(uname)" = "Linux" ]]; then
51+ if [[ "$(uname)" = "Linux" ]]; then
52− stack --no-install-ghc --system-ghc --no-haddock-deps haddock
52+ stack --no-install-ghc --system-ghc --no-haddock-deps haddock
53 fi
53 fi
54
54
55after_success:
55after_success:
.travis/install-dependencies.sh+1−1
@@ -4,7 +4,7 @@ if [[ "$(uname)" = "Darwin" ]]; then
4else
4else
5 timeout_cmd="timeout"
5 timeout_cmd="timeout"
6fi
6fi
7−$timeout_cmd 15m stack --no-terminal --jobs=2 --install-ghc --system-ghc build --only-dependencies --fast
7+$timeout_cmd 40m stack --no-terminal --jobs=2 --install-ghc --system-ghc build --only-dependencies --fast
8ret=$?
8ret=$?
9case "$ret" in
9case "$ret" in
10 0)
10 0)
.travis/install-stack.sh+2−2
@@ -10,11 +10,11 @@ travis_retry() {
10}
10}
11
11
12fetch_stack_osx() {
12fetch_stack_osx() {
13− curl -skL https://www.stackage.org/stack/osx-x86_64 | tar xz --strip-components=1 --include '*/stack' -C ~/.local/bin;
13+ curl -skL https://get.haskellstack.org/stable/osx-x86_64.tar.gz | tar xz --strip-components=1 --include '*/stack' -C ~/.local/bin;
14}
14}
15
15
16fetch_stack_linux() {
16fetch_stack_linux() {
17− curl -sL https://www.stackage.org/stack/linux-x86_64 | tar xz --wildcards --strip-components=1 -C ~/.local/bin '*/stack';
17+ curl -sL https://get.haskellstack.org/stable/linux-x86_64.tar.gz | tar xz --wildcards --strip-components=1 -C ~/.local/bin '*/stack';
18}
18}
19
19
20# We need stack to generate cabal files with precise bounds, even for cabal
20# We need stack to generate cabal files with precise bounds, even for cabal
Changelog.markdown+34
@@ -1,3 +1,37 @@
1+# 2020-10-05 (v0.8.1)
2+
3+* support GHC 8.10
4+
5+# 2020-05-25 (v0.8)
6+
7+* refactor backend to maximize laziness: [An Architecture for Data Independence](docs/data_independence.markdown)
8+
9+# 2019-09-07 (v0.7)
10+
11+* fix case sensitivity issue with relation variables in tutd
12+* fix multibyte escaping in data frames
13+* fix broken instances of `Atomable [a]`
14+* fix `TypeConstructor` validation of argument count
15+* add help option to executables
16+
17+# 2019-01-08 (v0.6)
18+
19+* fix atom type parsing to support more complex data types
20+* add [data frames](docs/dataframes.markdown) to support server-side sort ordering, limits, and offsets
21+
22+# 2018-10-03 (v0.5.1)
23+
24+* fix atom function type validation
25+* add support for GHC 8.4 (now we support GHC 8.0, 8.2, and 8.4)
26+
27+# 2018-08-10 (v0.5)
28+
29+* fix critical type bug which allowed unresolved types to be used
30+* add full support for GHC 8.2 with stack or cabal (delayed for a long time by dependency version boundaries)
31+* drop support for GHC 7.10
32+* add support for `with (relexpr as name,...)` syntax for use as tutd macros
33+* add `NonEmptyList` list data type
34+
1# 2018-06-04 (v0.4)
35# 2018-06-04 (v0.4)
2
36
3* add contributed feature to allow users to [create arbitrary relations](https://github.com/agentm/project-m36/blob/master/docs/tutd_tutorial.markdown#arbitrary-relation-variables)
37* add contributed feature to allow users to [create arbitrary relations](https://github.com/agentm/project-m36/blob/master/docs/tutd_tutorial.markdown#arbitrary-relation-variables)
README.markdown+14−5
@@ -6,6 +6,7 @@
6[![Hackage dependency status](https://img.shields.io/hackage-deps/v/project-m36.svg)](http://packdeps.haskellers.com/feed?needle=project-m36)
6[![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)
7[![Build status](https://travis-ci.org/agentm/project-m36.svg?branch=master)](https://travis-ci.org/agentm/project-m36)
8[![Windows Build status](https://ci.appveyor.com/api/projects/status/q7jyddd6dy1ibqdo/branch/master?svg=true)](https://ci.appveyor.com/project/agentm/project-m36)
8[![Windows Build status](https://ci.appveyor.com/api/projects/status/q7jyddd6dy1ibqdo/branch/master?svg=true)](https://ci.appveyor.com/project/agentm/project-m36)
9+[![Github Workflow status](https://github.com/agentm/project-m36/workflows/CI/badge.svg)](https://github.com/agentm/project-m36/actions?query=workflow%3ACI)
9
10
10
11
11*Software can always be made faster, but rarely can it be made more correct.*
12*Software can always be made faster, but rarely can it be made more correct.*
@@ -14,6 +15,12 @@
14
15
15Project:M36 implements a relational algebra engine as inspired by the writings of Chris Date.
16Project:M36 implements a relational algebra engine as inspired by the writings of Chris Date.
16
17
18+## Quick Install
19+
20+Project:M36 can be downloaded and run via docker, which supports Windows 10, macOS, and Linux.
21+
22+Run `docker run -it projectm36/project-m36 tutd` to start the TutorialD command line interface.
23+
17## Description
24## Description
18
25
19Unlike 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.
26Unlike 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 +33,6 @@ Project:M36 is written entirely in the [Haskell programming language](https://ww
26
33
27[![asciicast](https://asciinema.org/a/3syu35c8cydm403292a74l1n5.png)](https://asciinema.org/a/3syu35c8cydm403292a74l1n5)
34[![asciicast](https://asciinema.org/a/3syu35c8cydm403292a74l1n5.png)](https://asciinema.org/a/3syu35c8cydm403292a74l1n5)
28
35
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−
33## Use-Cases
36## Use-Cases
34
37
35Project:M36 supports multiple frontends which target different audiences.
38Project:M36 supports multiple frontends which target different audiences.
@@ -52,22 +55,26 @@ Project:M36 supports multiple frontends which target different audiences.
52
55
531. [Installation and Introduction to Project:M36](docs/introduction_to_projectm36.markdown)
561. [Installation and Introduction to Project:M36](docs/introduction_to_projectm36.markdown)
541. [Introduction to the Relational Algebra](docs/introduction_to_the_relational_algebra.markdown)
571. [Introduction to the Relational Algebra](docs/introduction_to_the_relational_algebra.markdown)
58+1. [TutorialD Cheatsheet](docs/tutd_cheatsheet.markdown)
551. [TutorialD via Jupyter Notebook Walkthrough](jupyter/TutorialD%20Notebook%20Walkthrough.ipynb)
591. [TutorialD via Jupyter Notebook Walkthrough](jupyter/TutorialD%20Notebook%20Walkthrough.ipynb)
561. [TutorialD Tutorial](docs/tutd_tutorial.markdown)
601. [TutorialD Tutorial](docs/tutd_tutorial.markdown)
571. [15 Minute Tutorial](docs/15_minute_tutorial.markdown)
611. [15 Minute Tutorial](docs/15_minute_tutorial.markdown)
581. [Developer's Change Log](Changelog.markdown)
621. [Developer's Change Log](Changelog.markdown)
591. [Simple Client API](docs/simple_api.markdown)
631. [Simple Client API](docs/simple_api.markdown)
64+1. [CSV Import/Export](docs/import_export_csv.markdown)
60
65
61### Database Comparisons
66### Database Comparisons
62
67
631. [ACID Database Properties](docs/acid_assessment.markdown)
681. [ACID Database Properties](docs/acid_assessment.markdown)
641. [On NULL (in SQL)](docs/on_null.markdown)
691. [On NULL (in SQL)](docs/on_null.markdown)
651. [Reaching "Out of the Tarpit" with Project:M36](docs/reaching_out_of_the_tarpit.markdown)
701. [Reaching "Out of the Tarpit" with Project:M36](docs/reaching_out_of_the_tarpit.markdown)
71+1. [An Architecture for Data Independence](docs/data_independence.markdown)
66
72
67### Advanced Features
73### Advanced Features
68
74
691. [Transaction Graph Operators](docs/transaction_graph_operators.markdown)
751. [Transaction Graph Operators](docs/transaction_graph_operators.markdown)
701. [ProjectM36.Client Library](docs/projectm36_client_library.markdown)
761. [ProjectM36.Client Library](docs/projectm36_client_library.markdown)
77+1. [Data Frames for Sorting](docs/dataframes.markdown)
711. [Adding New Data Types](docs/new_datatypes.markdown)
781. [Adding New Data Types](docs/new_datatypes.markdown)
721. [Database-Manipulating Functions](docs/database_context_functions.markdown)
791. [Database-Manipulating Functions](docs/database_context_functions.markdown)
731. [Serving Remote ProjectM36 Databases](docs/server_mode.markdown)
801. [Serving Remote ProjectM36 Databases](docs/server_mode.markdown)
@@ -78,15 +85,17 @@ Project:M36 supports multiple frontends which target different audiences.
781. [Isomorphic Schemas](docs/isomorphic_schemas.markdown)
851. [Isomorphic Schemas](docs/isomorphic_schemas.markdown)
791. [Replication](docs/replication.markdown)
861. [Replication](docs/replication.markdown)
801. [Basic Operator Benchmarks](https://rawgit.com/agentm/project-m36/master/docs/basic_benchmarks.html)
871. [Basic Operator Benchmarks](https://rawgit.com/agentm/project-m36/master/docs/basic_benchmarks.html)
88+1. [Merkle Transaction Hashes](docs/merkle_transaction_graph.markdown)
81
89
82### Integrations
90### Integrations
83
91
841. [WebSocket Server](docs/websocket_server.markdown)
921. [WebSocket Server](docs/websocket_server.markdown)
851. [Jupyter Notebook Kernel](docs/jupyter_kernel.markdown)
931. [Jupyter Notebook Kernel](docs/jupyter_kernel.markdown)
94+1. [Persistent Driver](https://github.com/YuMingLiao/persistent-project-m36)
86
95
87## Development
96## Development
88
97
89−Project:M36 is developed in Haskell and compiled with GHC 7.10 or GHC 8.0.2 or later.
98+Project:M36 is developed in Haskell and compiled with GHC 8.2.2 or later.
90
99
91## Related Projects
100## Related Projects
92
101
cabal.project+7−1
@@ -1,3 +1,9 @@
1-- this is needed for GHC8 until distributed-process-extras is updated on Hackage with increased upper bounds
1-- this is needed for GHC8 until distributed-process-extras is updated on Hackage with increased upper bounds
2packages: project-m36.cabal
2packages: 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
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,distributed-process-extras:stm,distributed-process-extras:containers,network-transport-tcp:containers,distributed-process-client-server:stm,distributed-process-client-server:containers,distributed-process-async:stm,distributed-process-async:containers,distributed-process:hashable,distributed-process-extras:hashable,distributed-process-client-server:hashable,distributed-process-async:hashable
4+
5+--necessary for GHC 8.6 support :/
6+source-repository-package
7+ type: git
8+ location: https://github.com/agentm/distributed-process.git
9+ tag: f352e097fbe494ad648b4e09249f865893ae90a3
default.nixnew file+1
@@ -0,0 +1 @@
1+(import ./release.nix { }).project
docker.nixnew file+13
@@ -0,0 +1,13 @@
1+{ pkgs ? import ./pkgs.nix }:
2+let
3+ release = import ./release.nix { inherit pkgs; };
4+ static-project-m36 = pkgs.haskell.lib.justStaticExecutables release.project;
5+in
6+ pkgs.dockerTools.buildImage {
7+ name = "project-m36";
8+ tag = "latest";
9+ contents = [static-project-m36];
10+ #expose default project-m36 and websocket server ports
11+ config = { Env = ["LC_ALL=en_US.UTF-8"];
12+ ExposedPorts = { "6543/tcp" = {}; "8000/tcp" = {}; }; };
13+ }
docs/15_minute_tutorial.markdown+63−62
@@ -5,11 +5,17 @@ Thank you for evaluating Project:M36, a new relational algebra engine written in
5## Prerequisites
5## Prerequisites
6
6
7* any Linux
7* any Linux
8−* GHC 7.10 or later version (Haskell compiler)
8+* GHC 8.2 or later version (Haskell compiler)
9* cabal (package downloader) installed
9* cabal (package downloader) installed
10
10
11## Download and Install
11## Download and Install
12
12
13+Run a pre-built docker image:
14+
15+```docker run -it projectm36/project-m36 tutd```
16+
17+or build it yourself:
18+
13```bash
19```bash
14git clone https://github.com/agentm/project-m36.git
20git clone https://github.com/agentm/project-m36.git
15cabal sandbox init
21cabal sandbox init
@@ -19,7 +25,7 @@ cabal run tutd
19
25
20## Some Basic TutorialD
26## Some Basic TutorialD
21
27
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.
28+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.
23
29
24Note 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.
30Note 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.
25
31
@@ -29,15 +35,7 @@ Note that TutorialD is strongly-typed- no type coercions take place automaticall
29TutorialD (master/main): :importexample date
35TutorialD (master/main): :importexample date
30```
36```
31
37
32−or
33−
34−```
35−TutorialD (master/main): :importtud "scripts/DateExamples.tutd"
36−```
37−
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.
38+```: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.
39−
40−```:importexample date``` loads the date example directly without any file I/O, so it is safe to use with the websocket server.
41
39
42### Execute Relational Expressions
40### Execute Relational Expressions
43
41
@@ -164,7 +162,7 @@ Database context expressions change the state of the database, much like "CREATE
164#### Create a Relation Variable
162#### Create a Relation Variable
165
163
166```
164```
167−TutorialD (master/main): x:=relation{name Text, age Int}{tuple{name "Steve", age 40},tuple{name "Mike", age 31}}
165+TutorialD (master/main): x:=relation{name Text, age Integer}{tuple{name "Steve", age 40},tuple{name "Mike", age 31}}
168TutorialD (master/main): :showexpr x
166TutorialD (master/main): :showexpr x
169┌────────┬──────────┐
167┌────────┬──────────┐
170│age::Int│name::Text│
168│age::Int│name::Text│
@@ -179,23 +177,25 @@ This is similar to SQL's "CREATE TABLE" operator.
179#### Insert Additional Tuples
177#### Insert Additional Tuples
180
178
181```
179```
182−TutorialD (master/main): x:=relation{name Text, age Int}{tuple{name "Steve", age 40},tuple{name "Mike", age 31}}
180+TutorialD (master/main): x:=relation{name Text, age Integer}{tuple{name "Steve", age 40},tuple{name "Mike", age 31}}
183TutorialD (master/main): :showexpr x
181TutorialD (master/main): :showexpr x
184−┌────────┬──────────┐
182+┌────────────┬──────────┐
185−│age::Int│name::Text│
183+│age::Integer│name::Text│
186−├────────┼──────────┤
184+├────────────┼──────────┤
185+│31 │"Mike" │
187−│40 │"Steve" │
186+│40 │"Steve" │
188−│31 │"Mike" │
189−└────────┴──────────┘
187+└────────────┴──────────┘
188+
190TutorialD (master/main): insert x relation{tuple{name "Bob", age 24}}
189TutorialD (master/main): insert x relation{tuple{name "Bob", age 24}}
191TutorialD (master/main): :showexpr x
190TutorialD (master/main): :showexpr x
192−┌────────┬──────────┐
191+┌────────────┬──────────┐
193−│age::Int│name::Text│
192+│age::Integer│name::Text│
194−├────────┼──────────┤
193+├────────────┼──────────┤
194+│31 │"Mike" │
195−│40 │"Steve" │
195+│40 │"Steve" │
196−│24 │"Bob" │
196+│24 │"Bob" │
197−│31 │"Mike" │
198−└────────┴──────────┘
197+└────────────┴──────────┘
198+
199```
199```
200
200
201Note that the relational insertion is identical to "x:=x union relation{...}".
201Note that the relational insertion is identical to "x:=x union relation{...}".
@@ -204,50 +204,51 @@ Note that the relational insertion is identical to "x:=x union relation{...}".
204
204
205```
205```
206TutorialD (master/main): :showexpr s
206TutorialD (master/main): :showexpr s
207−┌──────────┬────────┬───────────┬───────────┐
207+┌──────────┬────────┬───────────┬───────────────┐
208−│city::Text│s#::Text│sname::Text│status::Int│
208+│city::Text│s#::Text│sname::Text│status::Integer│
209−├──────────┼────────┼───────────┼───────────┤
209+├──────────┼────────┼───────────┼───────────────┤
210−│"Paris" │"S2" │"Jones" │10 │
211−│"Paris" │"S3" │"Blake" │30 │
212−│"London" │"S1" │"Smith" │20 │
210+│"London" │"S1" │"Smith" │20 │
213−│"London" │"S4" │"Clark" │20 │
214−│"Athens" │"S5" │"Adams" │30 │
211+│"Athens" │"S5" │"Adams" │30 │
212+│"Paris" │"S3" │"Blake" │30 │
213+│"London" │"S4" │"Clark" │20 │
214+│"Paris" │"S2" │"Jones" │10 │
215−└──────────┴────────┴───────────┴───────────┘
215+└──────────┴────────┴───────────┴───────────────┘
216TutorialD (master/main): update s where city="London" (status:=35)
216TutorialD (master/main): update s where city="London" (status:=35)
217TutorialD (master/main): :showexpr s
217TutorialD (master/main): :showexpr s
218−┌──────────┬────────┬───────────┬───────────┐
218+┌──────────┬────────┬───────────┬───────────────┐
219−│city::Text│s#::Text│sname::Text│status::Int│
219+│city::Text│s#::Text│sname::Text│status::Integer│
220−├──────────┼────────┼───────────┼───────────┤
220+├──────────┼────────┼───────────┼───────────────┤
221+│"Athens" │"S5" │"Adams" │30 │
222+│"London" │"S1" │"Smith" │35 │
221−│"London" │"S4" │"Clark" │35 │
223+│"London" │"S4" │"Clark" │35 │
222−│"London" │"S1" │"Smith" │35 │
224+│"Paris" │"S3" │"Blake" │30 │
223−│"Paris" │"S2" │"Jones" │10 │
225+│"Paris" │"S2" │"Jones" │10 │
224−│"Paris" │"S3" │"Blake" │30 │
225−│"Athens" │"S5" │"Adams" │30 │
226−└──────────┴────────┴───────────┴───────────┘
226+└──────────┴────────┴───────────┴───────────────┘
227+
227```
228```
228#### Deleting Tuples from a Relation Variable
229#### Deleting Tuples from a Relation Variable
229
230
230```
231```
231TutorialD (master/main): :showexpr s
232TutorialD (master/main): :showexpr s
232−┌──────────┬────────┬───────────┬───────────┐
233+┌──────────┬────────┬───────────┬───────────────┐
233−│city::Text│s#::Text│sname::Text│status::Int│
234+│city::Text│s#::Text│sname::Text│status::Integer│
234−├──────────┼────────┼───────────┼───────────┤
235+├──────────┼────────┼───────────┼───────────────┤
235−│"Paris" │"S2" │"Jones" │10 │
236+│"Paris" │"S2" │"Jones" │10 │
236−│"Paris" │"S3" │"Blake" │30 │
237+│"Paris" │"S3" │"Blake" │30 │
237−│"London" │"S1" │"Smith" │20 │
238+│"London" │"S1" │"Smith" │20 │
238−│"London" │"S4" │"Clark" │20 │
239−│"Athens" │"S5" │"Adams" │30 │
239+│"Athens" │"S5" │"Adams" │30 │
240+│"London" │"S4" │"Clark" │20 │
240−└──────────┴────────┴───────────┴───────────┘
241+└──────────┴────────┴───────────┴───────────────┘
241TutorialD (master/main): delete s where sname="Adams"
242TutorialD (master/main): delete s where sname="Adams"
242TutorialD (master/main): :showexpr s
243TutorialD (master/main): :showexpr s
243−┌──────────┬────────┬───────────┬───────────┐
244+┌──────────┬────────┬───────────┬───────────────┐
244−│city::Text│s#::Text│sname::Text│status::Int│
245+│city::Text│s#::Text│sname::Text│status::Integer│
245−├──────────┼────────┼───────────┼───────────┤
246+├──────────┼────────┼───────────┼───────────────┤
246−│"Paris" │"S2" │"Jones" │10 │
247+│"Paris" │"S2" │"Jones" │10 │
248+│"London" │"S4" │"Clark" │20 │
247−│"Paris" │"S3" │"Blake" │30 │
249+│"Paris" │"S3" │"Blake" │30 │
248−│"London" │"S1" │"Smith" │20 │
250+│"London" │"S1" │"Smith" │20 │
249−│"London" │"S4" │"Clark" │20 │
250−└──────────┴────────┴───────────┴───────────┘
251+└──────────┴────────┴───────────┴───────────────┘
251```
252```
252
253
253### Execute Transaction Graph Expressions
254### Execute Transaction Graph Expressions
@@ -270,7 +271,7 @@ TutorialD (master/main): :rollback
270
271
271```
272```
272TutorialD (master/main): :branch experimental
273TutorialD (master/main): :branch experimental
273−TutorialD (experimental): employee:=relation{name Text, salary Int}
274+TutorialD (experimental): employee:=relation{name Text, salary Integer}
274TutorialD (experimental): :commit
275TutorialD (experimental): :commit
275```
276```
276
277
docs/atomfunctions.markdown+1−1
@@ -15,7 +15,7 @@ In this example, we install an atom function to convert between Fahrenheit and C
15We write the function giving it the name "celsiusToFahrenheit" with type ```Int -> Int``` which indicates to the compiler that the function take one ```Int``` argument value and returns one ```Int``` value. Finally, the body of the function is implemented in quotes or triple-quotes. Note that the function makes use of the "[ProjectM36.Base](/src/lib/ProjectM36/Base.hs)" module to handle the Atom type. The function must take a list of Atoms as arguments and return an Atom. The standard GHC Prelude is available in this AtomFunctionBody context.
15We write the function giving it the name "celsiusToFahrenheit" with type ```Int -> Int``` which indicates to the compiler that the function take one ```Int``` argument value and returns one ```Int``` value. Finally, the body of the function is implemented in quotes or triple-quotes. Note that the function makes use of the "[ProjectM36.Base](/src/lib/ProjectM36/Base.hs)" module to handle the Atom type. The function must take a list of Atoms as arguments and return an Atom. The standard GHC Prelude is available in this AtomFunctionBody context.
16
16
17```
17```
18−TutorialD (master/main): addatomfunction "celsiusToFahrenheit" Int -> Either AtomFunctionError Int """(\\((IntAtom c):_) -> pure $ IntAtom ( (c * 9 `div` 5) + 32)) :: [Atom] -> Either AtomFunctionError Atom"""
18+TutorialD (master/main): addatomfunction "celsiusToFahrenheit" Int -> Either AtomFunctionError Int """(\((IntAtom c):_) -> pure $ IntAtom ( (c * 9 `div` 5) + 32)) :: [Atom] -> Either AtomFunctionError Atom"""
19```
19```
20
20
21Using triple-quotes allows quotes to be used inside the string without backslash escaping, which can become tedious. The sum type using ```Either``` allows the function to return an error, if necessary.
21Using triple-quotes allows quotes to be used inside the string without backslash escaping, which can become tedious. The sum type using ```Either``` allows the function to return an error, if necessary.
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/dataframes.markdownnew file+53
@@ -0,0 +1,53 @@
1+# Project:M36 DataFrames
2+
3+Users of typical relational algebra engines have come to expect sorting and limiting of query results despite the fact that relations do not support ordering. To that end, Project:M36 supports converting relations to "data frames" to support sorting on attributes and limiting the maximum tuple count in the result set.
4+
5+The equivalent feature in SQL is invoked by the `ORDER BY`, `LIMIT`, and `OFFSET` clauses.
6+
7+## Usage
8+
9+From within the `tutd` console, converting a relation to be sorted as a data frame is invoked using the `:showdataframe` command.
10+
11+```
12+:showdataframe <relational expression> orderby {<attribute {ascending,descending}>} {offset <num>} {limit <num>}
13+```
14+
15+The default sort order is `ascending`.
16+
17+## Examples
18+
19+```
20+TutorialD (master/main): :showdataframe s orderby {status}
21+┌──┬───────────┬─────────┬────────────┬────────────────┐
22+│DF│city::Text↕│s#::Text↕│sname::Text↕│status::Integer⬆│
23+├──┼───────────┼─────────┼────────────┼────────────────┤
24+│1 │"Paris" │"S2" │"Jones" │10 │
25+│2 │"London" │"S1" │"Smith" │20 │
26+│3 │"London" │"S4" │"Clark" │20 │
27+│4 │"Athens" │"S5" │"Adams" │30 │
28+│5 │"Paris" │"S3" │"Blake" │30 │
29+└──┴───────────┴─────────┴────────────┴────────────────┘
30+TutorialD (master/main): :showdataframe s{status} orderby {status}
31+┌──┬────────────────┐
32+│DF│status::Integer⬆│
33+├──┼────────────────┤
34+│1 │10 │
35+│2 │20 │
36+│3 │30 │
37+└──┴────────────────┘
38+TutorialD (master/main): :showdataframe s{status} orderby {status descending} limit 1
39+┌──┬────────────────┐
40+│DF│status::Integer⬇│
41+├──┼────────────────┤
42+│1 │30 │
43+└──┴────────────────┘
44+TutorialD (master/main): :showdataframe s{status} orderby {status descending} offset 1 limit 3
45+┌──┬────────────────┐
46+│DF│status::Integer⬇│
47+├──┼────────────────┤
48+│1 │20 │
49+│2 │10 │
50+└──┴────────────────┘
51+
52+```
53+The arrow in the attributes indicates the sort order while the DF column indicates the row number based on the sort order. Column ordering can also be arbitrary.
docs/filesystem-persistence.markdown+1−1
@@ -1,4 +1,4 @@
1−# Project-M36 Filesystem Persistence
1+# Project-M36 Filesystem Persistence (Change Proposal)
2
2
3## Introduction
3## Introduction
4
4
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 date
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 date
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+33−12
@@ -15,38 +15,59 @@ The relational algebra is the mathematical model underpinning Project:M36. When
15
15
16## Binary Releases
16## Binary Releases
17
17
18−### Windows
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.
19−Project:M36 now provides binary installations for Windows. Check the (releases page)[https://github.com/agentm/project-m36/releases] for downloads.
20
19
21−### MacOS X
20+### Install Docker:
22
21
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)
24
25
25−### Linux
26+### Run TutorialD from Docker Image
26
27
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+```
28
47
29## Source Installation
48## Source Installation
30
49
31Requirements:
50Requirements:
32
51
52+To build with stack:
53+
33−* [GHC 7.10 or greater](https://www.haskell.org/downloads)
54+* [GHC 8.4.4 or greater](https://www.haskell.org/downloads)
34* [Haskell stack](https://docs.haskellstack.org/en/stable/README/)
55* [Haskell stack](https://docs.haskellstack.org/en/stable/README/)
35−* Linux, MacOS X, or Windows OS
56+* Linux, macOS, or Microsoft Windows
36
57
37Compilation steps:
58Compilation steps:
38
59
39* ```git clone https://github.com/agentm/project-m36```
60* ```git clone https://github.com/agentm/project-m36```
40* ```cd project-m36```
61* ```cd project-m36```
41−* ```stack build```
62+* ```stack --stack-yaml stack.ghc8.6.yaml build```
42
63
43At this point, the TutorialD interactive interpreter can be run using ```stack exec tutd```.
64At this point, the TutorialD interactive interpreter can be run using ```stack exec tutd```.
44
65
45−Alternative building with GHC 8.0.x:
66+Alternative building with GHC 8.4.4 or greater:
46
67
47* ```cabal new-build```
68* ```cabal new-build```
48
69
49−The resultant binaries can be found in ```./dist-newstyle/build/project-m36-0.1/build```.
70+The resultant binaries can be found in ```./dist-newstyle/build/project-m36-<version>/build```.
50
71
51## Accessing Project:M36 Databases
72## Accessing Project:M36 Databases
52
73
@@ -87,7 +108,7 @@ Decreasing a transaction's durability can reduce IO contention at the cost of re
87
108
88### Native Haskell Compatibility
109### Native Haskell Compatibility
89
110
90−Any Haskell data type which implements the ```Atom``` typeclass can be manipulated as a value in the database.
111+Any Haskell data type which implements the ```Atomable``` typeclass can be manipulated as a value in the database.
91
112
92Haskell functions which operate on those values can also be added to the database.
113Haskell functions which operate on those values can also be added to the database.
93
114
docs/introduction_to_the_relational_algebra.markdown+1−1
@@ -378,7 +378,7 @@ Since a value can store any (immutable) type, it can certainly hold a relation.
378
378
379For 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.
379For 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.
380
380
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.
382
382
383Example:
383Example:
384
384
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/new_datatypes.markdown+1−1
@@ -106,6 +106,6 @@ The essential ```Atomable``` typeclass functions are:
106| ```toAtomType :: Proxy a -> AtomType``` | generate a database AtomType for a Haskell datatype |
106| ```toAtomType :: Proxy a -> AtomType``` | generate a database AtomType for a Haskell datatype |
107| ```toAddTypeExpr :: Proxy a -> DatabaseContextExpr``` | generate a ```DatabaseContextExpr``` which can be executed against a database context in order to add the new type |
107| ```toAddTypeExpr :: Proxy a -> DatabaseContextExpr``` | generate a ```DatabaseContextExpr``` which can be executed against a database context in order to add the new type |
108
108
109−In addition, basic Haskell data types like ```Int```, ```Double```, ```Text```, ```Day```, ```Bool```, ```UTCTime```, and l```ByteString``` already have `Atomable` instances ready-to-go. In addition, an ```Atomable``` instance is available for lists: ```Atomable a => [a]```, though one should be very careful not to use this in a common anti-pattern. Typically, it makes more sense to store one-to-many relationships as discrete relation variables; when storing them as lists, one gives up the various query capabilities and optimizations of the relational algebra.
109+In addition, basic Haskell data types like ```Int```, ```Double```, ```Text```, ```Day```, ```Bool```, ```UTCTime```, and ```ByteString``` already have `Atomable` instances ready-to-go. In addition, an ```Atomable``` instance is available for lists: ```Atomable a => [a]```, though one should be very careful not to use this in a common anti-pattern. Typically, it makes more sense to store one-to-many relationships as discrete relation variables; when storing them as lists, one gives up the various query capabilities and optimizations of the relational algebra.
110
110
111To be clear, these data types are not black boxes once stored in the database. These new types can be scanned and manipulated by Haskell scripts which can be created at runtime. For more information, read about [```AtomFunction```s](/docs/atomfunctions.markdown).
111To be clear, these data types are not black boxes once stored in the database. These new types can be scanned and manipulated by Haskell scripts which can be created at runtime. For more information, read about [```AtomFunction```s](/docs/atomfunctions.markdown).
docs/server_mode.markdown+1−1
@@ -8,7 +8,7 @@ While Project:M36 is easy-to-use as an interactive, in-process database manageme
8
8
9To 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.
9To 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.
10
10
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```.
12
12
13## Connecting an Interactive Client
13## Connecting an Interactive Client
14
14
docs/transaction_graph_operators.markdown+8−18
@@ -10,23 +10,11 @@ When a new database is created, a new transaction graph is created for it with o
10
10
11As the user interactively alters the database context such as by adding a new relation variable, the database context is no longer equal to that of the first transactions. This is called "database context divergence" because many of the same components exist in both the updated context and the context of the first transaction.
11As the user interactively alters the database context such as by adding a new relation variable, the database context is no longer equal to that of the first transactions. This is called "database context divergence" because many of the same components exist in both the updated context and the context of the first transaction.
12
12
13−![Initial database starting state](http://g.gravizo.com/g?
13+![Initial database starting state](http://g.gravizo.com/g?%20digraph%20G%20{%20base[label=%22base%20transaction%22,shape=rectangle];%20new[label=%22mutable%20database%20context%22];%20new%20-%3E%20base;%20})
14−digraph G {
15− base[label="base transaction",shape=rectangle];
16− new[label="mutable database context"];
17− new -> base;
18−})
19
14
20Once the user decides that the changes in the updated database context are worth adding to the transaction graph, the user issues a "commit" request. The commit operation converts the current database context into a new transaction which is then added to the graph with the parent transaction set to the same parent transaction as the database context. The user's mutable database context is shifted to be a copy of the context of the newly-committed transaction.
15Once the user decides that the changes in the updated database context are worth adding to the transaction graph, the user issues a "commit" request. The commit operation converts the current database context into a new transaction which is then added to the graph with the parent transaction set to the same parent transaction as the database context. The user's mutable database context is shifted to be a copy of the context of the newly-committed transaction.
21
16
22−![Freshly committed transaction](http://g.gravizo.com/g?
17+![Freshly committed transaction](http://g.gravizo.com/g?%20digraph%20G%20{%20base[label=%22base%20transaction%22,shape=rectangle];%20discon[label=%22mutable%20database%20context%22];%20fresh[label=%22newly%20committed%20transaction%22,shape=rectangle];%20fresh%20-%3E%20base;%20discon%20-%3E%20fresh;%20})
23−digraph G {
24− base[label="base transaction",shape=rectangle];
25− discon[label="mutable database context"];
26− fresh[label="newly committed transaction",shape=rectangle];
27− fresh -> base;
28− discon -> fresh;
29−})
30
18
31It can be handy to attempt to modify the database without altering the data that others may wish to continue to use and modify. If a set of transactions may diverge from another use-case for the data, the user may choose to "branch" the transaction graph. Branching allows the user to assign an arbitrary name to a series of transactions and then potentially merge the set of transactions back to the originating branch. Project:M36 creates a "master" branch when the transaction graph is first created.
19It can be handy to attempt to modify the database without altering the data that others may wish to continue to use and modify. If a set of transactions may diverge from another use-case for the data, the user may choose to "branch" the transaction graph. Branching allows the user to assign an arbitrary name to a series of transactions and then potentially merge the set of transactions back to the originating branch. Project:M36 creates a "master" branch when the transaction graph is first created.
32
20
@@ -55,15 +43,17 @@ TutorialD (master/main): :rollback
55In 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.
43In 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.
56
44
57```
45```
58−TutorialD (master/main): :showgraph
59−┌─────────────┬──────────┬──────────────────────────────────────┬────────────────────────────┬──────────────────────────────┐
46+┌─────────────┬────────────────────────────────────────────┬──────────┬──────────────────────────────────────┬────────────────────────────────────────┬─────────────────────────────────┐
60−│current::Bool│head::Text│id::Text │parents::relation {id::Text}│stamp::DateTime │
47+│current::Bool│hash::ByteString │head::Text│id::Text │parents::relation {id::Text} │stamp::DateTime │
61−├─────────────┼──────────┼──────────────────────────────────────┼────────────────────────────┼──────────────────────────────┤
48+├─────────────┼────────────────────────────────────────────┼──────────┼──────────────────────────────────────┼────────────────────────────────────────┼─────────────────────────────────┤
49+
62
50
63<big result elided>
51<big result elided>
64```
52```
65The "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.
53The "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.
66
54
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+
67The "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.
57The "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.
68
58
69The "id" attribute is the UUID needed in order to navigate the graph.
59The "id" attribute is the UUID needed in order to navigate the graph.
docs/tupleable.markdown+19
@@ -23,6 +23,25 @@ instance Tupleable Person
23
23
24Now, ```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.
24Now, ```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.
25
25
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+
26## Usage
45## Usage
27
46
28The ```Tupleable``` module includes the following functions:
47The ```Tupleable``` module includes the following functions:
docs/tutd_cheatsheet.markdownnew file+97
@@ -0,0 +1,97 @@
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 date`|Imports a precooked schema from Chris Date's books resulting in relvars `s`, `sp`, and `p`|
51+|`newrelvar:=relation{tuple{age 3}}`|Assign a new relation variable named `newrelvar`|
52+|`undefine s`|Remove a relation variable|
53+|`insert s relation{tuple{city "Boston",s# "S10",sname "Gonzalez",status 10}}`| Append to an existing relation variable with another relational expression|
54+|`update s where status=20 (sname:="Mr. Twenty")`|Replace one or more values in matching tuples with a new value|
55+|`delete sp where s#="S4"`|Remove tuples matching the criteria|
56+|`key s_key_constraint {s#} s`|Add a constraint named `s_key_constraint` on relation variable `s` ensuring that `s#` is unique|
57+|`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`|
58+|`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|
59+|`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|
60+|`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|
61+|`data Hair = Bald | Brown | Blond | OtherColor Text`|Create a new algebraic data type for use with values inside tuples|
62+|`undata Hair`|Delete the `Hair` custom type|
63+
64+
65+## Transaction Graph Expressions
66+
67+Transaction graph expressions alter the state of the transaction graph by append new states.
68+
69+|Transaction Graph Expression |Description |
70+|------------------------------------------------------|---------------------------------------|
71+|`:commit`|Save the current database context to a new transaction and add it to the transaction graph|
72+|`:rollback`|Return the database context to the state before any alterations were made|
73+|`:branch experimental`|Create a new branch from the existing branch and switch the current context to be able to commit to the new branch|
74+|`:jumphead master`|Discard any changes in the current context and jump to the head of a different branch|
75+|`:jump 11b601c9-f46b-42b0-a2ce-cf18ced31b7f`|Jump to the specific transaction by UUID- useful for introspecting past states|
76+|`:showgraph`|Display a representation of the transaction graph|
77+|`: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|
78+
79+## Data Frame Expressions
80+
81+In contrast to relational expressions, data frame expressions generate ordered tuples.
82+
83+|Data Frame Expression |Description |
84+|------------------------------------------------------|---------------------------------------|
85+|`:showdataframe s orderby {status}`|Display a data frame result for the relational expression `s` and sort the tuples by `status`|
86+|`: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|
87+
88+## Trans-Graph Relational Expressions
89+
90+Trans-graph relational expressions allow queries spanning multiple transactions.
91+
92+|Trans-Graph Relational Expressions |Description |
93+|------------------------------------------------------|---------------------------------------|
94+|`:showtransgraphexpr s@master join sp@master`|Display a result for joining `s` and `sp` on the branch `master`|
95+|`: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|
96+|`:showtransgraphexpr s@master~^2`|Display a result for `s` two parents previous to the parent of the current `master`'s head|
97+
docs/tutd_tutorial.markdown+17−17
@@ -14,6 +14,22 @@ TutorialD (master/main):
14
14
15"master" refers to the name of the branch to which the current transaction will be potentially committing.
15"master" refers to the name of the branch to which the current transaction will be potentially committing.
16
16
17+### Date's Sample Relations
18+
19+The examples in this tutorial can be executed after loading Chris Date's sample relations using:
20+
21+```
22+:importexample date
23+```
24+
25+Each section assumes a fresh instance of the Date examples. The relation variables created in the script are:
26+
27+|Relation Variable Name|Description|
28+|----------------------|-----------|
29+|s|suppliers|
30+|p|parts|
31+|sp|contains mapping of which suppliers supply which parts|
32+
17### Types
33### Types
18
34
19TutorialD is strongly-typed. The basic built-in types are:
35TutorialD is strongly-typed. The basic built-in types are:
@@ -37,7 +53,7 @@ The ```interval``` function last two arguments are boolean values indicating whe
37Project:M36 will complain loudly if the expected types do not match. Automatic type coercion does not exist.
53Project:M36 will complain loudly if the expected types do not match. Automatic type coercion does not exist.
38
54
39```
55```
40−TutorialD (master/main): :showexpr S:{more:=add(10,@sname)}
56+TutorialD (master/main): :showexpr s:{more:=add(10,@sname)}
41ERR: AtomFunctionTypeError "add" 2 IntAtomType StringAtomType
57ERR: AtomFunctionTypeError "add" 2 IntAtomType StringAtomType
42```
58```
43
59
@@ -68,22 +84,6 @@ Chris Date refers to these relations as "TABLE_DUM" and "TABLE_DEE" but such arb
68products{}
84products{}
69```
85```
70
86
71−### Date's Sample Relations
72−
73−The examples in this tutorial can be executed after loading Chris Date's sample relations using:
74−
75−```
76−:importexample date
77−```
78−
79−Each section assumes a fresh instance of the Date examples. The relation variables created in the script are:
80−
81−|Relation Variable Name|Description|
82−|----------------------|-----------|
83−|s|suppliers|
84−|p|parts|
85−|sp|contains mapping of which suppliers supply which parts|
86−
87### Relational Expressions
87### Relational Expressions
88
88
89A relational expression combines relational operators to create a new relation. ```tutd``` can display the result of executing a relational expression with ":showexpr".
89A relational expression combines relational operators to create a new relation. ```tutd``` can display the result of executing a relational expression with ":showexpr".
docs/websocket_server.markdown+2−2
@@ -16,8 +16,8 @@ except that the websocket server is now listening for websocket connections on p
16
16
17## Client Connection
17## Client Connection
18
18
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.
20
20
21## Sample Application
21## Sample Application
22
22
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+52
@@ -0,0 +1,52 @@
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.Binary (Binary)
7+import Data.Text (Text)
8+import GHC.Generics (Generic)
9+
10+newtype BlogId = BlogId { getBlogId :: Int }
11+ deriving stock (Eq, Ord, Show, Generic)
12+ deriving newtype (Num)
13+
14+instance NFData BlogId
15+instance Binary 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+
27+data Comment = Comment
28+ { commentAuthorName :: Text
29+ , commentComment :: Text
30+ , commentFor :: BlogId
31+ }
32+ deriving stock (Show, Generic)
33+ deriving (Tupleable)
34+ via Codec (Field (DropPrefix "comment" >>> CamelCase)) Comment
35+
36+main :: IO ()
37+main = do
38+ let exampleBlog = Blog
39+ { blogId = 0
40+ , blogTitle = "Cat Pics"
41+ , blogAuthorName = "Alice"
42+ }
43+ exampleComment = Comment
44+ { commentAuthorName = "Bob"
45+ , commentComment = "great"
46+ , commentFor = 0
47+ }
48+ print exampleBlog
49+ print (toTuple exampleBlog)
50+ putStrLn ""
51+ print exampleComment
52+ print (toTuple exampleComment)
examples/blog.hs+8−6
@@ -1,5 +1,5 @@
1-- a simple example of a blog schema
1-- a simple example of a blog schema
2−{-# LANGUAGE DeriveAnyClass, DeriveGeneric, OverloadedStrings #-}
2+{-# LANGUAGE DeriveAnyClass, DeriveGeneric, OverloadedStrings, CPP #-}
3
3
4import ProjectM36.Client
4import ProjectM36.Client
5import ProjectM36.Base
5import ProjectM36.Base
@@ -17,7 +17,9 @@ import Data.Time.Clock
17import Data.Time.Calendar
17import Data.Time.Calendar
18import Control.DeepSeq
18import Control.DeepSeq
19import Data.Proxy
19import Data.Proxy
20+#if __GLASGOW_HASKELL__ < 804
20import Data.Monoid
21import Data.Monoid
22+#endif
21import Data.List
23import Data.List
22import Control.Monad (when, forM_)
24import Control.Monad (when, forM_)
23
25
@@ -33,7 +35,7 @@ import Data.Time.Format
33data Blog = Blog {
35data Blog = Blog {
34 title :: T.Text,
36 title :: T.Text,
35 entry :: T.Text,
37 entry :: T.Text,
36− stamp :: UTCTime,
38+ tstamp :: UTCTime,
37 category :: Category --note that this type is an algebraic data type
39 category :: Category --note that this type is an algebraic data type
38 }
40 }
39 deriving (Generic, Show) --derive Generic so that Tupleable can use default instances
41 deriving (Generic, Show) --derive Generic so that Tupleable can use default instances
@@ -103,11 +105,11 @@ insertSampleData :: SessionId -> Connection -> IO ()
103insertSampleData sessionId conn = do
105insertSampleData sessionId conn = do
104 let blogs = [Blog { title = "Haskell Lenses",
106 let blogs = [Blog { title = "Haskell Lenses",
105 entry = "I wear Haskell rose-colored lenses.",
107 entry = "I wear Haskell rose-colored lenses.",
106− stamp = UTCTime (fromGregorian 2017 5 8) (secondsToDiffTime 1000),
108+ tstamp = UTCTime (fromGregorian 2017 5 8) (secondsToDiffTime 1000),
107 category = Food },
109 category = Food },
108 Blog { title = "Haskell Monad Analogy",
110 Blog { title = "Haskell Monad Analogy",
109 entry = "Monads are like burritos going through intestines.",
111 entry = "Monads are like burritos going through intestines.",
110− stamp = UTCTime (fromGregorian 2017 6 10) (secondsToDiffTime 2000),
112+ tstamp = UTCTime (fromGregorian 2017 6 10) (secondsToDiffTime 2000),
111 category = Cats }
113 category = Cats }
112 ]
114 ]
113 comments = [Comment { blogTitle = "Haskell Lenses",
115 comments = [Comment { blogTitle = "Haskell Lenses",
@@ -136,7 +138,7 @@ listBlogs sessionId conn = do
136 Left err -> render500 (toHtml (show err))
138 Left err -> render500 (toHtml (show err))
137 Right blogRel -> do
139 Right blogRel -> do
138 blogs <- liftIO (toList blogRel) >>= mapM (handleWebError . fromTuple) :: ActionM [Blog]
140 blogs <- liftIO (toList blogRel) >>= mapM (handleWebError . fromTuple) :: ActionM [Blog]
139− let sortedBlogs = sortBy (\b1 b2 -> stamp b1 `compare` stamp b2) blogs
141+ let sortedBlogs = sortBy (\b1 b2 -> tstamp b1 `compare` tstamp b2) blogs
140 html . renderHtml $ do
142 html . renderHtml $ do
141 h1 "Blog Posts"
143 h1 "Blog Posts"
142 forM_ sortedBlogs $ \blog -> a ! href (toValue $ "/blog/" <> title blog) $ h2 (toHtml (title blog))
144 forM_ sortedBlogs $ \blog -> a ! href (toValue $ "/blog/" <> title blog) $ h2 (toHtml (title blog))
@@ -182,7 +184,7 @@ showBlogEntry sessionId conn = do
182 render $ do
184 render $ do
183 --show blog details
185 --show blog details
184 h1 (toHtml (title blog))
186 h1 (toHtml (title blog))
185− p (toHtml ("Posted at " <> formatStamp (stamp blog) <> " under " <> show (category blog)))
187+ p (toHtml ("Posted at " <> formatStamp (tstamp blog) <> " under " <> show (category blog)))
186 p (toHtml (entry blog))
188 p (toHtml (entry blog))
187 hr
189 hr
188 h3 "Comments"
190 h3 "Comments"
examples/hair.hs+5−3
@@ -31,11 +31,13 @@ main = do
31
31
32 --create a relation with the new Hair AtomType
32 --create a relation with the new Hair AtomType
33 let blond = NakedAtomExpr (toAtom Blond)
33 let blond = NakedAtomExpr (toAtom Blond)
34− eCheck $ executeDatabaseContextExpr sessionId conn (Assign "people" (MakeRelationFromExprs Nothing [
34+ eCheck $ executeDatabaseContextExpr sessionId conn
35+ (Assign "people"
36+ (MakeRelationFromExprs Nothing $ TupleExprs () [
35− TupleExpr (M.fromList [("hair", blond), ("name", NakedAtomExpr (TextAtom "Colin"))])]))
37+ TupleExpr (M.fromList [("hair", blond), ("name", NakedAtomExpr (TextAtom "Colin"))])]))
36
38
37 let restrictionPredicate = AttributeEqualityPredicate "hair" blond
39 let restrictionPredicate = AttributeEqualityPredicate "hair" blond
38 peopleRel <- eCheck $ executeRelationalExpr sessionId conn (Restrict restrictionPredicate (RelationVariable "people" ()))
40 peopleRel <- eCheck $ executeRelationalExpr sessionId conn (Restrict restrictionPredicate (RelationVariable "people" ()))
39
41
40 TIO.putStrLn (showRelation peopleRel)
42 TIO.putStrLn (showRelation peopleRel)
41−
43+
pkgs.nixnew file+7
@@ -0,0 +1,7 @@
1+let
2+nixpkgs = builtins.fetchGit {
3+ url = "https://github.com/NixOS/nixpkgs";
4+ rev = "f58482658eabf7d695f45904ecbc5f49c19fef98";
5+};
6+in
7+import nixpkgs { config.allowBroken = true; }
project-m36.cabal+105−117
@@ -1,5 +1,5 @@
1Name: project-m36
1Name: project-m36
2−Version: 0.4
2+Version: 0.8.1
3License: PublicDomain
3License: PublicDomain
4Build-Type: Simple
4Build-Type: Simple
5Homepage: https://github.com/agentm/project-m36
5Homepage: https://github.com/agentm/project-m36
@@ -22,70 +22,27 @@ Flag profiler
22 Default: False
22 Default: False
23 Manual: True
23 Manual: True
24
24
25+--flag to allow stack to use its older, pinned packages
26+Flag stack
27+ Description: build with stack and stackage
28+ Manual: True
29+ Default: False
30+
31+Flag haskell-scripting
32+ Description: enables Haskell scripting which links against GHC as a library
33+ Manual: True
34+ Default: True
35+
25Library
36Library
26− Build-Depends: base>=4.8 && < 6.0
37+ 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, 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, text-manipulate >= 0.2.0.1 && < 0.3
27− ,ghc >= 7.8 && < 8.3
38+ if flag(haskell-scripting)
28− ,ghc-paths
39+ Build-Depends: ghc >= 8.2 && < 8.11
29− ,mtl
40+ CPP-Options: -DPM36_HASKELL_SCRIPTING
30− ,containers
41+ if impl(ghc>= 8) && flag(haskell-scripting)
31− ,unordered-containers
42+ build-depends:
32− ,hashable
43+ ghc-boot, ghci
33− ,haskeline
44+ if impl(ghc>= 8.6)
34− ,directory
45+ Build-Depends: deferred-folds
35− ,MonadRandom
36− ,random-shuffle
37− --critical uuid bug in lesser versions https://www.reddit.com/r/haskell/comments/4myot5/psa_make_sure_to_use_uuid_1312/
38− ,uuid >= 1.3.12
39− ,cassava >= 0.4.5.1 && < 0.6
40− ,text
41− ,bytestring
42− ,deepseq
43− ,deepseq-generics
44− ,vector
45− ,parallel
46− ,monad-parallel
47− ,exceptions
48− ,transformers
49− ,gnuplot
50− ,binary
51− ,filepath
52− ,zlib
53− ,directory
54− ,vector-binary-instances
55− ,temporary
56− ,stm
57− ,time
58− ,hashable-time
59− ,old-locale
60− ,rset
61− --used for CSV parsing
62− ,attoparsec
63− ,either
64− ,base64-bytestring
65− ,data-interval
66− ,extended-reals
67− ,network-transport
68− -- aeson 1.1 and above includes instances for UUID types
69− ,aeson >= 1.1
70− ,path-pieces
71− ,conduit
72− ,resourcet
73− ,http-api-data
74− -- used for arbitrary tuples
75− ,QuickCheck
76−--needed for remote access
77− ,distributed-process-client-server >= 0.2.3
78− ,distributed-process >= 0.6.6
79− ,distributed-process-extras >= 0.3.2
80− ,distributed-process-async >= 0.2.4
81− ,network-transport-tcp
82− ,network-transport
83− ,list-t
84− ,stm-containers >= 0.2.15
85− ,optparse-applicative
86− ,Glob
87−--used for hashing the transaction graph file to check for differences
88− ,cryptohash-sha256
89 Exposed-Modules: ProjectM36.Error,
46 Exposed-Modules: ProjectM36.Error,
90 ProjectM36.Transaction,
47 ProjectM36.Transaction,
91 ProjectM36.TransactionGraph,
48 ProjectM36.TransactionGraph,
@@ -94,6 +51,7 @@ Library
94 ProjectM36.TransactionGraph.Merge,
51 ProjectM36.TransactionGraph.Merge,
95 ProjectM36.TransGraphRelationalExpression,
52 ProjectM36.TransGraphRelationalExpression,
96 ProjectM36.Base,
53 ProjectM36.Base,
54+ ProjectM36.DataFrame,
97 ProjectM36.Attribute,
55 ProjectM36.Attribute,
98 ProjectM36.AttributeNames,
56 ProjectM36.AttributeNames,
99 ProjectM36.Tuple,
57 ProjectM36.Tuple,
@@ -121,6 +79,7 @@ Library
121 ProjectM36.Relation.Parse.CSV,
79 ProjectM36.Relation.Parse.CSV,
122 ProjectM36.IsomorphicSchema,
80 ProjectM36.IsomorphicSchema,
123 ProjectM36.InclusionDependency,
81 ProjectM36.InclusionDependency,
82+ ProjectM36.MerkleHash,
124 ProjectM36.Client,
83 ProjectM36.Client,
125 ProjectM36.Client.Simple,
84 ProjectM36.Client.Simple,
126 ProjectM36.Persist,
85 ProjectM36.Persist,
@@ -130,13 +89,16 @@ Library
130 ProjectM36.AtomFunctions.Primitive,
89 ProjectM36.AtomFunctions.Primitive,
131 ProjectM36.Atomable,
90 ProjectM36.Atomable,
132 ProjectM36.Tupleable,
91 ProjectM36.Tupleable,
92+ ProjectM36.Tupleable.Deriving,
133 ProjectM36.DataConstructorDef,
93 ProjectM36.DataConstructorDef,
134 ProjectM36.DataTypes.Basic,
94 ProjectM36.DataTypes.Basic,
95+ ProjectM36.DataTypes.Sorting,
135 ProjectM36.DataTypes.Day,
96 ProjectM36.DataTypes.Day,
136 ProjectM36.DataTypes.DateTime,
97 ProjectM36.DataTypes.DateTime,
137 ProjectM36.DataTypes.Either,
98 ProjectM36.DataTypes.Either,
138 ProjectM36.DataTypes.Maybe,
99 ProjectM36.DataTypes.Maybe,
139 ProjectM36.DataTypes.List,
100 ProjectM36.DataTypes.List,
101+ ProjectM36.DataTypes.NonEmptyList,
140 ProjectM36.DataTypes.Primitive,
102 ProjectM36.DataTypes.Primitive,
141 ProjectM36.DataTypes.Interval,
103 ProjectM36.DataTypes.Interval,
142 ProjectM36.DataTypes.ByteString,
104 ProjectM36.DataTypes.ByteString,
@@ -155,25 +117,31 @@ Library
155 ProjectM36.TypeConstructorDef,
117 ProjectM36.TypeConstructorDef,
156 ProjectM36.FileLock,
118 ProjectM36.FileLock,
157 ProjectM36.FSType,
119 ProjectM36.FSType,
158− ProjectM36.Arbitrary
120+ ProjectM36.Arbitrary,
121+ ProjectM36.GraphRefRelationalExpr,
122+ ProjectM36.NormalizeExpr,
123+ ProjectM36.TransactionInfo,
124+ ProjectM36.WithNameExpr
159 GHC-Options: -Wall -rdynamic
125 GHC-Options: -Wall -rdynamic
160 if os(windows)
126 if os(windows)
161− Build-Depends: Win32 >= 2.3
127+ Build-Depends: Win32 >= 2.5.4.1
162 Other-Modules: ProjectM36.Win32Handle
128 Other-Modules: ProjectM36.Win32Handle
163 else
129 else
130+ --219- too many exported symbols under Windows and GHC 8.4
131+ GHC-Options: -rdynamic
164 C-sources: cbits/DirectoryFsync.c, cbits/darwin_statfs.c
132 C-sources: cbits/DirectoryFsync.c, cbits/darwin_statfs.c
165 Build-Depends: unix
133 Build-Depends: unix
166− CC-Options: -fPIC
134+ CC-Options: -fPIC
167 Hs-Source-Dirs: ./src/lib
135 Hs-Source-Dirs: ./src/lib
168 Default-Language: Haskell2010
136 Default-Language: Haskell2010
169 Default-Extensions: OverloadedStrings, CPP
137 Default-Extensions: OverloadedStrings, CPP
170− if impl(ghc>= 8)
138+ if !flag(stack)
171− build-depends:
139+ Build-Depends: deferred-folds
172− ghc-boot, ghci
173
140
174Executable tutd
141Executable tutd
142+ if flag(haskell-scripting)
143+ Build-Depends: ghc >= 8.2 && < 8.11
175 Build-Depends: base >=4.8 && <5.0,
144 Build-Depends: base >=4.8 && <5.0,
176− ghc >= 7.8 && < 8.3,
177 ghc-paths,
145 ghc-paths,
178 project-m36,
146 project-m36,
179 containers,
147 containers,
@@ -201,14 +169,15 @@ Executable tutd
201 directory,
169 directory,
202 filepath,
170 filepath,
203 temporary,
171 temporary,
204− megaparsec >= 5.2.0 && < 5.4,
172+ megaparsec >= 5.2.0 && < 9,
205 haskeline,
173 haskeline,
206 random, MonadRandom,
174 random, MonadRandom,
207 base64-bytestring,
175 base64-bytestring,
208 optparse-applicative,
176 optparse-applicative,
209 attoparsec,
177 attoparsec,
210− stm-containers,
178+ stm-containers >= 1.0.0,
211− list-t
179+ list-t,
180+ parser-combinators
212 Other-Modules: TutorialD.Interpreter,
181 Other-Modules: TutorialD.Interpreter,
213 TutorialD.Interpreter.Base,
182 TutorialD.Interpreter.Base,
214 TutorialD.Interpreter.DatabaseContextExpr,
183 TutorialD.Interpreter.DatabaseContextExpr,
@@ -229,14 +198,15 @@ Executable tutd
229 TutorialD.Interpreter.SchemaOperator
198 TutorialD.Interpreter.SchemaOperator
230 main-is: TutorialD/tutd.hs
199 main-is: TutorialD/tutd.hs
231 CC-Options: -fPIC
200 CC-Options: -fPIC
232− GHC-Options: -Wall -rdynamic
201+ GHC-Options: -Wall -threaded
233 Hs-Source-Dirs: ./src/bin
202 Hs-Source-Dirs: ./src/bin
234 Default-Language: Haskell2010
203 Default-Language: Haskell2010
235 Default-Extensions: OverloadedStrings
204 Default-Extensions: OverloadedStrings
236
205
237Executable project-m36-server
206Executable project-m36-server
207+ if flag(haskell-scripting)
208+ Build-Depends: ghc >= 8.2 && < 8.11
238 Build-Depends: base,
209 Build-Depends: base,
239− ghc >= 7.8 && < 8.3,
240 ghc-paths,
210 ghc-paths,
241 project-m36,
211 project-m36,
242 binary,
212 binary,
@@ -275,7 +245,7 @@ Executable project-m36-server
275Executable bigrel
245Executable bigrel
276 Default-Language: Haskell2010
246 Default-Language: Haskell2010
277 Default-Extensions: OverloadedStrings
247 Default-Extensions: OverloadedStrings
278− 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
248+ 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, parser-combinators
279 Other-Modules: TutorialD.Interpreter.Base,
249 Other-Modules: TutorialD.Interpreter.Base,
280 TutorialD.Interpreter.DatabaseContextExpr,
250 TutorialD.Interpreter.DatabaseContextExpr,
281 TutorialD.Interpreter.RelationalExpr,
251 TutorialD.Interpreter.RelationalExpr,
@@ -302,9 +272,9 @@ Test-Suite test-tutoriald
302 Default-Extensions: OverloadedStrings
272 Default-Extensions: OverloadedStrings
303 type: exitcode-stdio-1.0
273 type: exitcode-stdio-1.0
304 main-is: test/TutorialD/Interpreter.hs
274 main-is: test/TutorialD/Interpreter.hs
305− 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
275+ 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, parser-combinators
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
276 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
307− GHC-Options: -Wall
277+ GHC-Options: -Wall -threaded
308 Hs-Source-Dirs: ./src/bin, ., test
278 Hs-Source-Dirs: ./src/bin, ., test
309
279
310Test-Suite test-tutoriald-atomfunctionscript
280Test-Suite test-tutoriald-atomfunctionscript
@@ -313,8 +283,8 @@ Test-Suite test-tutoriald-atomfunctionscript
313 type: exitcode-stdio-1.0
283 type: exitcode-stdio-1.0
314 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
284 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
315 main-is: test/TutorialD/Interpreter/AtomFunctionScript.hs
285 main-is: test/TutorialD/Interpreter/AtomFunctionScript.hs
316− Build-Depends: base, HUnit, project-m36, uuid, containers, megaparsec, text, vector, directory, bytestring, mtl, haskeline, random, MonadRandom, semigroups, time
286+ Build-Depends: base, HUnit, project-m36, uuid, containers, megaparsec, text, vector, directory, bytestring, mtl, haskeline, random, MonadRandom, semigroups, time, parser-combinators
317− GHC-Options: -Wall
287+ GHC-Options: -Wall -threaded
318 Hs-Source-Dirs: ./src/bin, ./test, .
288 Hs-Source-Dirs: ./src/bin, ./test, .
319
289
320Test-Suite test-tutoriald-databasecontextfunctionscript
290Test-Suite test-tutoriald-databasecontextfunctionscript
@@ -323,8 +293,8 @@ Test-Suite test-tutoriald-databasecontextfunctionscript
323 type: exitcode-stdio-1.0
293 type: exitcode-stdio-1.0
324 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
294 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
325 main-is: test/TutorialD/Interpreter/DatabaseContextFunctionScript.hs
295 main-is: test/TutorialD/Interpreter/DatabaseContextFunctionScript.hs
326− Build-Depends: base, HUnit, project-m36, uuid, containers, megaparsec, text, vector, directory, bytestring, mtl, haskeline, random, MonadRandom, semigroups, time
296+ Build-Depends: base, HUnit, project-m36, uuid, containers, megaparsec, text, vector, directory, bytestring, mtl, haskeline, random, MonadRandom, semigroups, time, parser-combinators
327− GHC-Options: -Wall
297+ GHC-Options: -Wall -threaded
328 Hs-Source-Dirs: ./src/bin, ./test, .
298 Hs-Source-Dirs: ./src/bin, ./test, .
329
299
330Test-Suite test-relation
300Test-Suite test-relation
@@ -333,7 +303,7 @@ Test-Suite test-relation
333 type: exitcode-stdio-1.0
303 type: exitcode-stdio-1.0
334 main-is: test/Relation/Basic.hs
304 main-is: test/Relation/Basic.hs
335 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
305 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
336− GHC-Options: -Wall
306+ GHC-Options: -Wall -threaded
337
307
338Test-Suite test-static-optimizer
308Test-Suite test-static-optimizer
339 Default-Language: Haskell2010
309 Default-Language: Haskell2010
@@ -341,17 +311,17 @@ Test-Suite test-static-optimizer
341 type: exitcode-stdio-1.0
311 type: exitcode-stdio-1.0
342 main-is: test/Relation/StaticOptimizer.hs
312 main-is: test/Relation/StaticOptimizer.hs
343 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
313 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
344− GHC-Options: -Wall
314+ GHC-Options: -Wall -threaded
345
315
346Test-Suite test-transactiongraph-persist
316Test-Suite test-transactiongraph-persist
347 Default-Language: Haskell2010
317 Default-Language: Haskell2010
348 Default-Extensions: OverloadedStrings
318 Default-Extensions: OverloadedStrings
349 type: exitcode-stdio-1.0
319 type: exitcode-stdio-1.0
350 main-is: test/TransactionGraph/Persist.hs
320 main-is: test/TransactionGraph/Persist.hs
351− 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+ 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, parser-combinators
352 Other-Modules: TutorialD.Interpreter.Base, TutorialD.Interpreter.RelationalExpr, TutorialD.Interpreter.Types, TutorialD.Interpreter.DatabaseContextExpr, TutorialD.Interpreter.Import.BasicExamples
322 Other-Modules: TutorialD.Interpreter.Base, TutorialD.Interpreter.RelationalExpr, TutorialD.Interpreter.Types, TutorialD.Interpreter.DatabaseContextExpr, TutorialD.Interpreter.Import.BasicExamples
353 Hs-Source-Dirs: ., ./src/bin
323 Hs-Source-Dirs: ., ./src/bin
354− GHC-Options: -Wall
324+ GHC-Options: -Wall -threaded
355
325
356Test-Suite test-relation-import-csv
326Test-Suite test-relation-import-csv
357 Default-Language: Haskell2010
327 Default-Language: Haskell2010
@@ -359,16 +329,16 @@ Test-Suite test-relation-import-csv
359 type: exitcode-stdio-1.0
329 type: exitcode-stdio-1.0
360 main-is: test/Relation/Import/CSV.hs
330 main-is: test/Relation/Import/CSV.hs
361 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 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
362− GHC-Options: -Wall
332+ GHC-Options: -Wall -threaded
363
333
364Test-Suite test-tutoriald-import-tutoriald
334Test-Suite test-tutoriald-import-tutoriald
365 Default-Language: Haskell2010
335 Default-Language: Haskell2010
366 Default-Extensions: OverloadedStrings
336 Default-Extensions: OverloadedStrings
367 type: exitcode-stdio-1.0
337 type: exitcode-stdio-1.0
368 main-is: test/TutorialD/Interpreter/Import/TutorialD.hs
338 main-is: test/TutorialD/Interpreter/Import/TutorialD.hs
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, stm-containers, project-m36, random, MonadRandom, semigroups
339+ 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, parser-combinators
370 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
340 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
371− GHC-Options: -Wall
341+ GHC-Options: -Wall -threaded
372 Hs-Source-Dirs: ., ./src/bin
342 Hs-Source-Dirs: ., ./src/bin
373
343
374Test-Suite test-relation-export-csv
344Test-Suite test-relation-export-csv
@@ -377,7 +347,7 @@ Test-Suite test-relation-export-csv
377 type: exitcode-stdio-1.0
347 type: exitcode-stdio-1.0
378 main-is: test/Relation/Export/CSV.hs
348 main-is: test/Relation/Export/CSV.hs
379 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
349 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
380− GHC-Options: -Wall
350+ GHC-Options: -Wall -threaded
381
351
382Test-Suite test-transactiongraph-merge
352Test-Suite test-transactiongraph-merge
383 Default-Language: Haskell2010
353 Default-Language: Haskell2010
@@ -385,7 +355,7 @@ Test-Suite test-transactiongraph-merge
385 type: exitcode-stdio-1.0
355 type: exitcode-stdio-1.0
386 main-is: test/TransactionGraph/Merge.hs
356 main-is: test/TransactionGraph/Merge.hs
387 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
357 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
388− GHC-Options: -Wall
358+ GHC-Options: -Wall -threaded
389
359
390benchmark bench
360benchmark bench
391 Default-Language: Haskell2010
361 Default-Language: Haskell2010
@@ -393,7 +363,7 @@ benchmark bench
393 type: exitcode-stdio-1.0
363 type: exitcode-stdio-1.0
394 main-is: benchmark/Relation.hs
364 main-is: benchmark/Relation.hs
395 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
365 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
396− GHC-Options: -Wall -rtsopts
366+ GHC-Options: -Wall -rtsopts -threaded
397 Hs-Source-Dirs: ./src/bin
367 Hs-Source-Dirs: ./src/bin
398
368
399Test-Suite test-server
369Test-Suite test-server
@@ -403,28 +373,28 @@ Test-Suite test-server
403 main-is: test/Server/Main.hs
373 main-is: test/Server/Main.hs
404 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
374 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
405 HS-Source-Dirs: ., ./src/bin
375 HS-Source-Dirs: ., ./src/bin
406− GHC-Options: -Wall
376+ GHC-Options: -Wall -threaded
407
377
408Executable Example-SimpleClient
378Executable Example-SimpleClient
409 Default-Language: Haskell2010
379 Default-Language: Haskell2010
410 Default-Extensions: OverloadedStrings
380 Default-Extensions: OverloadedStrings
411 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
381 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
412 Main-Is: examples/SimpleClient.hs
382 Main-Is: examples/SimpleClient.hs
413− GHC-Options: -Wall
383+ GHC-Options: -Wall -threaded
414
384
415Executable Example-OutOfTheTarpit
385Executable Example-OutOfTheTarpit
416 Default-Language: Haskell2010
386 Default-Language: Haskell2010
417 Default-Extensions: OverloadedStrings
387 Default-Extensions: OverloadedStrings
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, aeson, path-pieces, either, conduit, http-api-data, template-haskell, ghc, ghc-paths, project-m36
388 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
419 Main-Is: examples/out_of_the_tarpit.hs
389 Main-Is: examples/out_of_the_tarpit.hs
420− GHC-Options: -Wall
390+ GHC-Options: -Wall -threaded
421
391
422Executable Example-Blog
392Executable Example-Blog
423 Default-Language: Haskell2010
393 Default-Language: Haskell2010
424 Default-Extensions: OverloadedStrings
394 Default-Extensions: OverloadedStrings
425 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
395 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
426 Main-Is: examples/blog.hs
396 Main-Is: examples/blog.hs
427− GHC-Options: -Wall
397+ GHC-Options: -Wall -threaded
428
398
429
399
430Executable Example-Hair
400Executable Example-Hair
@@ -432,31 +402,41 @@ Executable Example-Hair
432 Default-Extensions: OverloadedStrings
402 Default-Extensions: OverloadedStrings
433 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
403 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
434 Main-Is: examples/hair.hs
404 Main-Is: examples/hair.hs
435− GHC-Options: -Wall
405+ GHC-Options: -Wall -threaded
436
406
437Executable Example-CustomTupleable
407Executable Example-CustomTupleable
438 Default-Language: Haskell2010
408 Default-Language: Haskell2010
439 Default-Extensions: OverloadedStrings
409 Default-Extensions: OverloadedStrings
440 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
410 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
441 Main-Is: examples/CustomTupleable.hs
411 Main-Is: examples/CustomTupleable.hs
442− GHC-Options: -Wall
412+ GHC-Options: -Wall -threaded
443−
413+
414+Executable Example-DerivingCustomTupleable
415+ if impl(ghc>=8.6)
416+ Buildable: True
417+ else
418+ Buildable: False
419+ Default-Language: Haskell2010
420+ Build-Depends: base, text, deepseq, binary, project-m36
421+ Main-Is: examples/DerivingCustomTupleable.hs
422+ GHC-Options: -Wall -threaded
423+
444Test-Suite test-scripts
424Test-Suite test-scripts
445 Default-Language: Haskell2010
425 Default-Language: Haskell2010
446 Default-Extensions: OverloadedStrings
426 Default-Extensions: OverloadedStrings
447 type: exitcode-stdio-1.0
427 type: exitcode-stdio-1.0
448 main-is: test/scripts.hs
428 main-is: test/scripts.hs
449− 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
429+ 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, parser-combinators
450 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
430 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
451− GHC-Options: -Wall
431+ GHC-Options: -Wall -threaded
452 Hs-Source-Dirs: ., ./src/bin
432 Hs-Source-Dirs: ., ./src/bin
453
433
454Executable project-m36-websocket-server
434Executable project-m36-websocket-server
455 Default-Language: Haskell2010
435 Default-Language: Haskell2010
456− 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, network-transport-tcp, semigroups, attoparsec, parser-combinators
457 Main-Is: ProjectM36/Server/WebSocket/websocket-server.hs
437 Main-Is: ProjectM36/Server/WebSocket/websocket-server.hs
458 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
459− GHC-Options: -Wall
439+ GHC-Options: -Wall -threaded
460 Hs-Source-Dirs: ./src/bin
440 Hs-Source-Dirs: ./src/bin
461 Default-Extensions: OverloadedStrings
441 Default-Extensions: OverloadedStrings
462
442
@@ -464,10 +444,10 @@ Test-Suite test-websocket-server
464 Default-Language: Haskell2010
444 Default-Language: Haskell2010
465 type: exitcode-stdio-1.0
445 type: exitcode-stdio-1.0
466 main-is: test/Server/WebSocket.hs
446 main-is: test/Server/WebSocket.hs
467− 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
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, network-transport-tcp, semigroups, parser-combinators
468 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
448 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
469 Default-Extensions: OverloadedStrings
449 Default-Extensions: OverloadedStrings
470− GHC-Options: -Wall
450+ GHC-Options: -Wall -threaded
471 Hs-Source-Dirs: ./src/bin, .
451 Hs-Source-Dirs: ./src/bin, .
472
452
473Test-Suite test-isomorphic-schemas
453Test-Suite test-isomorphic-schemas
@@ -476,17 +456,17 @@ Test-Suite test-isomorphic-schemas
476 main-is: test/IsomorphicSchema.hs
456 main-is: test/IsomorphicSchema.hs
477 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
457 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
478 Default-Extensions: OverloadedStrings
458 Default-Extensions: OverloadedStrings
479− GHC-Options: -Wall
459+ GHC-Options: -Wall -threaded
480 Hs-Source-Dirs: ./src/bin, .
460 Hs-Source-Dirs: ./src/bin, .
481
461
482Test-Suite test-atomable
462Test-Suite test-atomable
483 Default-Language: Haskell2010
463 Default-Language: Haskell2010
484 type: exitcode-stdio-1.0
464 type: exitcode-stdio-1.0
485 main-is: test/Relation/Atomable.hs
465 main-is: test/Relation/Atomable.hs
486− 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
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, parser-combinators
487 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
467 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
488 Default-Extensions: OverloadedStrings
468 Default-Extensions: OverloadedStrings
489− GHC-Options: -Wall
469+ GHC-Options: -Wall -threaded
490 Hs-Source-Dirs: ./src/bin, ., test/
470 Hs-Source-Dirs: ./src/bin, ., test/
491
471
492Test-Suite test-multiprocess-access
472Test-Suite test-multiprocess-access
@@ -495,17 +475,17 @@ Test-Suite test-multiprocess-access
495 main-is: test/MultiProcessDatabaseAccess.hs
475 main-is: test/MultiProcessDatabaseAccess.hs
496 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
476 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
497 Default-Extensions: OverloadedStrings
477 Default-Extensions: OverloadedStrings
498− GHC-Options: -Wall
478+ GHC-Options: -Wall -threaded
499 Hs-Source-Dirs: ./src/bin, ., test/
479 Hs-Source-Dirs: ./src/bin, ., test/
500
480
501Test-Suite test-transactiongraph-automerge
481Test-Suite test-transactiongraph-automerge
502 Default-Language: Haskell2010
482 Default-Language: Haskell2010
503 type: exitcode-stdio-1.0
483 type: exitcode-stdio-1.0
504 main-is: test/TransactionGraph/Automerge.hs
484 main-is: test/TransactionGraph/Automerge.hs
505− 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
485+ 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, parser-combinators
506 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
486 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
507 Default-Extensions: OverloadedStrings
487 Default-Extensions: OverloadedStrings
508− GHC-Options: -Wall
488+ GHC-Options: -Wall -threaded
509 Hs-Source-Dirs: ./src/bin, ., test/
489 Hs-Source-Dirs: ./src/bin, ., test/
510
490
511Test-Suite test-tupleable
491Test-Suite test-tupleable
@@ -514,7 +494,7 @@ Test-Suite test-tupleable
514 main-is: test/Relation/Tupleable.hs
494 main-is: test/Relation/Tupleable.hs
515 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
495 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
516 Default-Extensions: OverloadedStrings
496 Default-Extensions: OverloadedStrings
517− GHC-Options: -Wall
497+ GHC-Options: -Wall -threaded
518 Hs-Source-Dirs: ./src/bin, ., test/
498 Hs-Source-Dirs: ./src/bin, ., test/
519
499
520Test-Suite test-client-simple
500Test-Suite test-client-simple
@@ -523,14 +503,14 @@ Test-Suite test-client-simple
523 type: exitcode-stdio-1.0
503 type: exitcode-stdio-1.0
524 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
504 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
525 Default-Extensions: OverloadedStrings
505 Default-Extensions: OverloadedStrings
526− GHC-Options: -Wall
506+ GHC-Options: -Wall -threaded
527 Hs-Source-Dirs: ./src/bin, ., test/
507 Hs-Source-Dirs: ./src/bin, ., test/
528
508
529-- test for file handle leaks
509-- test for file handle leaks
530Executable handles
510Executable handles
531 Default-Language: Haskell2010
511 Default-Language: Haskell2010
532 Default-Extensions: OverloadedStrings
512 Default-Extensions: OverloadedStrings
533− 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
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, optparse-applicative, stm-containers, list-t, ghc, ghc-paths, transformers, project-m36, random, MonadRandom, semigroups, parser-combinators
534 main-is: benchmark/Handles.hs
514 main-is: benchmark/Handles.hs
535 Other-Modules: TutorialD.Interpreter,
515 Other-Modules: TutorialD.Interpreter,
536 TutorialD.Interpreter.Base,
516 TutorialD.Interpreter.Base,
@@ -553,5 +533,13 @@ Executable handles
553 HS-Source-Dirs: ./src/bin
533 HS-Source-Dirs: ./src/bin
554 if flag(profiler)
534 if flag(profiler)
555 GHC-Prof-Options: -fprof-auto -rtsopts -threaded -Wall
535 GHC-Prof-Options: -fprof-auto -rtsopts -threaded -Wall
556−
536+
557−
537+Test-Suite test-dataframe
538+ Default-Language: Haskell2010
539+ Main-Is: test/DataFrame.hs
540+ type: exitcode-stdio-1.0
541+ 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
542+ 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, parser-combinators
543+ Default-Extensions: OverloadedStrings
544+ GHC-Options: -Wall -threaded
545+ Hs-Source-Dirs: ./src/bin, ., test/
release.nixnew file+113
@@ -0,0 +1,113 @@
1+{ compiler ? "ghc865"
2+, pkgs ? import ./pkgs.nix
3+}:
4+
5+let
6+ inherit (pkgs.lib.trivial) flip pipe;
7+ inherit (pkgs.haskell.lib) appendPatch appendConfigureFlags;
8+ doJailbreak = pkgs.haskell.lib.doJailbreak;
9+ dontHaddock = pkgs.haskell.lib.dontHaddock;
10+ dontCheck = pkgs.haskell.lib.dontCheck;
11+ #distributed-process packages are no longer maintained- until we replace it entirely, add some hacks to build on newer GHC and packages
12+ distProcessPkg = pkg : dontHaddock (doJailbreak (dontCheck pkg));
13+ callHackageDirectWithOptions = {pkg,ver, sha256, options}:
14+ let pkgver = "${pkg}-${ver}";
15+ in
16+ haskellPackages.callCabal2nixWithOptions pkg (pkgs.fetchzip {
17+ url = "mirror://hackage/${pkgver}/${pkgver}.tar.gz";
18+ inherit sha256;
19+ }) options;
20+
21+ haskellPackages = pkgs.haskell.packages.${compiler}.override {
22+ overrides = self: super: {
23+ distributed-process-extras =
24+ distProcessPkg (self.callHackageDirect {
25+ pkg = "distributed-process-extras";
26+ ver = "0.3.5";
27+ sha256 = "13clq3alymcvknp7q8gz0i1hzx8im855lzmyrfffl8gglnlbi2w9";
28+ }{});
29+
30+ distributed-process-client-server =
31+ distProcessPkg (self.callHackageDirect {
32+ pkg = "distributed-process-client-server";
33+ ver = "0.2.5.1";
34+ sha256 = "0gkd8awapq7vy14vpnzawnwb67jvvcjaqg7imm0bp1wb6rw6x5x4";
35+ }{});
36+
37+ distributed-process-async =
38+ distProcessPkg (callHackageDirectWithOptions {
39+ pkg = "distributed-process-async";
40+ ver = "0.2.6";
41+ sha256 = "15wyfq115r6xjaz1h00sjh1v0fv498kkxr3xx6w84d8wdp2gxbn1";
42+ options = "--no-check";
43+ }{});
44+
45+ distributed-process =
46+ dontHaddock (self.callCabal2nix "distributed-process" (pkgs.fetchFromGitHub {
47+ owner = "agentm";
48+ repo = "distributed-process";
49+ rev = "f352e097fbe494ad648b4e09249f865893ae90a3";
50+ sha256 = "0xa2v77c9idmi89bky2wq1fykrn8grpk4rk7gcd5bkicxvdbcrym";}){});
51+
52+ distributed-static =
53+ self.callHackageDirect {
54+ pkg = "distributed-static";
55+ ver = "0.3.9";
56+ sha256 = "0hibpzqwklnq335m7fwgk1bghz0lgxnd7ym10pbvxlcf7ly3nr6v";
57+}{};
58+ rank1dynamic =
59+ distProcessPkg (self.callHackageDirect {
60+ pkg = "rank1dynamic";
61+ ver = "0.4.0";
62+ sha256 = "1x6p9z53s7xwp93jp4n1lq6m5xspcn6w62p461v8vqnp9600328b";
63+}{});
64+ stm-hamt =
65+ self.callHackageDirect {
66+ pkg = "stm-hamt";
67+ ver = "1.2.0.3";
68+ sha256 = "1i8j7q8nhx3l7gydrjlsyhkvllr6bppgrjf0hp38zpm7p6xcv2bb";
69+ }{};
70+
71+ stm-containers =
72+ self.callHackageDirect {
73+ pkg = "stm-containers";
74+ ver = "1.1.0.4";
75+ sha256 = "0h9z6lawdm44minx9spvdb7sp645l36ri5cnxvhrcxwzr64s7qb5";
76+ }{};
77+
78+ network-transport-tcp =
79+ dontCheck (self.callHackageDirect {
80+ pkg = "network-transport-tcp";
81+ ver = "0.7.0";
82+ sha256 = "0kfzrcynf34xsxx4rccg4qfy7jvinwqd8baian8ifqad9lfcapsb";
83+ }{});
84+
85+ data-interval =
86+ self.callHackageDirect {
87+ pkg = "data-interval";
88+ ver = "2.0.1";
89+ sha256 = "085j4yjr8wimxampxqdrg47p577whwg2mjxgfdl44yfck52fb6an";
90+ }{};
91+
92+ project-m36 = dontCheck (self.callCabal2nixWithOptions "project-m36" ./. "-f-haskell-scripting" { });
93+
94+ };
95+ };
96+
97+ project = haskellPackages.project-m36;
98+in
99+{
100+ project = project;
101+
102+ shell = haskellPackages.shellFor {
103+ packages = p: with p; [
104+ project
105+ ];
106+ buildInputs = [
107+ haskellPackages.ghcid
108+ haskellPackages.hlint
109+ pkgs.docker
110+ ];
111+ withHoogle = true;
112+ };
113+}
runghcid.sh+1−1
@@ -1,2 +1,2 @@
1#!/bin/sh
1#!/bin/sh
2−./.cabal-sandbox/bin/ghcid --command="cabal repl $1"
2+~/.cabal/bin/ghcid --command="cabal new-repl $1"
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
3import Data.Aeson
3import Data.Aeson
4import ProjectM36.Server.RemoteCallTypes.Json ()
4import ProjectM36.Server.RemoteCallTypes.Json ()
5import ProjectM36.Client
5import ProjectM36.Client
6+import ProjectM36.TransactionGraph
6import Control.Exception (IOException)
7import Control.Exception (IOException)
7
8
8instance ToJSON EvaluatedNotification
9instance ToJSON EvaluatedNotification
@@ -11,4 +12,6 @@ instance FromJSON EvaluatedNotification
11instance ToJSON ConnectionError
12instance ToJSON ConnectionError
12
13
13instance ToJSON IOException where
14instance 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+30−1
@@ -1,14 +1,16 @@
1--create a bunch of orphan instances for use with the websocket server
1--create a bunch of orphan instances for use with the websocket server
2−{-# LANGUAGE FlexibleInstances, TypeSynonymInstances #-}
2+{-# LANGUAGE FlexibleInstances #-}
3{-# OPTIONS_GHC -fno-warn-orphans #-}
3{-# OPTIONS_GHC -fno-warn-orphans #-}
4module ProjectM36.Server.RemoteCallTypes.Json where
4module ProjectM36.Server.RemoteCallTypes.Json where
5import ProjectM36.AtomFunctionError
5import ProjectM36.AtomFunctionError
6import ProjectM36.Base
6import ProjectM36.Base
7+import ProjectM36.DataFrame
7import ProjectM36.DatabaseContextFunctionError
8import ProjectM36.DatabaseContextFunctionError
8import ProjectM36.DataTypes.Primitive
9import ProjectM36.DataTypes.Primitive
9import ProjectM36.Error
10import ProjectM36.Error
10import ProjectM36.IsomorphicSchema
11import ProjectM36.IsomorphicSchema
11import ProjectM36.Server.RemoteCallTypes
12import ProjectM36.Server.RemoteCallTypes
13+import ProjectM36.MerkleHash
12
14
13import Data.Aeson
15import Data.Aeson
14import Data.ByteString.Base64 as B64
16import Data.ByteString.Base64 as B64
@@ -21,6 +23,9 @@ instance FromJSON RelationalExpr
21instance ToJSON TupleExpr
23instance ToJSON TupleExpr
22instance FromJSON TupleExpr
24instance FromJSON TupleExpr
23
25
26+instance ToJSON TupleExprs
27+instance FromJSON TupleExprs
28+
24instance ToJSON RestrictionPredicateExpr
29instance ToJSON RestrictionPredicateExpr
25instance FromJSON RestrictionPredicateExpr
30instance FromJSON RestrictionPredicateExpr
26
31
@@ -63,6 +68,18 @@ instance FromJSON SchemaExpr
63instance ToJSON SchemaIsomorph
68instance ToJSON SchemaIsomorph
64instance FromJSON SchemaIsomorph
69instance FromJSON SchemaIsomorph
65
70
71+instance ToJSON DataFrame
72+instance FromJSON DataFrame
73+
74+instance ToJSON DataFrameTuple
75+instance FromJSON DataFrameTuple
76+
77+instance ToJSON AttributeOrder
78+instance FromJSON AttributeOrder
79+
80+instance ToJSON Order
81+instance FromJSON Order
82+
66instance ToJSON Atom where
83instance ToJSON Atom where
67 toJSON atom@(IntegerAtom i) = object [ "type" .= atomTypeForAtom atom,
84 toJSON atom@(IntegerAtom i) = object [ "type" .= atomTypeForAtom atom,
68 "val" .= i ]
85 "val" .= i ]
@@ -116,6 +133,15 @@ instance FromJSON Notification
116instance ToJSON ScriptCompilationError
133instance ToJSON ScriptCompilationError
117instance FromJSON ScriptCompilationError
134instance FromJSON ScriptCompilationError
118
135
136+instance ToJSON MerkleHash where
137+ toJSON h = object [ "merklehash" .= decodeUtf8 (B64.encode (_unMerkleHash h))]
138+instance FromJSON MerkleHash where
139+ parseJSON = withObject "merklehash" $ \o -> do
140+ b64bs <- encodeUtf8 <$> o .: "merklehash"
141+ case B64.decode b64bs of
142+ Left err -> fail ("Failed to parse merkle hash: " ++ err)
143+ Right bs -> pure (MerkleHash bs)
144+
119instance ToJSON RelationalError
145instance ToJSON RelationalError
120instance FromJSON RelationalError
146instance FromJSON RelationalError
121
147
@@ -136,3 +162,6 @@ instance FromJSON PersistenceError
136
162
137instance ToJSON AtomFunctionError
163instance ToJSON AtomFunctionError
138instance FromJSON AtomFunctionError
164instance FromJSON AtomFunctionError
165+
166+instance ToJSON WithNameExpr
167+instance FromJSON WithNameExpr
src/bin/ProjectM36/Server/WebSocket.hs+38−20
@@ -1,4 +1,4 @@
1−{-# LANGUAGE LambdaCase #-}
1+{-# LANGUAGE LambdaCase, CPP #-}
2module ProjectM36.Server.WebSocket where
2module ProjectM36.Server.WebSocket where
3-- 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
3-- 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
4-- 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
4-- 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
@@ -10,11 +10,12 @@ import qualified Data.Text as T
10import qualified Network.WebSockets as WS
10import qualified Network.WebSockets as WS
11import ProjectM36.Server.RemoteCallTypes.Json ()
11import ProjectM36.Server.RemoteCallTypes.Json ()
12import ProjectM36.Client.Json ()
12import ProjectM36.Client.Json ()
13+import ProjectM36.DataFrame
13import ProjectM36.Relation.Show.Term
14import ProjectM36.Relation.Show.Term
14import ProjectM36.Relation.Show.HTML
15import ProjectM36.Relation.Show.HTML
15import Data.Aeson
16import Data.Aeson
16import TutorialD.Interpreter
17import TutorialD.Interpreter
17−import TutorialD.Interpreter.Base
18+import TutorialD.Interpreter.Base (TutorialDOperatorResult(..))
18import ProjectM36.Client
19import ProjectM36.Client
19import Control.Exception
20import Control.Exception
20import Data.Attoparsec.Text
21import Data.Attoparsec.Text
@@ -22,8 +23,12 @@ import Control.Applicative
22import Text.Megaparsec.Error
23import Text.Megaparsec.Error
23import Data.Functor
24import Data.Functor
24
25
26+#if MIN_VERSION_megaparsec(7,0,0)
27+import Data.List.NonEmpty as NE
28+#endif
29+
25websocketProxyServer :: Port -> Hostname -> WS.ServerApp
30websocketProxyServer :: Port -> Hostname -> WS.ServerApp
26−websocketProxyServer port host pending = do
31+websocketProxyServer port host pending = do
27 conn <- WS.acceptRequest pending
32 conn <- WS.acceptRequest pending
28 let unexpectedMsg = WS.sendTextData conn ("messagenotexpected" :: T.Text)
33 let unexpectedMsg = WS.sendTextData conn ("messagenotexpected" :: T.Text)
29 --phase 1- accept database name for connection
34 --phase 1- accept database name for connection
@@ -32,10 +37,10 @@ websocketProxyServer port host pending = do
32 if not (connectdbmsg `T.isPrefixOf` dbmsg) then unexpectedMsg >> WS.sendClose conn ("" :: T.Text)
37 if not (connectdbmsg `T.isPrefixOf` dbmsg) then unexpectedMsg >> WS.sendClose conn ("" :: T.Text)
33 else do
38 else do
34 let dbname = T.unpack $ T.drop (T.length connectdbmsg) dbmsg
39 let dbname = T.unpack $ T.drop (T.length connectdbmsg) dbmsg
35− bracket (createConnection conn dbname port host)
40+ bracket (createConnection conn dbname port host)
36 (\case
41 (\case
37 Right dbconn -> close dbconn
42 Right dbconn -> close dbconn
38− Left _ -> pure ()) $ \case
43+ Left _ -> pure ()) $ \case
39 Left err -> sendError conn err
44 Left err -> sendError conn err
40 Right dbconn -> do
45 Right dbconn -> do
41 eSessionId <- createSessionAtHead dbconn "master"
46 eSessionId <- createSessionAtHead dbconn "master"
@@ -46,31 +51,38 @@ websocketProxyServer port host pending = do
46 _ <- forever $ do
51 _ <- forever $ do
47 pInfo <- promptInfo sessionId dbconn
52 pInfo <- promptInfo sessionId dbconn
48 --figure out why sending three times during startup is necessary
53 --figure out why sending three times during startup is necessary
49− sendPromptInfo pInfo conn
54+ sendPromptInfo pInfo conn
50 sendPromptInfo pInfo conn
55 sendPromptInfo pInfo conn
51 msg <- WS.receiveData conn :: IO T.Text
56 msg <- WS.receiveData conn :: IO T.Text
52 case parseOnly parseExecuteMessage msg of
57 case parseOnly parseExecuteMessage msg of
53 Left _ -> unexpectedMsg
58 Left _ -> unexpectedMsg
54 Right (presentation, tutdString) ->
59 Right (presentation, tutdString) ->
55 case parseTutorialD tutdString of
60 case parseTutorialD tutdString of
61+ Left err -> handleOpResult conn dbconn presentation
62+#if MIN_VERSION_megaparsec(7,0,0)
63+ (DisplayErrorResult
64+ ("parse error: " `T.append` T.pack
65+ (parseErrorPretty . NE.head . bundleErrors $ err)))
66+#else
56− Left err -> handleOpResult conn dbconn presentation (DisplayErrorResult ("parse error: " `T.append` T.pack (parseErrorPretty err)))
67+ (DisplayErrorResult ("parse error: " `T.append` T.pack (parseErrorPretty err)))
68+#endif
57 Right parsed -> do
69 Right parsed -> do
58− let timeoutFilter exc = if exc == RequestTimeoutException
70+ let timeoutFilter exc = if exc == RequestTimeoutException
59− then Just exc
71+ then Just exc
60 else Nothing
72 else Nothing
61 responseHandler = do
73 responseHandler = do
62 result <- evalTutorialD sessionId dbconn SafeEvaluation parsed
74 result <- evalTutorialD sessionId dbconn SafeEvaluation parsed
63 pInfo' <- promptInfo sessionId dbconn
75 pInfo' <- promptInfo sessionId dbconn
64− sendPromptInfo pInfo' conn
76+ sendPromptInfo pInfo' conn
65 handleOpResult conn dbconn presentation result
77 handleOpResult conn dbconn presentation result
66 catchJust timeoutFilter responseHandler (\_ -> handleOpResult conn dbconn presentation (DisplayErrorResult "Request Timed Out."))
78 catchJust timeoutFilter responseHandler (\_ -> handleOpResult conn dbconn presentation (DisplayErrorResult "Request Timed Out."))
67 pure ()
79 pure ()
68−
80+
69−notificationCallback :: WS.Connection -> NotificationCallback
81+notificationCallback :: WS.Connection -> NotificationCallback
70notificationCallback conn notifName evaldNotif = WS.sendTextData conn (encode (object ["notificationname" .= notifName,
82notificationCallback conn notifName evaldNotif = WS.sendTextData conn (encode (object ["notificationname" .= notifName,
71 "evaldnotification" .= evaldNotif
83 "evaldnotification" .= evaldNotif
72 ]))
84 ]))
73−
85+
74--this creates a new database for each connection- perhaps not what we want (?)
86--this creates a new database for each connection- perhaps not what we want (?)
75createConnection :: WS.Connection -> DatabaseName -> Port -> Hostname -> IO (Either ConnectionError Connection)
87createConnection :: WS.Connection -> DatabaseName -> Port -> Hostname -> IO (Either ConnectionError Connection)
76createConnection wsconn dbname port host = connectProjectM36 (RemoteProcessConnectionInfo dbname (createNodeId host port) (notificationCallback wsconn))
88createConnection wsconn dbname port host = connectProjectM36 (RemoteProcessConnectionInfo dbname (createNodeId host port) (notificationCallback wsconn))
@@ -94,34 +106,40 @@ handleOpResult conn _ presentation (DisplayRelationResult rel) = do
94 texto = ["text" .= showRelation rel | textPresentation presentation]
106 texto = ["text" .= showRelation rel | textPresentation presentation]
95 htmlo = ["html" .= relationAsHTML rel | htmlPresentation presentation]
107 htmlo = ["html" .= relationAsHTML rel | htmlPresentation presentation]
96 WS.sendTextData conn (encode (object ["displayrelation" .= object (jsono ++ texto ++ htmlo)]))
108 WS.sendTextData conn (encode (object ["displayrelation" .= object (jsono ++ texto ++ htmlo)]))
109+handleOpResult conn _ presentation (DisplayDataFrameResult df) = do
110+ let jsono = ["json" .= df | jsonPresentation presentation]
111+ texto = ["text" .= showDataFrame df | textPresentation presentation]
112+ htmlo = ["html" .= dataFrameAsHTML df | htmlPresentation presentation]
113+ WS.sendTextData conn (encode (object ["displaydataframe" .= object (jsono ++ texto ++ htmlo)]))
114+
97-- get current schema and head name for client
115-- get current schema and head name for client
98promptInfo :: SessionId -> Connection -> IO (HeadName, SchemaName)
116promptInfo :: SessionId -> Connection -> IO (HeadName, SchemaName)
99promptInfo sessionId conn = do
117promptInfo sessionId conn = do
100− eHeadName <- headName sessionId conn
118+ eHeadName <- headName sessionId conn
101 eSchemaName <- currentSchemaName sessionId conn
119 eSchemaName <- currentSchemaName sessionId conn
102 pure (either (const "<unknown>") id eHeadName, either (const "<no schema>") id eSchemaName)
120 pure (either (const "<unknown>") id eHeadName, either (const "<no schema>") id eSchemaName)
103−
121+
104sendPromptInfo :: (HeadName, SchemaName) -> WS.Connection -> IO ()
122sendPromptInfo :: (HeadName, SchemaName) -> WS.Connection -> IO ()
105sendPromptInfo (hName, sName) conn = WS.sendTextData conn (encode (object ["promptInfo" .= object ["headname" .= hName, "schemaname" .= sName]]))
123sendPromptInfo (hName, sName) conn = WS.sendTextData conn (encode (object ["promptInfo" .= object ["headname" .= hName, "schemaname" .= sName]]))
106
124
107--a returning relation can be returned as JSON, Text (for consoles), or HTML
125--a returning relation can be returned as JSON, Text (for consoles), or HTML
108data Presentation = Presentation {
126data Presentation = Presentation {
109− jsonPresentation :: Bool,
127+ jsonPresentation :: Bool,
110 textPresentation :: Bool,
128 textPresentation :: Bool,
111 htmlPresentation :: Bool }
129 htmlPresentation :: Bool }
112−
130+
113data PresentationFlag = JSONFlag | TextFlag | HTMLFlag
131data PresentationFlag = JSONFlag | TextFlag | HTMLFlag
114−
132+
115parseExecuteMessage :: Parser (Presentation, T.Text)
133parseExecuteMessage :: Parser (Presentation, T.Text)
116parseExecuteMessage = do
134parseExecuteMessage = do
117 _ <- string "executetutd/"
135 _ <- string "executetutd/"
118 flags <- sepBy ((string "json" $> JSONFlag) <|>
136 flags <- sepBy ((string "json" $> JSONFlag) <|>
119 (string "text" $> TextFlag) <|>
137 (string "text" $> TextFlag) <|>
120 (string "html" $> HTMLFlag)) "+"
138 (string "html" $> HTMLFlag)) "+"
121− let presentation = foldr (\flag acc -> case flag of
139+ let presentation = foldr (\flag acc -> case flag of
122 JSONFlag -> acc {jsonPresentation = True}
140 JSONFlag -> acc {jsonPresentation = True}
123 TextFlag -> acc {textPresentation = True}
141 TextFlag -> acc {textPresentation = True}
124 HTMLFlag -> acc {htmlPresentation = True}) (Presentation False False False) flags
142 HTMLFlag -> acc {htmlPresentation = True}) (Presentation False False False) flags
125 _ <- char ':'
143 _ <- char ':'
126 tutd <- T.pack <$> manyTill anyChar endOfInput
144 tutd <- T.pack <$> manyTill anyChar endOfInput
127− pure (presentation, tutd)
145+ pure (presentation, tutd)
src/bin/ProjectM36/Server/WebSocket/project-m36.js+45−6
@@ -55,9 +55,10 @@ var ProjectM36Connection = function (protocol, host, port, path, dbname, openCal
55* @param {Object} acknowledgementresult - The status update containing an acknowledgement that the query was executed or null.
55* @param {Object} acknowledgementresult - The status update containing an acknowledgement that the query was executed or null.
56* @param {Object} errorResult - The status update containing the error information or null.
56* @param {Object} errorResult - The status update containing the error information or null.
57*/
57*/
58−var ProjectM36Status = function (relationResult, acknowledgementResult, errorResult)
58+var ProjectM36Status = function (relationResult, dataFrameResult, acknowledgementResult, errorResult)
59{
59{
60 this.relation = relationResult;
60 this.relation = relationResult;
61+ this.dataframe = dataFrameResult;
61 this.acknowledgement = acknowledgementResult;
62 this.acknowledgement = acknowledgementResult;
62 this.error = errorResult;
63 this.error = errorResult;
63}
64}
@@ -75,6 +76,7 @@ ProjectM36Connection.prototype.readyState = function()
75ProjectM36Connection.prototype.handleResponse = function(message)
76ProjectM36Connection.prototype.handleResponse = function(message)
76{
77{
77 var relation = message["displayrelation"];
78 var relation = message["displayrelation"];
79+ var dataframe = message["displaydataframe"];
78 var acknowledged = message["acknowledged"];
80 var acknowledged = message["acknowledged"];
79 var error = message["displayerror"];
81 var error = message["displayerror"];
80 var prompt = message["promptInfo"];
82 var prompt = message["promptInfo"];
@@ -82,12 +84,17 @@ ProjectM36Connection.prototype.handleResponse = function(message)
82
84
83 if(relation)
85 if(relation)
84 {
86 {
85− this.statuscallback(new ProjectM36Status(relation['json'], null, null));
87+ this.statuscallback(new ProjectM36Status(relation['json'], null, null, null));
88+ }
89+
90+ if(dataframe)
91+ {
92+ this.statuscallback(new ProjectM36Status(null, dataframe['json'], null, null));
86 }
93 }
87
94
88 if(acknowledged)
95 if(acknowledged)
89 {
96 {
90− this.statuscallback(new ProjectM36Status(null, true, null));
97+ this.statuscallback(new ProjectM36Status(null, null, true, null));
91 }
98 }
92
99
93 if(error)
100 if(error)
@@ -96,7 +103,7 @@ ProjectM36Connection.prototype.handleResponse = function(message)
96 {
103 {
97 error=error.tag; // for error objects
104 error=error.tag; // for error objects
98 }
105 }
99− this.statuscallback(new ProjectM36Status(null, null, error['json']));
106+ this.statuscallback(new ProjectM36Status(null, null, null, error['json']));
100 }
107 }
101
108
102 if(prompt)
109 if(prompt)
@@ -161,6 +168,7 @@ ProjectM36Connection.prototype.generateAtomType = function(attr)
161{
168{
162 var atomType = attr[1]["tag"];
169 var atomType = attr[1]["tag"];
163 var attrName = attr[0];
170 var attrName = attr[0];
171+ var accessory = attr[2];
164 var element = document.createElement("span");
172 var element = document.createElement("span");
165 element.textContent = attrName + "::";
173 element.textContent = attrName + "::";
166 if (atomType == "RelationAtomType")
174 if (atomType == "RelationAtomType")
@@ -185,7 +193,11 @@ ProjectM36Connection.prototype.generateAtomType = function(attr)
185 var readableType = atomType.slice(0,-8);
193 var readableType = atomType.slice(0,-8);
186 element.textContent += readableType;
194 element.textContent += readableType;
187 }
195 }
196+ if(accessory)
197+ {
198+ element.textContent += accessory;
199+ }
188− return element
200+ return element;
189}
201}
190
202
191ProjectM36Connection.prototype.generateRelationBody = function (body)
203ProjectM36Connection.prototype.generateRelationBody = function (body)
@@ -230,6 +242,33 @@ ProjectM36Connection.prototype.generateAtom = function(atom)
230 return element;
242 return element;
231}
243}
232
244
245+ProjectM36Connection.prototype.generateDataFrame = function(dataframe)
246+{
247+ for(var attrIndex=0; attrIndex < dataframe.attributes.length; attrIndex++)
248+ {
249+ var attr = dataframe.attributes[attrIndex];
250+ var ordering = "↕";
251+ for(var orderIndex=0; orderIndex < dataframe.orders.length; orderIndex++)
252+ {
253+ var order = dataframe.orders[orderIndex];
254+ if(order[0] == attr[0])
255+ {
256+ if(order[1] == "AscendingOrder")
257+ {
258+ ordering = "⬆";
259+ }
260+ else if(order[1] == "DescendingOrder")
261+ {
262+ ordering = "⬇";
263+ }
264+ }
265+ }
266+ dataframe.attributes[attrIndex].push(ordering);
267+ }
268+ return this.generateRelation([dataframe.attributes,
269+ {asList:dataframe.tuples}]);
270+}
271+
233//special case to make sure that a table appears for "true" and "false"
272//special case to make sure that a table appears for "true" and "false"
234function mungeEmptyRows()
273function mungeEmptyRows()
235{
274{
@@ -249,4 +288,4 @@ function mungeEmptyRows()
249 empty.appendChild(dudHeader);
288 empty.appendChild(dudHeader);
250 }
289 }
251 }
290 }
252−}
291+}
src/bin/ProjectM36/Server/WebSocket/websocket-client.js+7−1
@@ -30,6 +30,12 @@ function updateStatus(status)
30 appendResult(tutd, relastable);
30 appendResult(tutd, relastable);
31 mungeEmptyRows();
31 mungeEmptyRows();
32 }
32 }
33+ if(status.dataframe)
34+ {
35+ var dataframeastable = conn.generateDataFrame(status.dataframe);
36+ appendResult(tutd, dataframeastable);
37+ mungeEmptyRows();
38+ }
33 if(status.acknowledgement)
39 if(status.acknowledgement)
34 {
40 {
35 var ok = document.createElement("span");
41 var ok = document.createElement("span");
@@ -253,4 +259,4 @@ function pageload()
253{
259{
254 installSampleHandlers();
260 installSampleHandlers();
255 setupDefaultConfig();
261 setupDefaultConfig();
256−}
262+}
src/bin/ProjectM36/Server/WebSocket/websocket-server.hs+7
@@ -1,10 +1,17 @@
1+{-# LANGUAGE CPP #-}
1import ProjectM36.Server.WebSocket
2import ProjectM36.Server.WebSocket
2import ProjectM36.Server.Config
3import ProjectM36.Server.Config
3import ProjectM36.Server.ParseArgs
4import ProjectM36.Server.ParseArgs
4import ProjectM36.Server
5import ProjectM36.Server
5import Control.Concurrent
6import Control.Concurrent
6import qualified Network.WebSockets as WS
7import 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
7import Network.Transport.TCP (decodeEndPointAddress)
12import Network.Transport.TCP (decodeEndPointAddress)
13+#endif
14+
8import Control.Exception
15import Control.Exception
9
16
10main :: IO ()
17main :: IO ()
src/bin/TutorialD/Interpreter.hs+30−30
@@ -1,4 +1,4 @@
1−{-# LANGUAGE GADTs, LambdaCase #-}
1+{-# LANGUAGE GADTs, LambdaCase, CPP #-}
2module TutorialD.Interpreter where
2module TutorialD.Interpreter where
3import TutorialD.Interpreter.Base
3import TutorialD.Interpreter.Base
4import TutorialD.Interpreter.RODatabaseContextOperator
4import TutorialD.Interpreter.RODatabaseContextOperator
@@ -24,13 +24,13 @@ import ProjectM36.TransactionGraph
24import qualified ProjectM36.Client as C
24import qualified ProjectM36.Client as C
25import ProjectM36.Relation (attributes)
25import ProjectM36.Relation (attributes)
26
26
27−import Text.Megaparsec
28−import Text.Megaparsec.Text
29import System.Console.Haskeline
27import System.Console.Haskeline
30import System.Directory (getHomeDirectory)
28import System.Directory (getHomeDirectory)
31import qualified Data.Text as T
29import qualified Data.Text as T
32import System.IO (hPutStrLn, stderr)
30import System.IO (hPutStrLn, stderr)
31+#if __GLASGOW_HASKELL__ < 804
33import Data.Monoid
32import Data.Monoid
33+#endif
34import Data.List (isPrefixOf)
34import Data.List (isPrefixOf)
35import Control.Exception
35import Control.Exception
36import System.Exit
36import System.Exit
@@ -61,7 +61,7 @@ interpreterParserP = safeInterpreterParserP <|>
61 fmap ImportDBContextOp (tutdImportP <* eof) <|>
61 fmap ImportDBContextOp (tutdImportP <* eof) <|>
62 fmap RelVarExportOp (exportCSVP <* eof) <|>
62 fmap RelVarExportOp (exportCSVP <* eof) <|>
63 fmap DatabaseContextIOExprOp (dbContextIOExprP <* eof)
63 fmap DatabaseContextIOExprOp (dbContextIOExprP <* eof)
64−
64+
65-- the safe interpreter never reads or writes the file system
65-- the safe interpreter never reads or writes the file system
66safeInterpreterParserP :: Parser ParsedOperation
66safeInterpreterParserP :: Parser ParsedOperation
67safeInterpreterParserP = fmap RODatabaseContextOp (roDatabaseContextOperatorP <* eof) <|>
67safeInterpreterParserP = fmap RODatabaseContextOp (roDatabaseContextOperatorP <* eof) <|>
@@ -78,12 +78,12 @@ promptText :: Either RelationalError HeadName -> Either RelationalError SchemaNa
78promptText eHeadName eSchemaName = "TutorialD (" <> transInfo <> "): "
78promptText eHeadName eSchemaName = "TutorialD (" <> transInfo <> "): "
79 where
79 where
80 transInfo = either (const "<unknown>") id eHeadName <> "/" <> either (const "<no schema>") id eSchemaName
80 transInfo = either (const "<unknown>") id eHeadName <> "/" <> either (const "<no schema>") id eSchemaName
81−
81+
82−parseTutorialD :: T.Text -> Either (ParseError Char Dec) ParsedOperation
82+parseTutorialD :: T.Text -> Either ParserError ParsedOperation
83parseTutorialD = parse interpreterParserP ""
83parseTutorialD = parse interpreterParserP ""
84
84
85--only parse tutoriald which doesn't result in file I/O
85--only parse tutoriald which doesn't result in file I/O
86−safeParseTutorialD :: T.Text -> Either (ParseError Char Dec) ParsedOperation
86+safeParseTutorialD :: T.Text -> Either ParserError ParsedOperation
87safeParseTutorialD = parse safeInterpreterParserP ""
87safeParseTutorialD = parse safeInterpreterParserP ""
88
88
89data SafeEvaluationFlag = SafeEvaluation | UnsafeEvaluation deriving (Eq)
89data SafeEvaluationFlag = SafeEvaluation | UnsafeEvaluation deriving (Eq)
@@ -106,20 +106,20 @@ evalTutorialDInteractive sessionId conn safe interactive expr = case expr of
106 else
106 else
107 pure res
107 pure res
108 _ -> pure res
108 _ -> pure res
109−
109+
110− (DatabaseContextExprOp execOp) ->
110+ (DatabaseContextExprOp execOp) ->
111− eHandler $ C.executeDatabaseContextExpr sessionId conn execOp
111+ eHandler $ C.executeDatabaseContextExpr sessionId conn execOp
112−
112+
113− (DatabaseContextIOExprOp execOp) ->
113+ (DatabaseContextIOExprOp execOp) ->
114 if needsSafe then
114 if needsSafe then
115 unsafeError
115 unsafeError
116 else
116 else
117 eHandler $ C.executeDatabaseContextIOExpr sessionId conn execOp
117 eHandler $ C.executeDatabaseContextIOExpr sessionId conn execOp
118−
118+
119 (GraphOp execOp) -> do
119 (GraphOp execOp) -> do
120 -- warn if the graph op could cause uncommited changes to be discarded
120 -- warn if the graph op could cause uncommited changes to be discarded
121 eIsDirty <- C.disconnectedTransactionIsDirty sessionId conn
121 eIsDirty <- C.disconnectedTransactionIsDirty sessionId conn
122− let runGraphOp = eHandler $ C.executeGraphExpr sessionId conn execOp
122+ let runGraphOp = eHandler $ C.executeGraphExpr sessionId conn execOp
123 settings = Settings {complete = noCompletion,
123 settings = Settings {complete = noCompletion,
124 historyFile = Nothing,
124 historyFile = Nothing,
125 autoAddHistory = False}
125 autoAddHistory = False}
@@ -143,20 +143,20 @@ evalTutorialDInteractive sessionId conn safe interactive expr = case expr of
143 pure (DisplayErrorResult "Graph operation cancelled.")
143 pure (DisplayErrorResult "Graph operation cancelled.")
144 else
144 else
145 runGraphOp
145 runGraphOp
146−
146+
147 (ConvenienceGraphOp execOp) ->
147 (ConvenienceGraphOp execOp) ->
148 eHandler $ evalConvenienceGraphOp sessionId conn execOp
148 eHandler $ evalConvenienceGraphOp sessionId conn execOp
149
149
150 (ROGraphOp execOp) -> do
150 (ROGraphOp execOp) -> do
151 opResult <- evalROGraphOp sessionId conn execOp
151 opResult <- evalROGraphOp sessionId conn execOp
152− case opResult of
152+ case opResult of
153 Left err -> barf err
153 Left err -> barf err
154 Right rel -> pure (DisplayRelationResult rel)
154 Right rel -> pure (DisplayRelationResult rel)
155−
155+
156 (SchemaOp execOp) ->
156 (SchemaOp execOp) ->
157 eHandler $ evalSchemaOperator sessionId conn execOp
157 eHandler $ evalSchemaOperator sessionId conn execOp
158−
158+
159− (ImportRelVarOp execOp@(RelVarDataImportOperator relVarName _ _)) ->
159+ (ImportRelVarOp execOp@(RelVarDataImportOperator relVarName _ _)) ->
160 if needsSafe then
160 if needsSafe then
161 unsafeError
161 unsafeError
162 else do
162 else do
@@ -174,8 +174,8 @@ evalTutorialDInteractive sessionId conn safe interactive expr = case expr of
174 case exprErr of
174 case exprErr of
175 Left err -> barf err
175 Left err -> barf err
176 Right dbexpr -> evalTutorialD sessionId conn safe (DatabaseContextExprOp dbexpr)
176 Right dbexpr -> evalTutorialD sessionId conn safe (DatabaseContextExprOp dbexpr)
177−
177+
178− (ImportDBContextOp execOp) ->
178+ (ImportDBContextOp execOp) ->
179 if needsSafe then
179 if needsSafe then
180 unsafeError
180 unsafeError
181 else do
181 else do
@@ -183,15 +183,15 @@ evalTutorialDInteractive sessionId conn safe interactive expr = case expr of
183 case eErr of
183 case eErr of
184 Left err -> barf err
184 Left err -> barf err
185 Right dbexprs -> evalTutorialD sessionId conn safe (DatabaseContextExprOp dbexprs)
185 Right dbexprs -> evalTutorialD sessionId conn safe (DatabaseContextExprOp dbexprs)
186−
186+
187− (InfoOp execOp) ->
187+ (InfoOp execOp) ->
188 if needsSafe then
188 if needsSafe then
189 unsafeError
189 unsafeError
190 else
190 else
191 case evalInformationOperator execOp of
191 case evalInformationOperator execOp of
192 Left err -> pure (DisplayErrorResult err)
192 Left err -> pure (DisplayErrorResult err)
193 Right info -> pure (DisplayResult info)
193 Right info -> pure (DisplayResult info)
194−
194+
195 (RelVarExportOp execOp@(RelVarDataExportOperator relExpr _ _)) ->
195 (RelVarExportOp execOp@(RelVarDataExportOperator relExpr _ _)) ->
196 --eval relexpr to relation and pass to export function
196 --eval relexpr to relation and pass to export function
197 if needsSafe then
197 if needsSafe then
@@ -221,11 +221,11 @@ evalTutorialDInteractive sessionId conn safe interactive expr = case expr of
221 case eErr of
221 case eErr of
222 Left err -> barf err
222 Left err -> barf err
223 Right () -> return QuietSuccessResult
223 Right () -> return QuietSuccessResult
224−
224+
225−type GhcPkgPath = String
225+type GhcPkgPath = String
226type TutorialDExec = String
226type TutorialDExec = String
227type CheckFS = Bool
227type CheckFS = Bool
228−
228+
229data InterpreterConfig = LocalInterpreterConfig PersistenceStrategy HeadName (Maybe TutorialDExec) [GhcPkgPath] CheckFS |
229data InterpreterConfig = LocalInterpreterConfig PersistenceStrategy HeadName (Maybe TutorialDExec) [GhcPkgPath] CheckFS |
230 RemoteInterpreterConfig C.NodeId C.DatabaseName HeadName (Maybe TutorialDExec) CheckFS
230 RemoteInterpreterConfig C.NodeId C.DatabaseName HeadName (Maybe TutorialDExec) CheckFS
231
231
@@ -256,12 +256,12 @@ reprLoop config sessionId conn = do
256 Just line -> do
256 Just line -> do
257 runTutorialD sessionId conn (Just (T.length prompt)) (T.pack line)
257 runTutorialD sessionId conn (Just (T.length prompt)) (T.pack line)
258 reprLoop config sessionId conn
258 reprLoop config sessionId conn
259−
259+
260
260
261runTutorialD :: C.SessionId -> C.Connection -> Maybe PromptLength -> T.Text -> IO ()
261runTutorialD :: C.SessionId -> C.Connection -> Maybe PromptLength -> T.Text -> IO ()
262−runTutorialD sessionId conn mPromptLength tutd =
262+runTutorialD sessionId conn mPromptLength tutd =
263 case parseTutorialD tutd of
263 case parseTutorialD tutd of
264− Left err ->
264+ Left err ->
265 displayOpResult $ DisplayParseErrorResult mPromptLength err
265 displayOpResult $ DisplayParseErrorResult mPromptLength err
266 Right parsed ->
266 Right parsed ->
267 catchJust (\exc -> if exc == C.RequestTimeoutException then Just exc else Nothing) (do
267 catchJust (\exc -> if exc == C.RequestTimeoutException then Just exc else Nothing) (do
src/bin/TutorialD/Interpreter/Base.hs+96−37
@@ -1,12 +1,31 @@
1{-# LANGUAGE DeriveGeneric, CPP #-}
1{-# LANGUAGE DeriveGeneric, CPP #-}
2−module TutorialD.Interpreter.Base where
2+module TutorialD.Interpreter.Base (
3+ module TutorialD.Interpreter.Base,
4+ module Text.Megaparsec,
5+#if MIN_VERSION_megaparsec(6,0,0)
6+ module Text.Megaparsec.Char,
7+ module Control.Applicative
8+#else
9+ module Text.Megaparsec.Text
10+#endif
11+ )
12+ where
3import ProjectM36.Base
13import ProjectM36.Base
4import ProjectM36.AtomType
14import ProjectM36.AtomType
5import ProjectM36.Relation
15import ProjectM36.Relation
16+import ProjectM36.DataFrame
6
17
18+#if MIN_VERSION_megaparsec(6,0,0)
19+import Text.Megaparsec.Char
20+import qualified Text.Megaparsec.Char.Lexer as Lex
7import Text.Megaparsec
21import Text.Megaparsec
22+import Data.Void
23+import Control.Applicative hiding (many, some)
24+#else
8import Text.Megaparsec.Text
25import Text.Megaparsec.Text
9import qualified Text.Megaparsec.Lexer as Lex
26import qualified Text.Megaparsec.Lexer as Lex
27+#endif
28+
10import Data.Text hiding (count)
29import Data.Text hiding (count)
11import System.Random
30import System.Random
12import qualified Data.Text as T
31import qualified Data.Text as T
@@ -16,7 +35,9 @@ import qualified Data.Text.IO as TIO
16import System.IO
35import System.IO
17import ProjectM36.Relation.Show.Term
36import ProjectM36.Relation.Show.Term
18import GHC.Generics
37import GHC.Generics
38+#if __GLASGOW_HASKELL__ < 804
19import Data.Monoid
39import Data.Monoid
40+#endif
20import qualified Data.UUID as U
41import qualified Data.UUID as U
21import Control.Monad.Random
42import Control.Monad.Random
22import Data.List.NonEmpty as NE
43import Data.List.NonEmpty as NE
@@ -24,11 +45,16 @@ import Data.Time.Clock
24import Data.Time.Format
45import Data.Time.Format
25import Control.Monad (void)
46import Control.Monad (void)
26
47
48+#if !MIN_VERSION_megaparsec(7,0,0)
49+anySingle :: Parsec Void Text (Token Text)
50+anySingle = anyChar
51+#endif
52+
27displayOpResult :: TutorialDOperatorResult -> IO ()
53displayOpResult :: TutorialDOperatorResult -> IO ()
28displayOpResult QuitResult = return ()
54displayOpResult QuitResult = return ()
29displayOpResult (DisplayResult out) = TIO.putStrLn out
55displayOpResult (DisplayResult out) = TIO.putStrLn out
30displayOpResult (DisplayIOResult ioout) = ioout
56displayOpResult (DisplayIOResult ioout) = ioout
31−displayOpResult (DisplayErrorResult err) = let outputf = if T.length err > 0 && T.last err /= '\n' then TIO.hPutStrLn else TIO.hPutStr in
57+displayOpResult (DisplayErrorResult err) = let outputf = if T.length err > 0 && T.last err /= '\n' then TIO.hPutStrLn else TIO.hPutStr in
32 outputf stderr ("ERR: " <> err)
58 outputf stderr ("ERR: " <> err)
33displayOpResult QuietSuccessResult = return ()
59displayOpResult QuietSuccessResult = return ()
34displayOpResult (DisplayRelationResult rel) = do
60displayOpResult (DisplayRelationResult rel) = do
@@ -36,22 +62,35 @@ displayOpResult (DisplayRelationResult rel) = do
36 let randomlySortedRel = evalRand (randomizeTupleOrder rel) gen
62 let randomlySortedRel = evalRand (randomizeTupleOrder rel) gen
37 TIO.putStrLn (showRelation randomlySortedRel)
63 TIO.putStrLn (showRelation randomlySortedRel)
38displayOpResult (DisplayParseErrorResult mPromptLength err) = do
64displayOpResult (DisplayParseErrorResult mPromptLength err) = do
65+#if MIN_VERSION_megaparsec(7,0,0)
66+ let errorIndent = errorOffset . NE.head . bundleErrors $ err
39− let errString = T.pack (parseErrorPretty err)
67+ errString = T.pack (parseErrorPretty . NE.head . bundleErrors $ err)
68+#else
40− errorIndent = unPos (sourceColumn (NE.head (errorPos err)))
69+ let errorIndent = unPos (sourceColumn (NE.head (errorPos err)))
70+ errString = T.pack (parseErrorPretty err)
71+#endif
41 pointyString len = T.justifyRight (len + fromIntegral errorIndent) '_' "^"
72 pointyString len = T.justifyRight (len + fromIntegral errorIndent) '_' "^"
42 maybe (pure ()) (TIO.putStrLn . pointyString) mPromptLength
73 maybe (pure ()) (TIO.putStrLn . pointyString) mPromptLength
43 TIO.putStr ("ERR:" <> errString)
74 TIO.putStr ("ERR:" <> errString)
75+displayOpResult (DisplayDataFrameResult dFrame) = TIO.putStrLn (showDataFrame dFrame)
76+
77+#if MIN_VERSION_megaparsec(6,0,0)
78+type Parser = Parsec Void Text
79+type ParseStr = Text
80+#else
81+type ParseStr = String
82+#endif
44
83
45spaceConsumer :: Parser ()
84spaceConsumer :: Parser ()
46spaceConsumer = Lex.space (void spaceChar) (Lex.skipLineComment "--") (Lex.skipBlockComment "{-" "-}")
85spaceConsumer = Lex.space (void spaceChar) (Lex.skipLineComment "--") (Lex.skipBlockComment "{-" "-}")
47−
86+
48opChar :: Parser Char
87opChar :: Parser Char
49opChar = oneOf (":!#$%&*+./<=>?\\^|-~" :: String)-- remove "@" so it can be used as attribute marker without spaces
88opChar = oneOf (":!#$%&*+./<=>?\\^|-~" :: String)-- remove "@" so it can be used as attribute marker without spaces
50
89
51−reserved :: String -> Parser ()
90+reserved :: ParseStr -> Parser ()
52reserved word = try (string word *> notFollowedBy opChar *> spaceConsumer)
91reserved word = try (string word *> notFollowedBy opChar *> spaceConsumer)
53
92
54−reservedOp :: String -> Parser ()
93+reservedOp :: ParseStr -> Parser ()
55reservedOp op = try (spaceConsumer *> string op *> notFollowedBy opChar *> spaceConsumer)
94reservedOp op = try (spaceConsumer *> string op *> notFollowedBy opChar *> spaceConsumer)
56
95
57parens :: Parser a -> Parser a
96parens :: Parser a -> Parser a
@@ -63,12 +102,20 @@ braces = between (symbol "{") (symbol "}")
63identifier :: Parser Text
102identifier :: Parser Text
64identifier = do
103identifier = do
65 istart <- letterChar <|> char '_'
104 istart <- letterChar <|> char '_'
105+ identifierRemainder istart
106+
107+identifierRemainder :: Char -> Parser Text
108+identifierRemainder c = do
66− irest <- many (alphaNumChar <|> char '_' <|> char '#')
109+ rest <- many (alphaNumChar <|> char '_' <|> char '#')
67 spaceConsumer
110 spaceConsumer
68− pure (pack (istart:irest))
111+ pure (pack (c:rest))
69
112
70−symbol :: String -> Parser Text
113+symbol :: ParseStr -> Parser Text
114+#if MIN_VERSION_megaparsec(6,0,0)
115+symbol sym = Lex.symbol spaceConsumer sym
116+#else
71symbol sym = pack <$> Lex.symbol spaceConsumer sym
117symbol sym = pack <$> Lex.symbol spaceConsumer sym
118+#endif
72
119
73comma :: Parser Text
120comma :: Parser Text
74comma = symbol ","
121comma = symbol ","
@@ -88,32 +135,30 @@ arrow = symbol "->"
88semi :: Parser Text
135semi :: Parser Text
89semi = symbol ";"
136semi = symbol ";"
90
137
91−{-
92−whiteSpace :: Parser ()
93−whiteSpace = Token.whiteSpace lexer
94−-}
95−
96integer :: Parser Integer
138integer :: Parser Integer
139+#if MIN_VERSION_megaparsec(6,0,0)
97−integer = Lex.signed spaceConsumer Lex.integer
140+integer = Lex.signed (pure ()) Lex.decimal <* spaceConsumer
141+#else
142+integer = Lex.signed (pure ()) Lex.integer <* spaceConsumer
143+#endif
144+
145+natural :: Parser Integer
146+#if MIN_VERSION_megaparsec(6,0,0)
147+natural = Lex.decimal <* spaceConsumer
148+#else
149+natural = Lex.integer <* spaceConsumer
150+#endif
98
151
99float :: Parser Double
152float :: Parser Double
100float = Lex.float
153float = Lex.float
101
154
102capitalizedIdentifier :: Parser Text
155capitalizedIdentifier :: Parser Text
103−capitalizedIdentifier = do
156+capitalizedIdentifier =
104− fletter <- upperChar
157+ upperChar >>= identifierRemainder
105− restOfIdentifier_ fletter
158+
106−
107−restOfIdentifier_ :: Char -> Parser Text
108−restOfIdentifier_ fletter = do
109− rest <- option "" identifier
110− spaceConsumer
111− pure (T.cons fletter rest)
112−
113uncapitalizedIdentifier :: Parser Text
159uncapitalizedIdentifier :: Parser Text
114−uncapitalizedIdentifier = do
160+uncapitalizedIdentifier =
115− fletter <- lowerChar
161+ lowerChar >>= identifierRemainder
116− restOfIdentifier_ fletter
117
162
118showRelationAttributes :: Attributes -> Text
163showRelationAttributes :: Attributes -> Text
119showRelationAttributes attrs = "{" <> T.concat (L.intersperse ", " $ L.map showAttribute attrsL) <> "}"
164showRelationAttributes attrs = "{" <> T.concat (L.intersperse ", " $ L.map showAttribute attrsL) <> "}"
@@ -121,25 +166,34 @@ showRelationAttributes attrs = "{" <> T.concat (L.intersperse ", " $ L.map showA
121 showAttribute (Attribute name atomType) = name <> " " <> prettyAtomType atomType
166 showAttribute (Attribute name atomType) = name <> " " <> prettyAtomType atomType
122 attrsL = V.toList attrs
167 attrsL = V.toList attrs
123
168
124−type PromptLength = Int
169+type PromptLength = Int
170+
171+#if MIN_VERSION_megaparsec(7,0,0)
172+type ParserError = ParseErrorBundle T.Text Void
173+#elif MIN_VERSION_megaparsec(6,0,0)
174+type ParserError = ParseError Char Void
175+#else
176+type ParserError = ParseError Char Dec
177+#endif
125
178
126data TutorialDOperatorResult = QuitResult |
179data TutorialDOperatorResult = QuitResult |
127 DisplayResult StringType |
180 DisplayResult StringType |
128 DisplayIOResult (IO ()) |
181 DisplayIOResult (IO ()) |
129 DisplayRelationResult Relation |
182 DisplayRelationResult Relation |
183+ DisplayDataFrameResult DataFrame |
130 DisplayErrorResult StringType |
184 DisplayErrorResult StringType |
131− DisplayParseErrorResult (Maybe PromptLength) (ParseError Char Dec) | -- Int refers to length of prompt text
185+ DisplayParseErrorResult (Maybe PromptLength) ParserError | -- PromptLength refers to length of prompt text
132 QuietSuccessResult
186 QuietSuccessResult
133 deriving (Generic)
187 deriving (Generic)
134−
188+
135type TransactionGraphWasUpdated = Bool
189type TransactionGraphWasUpdated = Bool
136
190
137--allow for python-style triple quoting because guessing the correct amount of escapes in different contexts is annoying
191--allow for python-style triple quoting because guessing the correct amount of escapes in different contexts is annoying
138tripleQuotedString :: Parser Text
192tripleQuotedString :: Parser Text
139tripleQuotedString = do
193tripleQuotedString = do
140 _ <- tripleQuote
194 _ <- tripleQuote
141− pack <$> manyTill anyChar (try (tripleQuote >> notFollowedBy quote))
195+ pack <$> manyTill anySingle (try (tripleQuote >> notFollowedBy quote))
142−
196+
143normalQuotedString :: Parser Text
197normalQuotedString :: Parser Text
144normalQuotedString = quote *> (T.pack <$> manyTill Lex.charLiteral quote)
198normalQuotedString = quote *> (T.pack <$> manyTill Lex.charLiteral quote)
145
199
@@ -148,7 +202,7 @@ quotedString = try tripleQuotedString <|> normalQuotedString
148
202
149uuidP :: Parser U.UUID
203uuidP :: Parser U.UUID
150uuidP = do
204uuidP = do
151− uuidStart <- count 8 hexDigitChar
205+ uuidStart <- count 8 hexDigitChar
152 _ <- char '-' -- min 28 with no dashes, maximum 4 dashes
206 _ <- char '-' -- min 28 with no dashes, maximum 4 dashes
153 uuidMid1 <- count 4 hexDigitChar
207 uuidMid1 <- count 4 hexDigitChar
154 _ <- char '-'
208 _ <- char '-'
@@ -167,5 +221,10 @@ utcTimeP = do
167 timeStr <- quotedString
221 timeStr <- quotedString
168 case parseTimeM True defaultTimeLocale "%Y-%m-%d %H:%M:%S" (T.unpack timeStr) of
222 case parseTimeM True defaultTimeLocale "%Y-%m-%d %H:%M:%S" (T.unpack timeStr) of
169 Nothing -> fail "invalid datetime input, use \"YYYY-MM-DD HH:MM:SS\""
223 Nothing -> fail "invalid datetime input, use \"YYYY-MM-DD HH:MM:SS\""
170− Just stamp -> pure stamp
224+ Just stamp' -> pure stamp'
171−
225+
226+
227+colonOp :: Text -> Parser ()
228+colonOp opStr = do
229+ _ <- string opStr <* spaceChar <* spaceConsumer
230+ pure ()
src/bin/TutorialD/Interpreter/DatabaseContextExpr.hs+29−29
@@ -1,20 +1,20 @@
1+{-# LANGUAGE CPP #-}
1module TutorialD.Interpreter.DatabaseContextExpr where
2module TutorialD.Interpreter.DatabaseContextExpr where
2−import Text.Megaparsec
3−import Text.Megaparsec.Text
4import ProjectM36.Base
3import ProjectM36.Base
5import TutorialD.Interpreter.Base
4import TutorialD.Interpreter.Base
6import qualified Data.Text as T
5import qualified Data.Text as T
7import TutorialD.Interpreter.RelationalExpr
6import TutorialD.Interpreter.RelationalExpr
8import TutorialD.Interpreter.Types
7import TutorialD.Interpreter.Types
9import qualified Data.Map as M
8import qualified Data.Map as M
10−import Control.Monad.State
11import ProjectM36.StaticOptimizer
9import ProjectM36.StaticOptimizer
12import qualified ProjectM36.Error as PM36E
10import qualified ProjectM36.Error as PM36E
13import ProjectM36.Error
11import ProjectM36.Error
14import qualified ProjectM36.RelationalExpression as RE
12import qualified ProjectM36.RelationalExpression as RE
15import ProjectM36.Key
13import ProjectM36.Key
16import ProjectM36.FunctionalDependency
14import ProjectM36.FunctionalDependency
15+#if __GLASGOW_HASKELL__ < 804
17import Data.Monoid
16import Data.Monoid
17+#endif
18import Data.Functor
18import Data.Functor
19
19
20--parsers which create "database expressions" which modify the database context (such as relvar assignment)
20--parsers which create "database expressions" which modify the database context (such as relvar assignment)
@@ -44,11 +44,10 @@ nothingP = spaceConsumer >> pure NoOperation
44assignP :: Parser DatabaseContextExpr
44assignP :: Parser DatabaseContextExpr
45assignP = do
45assignP = do
46 relVarName <- try $ do
46 relVarName <- try $ do
47− relVarName <- identifier
47+ relVarName <- relVarNameP
48 reservedOp ":="
48 reservedOp ":="
49 return relVarName
49 return relVarName
50− expr <- relExprP
51− pure $ Assign relVarName expr
50+ Assign relVarName <$> relExprP
52
51
53multilineSep :: Parser T.Text
52multilineSep :: Parser T.Text
54multilineSep = newline >> pure "\n"
53multilineSep = newline >> pure "\n"
@@ -60,33 +59,31 @@ multipleDatabaseContextExprP =
60insertP :: Parser DatabaseContextExpr
59insertP :: Parser DatabaseContextExpr
61insertP = do
60insertP = do
62 reservedOp "insert"
61 reservedOp "insert"
63− relvar <- identifier
62+ relvar <- relVarNameP
64− expr <- relExprP
65− pure $ Insert relvar expr
63+ Insert relvar <$> relExprP
66
64
67defineP :: Parser DatabaseContextExpr
65defineP :: Parser DatabaseContextExpr
68defineP = do
66defineP = do
69 relVarName <- try $ do
67 relVarName <- try $ do
70− relVarName <- identifier
68+ relVarName <- relVarNameP
71 reservedOp "::"
69 reservedOp "::"
72 return relVarName
70 return relVarName
73− attributeSet <- makeAttributeExprsP
74− pure $ Define relVarName attributeSet
71+ Define relVarName <$> makeAttributeExprsP
75
72
76undefineP :: Parser DatabaseContextExpr
73undefineP :: Parser DatabaseContextExpr
77undefineP = do
74undefineP = do
78 reservedOp "undefine"
75 reservedOp "undefine"
79− Undefine <$> identifier
76+ Undefine <$> relVarNameP
80
77
81deleteP :: Parser DatabaseContextExpr
78deleteP :: Parser DatabaseContextExpr
82deleteP = do
79deleteP = do
83 reservedOp "delete"
80 reservedOp "delete"
84− Delete <$> identifier <*> option TruePredicate (reservedOp "where" *> restrictionPredicateP)
81+ Delete <$> relVarNameP <*> option TruePredicate (reservedOp "where" *> restrictionPredicateP)
85
82
86updateP :: Parser DatabaseContextExpr
83updateP :: Parser DatabaseContextExpr
87updateP = do
84updateP = do
88 reservedOp "update"
85 reservedOp "update"
89− relVarName <- identifier
86+ relVarName <- relVarNameP
90 predicate <- option TruePredicate (reservedOp "where" *> restrictionPredicateP <* spaceConsumer)
87 predicate <- option TruePredicate (reservedOp "where" *> restrictionPredicateP <* spaceConsumer)
91 attributeAssignments <- M.fromList <$> parens (sepBy attributeAssignmentP comma)
88 attributeAssignments <- M.fromList <$> parens (sepBy attributeAssignmentP comma)
92 return $ Update relVarName attributeAssignments predicate
89 return $ Update relVarName attributeAssignments predicate
@@ -110,8 +107,7 @@ addConstraintP = do
110deleteConstraintP :: Parser DatabaseContextExpr
107deleteConstraintP :: Parser DatabaseContextExpr
111deleteConstraintP = do
108deleteConstraintP = do
112 reserved "deleteconstraint"
109 reserved "deleteconstraint"
113− constraintName <- identifier
110+ RemoveInclusionDependency <$> identifier
114− pure $ RemoveInclusionDependency constraintName
115
111
116-- key <constraint name> {<uniqueness attributes>} <uniqueness relexpr>
112-- key <constraint name> {<uniqueness attributes>} <uniqueness relexpr>
117keyP :: Parser DatabaseContextExpr
113keyP :: Parser DatabaseContextExpr
@@ -151,14 +147,12 @@ addNotificationP = do
151 notName <- identifier
147 notName <- identifier
152 triggerExpr <- relExprP
148 triggerExpr <- relExprP
153 resultOldExpr <- relExprP
149 resultOldExpr <- relExprP
154− resultNewExpr <- relExprP
155− pure $ AddNotification notName triggerExpr resultOldExpr resultNewExpr
150+ AddNotification notName triggerExpr resultOldExpr <$> relExprP
156
151
157removeNotificationP :: Parser DatabaseContextExpr
152removeNotificationP :: Parser DatabaseContextExpr
158removeNotificationP = do
153removeNotificationP = do
159 reserved "unnotify"
154 reserved "unnotify"
160− notName <- identifier
155+ RemoveNotification <$> identifier
161− pure $ RemoveNotification notName
162
156
163-- | data Hair = Bald | Color Text
157-- | data Hair = Bald | Color Text
164addTypeConstructorP :: Parser DatabaseContextExpr
158addTypeConstructorP :: Parser DatabaseContextExpr
@@ -172,7 +166,7 @@ addTypeConstructorP = do
172removeTypeConstructorP :: Parser DatabaseContextExpr
166removeTypeConstructorP :: Parser DatabaseContextExpr
173removeTypeConstructorP = do
167removeTypeConstructorP = do
174 reserved "undata"
168 reserved "undata"
175− RemoveTypeConstructor <$> identifier
169+ RemoveTypeConstructor <$> typeConstructorNameP
176
170
177removeAtomFunctionP :: Parser DatabaseContextExpr
171removeAtomFunctionP :: Parser DatabaseContextExpr
178removeAtomFunctionP = do
172removeAtomFunctionP = do
@@ -184,29 +178,35 @@ removeDatabaseContextFunctionP = do
184 reserved "removedatabasecontextfunction"
178 reserved "removedatabasecontextfunction"
185 RemoveDatabaseContextFunction <$> quotedString
179 RemoveDatabaseContextFunction <$> quotedString
186
180
181+functionNameP :: Parser AtomFunctionName
182+functionNameP = uncapitalizedIdentifier
183+
187executeDatabaseContextFunctionP :: Parser DatabaseContextExpr
184executeDatabaseContextFunctionP :: Parser DatabaseContextExpr
188executeDatabaseContextFunctionP = do
185executeDatabaseContextFunctionP = do
189 reserved "execute"
186 reserved "execute"
190− funcName <- identifier
187+ funcName <- functionNameP
191 args <- parens (sepBy atomExprP comma)
188 args <- parens (sepBy atomExprP comma)
192 pure (ExecuteDatabaseContextFunction funcName args)
189 pure (ExecuteDatabaseContextFunction funcName args)
193
190
194databaseExprOpP :: Parser DatabaseContextExpr
191databaseExprOpP :: Parser DatabaseContextExpr
195databaseExprOpP = multipleDatabaseContextExprP
192databaseExprOpP = multipleDatabaseContextExprP
196
193
194+{-
197evalDatabaseContextExpr :: Bool -> DatabaseContext -> DatabaseContextExpr -> Either RelationalError DatabaseContext
195evalDatabaseContextExpr :: Bool -> DatabaseContext -> DatabaseContextExpr -> Either RelationalError DatabaseContext
198evalDatabaseContextExpr useOptimizer context expr = do
196evalDatabaseContextExpr useOptimizer context expr = do
199 optimizedExpr <- evalState (applyStaticDatabaseOptimization expr) (RE.freshDatabaseState context)
197 optimizedExpr <- evalState (applyStaticDatabaseOptimization expr) (RE.freshDatabaseState context)
200 case runState (RE.evalDatabaseContextExpr (if useOptimizer then optimizedExpr else expr)) (RE.freshDatabaseState context) of
198 case runState (RE.evalDatabaseContextExpr (if useOptimizer then optimizedExpr else expr)) (RE.freshDatabaseState context) of
201 (Right (), (context',_, _)) -> Right context'
199 (Right (), (context',_, _)) -> Right context'
202 (Left err, _) -> Left err
200 (Left err, _) -> Left err
201+-}
203
202
204−
205−interpretDatabaseContextExpr :: DatabaseContext -> T.Text -> Either RelationalError DatabaseContext
203+interpretDatabaseContextExpr :: DatabaseContext -> TransactionId -> TransactionGraph -> T.Text -> Either RelationalError DatabaseContext
206−interpretDatabaseContextExpr context tutdstring = case parse databaseExprOpP "" tutdstring of
204+interpretDatabaseContextExpr context transId graph tutdstring =
205+ case parse databaseExprOpP "" tutdstring of
207− Left err -> Left $ PM36E.ParseError (T.pack (show err))
206+ Left err -> Left $ PM36E.ParseError (T.pack (show err))
208− Right parsed ->
207+ Right parsed -> do
209− evalDatabaseContextExpr True context parsed
208+ let env = RE.mkDatabaseContextEvalEnv transId graph
209+ RE.dbc_context <$> RE.runDatabaseContextEvalMonad context env (optimizeAndEvalDatabaseContextExpr True parsed)
210
210
211{-
211{-
212--no optimization
212--no optimization
src/bin/TutorialD/Interpreter/DatabaseContextIOOperator.hs+2−6
@@ -1,11 +1,8 @@
1--compiling the script requires the IO monad because it must load modules from the filesystem, so we create the function and generate the requisite DatabaseExpr here.
1--compiling the script requires the IO monad because it must load modules from the filesystem, so we create the function and generate the requisite DatabaseExpr here.
2module TutorialD.Interpreter.DatabaseContextIOOperator where
2module TutorialD.Interpreter.DatabaseContextIOOperator where
3import ProjectM36.Base
3import ProjectM36.Base
4−
5import TutorialD.Interpreter.Base
4import TutorialD.Interpreter.Base
6import TutorialD.Interpreter.Types
5import TutorialD.Interpreter.Types
7−import Text.Megaparsec
8−import Text.Megaparsec.Text
9import Data.Text
6import Data.Text
10
7
11addAtomFunctionExprP :: Parser DatabaseContextIOExpr
8addAtomFunctionExprP :: Parser DatabaseContextIOExpr
@@ -24,13 +21,12 @@ createArbitraryRelationP = do
24 max' <- fromInteger <$> integer
21 max' <- fromInteger <$> integer
25 pure $ CreateArbitraryRelation relVarName attrExprs (min',max')
22 pure $ CreateArbitraryRelation relVarName attrExprs (min',max')
26
23
27−dbioexprP :: String -> (Text -> [TypeConstructor] -> Text -> DatabaseContextIOExpr) -> Parser DatabaseContextIOExpr
24+dbioexprP :: ParseStr -> (Text -> [TypeConstructor] -> Text -> DatabaseContextIOExpr) -> Parser DatabaseContextIOExpr
28dbioexprP res adt = do
25dbioexprP res adt = do
29 reserved res
26 reserved res
30 funcName <- quotedString
27 funcName <- quotedString
31 funcType <- atomTypeSignatureP
28 funcType <- atomTypeSignatureP
32− funcScript <- quotedString
33− pure $ adt funcName funcType funcScript
29+ adt funcName funcType <$> quotedString
34
30
35atomTypeSignatureP :: Parser [TypeConstructor]
31atomTypeSignatureP :: Parser [TypeConstructor]
36atomTypeSignatureP = sepBy typeConstructorP arrow
32atomTypeSignatureP = sepBy typeConstructorP arrow
src/bin/TutorialD/Interpreter/Export/Base.hs+3
@@ -1,7 +1,10 @@
1+{-# LANGUAGE CPP #-}
1module TutorialD.Interpreter.Export.Base where
2module TutorialD.Interpreter.Export.Base where
2import ProjectM36.Base
3import ProjectM36.Base
3import ProjectM36.Error
4import ProjectM36.Error
5+#if __GLASGOW_HASKELL__ < 804
4import Data.Monoid
6import Data.Monoid
7+#endif
5
8
6data RelVarDataExportOperator = RelVarDataExportOperator RelationalExpr FilePath (RelVarDataExportOperator -> Relation -> IO (Maybe RelationalError))
9data RelVarDataExportOperator = RelVarDataExportOperator RelationalExpr FilePath (RelVarDataExportOperator -> Relation -> IO (Maybe RelationalError))
7
10
src/bin/TutorialD/Interpreter/Export/CSV.hs+1−2
@@ -2,10 +2,9 @@ module TutorialD.Interpreter.Export.CSV where
2import ProjectM36.Relation.Show.CSV
2import ProjectM36.Relation.Show.CSV
3import TutorialD.Interpreter.Export.Base
3import TutorialD.Interpreter.Export.Base
4import TutorialD.Interpreter.RelationalExpr
4import TutorialD.Interpreter.RelationalExpr
5−import TutorialD.Interpreter.Base
5+import TutorialD.Interpreter.Base hiding (try)
6import ProjectM36.Base
6import ProjectM36.Base
7import ProjectM36.Error
7import ProjectM36.Error
8−import Text.Megaparsec.Text
9import qualified Data.ByteString.Lazy as BS
8import qualified Data.ByteString.Lazy as BS
10import Control.Exception (try)
9import Control.Exception (try)
11import qualified Data.Text as T
10import qualified Data.Text as T
src/bin/TutorialD/Interpreter/Import/Base.hs+3
@@ -1,7 +1,10 @@
1+{-# LANGUAGE CPP #-}
1module TutorialD.Interpreter.Import.Base where
2module TutorialD.Interpreter.Import.Base where
2import ProjectM36.Base
3import ProjectM36.Base
3import ProjectM36.Error
4import ProjectM36.Error
5+#if __GLASGOW_HASKELL__ < 804
4import Data.Monoid
6import Data.Monoid
7+#endif
5
8
6-- | import data into a relation variable
9-- | import data into a relation variable
7data RelVarDataImportOperator = RelVarDataImportOperator RelVarName FilePath (RelVarName -> TypeConstructorMapping -> Attributes -> FilePath -> IO (Either RelationalError DatabaseContextExpr))
10data RelVarDataImportOperator = RelVarDataImportOperator RelVarName FilePath (RelVarName -> TypeConstructorMapping -> Attributes -> FilePath -> IO (Either RelationalError DatabaseContextExpr))
src/bin/TutorialD/Interpreter/Import/BasicExamples.hs+4
@@ -1,10 +1,14 @@
1+{-# LANGUAGE CPP #-}
1--includes some hardcoded examples which can be imported even during safe evaluation (no file I/O)
2--includes some hardcoded examples which can be imported even during safe evaluation (no file I/O)
2module TutorialD.Interpreter.Import.BasicExamples where
3module TutorialD.Interpreter.Import.BasicExamples where
3import ProjectM36.DateExamples
4import ProjectM36.DateExamples
4import ProjectM36.Base
5import ProjectM36.Base
5import ProjectM36.DatabaseContext
6import ProjectM36.DatabaseContext
6import TutorialD.Interpreter.Base
7import TutorialD.Interpreter.Base
8+
9+#if !MIN_VERSION_megaparsec(6,0,0)
7import Text.Megaparsec.Text
10import Text.Megaparsec.Text
11+#endif
8
12
9data ImportBasicExampleOperator = ImportBasicDateExampleOperator
13data ImportBasicExampleOperator = ImportBasicDateExampleOperator
10 deriving (Show)
14 deriving (Show)
src/bin/TutorialD/Interpreter/Import/CSV.hs+2−2
@@ -1,3 +1,4 @@
1+{-# LANGUAGE CPP #-}
1module TutorialD.Interpreter.Import.CSV where
2module TutorialD.Interpreter.Import.CSV where
2import TutorialD.Interpreter.Import.Base
3import TutorialD.Interpreter.Import.Base
3import ProjectM36.Base
4import ProjectM36.Base
@@ -5,8 +6,7 @@ import ProjectM36.Error
5import ProjectM36.Relation.Parse.CSV hiding (quotedString)
6import ProjectM36.Relation.Parse.CSV hiding (quotedString)
6import qualified Data.ByteString.Lazy as BS
7import qualified Data.ByteString.Lazy as BS
7import qualified Data.Text as T
8import qualified Data.Text as T
8−import Text.Megaparsec.Text
9−import TutorialD.Interpreter.Base
9+import TutorialD.Interpreter.Base hiding (try)
10import Control.Exception
10import Control.Exception
11
11
12importCSVRelation :: RelVarName -> TypeConstructorMapping -> Attributes -> FilePath -> IO (Either RelationalError DatabaseContextExpr)
12importCSVRelation :: RelVarName -> TypeConstructorMapping -> Attributes -> FilePath -> IO (Either RelationalError DatabaseContextExpr)
src/bin/TutorialD/Interpreter/Import/TutorialD.hs+1−3
@@ -1,10 +1,8 @@
1module TutorialD.Interpreter.Import.TutorialD where
1module TutorialD.Interpreter.Import.TutorialD where
2import ProjectM36.Base
2import ProjectM36.Base
3import TutorialD.Interpreter.Import.Base
3import TutorialD.Interpreter.Import.Base
4−import TutorialD.Interpreter.Base
4+import TutorialD.Interpreter.Base hiding (try)
5import TutorialD.Interpreter.DatabaseContextExpr
5import TutorialD.Interpreter.DatabaseContextExpr
6−import Text.Megaparsec.Text
7−import Text.Megaparsec hiding (try)
8import ProjectM36.Error
6import ProjectM36.Error
9import qualified ProjectM36.Error as PM36E
7import qualified ProjectM36.Error as PM36E
10import qualified Data.Text as T
8import qualified Data.Text as T
src/bin/TutorialD/Interpreter/InformationOperator.hs−1
@@ -2,7 +2,6 @@
2module TutorialD.Interpreter.InformationOperator where
2module TutorialD.Interpreter.InformationOperator where
3import Data.Text
3import Data.Text
4import Text.Megaparsec
4import Text.Megaparsec
5−import Text.Megaparsec.Text
6import TutorialD.Interpreter.Base
5import TutorialD.Interpreter.Base
7-- older versions of stack fail to
6-- older versions of stack fail to
8#if !defined(VERSION_project_m36)
7#if !defined(VERSION_project_m36)
src/bin/TutorialD/Interpreter/RODatabaseContextOperator.hs+48−13
@@ -1,11 +1,10 @@
1{-# LANGUAGE GADTs #-}
1{-# LANGUAGE GADTs #-}
2module TutorialD.Interpreter.RODatabaseContextOperator where
2module TutorialD.Interpreter.RODatabaseContextOperator where
3import ProjectM36.Base
3import ProjectM36.Base
4+import qualified ProjectM36.DataFrame as DF
4import ProjectM36.Error
5import ProjectM36.Error
5import ProjectM36.InclusionDependency
6import ProjectM36.InclusionDependency
6import qualified ProjectM36.Client as C
7import qualified ProjectM36.Client as C
7−import Text.Megaparsec
8−import Text.Megaparsec.Text
9import TutorialD.Interpreter.Base
8import TutorialD.Interpreter.Base
10import TutorialD.Interpreter.RelationalExpr
9import TutorialD.Interpreter.RelationalExpr
11import TutorialD.Interpreter.DatabaseContextExpr
10import TutorialD.Interpreter.DatabaseContextExpr
@@ -26,49 +25,50 @@ data RODatabaseContextOperator where
26 ShowRelationVariables :: RODatabaseContextOperator
25 ShowRelationVariables :: RODatabaseContextOperator
27 ShowAtomFunctions :: RODatabaseContextOperator
26 ShowAtomFunctions :: RODatabaseContextOperator
28 ShowDatabaseContextFunctions :: RODatabaseContextOperator
27 ShowDatabaseContextFunctions :: RODatabaseContextOperator
28+ ShowDataFrame :: DF.DataFrameExpr -> RODatabaseContextOperator
29 Quit :: RODatabaseContextOperator
29 Quit :: RODatabaseContextOperator
30 deriving (Show)
30 deriving (Show)
31
31
32typeP :: Parser RODatabaseContextOperator
32typeP :: Parser RODatabaseContextOperator
33typeP = do
33typeP = do
34− reservedOp ":type"
34+ colonOp ":type"
35 ShowRelationType <$> relExprP
35 ShowRelationType <$> relExprP
36
36
37showRelP :: Parser RODatabaseContextOperator
37showRelP :: Parser RODatabaseContextOperator
38showRelP = do
38showRelP = do
39− reservedOp ":showexpr"
39+ colonOp ":showexpr"
40 ShowRelation <$> relExprP
40 ShowRelation <$> relExprP
41
41
42showPlanP :: Parser RODatabaseContextOperator
42showPlanP :: Parser RODatabaseContextOperator
43showPlanP = do
43showPlanP = do
44− reservedOp ":showplan"
44+ colonOp ":showplan"
45 ShowPlan <$> databaseContextExprP
45 ShowPlan <$> databaseContextExprP
46
46
47showTypesP :: Parser RODatabaseContextOperator
47showTypesP :: Parser RODatabaseContextOperator
48−showTypesP = reserved ":showtypes" >> pure ShowTypes
48+showTypesP = colonOp ":showtypes" >> pure ShowTypes
49
49
50showRelationVariables :: Parser RODatabaseContextOperator
50showRelationVariables :: Parser RODatabaseContextOperator
51−showRelationVariables = reserved ":showrelvars" >> pure ShowRelationVariables
51+showRelationVariables = colonOp ":showrelvars" >> pure ShowRelationVariables
52
52
53showAtomFunctionsP :: Parser RODatabaseContextOperator
53showAtomFunctionsP :: Parser RODatabaseContextOperator
54−showAtomFunctionsP = reserved ":showatomfunctions" >> pure ShowAtomFunctions
54+showAtomFunctionsP = colonOp ":showatomfunctions" >> pure ShowAtomFunctions
55
55
56showDatabaseContextFunctionsP :: Parser RODatabaseContextOperator
56showDatabaseContextFunctionsP :: Parser RODatabaseContextOperator
57−showDatabaseContextFunctionsP = reserved ":showdatabasecontextfunctions" >> pure ShowDatabaseContextFunctions
57+showDatabaseContextFunctionsP = colonOp ":showdatabasecontextfunctions" >> pure ShowDatabaseContextFunctions
58
58
59quitP :: Parser RODatabaseContextOperator
59quitP :: Parser RODatabaseContextOperator
60quitP = do
60quitP = do
61− reservedOp ":quit"
61+ colonOp ":quit"
62 return Quit
62 return Quit
63
63
64showConstraintsP :: Parser RODatabaseContextOperator
64showConstraintsP :: Parser RODatabaseContextOperator
65showConstraintsP = do
65showConstraintsP = do
66− reservedOp ":constraints"
66+ colonOp ":constraints"
67 ShowConstraint <$> option "" identifier
67 ShowConstraint <$> option "" identifier
68
68
69plotRelExprP :: Parser RODatabaseContextOperator
69plotRelExprP :: Parser RODatabaseContextOperator
70plotRelExprP = do
70plotRelExprP = do
71− reserved ":plotexpr"
71+ colonOp ":plotexpr"
72 PlotRelation <$> relExprP
72 PlotRelation <$> relExprP
73
73
74roDatabaseContextOperatorP :: Parser RODatabaseContextOperator
74roDatabaseContextOperatorP :: Parser RODatabaseContextOperator
@@ -81,6 +81,7 @@ roDatabaseContextOperatorP = typeP
81 <|> showTypesP
81 <|> showTypesP
82 <|> showAtomFunctionsP
82 <|> showAtomFunctionsP
83 <|> showDatabaseContextFunctionsP
83 <|> showDatabaseContextFunctionsP
84+ <|> showDataFrameP
84 <|> quitP
85 <|> quitP
85
86
86--logically, these read-only operations could happen purely, but not if a remote call is required
87--logically, these read-only operations could happen purely, but not if a remote call is required
@@ -148,6 +149,12 @@ evalRODatabaseContextOp sessionId conn ShowDatabaseContextFunctions = do
148 Left err -> pure $ DisplayErrorResult (T.pack (show err))
149 Left err -> pure $ DisplayErrorResult (T.pack (show err))
149 Right rel -> evalRODatabaseContextOp sessionId conn (ShowRelation (ExistingRelation rel))
150 Right rel -> evalRODatabaseContextOp sessionId conn (ShowRelation (ExistingRelation rel))
150
151
152+evalRODatabaseContextOp sessionId conn (ShowDataFrame dfExpr) = do
153+ eDataFrame <- C.executeDataFrameExpr sessionId conn dfExpr
154+ case eDataFrame of
155+ Left err -> pure (DisplayErrorResult (T.pack (show err)))
156+ Right dframe -> pure (DisplayDataFrameResult dframe)
157+
151evalRODatabaseContextOp _ _ Quit = pure QuitResult
158evalRODatabaseContextOp _ _ Quit = pure QuitResult
152
159
153interpretRODatabaseContextOp :: C.SessionId -> C.Connection -> T.Text -> IO TutorialDOperatorResult
160interpretRODatabaseContextOp :: C.SessionId -> C.Connection -> T.Text -> IO TutorialDOperatorResult
@@ -155,4 +162,32 @@ interpretRODatabaseContextOp sessionId conn tutdstring = case parse roDatabaseCo
155 Left err -> pure $ DisplayErrorResult (T.pack (show err))
162 Left err -> pure $ DisplayErrorResult (T.pack (show err))
156 Right parsed -> evalRODatabaseContextOp sessionId conn parsed
163 Right parsed -> evalRODatabaseContextOp sessionId conn parsed
157
164
158−
165+showDataFrameP :: Parser RODatabaseContextOperator
166+showDataFrameP = do
167+ colonOp ":showdataframe"
168+ relExpr <- relExprP
169+ reservedOp "orderby"
170+ attrOrdersExpr <- attrOrdersExprP
171+ mbOffset <- optional offsetP
172+ mbLimit <- optional limitP
173+ pure $ ShowDataFrame (DF.DataFrameExpr relExpr attrOrdersExpr mbOffset mbLimit)
174+
175+
176+offsetP :: Parser Integer
177+offsetP = do
178+ reservedOp "offset"
179+ natural
180+
181+limitP :: Parser Integer
182+limitP = do
183+ reservedOp "limit"
184+ natural
185+
186+attrOrdersExprP :: Parser [DF.AttributeOrderExpr]
187+attrOrdersExprP = braces (sepBy attrOrderExprP comma)
188+
189+attrOrderExprP :: Parser DF.AttributeOrderExpr
190+attrOrderExprP = DF.AttributeOrderExpr <$> identifier <*> orderP
191+
192+orderP :: Parser DF.Order
193+orderP = try (reservedOp "ascending" >> pure DF.AscendingOrder) <|> try (reservedOp "descending" >> pure DF.DescendingOrder) <|> pure DF.AscendingOrder
src/bin/TutorialD/Interpreter/RelationalExpr.hs+80−45
@@ -1,8 +1,12 @@
1+{-# LANGUAGE CPP #-}
1module TutorialD.Interpreter.RelationalExpr where
2module TutorialD.Interpreter.RelationalExpr where
2import Text.Megaparsec
3import Text.Megaparsec
4+#if MIN_VERSION_megaparsec(7,0,0)
5+import Control.Monad.Combinators.Expr
6+#else
3import Text.Megaparsec.Expr
7import Text.Megaparsec.Expr
8+#endif
4import ProjectM36.Base
9import ProjectM36.Base
5−import Text.Megaparsec.Text
6import TutorialD.Interpreter.Base
10import TutorialD.Interpreter.Base
7import TutorialD.Interpreter.Types
11import TutorialD.Interpreter.Types
8import qualified Data.Text as T
12import qualified Data.Text as T
@@ -13,26 +17,27 @@ import ProjectM36.MiscUtils
13
17
14--used in projection
18--used in projection
15attributeListP :: RelationalMarkerExpr a => Parser (AttributeNamesBase a)
19attributeListP :: RelationalMarkerExpr a => Parser (AttributeNamesBase a)
16−attributeListP =
20+attributeListP =
17 (reservedOp "all but" >>
21 (reservedOp "all but" >>
18− InvertedAttributeNames . S.fromList <$> sepBy identifier comma) <|>
22+ InvertedAttributeNames . S.fromList <$> sepBy attributeNameP comma) <|>
19 (reservedOp "all from" >>
23 (reservedOp "all from" >>
20 RelationalExprAttributeNames <$> relExprP) <|>
24 RelationalExprAttributeNames <$> relExprP) <|>
21− (AttributeNames . S.fromList <$> sepBy identifier comma)
25+ (AttributeNames . S.fromList <$> sepBy attributeNameP comma)
22
26
23makeRelationP :: RelationalMarkerExpr a => Parser (RelationalExprBase a)
27makeRelationP :: RelationalMarkerExpr a => Parser (RelationalExprBase a)
24makeRelationP = do
28makeRelationP = do
25 reserved "relation"
29 reserved "relation"
26 attrExprs <- try (fmap Just makeAttributeExprsP) <|> pure Nothing
30 attrExprs <- try (fmap Just makeAttributeExprsP) <|> pure Nothing
27 tupleExprs <- braces (sepBy tupleExprP comma) <|> pure []
31 tupleExprs <- braces (sepBy tupleExprP comma) <|> pure []
32+ marker <- parseMarkerP
28− pure $ MakeRelationFromExprs attrExprs tupleExprs
33+ pure $ MakeRelationFromExprs attrExprs (TupleExprs marker tupleExprs)
34+
29
35
30−
31--abstract data type parser- in this context, the type constructor must not include any type arguments
36--abstract data type parser- in this context, the type constructor must not include any type arguments
32--Either Text Int
37--Either Text Int
33adTypeConstructorP :: Parser TypeConstructor
38adTypeConstructorP :: Parser TypeConstructor
34adTypeConstructorP = do
39adTypeConstructorP = do
35− tConsName <- capitalizedIdentifier
40+ tConsName <- typeConstructorNameP
36 tConsArgs <- many typeConstructorP
41 tConsArgs <- many typeConstructorP
37 pure $ ADTypeConstructor tConsName tConsArgs
42 pure $ ADTypeConstructor tConsName tConsArgs
38
43
@@ -42,25 +47,25 @@ tupleExprP = do
42 attrAssocs <- braces (sepBy tupleAtomExprP comma)
47 attrAssocs <- braces (sepBy tupleAtomExprP comma)
43 --detect duplicate attribute names
48 --detect duplicate attribute names
44 let dupAttrNames = dupes (sort (map fst attrAssocs))
49 let dupAttrNames = dupes (sort (map fst attrAssocs))
45− if not (null dupAttrNames) then
50+ if not (null dupAttrNames) then
46 fail ("Attribute names duplicated: " ++ show dupAttrNames)
51 fail ("Attribute names duplicated: " ++ show dupAttrNames)
47 else
52 else
48 pure (TupleExpr (M.fromList attrAssocs))
53 pure (TupleExpr (M.fromList attrAssocs))
49
54
50tupleAtomExprP :: RelationalMarkerExpr a => Parser (AttributeName, AtomExprBase a)
55tupleAtomExprP :: RelationalMarkerExpr a => Parser (AttributeName, AtomExprBase a)
51tupleAtomExprP = do
56tupleAtomExprP = do
52− attributeName <- identifier
57+ attributeName <- attributeNameP
53 atomExpr <- atomExprP
58 atomExpr <- atomExprP
54 pure (attributeName, atomExpr)
59 pure (attributeName, atomExpr)
55−
60+
56projectP :: RelationalMarkerExpr a => Parser (RelationalExprBase a -> RelationalExprBase a)
61projectP :: RelationalMarkerExpr a => Parser (RelationalExprBase a -> RelationalExprBase a)
57projectP = Project <$> braces attributeListP
62projectP = Project <$> braces attributeListP
58
63
59renameClauseP :: Parser (T.Text, T.Text)
64renameClauseP :: Parser (T.Text, T.Text)
60renameClauseP = do
65renameClauseP = do
61− oldAttr <- identifier
66+ oldAttr <- attributeNameP
62 reservedOp "as"
67 reservedOp "as"
63− newAttr <- identifier
68+ newAttr <- attributeNameP
64 pure (oldAttr, newAttr)
69 pure (oldAttr, newAttr)
65
70
66renameP :: Parser (RelationalExprBase a -> RelationalExprBase a)
71renameP :: Parser (RelationalExprBase a -> RelationalExprBase a)
@@ -69,7 +74,7 @@ renameP = do
69 renameList <- braces (sepBy renameClauseP comma)
74 renameList <- braces (sepBy renameClauseP comma)
70 case renameList of
75 case renameList of
71 [] -> pure (Restrict TruePredicate) --no-op when rename list is empty
76 [] -> pure (Restrict TruePredicate) --no-op when rename list is empty
72− renames ->
77+ renames ->
73 pure $ \expr -> foldl (\acc (oldAttr, newAttr) -> Rename oldAttr newAttr acc) expr renames
78 pure $ \expr -> foldl (\acc (oldAttr, newAttr) -> Rename oldAttr newAttr acc) expr renames
74
79
75whereClauseP :: RelationalMarkerExpr a => Parser (RelationalExprBase a -> RelationalExprBase a)
80whereClauseP :: RelationalMarkerExpr a => Parser (RelationalExprBase a -> RelationalExprBase a)
@@ -79,7 +84,7 @@ groupClauseP :: RelationalMarkerExpr a => Parser (AttributeNamesBase a, T.Text)
79groupClauseP = do
84groupClauseP = do
80 attrs <- braces attributeListP
85 attrs <- braces attributeListP
81 reservedOp "as"
86 reservedOp "as"
82− newAttrName <- identifier
87+ newAttrName <- attributeNameP
83 pure (attrs, newAttrName)
88 pure (attrs, newAttrName)
84
89
85groupP :: RelationalMarkerExpr a => Parser (RelationalExprBase a -> RelationalExprBase a)
90groupP :: RelationalMarkerExpr a => Parser (RelationalExprBase a -> RelationalExprBase a)
@@ -92,27 +97,30 @@ groupP = do
92ungroupP :: Parser (RelationalExprBase a -> RelationalExprBase a)
97ungroupP :: Parser (RelationalExprBase a -> RelationalExprBase a)
93ungroupP = do
98ungroupP = do
94 reservedOp "ungroup"
99 reservedOp "ungroup"
95− rvaAttrName <- identifier
100+ Ungroup <$> attributeNameP
96− pure $ Ungroup rvaAttrName
97
101
98extendP :: RelationalMarkerExpr a => Parser (RelationalExprBase a -> RelationalExprBase a)
102extendP :: RelationalMarkerExpr a => Parser (RelationalExprBase a -> RelationalExprBase a)
99extendP = do
103extendP = do
100 reservedOp ":"
104 reservedOp ":"
101− Extend <$> braces extendTupleExpressionP
105+ extends <- braces (sepBy extendTupleExpressionP comma)
102−
106+ case extends of
107+ [] -> pure (Restrict TruePredicate)
108+ extends' ->
109+ pure $ \expr -> foldl (flip Extend) expr extends'
110+
103semijoinP :: RelationalMarkerExpr a => Parser (RelationalExprBase a -> RelationalExprBase a -> RelationalExprBase a)
111semijoinP :: RelationalMarkerExpr a => Parser (RelationalExprBase a -> RelationalExprBase a -> RelationalExprBase a)
104semijoinP = do
112semijoinP = do
105 reservedOp "semijoin" <|> reservedOp "matching"
113 reservedOp "semijoin" <|> reservedOp "matching"
106− pure (\exprA exprB ->
114+ pure (\exprA exprB ->
107 Project (RelationalExprAttributeNames exprA) (Join exprA exprB))
115 Project (RelationalExprAttributeNames exprA) (Join exprA exprB))
108−
116+
109−antijoinP :: RelationalMarkerExpr a => Parser (RelationalExprBase a -> RelationalExprBase a -> RelationalExprBase a)
117+antijoinP :: RelationalMarkerExpr a => Parser (RelationalExprBase a -> RelationalExprBase a -> RelationalExprBase a)
110antijoinP = do
118antijoinP = do
111 reservedOp "not matching" <|> reservedOp "antijoin"
119 reservedOp "not matching" <|> reservedOp "antijoin"
112 pure (\exprA exprB ->
120 pure (\exprA exprB ->
113 Difference exprA (
121 Difference exprA (
114 Project (RelationalExprAttributeNames exprA) (Join exprA exprB)))
122 Project (RelationalExprAttributeNames exprA) (Join exprA exprB)))
115−
123+
116relOperators :: RelationalMarkerExpr a => [[Operator Parser (RelationalExprBase a)]]
124relOperators :: RelationalMarkerExpr a => [[Operator Parser (RelationalExprBase a)]]
117relOperators = [
125relOperators = [
118 [Postfix projectP],
126 [Postfix projectP],
@@ -125,15 +133,23 @@ relOperators = [
125 [InfixL antijoinP],
133 [InfixL antijoinP],
126 [InfixL (reservedOp "union" >> return Union)],
134 [InfixL (reservedOp "union" >> return Union)],
127 [InfixL (reservedOp "minus" >> return Difference)],
135 [InfixL (reservedOp "minus" >> return Difference)],
128− [InfixN (reservedOp "=" >> return Equals)],
136+ [InfixN (reservedOp "=" >> return Equals),
137+ InfixN (reservedOp "/=" >> return NotEquals)],
129 [Postfix extendP]
138 [Postfix extendP]
130 ]
139 ]
131
140
132relExprP :: RelationalMarkerExpr a => Parser (RelationalExprBase a)
141relExprP :: RelationalMarkerExpr a => Parser (RelationalExprBase a)
133−relExprP = makeExprParser relTerm relOperators
142+relExprP = try withMacroExprP <|> makeExprParser relTerm relOperators
143+
144+--allow for additional characters
145+attributeNameP :: Parser AttributeName
146+attributeNameP = uncapitalizedIdentifier
147+
148+relVarNameP :: Parser RelVarName
149+relVarNameP = uncapitalizedIdentifier
134
150
135relVarP :: RelationalMarkerExpr a => Parser (RelationalExprBase a)
151relVarP :: RelationalMarkerExpr a => Parser (RelationalExprBase a)
136−relVarP = RelationVariable <$> identifier <*> parseMarkerP
152+relVarP = RelationVariable <$> relVarNameP <*> parseMarkerP
137
153
138relTerm :: RelationalMarkerExpr a => Parser (RelationalExprBase a)
154relTerm :: RelationalMarkerExpr a => Parser (RelationalExprBase a)
139relTerm = parens relExprP
155relTerm = parens relExprP
@@ -154,13 +170,13 @@ restrictionPredicateP = makeExprParser predicateTerm predicateOperators
154 <|> relationalBooleanExprP
170 <|> relationalBooleanExprP
155
171
156relationalBooleanExprP :: RelationalMarkerExpr a => Parser (RestrictionPredicateExprBase a)
172relationalBooleanExprP :: RelationalMarkerExpr a => Parser (RestrictionPredicateExprBase a)
157−relationalBooleanExprP =
173+relationalBooleanExprP =
158 --we can't actually detect if the type is relational boolean, so we just pass it to the next phase
174 --we can't actually detect if the type is relational boolean, so we just pass it to the next phase
159 RelationalExprPredicate <$> (parens relExprP <|> relTerm)
175 RelationalExprPredicate <$> (parens relExprP <|> relTerm)
160−
176+
161restrictionAttributeEqualityP :: RelationalMarkerExpr a => Parser (RestrictionPredicateExprBase a)
177restrictionAttributeEqualityP :: RelationalMarkerExpr a => Parser (RestrictionPredicateExprBase a)
162restrictionAttributeEqualityP = do
178restrictionAttributeEqualityP = do
163− attributeName <- identifier
179+ attributeName <- attributeNameP
164 reservedOp "="
180 reservedOp "="
165 AttributeEqualityPredicate attributeName <$> atomExprP
181 AttributeEqualityPredicate attributeName <$> atomExprP
166
182
@@ -177,7 +193,7 @@ extendTupleExpressionP = attributeExtendTupleExpressionP
177
193
178attributeExtendTupleExpressionP :: RelationalMarkerExpr a => Parser (ExtendTupleExprBase a)
194attributeExtendTupleExpressionP :: RelationalMarkerExpr a => Parser (ExtendTupleExprBase a)
179attributeExtendTupleExpressionP = do
195attributeExtendTupleExpressionP = do
180− newAttr <- identifier
196+ newAttr <- attributeNameP
181 reservedOp ":="
197 reservedOp ":="
182 AttributeExtendTupleExpr newAttr <$> atomExprP
198 AttributeExtendTupleExpr newAttr <$> atomExprP
183
199
@@ -189,34 +205,33 @@ consumeAtomExprP consume = try functionAtomExprP <|>
189 try (parens (constructedAtomExprP True)) <|>
205 try (parens (constructedAtomExprP True)) <|>
190 constructedAtomExprP consume <|>
206 constructedAtomExprP consume <|>
191 attributeAtomExprP <|>
207 attributeAtomExprP <|>
192− nakedAtomExprP <|>
208+ try nakedAtomExprP <|>
193 relationalAtomExprP
209 relationalAtomExprP
194
210
195attributeAtomExprP :: Parser (AtomExprBase a)
211attributeAtomExprP :: Parser (AtomExprBase a)
196attributeAtomExprP = do
212attributeAtomExprP = do
197 _ <- string "@"
213 _ <- string "@"
198− AttributeAtomExpr <$> identifier
214+ AttributeAtomExpr <$> attributeNameP
199
215
200nakedAtomExprP :: Parser (AtomExprBase a)
216nakedAtomExprP :: Parser (AtomExprBase a)
201nakedAtomExprP = NakedAtomExpr <$> atomP
217nakedAtomExprP = NakedAtomExpr <$> atomP
202
218
203constructedAtomExprP :: RelationalMarkerExpr a => Bool -> Parser (AtomExprBase a)
219constructedAtomExprP :: RelationalMarkerExpr a => Bool -> Parser (AtomExprBase a)
204constructedAtomExprP consume = do
220constructedAtomExprP consume = do
205− dConsName <- capitalizedIdentifier
221+ dConsName <- dataConstructorNameP
206 dConsArgs <- if consume then sepBy (consumeAtomExprP False) spaceConsumer else pure []
222 dConsArgs <- if consume then sepBy (consumeAtomExprP False) spaceConsumer else pure []
207− marker <- parseMarkerP
208− pure $ ConstructedAtomExpr dConsName dConsArgs marker
223+ ConstructedAtomExpr dConsName dConsArgs <$> parseMarkerP
209−
224+
210-- used only for primitive type parsing ?
225-- used only for primitive type parsing ?
211atomP :: Parser Atom
226atomP :: Parser Atom
212−atomP = stringAtomP <|>
227+atomP = stringAtomP <|>
213− doubleAtomP <|>
228+ doubleAtomP <|>
214− integerAtomP <|>
229+ integerAtomP <|>
215 boolAtomP
230 boolAtomP
216−
231+
217functionAtomExprP :: RelationalMarkerExpr a => Parser (AtomExprBase a)
232functionAtomExprP :: RelationalMarkerExpr a => Parser (AtomExprBase a)
218−functionAtomExprP =
233+functionAtomExprP =
219− FunctionAtomExpr <$> identifier <*> parens (sepBy atomExprP comma) <*> parseMarkerP
234+ FunctionAtomExpr <$> uncapitalizedIdentifier <*> parens (sepBy atomExprP comma) <*> parseMarkerP
220
235
221relationalAtomExprP :: RelationalMarkerExpr a => Parser (AtomExprBase a)
236relationalAtomExprP :: RelationalMarkerExpr a => Parser (AtomExprBase a)
222relationalAtomExprP = RelationAtomExpr <$> relExprP
237relationalAtomExprP = RelationAtomExpr <$> relExprP
@@ -224,7 +239,7 @@ relationalAtomExprP = RelationAtomExpr <$> relExprP
224stringAtomP :: Parser Atom
239stringAtomP :: Parser Atom
225stringAtomP = TextAtom <$> quotedString
240stringAtomP = TextAtom <$> quotedString
226
241
227−doubleAtomP :: Parser Atom
242+doubleAtomP :: Parser Atom
228doubleAtomP = DoubleAtom <$> try float
243doubleAtomP = DoubleAtom <$> try float
229
244
230integerAtomP :: Parser Atom
245integerAtomP :: Parser Atom
@@ -232,8 +247,28 @@ integerAtomP = IntegerAtom <$> integer
232
247
233boolAtomP :: Parser Atom
248boolAtomP :: Parser Atom
234boolAtomP = do
249boolAtomP = do
235− val <- char 't' <|> char 'f'
250+ v <- identifier
251+ if v == "t" || v == "f" then
236− return $ BoolAtom (val == 't')
252+ pure $ BoolAtom (v == "t")
237−
253+ else
254+ fail "invalid boolAtom"
255+
256+
238relationAtomExprP :: RelationalMarkerExpr a => Parser (AtomExprBase a)
257relationAtomExprP :: RelationalMarkerExpr a => Parser (AtomExprBase a)
239relationAtomExprP = RelationAtomExpr <$> makeRelationP
258relationAtomExprP = RelationAtomExpr <$> makeRelationP
259+
260+withMacroExprP :: RelationalMarkerExpr a => Parser (RelationalExprBase a)
261+withMacroExprP = do
262+ reservedOp "with"
263+ views <- parens (sepBy1 createMacroP comma)
264+ With views <$> relExprP
265+
266+createMacroP :: RelationalMarkerExpr a => Parser (WithNameExprBase a, RelationalExprBase a)
267+createMacroP = do
268+ name <- identifier
269+ reservedOp "as"
270+ expr <- relExprP
271+ marker <- parseMarkerP
272+ pure (WithNameExpr name marker, expr)
273+
274+
src/bin/TutorialD/Interpreter/SchemaOperator.hs+3−5
@@ -1,7 +1,5 @@
1module TutorialD.Interpreter.SchemaOperator where
1module TutorialD.Interpreter.SchemaOperator where
2import Text.Megaparsec
2import Text.Megaparsec
3−import Text.Megaparsec.Text
4−
5import ProjectM36.Base
3import ProjectM36.Base
6import ProjectM36.IsomorphicSchema
4import ProjectM36.IsomorphicSchema
7import ProjectM36.Session
5import ProjectM36.Session
@@ -44,7 +42,7 @@ isoRestrictP = do
44 reserved "isorestrict"
42 reserved "isorestrict"
45 relVarIn <- qrelVarP
43 relVarIn <- qrelVarP
46 relvarsOut <- isoRestrictOutRelVarsP
44 relvarsOut <- isoRestrictOutRelVarsP
47− IsoRestrict <$> pure relVarIn <*> restrictionPredicateP <*> pure relvarsOut
45+ IsoRestrict relVarIn <$> restrictionPredicateP <*> pure relvarsOut
48
46
49isoRestrictOutRelVarsP :: Parser (RelVarName, RelVarName)
47isoRestrictOutRelVarsP :: Parser (RelVarName, RelVarName)
50isoRestrictOutRelVarsP = (,) <$> qrelVarP <*> qrelVarP
48isoRestrictOutRelVarsP = (,) <$> qrelVarP <*> qrelVarP
@@ -57,7 +55,7 @@ isoUnionP = do
57 reserved "isounion"
55 reserved "isounion"
58 relVarsIn <- isoUnionInRelVarsP
56 relVarsIn <- isoUnionInRelVarsP
59 relVarsOut <- qrelVarP
57 relVarsOut <- qrelVarP
60− IsoUnion <$> pure relVarsIn <*> restrictionPredicateP <*> pure relVarsOut
58+ IsoUnion relVarsIn <$> restrictionPredicateP <*> pure relVarsOut
61
59
62isoRenameP :: Parser SchemaIsomorph
60isoRenameP :: Parser SchemaIsomorph
63isoRenameP = do
61isoRenameP = do
@@ -76,4 +74,4 @@ isoUnionInRelVarsP = (,) <$> qrelVarP <*> qrelVarP
76evalSchemaOperator :: SessionId -> Connection -> SchemaOperator -> IO (Either RelationalError ())
74evalSchemaOperator :: SessionId -> Connection -> SchemaOperator -> IO (Either RelationalError ())
77evalSchemaOperator sessionId conn (ModifySchemaExpr expr) = executeSchemaExpr sessionId conn expr
75evalSchemaOperator sessionId conn (ModifySchemaExpr expr) = executeSchemaExpr sessionId conn expr
78evalSchemaOperator sessionId conn (SetCurrentSchema sname) = setCurrentSchemaName sessionId conn sname
76evalSchemaOperator sessionId conn (SetCurrentSchema sname) = setCurrentSchemaName sessionId conn sname
79−
77+
src/bin/TutorialD/Interpreter/TransGraphRelationalOperator.hs+2−5
@@ -1,4 +1,4 @@
1−{-# LANGUAGE TypeSynonymInstances, FlexibleInstances #-}
1+{-# LANGUAGE FlexibleInstances #-}
2{-# OPTIONS_GHC -fno-warn-orphans #-}
2{-# OPTIONS_GHC -fno-warn-orphans #-}
3module TutorialD.Interpreter.TransGraphRelationalOperator where
3module TutorialD.Interpreter.TransGraphRelationalOperator where
4import ProjectM36.TransGraphRelationalExpression
4import ProjectM36.TransGraphRelationalExpression
@@ -9,9 +9,6 @@ import qualified ProjectM36.Client as C
9import TutorialD.Interpreter.Base
9import TutorialD.Interpreter.Base
10import TutorialD.Interpreter.RelationalExpr
10import TutorialD.Interpreter.RelationalExpr
11
11
12−import Text.Megaparsec
13−import Text.Megaparsec.Text
14−
15import qualified Data.Text as T
12import qualified Data.Text as T
16
13
17instance RelationalMarkerExpr TransactionIdLookup where
14instance RelationalMarkerExpr TransactionIdLookup where
@@ -46,4 +43,4 @@ evalTransGraphRelationalOp sessionId conn (ShowTransGraphRelation expr) = do
46 case res of
43 case res of
47 Left err -> pure $ DisplayErrorResult $ T.pack (show err)
44 Left err -> pure $ DisplayErrorResult $ T.pack (show err)
48 Right rel -> pure $ DisplayRelationResult rel
45 Right rel -> pure $ DisplayRelationResult rel
49−
46+
src/bin/TutorialD/Interpreter/TransactionGraphOperator.hs+15−13
@@ -1,11 +1,10 @@
1{-# LANGUAGE GADTs #-}
1{-# LANGUAGE GADTs #-}
2module TutorialD.Interpreter.TransactionGraphOperator where
2module TutorialD.Interpreter.TransactionGraphOperator where
3import TutorialD.Interpreter.Base
3import TutorialD.Interpreter.Base
4−import Text.Megaparsec.Text
5−import Text.Megaparsec
6import ProjectM36.TransactionGraph hiding (autoMergeToHead)
4import ProjectM36.TransactionGraph hiding (autoMergeToHead)
7−import ProjectM36.Client
5+import ProjectM36.Client as C
8import ProjectM36.Base
6import ProjectM36.Base
7+import ProjectM36.Relation (relationTrue)
9import Data.Functor
8import Data.Functor
10
9
11data ConvenienceTransactionGraphOperator = AutoMergeToHead MergeStrategy HeadName
10data ConvenienceTransactionGraphOperator = AutoMergeToHead MergeStrategy HeadName
@@ -63,20 +62,18 @@ mergeTransactionStrategyP :: Parser MergeStrategy
63mergeTransactionStrategyP = (reserved "union" $> UnionMergeStrategy) <|>
62mergeTransactionStrategyP = (reserved "union" $> UnionMergeStrategy) <|>
64 (do
63 (do
65 reserved "selectedbranch"
64 reserved "selectedbranch"
66− branch <- identifier
67− pure (SelectedBranchMergeStrategy branch)) <|>
65+ SelectedBranchMergeStrategy <$> identifier) <|>
68 (do
66 (do
69 reserved "unionpreferbranch"
67 reserved "unionpreferbranch"
70− branch <- identifier
71− pure (UnionPreferMergeStrategy branch))
68+ UnionPreferMergeStrategy <$> identifier)
72
69
73mergeTransactionsP :: Parser TransactionGraphOperator
70mergeTransactionsP :: Parser TransactionGraphOperator
74mergeTransactionsP = do
71mergeTransactionsP = do
75 reservedOp ":mergetrans"
72 reservedOp ":mergetrans"
76− strategy <- mergeTransactionStrategyP
73+ MergeTransactions <$> mergeTransactionStrategyP <*> identifier <*> identifier
77− headA <- identifier
74+
78− headB <- identifier
75+validateMerkleHashesP :: Parser ROTransactionGraphOperator
79− pure (MergeTransactions strategy headA headB)
76+validateMerkleHashesP = reservedOp ":validatemerklehashes" $> ValidateMerkleHashes
80
77
81transactionGraphOpP :: Parser TransactionGraphOperator
78transactionGraphOpP :: Parser TransactionGraphOperator
82transactionGraphOpP =
79transactionGraphOpP =
@@ -90,7 +87,7 @@ transactionGraphOpP =
90 <|> mergeTransactionsP
87 <|> mergeTransactionsP
91
88
92roTransactionGraphOpP :: Parser ROTransactionGraphOperator
89roTransactionGraphOpP :: Parser ROTransactionGraphOperator
93−roTransactionGraphOpP = showGraphP
90+roTransactionGraphOpP = showGraphP <|> validateMerkleHashesP
94
91
95
92
96
93
@@ -108,6 +105,11 @@ interpretOps newUUID trans@(DisconnectedTransaction _ context) transGraph instri
108
105
109evalROGraphOp :: SessionId -> Connection -> ROTransactionGraphOperator -> IO (Either RelationalError Relation)
106evalROGraphOp :: SessionId -> Connection -> ROTransactionGraphOperator -> IO (Either RelationalError Relation)
110evalROGraphOp sessionId conn ShowGraph = transactionGraphAsRelation sessionId conn
107evalROGraphOp 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)
111
113
112evalConvenienceGraphOp :: SessionId -> Connection -> ConvenienceTransactionGraphOperator -> IO (Either RelationalError ())
114evalConvenienceGraphOp :: SessionId -> Connection -> ConvenienceTransactionGraphOperator -> IO (Either RelationalError ())
113−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+13−11
@@ -1,7 +1,6 @@
1--parse type and data constructors
1--parse type and data constructors
2module TutorialD.Interpreter.Types where
2module TutorialD.Interpreter.Types where
3import ProjectM36.Base
3import ProjectM36.Base
4−import Text.Megaparsec.Text
5import Text.Megaparsec
4import Text.Megaparsec
6import TutorialD.Interpreter.Base
5import TutorialD.Interpreter.Base
7
6
@@ -10,23 +9,28 @@ class RelationalMarkerExpr a where
10
9
11instance RelationalMarkerExpr () where
10instance RelationalMarkerExpr () where
12 parseMarkerP = pure ()
11 parseMarkerP = pure ()
13−
12+
13+typeConstructorNameP :: Parser TypeConstructorName
14+typeConstructorNameP = capitalizedIdentifier
15+
16+dataConstructorNameP :: Parser DataConstructorName
17+dataConstructorNameP = capitalizedIdentifier
18+
14-- | Upper case names are type names while lower case names are polymorphic typeconstructor arguments.
19-- | Upper case names are type names while lower case names are polymorphic typeconstructor arguments.
15-- data *Either a b* = Left a | Right b
20-- data *Either a b* = Left a | Right b
16typeConstructorDefP :: Parser TypeConstructorDef
21typeConstructorDefP :: Parser TypeConstructorDef
17−typeConstructorDefP = ADTypeConstructorDef <$> capitalizedIdentifier <*> typeVarNamesP
22+typeConstructorDefP = ADTypeConstructorDef <$> typeConstructorNameP <*> typeVarNamesP
18
23
19typeVarNamesP :: Parser [TypeVarName]
24typeVarNamesP :: Parser [TypeVarName]
20typeVarNamesP = many uncapitalizedIdentifier
25typeVarNamesP = many uncapitalizedIdentifier
21
26
22-- data Either a b = *Left a* | *Right b*
27-- data Either a b = *Left a* | *Right b*
23dataConstructorDefP :: Parser DataConstructorDef
28dataConstructorDefP :: Parser DataConstructorDef
24−dataConstructorDefP = DataConstructorDef <$> capitalizedIdentifier <*> many dataConstructorDefArgP
29+dataConstructorDefP = DataConstructorDef <$> typeConstructorNameP <*> many dataConstructorDefArgP
25
30
26-- data *Either a b* = Left *a* | Right *b*
31-- data *Either a b* = Left *a* | Right *b*
27dataConstructorDefArgP :: Parser DataConstructorDefArg
32dataConstructorDefArgP :: Parser DataConstructorDefArg
28−dataConstructorDefArgP = parens (DataConstructorDefTypeConstructorArg <$> typeConstructorP) <|>
33+dataConstructorDefArgP = DataConstructorDefTypeConstructorArg <$> (monoTypeConstructorP <|> parens typeConstructorP) <|>
29− DataConstructorDefTypeConstructorArg <$> typeConstructorP <|>
30 DataConstructorDefTypeVarNameArg <$> uncapitalizedIdentifier
34 DataConstructorDefTypeVarNameArg <$> uncapitalizedIdentifier
31
35
32-- relation{a Int} in type construction (no tuples parsed)
36-- relation{a Int} in type construction (no tuples parsed)
@@ -41,17 +45,15 @@ makeAttributeExprsP = braces (sepBy attributeAndTypeNameP comma)
41
45
42attributeAndTypeNameP :: RelationalMarkerExpr a => Parser (AttributeExprBase a)
46attributeAndTypeNameP :: RelationalMarkerExpr a => Parser (AttributeExprBase a)
43attributeAndTypeNameP = AttributeAndTypeNameExpr <$> identifier <*> typeConstructorP <*> parseMarkerP
47attributeAndTypeNameP = AttributeAndTypeNameExpr <$> identifier <*> typeConstructorP <*> parseMarkerP
44−
45
48
46-- *Either Int Text*, *Int*
49-- *Either Int Text*, *Int*
47typeConstructorP :: Parser TypeConstructor
50typeConstructorP :: Parser TypeConstructor
48typeConstructorP = relationTypeConstructorP <|>
51typeConstructorP = relationTypeConstructorP <|>
49− TypeVariable <$> uncapitalizedIdentifier <|>
50− ADTypeConstructor <$> capitalizedIdentifier <*> many (parens typeConstructorP <|>
52+ ADTypeConstructor <$> capitalizedIdentifier <*> many (monoTypeConstructorP <|> parens typeConstructorP) <|>
51− monoTypeConstructorP)
53+ monoTypeConstructorP
52
54
53monoTypeConstructorP :: Parser TypeConstructor
55monoTypeConstructorP :: Parser TypeConstructor
54−monoTypeConstructorP = ADTypeConstructor <$> capitalizedIdentifier <*> pure [] <|>
56+monoTypeConstructorP = ADTypeConstructor <$> typeConstructorNameP <*> pure [] <|>
55 TypeVariable <$> uncapitalizedIdentifier
57 TypeVariable <$> uncapitalizedIdentifier
56
58
57
59
src/bin/TutorialD/tutd.hs+16−1
@@ -5,9 +5,13 @@ import ProjectM36.Client
5import ProjectM36.Server.ParseArgs
5import ProjectM36.Server.ParseArgs
6import ProjectM36.Server
6import ProjectM36.Server
7import System.IO
7import System.IO
8+import GHC.IO.Encoding
8import Options.Applicative
9import Options.Applicative
9import System.Exit
10import System.Exit
11+import Control.Monad
12+#if __GLASGOW_HASKELL__ < 804
10import Data.Monoid
13import Data.Monoid
14+#endif
11import Data.Maybe
15import Data.Maybe
12import qualified Data.Text as T
16import qualified Data.Text as T
13
17
@@ -23,6 +27,7 @@ parseArgs = LocalInterpreterConfig <$> parsePersistenceStrategy <*> parseHeadNam
23parseHeadName :: Parser HeadName
27parseHeadName :: Parser HeadName
24parseHeadName = option auto (long "head" <>
28parseHeadName = option auto (long "head" <>
25 help "Start session at head name." <>
29 help "Start session at head name." <>
30+ metavar "GRAPH HEAD NAME" <>
26 value "master"
31 value "master"
27 )
32 )
28
33
@@ -31,8 +36,10 @@ parseNodeId = createNodeId <$>
31 strOption (long "host" <>
36 strOption (long "host" <>
32 short 'h' <>
37 short 'h' <>
33 help "Remote host name" <>
38 help "Remote host name" <>
39+ metavar "HOSTNAME" <>
34 value "127.0.0.1") <*>
40 value "127.0.0.1") <*>
35 option auto (long "port" <>
41 option auto (long "port" <>
42+ metavar "PORT NUMBER" <>
36 short 'p' <>
43 short 'p' <>
37 help "Remote port" <>
44 help "Remote port" <>
38 value defaultServerPort)
45 value defaultServerPort)
@@ -41,11 +48,12 @@ parseNodeId = createNodeId <$>
41parseTutDExec :: Parser (Maybe TutorialDExec)
48parseTutDExec :: Parser (Maybe TutorialDExec)
42parseTutDExec = optional $ strOption (long "exec-tutd" <>
49parseTutDExec = optional $ strOption (long "exec-tutd" <>
43 short 'e' <>
50 short 'e' <>
51+ metavar "TUTORIALD" <>
44 help "Execute TutorialD expression and exit"
52 help "Execute TutorialD expression and exit"
45 )
53 )
46
54
47opts :: ParserInfo InterpreterConfig
55opts :: ParserInfo InterpreterConfig
48−opts = info parseArgs idm
56+opts = info (parseArgs <**> helpOption) idm
49
57
50connectionInfoForConfig :: InterpreterConfig -> ConnectionInfo
58connectionInfoForConfig :: InterpreterConfig -> ConnectionInfo
51connectionInfoForConfig (LocalInterpreterConfig pStrategy _ _ ghcPkgPaths _) = InProcessConnectionInfo pStrategy outputNotificationCallback ghcPkgPaths
59connectionInfoForConfig (LocalInterpreterConfig pStrategy _ _ ghcPkgPaths _) = InProcessConnectionInfo pStrategy outputNotificationCallback ghcPkgPaths
@@ -80,8 +88,15 @@ printWelcome = do
80 putStrLn "A full tutorial is available at:"
88 putStrLn "A full tutorial is available at:"
81 putStrLn "https://github.com/agentm/project-m36/blob/master/docs/tutd_tutorial.markdown"
89 putStrLn "https://github.com/agentm/project-m36/blob/master/docs/tutd_tutorial.markdown"
82
90
91+-- | 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.
92+setLocaleIfNecessary :: IO ()
93+setLocaleIfNecessary = do
94+ l <- getLocaleEncoding
95+ when (textEncodingName l == "ASCII") (setLocaleEncoding utf8)
96+
83main :: IO ()
97main :: IO ()
84main = do
98main = do
99+ setLocaleIfNecessary
85 interpreterConfig <- execParser opts
100 interpreterConfig <- execParser opts
86 let connInfo = connectionInfoForConfig interpreterConfig
101 let connInfo = connectionInfoForConfig interpreterConfig
87 fscheck <- checkFSType (checkFSForConfig interpreterConfig) (fromMaybe NoPersistence (persistenceStrategyForConfig interpreterConfig))
102 fscheck <- checkFSType (checkFSForConfig interpreterConfig) (fromMaybe NoPersistence (persistenceStrategyForConfig interpreterConfig))
src/bin/benchmark/Handles.hs+26−16
@@ -4,16 +4,17 @@ import ProjectM36.Client
4import ProjectM36.Persist
4import ProjectM36.Persist
5import Options.Applicative
5import Options.Applicative
6import TutorialD.Interpreter
6import TutorialD.Interpreter
7−import TutorialD.Interpreter.Base
7+import TutorialD.Interpreter.Base hiding (Parser, option)
8import qualified Data.Text as T
8import qualified Data.Text as T
9−import Text.Megaparsec hiding (option)
9+#if __GLASGOW_HASKELL__ < 804
10import Data.Monoid
10import Data.Monoid
11+#endif
11import Control.Monad
12import Control.Monad
12
13
13data HandlesArgs = HandlesArgs {
14data HandlesArgs = HandlesArgs {
14 openCloseCount :: Int,
15 openCloseCount :: Int,
15 transactionCount :: Int,
16 transactionCount :: Int,
16− dbdir :: FilePath,
17+ dbdir :: FilePath,
17 tutdSetup :: String,
18 tutdSetup :: String,
18 tutdIterate :: String
19 tutdIterate :: String
19 }
20 }
@@ -39,13 +40,13 @@ parseTutdIterate = strOption (short 'i' <> long "iterate-tutd" <> value "update
39main :: IO ()
40main :: IO ()
40main = do
41main = do
41 args <- execParser $ info (helper <*> parseArgs) fullDesc
42 args <- execParser $ info (helper <*> parseArgs) fullDesc
42− replicateM_ (openCloseCount args) (runOpenClose
43+ replicateM_ (openCloseCount args) (runOpenClose
43 (T.pack (tutdSetup args))
44 (T.pack (tutdSetup args))
44 (T.pack (tutdIterate args))
45 (T.pack (tutdIterate args))
45− (transactionCount args)
46+ (transactionCount args)
46 (dbdir args))
47 (dbdir args))
47−
48+
48−runOpenClose :: T.Text -> T.Text -> Int -> FilePath -> IO ()
49+runOpenClose :: T.Text -> T.Text -> Int -> FilePath -> IO ()
49runOpenClose tutdSetup' tutdIterate' tCount dbdir' = do
50runOpenClose tutdSetup' tutdIterate' tCount dbdir' = do
50 let connInfo = InProcessConnectionInfo (MinimalPersistence dbdir') emptyNotificationCallback []
51 let connInfo = InProcessConnectionInfo (MinimalPersistence dbdir') emptyNotificationCallback []
51 eConn <- connectProjectM36 connInfo
52 eConn <- connectProjectM36 connInfo
@@ -55,7 +56,7 @@ runOpenClose tutdSetup' tutdIterate' tCount dbdir' = do
55 eSess <- createSessionAtHead conn "master"
56 eSess <- createSessionAtHead conn "master"
56 case eSess of
57 case eSess of
57 Left err -> error (show err)
58 Left err -> error (show err)
58− Right session ->
59+ Right session ->
59 --database setup
60 --database setup
60 case parseTutorialD tutdSetup' of
61 case parseTutorialD tutdSetup' of
61 Left err -> error (show err)
62 Left err -> error (show err)
@@ -63,14 +64,19 @@ runOpenClose tutdSetup' tutdIterate' tCount dbdir' = do
63 res <- evalTutorialD session conn UnsafeEvaluation parsed
64 res <- evalTutorialD session conn UnsafeEvaluation parsed
64 case res of
65 case res of
65 DisplayErrorResult err -> error (T.unpack err)
66 DisplayErrorResult err -> error (T.unpack err)
66− DisplayParseErrorResult _ err -> error (parseErrorPretty err)
67+ DisplayParseErrorResult _ err ->
68+#if MIN_VERSION_megaparsec(7,0,0)
69+ error (errorBundlePretty err)
70+#else
71+ error (parseErrorPretty err)
72+#endif
67− _ -> do
73+ _ -> do
68 replicateM_ tCount (runTransaction tutdIterate' session conn)
74 replicateM_ tCount (runTransaction tutdIterate' session conn)
69 close conn
75 close conn
70 printFdCount
76 printFdCount
71−
77+
72runTransaction :: T.Text -> SessionId -> Connection -> IO ()
78runTransaction :: T.Text -> SessionId -> Connection -> IO ()
73−runTransaction tutdIterate' sess conn =
79+runTransaction tutdIterate' sess conn =
74 --run tutd on every iteration
80 --run tutd on every iteration
75 case parseTutorialD tutdIterate' of
81 case parseTutorialD tutdIterate' of
76 Left err -> error (show err)
82 Left err -> error (show err)
@@ -78,10 +84,14 @@ runTransaction tutdIterate' sess conn =
78 res <- evalTutorialD sess conn UnsafeEvaluation parsed
84 res <- evalTutorialD sess conn UnsafeEvaluation parsed
79 case res of
85 case res of
80 DisplayErrorResult err -> error (T.unpack err)
86 DisplayErrorResult err -> error (T.unpack err)
81− DisplayParseErrorResult _ err -> error (parseErrorPretty err)
87+ DisplayParseErrorResult _ err ->
88+#if MIN_VERSION_megaparsec(7,0,0)
89+ error (errorBundlePretty err)
90+#else
91+ error (parseErrorPretty err)
92+#endif
82− _ -> do
93+ _ -> do
83− eErr <- commit sess conn
94+ eErr <- commit sess conn
84 case eErr of
95 case eErr of
85 Left err -> error (show err)
96 Left err -> error (show err)
86 Right _ -> printFdCount
97 Right _ -> printFdCount
87−
src/bin/benchmark/bigrel.hs+42−19
@@ -1,33 +1,39 @@
1−{-# LANGUAGE FlexibleInstances #-}
1+{-# LANGUAGE FlexibleInstances, CPP #-}
2{-# OPTIONS_GHC -fno-warn-orphans #-}
2{-# OPTIONS_GHC -fno-warn-orphans #-}
3import ProjectM36.Base
3import ProjectM36.Base
4import ProjectM36.Relation
4import ProjectM36.Relation
5import ProjectM36.DateExamples
5import ProjectM36.DateExamples
6import ProjectM36.Error
6import ProjectM36.Error
7+import ProjectM36.StaticOptimizer
7import qualified ProjectM36.Attribute as A
8import qualified ProjectM36.Attribute as A
8import qualified Data.Text as T
9import qualified Data.Text as T
9−import ProjectM36.Relation.Show.CSV
10+--import ProjectM36.Relation.Show.CSV
10import ProjectM36.Relation.Show.HTML
11import ProjectM36.Relation.Show.HTML
11−import TutorialD.Interpreter.DatabaseContextExpr (interpretDatabaseContextExpr)
12import ProjectM36.RelationalExpression
12import ProjectM36.RelationalExpression
13+import ProjectM36.TransactionGraph
13−import qualified Data.HashSet as HS
14+--import qualified Data.HashSet as HS
14−import qualified Data.ByteString.Lazy.Char8 as BS
15+--import qualified Data.ByteString.Lazy.Char8 as BS
15−import qualified Data.IntMap as IM
16+--import qualified Data.IntMap as IM
16−import qualified Data.Hashable as Hash
17+--import qualified Data.Hashable as Hash
17import qualified Data.Vector as V
18import qualified Data.Vector as V
18import Options.Applicative
19import Options.Applicative
19−import qualified Data.Map as M
20import qualified Data.Text.IO as TIO
20import qualified Data.Text.IO as TIO
21import System.IO
21import System.IO
22−import Control.Monad.State
23import Control.DeepSeq
22import Control.DeepSeq
24import Data.Text hiding (map)
23import Data.Text hiding (map)
24+import Data.Time.Clock
25+import Data.UUID.V4
26+#if __GLASGOW_HASKELL__ < 804
25import Data.Monoid
27import Data.Monoid
28+#endif
26
29
30+
31+{-
27dumpcsv :: Relation -> IO ()
32dumpcsv :: Relation -> IO ()
28dumpcsv rel = case relationAsCSV rel of
33dumpcsv rel = case relationAsCSV rel of
29 Left err -> hPrint stderr err
34 Left err -> hPrint stderr err
30 Right bsData -> BS.putStrLn bsData
35 Right bsData -> BS.putStrLn bsData
36+-}
31
37
32data BigrelArgs = BigrelArgs Int Int Text
38data BigrelArgs = BigrelArgs Int Int Text
33
39
@@ -58,46 +64,63 @@ matrixRun (BigrelArgs attributeCount tupleCount tutd) =
58 Right rel -> if tutd == "" then
64 Right rel -> if tutd == "" then
59 putStrLn "Done."
65 putStrLn "Done."
60 else do
66 else do
67+ now <- getCurrentTime
68+ tid <- nextRandom
61 let setx = Assign "x" (ExistingRelation (force rel))
69 let setx = Assign "x" (ExistingRelation (force rel))
62− (context,_,_) = execState (evalDatabaseContextExpr setx) (freshDatabaseState dateExamples)
70+ graph = bootstrapTransactionGraph now tid dateExamples
63− interpreted = interpretDatabaseContextExpr context tutd
71+ env = mkDatabaseContextEvalEnv tid graph
72+ eNewState = runDatabaseContextEvalMonad dateExamples env (optimizeAndEvalDatabaseContextExpr True setx)
64 --plan = interpretRODatabaseContextOp context $ ":showplan " ++ tutd
73 --plan = interpretRODatabaseContextOp context $ ":showplan " ++ tutd
65 --displayOpResult plan
74 --displayOpResult plan
66− case interpreted of
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
67− Right context' -> TIO.putStrLn $ relationAsHTML (relationVariables context' M.! "x")
80+ TIO.putStrLn $ relationAsHTML x
68 Left err -> hPrint stderr err
81 Left err -> hPrint stderr err
69
82
70−
83+{-
71intmapMatrixRun :: IO ()
84intmapMatrixRun :: IO ()
72intmapMatrixRun = do
85intmapMatrixRun = do
73 let matrix = intmapMatrixRelation 100 100000
86 let matrix = intmapMatrixRelation 100 100000
74 print matrix
87 print matrix
88+-}
75
89
76--compare IntMap speed and size
90--compare IntMap speed and size
77--this is about 3 times faster (9 minutes) for 10x100000 and uses 800 MB
91--this is about 3 times faster (9 minutes) for 10x100000 and uses 800 MB
92+{-
78intmapMatrixRelation :: Int -> Int -> HS.HashSet (IM.IntMap Atom)
93intmapMatrixRelation :: Int -> Int -> HS.HashSet (IM.IntMap Atom)
79intmapMatrixRelation attributeCount tupleCount = HS.fromList $ map mapper [0..tupleCount]
94intmapMatrixRelation attributeCount tupleCount = HS.fromList $ map mapper [0..tupleCount]
80 where
95 where
81 mapper tupCount = IM.fromList $ map (\c-> (c, IntAtom (fromIntegral tupCount))) [0..attributeCount]
96 mapper tupCount = IM.fromList $ map (\c-> (c, IntAtom (fromIntegral tupCount))) [0..attributeCount]
97+-}
98+-- instance Hash.Hashable (IM.IntMap Atom) where
99+-- hashWithSalt salt tupMap = Hash.hashWithSalt salt (show tupMap)
82
100
83−instance Hash.Hashable (IM.IntMap Atom) where
101+{-
84− hashWithSalt salt tupMap = Hash.hashWithSalt salt (show tupMap)
85−
86vectorMatrixRun :: IO ()
102vectorMatrixRun :: IO ()
87vectorMatrixRun = do
103vectorMatrixRun = do
88 let matrix = vectorMatrixRelation 100 100000
104 let matrix = vectorMatrixRelation 100 100000
89 print matrix
105 print matrix
106+-}
107+-- 20 s 90 MBs- a clear win- ideal size is 10 * 100000 * 8 bytes = 80 MB! without IntAtom wrapper
108+--with IntAtom wrapper: 1m12s 90 MB
109+{-
110+
90
111
91-- 20 s 90 MBs- a clear win- ideal size is 10 * 100000 * 8 bytes = 80 MB! without IntAtom wrapper
112-- 20 s 90 MBs- a clear win- ideal size is 10 * 100000 * 8 bytes = 80 MB! without IntAtom wrapper
92--with IntAtom wrapper: 1m12s 90 MB
113--with IntAtom wrapper: 1m12s 90 MB
114+{-
115+
93vectorMatrixRelation :: Int -> Int -> HS.HashSet (V.Vector Atom)
116vectorMatrixRelation :: Int -> Int -> HS.HashSet (V.Vector Atom)
94vectorMatrixRelation attributeCount tupleCount = HS.fromList $ map mapper [0..tupleCount]
117vectorMatrixRelation attributeCount tupleCount = HS.fromList $ map mapper [0..tupleCount]
95 where
118 where
96 mapper tupCount = V.replicate attributeCount (IntAtom (fromIntegral tupCount))
119 mapper tupCount = V.replicate attributeCount (IntAtom (fromIntegral tupCount))
97−
120+-}
98instance Hash.Hashable (V.Vector Atom) where
121instance Hash.Hashable (V.Vector Atom) where
99 hashWithSalt salt vec = Hash.hashWithSalt salt (show vec)
122 hashWithSalt salt vec = Hash.hashWithSalt salt (show vec)
100−
123+-}
101-- returns a relation with tupleCount tuples with a set of integer attributes attributesCount long
124-- returns a relation with tupleCount tuples with a set of integer attributes attributesCount long
102-- this is useful for performance and resource usage testing
125-- this is useful for performance and resource usage testing
103matrixRelation :: Int -> Int -> Either RelationalError Relation
126matrixRelation :: Int -> Int -> Either RelationalError Relation
src/lib/ProjectM36/.ghcideleted−6
@@ -1,6 +0,0 @@
1−import Fake.Provider.Person.EN_US
2−import Test.QuickCheck.Arbitrary
3−import Test.QuickCheck
4−import System.Random
5−import Conversion
6−import System.Random.TF.Gen
src/lib/ProjectM36/Arbitrary.hs+2−13
@@ -10,8 +10,9 @@ import ProjectM36.Attribute (atomType)
10import ProjectM36.DataConstructorDef as DCD
10import ProjectM36.DataConstructorDef as DCD
11import ProjectM36.DataTypes.Interval
11import ProjectM36.DataTypes.Interval
12import qualified Data.Vector as V
12import qualified Data.Vector as V
13−import Data.Text (Text,pack)
13+import Data.Text (Text)
14import Test.QuickCheck
14import Test.QuickCheck
15+import Test.QuickCheck.Instances ()
15import qualified Data.ByteString.Char8 as B
16import qualified Data.ByteString.Char8 as B
16import Data.Time
17import Data.Time
17import Control.Monad.Reader
18import Control.Monad.Reader
@@ -75,18 +76,6 @@ maybeToRight :: b -> Maybe a -> Either b a
75maybeToRight _ (Just x) = Right x
76maybeToRight _ (Just x) = Right x
76maybeToRight y Nothing = Left y
77maybeToRight y Nothing = Left y
77
78
78−instance Arbitrary Text where
79− arbitrary = pack <$> elements (map (replicate 3) ['A'..'Z'])
80−
81−instance Arbitrary Day where
82− arbitrary = ModifiedJulianDay <$> (arbitrary :: Gen Integer)
83−
84−instance Arbitrary UTCTime where
85− arbitrary = UTCTime <$> arbitrary <*> (secondsToDiffTime <$> choose(0,86400))
86−
87−instance Arbitrary B.ByteString where
88− arbitrary = B.pack <$> (arbitrary :: Gen String)
89−
90arbitraryRelationTuple :: Attributes -> WithTCMap Gen (Either RelationalError RelationTuple)
79arbitraryRelationTuple :: Attributes -> WithTCMap Gen (Either RelationalError RelationTuple)
91arbitraryRelationTuple attris = do
80arbitraryRelationTuple attris = do
92 tcMap <- ask
81 tcMap <- ask
src/lib/ProjectM36/Atom.hs+2
@@ -3,7 +3,9 @@ import ProjectM36.Base
3import ProjectM36.Error
3import ProjectM36.Error
4import ProjectM36.DataTypes.Interval
4import ProjectM36.DataTypes.Interval
5import qualified Data.Text as T
5import qualified Data.Text as T
6+#if __GLASGOW_HASKELL__ < 804
6import Data.Monoid
7import Data.Monoid
8+#endif
7
9
8relationForAtom :: Atom -> Either RelationalError Relation
10relationForAtom :: Atom -> Either RelationalError Relation
9relationForAtom (RelationAtom rel) = Right rel
11relationForAtom (RelationAtom rel) = Right rel
src/lib/ProjectM36/AtomFunction.hs+18−2
@@ -1,3 +1,4 @@
1+{-# LANGUAGE CPP #-}
1module ProjectM36.AtomFunction where
2module ProjectM36.AtomFunction where
2import ProjectM36.Base
3import ProjectM36.Base
3import ProjectM36.Error
4import ProjectM36.Error
@@ -8,7 +9,8 @@ import ProjectM36.ScriptSession
8import qualified ProjectM36.Attribute as A
9import qualified ProjectM36.Attribute as A
9import qualified Data.HashSet as HS
10import qualified Data.HashSet as HS
10import qualified Data.Text as T
11import qualified Data.Text as T
11−
12+import qualified Data.ByteString.Lazy as BL
13+import Data.Binary as B
12
14
13foldAtomFuncType :: AtomType -> AtomType -> [AtomType]
15foldAtomFuncType :: AtomType -> AtomType -> [AtomType]
14--the underscore in the attribute name means that any attributes are acceptable
16--the underscore in the attribute name means that any attributes are acceptable
@@ -72,7 +74,11 @@ createScriptedAtomFunction funcName argsType retType = AddAtomFunction funcName
72 retType]])
74 retType]])
73
75
74loadAtomFunctions :: ModName -> FuncName -> FilePath -> IO (Either LoadSymbolError [AtomFunction])
76loadAtomFunctions :: ModName -> FuncName -> FilePath -> IO (Either LoadSymbolError [AtomFunction])
77+#ifdef PM36_HASKELL_SCRIPTING
75loadAtomFunctions = loadFunction
78loadAtomFunctions = loadFunction
79+#else
80+loadAtomFunctions _ _ _ = pure (Left LoadSymbolError)
81+#endif
76
82
77atomFunctionsAsRelation :: AtomFunctions -> Either RelationalError Relation
83atomFunctionsAsRelation :: AtomFunctions -> Either RelationalError Relation
78atomFunctionsAsRelation funcs = mkRelationFromList attrs tups
84atomFunctionsAsRelation funcs = mkRelationFromList attrs tups
@@ -81,4 +87,14 @@ atomFunctionsAsRelation funcs = mkRelationFromList attrs tups
81 Attribute "arguments" TextAtomType]
87 Attribute "arguments" TextAtomType]
82 atomFuncToTuple aFunc = [TextAtom (atomFuncName aFunc),
88 atomFuncToTuple aFunc = [TextAtom (atomFuncName aFunc),
83 TextAtom (atomFuncTypeToText aFunc)]
89 TextAtom (atomFuncTypeToText aFunc)]
84− atomFuncTypeToText aFunc = T.intercalate " -> " (map prettyAtomType (atomFuncType aFunc))
90+ atomFuncTypeToText aFunc = T.intercalate " -> " (map prettyAtomType (atomFuncType aFunc))
91+
92+--for calculating the merkle hash
93+hashBytes :: AtomFunction -> BL.ByteString
94+hashBytes func = mconcat [B.encode (atomFuncName func),
95+ B.encode (atomFuncType func),
96+ bodyBin
97+ ]
98+ where
99+ bodyBin = case atomFuncBody func of
100+ AtomFunctionBody mScript _ -> B.encode mScript
src/lib/ProjectM36/AtomFunctions/Basic.hs+2
@@ -6,6 +6,7 @@ import ProjectM36.DataTypes.Either
6import ProjectM36.DataTypes.Maybe
6import ProjectM36.DataTypes.Maybe
7import ProjectM36.DataTypes.Interval
7import ProjectM36.DataTypes.Interval
8import ProjectM36.DataTypes.ByteString
8import ProjectM36.DataTypes.ByteString
9+import ProjectM36.DataTypes.NonEmptyList
9import ProjectM36.AtomFunctions.Primitive
10import ProjectM36.AtomFunctions.Primitive
10import ProjectM36.AtomFunction
11import ProjectM36.AtomFunction
11import ProjectM36.DataTypes.List
12import ProjectM36.DataTypes.List
@@ -19,6 +20,7 @@ basicAtomFunctions = HS.unions [primitiveAtomFunctions,
19 eitherAtomFunctions,
20 eitherAtomFunctions,
20 maybeAtomFunctions,
21 maybeAtomFunctions,
21 listAtomFunctions,
22 listAtomFunctions,
23+ nonEmptyListAtomFunctions,
22 bytestringAtomFunctions,
24 bytestringAtomFunctions,
23 intervalAtomFunctions]
25 intervalAtomFunctions]
24
26
src/lib/ProjectM36/AtomType.hs+138−32
@@ -31,6 +31,7 @@ findDataConstructor dName = foldr tConsFolder Nothing
31 [dCons] -> Just dCons
31 [dCons] -> Just dCons
32 _ -> error "More than one data constructor with the same name found"
32 _ -> error "More than one data constructor with the same name found"
33
33
34+{-
34-- | Scan the atom types and return the resultant ConstructedAtomType or error.
35-- | Scan the atom types and return the resultant ConstructedAtomType or error.
35-- Used in typeFromAtomExpr to validate argument types.
36-- Used in typeFromAtomExpr to validate argument types.
36atomTypeForDataConstructorName :: DataConstructorName -> [AtomType] -> TypeConstructorMapping -> Either RelationalError AtomType
37atomTypeForDataConstructorName :: DataConstructorName -> [AtomType] -> TypeConstructorMapping -> Either RelationalError AtomType
@@ -38,8 +39,12 @@ atomTypeForDataConstructorName :: DataConstructorName -> [AtomType] -> TypeConst
38atomTypeForDataConstructorName dConsName atomTypesIn tConsList =
39atomTypeForDataConstructorName dConsName atomTypesIn tConsList =
39 case findDataConstructor dConsName tConsList of
40 case findDataConstructor dConsName tConsList of
40 Nothing -> Left (NoSuchDataConstructorError dConsName)
41 Nothing -> Left (NoSuchDataConstructorError dConsName)
41− Just (tCons, dCons) ->
42+ Just (tCons, dCons) -> do
43+ dConsVars <- resolveDataConstructorTypeVars dCons atomTypesIn tConsList
44+ let tConsVars = M.fromList (map TypeVariableType (TCD.typeVars tCons))
45+ allVars = M.union dConsVars tConsVars
42− ConstructedAtomType (TCD.name tCons) <$> resolveDataConstructorTypeVars dCons atomTypesIn tConsList
46+ ConstructedAtomType (TCD.name tCons) <$> allVars
47+-}
43
48
44atomTypeForDataConstructorDefArg :: DataConstructorDefArg -> AtomType -> TypeConstructorMapping -> Either RelationalError AtomType
49atomTypeForDataConstructorDefArg :: DataConstructorDefArg -> AtomType -> TypeConstructorMapping -> Either RelationalError AtomType
45atomTypeForDataConstructorDefArg (DataConstructorDefTypeConstructorArg tCons) aType tConss = do
50atomTypeForDataConstructorDefArg (DataConstructorDefTypeConstructorArg tCons) aType tConss = do
@@ -49,15 +54,20 @@ atomTypeForDataConstructorDefArg (DataConstructorDefTypeConstructorArg tCons) aT
49atomTypeForDataConstructorDefArg (DataConstructorDefTypeVarNameArg _) aType _ = Right aType --any type is OK
54atomTypeForDataConstructorDefArg (DataConstructorDefTypeVarNameArg _) aType _ = Right aType --any type is OK
50
55
51-- | Used to determine if the atom arguments can be used with the data constructor.
56-- | Used to determine if the atom arguments can be used with the data constructor.
52−-- | This is the entry point for type-checking from RelationalExpression.hs.
57+-- | This is the entry point for type-checking from RelationalExpression.hs
53atomTypeForDataConstructor :: TypeConstructorMapping -> DataConstructorName -> [AtomType] -> Either RelationalError AtomType
58atomTypeForDataConstructor :: TypeConstructorMapping -> DataConstructorName -> [AtomType] -> Either RelationalError AtomType
54atomTypeForDataConstructor tConss dConsName atomArgTypes =
59atomTypeForDataConstructor tConss dConsName atomArgTypes =
55 --lookup the data constructor
60 --lookup the data constructor
56 case findDataConstructor dConsName tConss of
61 case findDataConstructor dConsName tConss of
57 Nothing -> Left (NoSuchDataConstructorError dConsName)
62 Nothing -> Left (NoSuchDataConstructorError dConsName)
58− Just (tCons, dCons) ->
63+ Just (tCons, dCons) -> do
59 --validate that the type constructor arguments are fulfilled in the data constructor
64 --validate that the type constructor arguments are fulfilled in the data constructor
60− ConstructedAtomType (TCD.name tCons) <$> resolveDataConstructorTypeVars dCons atomArgTypes tConss
65+ dConsVars <- resolveDataConstructorTypeVars dCons atomArgTypes tConss
66+ let tConsVars = M.fromList (map (\v -> (v, TypeVariableType v)) (TCD.typeVars tCons))
67+ allVars = M.union dConsVars tConsVars
68+ unresolvedType = ConstructedAtomType (TCD.name tCons) allVars
69+ --validateAtomType unresolvedType tConss -- do not validate here because the type may not be fully resolved at this point
70+ pure unresolvedType
61
71
62-- | Walks the data and type constructors to extract the type variable map.
72-- | Walks the data and type constructors to extract the type variable map.
63resolveDataConstructorTypeVars :: DataConstructorDef -> [AtomType] -> TypeConstructorMapping -> Either RelationalError TypeVarMap
73resolveDataConstructorTypeVars :: DataConstructorDef -> [AtomType] -> TypeConstructorMapping -> Either RelationalError TypeVarMap
@@ -71,10 +81,11 @@ resolveDataConstructorTypeVars dCons@(DataConstructorDef _ defArgs) aTypeArgs tC
71 --if any two maps have the same key and different values, this indicates a type arg mismatch
81 --if any two maps have the same key and different values, this indicates a type arg mismatch
72 let typeVarMapFolder valMap acc = case acc of
82 let typeVarMapFolder valMap acc = case acc of
73 Left err -> Left err
83 Left err -> Left err
74− Right accMap -> if accMap `M.isSubmapOf` valMap then
84+ Right accMap ->
75− Right (M.union accMap valMap)
85+ case resolveAtomTypesInTypeVarMap valMap accMap of
76− else
77− Left (DataConstructorTypeVarsMismatch (DCD.name dCons) accMap valMap)
86+ Left (TypeConstructorTypeVarMissing _) -> Left (DataConstructorTypeVarsMismatch (DCD.name dCons) accMap valMap)
87+ Left err -> Left err
88+ Right ok -> pure ok
78 case foldr typeVarMapFolder (Right M.empty) maps of
89 case foldr typeVarMapFolder (Right M.empty) maps of
79 Left err -> Left err
90 Left err -> Left err
80 Right typeVarMaps -> pure typeVarMaps
91 Right typeVarMaps -> pure typeVarMaps
@@ -128,16 +139,37 @@ resolveAttributeExprTypeVars (AttributeAndTypeNameExpr _ tCons _) aType tConsMap
128
139
129-- check that type vars on the right also appear on the left
140-- check that type vars on the right also appear on the left
130-- check that the data constructor names are unique
141-- check that the data constructor names are unique
131−validateTypeConstructorDef :: TypeConstructorDef -> [DataConstructorDef] -> [RelationalError]
142+validateTypeConstructorDef :: TypeConstructorDef -> [DataConstructorDef] -> TypeConstructorMapping -> Either RelationalError ()
132−validateTypeConstructorDef tConsDef dConsList = execWriter $ do
143+validateTypeConstructorDef tConsDef dConsList tConsMap = do
133 let duplicateDConsNames = dupes (L.sort (map DCD.name dConsList))
144 let duplicateDConsNames = dupes (L.sort (map DCD.name dConsList))
134− mapM_ tell [map DataConstructorNameInUseError duplicateDConsNames]
145+ unless (null duplicateDConsNames) (Left (someErrors (map DataConstructorNameInUseError duplicateDConsNames)))
135 let leftSideVars = S.fromList (TCD.typeVars tConsDef)
146 let leftSideVars = S.fromList (TCD.typeVars tConsDef)
136 rightSideVars = S.unions (map DCD.typeVars dConsList)
147 rightSideVars = S.unions (map DCD.typeVars dConsList)
137 varsDiff = S.difference leftSideVars rightSideVars
148 varsDiff = S.difference leftSideVars rightSideVars
138− mapM_ tell [map DataConstructorUsesUndeclaredTypeVariable (S.toList varsDiff)]
149+ when (S.size varsDiff > 0) (Left (someErrors (map DataConstructorUsesUndeclaredTypeVariable (S.toList varsDiff))))
139− pure ()
150+ mapM_ (\dConsDef -> validateDataConstructorDef dConsDef tConsDef tConsMap) dConsList
140−
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 ()
141
173
142atomTypeForTypeConstructor :: TypeConstructor -> TypeConstructorMapping -> TypeVarMap -> Either RelationalError AtomType
174atomTypeForTypeConstructor :: TypeConstructor -> TypeConstructorMapping -> TypeVarMap -> Either RelationalError AtomType
143atomTypeForTypeConstructor = atomTypeForTypeConstructorValidate False
175atomTypeForTypeConstructor = atomTypeForTypeConstructorValidate False
@@ -180,7 +212,6 @@ isValidAtomTypeForTypeConstructor (ConstructedAtomType tConsName _) (ADTypeConst
180isValidAtomTypeForTypeConstructor (RelationAtomType attrs) (RelationAtomTypeConstructor attrExprs) tConsMap = do
212isValidAtomTypeForTypeConstructor (RelationAtomType attrs) (RelationAtomTypeConstructor attrExprs) tConsMap = do
181 evaldAtomTypes <- mapM (\expr -> atomTypeForAttributeExpr expr tConsMap M.empty) attrExprs
213 evaldAtomTypes <- mapM (\expr -> atomTypeForAttributeExpr expr tConsMap M.empty) attrExprs
182 mapM_ (uncurry resolveAtomType) (zip (map A.atomType (V.toList attrs)) evaldAtomTypes)
214 mapM_ (uncurry resolveAtomType) (zip (map A.atomType (V.toList attrs)) evaldAtomTypes)
183− pure ()
184isValidAtomTypeForTypeConstructor aType tCons _ = Left (AtomTypeTypeConstructorReconciliationError aType (TC.name tCons))
215isValidAtomTypeForTypeConstructor aType tCons _ = Left (AtomTypeTypeConstructorReconciliationError aType (TC.name tCons))
185
216
186findTypeConstructor :: TypeConstructorName -> TypeConstructorMapping -> Maybe (TypeConstructorDef, [DataConstructorDef])
217findTypeConstructor :: TypeConstructorName -> TypeConstructorMapping -> Maybe (TypeConstructorDef, [DataConstructorDef])
@@ -190,15 +221,29 @@ findTypeConstructor name = foldr tConsFolder Nothing
190 Just (tCons, dConsList)
221 Just (tCons, dConsList)
191 else
222 else
192 accum
223 accum
193−
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
194resolveAtomType :: AtomType -> AtomType -> Either RelationalError AtomType
233resolveAtomType :: AtomType -> AtomType -> Either RelationalError AtomType
195resolveAtomType (ConstructedAtomType tConsName resolvedTypeVarMap) (ConstructedAtomType _ unresolvedTypeVarMap) =
234resolveAtomType (ConstructedAtomType tConsName resolvedTypeVarMap) (ConstructedAtomType _ unresolvedTypeVarMap) =
196− ConstructedAtomType tConsName <$> resolveAtomTypesInTypeVarMap resolvedTypeVarMap unresolvedTypeVarMap
235+ ConstructedAtomType tConsName <$> resolveAtomTypesInTypeVarMap resolvedTypeVarMap unresolvedTypeVarMap
197resolveAtomType typeFromRelation unresolvedType = if typeFromRelation == unresolvedType then
236resolveAtomType typeFromRelation unresolvedType = if typeFromRelation == unresolvedType then
198 Right typeFromRelation
237 Right typeFromRelation
199 else
238 else
200 Left (AtomTypeMismatchError typeFromRelation unresolvedType)
239 Left (AtomTypeMismatchError typeFromRelation unresolvedType)
201
240
241+{-
242+--walk an `AtomType` and apply the type variables in the map
243+resolveAtomTypeVars :: TypeVarMap -> AtomType -> AtomType
244+resolveAtomTypeVars tvMap typ@(TypeVariableType nam) = fromMaybe typ (M.lookup nam tvMap)
245+resolveAtomTypeVars tvMap (RelationAtomType relAttrs) =
246+-}
202-- this could be optimized to reduce new tuple creation
247-- this could be optimized to reduce new tuple creation
203resolveAtomTypesInTypeVarMap :: TypeVarMap -> TypeVarMap -> Either RelationalError TypeVarMap
248resolveAtomTypesInTypeVarMap :: TypeVarMap -> TypeVarMap -> Either RelationalError TypeVarMap
204resolveAtomTypesInTypeVarMap resolvedTypeMap unresolvedTypeMap = do
249resolveAtomTypesInTypeVarMap resolvedTypeMap unresolvedTypeMap = do
@@ -215,29 +260,42 @@ resolveAtomTypesInTypeVarMap resolvedTypeMap unresolvedTypeMap = do
215 let resolveTypePair resKey resType =
260 let resolveTypePair resKey resType =
216 -- if the key is missing in the unresolved type map, then fill it in with the value from the resolved map
261 -- if the key is missing in the unresolved type map, then fill it in with the value from the resolved map
217 case M.lookup resKey unresolvedTypeMap of
262 case M.lookup resKey unresolvedTypeMap of
218− Just unresType -> case unresType of
263+ Just unresType -> case unresType of
219 --do we need to recurse for RelationAtomType?
264 --do we need to recurse for RelationAtomType?
220 subType@(ConstructedAtomType _ _) -> do
265 subType@(ConstructedAtomType _ _) -> do
221 resSubType <- resolveAtomType resType subType
266 resSubType <- resolveAtomType resType subType
222 pure (resKey, resSubType)
267 pure (resKey, resSubType)
223− otherType -> pure (resKey, otherType)
268+ TypeVariableType _ -> pure (resKey, resType)
269+ typ -> if typ == resType then
270+ pure (resKey, resType)
271+ else
272+ Left $ AtomTypeMismatchError typ resType
224 Nothing ->
273 Nothing ->
225 pure (resKey, resType) --swipe the missing type var from the expected map
274 pure (resKey, resType) --swipe the missing type var from the expected map
226 tVarList <- mapM (uncurry resolveTypePair) (M.toList resolvedTypeMap)
275 tVarList <- mapM (uncurry resolveTypePair) (M.toList resolvedTypeMap)
227 pure (M.fromList tVarList)
276 pure (M.fromList tVarList)
228
277
229-- | See notes at `resolveTypesInTuple`. The typeFromRelation must not include any wildcards.
278-- | See notes at `resolveTypesInTuple`. The typeFromRelation must not include any wildcards.
230−resolveTypeInAtom :: AtomType -> Atom -> Either RelationalError Atom
279+resolveTypeInAtom :: AtomType -> Atom -> TypeConstructorMapping -> Either RelationalError Atom
231−resolveTypeInAtom typeFromRelation atomIn@(ConstructedAtom dConsName _ args) = do
280+resolveTypeInAtom typeFromRelation@(ConstructedAtomType _ tvMap) atomIn@(ConstructedAtom dConsName _ args) tConss = do
232 newType <- resolveAtomType typeFromRelation (atomTypeForAtom atomIn)
281 newType <- resolveAtomType typeFromRelation (atomTypeForAtom atomIn)
282+ case findDataConstructor dConsName tConss of
283+ Nothing -> -- the atom may have been constructed using a constructor function without a public data constructor, no further resolution is possible
284+ pure atomIn
285+ Just (_, dConsDef) -> do
286+ atomArgTypes <- resolvedAtomTypesForDataConstructorDefArgs tConss tvMap dConsDef
287+ newArgs <- mapM (\(atom, atomTyp) -> resolveTypeInAtom atomTyp atom tConss) (zip args atomArgTypes)
233− pure (ConstructedAtom dConsName newType args)
288+ pure (ConstructedAtom dConsName newType newArgs)
289+resolveTypeInAtom (RelationAtomType attrs) (RelationAtom (Relation _ tupSet)) tConss = do
290+ let newTups = mapM (resolveTypesInTuple attrs tConss) (asList tupSet)
291+ RelationAtom . Relation attrs . RelationTupleSet <$> newTups
234−resolveTypeInAtom _ atom = Right atom
292+resolveTypeInAtom _ atom _ = Right atom
235
293
236-- | When creating a tuple, the data constructor may not complete the type constructor arguments, so the wildcard "TypeVar x" fills in the type constructor's argument. The tuple type must be resolved before it can be part of a relation, however.
294-- | When creating a tuple, the data constructor may not complete the type constructor arguments, so the wildcard "TypeVar x" fills in the type constructor's argument. The tuple type must be resolved before it can be part of a relation, however.
237-- 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.
295-- 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.
238−resolveTypesInTuple :: Attributes -> RelationTuple -> Either RelationalError RelationTuple
296+resolveTypesInTuple :: Attributes -> TypeConstructorMapping -> RelationTuple -> Either RelationalError RelationTuple
239−resolveTypesInTuple resolvedAttrs (RelationTuple _ tupAtoms) = do
297+resolveTypesInTuple resolvedAttrs tConss (RelationTuple _ tupAtoms) = do
240− newAtoms <- mapM (\(atom, resolvedType) -> resolveTypeInAtom resolvedType atom) (zip (V.toList tupAtoms) $ map A.atomType (V.toList resolvedAttrs))
298+ newAtoms <- mapM (\(atom, resolvedType) -> resolveTypeInAtom resolvedType atom tConss) (zip (V.toList tupAtoms) $ map A.atomType (V.toList resolvedAttrs))
241 Right (RelationTuple resolvedAttrs (V.fromList newAtoms))
299 Right (RelationTuple resolvedAttrs (V.fromList newAtoms))
242
300
243-- | Validate that the type is provided with complete type variables for type constructors.
301-- | Validate that the type is provided with complete type variables for type constructors.
@@ -252,17 +310,38 @@ validateAtomType typ@(ConstructedAtomType tConsName tVarMap) tConss =
252 if not (S.null diff) then
310 if not (S.null diff) then
253 Left $ TypeConstructorTypeVarsMismatch expectedTyVarNames actualTyVarNames
311 Left $ TypeConstructorTypeVarsMismatch expectedTyVarNames actualTyVarNames
254 else
312 else
255− Right ()
313+ validateTypeVarMap tVarMap tConss
256 _ -> Right ()
314 _ -> Right ()
257−validateAtomType (RelationAtomType attrs) tConss = do
315+validateAtomType (RelationAtomType attrs) tConss =
258 mapM_ (\attr ->
316 mapM_ (\attr ->
259 validateAtomType (A.atomType attr) tConss) (V.toList attrs)
317 validateAtomType (A.atomType attr) tConss) (V.toList attrs)
260− pure ()
261validateAtomType (TypeVariableType x) _ = Left (TypeConstructorTypeVarMissing x)
318validateAtomType (TypeVariableType x) _ = Left (TypeConstructorTypeVarMissing x)
262validateAtomType _ _ = pure ()
319validateAtomType _ _ = pure ()
263
320
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.atomType) (V.toList attrs)
329+
330+--ensure that all type vars are fully resolved
331+validateTypeVarMap :: TypeVarMap -> TypeConstructorMapping -> Either RelationalError ()
332+validateTypeVarMap tvMap tConss = mapM_ (`validateAtomType` tConss) $ M.elems tvMap
333+
264validateTuple :: RelationTuple -> TypeConstructorMapping -> Either RelationalError ()
334validateTuple :: RelationTuple -> TypeConstructorMapping -> Either RelationalError ()
265−validateTuple (RelationTuple _ atoms) tConss = mapM_ (\a -> validateAtomType (atomTypeForAtom a) tConss) atoms
335+validateTuple (RelationTuple _ atoms) tConss = mapM_ (`validateAtom` tConss) atoms
336+
337+--ensure that all types are fully resolved
338+validateAtom :: Atom -> TypeConstructorMapping -> Either RelationalError ()
339+validateAtom (RelationAtom (Relation _ tupSet)) tConss = mapM_ (`validateTuple` tConss) (asList tupSet)
340+validateAtom (ConstructedAtom _ dConsType atomArgs) tConss = do
341+ validateAtomType dConsType tConss
342+ mapM_ (`validateAtom` tConss) atomArgs
343+validateAtom _ _ = pure ()
344+
266
345
267-- | Determine if two types are equal or compatible (including special handling for TypeVar x).
346-- | Determine if two types are equal or compatible (including special handling for TypeVar x).
268atomTypeVerify :: AtomType -> AtomType -> Either RelationalError AtomType
347atomTypeVerify :: AtomType -> AtomType -> Either RelationalError AtomType
@@ -288,7 +367,12 @@ atomTypeVerify x y = if x == y then
288
367
289-- | Determine if two typeVars are logically compatible.
368-- | Determine if two typeVars are logically compatible.
290typeVarMapsVerify :: TypeVarMap -> TypeVarMap -> Bool
369typeVarMapsVerify :: TypeVarMap -> TypeVarMap -> Bool
291−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)
292
376
293prettyAtomType :: AtomType -> T.Text
377prettyAtomType :: AtomType -> T.Text
294prettyAtomType (RelationAtomType attrs) = "relation {" `T.append` T.intercalate "," (map prettyAttribute (V.toList attrs)) `T.append` "}"
378prettyAtomType (RelationAtomType attrs) = "relation {" `T.append` T.intercalate "," (map prettyAttribute (V.toList attrs)) `T.append` "}"
@@ -347,3 +431,25 @@ resolvedAtomTypeForDataConstructorDefArg _ tvMap (DataConstructorDefTypeVarNameA
347 Nothing -> Left (DataConstructorUsesUndeclaredTypeVariable tvName)
431 Nothing -> Left (DataConstructorUsesUndeclaredTypeVariable tvName)
348 Just typ -> Right typ
432 Just typ -> Right typ
349
433
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+ RelationAtomType attrs -> isResolvedAttributes attrs
446+ ConstructedAtomType _ tvMap -> all isResolvedType (M.elems tvMap)
447+ TypeVariableType _ -> False
448+
449+isResolvedAttributes :: Attributes -> Bool
450+isResolvedAttributes attrs = all isResolvedAttribute (V.toList attrs)
451+
452+isResolvedAttribute :: Attribute -> Bool
453+isResolvedAttribute = isResolvedType . A.atomType
454+
455+--given two AtomTypes x,y
src/lib/ProjectM36/Atomable.hs+69−41
@@ -1,23 +1,25 @@
1{-# LANGUAGE DefaultSignatures, TypeFamilies, TypeOperators, PolyKinds, FlexibleInstances, ScopedTypeVariables, FlexibleContexts #-}
1{-# LANGUAGE DefaultSignatures, TypeFamilies, TypeOperators, PolyKinds, FlexibleInstances, ScopedTypeVariables, FlexibleContexts #-}
2+{-# OPTIONS_GHC -fno-warn-orphans #-}
2module ProjectM36.Atomable where
3module ProjectM36.Atomable where
3--http://stackoverflow.com/questions/13448361/type-families-with-ghc-generics-or-data-data
4--http://stackoverflow.com/questions/13448361/type-families-with-ghc-generics-or-data-data
4--instances to marshal Haskell ADTs to ConstructedAtoms and back
5--instances to marshal Haskell ADTs to ConstructedAtoms and back
5import ProjectM36.Base
6import ProjectM36.Base
6−import ProjectM36.DataTypes.Primitive
7import ProjectM36.DataTypes.List
7import ProjectM36.DataTypes.List
8+import ProjectM36.DataTypes.NonEmptyList
8import ProjectM36.DataTypes.Maybe
9import ProjectM36.DataTypes.Maybe
9import ProjectM36.DataTypes.Either
10import ProjectM36.DataTypes.Either
10import GHC.Generics
11import GHC.Generics
11import qualified Data.Map as M
12import qualified Data.Map as M
12import qualified Data.Text as T
13import qualified Data.Text as T
14+import qualified Data.Vector as V
13import Control.DeepSeq (NFData)
15import Control.DeepSeq (NFData)
14import Data.Binary
16import Data.Binary
15import Control.Applicative
17import Control.Applicative
16import Data.Time.Calendar
18import Data.Time.Calendar
17import Data.ByteString (ByteString)
19import Data.ByteString (ByteString)
18import Data.Time.Clock
20import Data.Time.Clock
19−import Data.Maybe
20import Data.Proxy
21import Data.Proxy
22+import qualified Data.List.NonEmpty as NE
21
23
22--also add haskell scripting atomable support
24--also add haskell scripting atomable support
23--rename this module to Atomable along with test
25--rename this module to Atomable along with test
@@ -52,9 +54,9 @@ class (Eq a, NFData a, Binary a, Show a) => Atomable a where
52 toAtomType _ = toAtomTypeG (from (undefined :: a))
54 toAtomType _ = toAtomTypeG (from (undefined :: a))
53
55
54 -- | Creates DatabaseContextExpr necessary to load the type constructor and data constructor into the database.
56 -- | Creates DatabaseContextExpr necessary to load the type constructor and data constructor into the database.
55− toAddTypeExpr :: Proxy a -> DatabaseContextExpr
57+ toAddTypeExpr :: proxy a -> DatabaseContextExpr
56 default toAddTypeExpr :: (Generic a, AtomableG (Rep a)) => proxy a -> DatabaseContextExpr
58 default toAddTypeExpr :: (Generic a, AtomableG (Rep a)) => proxy a -> DatabaseContextExpr
57− toAddTypeExpr _ = toAddTypeExprG (from (undefined :: a)) (toAtomType (Proxy :: Proxy a))
59+ toAddTypeExpr _ = toAddTypeExprG (from (error "insufficient laziness" :: a)) (toAtomType (Proxy :: Proxy a))
58
60
59instance Atomable Integer where
61instance Atomable Integer where
60 toAtom = IntegerAtom
62 toAtom = IntegerAtom
@@ -146,15 +148,27 @@ instance (Atomable a, Atomable b) => Atomable (Either a b) where
146--convert to ADT list
148--convert to ADT list
147instance Atomable a => Atomable [a] where
149instance Atomable a => Atomable [a] where
148 toAtom [] = ConstructedAtom "Empty" (listAtomType (toAtomType (Proxy :: Proxy a))) []
150 toAtom [] = ConstructedAtom "Empty" (listAtomType (toAtomType (Proxy :: Proxy a))) []
149− toAtom (x:xs) = ConstructedAtom "Cons" (listAtomType (toAtomType (Proxy :: Proxy a))) (map toAtom (x:xs))
151+ toAtom (x:xs) = ConstructedAtom "Cons" (listAtomType (toAtomType (Proxy :: Proxy a))) (toAtom x: [toAtom xs])
150
152
151 fromAtom (ConstructedAtom "Empty" _ _) = []
153 fromAtom (ConstructedAtom "Empty" _ _) = []
152− fromAtom (ConstructedAtom "Cons" _ (x:xs)) = fromAtom x:map fromAtom xs
154+ fromAtom (ConstructedAtom "Cons" _ [x,y]) = fromAtom x:fromAtom y
153 fromAtom _ = error "improper fromAtom [a]"
155 fromAtom _ = error "improper fromAtom [a]"
154
156
155 toAtomType _ = ConstructedAtomType "List" (M.singleton "a" (toAtomType (Proxy :: Proxy a)))
157 toAtomType _ = ConstructedAtomType "List" (M.singleton "a" (toAtomType (Proxy :: Proxy a)))
156 toAddTypeExpr _ = NoOperation
158 toAddTypeExpr _ = NoOperation
157
159
160+instance Atomable a => Atomable (NE.NonEmpty a) where
161+ toAtom (x NE.:| []) = ConstructedAtom "NECons" (nonEmptyListAtomType (toAtomType (Proxy :: Proxy a))) [toAtom x]
162+ toAtom (x NE.:| xs) = ConstructedAtom "NECons" (nonEmptyListAtomType (toAtomType (Proxy :: Proxy a))) (map toAtom (x:xs))
163+ fromAtom _ = error "improper fromAtom (NonEmptyList a)"
164+
165+ toAtomType _ = ConstructedAtomType "NonEmptyList" (M.singleton "a" (toAtomType (Proxy :: Proxy a)))
166+ toAddTypeExpr _ = NoOperation
167+
168+#if !MIN_VERSION_binary(0,8,4)
169+instance Binary a => Binary (NE.NonEmpty a)
170+#endif
171+
158-- Generics
172-- Generics
159class AtomableG g where
173class AtomableG g where
160 --type AtomTG g
174 --type AtomTG g
@@ -170,17 +184,17 @@ class AtomableG g where
170instance (Datatype c, AtomableG a) => AtomableG (M1 D c a) where
184instance (Datatype c, AtomableG a) => AtomableG (M1 D c a) where
171 toAtomG (M1 v) = toAtomG v
185 toAtomG (M1 v) = toAtomG v
172 fromAtomG atom args = M1 <$> fromAtomG atom args
186 fromAtomG atom args = M1 <$> fromAtomG atom args
173− toAtomsG = undefined
187+ toAtomsG = error "invalid toAtomsG in M1 D"
174 toAtomTypeG _ = ConstructedAtomType (T.pack typeName) M.empty -- generics don't allow us to get the type constructor variables- alternatives?
188 toAtomTypeG _ = ConstructedAtomType (T.pack typeName) M.empty -- generics don't allow us to get the type constructor variables- alternatives?
175 where
189 where
176 typeName = datatypeName (undefined :: M1 D c a x)
190 typeName = datatypeName (undefined :: M1 D c a x)
177− toAddTypeExprG (M1 v) (ConstructedAtomType tcName _) = AddTypeConstructor tcDef dataConstructors
191+ toAddTypeExprG ~(M1 v) (ConstructedAtomType tcName _) = AddTypeConstructor tcDef dataConstructors
178 where
192 where
179 tcDef = ADTypeConstructorDef tcName []
193 tcDef = ADTypeConstructorDef tcName []
180 dataConstructors = getConstructorsG v
194 dataConstructors = getConstructorsG v
181 toAddTypeExprG _ _ = NoOperation
195 toAddTypeExprG _ _ = NoOperation
182− getConstructorsG (M1 v) = getConstructorsG v
196+ getConstructorsG ~(M1 v) = getConstructorsG v
183− getConstructorArgsG = undefined
197+ getConstructorArgsG = error "invalid getConstructorArgsG in M1 D"
184
198
185--constructor metadata
199--constructor metadata
186instance (Constructor c, AtomableG a) => AtomableG (M1 C c a) where
200instance (Constructor c, AtomableG a) => AtomableG (M1 C c a) where
@@ -195,11 +209,11 @@ instance (Constructor c, AtomableG a) => AtomableG (M1 C c a) where
195 Nothing
209 Nothing
196 where
210 where
197 dName = T.pack (conName (undefined :: M1 C c a x))
211 dName = T.pack (conName (undefined :: M1 C c a x))
198− fromAtomG _ _ = error "unsupported generic traversal"
212+ fromAtomG _ _ = error "invalid fromAtomG in M1 C"
199− toAtomsG = undefined
213+ toAtomsG = error "invalid toAtomsG in M1 C"
200− toAtomTypeG = undefined
214+ toAtomTypeG = error "invalid toAtomTypeG in M1 C"
201− toAddTypeExprG = undefined
215+ toAddTypeExprG = error "invalid toAddTypeExprG in M1 C"
202− getConstructorsG (M1 v) = [DataConstructorDef (T.pack dName) dArgs]
216+ getConstructorsG ~(M1 v) = [DataConstructorDef (T.pack dName) dArgs]
203 where
217 where
204 dName = conName (undefined :: M1 C c a x)
218 dName = conName (undefined :: M1 C c a x)
205 dArgs = getConstructorArgsG v
219 dArgs = getConstructorArgsG v
@@ -211,9 +225,9 @@ instance (Selector c, AtomableG a) => AtomableG (M1 S c a) where
211 fromAtomG atom args = M1 <$> fromAtomG atom args
225 fromAtomG atom args = M1 <$> fromAtomG atom args
212 toAtomsG (M1 v) = toAtomsG v
226 toAtomsG (M1 v) = toAtomsG v
213 toAtomTypeG (M1 v) = toAtomTypeG v
227 toAtomTypeG (M1 v) = toAtomTypeG v
214− toAddTypeExprG _ _ = undefined
228+ toAddTypeExprG = error "invalid toAddTypeExprG in M1 S"
215− getConstructorsG = undefined
229+ getConstructorsG = error "invalid getConstructorsG in M1 S"
216− getConstructorArgsG (M1 v) = getConstructorArgsG v
230+ getConstructorArgsG ~(M1 v) = getConstructorArgsG v
217
231
218-- field data metadata
232-- field data metadata
219instance (Atomable a) => AtomableG (K1 c a) where
233instance (Atomable a) => AtomableG (K1 c a) where
@@ -223,48 +237,62 @@ instance (Atomable a) => AtomableG (K1 c a) where
223 headatom [] = error "no more atoms for constructor!"
237 headatom [] = error "no more atoms for constructor!"
224 toAtomsG (K1 v) = [toAtom v]
238 toAtomsG (K1 v) = [toAtom v]
225 toAtomTypeG _ = toAtomType (Proxy :: Proxy a)
239 toAtomTypeG _ = toAtomType (Proxy :: Proxy a)
226− toAddTypeExprG _ _ = undefined
240+ toAddTypeExprG = error "invalid toAddTypeExprG in K1"
227− getConstructorsG = undefined
241+ getConstructorsG = error "invalid getConstructorsG in K1"
228− getConstructorArgsG (K1 _) = [DataConstructorDefTypeConstructorArg tCons]
242+ getConstructorArgsG ~(K1 _) = [DataConstructorDefTypeConstructorArg tCons]
229 where
243 where
230− tCons = PrimitiveTypeConstructor primitiveATypeName primitiveAType
231− primitiveAType = toAtomType (Proxy :: Proxy a)
244+ tCons = typeToTypeConstructor $ toAtomType (Proxy :: Proxy a)
232− primitiveATypeName = fromMaybe (error ("primitive type missing: " ++ show primitiveAType)) (foldr (\(PrimitiveTypeConstructorDef name typ, _) acc -> if typ == primitiveAType then Just name else acc) Nothing primitiveTypeConstructorMapping)
245+
233−
246+typeToTypeConstructor :: AtomType -> TypeConstructor
247+typeToTypeConstructor x@IntAtomType = PrimitiveTypeConstructor "Int" x
248+typeToTypeConstructor x@IntegerAtomType = PrimitiveTypeConstructor "Integer" x
249+typeToTypeConstructor x@DoubleAtomType = PrimitiveTypeConstructor "Double" x
250+typeToTypeConstructor x@TextAtomType = PrimitiveTypeConstructor "Text" x
251+typeToTypeConstructor x@DayAtomType = PrimitiveTypeConstructor "Day" x
252+typeToTypeConstructor x@DateTimeAtomType = PrimitiveTypeConstructor "DateTime" x
253+typeToTypeConstructor x@ByteStringAtomType = PrimitiveTypeConstructor "ByteString" x
254+typeToTypeConstructor x@BoolAtomType = PrimitiveTypeConstructor "Bool" x
255+typeToTypeConstructor (RelationAtomType attrs)
256+ = RelationAtomTypeConstructor $ map attrToAttrExpr $ V.toList attrs
257+ where
258+ attrToAttrExpr (Attribute n t) = AttributeAndTypeNameExpr n (typeToTypeConstructor t) ()
259+typeToTypeConstructor (ConstructedAtomType tcName tvMap)
260+ = ADTypeConstructor tcName $ map typeToTypeConstructor (M.elems tvMap)
261+typeToTypeConstructor (TypeVariableType tvName) = TypeVariable tvName
262+
234instance AtomableG U1 where
263instance AtomableG U1 where
235− toAtomG = undefined
264+ toAtomG = error "invalid toAtomG in U1"
236 fromAtomG _ _ = pure U1
265 fromAtomG _ _ = pure U1
237 toAtomsG _ = []
266 toAtomsG _ = []
238− toAtomTypeG = undefined
267+ toAtomTypeG = error "invalid toAtomTypeG in U1"
239− toAddTypeExprG = undefined
268+ toAddTypeExprG = error "invalid toAddTypeExprG in U1"
240− getConstructorsG = undefined
269+ getConstructorsG = error "invalid getConstructorsG in U1"
241 getConstructorArgsG _ = []
270 getConstructorArgsG _ = []
242
271
243-- product types
272-- product types
244instance (AtomableG a, AtomableG b) => AtomableG (a :*: b) where
273instance (AtomableG a, AtomableG b) => AtomableG (a :*: b) where
245 toAtomG = undefined
274 toAtomG = undefined
246− fromAtomG atom args = (:*:) <$> fromAtomG atom [headatom args] <*> fromAtomG atom (tailatoms args)
275+ fromAtomG atom args = (:*:) <$> fromAtomG atom splitargs1 <*> fromAtomG atom splitargs2
247− where headatom (x:_) = x
276+ where splitargs1 = take splitpoint args
248− headatom [] = error "no more atoms in head for product!"
277+ splitargs2 = drop splitpoint args
249− tailatoms (_:xs) = xs
278+ splitpoint = length args `div` 2
250− tailatoms [] = error "no more atoms in tail for product!"
279+ toAtomTypeG = error "invalid toAtomTypeG in :*:"
251− toAtomTypeG = undefined
252 toAtomsG (x :*: y) = toAtomsG x ++ toAtomsG y
280 toAtomsG (x :*: y) = toAtomsG x ++ toAtomsG y
253− toAddTypeExprG _ _ = undefined
281+ toAddTypeExprG = error "invalid toAddTypeExprG in :*:"
254− getConstructorsG = undefined
282+ getConstructorsG = error "invalid getConstructorsG in :*:"
255− getConstructorArgsG (x :*: y) = getConstructorArgsG x ++ getConstructorArgsG y
283+ getConstructorArgsG ~(x :*: y) = getConstructorArgsG x ++ getConstructorArgsG y
256
284
257-- sum types
285-- sum types
258instance (AtomableG a, AtomableG b) => AtomableG (a :+: b) where
286instance (AtomableG a, AtomableG b) => AtomableG (a :+: b) where
259 toAtomG (L1 x) = toAtomG x
287 toAtomG (L1 x) = toAtomG x
260 toAtomG (R1 x) = toAtomG x
288 toAtomG (R1 x) = toAtomG x
261 fromAtomG atom args = (L1 <$> fromAtomG atom args) <|> (R1 <$> fromAtomG atom args)
289 fromAtomG atom args = (L1 <$> fromAtomG atom args) <|> (R1 <$> fromAtomG atom args)
262− toAtomTypeG = undefined
290+ toAtomTypeG = error "invalid toAtomTypeG in :+:"
263 toAtomsG (L1 x) = toAtomsG x
291 toAtomsG (L1 x) = toAtomsG x
264 toAtomsG (R1 x) = toAtomsG x
292 toAtomsG (R1 x) = toAtomsG x
265− toAddTypeExprG _ _ = undefined
293+ toAddTypeExprG = error "invalid toAddTypeExprG in :+:"
266 getConstructorsG _ = getConstructorsG (undefined :: a x) ++ getConstructorsG (undefined :: b x)
294 getConstructorsG _ = getConstructorsG (undefined :: a x) ++ getConstructorsG (undefined :: b x)
267− getConstructorArgsG = undefined
295+ getConstructorArgsG = error "invalid getConstructorArgsG in :+:"
268
296
269--this represents the unimplemented generics traversals which should never be called
297--this represents the unimplemented generics traversals which should never be called
270{-
298{-
src/lib/ProjectM36/Attribute.hs+4
@@ -7,6 +7,7 @@ import qualified Data.Vector as V
7import qualified Data.Hashable as Hash
7import qualified Data.Hashable as Hash
8import qualified Data.HashSet as HS
8import qualified Data.HashSet as HS
9import qualified Data.Map as M
9import qualified Data.Map as M
10+import Data.Either
10
11
11arity :: Attributes -> Int
12arity :: Attributes -> Int
12arity = V.length
13arity = V.length
@@ -74,6 +75,9 @@ attributeForName attrName attrs = case V.find (\attr -> attributeName attr == at
74 Nothing -> Left (NoSuchAttributeNamesError (S.singleton attrName))
75 Nothing -> Left (NoSuchAttributeNamesError (S.singleton attrName))
75 Just attr -> Right attr
76 Just attr -> Right attr
76
77
78+isAttributeNameContained :: AttributeName -> Attributes -> Bool
79+isAttributeNameContained nam attrs = isRight (attributeForName nam attrs)
80+
77--similar to attributesForNames, but returns error if some names are missing
81--similar to attributesForNames, but returns error if some names are missing
78projectionAttributesForNames :: S.Set AttributeName -> Attributes -> Either RelationalError Attributes
82projectionAttributesForNames :: S.Set AttributeName -> Attributes -> Either RelationalError Attributes
79projectionAttributesForNames names attrsIn =
83projectionAttributesForNames names attrsIn =
src/lib/ProjectM36/AttributeNames.hs+3−2
@@ -3,8 +3,9 @@ import ProjectM36.Base
3import qualified Data.Set as S
3import qualified Data.Set as S
4--AttributeNames is a data structure which can represent inverted projection attributes and attribute names derived from relational expressions
4--AttributeNames is a data structure which can represent inverted projection attributes and attribute names derived from relational expressions
5
5
6−empty :: AttributeNames
6+empty :: AttributeNamesBase a
7empty = AttributeNames S.empty
7empty = AttributeNames S.empty
8
8
9−all :: AttributeNames
9+all :: AttributeNamesBase a
10all = InvertedAttributeNames S.empty
10all = InvertedAttributeNames S.empty
11+
src/lib/ProjectM36/Base.hs+141−52
@@ -1,9 +1,10 @@
1−{-# LANGUAGE ExistentialQuantification,DeriveGeneric,DeriveAnyClass,TypeSynonymInstances,FlexibleInstances,OverloadedStrings #-}
1+{-# LANGUAGE ExistentialQuantification,DeriveGeneric,DeriveAnyClass,FlexibleInstances,OverloadedStrings, DeriveTraversable #-}
2{-# OPTIONS_GHC -fno-warn-orphans #-}
2{-# OPTIONS_GHC -fno-warn-orphans #-}
3
3
4module ProjectM36.Base where
4module ProjectM36.Base where
5import ProjectM36.DatabaseContextFunctionError
5import ProjectM36.DatabaseContextFunctionError
6import ProjectM36.AtomFunctionError
6import ProjectM36.AtomFunctionError
7+import ProjectM36.MerkleHash
7
8
8import qualified Data.Map as M
9import qualified Data.Map as M
9import qualified Data.HashSet as HS
10import qualified Data.HashSet as HS
@@ -13,6 +14,7 @@ import Data.UUID (UUID)
13import Control.DeepSeq (NFData, rnf)
14import Control.DeepSeq (NFData, rnf)
14import Control.DeepSeq.Generics (genericRnf)
15import Control.DeepSeq.Generics (genericRnf)
15import GHC.Generics (Generic)
16import GHC.Generics (Generic)
17+import GHC.Stack
16import qualified Data.Vector as V
18import qualified Data.Vector as V
17import qualified Data.List as L
19import qualified Data.List as L
18import Data.Text (Text,unpack)
20import Data.Text (Text,unpack)
@@ -24,6 +26,7 @@ import Data.Time.Calendar (Day,toGregorian,fromGregorian)
24import Data.Hashable.Time ()
26import Data.Hashable.Time ()
25import Data.Typeable
27import Data.Typeable
26import Data.ByteString (ByteString)
28import Data.ByteString (ByteString)
29+import qualified Data.List.NonEmpty as NE
27type StringType = Text
30type StringType = Text
28
31
29-- | Database atoms are the smallest, undecomposable units of a tuple. Common examples are integers, text, or unique identity keys.
32-- | Database atoms are the smallest, undecomposable units of a tuple. Common examples are integers, text, or unique identity keys.
@@ -77,7 +80,10 @@ data AtomType = IntAtomType |
77 TypeVariableType TypeVarName
80 TypeVariableType TypeVarName
78 --wildcard used in Atom Functions and tuples for data constructors which don't provide all arguments to the type constructor
81 --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)
82 deriving (Eq, NFData, Generic, Binary, Show)
80−
83+
84+instance Ord AtomType where
85+ compare = undefined
86+
81type TypeVarMap = M.Map TypeVarName AtomType
87type TypeVarMap = M.Map TypeVarName AtomType
82
88
83instance Hashable TypeVarMap where
89instance Hashable TypeVarMap where
@@ -145,13 +151,14 @@ instance Binary RelationTuple
145instance Eq RelationTuple where
151instance Eq RelationTuple where
146 (==) tuple1@(RelationTuple attrs1 _) tuple2@(RelationTuple attrs2 _) = attributesEqual attrs1 attrs2 && atomsEqual
152 (==) tuple1@(RelationTuple attrs1 _) tuple2@(RelationTuple attrs2 _) = attributesEqual attrs1 attrs2 && atomsEqual
147 where
153 where
148− atomForAttribute attr (RelationTuple attrs tupVec) = case V.findIndex (== attr) attrs of
154+ atomForAttribute attr (RelationTuple attrs tupVec) = case V.findIndex (== attr) attrs of
149− Nothing -> Nothing
155+ Nothing -> Nothing
150− Just index -> tupVec V.!? index
156+ Just index -> tupVec V.!? index
151− atomsEqual = V.all (== True) $ V.map (\attr -> atomForAttribute attr tuple1 == atomForAttribute attr tuple2) attrs1
157+ atomsEqual = V.all (== True) $ V.map (\attr -> atomForAttribute attr tuple1 == atomForAttribute attr tuple2) attrs1
152
158
153instance NFData RelationTuple where rnf = genericRnf
159instance NFData RelationTuple where rnf = genericRnf
154
160
161+
155data Relation = Relation Attributes RelationTupleSet deriving (Show, Generic,Typeable)
162data Relation = Relation Attributes RelationTupleSet deriving (Show, Generic,Typeable)
156
163
157instance Eq Relation where
164instance Eq Relation where
@@ -167,7 +174,7 @@ instance Hashable Relation where
167 sortedAttrs = map snd (sortedAttributesIndices attrs)
174 sortedAttrs = map snd (sortedAttributesIndices attrs)
168
175
169instance Binary Relation
176instance Binary Relation
170−
177+
171-- | Used to represent the number of tuples in a relation.
178-- | Used to represent the number of tuples in a relation.
172data RelationCardinality = Countable | Finite Int deriving (Eq, Show, Generic, Ord)
179data RelationCardinality = Countable | Finite Int deriving (Eq, Show, Generic, Ord)
173
180
@@ -179,7 +186,7 @@ type RelationalExpr = RelationalExprBase ()
179-- | A relational expression represents query (read) operations on a database.
186-- | A relational expression represents query (read) operations on a database.
180data RelationalExprBase a =
187data RelationalExprBase a =
181 --- | Create a relation from tuple expressions.
188 --- | Create a relation from tuple expressions.
182− MakeRelationFromExprs (Maybe [AttributeExprBase a]) [TupleExprBase a] |
189+ MakeRelationFromExprs (Maybe [AttributeExprBase a]) (TupleExprsBase a) |
183 --- | Create and reference a relation from attributes and a tuple set.
190 --- | Create and reference a relation from attributes and a tuple set.
184 MakeStaticRelation Attributes RelationTupleSet |
191 MakeStaticRelation Attributes RelationTupleSet |
185 --- | Reference an existing relation in Haskell-space.
192 --- | Reference an existing relation in Haskell-space.
@@ -188,7 +195,7 @@ data RelationalExprBase a =
188 --in Tutorial D, relational variables pick up the type of the first relation assigned to them
195 --in Tutorial D, relational variables pick up the type of the first relation assigned to them
189 --relational variables should also be able to be explicitly-typed like in Haskell
196 --relational variables should also be able to be explicitly-typed like in Haskell
190 --- | Reference a relation variable by its name.
197 --- | Reference a relation variable by its name.
191− RelationVariable RelVarName a |
198+ RelationVariable RelVarName a |
192 --- | Create a projection over attribute names. (Note that the 'AttributeNames' structure allows for the names to be inverted.)
199 --- | Create a projection over attribute names. (Note that the 'AttributeNames' structure allows for the names to be inverted.)
193 Project (AttributeNamesBase a) (RelationalExprBase a) |
200 Project (AttributeNamesBase a) (RelationalExprBase a) |
194 --- | Create a union of two relational expressions. The expressions should have identical attributes.
201 --- | Create a union of two relational expressions. The expressions should have identical attributes.
@@ -208,12 +215,23 @@ data RelationalExprBase a =
208 --- | Returns the true relation iff
215 --- | Returns the true relation iff
209 Equals (RelationalExprBase a) (RelationalExprBase a) |
216 Equals (RelationalExprBase a) (RelationalExprBase a) |
210 NotEquals (RelationalExprBase a) (RelationalExprBase a) |
217 NotEquals (RelationalExprBase a) (RelationalExprBase a) |
211− Extend (ExtendTupleExprBase a) (RelationalExprBase a)
218+ Extend (ExtendTupleExprBase a) (RelationalExprBase a) |
212 --Summarize :: AtomExpr -> AttributeName -> RelationalExpr -> RelationalExpr -> RelationalExpr -- a special case of Extend
219 --Summarize :: AtomExpr -> AttributeName -> RelationalExpr -> RelationalExpr -> RelationalExpr -- a special case of Extend
220+ --Evaluate relationalExpr with scoped views
221+ With [(WithNameExprBase a, RelationalExprBase a)] (RelationalExprBase a)
213− deriving (Show, Eq, Generic, NFData)
222+ deriving (Show, Eq, Generic, NFData, Foldable, Functor, Traversable)
214
223
215instance Binary RelationalExpr
224instance Binary RelationalExpr
216−
225+
226+data WithNameExprBase a = WithNameExpr RelVarName a
227+ deriving (Show, Eq, Generic, NFData, Foldable, Functor, Traversable)
228+
229+type WithNameExpr = WithNameExprBase ()
230+
231+instance Binary WithNameExpr
232+
233+type GraphRefWithNameExpr = WithNameExprBase GraphRefTransactionMarker
234+
217type NotificationName = StringType
235type NotificationName = StringType
218type Notifications = M.Map NotificationName Notification
236type Notifications = M.Map NotificationName Notification
219
237
@@ -257,7 +275,14 @@ data DataConstructorDefArg = DataConstructorDefTypeConstructorArg TypeConstructo
257 deriving (Show, Generic, Binary, Eq, NFData)
275 deriving (Show, Generic, Binary, Eq, NFData)
258
276
259type InclusionDependencies = M.Map IncDepName InclusionDependency
277type InclusionDependencies = M.Map IncDepName InclusionDependency
260−type RelationVariables = M.Map RelVarName Relation
278+type RelationVariables = M.Map RelVarName GraphRefRelationalExpr
279+
280+data GraphRefTransactionMarker = TransactionMarker TransactionId |
281+ UncommittedContextMarker
282+ deriving (Eq, Show, Binary, Generic, NFData, Ord)
283+
284+-- a fundamental relational expr to which other relational expressions compile
285+type GraphRefRelationalExpr = RelationalExprBase GraphRefTransactionMarker
261
286
262type SchemaName = StringType
287type SchemaName = StringType
263
288
@@ -300,15 +325,21 @@ type AttributeNameAtomExprMap = M.Map AttributeName AtomExpr
300--used for returning information about individual expressions
325--used for returning information about individual expressions
301type DatabaseContextExprName = StringType
326type DatabaseContextExprName = StringType
302
327
328+type DatabaseContextExpr = DatabaseContextExprBase ()
329+
330+type GraphRefDatabaseContextExpr = DatabaseContextExprBase GraphRefTransactionMarker
331+
332+instance Binary GraphRefDatabaseContextExpr
333+
303-- | Database context expressions modify the database context.
334-- | Database context expressions modify the database context.
304−data DatabaseContextExpr =
335+data DatabaseContextExprBase a =
305 NoOperation |
336 NoOperation |
306− Define RelVarName [AttributeExpr] |
337+ Define RelVarName [AttributeExprBase a] |
307 Undefine RelVarName | --forget existence of relvar X
338 Undefine RelVarName | --forget existence of relvar X
308− Assign RelVarName RelationalExpr |
339+ Assign RelVarName (RelationalExprBase a) |
309− Insert RelVarName RelationalExpr |
340+ Insert RelVarName (RelationalExprBase a) |
310− Delete RelVarName RestrictionPredicateExpr |
341+ Delete RelVarName (RestrictionPredicateExprBase a) |
311− Update RelVarName AttributeNameAtomExprMap RestrictionPredicateExpr |
342+ Update RelVarName AttributeNameAtomExprMap (RestrictionPredicateExprBase a) |
312
343
313 AddInclusionDependency IncDepName InclusionDependency |
344 AddInclusionDependency IncDepName InclusionDependency |
314 RemoveInclusionDependency IncDepName |
345 RemoveInclusionDependency IncDepName |
@@ -324,24 +355,33 @@ data DatabaseContextExpr =
324
355
325 RemoveDatabaseContextFunction DatabaseContextFunctionName |
356 RemoveDatabaseContextFunction DatabaseContextFunctionName |
326
357
327− ExecuteDatabaseContextFunction DatabaseContextFunctionName [AtomExpr] |
358+ ExecuteDatabaseContextFunction DatabaseContextFunctionName [AtomExprBase a] |
328
359
329− MultipleExpr [DatabaseContextExpr]
360+ MultipleExpr [DatabaseContextExprBase a]
330− deriving (Show, Eq, Binary, Generic)
361+ deriving (Show, Eq, Generic)
362+
363+instance Binary DatabaseContextExpr
331
364
332type ObjModuleName = StringType
365type ObjModuleName = StringType
333type ObjFunctionName = StringType
366type ObjFunctionName = StringType
334type Range = (Int,Int)
367type Range = (Int,Int)
335-- | Adding an atom function should be nominally a DatabaseExpr except for the fact that it cannot be performed purely. Thus, we create the DatabaseContextIOExpr.
368-- | Adding an atom function should be nominally a DatabaseExpr except for the fact that it cannot be performed purely. Thus, we create the DatabaseContextIOExpr.
369+data DatabaseContextIOExprBase a =
336−data DatabaseContextIOExpr = AddAtomFunction AtomFunctionName [TypeConstructor] AtomFunctionBodyScript |
370+ AddAtomFunction AtomFunctionName [TypeConstructor] AtomFunctionBodyScript |
337− LoadAtomFunctions ObjModuleName ObjFunctionName FilePath |
371+ LoadAtomFunctions ObjModuleName ObjFunctionName FilePath |
338− AddDatabaseContextFunction DatabaseContextFunctionName [TypeConstructor] DatabaseContextFunctionBodyScript |
372+ AddDatabaseContextFunction DatabaseContextFunctionName [TypeConstructor] DatabaseContextFunctionBodyScript |
339− LoadDatabaseContextFunctions ObjModuleName ObjFunctionName FilePath |
373+ LoadDatabaseContextFunctions ObjModuleName ObjFunctionName FilePath |
340− CreateArbitraryRelation RelVarName [AttributeExpr] Range
374+ CreateArbitraryRelation RelVarName [AttributeExprBase a] Range
341 deriving (Show, Eq, Generic, Binary)
375 deriving (Show, Eq, Generic, Binary)
342
376
377+type GraphRefDatabaseContextIOExpr = DatabaseContextIOExprBase GraphRefTransactionMarker
378+
379+type DatabaseContextIOExpr = DatabaseContextIOExprBase ()
380+
343type RestrictionPredicateExpr = RestrictionPredicateExprBase ()
381type RestrictionPredicateExpr = RestrictionPredicateExprBase ()
344
382
383+type GraphRefRestrictionPredicateExpr = RestrictionPredicateExprBase GraphRefTransactionMarker
384+
345-- | Restriction predicates are boolean algebra components which, when composed, indicate whether or not a tuple should be retained during a restriction (filtering) operation.
385-- | Restriction predicates are boolean algebra components which, when composed, indicate whether or not a tuple should be retained during a restriction (filtering) operation.
346data RestrictionPredicateExprBase a =
386data RestrictionPredicateExprBase a =
347 TruePredicate |
387 TruePredicate |
@@ -351,7 +391,7 @@ data RestrictionPredicateExprBase a =
351 RelationalExprPredicate (RelationalExprBase a) | --type must be same as true and false relations (no attributes)
391 RelationalExprPredicate (RelationalExprBase a) | --type must be same as true and false relations (no attributes)
352 AtomExprPredicate (AtomExprBase a) | --atom must evaluate to boolean
392 AtomExprPredicate (AtomExprBase a) | --atom must evaluate to boolean
353 AttributeEqualityPredicate AttributeName (AtomExprBase a) -- relationalexpr must result in relation with single tuple
393 AttributeEqualityPredicate AttributeName (AtomExprBase a) -- relationalexpr must result in relation with single tuple
354− deriving (Show, Eq, Generic, NFData)
394+ deriving (Show, Eq, Generic, NFData, Foldable, Functor, Traversable)
355
395
356instance Binary RestrictionPredicateExpr
396instance Binary RestrictionPredicateExpr
357
397
@@ -364,17 +404,27 @@ type TransactionHeads = M.Map HeadName Transaction
364-- | The transaction graph is the global database's state which references every committed transaction.
404-- | The transaction graph is the global database's state which references every committed transaction.
365data TransactionGraph = TransactionGraph TransactionHeads (S.Set Transaction)
405data TransactionGraph = TransactionGraph TransactionHeads (S.Set Transaction)
366
406
367−transactionsForGraph :: TransactionGraph -> S.Set Transaction
368−transactionsForGraph (TransactionGraph _ t) = t
369−
370transactionHeadsForGraph :: TransactionGraph -> TransactionHeads
407transactionHeadsForGraph :: TransactionGraph -> TransactionHeads
371−transactionHeadsForGraph (TransactionGraph heads _) = heads
408+transactionHeadsForGraph (TransactionGraph hs _) = hs
409+
410+transactionsForGraph :: TransactionGraph -> S.Set Transaction
411+transactionsForGraph (TransactionGraph _ ts) = ts
372
412
373-- | Every transaction has context-specific information attached to it.
413-- | Every transaction has context-specific information attached to it.
414+-- The `TransactionDiff`s represent child/edge relationships to previous transactions (branches or continuations of the same branch).
374−data TransactionInfo = TransactionInfo TransactionId (S.Set TransactionId) UTCTime | -- 1 parent + n children
415+data TransactionInfo = TransactionInfo {
416+ parents :: TransactionParents,
417+ stamp :: UTCTime,
418+ merkleHash :: MerkleHash
419+ } deriving (Show, Generic)
420+
421+type TransactionParents = NE.NonEmpty TransactionId
422+{-
423+data TransactionInfo = TransactionInfo TransactionId TransactionDiffs UTCTime | -- 1 parent + n children
375− MergeTransactionInfo TransactionId TransactionId (S.Set TransactionId) UTCTime -- 2 parents, n children
424+ MergeTransactionInfo TransactionId TransactionId TransactionDiffs UTCTime -- 2 parents, n children
376− deriving(Show, Generic)
425+ deriving (Show, Generic)
377−
426+-}
427+
378instance Binary TransactionInfo
428instance Binary TransactionInfo
379
429
380-- | Every set of modifications made to the database are atomically committed to the transaction graph as a transaction.
430-- | Every set of modifications made to the database are atomically committed to the transaction graph as a transaction.
@@ -382,13 +432,13 @@ type TransactionId = UUID
382
432
383data Transaction = Transaction TransactionId TransactionInfo Schemas
433data Transaction = Transaction TransactionId TransactionInfo Schemas
384
434
385−--instance Binary Transaction
435+-- | 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.
386−
436+data DisconnectedTransaction = DisconnectedTransaction TransactionId Schemas DirtyFlag
437+--the database context expression represents a difference between the disconnected transaction and its immutable parent transaction- is this diff expr used at all?
438+
387type DirtyFlag = Bool
439type DirtyFlag = Bool
388
440
389−-- | 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.
441+type TransactionDiffExpr = DatabaseContextExpr
390−data DisconnectedTransaction = DisconnectedTransaction TransactionId Schemas DirtyFlag --parentID, context- the context here represents the singular concrete context from the schema
391−--the dirty flag indicates that the database context has diverged from its parent's context
392
442
393transactionId :: Transaction -> TransactionId
443transactionId :: Transaction -> TransactionId
394transactionId (Transaction tid _ _) = tid
444transactionId (Transaction tid _ _) = tid
@@ -404,24 +454,27 @@ instance Ord Transaction where
404
454
405type AtomExpr = AtomExprBase ()
455type AtomExpr = AtomExprBase ()
406
456
457+type GraphRefAtomExpr = AtomExprBase GraphRefTransactionMarker
458+
407-- | An atom expression represents an action to take when extending a relation or when statically defining a relation or a new tuple.
459-- | An atom expression represents an action to take when extending a relation or when statically defining a relation or a new tuple.
408data AtomExprBase a = AttributeAtomExpr AttributeName |
460data AtomExprBase a = AttributeAtomExpr AttributeName |
409 NakedAtomExpr Atom |
461 NakedAtomExpr Atom |
410 FunctionAtomExpr AtomFunctionName [AtomExprBase a] a |
462 FunctionAtomExpr AtomFunctionName [AtomExprBase a] a |
411 RelationAtomExpr (RelationalExprBase a) |
463 RelationAtomExpr (RelationalExprBase a) |
412 ConstructedAtomExpr DataConstructorName [AtomExprBase a] a
464 ConstructedAtomExpr DataConstructorName [AtomExprBase a] a
413− deriving (Eq,Show,Generic, NFData)
465+ deriving (Eq,Show,Generic, NFData, Foldable, Functor, Traversable)
414
466
415instance Binary AtomExpr
467instance Binary AtomExpr
416
468
417-- | Used in tuple creation when creating a relation.
469-- | Used in tuple creation when creating a relation.
418data ExtendTupleExprBase a = AttributeExtendTupleExpr AttributeName (AtomExprBase a)
470data ExtendTupleExprBase a = AttributeExtendTupleExpr AttributeName (AtomExprBase a)
419− deriving (Show, Eq, Generic, NFData)
471+ deriving (Show, Eq, Generic, NFData, Foldable, Functor, Traversable)
420
472
421−type ExtendTupleExpr = ExtendTupleExprBase ()
473+type ExtendTupleExpr = ExtendTupleExprBase ()
474+type GraphRefExtendTupleExpr = ExtendTupleExprBase GraphRefTransactionMarker
422
475
423instance Binary ExtendTupleExpr
476instance Binary ExtendTupleExpr
424−
477+
425--enumerates the list of functions available to be run as part of tuple expressions
478--enumerates the list of functions available to be run as part of tuple expressions
426type AtomFunctions = HS.HashSet AtomFunction
479type AtomFunctions = HS.HashSet AtomFunction
427
480
@@ -466,9 +519,12 @@ data AttributeNamesBase a = AttributeNames (S.Set AttributeName) |
466 UnionAttributeNames (AttributeNamesBase a) (AttributeNamesBase a) |
519 UnionAttributeNames (AttributeNamesBase a) (AttributeNamesBase a) |
467 IntersectAttributeNames (AttributeNamesBase a) (AttributeNamesBase a) |
520 IntersectAttributeNames (AttributeNamesBase a) (AttributeNamesBase a) |
468 RelationalExprAttributeNames (RelationalExprBase a) -- use attribute names from the relational expression's type
521 RelationalExprAttributeNames (RelationalExprBase a) -- use attribute names from the relational expression's type
469− deriving (Eq, Show, Generic, NFData)
522+ deriving (Eq, Show, Generic, NFData, Foldable, Functor, Traversable)
470
523
471−type AttributeNames = AttributeNamesBase ()
524+type AttributeNames = AttributeNamesBase ()
525+
526+type GraphRefAttributeNames = AttributeNamesBase GraphRefTransactionMarker
527+
472instance Binary AttributeNames
528instance Binary AttributeNames
473
529
474-- | The persistence strategy is a global database option which represents how to persist the database in the filesystem, if at all.
530-- | The persistence strategy is a global database option which represents how to persist the database in the filesystem, if at all.
@@ -478,19 +534,31 @@ data PersistenceStrategy = NoPersistence | -- ^ no filesystem persistence/memory
478 deriving (Show, Read)
534 deriving (Show, Read)
479
535
480type AttributeExpr = AttributeExprBase ()
536type AttributeExpr = AttributeExprBase ()
537+type GraphRefAttributeExpr = AttributeExprBase GraphRefTransactionMarker
481
538
482-- | Create attributes dynamically.
539-- | Create attributes dynamically.
483data AttributeExprBase a = AttributeAndTypeNameExpr AttributeName TypeConstructor a |
540data AttributeExprBase a = AttributeAndTypeNameExpr AttributeName TypeConstructor a |
484 NakedAttributeExpr Attribute
541 NakedAttributeExpr Attribute
485− deriving (Eq, Show, Generic, Binary, NFData)
542+ deriving (Eq, Show, Generic, Binary, NFData, Foldable, Functor, Traversable)
486
543
487-- | Dynamically create a tuple from attribute names and 'AtomExpr's.
544-- | Dynamically create a tuple from attribute names and 'AtomExpr's.
488newtype TupleExprBase a = TupleExpr (M.Map AttributeName (AtomExprBase a))
545newtype TupleExprBase a = TupleExpr (M.Map AttributeName (AtomExprBase a))
489− deriving (Eq, Show, Generic, NFData)
546+ deriving (Eq, Show, Generic, NFData, Foldable, Functor, Traversable)
490−
491−instance Binary TupleExpr
492
547
548+instance Binary TupleExpr
549+
493−type TupleExpr = TupleExprBase ()
550+type TupleExpr = TupleExprBase ()
551+
552+type GraphRefTupleExpr = TupleExprBase GraphRefTransactionMarker
553+
554+data TupleExprsBase a = TupleExprs a [TupleExprBase a]
555+ deriving (Eq, Show, Generic, NFData, Foldable, Functor, Traversable)
556+
557+type GraphRefTupleExprs = TupleExprsBase GraphRefTransactionMarker
558+
559+type TupleExprs = TupleExprsBase ()
560+
561+instance Binary TupleExprs
494
562
495data MergeStrategy =
563data MergeStrategy =
496 -- | 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)
564 -- | 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)
@@ -563,3 +631,24 @@ atomTypeVars (RelationAtomType attrs) = S.unions (map attrTypeVars (V.toList att
563atomTypeVars (ConstructedAtomType _ tvMap) = M.keysSet tvMap
631atomTypeVars (ConstructedAtomType _ tvMap) = M.keysSet tvMap
564atomTypeVars (TypeVariableType nam) = S.singleton nam
632atomTypeVars (TypeVariableType nam) = S.singleton nam
565
633
634+unimplemented :: HasCallStack => a
635+unimplemented = undefined
636+
637+--for serializing GraphRefRelationalExpr as part of transaction serialization
638+instance Binary (TupleExprsBase GraphRefTransactionMarker)
639+
640+instance Binary (TupleExprBase GraphRefTransactionMarker)
641+
642+instance Binary GraphRefRelationalExpr
643+
644+instance Binary (AtomExprBase GraphRefTransactionMarker)
645+
646+instance Binary (AttributeNamesBase GraphRefTransactionMarker)
647+
648+instance Binary (RestrictionPredicateExprBase GraphRefTransactionMarker)
649+
650+instance Binary (ExtendTupleExprBase GraphRefTransactionMarker)
651+
652+instance Binary GraphRefWithNameExpr
653+
654+
src/lib/ProjectM36/Client.hs+203−97
@@ -1,4 +1,4 @@
1−{-# LANGUAGE DeriveAnyClass, DeriveGeneric, ScopedTypeVariables, BangPatterns #-}
1+{-# LANGUAGE DeriveAnyClass, DeriveGeneric, ScopedTypeVariables, MonoLocalBinds #-}
2{-|
2{-|
3Module: ProjectM36.Client
3Module: ProjectM36.Client
4
4
@@ -16,7 +16,8 @@ module ProjectM36.Client
16 closeRemote_,
16 closeRemote_,
17 executeRelationalExpr,
17 executeRelationalExpr,
18 executeDatabaseContextExpr,
18 executeDatabaseContextExpr,
19− executeDatabaseContextIOExpr,
19+ executeDatabaseContextIOExpr,
20+ executeDataFrameExpr,
20 executeGraphExpr,
21 executeGraphExpr,
21 executeSchemaExpr,
22 executeSchemaExpr,
22 executeTransGraphRelationalExpr,
23 executeTransGraphRelationalExpr,
@@ -45,8 +46,10 @@ module ProjectM36.Client
45 PersistenceStrategy(..),
46 PersistenceStrategy(..),
46 RelationalExpr,
47 RelationalExpr,
47 RelationalExprBase(..),
48 RelationalExprBase(..),
49+ DatabaseContextExprBase(..),
48− DatabaseContextExpr(..),
50+ DatabaseContextExpr,
51+ DatabaseContextIOExprBase(..),
49− DatabaseContextIOExpr(..),
52+ DatabaseContextIOExpr,
50 Attribute(..),
53 Attribute(..),
51 MergeStrategy(..),
54 MergeStrategy(..),
52 attributesFromList,
55 attributesFromList,
@@ -77,6 +80,7 @@ module ProjectM36.Client
77 databaseContextExprForUniqueKey,
80 databaseContextExprForUniqueKey,
78 databaseContextExprForForeignKey,
81 databaseContextExprForForeignKey,
79 createScriptedAtomFunction,
82 createScriptedAtomFunction,
83+ ProjectM36.Client.validateMerkleHashes,
80 AttributeExprBase(..),
84 AttributeExprBase(..),
81 TypeConstructorBase(..),
85 TypeConstructorBase(..),
82 TypeConstructorDef(..),
86 TypeConstructorDef(..),
@@ -86,12 +90,17 @@ module ProjectM36.Client
86 IncDepName,
90 IncDepName,
87 InclusionDependency(..),
91 InclusionDependency(..),
88 AttributeName,
92 AttributeName,
93+ DF.DataFrame,
94+ DF.DataFrameExpr,
95+ DF.AttributeOrderExpr,
96+ DF.Order(..),
89 RelationalError(..),
97 RelationalError(..),
90 RequestTimeoutException(..),
98 RequestTimeoutException(..),
91 RemoteProcessDiedException(..),
99 RemoteProcessDiedException(..),
92 AtomType(..),
100 AtomType(..),
93 Atomable(..),
101 Atomable(..),
94 TupleExprBase(..),
102 TupleExprBase(..),
103+ TupleExprsBase(..),
95 AtomExprBase(..),
104 AtomExprBase(..),
96 RestrictionPredicateExprBase(..),
105 RestrictionPredicateExprBase(..),
97 withTransaction
106 withTransaction
@@ -103,32 +112,41 @@ import ProjectM36.Atomable
103import ProjectM36.AtomFunction as AF
112import ProjectM36.AtomFunction as AF
104import ProjectM36.StaticOptimizer
113import ProjectM36.StaticOptimizer
105import ProjectM36.Key
114import ProjectM36.Key
115+import qualified ProjectM36.DataFrame as DF
106import ProjectM36.DatabaseContextFunction as DCF
116import ProjectM36.DatabaseContextFunction as DCF
107import qualified ProjectM36.IsomorphicSchema as Schema
117import qualified ProjectM36.IsomorphicSchema as Schema
108import Control.Monad.State
118import Control.Monad.State
109−import Control.Monad.Trans.Reader
110import qualified ProjectM36.RelationalExpression as RE
119import qualified ProjectM36.RelationalExpression as RE
111import ProjectM36.DatabaseContext (basicDatabaseContext)
120import ProjectM36.DatabaseContext (basicDatabaseContext)
112import qualified ProjectM36.TransactionGraph as Graph
121import qualified ProjectM36.TransactionGraph as Graph
113−import ProjectM36.TransactionGraph
122+import ProjectM36.TransactionGraph as TG
114import qualified ProjectM36.Transaction as Trans
123import qualified ProjectM36.Transaction as Trans
115import ProjectM36.TransactionGraph.Persist
124import ProjectM36.TransactionGraph.Persist
116import ProjectM36.Attribute
125import ProjectM36.Attribute
117−import ProjectM36.TransGraphRelationalExpression (TransGraphRelationalExpr, evalTransGraphRelationalExpr)
126+import ProjectM36.TransGraphRelationalExpression as TGRE (TransGraphRelationalExpr)
118import ProjectM36.Persist (DiskSync(..))
127import ProjectM36.Persist (DiskSync(..))
119import ProjectM36.FileLock
128import ProjectM36.FileLock
129+import ProjectM36.NormalizeExpr
120import ProjectM36.Notifications
130import ProjectM36.Notifications
121import ProjectM36.Server.RemoteCallTypes
131import ProjectM36.Server.RemoteCallTypes
122import qualified ProjectM36.DisconnectedTransaction as Discon
132import qualified ProjectM36.DisconnectedTransaction as Discon
123import ProjectM36.Relation (typesAsRelation)
133import ProjectM36.Relation (typesAsRelation)
124import ProjectM36.ScriptSession (initScriptSession, ScriptSession)
134import ProjectM36.ScriptSession (initScriptSession, ScriptSession)
125import qualified ProjectM36.Relation as R
135import qualified ProjectM36.Relation as R
126−import qualified ProjectM36.DatabaseContext as DBC
127import Control.Exception.Base
136import Control.Exception.Base
128import GHC.Conc.Sync
137import GHC.Conc.Sync
129
138
130import Network.Transport (Transport(closeTransport))
139import Network.Transport (Transport(closeTransport))
140+#if MIN_VERSION_network_transport_tcp(0,7,0)
131−import Network.Transport.TCP (createTransport, defaultTCPParameters, encodeEndPointAddress)
141+import Network.Transport.TCP (createTransport, defaultTCPParameters, defaultTCPAddr)
142+import Network.Transport.TCP.Internal (encodeEndPointAddress)
143+#elif MIN_VERSION_network_transport_tcp(0,6,0)
144+import Network.Transport.TCP (createTransport, defaultTCPParameters)
145+import Network.Transport.TCP.Internal (encodeEndPointAddress)
146+#else
147+import Network.Transport.TCP (encodeEndPointAddress, createTransport, defaultTCPParameters)
148+#endif
149+
132import Control.Distributed.Process.Node (newLocalNode, initRemoteTable, runProcess, LocalNode, forkProcess, closeLocalNode)
150import Control.Distributed.Process.Node (newLocalNode, initRemoteTable, runProcess, LocalNode, forkProcess, closeLocalNode)
133import Control.Distributed.Process.Extras.Internal.Types (whereisRemote)
151import Control.Distributed.Process.Extras.Internal.Types (whereisRemote)
134import Control.Distributed.Process.ManagedProcess.Client (call, safeCall)
152import Control.Distributed.Process.ManagedProcess.Client (call, safeCall)
@@ -139,18 +157,22 @@ import Control.Distributed.Process (ProcessId, Process, receiveWait, send, match
139import Control.Exception (IOException, handle, AsyncException, throwIO, fromException, Exception)
157import Control.Exception (IOException, handle, AsyncException, throwIO, fromException, Exception)
140import Control.Concurrent.MVar
158import Control.Concurrent.MVar
141import qualified Data.Map as M
159import qualified Data.Map as M
142−import Control.Distributed.Process.Serializable (Serializable)
160+#if MIN_VERSION_stm_containers(1,0,0)
161+import qualified StmContainers.Map as StmMap
162+import qualified StmContainers.Set as StmSet
163+#else
143−import qualified STMContainers.Map as STMMap
164+import qualified STMContainers.Map as StmMap
144−import qualified STMContainers.Set as STMSet
165+import qualified STMContainers.Set as StmSet
166+#endif
145import qualified ProjectM36.Session as Sess
167import qualified ProjectM36.Session as Sess
146import ProjectM36.Session
168import ProjectM36.Session
147import ProjectM36.Sessions
169import ProjectM36.Sessions
148−import ListT
149import Data.Binary (Binary)
170import Data.Binary (Binary)
150import GHC.Generics (Generic)
171import GHC.Generics (Generic)
151import Control.DeepSeq (force)
172import Control.DeepSeq (force)
152import System.IO
173import System.IO
153import Data.Time.Clock
174import Data.Time.Clock
175+import Data.Typeable
154
176
155type Hostname = String
177type Hostname = String
156
178
@@ -217,7 +239,7 @@ defaultRemoteConnectionInfo :: ConnectionInfo
217defaultRemoteConnectionInfo = RemoteProcessConnectionInfo defaultDatabaseName (createNodeId "127.0.0.1" defaultServerPort) emptyNotificationCallback
239defaultRemoteConnectionInfo = RemoteProcessConnectionInfo defaultDatabaseName (createNodeId "127.0.0.1" defaultServerPort) emptyNotificationCallback
218
240
219-- | The 'Connection' represents either local or remote access to a database. All operations flow through the connection.
241-- | The 'Connection' represents either local or remote access to a database. All operations flow through the connection.
220−type ClientNodes = STMSet.Set ProcessId
242+type ClientNodes = StmSet.Set ProcessId
221
243
222-- internal structure specific to in-process connections
244-- internal structure specific to in-process connections
223data InProcessConnectionConf = InProcessConnectionConf {
245data InProcessConnectionConf = InProcessConnectionConf {
@@ -244,6 +266,7 @@ data Connection = InProcessConnection InProcessConnectionConf |
244data ConnectionError = SetupDatabaseDirectoryError PersistenceError |
266data ConnectionError = SetupDatabaseDirectoryError PersistenceError |
245 IOExceptionError IOException |
267 IOExceptionError IOException |
246 NoSuchDatabaseByNameError DatabaseName |
268 NoSuchDatabaseByNameError DatabaseName |
269+ DatabaseValidationError [MerkleValidationError] |
247 LoginError
270 LoginError
248 deriving (Show, Eq, Generic)
271 deriving (Show, Eq, Generic)
249
272
@@ -252,7 +275,13 @@ remoteDBLookupName = (++) "db-"
252
275
253createLocalNode :: IO (LocalNode, Transport)
276createLocalNode :: IO (LocalNode, Transport)
254createLocalNode = do
277createLocalNode = do
278+#if MIN_VERSION_network_transport_tcp(0,7,0)
279+ eLocalTransport <- createTransport (defaultTCPAddr "127.0.0.1" "0") defaultTCPParameters
280+#elif MIN_VERSION_network_transport_tcp(0,6,0)
281+ eLocalTransport <- createTransport "127.0.0.1" "0" (\sn -> ("127.0.0.1", sn)) defaultTCPParameters
282+#else
255 eLocalTransport <- createTransport "127.0.0.1" "0" defaultTCPParameters
283 eLocalTransport <- createTransport "127.0.0.1" "0" defaultTCPParameters
284+#endif
256 case eLocalTransport of
285 case eLocalTransport of
257 Left err -> error ("failed to create transport: " ++ show err)
286 Left err -> error ("failed to create transport: " ++ show err)
258 Right localTransport -> do
287 Right localTransport -> do
@@ -289,15 +318,15 @@ connectProjectM36 :: ConnectionInfo -> IO (Either ConnectionError Connection)
289--create a new in-memory database/transaction graph
318--create a new in-memory database/transaction graph
290connectProjectM36 (InProcessConnectionInfo strat notificationCallback ghcPkgPaths) = do
319connectProjectM36 (InProcessConnectionInfo strat notificationCallback ghcPkgPaths) = do
291 freshId <- nextRandom
320 freshId <- nextRandom
292− stamp <- getCurrentTime
321+ tstamp <- getCurrentTime
293 let bootstrapContext = basicDatabaseContext
322 let bootstrapContext = basicDatabaseContext
294− freshGraph = bootstrapTransactionGraph stamp freshId bootstrapContext
323+ freshGraph = bootstrapTransactionGraph tstamp freshId bootstrapContext
295 case strat of
324 case strat of
296 --create date examples graph for now- probably should be empty context in the future
325 --create date examples graph for now- probably should be empty context in the future
297 NoPersistence -> do
326 NoPersistence -> do
298 graphTvar <- newTVarIO freshGraph
327 graphTvar <- newTVarIO freshGraph
299− clientNodes <- STMSet.newIO
328+ clientNodes <- StmSet.newIO
300− sessions <- STMMap.newIO
329+ sessions <- StmMap.newIO
301 (localNode, transport) <- createLocalNode
330 (localNode, transport) <- createLocalNode
302 notificationPid <- startNotificationListener localNode notificationCallback
331 notificationPid <- startNotificationListener localNode notificationCallback
303 mScriptSession <- createScriptSession ghcPkgPaths
332 mScriptSession <- createScriptSession ghcPkgPaths
@@ -352,12 +381,15 @@ connectPersistentProjectM36 strat sync dbdir freshGraph notificationCallback ghc
352 case graph of
381 case graph of
353 Left err' -> return $ Left (SetupDatabaseDirectoryError err')
382 Left err' -> return $ Left (SetupDatabaseDirectoryError err')
354 Right graph' -> do
383 Right graph' -> do
384+ case TG.validateMerkleHashes graph' of
385+ Left merkleErrs -> pure (Left (DatabaseValidationError merkleErrs))
386+ Right _ -> do
355− tvarGraph <- newTVarIO graph'
387+ tvarGraph <- newTVarIO graph'
356− sessions <- STMMap.newIO
388+ sessions <- StmMap.newIO
357− clientNodes <- STMSet.newIO
389+ clientNodes <- StmSet.newIO
358− (localNode, transport) <- createLocalNode
390+ (localNode, transport) <- createLocalNode
359− lockMVar <- newMVar digest
391+ lockMVar <- newMVar digest
360− let conn = InProcessConnection InProcessConnectionConf {
392+ let conn = InProcessConnection InProcessConnectionConf {
361 ipPersistenceStrategy = strat,
393 ipPersistenceStrategy = strat,
362 ipClientNodes = clientNodes,
394 ipClientNodes = clientNodes,
363 ipSessions = sessions,
395 ipSessions = sessions,
@@ -368,9 +400,9 @@ connectPersistentProjectM36 strat sync dbdir freshGraph notificationCallback ghc
368 ipLocks = Just (lockFileH, lockMVar)
400 ipLocks = Just (lockFileH, lockMVar)
369 }
401 }
370
402
371− notificationPid <- startNotificationListener localNode notificationCallback
403+ notificationPid <- startNotificationListener localNode notificationCallback
372− addClientNode conn notificationPid
404+ addClientNode conn notificationPid
373− pure (Right conn)
405+ pure (Right conn)
374
406
375-- | Create a new session at the transaction id and return the session's Id.
407-- | Create a new session at the transaction id and return the session's Id.
376createSessionAtCommit :: Connection -> TransactionId -> IO (Either RelationalError SessionId)
408createSessionAtCommit :: Connection -> TransactionId -> IO (Either RelationalError SessionId)
@@ -384,15 +416,15 @@ createSessionAtCommit_ commitId newSessionId (InProcessConnection conf) = do
384 let sessions = ipSessions conf
416 let sessions = ipSessions conf
385 graphTvar = ipTransactionGraph conf
417 graphTvar = ipTransactionGraph conf
386 graph <- readTVar graphTvar
418 graph <- readTVar graphTvar
387− case transactionForId commitId graph of
419+ case RE.transactionForId commitId graph of
388 Left err -> pure (Left err)
420 Left err -> pure (Left err)
389 Right transaction -> do
421 Right transaction -> do
390 let freshDiscon = DisconnectedTransaction commitId (Trans.schemas transaction) False
422 let freshDiscon = DisconnectedTransaction commitId (Trans.schemas transaction) False
391− keyDuplication <- STMMap.lookup newSessionId sessions
423+ keyDuplication <- StmMap.lookup newSessionId sessions
392 case keyDuplication of
424 case keyDuplication of
393 Just _ -> pure $ Left (SessionIdInUseError newSessionId)
425 Just _ -> pure $ Left (SessionIdInUseError newSessionId)
394 Nothing -> do
426 Nothing -> do
395− STMMap.insert (Session freshDiscon defaultSchemaName) newSessionId sessions
427+ StmMap.insert (Session freshDiscon defaultSchemaName) newSessionId sessions
396 pure $ Right newSessionId
428 pure $ Right newSessionId
397createSessionAtCommit_ _ _ (RemoteProcessConnection _) = error "createSessionAtCommit_ called on remote connection"
429createSessionAtCommit_ _ _ (RemoteProcessConnection _) = error "createSessionAtCommit_ called on remote connection"
398
430
@@ -411,12 +443,12 @@ createSessionAtHead conn@(RemoteProcessConnection _) headn = remoteCall conn (Cr
411-- | Used internally for server connections to keep track of remote nodes for the purpose of sending notifications later.
443-- | Used internally for server connections to keep track of remote nodes for the purpose of sending notifications later.
412addClientNode :: Connection -> ProcessId -> IO ()
444addClientNode :: Connection -> ProcessId -> IO ()
413addClientNode (RemoteProcessConnection _) _ = error "addClientNode called on remote connection"
445addClientNode (RemoteProcessConnection _) _ = error "addClientNode called on remote connection"
414−addClientNode (InProcessConnection conf) newProcessId = atomically (STMSet.insert newProcessId (ipClientNodes conf))
446+addClientNode (InProcessConnection conf) newProcessId = atomically (StmSet.insert newProcessId (ipClientNodes conf))
415
447
416-- | Discards a session, eliminating any uncommitted changes present in the session.
448-- | Discards a session, eliminating any uncommitted changes present in the session.
417closeSession :: SessionId -> Connection -> IO ()
449closeSession :: SessionId -> Connection -> IO ()
418closeSession sessionId (InProcessConnection conf) =
450closeSession sessionId (InProcessConnection conf) =
419− atomically $ STMMap.delete sessionId (ipSessions conf)
451+ atomically $ StmMap.delete sessionId (ipSessions conf)
420closeSession sessionId conn@(RemoteProcessConnection _) = remoteCall conn (CloseSession sessionId)
452closeSession sessionId conn@(RemoteProcessConnection _) = remoteCall conn (CloseSession sessionId)
421
453
422-- | 'close' cleans up the database access connection and closes any relevant sockets.
454-- | 'close' cleans up the database access connection and closes any relevant sockets.
@@ -424,7 +456,11 @@ close :: Connection -> IO ()
424close (InProcessConnection conf) = do
456close (InProcessConnection conf) = do
425 atomically $ do
457 atomically $ do
426 let sessions = ipSessions conf
458 let sessions = ipSessions conf
459+#if MIN_VERSION_stm_containers(1,0,0)
460+ StmMap.reset sessions
461+#else
427− STMMap.deleteAll sessions
462+ StmMap.deleteAll sessions
463+#endif
428 pure ()
464 pure ()
429 closeLocalNode (ipLocalNode conf)
465 closeLocalNode (ipLocalNode conf)
430 closeTransport (ipTransport conf)
466 closeTransport (ipTransport conf)
@@ -468,7 +504,7 @@ safeLogin login procId = do
468 Left (_ :: ServerError) -> pure False
504 Left (_ :: ServerError) -> pure False
469 Right val -> pure val
505 Right val -> pure val
470
506
471−remoteCall :: (Serializable a, Serializable b) => Connection -> a -> IO b
507+remoteCall :: (Binary a, Binary b, Typeable a, Typeable b) => Connection -> a -> IO b
472remoteCall (InProcessConnection _ ) _ = error "remoteCall called on local connection"
508remoteCall (InProcessConnection _ ) _ = error "remoteCall called on local connection"
473remoteCall (RemoteProcessConnection conf) arg = runProcessResult localNode $ do
509remoteCall (RemoteProcessConnection conf) arg = runProcessResult localNode $ do
474 ret <- safeCall serverProcessId arg
510 ret <- safeCall serverProcessId arg
@@ -484,7 +520,7 @@ remoteCall (RemoteProcessConnection conf) arg = runProcessResult localNode $ do
484
520
485sessionForSessionId :: SessionId -> Sessions -> STM (Either RelationalError Session)
521sessionForSessionId :: SessionId -> Sessions -> STM (Either RelationalError Session)
486sessionForSessionId sessionId sessions =
522sessionForSessionId sessionId sessions =
487− maybe (Left $ NoSuchSessionError sessionId) Right <$> STMMap.lookup sessionId sessions
523+ maybe (Left $ NoSuchSessionError sessionId) Right <$> StmMap.lookup sessionId sessions
488
524
489schemaForSessionId :: Session -> STM (Either RelationalError Schema)
525schemaForSessionId :: Session -> STM (Either RelationalError Schema)
490schemaForSessionId session = do
526schemaForSessionId session = do
@@ -526,7 +562,7 @@ setCurrentSchemaName sessionId (InProcessConnection conf) sname = atomically $ d
526 Left err -> pure (Left err)
562 Left err -> pure (Left err)
527 Right session -> case Sess.setSchemaName sname session of
563 Right session -> case Sess.setSchemaName sname session of
528 Left err -> pure (Left err)
564 Left err -> pure (Left err)
529− Right newSession -> STMMap.insert newSession sessionId sessions >> pure (Right ())
565+ Right newSession -> StmMap.insert newSession sessionId sessions >> pure (Right ())
530setCurrentSchemaName sessionId conn@(RemoteProcessConnection _) sname = remoteCall conn (ExecuteSetCurrentSchema sessionId sname)
566setCurrentSchemaName sessionId conn@(RemoteProcessConnection _) sname = remoteCall conn (ExecuteSetCurrentSchema sessionId sname)
531
567
532-- | Execute a relational expression in the context of the session and connection. Relational expressions are queries and therefore cannot alter the database.
568-- | Execute a relational expression in the context of the session and connection. Relational expressions are queries and therefore cannot alter the database.
@@ -543,13 +579,14 @@ executeRelationalExpr sessionId (InProcessConnection conf) expr = excEither $ at
543 Right expr
579 Right expr
544 case expr' of
580 case expr' of
545 Left err -> pure (Left err)
581 Left err -> pure (Left err)
546− Right expr'' -> case optimizeRelationalExpr (Sess.concreteDatabaseContext session) expr'' of
582+ Right expr'' -> do
547− Left err -> pure (Left err)
583+ let graphTvar = ipTransactionGraph conf
548− Right optExpr -> do
584+ graph <- readTVar graphTvar
549− let evald = runReader (RE.evalRelationalExpr optExpr) (RE.mkRelationalExprState (Sess.concreteDatabaseContext session))
585+ let reEnv = RE.mkRelationalExprEnv (Sess.concreteDatabaseContext session) graph
550− case evald of
586+ case optimizeAndEvalRelationalExpr reEnv expr'' of
551− Left err -> pure (Left err)
552− Right rel -> pure (force (Right rel)) -- this is necessary so that any undefined/error exceptions are spit out here
587+ Right rel -> pure (force (Right rel)) -- this is necessary so that any undefined/error exceptions are spit out here
588+ Left err -> pure (Left err)
589+
553executeRelationalExpr sessionId conn@(RemoteProcessConnection _) relExpr = remoteCall conn (ExecuteRelationalExpr sessionId relExpr)
590executeRelationalExpr sessionId conn@(RemoteProcessConnection _) relExpr = remoteCall conn (ExecuteRelationalExpr sessionId relExpr)
554
591
555-- | 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.
592-- | 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.
@@ -566,21 +603,24 @@ executeDatabaseContextExpr sessionId (InProcessConnection conf) expr = excEither
566 Schema.processDatabaseContextExprInSchema schema expr
603 Schema.processDatabaseContextExprInSchema schema expr
567 case expr' of
604 case expr' of
568 Left err -> pure (Left err)
605 Left err -> pure (Left err)
569− Right expr'' -> case runState (do
606+ Right expr'' -> do
570− eOptExpr <- applyStaticDatabaseOptimization expr''
607+ graph <- readTVar (ipTransactionGraph conf)
571− case eOptExpr of
572− Left err -> pure (Left err)
573− Right optExpr ->
574− RE.evalDatabaseContextExpr optExpr) (RE.freshDatabaseState (Sess.concreteDatabaseContext session)) of
608+ let ctx = Sess.concreteDatabaseContext session
609+ env = RE.mkDatabaseContextEvalEnv transId graph
610+ transId = Sess.parentId session
611+ case RE.runDatabaseContextEvalMonad ctx env (optimizeAndEvalDatabaseContextExpr True expr'') of
575− (Left err,_) -> pure (Left err)
612+ Left err -> pure (Left err)
613+ Right newState ->
576− (Right (), (_,_,False)) -> pure (Right ()) --optimization- if nothing was dirtied, nothing to do
614+ if not (RE.dbc_dirty newState) then --nothing dirtied, nothing to do
577− (Right (), (!context',_,True)) -> do
615+ pure (Right ())
616+ else do
578− let newDiscon = DisconnectedTransaction (Sess.parentId session) newSchemas True
617+ let newDiscon = DisconnectedTransaction (Sess.parentId session) newSchemas True
618+ context' = RE.dbc_context newState
579− newSubschemas = Schema.processDatabaseContextExprSchemasUpdate (Sess.subschemas session) expr
619+ newSubschemas = Schema.processDatabaseContextExprSchemasUpdate (Sess.subschemas session) expr
580− newSchemas = Schemas context' newSubschemas
620+ newSchemas = Schemas context' newSubschemas
581− newSession = Session newDiscon (Sess.schemaName session)
621+ newSession = Session newDiscon (Sess.schemaName session)
582− STMMap.insert newSession sessionId sessions
622+ StmMap.insert newSession sessionId sessions
583− pure (Right ())
623+ pure (Right ())
584executeDatabaseContextExpr sessionId conn@(RemoteProcessConnection _) dbExpr = remoteCall conn (ExecuteDatabaseContextExpr sessionId dbExpr)
624executeDatabaseContextExpr sessionId conn@(RemoteProcessConnection _) dbExpr = remoteCall conn (ExecuteDatabaseContextExpr sessionId dbExpr)
585
625
586-- | 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.
626-- | 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.
@@ -590,7 +630,7 @@ autoMergeToHead sessionId (InProcessConnection conf) strat headName' = do
590 id1 <- nextRandom
630 id1 <- nextRandom
591 id2 <- nextRandom
631 id2 <- nextRandom
592 id3 <- nextRandom
632 id3 <- nextRandom
593− stamp <- getCurrentTime
633+ tstamp <- getCurrentTime
594 commitLock_ sessionId conf $ \graph -> do
634 commitLock_ sessionId conf $ \graph -> do
595 eSession <- sessionForSessionId sessionId sessions
635 eSession <- sessionForSessionId sessionId sessions
596 case eSession of
636 case eSession of
@@ -601,10 +641,10 @@ autoMergeToHead sessionId (InProcessConnection conf) strat headName' = do
601 Just headTrans -> do
641 Just headTrans -> do
602 --attempt fast-forward commit, if possible
642 --attempt fast-forward commit, if possible
603 let graphInfo = if Sess.parentId session == transactionId headTrans then do
643 let graphInfo = if Sess.parentId session == transactionId headTrans then do
604− ret <- Graph.evalGraphOp stamp id1 (Sess.disconnectedTransaction session) graph Commit
644+ ret <- Graph.evalGraphOp tstamp id1 (Sess.disconnectedTransaction session) graph Commit
605 pure (ret, [id1])
645 pure (ret, [id1])
606 else do
646 else do
607− ret <- Graph.autoMergeToHead stamp (id1, id2, id3) (Sess.disconnectedTransaction session) headName' strat graph
647+ ret <- Graph.autoMergeToHead tstamp (id1, id2, id3) (Sess.disconnectedTransaction session) headName' strat graph
608 pure (ret, [id1,id2,id3])
648 pure (ret, [id1,id2,id3])
609 case graphInfo of
649 case graphInfo of
610 Left err -> pure (Left err)
650 Left err -> pure (Left err)
@@ -622,14 +662,19 @@ executeDatabaseContextIOExpr sessionId (InProcessConnection conf) expr = excEith
622 case eSession of
662 case eSession of
623 Left err -> pure (Left err)
663 Left err -> pure (Left err)
624 Right session -> do
664 Right session -> do
665+ graph <- readTVarIO (ipTransactionGraph conf)
666+ let env = RE.DatabaseContextIOEvalEnv transId graph scriptSession
667+ transId = Sess.parentId session
625− res <- RE.evalDatabaseContextIOExpr scriptSession (Sess.concreteDatabaseContext session) expr
668+ context = Sess.concreteDatabaseContext session
669+ res <- RE.runDatabaseContextIOEvalMonad env context (optimizeAndEvalDatabaseContextIOExpr expr)
626 case res of
670 case res of
627 Left err -> pure (Left err)
671 Left err -> pure (Left err)
628− Right context' -> do
672+ Right newState -> do
629− let newDiscon = DisconnectedTransaction (Sess.parentId session) newSchemas True
673+ let newDiscon = DisconnectedTransaction (Sess.parentId session) newSchemas False
630 newSchemas = Schemas context' (Sess.subschemas session)
674 newSchemas = Schemas context' (Sess.subschemas session)
631 newSession = Session newDiscon (Sess.schemaName session)
675 newSession = Session newDiscon (Sess.schemaName session)
676+ context' = RE.dbc_context newState
632− atomically $ STMMap.insert newSession sessionId sessions
677+ atomically $ StmMap.insert newSession sessionId sessions
633 pure (Right ())
678 pure (Right ())
634executeDatabaseContextIOExpr sessionId conn@(RemoteProcessConnection _) dbExpr = remoteCall conn (ExecuteDatabaseContextIOExpr sessionId dbExpr)
679executeDatabaseContextIOExpr sessionId conn@(RemoteProcessConnection _) dbExpr = remoteCall conn (ExecuteDatabaseContextIOExpr sessionId dbExpr)
635
680
@@ -648,12 +693,18 @@ executeGraphExprSTM_ freshId sessionId session sessions graphExpr graph graphTVa
648-}
693-}
649
694
650-- process notifications for commits
695-- process notifications for commits
696+executeCommitExprSTM_
697+ :: TransactionGraph
698+ -> DatabaseContext
699+ -> DatabaseContext
700+ -> ClientNodes
651−executeCommitExprSTM_ :: DatabaseContext -> DatabaseContext -> ClientNodes -> STM (EvaluatedNotifications, ClientNodes)
701+ -> STM (EvaluatedNotifications, ClientNodes)
652−executeCommitExprSTM_ oldContext newContext nodes = do
702+executeCommitExprSTM_ graph oldContext newContext nodes = do
653 let nots = notifications oldContext
703 let nots = notifications oldContext
654− fireNots = notificationChanges nots oldContext newContext
704+ fireNots = notificationChanges nots graph oldContext newContext
655 evaldNots = M.map mkEvaldNot fireNots
705 evaldNots = M.map mkEvaldNot fireNots
656− evalInContext expr ctx = runReader (RE.evalRelationalExpr expr) (RE.mkRelationalExprState ctx)
706+ evalInContext expr ctx = optimizeAndEvalRelationalExpr (RE.mkRelationalExprEnv ctx graph) expr
707+
657 mkEvaldNot notif = EvaluatedNotification { notification = notif,
708 mkEvaldNot notif = EvaluatedNotification { notification = notif,
658 reportOldRelation = evalInContext (reportOldExpr notif) oldContext,
709 reportOldRelation = evalInContext (reportOldExpr notif) oldContext,
659 reportNewRelation = evalInContext (reportNewExpr notif) newContext}
710 reportNewRelation = evalInContext (reportNewExpr notif) newContext}
@@ -668,18 +719,18 @@ executeGraphExpr :: SessionId -> Connection -> TransactionGraphOperator -> IO (E
668executeGraphExpr sessionId (InProcessConnection conf) graphExpr = excEither $ do
719executeGraphExpr sessionId (InProcessConnection conf) graphExpr = excEither $ do
669 let sessions = ipSessions conf
720 let sessions = ipSessions conf
670 freshId <- nextRandom
721 freshId <- nextRandom
671− stamp <- getCurrentTime
722+ tstamp <- getCurrentTime
672 commitLock_ sessionId conf $ \updatedGraph -> do
723 commitLock_ sessionId conf $ \updatedGraph -> do
673 eSession <- sessionForSessionId sessionId sessions
724 eSession <- sessionForSessionId sessionId sessions
674 case eSession of
725 case eSession of
675 Left err -> pure (Left err)
726 Left err -> pure (Left err)
676 Right session -> do
727 Right session -> do
677 let discon = Sess.disconnectedTransaction session
728 let discon = Sess.disconnectedTransaction session
678− case evalGraphOp stamp freshId discon updatedGraph graphExpr of
729+ case evalGraphOp tstamp freshId discon updatedGraph graphExpr of
679 Left err -> pure (Left err)
730 Left err -> pure (Left err)
680 Right (discon', graph') -> do
731 Right (discon', graph') -> do
681 --if freshId appears in the graph, then we need to pass it on
732 --if freshId appears in the graph, then we need to pass it on
682− let transIds = [freshId | isRight (transactionForId freshId graph')]
733+ let transIds = [freshId | isRight (RE.transactionForId freshId graph')]
683 pure (Right (discon', graph', transIds))
734 pure (Right (discon', graph', transIds))
684{-
735{-
685executeGraphExpr sessionId (InProcessConnection conf) graphExpr = excEither $ do
736executeGraphExpr sessionId (InProcessConnection conf) graphExpr = excEither $ do
@@ -740,7 +791,7 @@ executeGraphExpr sessionId (InProcessConnection conf) graphExpr = excEither $ do
740 Left err -> pure $ Left err
791 Left err -> pure $ Left err
741 Right previousTrans -> do
792 Right previousTrans -> do
742 (evaldNots, nodes) <- executeCommitExprSTM_ (Trans.concreteDatabaseContext previousTrans) (Sess.concreteDatabaseContext session) clientNodes
793 (evaldNots, nodes) <- executeCommitExprSTM_ (Trans.concreteDatabaseContext previousTrans) (Sess.concreteDatabaseContext session) clientNodes
743− nodesToNotify <- toList (STMSet.stream nodes)
794+ nodesToNotify <- toList (StmSet.stream nodes)
744 pure $ Right (evaldNots, nodesToNotify, newGraph)
795 pure $ Right (evaldNots, nodesToNotify, newGraph)
745 else
796 else
746 pure $ Right (M.empty, [], newGraph)
797 pure $ Right (M.empty, [], newGraph)
@@ -759,11 +810,10 @@ executeTransGraphRelationalExpr :: SessionId -> Connection -> TransGraphRelation
759executeTransGraphRelationalExpr _ (InProcessConnection conf) tgraphExpr = excEither . atomically $ do
810executeTransGraphRelationalExpr _ (InProcessConnection conf) tgraphExpr = excEither . atomically $ do
760 let graphTvar = ipTransactionGraph conf
811 let graphTvar = ipTransactionGraph conf
761 graph <- readTVar graphTvar
812 graph <- readTVar graphTvar
762− case evalTransGraphRelationalExpr tgraphExpr graph of
813+ pure $ force $ optimizeAndEvalTransGraphRelationalExpr graph tgraphExpr
763− Left err -> pure (Left err)
764− Right relExpr -> case runReader (RE.evalRelationalExpr relExpr) (RE.mkRelationalExprState DBC.empty) of
814+{- case runReader (RE.evalRelationalExpr relExpr) (RE.mkRelationalExprState DBC.empty) of
765 Left err -> pure (Left err)
815 Left err -> pure (Left err)
766− Right rel -> pure (force (Right rel))
816+ Right rel -> pure (force (Right rel))-}
767executeTransGraphRelationalExpr sessionId conn@(RemoteProcessConnection _) tgraphExpr = remoteCall conn (ExecuteTransGraphRelationalExpr sessionId tgraphExpr)
817executeTransGraphRelationalExpr sessionId conn@(RemoteProcessConnection _) tgraphExpr = remoteCall conn (ExecuteTransGraphRelationalExpr sessionId tgraphExpr)
768
818
769-- | Schema expressions manipulate the isomorphic schemas for the current 'DatabaseContext'.
819-- | Schema expressions manipulate the isomorphic schemas for the current 'DatabaseContext'.
@@ -775,14 +825,17 @@ executeSchemaExpr sessionId (InProcessConnection conf) schemaExpr = atomically $
775 Left err -> pure (Left err)
825 Left err -> pure (Left err)
776 Right (session, _) -> do
826 Right (session, _) -> do
777 let subschemas' = subschemas session
827 let subschemas' = subschemas session
828+ transId = Sess.parentId session
829+ context = Sess.concreteDatabaseContext session
830+ graph <- readTVar (ipTransactionGraph conf)
778− case Schema.evalSchemaExpr schemaExpr (Sess.concreteDatabaseContext session) subschemas' of
831+ case Schema.evalSchemaExpr schemaExpr context transId graph subschemas' of
779 Left err -> pure (Left err)
832 Left err -> pure (Left err)
780 Right (newSubschemas, newContext) -> do
833 Right (newSubschemas, newContext) -> do
781 --hm- maybe we should start using lenses
834 --hm- maybe we should start using lenses
782 let discon = Sess.disconnectedTransaction session
835 let discon = Sess.disconnectedTransaction session
783 newSchemas = Schemas newContext newSubschemas
836 newSchemas = Schemas newContext newSubschemas
784− newSession = Session (DisconnectedTransaction (Discon.parentId discon) newSchemas True) (Sess.schemaName session)
837+ newSession = Session (DisconnectedTransaction (Discon.parentId discon) newSchemas False) (Sess.schemaName session)
785− STMMap.insert newSession sessionId sessions
838+ StmMap.insert newSession sessionId sessions
786 pure (Right ())
839 pure (Right ())
787executeSchemaExpr sessionId conn@(RemoteProcessConnection _) schemaExpr = remoteCall conn (ExecuteSchemaExpr sessionId schemaExpr)
840executeSchemaExpr sessionId conn@(RemoteProcessConnection _) schemaExpr = remoteCall conn (ExecuteSchemaExpr sessionId schemaExpr)
788
841
@@ -831,7 +884,10 @@ typeForRelationalExprSTM sessionId (InProcessConnection conf) relExpr = do
831 Schema.processRelationalExprInSchema schema relExpr
884 Schema.processRelationalExprInSchema schema relExpr
832 case processed of
885 case processed of
833 Left err -> pure (Left err)
886 Left err -> pure (Left err)
887+ Right relExpr' -> do
888+ graph <- readTVar (ipTransactionGraph conf)
834− Right relExpr' -> pure $ runReader (RE.typeForRelationalExpr relExpr') (RE.mkRelationalExprState (Sess.concreteDatabaseContext session))
889+ let reEnv = RE.mkRelationalExprEnv (Sess.concreteDatabaseContext session) graph
890+ pure $ RE.runRelationalExprM reEnv (RE.typeForRelationalExpr relExpr')
835
891
836typeForRelationalExprSTM _ _ _ = error "typeForRelationalExprSTM called on non-local connection"
892typeForRelationalExprSTM _ _ _ = error "typeForRelationalExprSTM called on non-local connection"
837
893
@@ -864,17 +920,22 @@ typeConstructorMapping sessionId (InProcessConnection conf) = do
864typeConstructorMapping sessionId conn@(RemoteProcessConnection _) = remoteCall conn (RetrieveTypeConstructorMapping sessionId)
920typeConstructorMapping sessionId conn@(RemoteProcessConnection _) = remoteCall conn (RetrieveTypeConstructorMapping sessionId)
865
921
866-- | 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.
922-- | 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.
867−planForDatabaseContextExpr :: SessionId -> Connection -> DatabaseContextExpr -> IO (Either RelationalError DatabaseContextExpr)
923+planForDatabaseContextExpr :: SessionId -> Connection -> DatabaseContextExpr -> IO (Either RelationalError GraphRefDatabaseContextExpr)
868planForDatabaseContextExpr sessionId (InProcessConnection conf) dbExpr = do
924planForDatabaseContextExpr sessionId (InProcessConnection conf) dbExpr = do
869 let sessions = ipSessions conf
925 let sessions = ipSessions conf
870 atomically $ do
926 atomically $ do
927+ graph <- readTVar (ipTransactionGraph conf)
871 eSession <- sessionAndSchema sessionId sessions
928 eSession <- sessionAndSchema sessionId sessions
872 case eSession of
929 case eSession of
873 Left err -> pure $ Left err
930 Left err -> pure $ Left err
931+ Right (session, _) ->
874− Right (session, _) -> if schemaName session == defaultSchemaName then
932+ if schemaName session == defaultSchemaName then do
875− pure $ evalState (applyStaticDatabaseOptimization dbExpr) (RE.freshDatabaseState (Sess.concreteDatabaseContext session))
933+ let ctx = Sess.concreteDatabaseContext session
934+ transId = Sess.parentId session
935+ gfExpr = runProcessExprM UncommittedContextMarker (processDatabaseContextExpr dbExpr)
936+ pure $ runGraphRefSOptDatabaseContextExprM transId ctx graph (optimizeGraphRefDatabaseContextExpr gfExpr)
876− 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
937+ 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-}
877− pure (Right dbExpr)
938+ pure (Left NonConcreteSchemaPlanError)
878
939
879planForDatabaseContextExpr sessionId conn@(RemoteProcessConnection _) dbExpr = remoteCall conn (RetrievePlanForDatabaseContextExpr sessionId dbExpr)
940planForDatabaseContextExpr sessionId conn@(RemoteProcessConnection _) dbExpr = remoteCall conn (RetrievePlanForDatabaseContextExpr sessionId dbExpr)
880
941
@@ -901,17 +962,20 @@ relationVariablesAsRelation :: SessionId -> Connection -> IO (Either RelationalE
901relationVariablesAsRelation sessionId (InProcessConnection conf) = do
962relationVariablesAsRelation sessionId (InProcessConnection conf) = do
902 let sessions = ipSessions conf
963 let sessions = ipSessions conf
903 atomically $ do
964 atomically $ do
965+ graph <- readTVar (ipTransactionGraph conf)
904 eSession <- sessionAndSchema sessionId sessions
966 eSession <- sessionAndSchema sessionId sessions
905 case eSession of
967 case eSession of
906 Left err -> pure (Left err)
968 Left err -> pure (Left err)
907 Right (session, schema) -> do
969 Right (session, schema) -> do
908 let context = Sess.concreteDatabaseContext session
970 let context = Sess.concreteDatabaseContext session
909 if Sess.schemaName session == defaultSchemaName then
971 if Sess.schemaName session == defaultSchemaName then
910− pure $ R.relationVariablesAsRelation (relationVariables context)
972+ pure $ RE.relationVariablesAsRelation context graph
911 else
973 else
912− case Schema.relationVariablesInSchema schema context of
974+ case Schema.relationVariablesInSchema schema of
913 Left err -> pure (Left err)
975 Left err -> pure (Left err)
976+ Right relvars -> do
977+ let schemaContext = context {relationVariables = relvars }
914− Right relvars -> pure $ R.relationVariablesAsRelation relvars
978+ pure $ RE.relationVariablesAsRelation schemaContext graph
915
979
916relationVariablesAsRelation sessionId conn@(RemoteProcessConnection _) = remoteCall conn (RetrieveRelationVariableSummary sessionId)
980relationVariablesAsRelation sessionId conn@(RemoteProcessConnection _) = remoteCall conn (RetrieveRelationVariableSummary sessionId)
917
981
@@ -957,7 +1021,7 @@ headNameSTM_ sessionId sessions graphTvar = do
957 eSession <- sessionForSessionId sessionId sessions
1021 eSession <- sessionForSessionId sessionId sessions
958 case eSession of
1022 case eSession of
959 Left err -> pure (Left err)
1023 Left err -> pure (Left err)
960− Right session -> case transactionForId (Sess.parentId session) graph of
1024+ Right session -> case RE.transactionForId (Sess.parentId session) graph of
961 Left err -> pure (Left err)
1025 Left err -> pure (Left err)
962 Right parentTrans -> case headNameForTransaction parentTrans graph of
1026 Right parentTrans -> case headNameForTransaction parentTrans graph of
963 Nothing -> pure (Left UnknownHeadError)
1027 Nothing -> pure (Left UnknownHeadError)
@@ -1003,14 +1067,14 @@ callTestTimeout_ sessionId conn@(RemoteProcessConnection _) = remoteCall conn (T
1003
1067
1004--used in tests only
1068--used in tests only
1005transactionGraph_ :: Connection -> IO TransactionGraph
1069transactionGraph_ :: Connection -> IO TransactionGraph
1006−transactionGraph_ (InProcessConnection conf) = atomically $ readTVar (ipTransactionGraph conf)
1070+transactionGraph_ (InProcessConnection conf) = readTVarIO (ipTransactionGraph conf)
1007transactionGraph_ _ = error "remote connection used"
1071transactionGraph_ _ = error "remote connection used"
1008
1072
1009--used in tests only
1073--used in tests only
1010disconnectedTransaction_ :: SessionId -> Connection -> IO DisconnectedTransaction
1074disconnectedTransaction_ :: SessionId -> Connection -> IO DisconnectedTransaction
1011disconnectedTransaction_ sessionId (InProcessConnection conf) = do
1075disconnectedTransaction_ sessionId (InProcessConnection conf) = do
1012 let sessions = ipSessions conf
1076 let sessions = ipSessions conf
1013− mSession <- atomically $ STMMap.lookup sessionId sessions
1077+ mSession <- atomically $ StmMap.lookup sessionId sessions
1014 case mSession of
1078 case mSession of
1015 Nothing -> error "No such session"
1079 Nothing -> error "No such session"
1016 Just (Sess.Session discon _) -> pure discon
1080 Just (Sess.Session discon _) -> pure discon
@@ -1068,13 +1132,13 @@ commitLock_ sessionId conf stmBlock = do
1068 Right (discon', graph', transactionIdsToPersist) -> do
1132 Right (discon', graph', transactionIdsToPersist) -> do
1069 writeTVar graphTvar graph'
1133 writeTVar graphTvar graph'
1070 let newSession = Session discon' (Sess.schemaName session)
1134 let newSession = Session discon' (Sess.schemaName session)
1071− STMMap.insert newSession sessionId sessions
1135+ StmMap.insert newSession sessionId sessions
1072− case transactionForId (Sess.parentId session) oldGraph of
1136+ case RE.transactionForId (Sess.parentId session) oldGraph of
1073 Left err -> pure $ Left err
1137 Left err -> pure $ Left err
1074 Right previousTrans ->
1138 Right previousTrans ->
1075 if not (Prelude.null transactionIdsToPersist) then do
1139 if not (Prelude.null transactionIdsToPersist) then do
1076− (evaldNots, nodes) <- executeCommitExprSTM_ (Trans.concreteDatabaseContext previousTrans) (Sess.concreteDatabaseContext session) clientNodes
1140+ (evaldNots, nodes) <- executeCommitExprSTM_ graph' (Trans.concreteDatabaseContext previousTrans) (Sess.concreteDatabaseContext session) clientNodes
1077− nodesToNotify <- toList (STMSet.stream nodes)
1141+ nodesToNotify <- stmSetToList nodes
1078 pure $ Right (evaldNots, nodesToNotify, graph', transactionIdsToPersist)
1142 pure $ Right (evaldNots, nodesToNotify, graph', transactionIdsToPersist)
1079 else pure (Right (M.empty, [], graph', []))
1143 else pure (Right (M.empty, [], graph', []))
1080
1144
@@ -1091,7 +1155,7 @@ writeDisconAndGraph_ :: TVar TransactionGraph -> SessionId -> Session -> Session
1091writeDisconAndGraph_ graphTvar sessionId session sessions discon graph = do
1155writeDisconAndGraph_ graphTvar sessionId session sessions discon graph = do
1092 writeTVar graphTvar graph
1156 writeTVar graphTvar graph
1093 let newSession = Session discon (Sess.schemaName session)
1157 let newSession = Session discon (Sess.schemaName session)
1094− STMMap.insert newSession sessionId sessions
1158+ StmMap.insert newSession sessionId sessions
1095-}
1159-}
1096
1160
1097-- | Runs an IO monad, commits the result when the monad returns no errors, otherwise, rolls back the changes and the error.
1161-- | Runs an IO monad, commits the result when the monad returns no errors, otherwise, rolls back the changes and the error.
@@ -1117,3 +1181,45 @@ withTransaction sessionId conn io successFunc = bracketOnError (pure ()) (const
1117 Right _ -> pure (Right val)
1181 Right _ -> pure (Right val)
1118 else -- no updates executed, so don't create a commit
1182 else -- no updates executed, so don't create a commit
1119 pure (Right val)
1183 pure (Right val)
1184+
1185+executeDataFrameExpr :: SessionId -> Connection -> DF.DataFrameExpr -> IO (Either RelationalError DF.DataFrame)
1186+executeDataFrameExpr sessionId conn@(InProcessConnection _) dfExpr = do
1187+ eRel <- executeRelationalExpr sessionId conn (DF.convertExpr dfExpr)
1188+ case eRel of
1189+ Left err -> pure (Left err)
1190+ Right rel -> do
1191+ let relAttrs = R.attributes rel
1192+ attrName (DF.AttributeOrderExpr name _) = name
1193+ order (DF.AttributeOrderExpr _ ord) = ord
1194+ orders = map order (DF.orderExprs dfExpr)
1195+ attributeForName' = flip attributeForName relAttrs
1196+ attrNames = map attrName (DF.orderExprs dfExpr)
1197+ verified = forM attrNames attributeForName'
1198+ case verified of
1199+ Left err -> pure (Left err)
1200+ Right attrs -> do
1201+ let attrOrders = zipWith
1202+ (DF.AttributeOrder . attributeName)
1203+ attrs
1204+ orders
1205+ case DF.sortDataFrameBy attrOrders . DF.toDataFrame $ rel of
1206+ Left err -> pure (Left err)
1207+ Right dFrame -> do
1208+ let dFrame' = maybe dFrame (`DF.drop'` dFrame) (DF.offset dfExpr)
1209+ dFrame'' = maybe dFrame' (`DF.take'` dFrame') (DF.limit dfExpr)
1210+ pure (Right dFrame'')
1211+executeDataFrameExpr sessionId conn@(RemoteProcessConnection _) dfExpr = remoteCall conn (ExecuteDataFrameExpr sessionId dfExpr)
1212+
1213+validateMerkleHashes :: SessionId -> Connection -> IO (Either RelationalError ())
1214+validateMerkleHashes sessionId (InProcessConnection conf) = do
1215+ let sessions = ipSessions conf
1216+ atomically $ do
1217+ eSession <- sessionForSessionId sessionId sessions
1218+ case eSession of
1219+ Left err -> pure (Left err)
1220+ Right _ -> do
1221+ graph <- readTVar (ipTransactionGraph conf)
1222+ case Graph.validateMerkleHashes graph of
1223+ Left merkleErrs -> pure $ Left $ someErrors (map (\(MerkleValidationError tid expected actual) -> MerkleHashValidationError tid expected actual) merkleErrs)
1224+ Right () -> pure (Right ())
1225+validateMerkleHashes sessionId conn@RemoteProcessConnection{} = remoteCall conn (ExecuteValidateMerkleHashes sessionId)
src/lib/ProjectM36/Client/Simple.hs+2−1
@@ -25,7 +25,8 @@ module ProjectM36.Client.Simple (
25 C.PersistenceStrategy(..),
25 C.PersistenceStrategy(..),
26 C.NotificationCallback,
26 C.NotificationCallback,
27 C.emptyNotificationCallback,
27 C.emptyNotificationCallback,
28− C.DatabaseContextExpr(..),
28+ C.DatabaseContextExprBase(..),
29+ C.DatabaseContextExpr,
29 C.RelationalExprBase(..)
30 C.RelationalExprBase(..)
30 ) where
31 ) where
31
32
src/lib/ProjectM36/DataFrame.hsnew file+176
@@ -0,0 +1,176 @@
1+{-# LANGUAGE DeriveGeneric, DeriveAnyClass #-}
2+{- A dataframe is a strongly-typed, ordered list of named tuples. A dataframe differs from a relation in that its tuples are ordered.-}
3+module ProjectM36.DataFrame where
4+import ProjectM36.Base
5+import ProjectM36.Attribute as A
6+import ProjectM36.Error
7+import qualified ProjectM36.Relation as R
8+import ProjectM36.Relation.Show.Term
9+import qualified ProjectM36.Relation.Show.HTML as RelHTML
10+import ProjectM36.DataTypes.Sorting
11+import ProjectM36.AtomType
12+import ProjectM36.Atom
13+import qualified Data.Vector as V
14+import GHC.Generics
15+import qualified Data.List as L
16+import qualified Data.Set as S
17+import Data.Maybe
18+import qualified Data.Text as T
19+import Data.Binary
20+import Control.Arrow
21+#if __GLASGOW_HASKELL__ < 804
22+import Data.Monoid
23+#endif
24+
25+data AttributeOrderExpr = AttributeOrderExpr AttributeName Order deriving (Show, Generic, Binary)
26+data AttributeOrder = AttributeOrder AttributeName Order deriving (Show, Generic, Binary)
27+data Order = AscendingOrder | DescendingOrder deriving (Eq, Show, Generic, Binary)
28+
29+ascending :: T.Text
30+ascending = "⬆"
31+
32+descending :: T.Text
33+descending = "⬇"
34+
35+arbitrary :: T.Text
36+arbitrary = "↕"
37+
38+data DataFrame = DataFrame {
39+ orders :: [AttributeOrder],
40+ attributes :: Attributes,
41+ tuples :: [DataFrameTuple]
42+ } deriving (Show, Generic, Binary)
43+
44+data DataFrameTuple = DataFrameTuple Attributes (V.Vector Atom) deriving (Eq, Show, Generic, Binary)
45+
46+sortDataFrameBy :: [AttributeOrder] -> DataFrame -> Either RelationalError DataFrame
47+sortDataFrameBy attrOrders frame = do
48+ attrs <- mapM (\(AttributeOrder nam _) -> A.attributeForName nam (attributes frame)) attrOrders
49+ mapM_ (\attr -> if not (isSortableAtomType (atomType attr)) then
50+ Left (AttributeNotSortableError attr)
51+ else
52+ pure ()) attrs
53+ pure $ DataFrame attrOrders (attributes frame) (sortTuplesBy (compareTupleByAttributeOrders attrOrders) (tuples frame))
54+
55+sortTuplesBy :: (DataFrameTuple -> DataFrameTuple -> Ordering) -> [DataFrameTuple] -> [DataFrameTuple]
56+sortTuplesBy = L.sortBy
57+
58+compareTupleByAttributeOrders :: [AttributeOrder] -> DataFrameTuple -> DataFrameTuple -> Ordering
59+compareTupleByAttributeOrders attributeOrders tup1 tup2 =
60+ let compare' (AttributeOrder attr order) = if order == DescendingOrder
61+ then compareTupleByOneAttributeName attr tup2 tup1
62+ else compareTupleByOneAttributeName attr tup1 tup2
63+ res = map compare' attributeOrders in
64+ fromMaybe EQ (L.find (/= EQ) res)
65+
66+compareTupleByOneAttributeName :: AttributeName -> DataFrameTuple -> DataFrameTuple -> Ordering
67+compareTupleByOneAttributeName attr tuple1 tuple2 =
68+ let eAtom1 = atomForAttributeName attr tuple1
69+ eAtom2 = atomForAttributeName attr tuple2 in
70+ case eAtom1 of
71+ Left err -> error (show err)
72+ Right atom1 ->
73+ case eAtom2 of
74+ Left err -> error (show err)
75+ Right atom2 -> compareAtoms atom1 atom2
76+
77+atomForAttributeName :: AttributeName -> DataFrameTuple -> Either RelationalError Atom
78+atomForAttributeName attrName (DataFrameTuple tupAttrs tupVec) = case V.findIndex (\attr -> attributeName attr == attrName) tupAttrs of
79+ Nothing -> Left (NoSuchAttributeNamesError (S.singleton attrName))
80+ Just index -> case tupVec V.!? index of
81+ Nothing -> Left (NoSuchAttributeNamesError (S.singleton attrName))
82+ Just atom -> Right atom
83+
84+take' :: Integer -> DataFrame -> DataFrame
85+take' n df = df { tuples = take (fromInteger n) (tuples df) }
86+
87+drop' :: Integer -> DataFrame -> DataFrame
88+drop' n df = df { tuples = drop (fromInteger n) (tuples df) }
89+
90+toDataFrame :: Relation -> DataFrame
91+toDataFrame (Relation attrs (RelationTupleSet tuples')) = DataFrame [] attrs (map (\(RelationTuple tupAttrs tupVec) -> DataFrameTuple tupAttrs tupVec) tuples')
92+
93+fromDataFrame :: DataFrame -> Either RelationalError Relation
94+fromDataFrame df = R.mkRelation (attributes df) (RelationTupleSet tuples')
95+ where
96+ tuples' = map (\(DataFrameTuple attrs' tupVec) -> RelationTuple attrs' tupVec) (tuples df)
97+
98+showDataFrame :: DataFrame -> T.Text
99+showDataFrame = renderTable . dataFrameAsTable
100+
101+--terminal display
102+dataFrameAsTable :: DataFrame -> Table
103+dataFrameAsTable df = (header, body)
104+ where
105+ oAttrNames = orderedAttributeNames (attributes df)
106+ oAttrs = orderedAttributes (attributes df)
107+ header = "DF" : map dfPrettyAttribute oAttrs
108+ dfPrettyAttribute attr = prettyAttribute attr <> case L.find (\(AttributeOrder nam _) -> nam == attributeName attr) (orders df) of
109+ Nothing -> arbitrary
110+ Just (AttributeOrder _ AscendingOrder) -> ascending
111+ Just (AttributeOrder _ DescendingOrder) -> descending
112+ body = snd (L.foldl' tupleFolder (1 :: Int,[]) (tuples df))
113+ tupleFolder (count, acc) tuple = (count + 1,
114+ acc ++ [T.pack (show count) : map (\attrName -> case atomForAttributeName attrName tuple of
115+ Left _ -> "?"
116+ Right atom -> showAtom 0 atom
117+ ) oAttrNames])
118+
119+-- | A Relation can be converted to a DataFrame for sorting, limits, and offsets.
120+data DataFrameExpr = DataFrameExpr {
121+ convertExpr :: RelationalExpr,
122+ orderExprs :: [AttributeOrderExpr],
123+ offset :: Maybe Integer,
124+ limit :: Maybe Integer
125+ } deriving (Show, Binary, Generic)
126+
127+dataFrameAsHTML :: DataFrame -> T.Text
128+-- 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
129+dataFrameAsHTML df
130+ | length (tuples df) == 1 && L.null (attributes df) = style <>
131+ tablestart <>
132+ "<tr><th></th></tr>" <>
133+ "<tr><td></td></tr>" <>
134+ tablefooter <> "</table>"
135+ | L.null (tuples df) && L.null (attributes df) = style <>
136+ tablestart <>
137+ "<tr><th></th></tr>" <>
138+ tablefooter <>
139+ "</table>"
140+ | otherwise = style <>
141+ tablestart <>
142+ attributesAsHTML (attributes df) (orders df) <>
143+ tuplesAsHTML (tuples df) <>
144+ tablefooter <>
145+ "</table>"
146+ where
147+ cardinality = T.pack (show (length (tuples df)))
148+ style = "<style>.pm36dataframe {empty-cells: show;} .pm36dataframe tbody td, .pm36relation th { border: 1px solid black;}</style>"
149+ tablefooter = "<tfoot><tr><td colspan=\"100%\">" <> cardinality <> " tuples</td></tr></tfoot>"
150+ tablestart = "<table class=\"pm36dataframe\"\">"
151+
152+tuplesAsHTML :: [DataFrameTuple] -> T.Text
153+tuplesAsHTML = foldr folder ""
154+ where
155+ folder tuple acc = acc <> tupleAsHTML tuple
156+
157+tupleAssocs :: DataFrameTuple -> [(AttributeName, Atom)]
158+tupleAssocs (DataFrameTuple attrVec tupVec) = V.toList $ V.map (first attributeName) (V.zip attrVec tupVec)
159+
160+
161+tupleAsHTML :: DataFrameTuple -> T.Text
162+tupleAsHTML tuple = "<tr>" <> T.concat (L.map tupleFrag (tupleAssocs tuple)) <> "</tr>"
163+ where
164+ tupleFrag tup = "<td>" <> atomAsHTML (snd tup) <> "</td>"
165+ atomAsHTML (RelationAtom rel) = RelHTML.relationAsHTML rel
166+ atomAsHTML (TextAtom t) = "&quot;" <> t <> "&quot;"
167+ atomAsHTML atom = atomToText atom
168+
169+attributesAsHTML :: Attributes -> [AttributeOrder] -> T.Text
170+attributesAsHTML attrs orders' = "<tr>" <> T.concat (map oneAttrHTML (V.toList attrs)) <> "</tr>"
171+ where
172+ oneAttrHTML attr = "<th>" <> prettyAttribute attr <> ordering (attributeName attr) <> "</th>"
173+ ordering attrName = " " <> case L.find (\(AttributeOrder nam _) -> nam == attrName) orders' of
174+ Nothing -> "(arb)"
175+ Just (AttributeOrder _ AscendingOrder) -> "(asc)"
176+ Just (AttributeOrder _ DescendingOrder) -> "(desc)"
src/lib/ProjectM36/DataTypes/Basic.hs+2
@@ -4,6 +4,7 @@ import ProjectM36.DataTypes.Primitive
4import ProjectM36.DataTypes.Either
4import ProjectM36.DataTypes.Either
5import ProjectM36.DataTypes.Maybe
5import ProjectM36.DataTypes.Maybe
6import ProjectM36.DataTypes.List
6import ProjectM36.DataTypes.List
7+import ProjectM36.DataTypes.NonEmptyList
7import ProjectM36.DataTypes.Interval
8import ProjectM36.DataTypes.Interval
8import ProjectM36.Base
9import ProjectM36.Base
9
10
@@ -12,6 +13,7 @@ basicTypeConstructorMapping = primitiveTypeConstructorMapping ++
12 maybeTypeConstructorMapping ++
13 maybeTypeConstructorMapping ++
13 eitherTypeConstructorMapping ++
14 eitherTypeConstructorMapping ++
14 listTypeConstructorMapping ++
15 listTypeConstructorMapping ++
16+ nonEmptyListTypeConstructorMapping ++
15 intervalTypeConstructorMapping
17 intervalTypeConstructorMapping
16
18
17
19
src/lib/ProjectM36/DataTypes/NonEmptyList.hsnew file+53
@@ -0,0 +1,53 @@
1+module ProjectM36.DataTypes.NonEmptyList where
2+import ProjectM36.Base
3+import qualified Data.Map as M
4+import qualified Data.HashSet as HS
5+import ProjectM36.AtomFunctionError
6+import ProjectM36.DataTypes.List
7+
8+nonEmptyListAtomType :: AtomType -> AtomType
9+nonEmptyListAtomType arg = ConstructedAtomType "NonEmptyList" (M.singleton "a" arg)
10+
11+-- data NonEmptyList = NECons a (Cons a)
12+nonEmptyListTypeConstructorMapping :: TypeConstructorMapping
13+nonEmptyListTypeConstructorMapping = [(ADTypeConstructorDef "NonEmptyList" ["a"],
14+ [DataConstructorDef "NECons" [DataConstructorDefTypeVarNameArg "a",
15+ DataConstructorDefTypeConstructorArg (ADTypeConstructor "List" [TypeVariable "a"])]])]
16+
17+nonEmptyListLength :: Atom -> Either AtomFunctionError Int
18+nonEmptyListLength (ConstructedAtom "NECons" _ (_:nextCons:_)) = do
19+ c <- listLength nextCons
20+ pure (c + 1)
21+nonEmptyListLength (ConstructedAtom "NECons" _ _) = pure 1
22+nonEmptyListLength _ = Left AtomFunctionTypeMismatchError
23+
24+nonEmptyListHead :: Atom -> Either AtomFunctionError Atom
25+nonEmptyListHead (ConstructedAtom "NECons" _ (val:_)) = pure val
26+nonEmptyListHead _ = Left AtomFunctionTypeMismatchError
27+
28+{-
29+listMaybeHead :: Atom -> Either AtomFunctionError Atom
30+listMaybeHead (ConstructedAtom "Cons" _ (val:_)) = pure (ConstructedAtom "Just" aType [val])
31+ where
32+ aType = maybeAtomType (atomTypeForAtom val)
33+listMaybeHead (ConstructedAtom "Empty" (ConstructedAtomType _ tvMap) _) =
34+ case M.lookup "a" tvMap of
35+ Nothing -> Left AtomFunctionTypeMismatchError
36+ Just aType -> pure (ConstructedAtom "Nothing" aType [])
37+listMaybeHead _ = Left AtomFunctionTypeMismatchError
38+-}
39+
40+nonEmptyListAtomFunctions :: AtomFunctions
41+nonEmptyListAtomFunctions = HS.fromList [
42+ AtomFunction {
43+ atomFuncName = "nonEmptyListLength",
44+ atomFuncType = [nonEmptyListAtomType (TypeVariableType "a"), IntAtomType],
45+ atomFuncBody = AtomFunctionBody Nothing (\(nonEmptyListAtom:_) ->
46+ IntAtom . fromIntegral <$> nonEmptyListLength nonEmptyListAtom)
47+ },
48+ AtomFunction {
49+ atomFuncName = "nonEmptyListHead",
50+ atomFuncType = [nonEmptyListAtomType (TypeVariableType "a"), TypeVariableType "a"],
51+ atomFuncBody = AtomFunctionBody Nothing (\(nonEmptyListAtom:_) -> nonEmptyListHead nonEmptyListAtom)
52+ }
53+ ]
src/lib/ProjectM36/DataTypes/Primitive.hs+3
@@ -27,6 +27,9 @@ textTypeConstructor = PrimitiveTypeConstructor "Text" TextAtomType
27dayTypeConstructor :: TypeConstructor
27dayTypeConstructor :: TypeConstructor
28dayTypeConstructor = PrimitiveTypeConstructor "Day" DayAtomType
28dayTypeConstructor = PrimitiveTypeConstructor "Day" DayAtomType
29
29
30+dateTimeTypeConstructor :: TypeConstructor
31+dateTimeTypeConstructor = PrimitiveTypeConstructor "DateTime" DayAtomType
32+
30-- | Return the type of an 'Atom'.
33-- | Return the type of an 'Atom'.
31atomTypeForAtom :: Atom -> AtomType
34atomTypeForAtom :: Atom -> AtomType
32atomTypeForAtom (IntAtom _) = IntAtomType
35atomTypeForAtom (IntAtom _) = IntAtomType
src/lib/ProjectM36/DataTypes/Sorting.hsnew file+30
@@ -0,0 +1,30 @@
1+module ProjectM36.DataTypes.Sorting where
2+import ProjectM36.Base
3+
4+compareAtoms :: Atom -> Atom -> Ordering
5+compareAtoms (IntegerAtom i1) (IntegerAtom i2) = compare i1 i2
6+compareAtoms (IntAtom i1) (IntAtom i2) = compare i1 i2
7+compareAtoms (DoubleAtom d1) (DoubleAtom d2) = compare d1 d2
8+compareAtoms (TextAtom t1) (TextAtom t2) = compare t1 t2
9+compareAtoms (DayAtom d1) (DayAtom d2) = compare d1 d2
10+compareAtoms (DateTimeAtom d1) (DateTimeAtom d2) = compare d1 d2
11+compareAtoms (ByteStringAtom b1) (ByteStringAtom b2) = compare b1 b2
12+compareAtoms (BoolAtom b1) (BoolAtom b2) = compare b1 b2
13+compareAtoms (RelationAtom _) _ = EQ
14+compareAtoms ConstructedAtom{} _ = EQ
15+compareAtoms _ _ = EQ
16+
17+isSortableAtomType :: AtomType -> Bool
18+isSortableAtomType typ = case typ of
19+ IntAtomType -> True
20+ IntegerAtomType -> True
21+ DoubleAtomType -> True
22+ TextAtomType -> True
23+ DayAtomType -> True
24+ DateTimeAtomType -> True
25+ ByteStringAtomType -> False
26+ BoolAtomType -> True
27+ RelationAtomType _ -> False
28+ ConstructedAtomType _ _ -> False
29+ TypeVariableType _ -> False
30+
src/lib/ProjectM36/DatabaseContext.hs+24−5
@@ -1,11 +1,15 @@
1module ProjectM36.DatabaseContext where
1module ProjectM36.DatabaseContext where
2import ProjectM36.Base
2import ProjectM36.Base
3+import Control.Monad (void)
3import qualified Data.Map as M
4import qualified Data.Map as M
4import qualified Data.HashSet as HS
5import qualified Data.HashSet as HS
5import ProjectM36.DataTypes.Basic
6import ProjectM36.DataTypes.Basic
6import ProjectM36.AtomFunctions.Basic
7import ProjectM36.AtomFunctions.Basic
7−import ProjectM36.DatabaseContextFunction
8import ProjectM36.Relation
8import ProjectM36.Relation
9+import qualified Data.ByteString.Lazy as BL
10+import Data.Binary as B
11+import ProjectM36.AtomFunction as AF
12+import ProjectM36.DatabaseContextFunction as DBCF
9
13
10empty :: DatabaseContext
14empty :: DatabaseContext
11empty = DatabaseContext { inclusionDependencies = M.empty,
15empty = DatabaseContext { inclusionDependencies = M.empty,
@@ -14,22 +18,37 @@ empty = DatabaseContext { inclusionDependencies = M.empty,
14 atomFunctions = HS.empty,
18 atomFunctions = HS.empty,
15 dbcFunctions = HS.empty,
19 dbcFunctions = HS.empty,
16 typeConstructorMapping = [] }
20 typeConstructorMapping = [] }
21+
22+-- | Remove TransactionId markers on GraphRefRelationalExpr
23+stripGraphRefRelationalExpr :: GraphRefRelationalExpr -> RelationalExpr
24+stripGraphRefRelationalExpr = void
17
25
18-- | convert an existing database context into its constituent expression.
26-- | convert an existing database context into its constituent expression.
19databaseContextAsDatabaseContextExpr :: DatabaseContext -> DatabaseContextExpr
27databaseContextAsDatabaseContextExpr :: DatabaseContext -> DatabaseContextExpr
20databaseContextAsDatabaseContextExpr context = MultipleExpr $ relVarsExprs ++ incDepsExprs ++ funcsExprs
28databaseContextAsDatabaseContextExpr context = MultipleExpr $ relVarsExprs ++ incDepsExprs ++ funcsExprs
21 where
29 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))
23 incDepsExprs :: [DatabaseContextExpr]
31 incDepsExprs :: [DatabaseContextExpr]
24 incDepsExprs = map (uncurry AddInclusionDependency) (M.toList (inclusionDependencies context))
32 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-}
26
34
27basicDatabaseContext :: DatabaseContext
35basicDatabaseContext :: DatabaseContext
28basicDatabaseContext = DatabaseContext { inclusionDependencies = M.empty,
36basicDatabaseContext = DatabaseContext { inclusionDependencies = M.empty,
29− relationVariables = M.fromList [("true", relationTrue),
37+ relationVariables = M.fromList [("true", ExistingRelation relationTrue),
30− ("false", relationFalse)],
38+ ("false", ExistingRelation relationFalse)],
31 atomFunctions = basicAtomFunctions,
39 atomFunctions = basicAtomFunctions,
32 dbcFunctions = basicDatabaseContextFunctions,
40 dbcFunctions = basicDatabaseContextFunctions,
33 notifications = M.empty,
41 notifications = M.empty,
34 typeConstructorMapping = basicTypeConstructorMapping
42 typeConstructorMapping = basicTypeConstructorMapping
35 }
43 }
44+
45+--for building the Merkle hash
46+hashBytes :: DatabaseContext -> BL.ByteString
47+hashBytes ctx = mconcat [incDeps, rvs, atomFs, dbcFs, nots, tConsMap]
48+ where
49+ incDeps = B.encode (inclusionDependencies ctx)
50+ rvs = B.encode (relationVariables ctx)
51+ atomFs = HS.foldr (mappend . AF.hashBytes) mempty (atomFunctions ctx)
52+ dbcFs = HS.foldr (mappend . DBCF.hashBytes) mempty (dbcFunctions ctx)
53+ nots = B.encode (notifications ctx)
54+ tConsMap = B.encode (typeConstructorMapping ctx)
src/lib/ProjectM36/DatabaseContextFunction.hs+16−1
@@ -1,3 +1,4 @@
1+{-# LANGUAGE CPP #-}
1module ProjectM36.DatabaseContextFunction where
2module ProjectM36.DatabaseContextFunction where
2--implements functions which operate as: [Atom] -> DatabaseContextExpr -> Either RelationalError DatabaseContextExpr
3--implements functions which operate as: [Atom] -> DatabaseContextExpr -> Either RelationalError DatabaseContextExpr
3import ProjectM36.Base
4import ProjectM36.Base
@@ -9,6 +10,8 @@ import qualified Data.HashSet as HS
9import qualified Data.Map as M
10import qualified Data.Map as M
10import ProjectM36.ScriptSession
11import ProjectM36.ScriptSession
11import qualified Data.Text as T
12import qualified Data.Text as T
13+import qualified Data.ByteString.Lazy as BL
14+import Data.Binary as B
12
15
13emptyDatabaseContextFunction :: DatabaseContextFunctionName -> DatabaseContextFunction
16emptyDatabaseContextFunction :: DatabaseContextFunctionName -> DatabaseContextFunction
14emptyDatabaseContextFunction name = DatabaseContextFunction {
17emptyDatabaseContextFunction name = DatabaseContextFunction {
@@ -61,7 +64,11 @@ createScriptedDatabaseContextFunction :: DatabaseContextFunctionName -> [TypeCon
61createScriptedDatabaseContextFunction funcName argsIn retArg = AddDatabaseContextFunction funcName (argsIn ++ [databaseContextFunctionReturnType retArg])
64createScriptedDatabaseContextFunction funcName argsIn retArg = AddDatabaseContextFunction funcName (argsIn ++ [databaseContextFunctionReturnType retArg])
62
65
63loadDatabaseContextFunctions :: ModName -> FuncName -> FilePath -> IO (Either LoadSymbolError [DatabaseContextFunction])
66loadDatabaseContextFunctions :: ModName -> FuncName -> FilePath -> IO (Either LoadSymbolError [DatabaseContextFunction])
67+#ifdef PM36_HASKELL_SCRIPTING
64loadDatabaseContextFunctions = loadFunction
68loadDatabaseContextFunctions = loadFunction
69+#else
70+loadDatabaseContextFunctions _ _ _ = pure (Left LoadSymbolError)
71+#endif
65
72
66databaseContextFunctionsAsRelation :: DatabaseContextFunctions -> Either RelationalError Relation
73databaseContextFunctionsAsRelation :: DatabaseContextFunctions -> Either RelationalError Relation
67databaseContextFunctionsAsRelation dbcFuncs = mkRelationFromList attrs tups
74databaseContextFunctionsAsRelation dbcFuncs = mkRelationFromList attrs tups
@@ -72,4 +79,12 @@ databaseContextFunctionsAsRelation dbcFuncs = mkRelationFromList attrs tups
72 dbcFuncToTuple func = [TextAtom (dbcFuncName func),
79 dbcFuncToTuple func = [TextAtom (dbcFuncName func),
73 TextAtom (dbcTextType (dbcFuncType func))]
80 TextAtom (dbcTextType (dbcFuncType func))]
74 dbcTextType typ = T.intercalate " -> " (map prettyAtomType typ ++ ["DatabaseContext", "DatabaseContext"])
81 dbcTextType typ = T.intercalate " -> " (map prettyAtomType typ ++ ["DatabaseContext", "DatabaseContext"])
75−
82+
83+-- for merkle hash
84+hashBytes :: DatabaseContextFunction -> BL.ByteString
85+hashBytes func = mconcat [fname, ftype, fbody]
86+ where
87+ fname = B.encode (dbcFuncName func)
88+ ftype = B.encode (dbcFuncType func)
89+ fbody = case dbcFuncBody func of
90+ DatabaseContextFunctionBody mBody _ -> B.encode mBody
src/lib/ProjectM36/DatabaseContextFunctionUtils.hs+15−8
@@ -3,13 +3,20 @@ import ProjectM36.RelationalExpression
3import ProjectM36.Base
3import ProjectM36.Base
4import ProjectM36.DatabaseContextFunctionError
4import ProjectM36.DatabaseContextFunctionError
5import ProjectM36.Error
5import ProjectM36.Error
6−import Control.Monad.State
6+import ProjectM36.StaticOptimizer
7−import Control.Monad.Trans.Reader
8
7
9−executeDatabaseContextExpr :: DatabaseContextExpr -> DatabaseContext -> Either DatabaseContextFunctionError DatabaseContext
8+executeDatabaseContextExpr :: DatabaseContextExpr -> TransactionId -> TransactionGraph -> DatabaseContext -> Either DatabaseContextFunctionError DatabaseContext
10−executeDatabaseContextExpr expr context = case runState (evalDatabaseContextExpr expr) (freshDatabaseState context) of
9+executeDatabaseContextExpr expr transId graph context' =
11− (Right (), (context', _, _)) -> pure context'
10+ case run of
11+ Right st -> pure (dbc_context st)
12− (Left err, _) -> error (show err)
12+ Left err -> error (show err)
13+ where
14+ env = mkDatabaseContextEvalEnv transId graph
15+ run = runDatabaseContextEvalMonad context' env (optimizeAndEvalDatabaseContextExpr True expr)
13
16
14−executeRelationalExpr :: RelationalExpr -> DatabaseContext -> Either RelationalError Relation
17+executeRelationalExpr :: RelationalExpr -> DatabaseContext -> TransactionGraph -> Either RelationalError Relation
15−executeRelationalExpr expr context = runReader (evalRelationalExpr expr) (mkRelationalExprState context)
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,
16 atomFunctions = basicAtomFunctions,
16 atomFunctions = basicAtomFunctions,
17 typeConstructorMapping = basicTypeConstructorMapping }
17 typeConstructorMapping = basicTypeConstructorMapping }
18 where -- these must be lower case now that data constructors are in play
18 where -- these must be lower case now that data constructors are in play
19− dateRelVars = M.fromList [("s", suppliers),
19+ dateRelVars = M.fromList [("s", ExistingRelation suppliers),
20− ("p", products),
20+ ("p", ExistingRelation products),
21− ("sp", supplierProducts)]
21+ ("sp", ExistingRelation supplierProducts)]
22 suppliers = suppliersRel
22 suppliers = suppliersRel
23 products = productsRel
23 products = productsRel
24 supplierProducts = supplierProductsRel
24 supplierProducts = supplierProductsRel
src/lib/ProjectM36/DisconnectedTransaction.hs+7−1
@@ -8,4 +8,10 @@ schemas :: DisconnectedTransaction -> Schemas
8schemas (DisconnectedTransaction _ s _) = s
8schemas (DisconnectedTransaction _ s _) = s
9
9
10parentId :: DisconnectedTransaction -> TransactionId
10parentId :: 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+10−1
@@ -1,6 +1,7 @@
1{-# LANGUAGE DeriveGeneric, DeriveAnyClass #-}
1{-# LANGUAGE DeriveGeneric, DeriveAnyClass #-}
2module ProjectM36.Error where
2module ProjectM36.Error where
3import ProjectM36.Base
3import ProjectM36.Base
4+import ProjectM36.MerkleHash
4import ProjectM36.DatabaseContextFunctionError
5import ProjectM36.DatabaseContextFunctionError
5import ProjectM36.AtomFunctionError
6import ProjectM36.AtomFunctionError
6import qualified Data.Set as S
7import qualified Data.Set as S
@@ -62,6 +63,7 @@ data RelationalError = NoSuchAttributeNamesError (S.Set AttributeName)
62 | AtomTypeNameInUseError AtomTypeName
63 | AtomTypeNameInUseError AtomTypeName
63 | IncompletelyDefinedAtomTypeWithConstructorError
64 | IncompletelyDefinedAtomTypeWithConstructorError
64 | AtomTypeNameNotInUseError AtomTypeName
65 | AtomTypeNameNotInUseError AtomTypeName
66+ | AttributeNotSortableError Attribute
65 | FunctionNameInUseError AtomFunctionName
67 | FunctionNameInUseError AtomFunctionName
66 | FunctionNameNotInUseError AtomFunctionName
68 | FunctionNameNotInUseError AtomFunctionName
67 | EmptyCommitError
69 | EmptyCommitError
@@ -95,6 +97,13 @@ data RelationalError = NoSuchAttributeNamesError (S.Set AttributeName)
95 | SchemaCreationError SchemaError
97 | SchemaCreationError SchemaError
96
98
97 | ImproperDatabaseStateError
99 | ImproperDatabaseStateError
100+
101+ | NonConcreteSchemaPlanError
102+
103+ | NoUncommittedContextInEvalError
104+ | TupleExprsReferenceMultipleMarkersError
105+
106+ | MerkleHashValidationError TransactionId MerkleHash MerkleHash
98
107
99 | MultipleErrors [RelationalError]
108 | MultipleErrors [RelationalError]
100 deriving (Show,Eq,Generic,Binary,Typeable, NFData)
109 deriving (Show,Eq,Generic,Binary,Typeable, NFData)
@@ -141,4 +150,4 @@ data SchemaError = RelVarReferencesMissing (S.Set RelVarName) |
141-- errors returned from the distributed-process call handlers
150-- errors returned from the distributed-process call handlers
142data ServerError = RequestTimeoutError |
151data ServerError = RequestTimeoutError |
143 ProcessDiedError String
152 ProcessDiedError String
144− deriving (Generic, Binary, Eq)
153+ deriving (Generic, Binary, Eq)
src/lib/ProjectM36/FileLock.hs+1−1
@@ -1,4 +1,4 @@
1−{-# LANGUAGE CPP, NamedFieldPuns #-}
1+{-# LANGUAGE CPP #-}
2--cross-platform file locking utilizing POSIX file locking on Unix/Linux and Windows file locking
2--cross-platform file locking utilizing POSIX file locking on Unix/Linux and Windows file locking
3--hackage's System.FileLock doesn't support POSIX advisory locks nor locking file based on file descriptors, hence this needless rewrite
3--hackage's System.FileLock doesn't support POSIX advisory locks nor locking file based on file descriptors, hence this needless rewrite
4module ProjectM36.FileLock where
4module 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/IsomorphicSchema.hs+28−29
@@ -3,20 +3,19 @@ module ProjectM36.IsomorphicSchema where
3import ProjectM36.Base
3import ProjectM36.Base
4import ProjectM36.Error
4import ProjectM36.Error
5import ProjectM36.MiscUtils
5import ProjectM36.MiscUtils
6−import ProjectM36.RelationalExpression
7import ProjectM36.Relation
6import ProjectM36.Relation
7+import ProjectM36.NormalizeExpr
8+import ProjectM36.RelationalExpression
8import qualified ProjectM36.AttributeNames as AN
9import qualified ProjectM36.AttributeNames as AN
9import Control.Monad
10import Control.Monad
10−import Control.Monad.State
11−import Control.Monad.Trans.Reader
12import GHC.Generics
11import GHC.Generics
13import Data.Binary
12import Data.Binary
14import qualified Data.Map as M
13import qualified Data.Map as M
15import qualified Data.Set as S
14import qualified Data.Set as S
16import qualified Data.List as L
15import qualified Data.List as L
17−import qualified Data.Text as T
16+#if __GLASGOW_HASKELL__ < 804
18import Data.Monoid
17import Data.Monoid
19−--import Debug.Trace
18+#endif
20-- isomorphic schemas offer bi-directional functors between two schemas
19-- isomorphic schemas offer bi-directional functors between two schemas
21
20
22--TODO: note that renaming a relvar should alter any stored isomorphisms as well
21--TODO: note that renaming a relvar should alter any stored isomorphisms as well
@@ -256,15 +255,15 @@ inclusionDependencyInSchema schema (InclusionDependency rexprA rexprB) = do
256inclusionDependenciesInSchema :: Schema -> InclusionDependencies -> Either RelationalError InclusionDependencies
255inclusionDependenciesInSchema :: Schema -> InclusionDependencies -> Either RelationalError InclusionDependencies
257inclusionDependenciesInSchema schema incDeps = M.fromList <$> mapM (\(depName, dep) -> inclusionDependencyInSchema schema dep >>= \newDep -> pure (depName, newDep)) (M.toList incDeps)
256inclusionDependenciesInSchema schema incDeps = M.fromList <$> mapM (\(depName, dep) -> inclusionDependencyInSchema schema dep >>= \newDep -> pure (depName, newDep)) (M.toList incDeps)
258
257
259−relationVariablesInSchema :: Schema -> DatabaseContext -> Either RelationalError RelationVariables
258+relationVariablesInSchema :: Schema -> Either RelationalError RelationVariables
260−relationVariablesInSchema schema@(Schema morphs) context = foldM transform M.empty morphs
259+relationVariablesInSchema schema@(Schema morphs) = foldM transform M.empty morphs
261 where
260 where
262 transform newRvMap morph = do
261 transform newRvMap morph = do
263 let rvNames = isomorphInRelVarNames morph
262 let rvNames = isomorphInRelVarNames morph
264 rvAssocs <- mapM (\rv -> do
263 rvAssocs <- mapM (\rv -> do
265 expr' <- processRelationalExprInSchema schema (RelationVariable rv ())
264 expr' <- processRelationalExprInSchema schema (RelationVariable rv ())
266− rel <- runReader (evalRelationalExpr expr') (RelationalExprStateElems context)
265+ let gfExpr = runProcessExprM UncommittedContextMarker (processRelationalExpr expr')
267− pure (rv, rel)) rvNames
266+ pure (rv, gfExpr)) rvNames
268 pure (M.union newRvMap (M.fromList rvAssocs))
267 pure (M.union newRvMap (M.fromList rvAssocs))
269
268
270
269
@@ -304,32 +303,32 @@ validate morph underlyingRvNames = if S.size invalidRvNames > 0 then
304
303
305-- | Create inclusion dependencies mainly for IsoRestrict because the predicate should hold in the base schema.
304-- | Create inclusion dependencies mainly for IsoRestrict because the predicate should hold in the base schema.
306createIncDepsForIsomorph :: SchemaName -> SchemaIsomorph -> InclusionDependencies
305createIncDepsForIsomorph :: SchemaName -> SchemaIsomorph -> InclusionDependencies
307−createIncDepsForIsomorph sname (IsoRestrict _ predi (rvTrue, rvFalse)) = let
306+createIncDepsForIsomorph sname (IsoRestrict origRv predi (rvTrue, rvFalse)) = let
308 newIncDep predicate rv = InclusionDependency (Project AN.empty (Restrict predicate (RelationVariable rv ()))) (ExistingRelation relationTrue)
307 newIncDep predicate rv = InclusionDependency (Project AN.empty (Restrict predicate (RelationVariable rv ()))) (ExistingRelation relationTrue)
309− incDepName b = "schema" <> "_" <> sname <> "_" <> T.pack (show b) in
308+ incDepName b = "schema" <> "_" <> sname <> "_" <> b in
310− M.fromList [(incDepName True, newIncDep predi rvTrue),
309+ M.fromList [(incDepName (origRv <> "_true"), newIncDep predi rvTrue),
311− (incDepName False, newIncDep (NotPredicate predi) rvFalse)]
310+ (incDepName (origRv <> "_false"), newIncDep (NotPredicate predi) rvFalse)]
312createIncDepsForIsomorph _ _ = M.empty
311createIncDepsForIsomorph _ _ = M.empty
313
312
314-- 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-- 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
315−evalSchemaExpr :: SchemaExpr -> DatabaseContext -> Subschemas -> Either RelationalError (Subschemas, DatabaseContext)
314+evalSchemaExpr :: SchemaExpr -> DatabaseContext -> TransactionId -> TransactionGraph -> Subschemas -> Either RelationalError (Subschemas, DatabaseContext)
316−evalSchemaExpr (AddSubschema sname morphs) context sschemas =
315+evalSchemaExpr (AddSubschema sname morphs) context transId graph sschemas =
317 if M.member sname sschemas then
316 if M.member sname sschemas then
318 Left (SubschemaNameInUseError sname)
317 Left (SubschemaNameInUseError sname)
319− else case valid of
318+ else
319+ case validateSchema (Schema morphs) context of
320− Just err -> Left (SchemaCreationError err)
320+ Just err -> Left (SchemaCreationError err)
321− Nothing ->
321+ Nothing -> do
322− let newSchemas = M.insert sname newSchema sschemas
322+ let newSchemas = M.insert sname newSchema sschemas
323+ newSchema = Schema morphs
323− moreIncDeps = foldr (\morph acc -> M.union acc (createIncDepsForIsomorph sname morph)) M.empty morphs
324+ moreIncDeps = foldr (\morph acc -> M.union acc (createIncDepsForIsomorph sname morph)) M.empty morphs
324− incDepExprs = MultipleExpr (map (uncurry AddInclusionDependency) (M.toList moreIncDeps))
325+ incDepExprs = MultipleExpr (map (uncurry AddInclusionDependency) (M.toList moreIncDeps))
325− in
326+ dbenv = mkDatabaseContextEvalEnv transId graph
326− case runState (evalDatabaseContextExpr incDepExprs) (context, M.empty, False) of
327+ dbstate <- runDatabaseContextEvalMonad context dbenv (evalGraphRefDatabaseContextExpr incDepExprs)
327− (Left err, _) -> Left err
328+ pure (newSchemas, dbc_context dbstate)
328− (Right (), (newContext,_,_)) -> pure (newSchemas, newContext) --need to propagate dirty flag here
329+--need to propagate dirty flag here
329− where
330+
330− newSchema = Schema morphs
331− valid = validateSchema newSchema context
332−evalSchemaExpr (RemoveSubschema sname) context sschemas = if M.member sname sschemas then
331+evalSchemaExpr (RemoveSubschema sname) context _ _ sschemas = if M.member sname sschemas then
333 pure (M.delete sname sschemas, context)
332 pure (M.delete sname sschemas, context)
334 else
333 else
335 Left (SubschemaNameNotInUseError sname)
334 Left (SubschemaNameNotInUseError sname)
src/lib/ProjectM36/Key.hs+2
@@ -2,7 +2,9 @@ module ProjectM36.Key where
2import ProjectM36.Base
2import ProjectM36.Base
3import ProjectM36.Relation
3import ProjectM36.Relation
4import qualified Data.Set as S
4import qualified Data.Set as S
5+#if __GLASGOW_HASKELL__ < 804
5import Data.Monoid
6import Data.Monoid
7+#endif
6
8
7{-
9{-
8keys 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
10keys 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+10
@@ -0,0 +1,10 @@
1+{-# LANGUAGE GeneralizedNewtypeDeriving, DeriveGeneric #-}
2+module ProjectM36.MerkleHash where
3+import Data.ByteString (ByteString)
4+import GHC.Generics
5+import Data.Binary (Binary)
6+import Control.DeepSeq (NFData)
7+
8+newtype MerkleHash = MerkleHash { _unMerkleHash :: ByteString }
9+ deriving (Show, Eq, Binary, Generic, Monoid, Semigroup, NFData)
10+
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 @@
1module ProjectM36.Notifications where
1module ProjectM36.Notifications where
2import ProjectM36.Base
2import ProjectM36.Base
3+import ProjectM36.Error
3import ProjectM36.RelationalExpression
4import ProjectM36.RelationalExpression
4−import Control.Monad.Trans.Reader
5+import ProjectM36.StaticOptimizer
5import qualified Data.Map as M
6import qualified Data.Map as M
6import Data.Either (isRight)
7import Data.Either (isRight)
7
8
8-- | Returns the notifications which should be triggered based on the transition from the first 'DatabaseContext' to the second 'DatabaseContext'.
9-- | 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 :: Notifications -> TransactionGraph -> DatabaseContext -> DatabaseContext -> Notifications
10−notificationChanges nots context1 context2 = M.filter notificationFilter nots
11+notificationChanges nots graph context1 context2 = M.filter notificationFilter nots
11 where
12 where
12− notificationFilter (Notification chExpr _ _) = let oldChangeEval = evalChangeExpr chExpr (RelationalExprStateElems context1)
13− newChangeEval = evalChangeExpr chExpr (RelationalExprStateElems context2) in
14− oldChangeEval /= newChangeEval && isRight oldChangeEval
13+ notificationFilter (Notification chExpr _ _) = oldChangeEval /= newChangeEval && isRight oldChangeEval
15− evalChangeExpr chExpr = runReader (evalRelationalExpr chExpr)
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
16
21
17
22
src/lib/ProjectM36/Persist.hs+8−5
@@ -66,7 +66,13 @@ renameSync sync srcPath dstPath = do
66atomicRename :: FilePath -> FilePath -> IO ()
66atomicRename :: FilePath -> FilePath -> IO ()
67atomicRename srcPath dstPath =
67atomicRename srcPath dstPath =
68#if defined(mingw32_HOST_OS)
68#if defined(mingw32_HOST_OS)
69+#if MIN_VERSION_Win32(2,6,0)
70+ let dst = Just dstPath
71+#else
72+ let dst = dstPath
73+#endif
74+ in
69− Win32.moveFileEx srcPath dstPath Win32.mOVEFILE_REPLACE_EXISTING
75+ Win32.moveFileEx srcPath dst Win32.mOVEFILE_REPLACE_EXISTING
70#else
76#else
71 Posix.rename srcPath dstPath
77 Posix.rename srcPath dstPath
72#endif
78#endif
@@ -119,13 +125,10 @@ printFdCount =
119 putStrLn "Fd count not supported on this OS."
125 putStrLn "Fd count not supported on this OS."
120#endif
126#endif
121
127
122−
123−fdCount :: IO Int
124#if FDCOUNTSUPPORTED
128#if FDCOUNTSUPPORTED
129+fdCount :: IO Int
125fdCount = do
130fdCount = do
126 fds <- getDirectoryContents FDDIR
131 fds <- getDirectoryContents FDDIR
127 pure ((length fds) - 2)
132 pure ((length fds) - 2)
128−#else
129--not supported on non-linux
133--not supported on non-linux
130−fdCount = pure 0
131#endif
134#endif
src/lib/ProjectM36/Relation.hs+6−18
@@ -4,8 +4,6 @@ import qualified Data.Set as S
4import qualified Data.HashSet as HS
4import qualified Data.HashSet as HS
5import Control.Monad
5import Control.Monad
6import qualified Data.Vector as V
6import qualified Data.Vector as V
7−import qualified Data.Map as M
8−import ProjectM36.AtomType
9import ProjectM36.Base
7import ProjectM36.Base
10import ProjectM36.Tuple
8import ProjectM36.Tuple
11import qualified ProjectM36.Attribute as A
9import qualified ProjectM36.Attribute as A
@@ -64,6 +62,10 @@ mkRelationDeferVerify :: Attributes -> RelationTupleSet -> Either RelationalErro
64mkRelationDeferVerify attrs tupleSet = return $ Relation attrs (RelationTupleSet (filter tupleFilter (asList tupleSet)))
62mkRelationDeferVerify attrs tupleSet = return $ Relation attrs (RelationTupleSet (filter tupleFilter (asList tupleSet)))
65 where
63 where
66 tupleFilter tuple = isRight (verifyTuple attrs tuple)
64 tupleFilter tuple = isRight (verifyTuple attrs tuple)
65+
66+--return a relation of the same type except without any tuples
67+relationWithEmptyTupleSet :: Relation -> Relation
68+relationWithEmptyTupleSet (Relation attrs _) = emptyRelationWithAttrs attrs
67
69
68mkRelationFromTuples :: Attributes -> [RelationTuple] -> Either RelationalError Relation
70mkRelationFromTuples :: Attributes -> [RelationTuple] -> Either RelationalError Relation
69mkRelationFromTuples attrs tupleSetList = do
71mkRelationFromTuples attrs tupleSetList = do
@@ -93,7 +95,7 @@ union (Relation attrs1 tupSet1) (Relation attrs2 tupSet2) =
93 where
95 where
94 newtuples = RelationTupleSet $ HS.toList . HS.fromList $ asList tupSet1 ++ map (reorderTuple attrs1) (asList tupSet2)
96 newtuples = RelationTupleSet $ HS.toList . HS.fromList $ asList tupSet1 ++ map (reorderTuple attrs1) (asList tupSet2)
95
97
96−project :: S.Set AttributeName -> Relation -> Either RelationalError Relation
98+project :: S.Set AttributeName -> Relation -> Either RelationalError Relation
97project attrNames rel@(Relation _ tupSet) = do
99project attrNames rel@(Relation _ tupSet) = do
98 newAttrs <- A.projectionAttributesForNames attrNames (attributes rel)
100 newAttrs <- A.projectionAttributesForNames attrNames (attributes rel)
99 let newAttrNameSet = A.attributeNameSet newAttrs
101 let newAttrNameSet = A.attributeNameSet newAttrs
@@ -300,20 +302,6 @@ typesAsRelation types = mkRelationFromTuples attrs tuples
300 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
302 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
301 Left err -> error ("mkRelationFromTuples pooped " ++ show err)
303 Left err -> error ("mkRelationFromTuples pooped " ++ show err)
302 Right rel -> RelationAtom rel
304 Right rel -> RelationAtom rel
303−
304−-- | Return a Relation describing the relation variables.
305−relationVariablesAsRelation :: M.Map RelVarName Relation -> Either RelationalError Relation
306−relationVariablesAsRelation relVarMap = mkRelationFromList attrs tups
307− where
308− subrelAttrs = A.attributesFromList [Attribute "attribute" TextAtomType, Attribute "type" TextAtomType]
309− attrs = A.attributesFromList [Attribute "name" TextAtomType,
310− Attribute "attributes" (RelationAtomType subrelAttrs)]
311− tups = map relVarToAtomList (M.toList relVarMap)
312− relVarToAtomList (rvName, rel) = [TextAtom rvName, attributesToRel (attributes rel)]
313− attributesToRel attrl = case mkRelationFromList subrelAttrs (map attrAtoms (V.toList attrl)) of
314− Left err -> error ("relationVariablesAsRelation pooped " ++ show err)
315− Right rel -> RelationAtom rel
316− attrAtoms a = [TextAtom (A.attributeName a), TextAtom (prettyAtomType (A.atomType a))]
317
305
318-- | 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.
306-- | 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.
319randomizeTupleOrder :: MonadRandom m => Relation -> m Relation
307randomizeTupleOrder :: MonadRandom m => Relation -> m Relation
@@ -326,4 +314,4 @@ oneTuple (Relation _ (RelationTupleSet [])) = Nothing
326oneTuple (Relation _ (RelationTupleSet (x:_))) = Just x
314oneTuple (Relation _ (RelationTupleSet (x:_))) = Just x
327
315
328tuplesList :: Relation -> [RelationTuple]
316tuplesList :: Relation -> [RelationTuple]
329−tuplesList (Relation _ tupleSet) = asList tupleSet
317+tuplesList (Relation _ tupleSet) = asList tupleSet
src/lib/ProjectM36/Relation/Show/HTML.hs+3
@@ -8,7 +8,9 @@ import qualified Data.List as L
8import Data.Text (Text, pack)
8import Data.Text (Text, pack)
9import qualified Data.Text as T
9import qualified Data.Text as T
10import qualified Data.Text.IO as TIO
10import qualified Data.Text.IO as TIO
11+#if __GLASGOW_HASKELL__ < 804
11import Data.Monoid
12import Data.Monoid
13+#endif
12import qualified Data.Vector as V
14import qualified Data.Vector as V
13
15
14attributesAsHTML :: Attributes -> Text
16attributesAsHTML :: Attributes -> Text
@@ -51,6 +53,7 @@ tupleAsHTML tuple = "<tr>" <> T.concat (L.map tupleFrag (tupleAssocs tuple)) <>
51 where
53 where
52 tupleFrag tup = "<td>" <> atomAsHTML (snd tup) <> "</td>"
54 tupleFrag tup = "<td>" <> atomAsHTML (snd tup) <> "</td>"
53 atomAsHTML (RelationAtom rel) = relationAsHTML rel
55 atomAsHTML (RelationAtom rel) = relationAsHTML rel
56+ atomAsHTML (TextAtom t) = "&quot;" <> t <> "&quot;"
54 atomAsHTML atom = atomToText atom
57 atomAsHTML atom = atomToText atom
55
58
56tupleSetAsHTML :: RelationTupleSet -> Text
59tupleSetAsHTML :: RelationTupleSet -> Text
src/lib/ProjectM36/Relation/Show/Term.hs+5−10
@@ -9,7 +9,11 @@ import ProjectM36.Attribute hiding (null)
9import qualified Data.List as L
9import qualified Data.List as L
10import qualified Data.Text as T
10import qualified Data.Text as T
11import Control.Arrow hiding (left)
11import Control.Arrow hiding (left)
12+import Data.ByteString.Base64 as B64
13+import qualified Data.Text.Encoding as TE
14+#if __GLASGOW_HASKELL__ < 804
12import Data.Monoid
15import Data.Monoid
16+#endif
13import ProjectM36.WCWidth --guess the width that the character will appear as in the terminal
17import ProjectM36.WCWidth --guess the width that the character will appear as in the terminal
14
18
15boxV :: StringType
19boxV :: StringType
@@ -38,16 +42,6 @@ boxBB = "┴"
38boxC :: StringType
42boxC :: StringType
39boxC = "┼"
43boxC = "┼"
40
44
41−dboxH :: StringType
42−dboxH = "═"
43−dboxL :: StringType
44−dboxL = "╞"
45−dboxR :: StringType
46−dboxR = "╡"
47−
48−class TermSize a where
49− termLength :: a -> Int
50−
51--represent a relation as a table similar to those drawn by Date
45--represent a relation as a table similar to those drawn by Date
52type Cell = StringType
46type Cell = StringType
53type Table = ([Cell], [[Cell]]) --header, body
47type Table = ([Cell], [[Cell]]) --header, body
@@ -105,6 +99,7 @@ showAtom :: Int -> Atom -> StringType
105showAtom _ (RelationAtom rel) = renderTable $ relationAsTable rel
99showAtom _ (RelationAtom rel) = renderTable $ relationAsTable rel
106showAtom level (ConstructedAtom dConsName _ atoms) = showParens (level >= 1 && not (null atoms)) $ T.concat (L.intersperse " " (dConsName : map (showAtom 1) atoms))
100showAtom level (ConstructedAtom dConsName _ atoms) = showParens (level >= 1 && not (null atoms)) $ T.concat (L.intersperse " " (dConsName : map (showAtom 1) atoms))
107showAtom _ (TextAtom t) = "\"" <> t <> "\""
101showAtom _ (TextAtom t) = "\"" <> t <> "\""
102+showAtom _ (ByteStringAtom bs) = TE.decodeUtf8 (B64.encode bs)
108showAtom _ atom = atomToText atom
103showAtom _ atom = atomToText atom
109
104
110renderTable :: Table -> StringType
105renderTable :: Table -> StringType
src/lib/ProjectM36/RelationalExpression.hs+1099−457
@@ -1,34 +1,50 @@
1{-# LANGUAGE ScopedTypeVariables #-}
1{-# LANGUAGE ScopedTypeVariables #-}
2+{-# LANGUAGE FlexibleInstances #-}
3+{-# LANGUAGE FlexibleContexts #-}
2module ProjectM36.RelationalExpression where
4module ProjectM36.RelationalExpression where
3import ProjectM36.Relation
5import ProjectM36.Relation
4import ProjectM36.Tuple
6import ProjectM36.Tuple
5import ProjectM36.TupleSet
7import ProjectM36.TupleSet
6import ProjectM36.Base
8import ProjectM36.Base
9+import qualified Data.UUID as U
7import ProjectM36.Error
10import ProjectM36.Error
8import ProjectM36.AtomType
11import ProjectM36.AtomType
9−import ProjectM36.Attribute (emptyAttributes)
12+import ProjectM36.Attribute (emptyAttributes, attributesFromList)
10import ProjectM36.ScriptSession
13import ProjectM36.ScriptSession
11import ProjectM36.DataTypes.Primitive
14import ProjectM36.DataTypes.Primitive
12import ProjectM36.AtomFunction
15import ProjectM36.AtomFunction
13import ProjectM36.DatabaseContextFunction
16import ProjectM36.DatabaseContextFunction
14import ProjectM36.Arbitrary
17import ProjectM36.Arbitrary
18+import ProjectM36.GraphRefRelationalExpr
19+import ProjectM36.Transaction
15import qualified ProjectM36.Attribute as A
20import qualified ProjectM36.Attribute as A
16import qualified Data.Map as M
21import qualified Data.Map as M
17import qualified Data.HashSet as HS
22import qualified Data.HashSet as HS
18import qualified Data.Set as S
23import qualified Data.Set as S
19import Control.Monad.State hiding (join)
24import Control.Monad.State hiding (join)
20−import Control.Exception
25+import Data.Bifunctor (second)
21import Data.Maybe
26import Data.Maybe
22import Data.Either
27import Data.Either
23import Data.Char (isUpper)
28import Data.Char (isUpper)
29+import Data.Time
30+import qualified Data.List.NonEmpty as NE
31+import Data.Functor.Identity
24import qualified Data.Text as T
32import qualified Data.Text as T
25import qualified Data.Vector as V
33import qualified Data.Vector as V
26import qualified ProjectM36.TypeConstructorDef as TCD
34import qualified ProjectM36.TypeConstructorDef as TCD
27−import Control.Monad.Trans.Except
35+import qualified Control.Monad.RWS.Strict as RWS
36+import Control.Monad.RWS.Strict (RWST, execRWST, runRWST)
37+import Control.Monad.Except hiding (join)
28−import Control.Monad.Trans.Reader
38+import Control.Monad.Trans.Except (except)
39+import Control.Monad.Reader as R hiding (join)
40+import ProjectM36.NormalizeExpr
41+import ProjectM36.WithNameExpr
29import Test.QuickCheck
42import Test.QuickCheck
43+#ifdef PM36_HASKELL_SCRIPTING
30−import GHC
44+import GHC hiding (getContext)
45+import Control.Exception
31import GHC.Paths
46import GHC.Paths
47+#endif
32
48
33data DatabaseContextExprDetails = CountUpdatedTuples
49data DatabaseContextExprDetails = CountUpdatedTuples
34
50
@@ -45,32 +61,63 @@ databaseContextExprDetailsFunc CountUpdatedTuples _ relIn = Relation attrs newTu
45 Right ts -> ts
61 Right ts -> ts
46
62
47-- | Used to start a fresh database state for a new database context expression.
63-- | Used to start a fresh database state for a new database context expression.
48−freshDatabaseState :: DatabaseContext -> DatabaseStateElems
64+mkDatabaseContextEvalState :: DatabaseContext -> DatabaseContextEvalState
65+mkDatabaseContextEvalState context = DatabaseContextEvalState {
66+ dbc_context = context,
67+ dbc_accum = M.empty,
68+ dbc_dirty = False
49−freshDatabaseState ctx = (ctx, M.empty, False) --future work: propagate return accumulator
69+ } --future work: propagate return accumulator
50
70
51-- we need to pass around a higher level RelationTuple and Attributes in order to solve #52
71-- 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
72+data RelationalExprEnv = RelationalExprEnv {
53− RelationalExprStateAttrsElems DatabaseContext Attributes | --used when evaluating the type of a relexpr
73+ re_context :: DatabaseContext,
54− RelationalExprStateElems DatabaseContext --used by default at the top level of evaluation
74+ re_graph :: TransactionGraph,
55−
75+ re_extra :: Maybe (Either RelationTuple Attributes)
56−instance Show RelationalExprStateElems where
76+ }
57− show (RelationalExprStateTupleElems _ tup) = "RelationalExprStateTupleElems " ++ show tup
77+
58− show (RelationalExprStateAttrsElems _ attrs) = "RelationalExprStateAttrsElems" ++ show attrs
78+envTuple :: GraphRefRelationalExprEnv -> RelationTuple
59− show (RelationalExprStateElems _) = "RelationalExprStateElems"
79+envTuple e = fromLeft emptyTuple (fromMaybe (Left emptyTuple) (gre_extra e))
60−
80+
61−mkRelationalExprState :: DatabaseContext -> RelationalExprStateElems
81+envAttributes :: GraphRefRelationalExprEnv -> Attributes
62−mkRelationalExprState = RelationalExprStateElems
82+envAttributes e = fromRight emptyAttributes (fromMaybe (Right emptyAttributes) (gre_extra e))
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)
69
83
70−mergeAttributesIntoRelationalExprState :: Attributes -> RelationalExprStateElems -> RelationalExprStateElems
84+instance Show RelationalExprEnv where
71−mergeAttributesIntoRelationalExprState attrs (RelationalExprStateElems ctx) = RelationalExprStateAttrsElems ctx attrs
85+ show e@RelationalExprEnv{} = "RelationalExprEnv " ++ show (re_extra e)
72−mergeAttributesIntoRelationalExprState _ st@(RelationalExprStateTupleElems _ _) = st
86+
73−mergeAttributesIntoRelationalExprState attrsIn (RelationalExprStateAttrsElems ctx attrs) = RelationalExprStateAttrsElems ctx (A.union attrsIn attrs)
87+--used to eval relationalexpr
88+type RelationalExprM a = ReaderT RelationalExprEnv (ExceptT RelationalError Identity) a
89+
90+runRelationalExprM :: RelationalExprEnv -> RelationalExprM a -> Either RelationalError a
91+runRelationalExprM env m = runIdentity (runExceptT (runReaderT m env))
92+
93+reGraph :: RelationalExprM TransactionGraph
94+reGraph = asks re_graph
95+
96+reContext :: RelationalExprM DatabaseContext
97+reContext = asks re_context
98+
99+mkRelationalExprEnv :: DatabaseContext -> TransactionGraph -> RelationalExprEnv
100+mkRelationalExprEnv ctx graph =
101+ RelationalExprEnv
102+ { re_context = ctx,
103+ re_graph = graph,
104+ re_extra = Nothing }
105+
106+askEnv :: GraphRefRelationalExprM GraphRefRelationalExprEnv
107+askEnv = R.ask
108+
109+mergeTuplesIntoGraphRefRelationalExprEnv :: RelationTuple -> GraphRefRelationalExprEnv -> GraphRefRelationalExprEnv
110+mergeTuplesIntoGraphRefRelationalExprEnv tupIn e =
111+ e{ gre_extra = new_elems }
112+ where
113+ new_elems = Just (Left newTuple)
114+ mergedTupMap = M.union (tupleToMap tupIn) (tupleToMap (envTuple e))
115+ newTuple = mkRelationTupleFromMap mergedTupMap
116+
117+mergeAttributesIntoGraphRefRelationalExprEnv :: Attributes -> GraphRefRelationalExprEnv -> GraphRefRelationalExprEnv
118+mergeAttributesIntoGraphRefRelationalExprEnv attrsIn e = e { gre_extra = newattrs }
119+ where
120+ newattrs = Just (Right (A.union attrsIn (envAttributes e)))
74
121
75type ResultAccumName = StringType
122type ResultAccumName = StringType
76
123
@@ -80,36 +127,103 @@ data ResultAccum = ResultAccum { resultAccumFunc :: ResultAccumFunc,
80 resultAccumResult :: Relation
127 resultAccumResult :: Relation
81 }
128 }
82
129
130+data DatabaseContextEvalState = DatabaseContextEvalState {
131+ dbc_context :: DatabaseContext, --new, alterable context for a new transaction
83−type DatabaseStateElems = (DatabaseContext, M.Map ResultAccumName ResultAccum, DirtyFlag)
132+ dbc_accum :: M.Map ResultAccumName ResultAccum,
133+ dbc_dirty :: DirtyFlag
134+ }
84
135
85−type DatabaseState a = State DatabaseStateElems a
136+data DatabaseContextEvalEnv = DatabaseContextEvalEnv
137+ { dce_transId :: TransactionId,
138+ dce_graph :: TransactionGraph
139+ }
86
140
87−getStateContext :: DatabaseState DatabaseContext
141+mkDatabaseContextEvalEnv :: TransactionId -> TransactionGraph -> DatabaseContextEvalEnv
88−getStateContext = do
142+mkDatabaseContextEvalEnv = DatabaseContextEvalEnv
89− (ctx,_, _) <- get
143+
90− pure ctx
144+type DatabaseContextEvalMonad a = RWST DatabaseContextEvalEnv () DatabaseContextEvalState (ExceptT RelationalError Identity) a
91−
145+
146+runDatabaseContextEvalMonad :: DatabaseContext -> DatabaseContextEvalEnv -> DatabaseContextEvalMonad () -> Either RelationalError DatabaseContextEvalState
147+runDatabaseContextEvalMonad ctx env m = runIdentity (runExceptT (fst <$> execRWST m env freshEnv))
148+ where
149+ freshEnv = mkDatabaseContextEvalState ctx
150+
151+
152+dbcTransId :: DatabaseContextEvalMonad TransactionId
153+dbcTransId = dce_transId <$> RWS.ask
154+
155+dbcGraph :: DatabaseContextEvalMonad TransactionGraph
156+dbcGraph = dce_graph <$> RWS.ask
157+
158+dbcRelationalExprEnv :: DatabaseContextEvalMonad RelationalExprEnv
159+dbcRelationalExprEnv =
160+ mkRelationalExprEnv <$> getStateContext <*> dbcGraph
161+
162+getStateContext :: DatabaseContextEvalMonad DatabaseContext
163+getStateContext = gets dbc_context
164+
92−putStateContext :: DatabaseContext -> DatabaseState ()
165+putStateContext :: DatabaseContext -> DatabaseContextEvalMonad ()
93−putStateContext ctx = do
166+putStateContext ctx' = do
94− (_, accum, _) <- get
167+ s <- get
95− put (ctx, accum, True)
168+ put (s {dbc_context = ctx', dbc_dirty = True})
169+
170+-- | The context is optionally passed down along in cases where the current context is uncommitted.
171+data GraphRefRelationalExprEnv =
172+ GraphRefRelationalExprEnv {
173+ gre_context :: Maybe DatabaseContext,
174+ gre_graph :: TransactionGraph,
175+ gre_extra :: Maybe (Either RelationTuple Attributes)
176+ }
96
177
97−type RelationalExprState a = Reader RelationalExprStateElems a
178+type GraphRefRelationalExprM a = ReaderT GraphRefRelationalExprEnv (ExceptT RelationalError Identity) a
179+
180+gfTransForId :: TransactionId -> GraphRefRelationalExprM Transaction
181+gfTransForId tid = do
182+ graph <- gfGraph
183+ lift $ except $ transactionForId tid graph
98
184
99−stateElemsContext :: RelationalExprStateElems -> DatabaseContext
185+gfDatabaseContextForMarker :: GraphRefTransactionMarker -> GraphRefRelationalExprM DatabaseContext
100−stateElemsContext (RelationalExprStateTupleElems ctx _) = ctx
186+gfDatabaseContextForMarker (TransactionMarker transId) = concreteDatabaseContext <$> gfTransForId transId
101−stateElemsContext (RelationalExprStateElems ctx) = ctx
187+gfDatabaseContextForMarker UncommittedContextMarker = do
102−stateElemsContext (RelationalExprStateAttrsElems ctx _) = ctx
188+ mctx <- gre_context <$> askEnv
189+ case mctx of
190+ Nothing -> throwError NoUncommittedContextInEvalError
191+ Just ctx -> pure ctx
103
192
104−setStateElemsContext :: RelationalExprStateElems -> DatabaseContext -> RelationalExprStateElems
193+runGraphRefRelationalExprM :: GraphRefRelationalExprEnv -> GraphRefRelationalExprM a -> Either RelationalError a
105−setStateElemsContext (RelationalExprStateTupleElems _ tup) ctx = RelationalExprStateTupleElems ctx tup
194+runGraphRefRelationalExprM env m = runIdentity (runExceptT (runReaderT m env))
106−setStateElemsContext (RelationalExprStateElems _) ctx = RelationalExprStateElems ctx
107−setStateElemsContext (RelationalExprStateAttrsElems _ attrs) ctx = RelationalExprStateAttrsElems ctx attrs
108
195
196+freshGraphRefRelationalExprEnv :: Maybe DatabaseContext -> TransactionGraph -> GraphRefRelationalExprEnv
197+freshGraphRefRelationalExprEnv mctx graph = GraphRefRelationalExprEnv {
198+ gre_context = mctx,
199+ gre_graph = graph,
200+ gre_extra = Nothing
201+ }
202+
203+gfGraph :: GraphRefRelationalExprM TransactionGraph
204+gfGraph = asks gre_graph
205+
206+envContext :: RelationalExprEnv -> DatabaseContext
207+envContext = re_context
208+
209+setEnvContext :: RelationalExprEnv -> DatabaseContext -> RelationalExprEnv
210+setEnvContext e ctx = e { re_context = ctx }
211+
212+{-
213+--full evaluation down the graph
214+eval :: RelationalExpr -> RelationalExprState (Either RelationalError Relation)
215+eval expr = do
216+ env <- askEnv
217+ eGfExpr <- processRelationalExpr expr
218+ case eGfExpr of
219+ Left err -> pure (Left err)
220+ Right gfExpr -> pure $ evalGraphRefRelationalExpr gfExpr (re_graph env)
221+-}
222+{-
109--relvar state is needed in evaluation of relational expression but only as read-only in order to extract current relvar values
223--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)
224+evalRelationalExpr :: RelationalExpr -> RelationalExprState (Either RelationalError GraphRefRelationalExpr)
111evalRelationalExpr (RelationVariable name _) = do
225evalRelationalExpr (RelationVariable name _) = do
112− relvarTable <- fmap (relationVariables . stateElemsContext) ask
226+ relvarTable <- fmap (relationVariables . envContext) askEnv
113 return $ case M.lookup name relvarTable of
227 return $ case M.lookup name relvarTable of
114 Just res -> Right res
228 Just res -> Right res
115 Nothing -> Left $ RelVarNotDefinedError name
229 Nothing -> Left $ RelVarNotDefinedError name
@@ -121,7 +235,7 @@ evalRelationalExpr (Project attrNames expr) = do
121 Right attrNameSet -> do
235 Right attrNameSet -> do
122 rel <- evalRelationalExpr expr
236 rel <- evalRelationalExpr expr
123 case rel of
237 case rel of
124− Right rel2 -> pure $ project attrNameSet rel2
238+ Right rel2 -> pure $ Right (Project (AttributeNames attrNameSet) rel2)
125 Left err -> pure $ Left err
239 Left err -> pure $ Left err
126
240
127evalRelationalExpr (Union exprA exprB) = do
241evalRelationalExpr (Union exprA exprB) = do
@@ -131,7 +245,7 @@ evalRelationalExpr (Union exprA exprB) = do
131 Left err -> return $ Left err
245 Left err -> return $ Left err
132 Right relA2 -> case relB of
246 Right relA2 -> case relB of
133 Left err -> return $ Left err
247 Left err -> return $ Left err
134− Right relB2 -> return $ union relA2 relB2
248+ Right relB2 -> return $ Right (Union relA2 relB2)
135
249
136evalRelationalExpr (Join exprA exprB) = do
250evalRelationalExpr (Join exprA exprB) = do
137 relA <- evalRelationalExpr exprA
251 relA <- evalRelationalExpr exprA
@@ -140,7 +254,7 @@ evalRelationalExpr (Join exprA exprB) = do
140 Left err -> return $ Left err
254 Left err -> return $ Left err
141 Right relA2 -> case relB of
255 Right relA2 -> case relB of
142 Left err -> return $ Left err
256 Left err -> return $ Left err
143− Right relB2 -> return $ join relA2 relB2
257+ Right relB2 -> return $ Right (Join relA2 relB2)
144
258
145evalRelationalExpr (Difference exprA exprB) = do
259evalRelationalExpr (Difference exprA exprB) = do
146 relA <- evalRelationalExpr exprA
260 relA <- evalRelationalExpr exprA
@@ -149,33 +263,34 @@ evalRelationalExpr (Difference exprA exprB) = do
149 Left err -> return $ Left err
263 Left err -> return $ Left err
150 Right relA2 -> case relB of
264 Right relA2 -> case relB of
151 Left err -> return $ Left err
265 Left err -> return $ Left err
152− Right relB2 -> return $ difference relA2 relB2
266+ Right relB2 -> return $ Right (Difference relA2 relB2)
153
267
154evalRelationalExpr (MakeStaticRelation attributeSet tupleSet) =
268evalRelationalExpr (MakeStaticRelation attributeSet tupleSet) =
155 case mkRelation attributeSet tupleSet of
269 case mkRelation attributeSet tupleSet of
156− Right rel -> return $ Right rel
270+ Right rel -> return $ Right (ExistingRelation rel)
157 Left err -> return $ Left err
271 Left err -> return $ Left err
158
272
159evalRelationalExpr (MakeRelationFromExprs mAttrExprs tupleExprs) = do
273evalRelationalExpr (MakeRelationFromExprs mAttrExprs tupleExprs) = do
160− currentContext <- fmap stateElemsContext ask
274+ currentContext <- fmap envContext askEnv
161 let tConss = typeConstructorMapping currentContext
275 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
276 -- 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
277 runExceptT $ do
164 mAttrs <- case mAttrExprs of
278 mAttrs <- case mAttrExprs of
165 Just _ ->
279 Just _ ->
166− Just . A.attributesFromList <$> mapM (either throwE pure . evalAttrExpr tConss) (fromMaybe [] mAttrExprs)
280+ Just . A.attributesFromList <$> mapM evalGraphRefAttrExpr (fromMaybe [] mAttrExprs)
167 Nothing -> pure Nothing
281 Nothing -> pure Nothing
168 tuples <- mapM (liftE . evalTupleExpr mAttrs) tupleExprs
282 tuples <- mapM (liftE . evalTupleExpr mAttrs) tupleExprs
169 let attrs = fromMaybe firstTupleAttrs mAttrs
283 let attrs = fromMaybe firstTupleAttrs mAttrs
170 firstTupleAttrs = if null tuples then A.emptyAttributes else tupleAttributes (head tuples)
284 firstTupleAttrs = if null tuples then A.emptyAttributes else tupleAttributes (head tuples)
171− either throwE pure (mkRelation attrs (RelationTupleSet tuples))
285+ expr <- either throwE pure (mkRelation attrs (RelationTupleSet tuples))
286+ pure (ExistingRelation expr)
172
287
173−evalRelationalExpr (ExistingRelation rel) = pure (Right rel)
288+evalRelationalExpr (ExistingRelation rel) = pure (Right (ExistingRelation rel))
174
289
175evalRelationalExpr (Rename oldAttrName newAttrName relExpr) = do
290evalRelationalExpr (Rename oldAttrName newAttrName relExpr) = do
176 evald <- evalRelationalExpr relExpr
291 evald <- evalRelationalExpr relExpr
177 case evald of
292 case evald of
178− Right rel -> return $ rename oldAttrName newAttrName rel
293+ Right expr -> return $ Right (Rename oldAttrName newAttrName expr)
179 Left err -> return $ Left err
294 Left err -> return $ Left err
180
295
181evalRelationalExpr (Group oldAttrNames newAttrName relExpr) = do
296evalRelationalExpr (Group oldAttrNames newAttrName relExpr) = do
@@ -185,324 +300,365 @@ evalRelationalExpr (Group oldAttrNames newAttrName relExpr) = do
185 Right oldAttrNameSet -> do
300 Right oldAttrNameSet -> do
186 evald <- evalRelationalExpr relExpr
301 evald <- evalRelationalExpr relExpr
187 case evald of
302 case evald of
188− Right rel -> return $ group oldAttrNameSet newAttrName rel
303+ Right expr -> return $ Right (Group (AttributeNames oldAttrNameSet) newAttrName expr)
189 Left err -> return $ Left err
304 Left err -> return $ Left err
190
305
191evalRelationalExpr (Ungroup attrName relExpr) = do
306evalRelationalExpr (Ungroup attrName relExpr) = do
192 evald <- evalRelationalExpr relExpr
307 evald <- evalRelationalExpr relExpr
193 case evald of
308 case evald of
194− Right rel -> return $ ungroup attrName rel
309+ Right expr -> return $ Right (Ungroup attrName expr)
195 Left err -> return $ Left err
310 Left err -> return $ Left err
196
311
197evalRelationalExpr (Restrict predicateExpr relExpr) = do
312evalRelationalExpr (Restrict predicateExpr relExpr) = do
198 evald <- evalRelationalExpr relExpr
313 evald <- evalRelationalExpr relExpr
314+ pred <- processRestrictionPredicateExpr predicateExpr
199 case evald of
315 case evald of
200 Left err -> return $ Left err
316 Left err -> return $ Left err
201− Right rel -> do
317+ Right expr ->
202− eFilterFunc <- predicateRestrictionFilter (attributes rel) predicateExpr
318+ pure $ Right (Restrict pred expr)
203− case eFilterFunc of
204− Left err -> return $ Left err
205− Right filterfunc ->
206− pure (restrict filterfunc rel)
207
319
208evalRelationalExpr (Equals relExprA relExprB) = do
320evalRelationalExpr (Equals relExprA relExprB) = do
209 evaldA <- evalRelationalExpr relExprA
321 evaldA <- evalRelationalExpr relExprA
210 evaldB <- evalRelationalExpr relExprB
322 evaldB <- evalRelationalExpr relExprB
211 case evaldA of
323 case evaldA of
212 Left err -> return $ Left err
324 Left err -> return $ Left err
213− Right relA -> case evaldB of
325+ Right exprA -> case evaldB of
214 Left err -> return $ Left err
326 Left err -> return $ Left err
215− Right relB -> return $ Right $ if relA == relB then relationTrue else relationFalse
327+ Right exprB -> return $ Right (Equals exprA exprB)
328+{-
329+evalRelationalExpr (With views mainExpr) = do
330+ rstate <- ask
331+
332+ let addScopedView ctx (vname,vexpr) = if vname `M.member` relationVariables ctx then
333+ Left (RelVarAlreadyDefinedError vname)
334+ else
335+ case runState (evalDatabaseContextExpr (Assign vname vexpr)) (freshDatabaseState ctx) of
336+ (Left err,_) -> Left err
337+ (Right (), (ctx',_,_)) -> Right ctx'
216
338
339+ case foldM addScopedView (stateElemsContext rstate) views of
340+ Left err -> return $ Left err
341+ Right ctx'' -> do
342+ let evalMainExpr expr = runReader (evalRelationalExpr expr) (RelationalExprEnv ctx'')
343+ case evalMainExpr mainExpr of
344+ Left err -> return $ Left err
345+ Right rel -> return $ Right rel
346+-}
217--warning: copy-pasta from above- refactor
347--warning: copy-pasta from above- refactor
218evalRelationalExpr (NotEquals relExprA relExprB) = do
348evalRelationalExpr (NotEquals relExprA relExprB) = do
219 evaldA <- evalRelationalExpr relExprA
349 evaldA <- evalRelationalExpr relExprA
220 evaldB <- evalRelationalExpr relExprB
350 evaldB <- evalRelationalExpr relExprB
221 case evaldA of
351 case evaldA of
222 Left err -> return $ Left err
352 Left err -> return $ Left err
223− Right relA -> case evaldB of
353+ Right exprA -> case evaldB of
224 Left err -> return $ Left err
354 Left err -> return $ Left err
225− Right relB -> return $ Right $ if relA /= relB then relationTrue else relationFalse
355+ Right exprB -> return $ Right (NotEquals exprA exprB)
226
356
227-- extending a relation adds a single attribute with the results of the per-tuple expression evaluated
357-- extending a relation adds a single attribute with the results of the per-tuple expression evaluated
228evalRelationalExpr (Extend tupleExpression relExpr) = do
358evalRelationalExpr (Extend tupleExpression relExpr) = do
229− rstate <- ask
230− let evald = runReader (evalRelationalExpr relExpr) rstate
359+ eExpr <- evalRelationalExpr relExpr
231− case evald of
360+ case eExpr of
232 Left err -> pure (Left err)
361 Left err -> pure (Left err)
233− Right rel -> do
362+ Right expr -> do
234− tupProc <- extendTupleExpressionProcessor rel tupleExpression
363+ tupProc <- processExtendTupleExpr tupleExpression
235− case tupProc of
364+ pure (Right (Extend tupProc expr))
236− Left err -> pure (Left err)
365+-}
237− Right (newAttrs, tupProc') -> pure $ relMogrify tupProc' newAttrs rel
238−
239--helper function to process relation variable creation/assignment
366--helper function to process relation variable creation/assignment
240−setRelVar :: RelVarName -> Relation -> DatabaseState (Either RelationalError ())
367+setRelVar :: RelVarName -> GraphRefRelationalExpr -> DatabaseContextEvalMonad ()
241−setRelVar relVarName rel = do
368+setRelVar relVarName relExpr = do
242 currentContext <- getStateContext
369 currentContext <- getStateContext
370+ --prevent recursive relvar definition by resolving references to relvars in previous states
371+ relExpr' <- resolve relExpr
243− let newRelVars = M.insert relVarName rel $ relationVariables currentContext
372+ let newRelVars = M.insert relVarName relExpr' $ relationVariables currentContext
244 potentialContext = currentContext { relationVariables = newRelVars }
373 potentialContext = currentContext { relationVariables = newRelVars }
245−
374+ --optimization: if the relexpr is unchanged, skip the update
375+ if M.lookup relVarName (relationVariables currentContext) == Just relExpr then
376+ pure ()
377+ else do
378+ --determine when to check constraints
379+ graph <- dbcGraph
380+ tid <- dbcTransId
246− case checkConstraints potentialContext of
381+ case checkConstraints potentialContext tid graph of
247− Left err -> pure (Left err)
382+ Left err -> dbErr err
248− Right _ -> do
249− putStateContext potentialContext
383+ Right _ -> putStateContext potentialContext
250− return (Right ())
251
384
252-- 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
385-- 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
253−deleteRelVar :: RelVarName -> DatabaseState (Either RelationalError ())
386+deleteRelVar :: RelVarName -> DatabaseContextEvalMonad ()
254deleteRelVar relVarName = do
387deleteRelVar relVarName = do
255 currContext <- getStateContext
388 currContext <- getStateContext
256 let relVars = relationVariables currContext
389 let relVars = relationVariables currContext
257 if M.notMember relVarName relVars then
390 if M.notMember relVarName relVars then
258− pure (Right ())
391+ pure ()
259 else do
392 else do
260 let newRelVars = M.delete relVarName relVars
393 let newRelVars = M.delete relVarName relVars
261 newContext = currContext { relationVariables = newRelVars }
394 newContext = currContext { relationVariables = newRelVars }
262 putStateContext newContext
395 putStateContext newContext
263− pure (Right ())
396+ pure ()
264
397
265−evalDatabaseContextExpr :: DatabaseContextExpr -> DatabaseState (Either RelationalError ())
398+evalGraphRefDatabaseContextExpr :: GraphRefDatabaseContextExpr -> DatabaseContextEvalMonad ()
266−evalDatabaseContextExpr NoOperation = pure (Right ())
399+evalGraphRefDatabaseContextExpr NoOperation = pure ()
267
400
268−evalDatabaseContextExpr (Define relVarName attrExprs) = do
401+evalGraphRefDatabaseContextExpr (Define relVarName attrExprs) = do
402+ context <- getStateContext
269 relvars <- fmap relationVariables getStateContext
403 relvars <- fmap relationVariables getStateContext
270 tConss <- fmap typeConstructorMapping getStateContext
404 tConss <- fmap typeConstructorMapping getStateContext
271− let eAttrs = map (evalAttrExpr tConss) attrExprs
405+ graph <- dbcGraph
272− attrErrs = lefts eAttrs
406+ let eAttrs = runGraphRefRelationalExprM gfEnv (mapM evalGraphRefAttrExpr attrExprs)
273− attrsList = rights eAttrs
407+ gfEnv = freshGraphRefRelationalExprEnv (Just context) graph
274− if not (null attrErrs) then
408+ case eAttrs of
275− pure (Left (someErrors attrErrs))
409+ Left err -> dbErr err
276− else do
410+ Right attrsList -> do
277− let atomTypeErrs = lefts $ map ((`validateAtomType` tConss) . A.atomType) attrsList
411+ lift $ except $ validateAttributes tConss (A.attributesFromList attrsList)
278− if not (null atomTypeErrs) then
279− pure (Left (someErrors atomTypeErrs))
280− else
281− case M.member relVarName relvars of
412+ case M.member relVarName relvars of
282− True -> pure (Left (RelVarAlreadyDefinedError relVarName))
413+ True -> dbErr (RelVarAlreadyDefinedError relVarName)
283− False -> setRelVar relVarName emptyRelation >> pure (Right ())
414+ False -> setRelVar relVarName (ExistingRelation emptyRelation)
284 where
415 where
285 attrs = A.attributesFromList attrsList
416 attrs = A.attributesFromList attrsList
286 emptyRelation = Relation attrs emptyTupleSet
417 emptyRelation = Relation attrs emptyTupleSet
287
418
288−evalDatabaseContextExpr (Undefine relVarName) = deleteRelVar relVarName
419+evalGraphRefDatabaseContextExpr (Undefine relVarName) = deleteRelVar relVarName
289
420
290−evalDatabaseContextExpr (Assign relVarName expr) = do
421+evalGraphRefDatabaseContextExpr (Assign relVarName expr) = do
291− -- in the future, it would be nice to get types from the RelationalExpr instead of needing to evaluate it
422+ graph <- re_graph <$> dbcRelationalExprEnv
292 context <- getStateContext
423 context <- getStateContext
293− let existingRelVar = M.lookup relVarName relVarTable
424+ let existingRelVar = M.lookup relVarName (relationVariables context)
294− relVarTable = relationVariables context
425+ reEnv = freshGraphRefRelationalExprEnv (Just context) graph
295− value = runReader (evalRelationalExpr expr) (RelationalExprStateElems context)
426+ eNewExprType = runGraphRefRelationalExprM reEnv (typeForGraphRefRelationalExpr expr)
296− case value of
297− Left err -> pure (Left err)
298− Right rel -> case existingRelVar of
427+ case existingRelVar of
299− Nothing -> setRelVar relVarName rel
428+ Nothing -> do
300− Just existingRel -> let expectedAttributes = attributes existingRel
429+ case runGraphRefRelationalExprM reEnv (typeForGraphRefRelationalExpr expr) of
301− foundAttributes = attributes rel in
430+ Left err -> dbErr err
302− if A.attributesEqual expectedAttributes foundAttributes then
431+ Right reltype -> do
303− setRelVar relVarName rel
432+ lift $ except $ validateAttributes (typeConstructorMapping context) (attributes reltype)
304− else
433+ setRelVar relVarName expr
305− pure (Left (RelationTypeMismatchError expectedAttributes foundAttributes))
434+ Just existingRel -> do
306−
435+ let eExpectedType = runGraphRefRelationalExprM reEnv (typeForGraphRefRelationalExpr existingRel)
307−evalDatabaseContextExpr (Insert relVarName relExpr) = do
436+ case eExpectedType of
308− context <- getStateContext
309− let unionexp = Union relExpr rv
310− rv = RelationVariable relVarName ()
311− unioned = runReader (evalRelationalExpr unionexp) (RelationalExprStateElems context)
312− origRel = runReader (evalRelationalExpr rv) (RelationalExprStateElems context)
313− case unioned of
314− Left err -> pure (Left err)
437+ Left err -> dbErr err
315− Right unioned' -> case origRel of
438+ Right expectedType ->
439+ case eNewExprType of
316− Left err -> pure (Left err)
440+ Left err -> dbErr err
317− Right origRel' -> if cardinality unioned' == cardinality origRel' then --no tuples actually inserted
441+ Right newExprType -> do
318− pure (Right ())
442+ if newExprType == expectedType then do
443+ lift $ except $ validateAttributes (typeConstructorMapping context) (attributes newExprType)
444+ setRelVar relVarName expr
319− else
445+ else
320− evalDatabaseContextExpr $ Assign relVarName (ExistingRelation unioned')
446+ dbErr (RelationTypeMismatchError (attributes expectedType) (attributes newExprType))
321
447
322−evalDatabaseContextExpr (Delete relVarName predicate) = do
448+evalGraphRefDatabaseContextExpr (Insert relVarName relExpr) = do
323− context <- getStateContext
449+ gfExpr <- relVarByName relVarName
324− let rv = RelationVariable relVarName ()
450+ evalGraphRefDatabaseContextExpr (Assign relVarName
325− let updatedRel = runReader (evalRelationalExpr (Restrict (NotPredicate predicate) rv)) (RelationalExprStateElems context)
451+ (Union
326− origRel = runReader (evalRelationalExpr rv) (RelationalExprStateElems context)
452+ gfExpr
327− case updatedRel of
453+ relExpr))
328− Left err -> pure (Left err)
329− Right updatedRel' -> case origRel of
330− Left err -> pure (Left err)
331− Right origRel' -> if cardinality origRel' == cardinality updatedRel' then
332− pure (Right ())
333− else
334− setRelVar relVarName updatedRel'
335
454
455+evalGraphRefDatabaseContextExpr (Delete relVarName predicate) = do
456+ gfExpr <- relVarByName relVarName
457+ setRelVar relVarName (Restrict (NotPredicate predicate) gfExpr)
458+
336--union of restricted+updated portion and the unrestricted+unupdated portion
459--union of restricted+updated portion and the unrestricted+unupdated portion
337−evalDatabaseContextExpr (Update relVarName atomExprMap restrictionPredicateExpr) = do
460+evalGraphRefDatabaseContextExpr (Update relVarName atomExprMap pred') = do
338− context <- getStateContext
461+ rvExpr <- relVarByName relVarName
339− let relVarTable = relationVariables context
462+ let unrestrictedPortion = Restrict (NotPredicate pred') rvExpr
340− case M.lookup relVarName relVarTable of
463+ tmpAttr attr = "_tmp_" <> attr --this could certainly be improved to verify that there is no attribute name conflict
341− Nothing -> pure (Left (RelVarNotDefinedError relVarName))
464+ updateAttr nam atomExpr = Extend (AttributeExtendTupleExpr (tmpAttr nam) atomExpr)
342− Just rel ->
465+ projectAndRename attr expr = Rename (tmpAttr attr) attr (Project (InvertedAttributeNames (S.singleton attr)) expr)
343− case runReader (predicateRestrictionFilter (attributes rel) restrictionPredicateExpr) (RelationalExprStateElems context) of
466+ restrictedPortion = Restrict pred' rvExpr
344− Left err -> pure (Left err)
467+ updated = foldr (\(oldname, atomExpr) accum ->
345− Right predicateFunc -> do
468+ let procAtomExpr = runProcessExprM UncommittedContextMarker (processAtomExpr atomExpr) in
346− let ret = do
469+ updateAttr oldname procAtomExpr accum
347− restrictedPortion <- restrict predicateFunc rel
470+ ) restrictedPortion (M.toList atomExprMap)
348− if cardinality restrictedPortion == Finite 0 then
471+ -- the atomExprMap could reference other attributes, so we must perform multi-pass folds
349− pure Nothing
472+ updatedPortion = foldr projectAndRename updated (M.keys atomExprMap)
350− else do
473+ setRelVar relVarName (Union unrestrictedPortion updatedPortion)
351− unrestrictedPortion <- restrict (predicateFunc >=> (pure . not)) rel
352− updatedPortion <- relMap (updateTupleWithAtomExprs atomExprMap context) restrictedPortion
353− updatedRel <- updatedPortion `union` unrestrictedPortion
354− pure (Just updatedRel)
355− case ret of
356− Left err -> pure (Left err)
357− Right Nothing -> pure (Right ())
358− Right (Just updatedRel) -> setRelVar relVarName updatedRel
359
474
360−evalDatabaseContextExpr (AddInclusionDependency newDepName newDep) = do
475+evalGraphRefDatabaseContextExpr (AddInclusionDependency newDepName newDep) = do
361 currContext <- getStateContext
476 currContext <- getStateContext
477+ transId <- dbcTransId
478+ graph <- dbcGraph
362 let currDeps = inclusionDependencies currContext
479 let currDeps = inclusionDependencies currContext
363 newDeps = M.insert newDepName newDep currDeps
480 newDeps = M.insert newDepName newDep currDeps
364 if M.member newDepName currDeps then
481 if M.member newDepName currDeps then
365− pure (Left (InclusionDependencyNameInUseError newDepName))
482+ dbErr (InclusionDependencyNameInUseError newDepName)
366 else do
483 else do
367 let potentialContext = currContext { inclusionDependencies = newDeps }
484 let potentialContext = currContext { inclusionDependencies = newDeps }
485+ -- if the potential context passes all constraints, then save it
486+ -- potential optimization: validate only the new constraint- all old constraints must already hold
368− case checkConstraints potentialContext of
487+ case checkConstraints potentialContext transId graph of
369− Left err -> pure (Left err)
488+ Left err -> dbErr err
370− Right _ -> do
489+ Right _ ->
371 putStateContext potentialContext
490 putStateContext potentialContext
372− return (Right ())
373
491
374−evalDatabaseContextExpr (RemoveInclusionDependency depName) = do
492+evalGraphRefDatabaseContextExpr (RemoveInclusionDependency depName) = do
375 currContext <- getStateContext
493 currContext <- getStateContext
376 let currDeps = inclusionDependencies currContext
494 let currDeps = inclusionDependencies currContext
377 newDeps = M.delete depName currDeps
495 newDeps = M.delete depName currDeps
378 if M.notMember depName currDeps then
496 if M.notMember depName currDeps then
379− pure (Left (InclusionDependencyNameNotInUseError depName))
497+ dbErr (InclusionDependencyNameNotInUseError depName)
380− else do
498+ else
381 putStateContext $ currContext {inclusionDependencies = newDeps }
499 putStateContext $ currContext {inclusionDependencies = newDeps }
382− return (Right ())
383
500
384-- | Add a notification which will send the resultExpr when triggerExpr changes between commits.
501-- | Add a notification which will send the resultExpr when triggerExpr changes between commits.
385−evalDatabaseContextExpr (AddNotification notName triggerExpr resultOldExpr resultNewExpr) = do
502+evalGraphRefDatabaseContextExpr (AddNotification notName triggerExpr resultOldExpr resultNewExpr) = do
386 currentContext <- getStateContext
503 currentContext <- getStateContext
387 let nots = notifications currentContext
504 let nots = notifications currentContext
388 if M.member notName nots then
505 if M.member notName nots then
389− pure (Left (NotificationNameInUseError notName))
506+ dbErr (NotificationNameInUseError notName)
390 else do
507 else do
391 let newNotifications = M.insert notName newNotification nots
508 let newNotifications = M.insert notName newNotification nots
392 newNotification = Notification { changeExpr = triggerExpr,
509 newNotification = Notification { changeExpr = triggerExpr,
393 reportOldExpr = resultOldExpr,
510 reportOldExpr = resultOldExpr,
394 reportNewExpr = resultNewExpr}
511 reportNewExpr = resultNewExpr}
395 putStateContext $ currentContext { notifications = newNotifications }
512 putStateContext $ currentContext { notifications = newNotifications }
396− return (Right ())
397
513
398−evalDatabaseContextExpr (RemoveNotification notName) = do
514+evalGraphRefDatabaseContextExpr (RemoveNotification notName) = do
399 currentContext <- getStateContext
515 currentContext <- getStateContext
400 let nots = notifications currentContext
516 let nots = notifications currentContext
401 if M.notMember notName nots then
517 if M.notMember notName nots then
402− pure (Left (NotificationNameNotInUseError notName))
518+ dbErr (NotificationNameNotInUseError notName)
403 else do
519 else do
404 let newNotifications = M.delete notName nots
520 let newNotifications = M.delete notName nots
405 putStateContext $ currentContext { notifications = newNotifications }
521 putStateContext $ currentContext { notifications = newNotifications }
406− pure (Right ())
522+
407
523
408-- | Adds type and data constructors to the database context.
524-- | Adds type and data constructors to the database context.
409-- validate that the type *and* constructor names are unique! not yet implemented!
525-- validate that the type *and* constructor names are unique! not yet implemented!
410−evalDatabaseContextExpr (AddTypeConstructor tConsDef dConsDefList) = do
526+evalGraphRefDatabaseContextExpr (AddTypeConstructor tConsDef dConsDefList) = do
411 currentContext <- getStateContext
527 currentContext <- getStateContext
412 let oldTypes = typeConstructorMapping currentContext
528 let oldTypes = typeConstructorMapping currentContext
413 tConsName = TCD.name tConsDef
529 tConsName = TCD.name tConsDef
414 -- validate that the constructor's types exist
530 -- validate that the constructor's types exist
415− case validateTypeConstructorDef tConsDef dConsDefList of
531+ case validateTypeConstructorDef tConsDef dConsDefList oldTypes of
416− errs@(_:_) -> pure (Left (someErrors errs))
532+ Left err -> throwError err
417− [] | T.null tConsName || not (isUpper (T.head tConsName)) -> pure (Left (InvalidAtomTypeName tConsName))
533+ Right () | T.null tConsName || not (isUpper (T.head tConsName)) -> dbErr (InvalidAtomTypeName tConsName)
418− | isJust (findTypeConstructor tConsName oldTypes) -> pure (Left (AtomTypeNameInUseError tConsName))
534+ | isJust (findTypeConstructor tConsName oldTypes) -> dbErr (AtomTypeNameInUseError tConsName)
419 | otherwise -> do
535 | otherwise -> do
420 let newTypes = oldTypes ++ [(tConsDef, dConsDefList)]
536 let newTypes = oldTypes ++ [(tConsDef, dConsDefList)]
421 putStateContext $ currentContext { typeConstructorMapping = newTypes }
537 putStateContext $ currentContext { typeConstructorMapping = newTypes }
422− pure (Right ())
423
538
424-- | 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.
539-- | 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.
425−evalDatabaseContextExpr (RemoveTypeConstructor tConsName) = do
540+evalGraphRefDatabaseContextExpr (RemoveTypeConstructor tConsName) = do
426 currentContext <- getStateContext
541 currentContext <- getStateContext
427 let oldTypes = typeConstructorMapping currentContext
542 let oldTypes = typeConstructorMapping currentContext
428 if isNothing (findTypeConstructor tConsName oldTypes) then
543 if isNothing (findTypeConstructor tConsName oldTypes) then
429− pure (Left (AtomTypeNameNotInUseError tConsName))
544+ dbErr (AtomTypeNameNotInUseError tConsName)
430 else do
545 else do
431 let newTypes = filter (\(tCons, _) -> TCD.name tCons /= tConsName) oldTypes
546 let newTypes = filter (\(tCons, _) -> TCD.name tCons /= tConsName) oldTypes
432 putStateContext $ currentContext { typeConstructorMapping = newTypes }
547 putStateContext $ currentContext { typeConstructorMapping = newTypes }
433− pure (Right ())
434
548
435−evalDatabaseContextExpr (MultipleExpr exprs) = do
549+evalGraphRefDatabaseContextExpr (MultipleExpr exprs) =
436 --the multiple expressions must pass the same context around- not the old unmodified context
550 --the multiple expressions must pass the same context around- not the old unmodified context
437− evald <- forM exprs evalDatabaseContextExpr
551+ mapM_ evalGraphRefDatabaseContextExpr exprs
438− --some lifting magic needed here
552+
439− case lefts evald of
440− [] -> pure (Right ())
441− errs -> pure (Left (someErrors errs))
442−
443−evalDatabaseContextExpr (RemoveAtomFunction funcName) = do
553+evalGraphRefDatabaseContextExpr (RemoveAtomFunction funcName) = do
444 currentContext <- getStateContext
554 currentContext <- getStateContext
445 let atomFuncs = atomFunctions currentContext
555 let atomFuncs = atomFunctions currentContext
446 case atomFunctionForName funcName atomFuncs of
556 case atomFunctionForName funcName atomFuncs of
447− Left err -> pure (Left err)
557+ Left err -> dbErr err
558+ Right realFunc ->
448− Right realFunc -> if isScriptedAtomFunction realFunc then do
559+ if isScriptedAtomFunction realFunc then do
449− let updatedFuncs = HS.delete realFunc atomFuncs
560+ let updatedFuncs = HS.delete realFunc atomFuncs
450− putStateContext (currentContext {atomFunctions = updatedFuncs })
561+ putStateContext (currentContext {atomFunctions = updatedFuncs })
451− pure (Right ())
452− else
562+ else
453− pure (Left (PrecompiledFunctionRemoveError funcName))
563+ dbErr (PrecompiledFunctionRemoveError funcName)
454
564
455−evalDatabaseContextExpr (RemoveDatabaseContextFunction funcName) = do
565+evalGraphRefDatabaseContextExpr (RemoveDatabaseContextFunction funcName) = do
456 context <- getStateContext
566 context <- getStateContext
457 let dbcFuncs = dbcFunctions context
567 let dbcFuncs = dbcFunctions context
458 case databaseContextFunctionForName funcName dbcFuncs of
568 case databaseContextFunctionForName funcName dbcFuncs of
459− Left err -> pure (Left err)
569+ Left err -> dbErr err
570+ Right realFunc ->
460− Right realFunc -> if isScriptedDatabaseContextFunction realFunc then do
571+ if isScriptedDatabaseContextFunction realFunc then do
461− let updatedFuncs = HS.delete realFunc dbcFuncs
572+ let updatedFuncs = HS.delete realFunc dbcFuncs
462− putStateContext (context { dbcFunctions = updatedFuncs })
573+ putStateContext (context { dbcFunctions = updatedFuncs })
463− pure (Right ())
464− else
574+ else
465− pure (Left (PrecompiledFunctionRemoveError funcName))
575+ dbErr (PrecompiledFunctionRemoveError funcName)
466
576
467−evalDatabaseContextExpr (ExecuteDatabaseContextFunction funcName atomArgExprs) = do
577+evalGraphRefDatabaseContextExpr (ExecuteDatabaseContextFunction funcName atomArgExprs) = do
468 context <- getStateContext
578 context <- getStateContext
579+ graph <- dbcGraph
469 --resolve atom arguments
580 --resolve atom arguments
470− let relExprState = mkRelationalExprState context
581+ let eAtomTypes = mapM (runGraphRefRelationalExprM gfEnv . typeForGraphRefAtomExpr emptyAttributes) atomArgExprs
471− eAtomTypes = map (\atomExpr -> runReader (typeFromAtomExpr emptyAttributes atomExpr) relExprState) atomArgExprs
472 eFunc = databaseContextFunctionForName funcName (dbcFunctions context)
582 eFunc = databaseContextFunctionForName funcName (dbcFunctions context)
583+ gfEnv = freshGraphRefRelationalExprEnv (Just context) graph
473 case eFunc of
584 case eFunc of
474− Left err -> pure (Left err)
585+ Left err -> dbErr err
475 Right func -> do
586 Right func -> do
476 let expectedArgCount = length (dbcFuncType func)
587 let expectedArgCount = length (dbcFuncType func)
477 actualArgCount = length atomArgExprs
588 actualArgCount = length atomArgExprs
478 if expectedArgCount /= actualArgCount then
589 if expectedArgCount /= actualArgCount then
479− pure (Left (FunctionArgumentCountMismatchError expectedArgCount actualArgCount))
590+ dbErr (FunctionArgumentCountMismatchError expectedArgCount actualArgCount)
480 else
591 else
481 --check that the atom types are valid
592 --check that the atom types are valid
482− case lefts eAtomTypes of
593+ case eAtomTypes of
483− _:_ -> pure (Left (someErrors (lefts eAtomTypes)))
594+ Left err -> dbErr err
484− [] -> do
595+ Right atomTypes -> do
485− let atomTypes = rights eAtomTypes
596+ let mValidTypes = zipWith (\ expType actType
486− let mValidTypes = map (\(expType, actType) -> case atomTypeVerify expType actType of
597+ -> case atomTypeVerify expType actType of
487− Left err -> Just err
598+ Left err -> Just err
599+ Right _ -> Nothing)
488− Right _ -> Nothing) (zip (dbcFuncType func) atomTypes)
600+ (dbcFuncType func) atomTypes
489− typeErrors = catMaybes mValidTypes
601+ typeErrors = catMaybes mValidTypes
490− eAtomArgs = map (\arg -> runReader (evalAtomExpr emptyTuple arg) relExprState) atomArgExprs
602+ eAtomArgs = map (runGraphRefRelationalExprM gfEnv . evalGraphRefAtomExpr emptyTuple) atomArgExprs
491 if length (lefts eAtomArgs) > 1 then
603 if length (lefts eAtomArgs) > 1 then
492− pure (Left (someErrors (lefts eAtomArgs)))
604+ dbErr (someErrors (lefts eAtomArgs))
493 else if not (null typeErrors) then
605 else if not (null typeErrors) then
494− pure (Left (someErrors typeErrors))
606+ dbErr (someErrors typeErrors)
495 else
607 else
496 case evalDatabaseContextFunction func (rights eAtomArgs) context of
608 case evalDatabaseContextFunction func (rights eAtomArgs) context of
497− Left err -> pure (Left err)
609+ Left err -> dbErr err
498− Right newContext -> putStateContext newContext >> pure (Right ())
610+ Right newContext -> putStateContext newContext
499−
611+data DatabaseContextIOEvalEnv = DatabaseContextIOEvalEnv
500−evalDatabaseContextIOExpr :: Maybe ScriptSession -> DatabaseContext -> DatabaseContextIOExpr -> IO (Either RelationalError DatabaseContext)
612+ { dbcio_transId :: TransactionId,
613+ dbcio_graph :: TransactionGraph,
614+ dbcio_mScriptSession :: Maybe ScriptSession
615+ }
616+
617+type DatabaseContextIOEvalMonad a = RWST DatabaseContextIOEvalEnv () DatabaseContextEvalState IO a
618+
619+runDatabaseContextIOEvalMonad :: DatabaseContextIOEvalEnv -> DatabaseContext -> DatabaseContextIOEvalMonad (Either RelationalError ()) -> IO (Either RelationalError DatabaseContextEvalState)
620+runDatabaseContextIOEvalMonad env ctx m = do
621+ res <- runRWST m env freshState
622+ case res of
623+ (Left err,_,_) -> pure (Left err)
624+ (Right (),s,_) -> pure (Right s)
625+ where
626+ freshState = mkDatabaseContextEvalState ctx
627+
628+requireScriptSession :: DatabaseContextIOEvalMonad (Either RelationalError ScriptSession)
629+requireScriptSession = do
630+ env <- RWS.ask
631+ case dbcio_mScriptSession env of
632+ Nothing -> pure $ Left $ ScriptError ScriptCompilationDisabledError
633+ Just ss -> pure (Right ss)
634+
635+putDBCIOContext :: DatabaseContext -> DatabaseContextIOEvalMonad (Either RelationalError ())
636+putDBCIOContext ctx = do
637+ RWS.modify (\dbstate -> dbstate { dbc_context = ctx})
638+ pure (Right ())
639+
640+getDBCIOContext :: DatabaseContextIOEvalMonad DatabaseContext
641+getDBCIOContext = dbc_context <$> RWS.get
642+
643+getDBCIORelationalExprEnv :: DatabaseContextIOEvalMonad RelationalExprEnv
644+getDBCIORelationalExprEnv = do
645+ context <- getDBCIOContext
646+ mkRelationalExprEnv context . dbcio_graph <$> RWS.ask
647+
648+evalGraphRefDatabaseContextIOExpr :: GraphRefDatabaseContextIOExpr -> DatabaseContextIOEvalMonad (Either RelationalError ())
649+#if !defined(PM36_HASKELL_SCRIPTING)
650+evalGraphRefDatabaseContextIOExpr AddAtomFunction{} = pure (Left (ScriptError ScriptCompilationDisabledError))
651+evalGraphRefDatabaseContextIOExpr AddDatabaseContextFunction{} = pure (Left (ScriptError ScriptCompilationDisabledError))
652+evalGraphRefDatabaseContextIOExpr LoadAtomFunctions{} = pure (Left (ScriptError ScriptCompilationDisabledError))
653+evalGraphRefDatabaseContextIOExpr LoadDatabaseContextFunctions{} = pure (Left (ScriptError ScriptCompilationDisabledError))
654+#else
501−evalDatabaseContextIOExpr mScriptSession currentContext (AddAtomFunction funcName funcType script) =
655+evalGraphRefDatabaseContextIOExpr (AddAtomFunction funcName funcType script) = do
502− case mScriptSession of
656+ eScriptSession <- requireScriptSession
503− Nothing -> pure (Left (ScriptError ScriptCompilationDisabledError))
657+ currentContext <- getDBCIOContext
658+ case eScriptSession of
659+ Left err -> pure (Left err)
504− Just scriptSession -> do
660+ Right scriptSession -> do
505− res <- try $ runGhc (Just libdir) $ do
661+ res <- liftIO $ try $ runGhc (Just libdir) $ do
506 setSession (hscEnv scriptSession)
662 setSession (hscEnv scriptSession)
507 let atomFuncs = atomFunctions currentContext
663 let atomFuncs = atomFunctions currentContext
508 case extractAtomFunctionType funcType of
664 case extractAtomFunctionType funcType of
@@ -528,12 +684,13 @@ evalDatabaseContextIOExpr mScriptSession currentContext (AddAtomFunction funcNam
528 Left (exc :: SomeException) -> pure $ Left (ScriptError (OtherScriptCompilationError (show exc)))
684 Left (exc :: SomeException) -> pure $ Left (ScriptError (OtherScriptCompilationError (show exc)))
529 Right eContext -> case eContext of
685 Right eContext -> case eContext of
530 Left err -> pure (Left err)
686 Left err -> pure (Left err)
531− Right context' -> pure (Right context')
687+ Right context' -> putDBCIOContext context'
532−
533−evalDatabaseContextIOExpr mScriptSession currentContext (AddDatabaseContextFunction funcName funcType script) =
688+evalGraphRefDatabaseContextIOExpr (AddDatabaseContextFunction funcName funcType script) = do
534− case mScriptSession of
689+ eScriptSession <- requireScriptSession
535− Nothing -> pure (Left (ScriptError ScriptCompilationDisabledError))
690+ currentContext <- getDBCIOContext
691+ case eScriptSession of
692+ Left err -> pure (Left err)
536− Just scriptSession -> do
693+ Right scriptSession -> do
537 --validate that the function signature is of the form x -> y -> ... -> DatabaseContext -> DatabaseContext
694 --validate that the function signature is of the form x -> y -> ... -> DatabaseContext -> DatabaseContext
538 let last2Args = reverse (take 2 (reverse funcType))
695 let last2Args = reverse (take 2 (reverse funcType))
539 atomArgs = take (length funcType - 2) funcType
696 atomArgs = take (length funcType - 2) funcType
@@ -543,7 +700,7 @@ evalDatabaseContextIOExpr mScriptSession currentContext (AddDatabaseContextFunct
543 if last2Args /= [ADTypeConstructor "DatabaseContext" [], dbContextTypeCons] then
700 if last2Args /= [ADTypeConstructor "DatabaseContext" [], dbContextTypeCons] then
544 pure (Left (ScriptError (TypeCheckCompilationError expectedType actualType)))
701 pure (Left (ScriptError (TypeCheckCompilationError expectedType actualType)))
545 else do
702 else do
546− res <- try $ runGhc (Just libdir) $ do
703+ res <- liftIO $ try $ runGhc (Just libdir) $ do
547 setSession (hscEnv scriptSession)
704 setSession (hscEnv scriptSession)
548 eCompiledFunc <- compileScript (dbcFunctionBodyType scriptSession) script
705 eCompiledFunc <- compileScript (dbcFunctionBodyType scriptSession) script
549 pure $ case eCompiledFunc of
706 pure $ case eCompiledFunc of
@@ -568,68 +725,98 @@ evalDatabaseContextIOExpr mScriptSession currentContext (AddDatabaseContextFunct
568 Left (exc :: SomeException) -> pure $ Left (ScriptError (OtherScriptCompilationError (show exc)))
725 Left (exc :: SomeException) -> pure $ Left (ScriptError (OtherScriptCompilationError (show exc)))
569 Right eContext -> case eContext of
726 Right eContext -> case eContext of
570 Left err -> pure (Left err)
727 Left err -> pure (Left err)
571− Right context' -> pure (Right context')
728+ Right context' -> putDBCIOContext context'
572−evalDatabaseContextIOExpr _ currentContext (LoadAtomFunctions modName funcName modPath) = do
729+evalGraphRefDatabaseContextIOExpr (LoadAtomFunctions modName funcName modPath) = do
730+ currentContext <- getDBCIOContext
573− eLoadFunc <- loadAtomFunctions (T.unpack modName) (T.unpack funcName) modPath
731+ eLoadFunc <- liftIO $ loadAtomFunctions (T.unpack modName) (T.unpack funcName) modPath
574 case eLoadFunc of
732 case eLoadFunc of
575 Left LoadSymbolError -> pure (Left LoadFunctionError)
733 Left LoadSymbolError -> pure (Left LoadFunctionError)
576 Right atomFunctionListFunc -> let newContext = currentContext { atomFunctions = mergedFuncs }
734 Right atomFunctionListFunc -> let newContext = currentContext { atomFunctions = mergedFuncs }
577 mergedFuncs = HS.union (atomFunctions currentContext) (HS.fromList atomFunctionListFunc)
735 mergedFuncs = HS.union (atomFunctions currentContext) (HS.fromList atomFunctionListFunc)
578− in pure (Right newContext)
736+ in putDBCIOContext newContext
579−evalDatabaseContextIOExpr _ currentContext (LoadDatabaseContextFunctions modName funcName modPath) = do
737+evalGraphRefDatabaseContextIOExpr (LoadDatabaseContextFunctions modName funcName modPath) = do
738+ currentContext <- getDBCIOContext
580− eLoadFunc <- loadDatabaseContextFunctions (T.unpack modName) (T.unpack funcName) modPath
739+ eLoadFunc <- liftIO $ loadDatabaseContextFunctions (T.unpack modName) (T.unpack funcName) modPath
581 case eLoadFunc of
740 case eLoadFunc of
582 Left LoadSymbolError -> pure (Left LoadFunctionError)
741 Left LoadSymbolError -> pure (Left LoadFunctionError)
583 Right dbcListFunc -> let newContext = currentContext { dbcFunctions = mergedFuncs }
742 Right dbcListFunc -> let newContext = currentContext { dbcFunctions = mergedFuncs }
584 mergedFuncs = HS.union (dbcFunctions currentContext) (HS.fromList dbcListFunc)
743 mergedFuncs = HS.union (dbcFunctions currentContext) (HS.fromList dbcListFunc)
585− in pure (Right newContext)
744+ in putDBCIOContext newContext
586−
745+#endif
587−evalDatabaseContextIOExpr _ currentContext (CreateArbitraryRelation relVarName attrExprs range) =
746+evalGraphRefDatabaseContextIOExpr (CreateArbitraryRelation relVarName attrExprs range) = do
588 --Define
747 --Define
589− case runState ( evalDatabaseContextExpr (Define relVarName attrExprs)) (freshDatabaseState currentContext) of
748+ currentContext <- getDBCIOContext
749+ env <- RWS.ask
750+ --create graph ref expr
751+ let gfExpr = Define relVarName attrExprs
752+ evalEnv = mkDatabaseContextEvalEnv (dbcio_transId env) (dbcio_graph env)
753+ graph = dbcio_graph env
754+ case runDatabaseContextEvalMonad currentContext evalEnv (evalGraphRefDatabaseContextExpr gfExpr) of
590− (Left err,_) -> pure (Left err)
755+ Left err -> pure (Left err)
591− (Right (), elems@(ctx,_,_)) -> do
756+ Right dbstate -> do
592 --Assign
757 --Assign
593 let existingRelVar = M.lookup relVarName relVarTable
758 let existingRelVar = M.lookup relVarName relVarTable
594− relVarTable = relationVariables ctx
759+ relVarTable = relationVariables (dbc_context dbstate)
595 case existingRelVar of
760 case existingRelVar of
596 Nothing -> pure $ Left (RelVarNotDefinedError relVarName)
761 Nothing -> pure $ Left (RelVarNotDefinedError relVarName)
597 Just existingRel -> do
762 Just existingRel -> do
598− let expectedAttributes = attributes existingRel
763+ let gfEnv = freshGraphRefRelationalExprEnv (Just currentContext) graph
764+ case runGraphRefRelationalExprM gfEnv (typeForGraphRefRelationalExpr existingRel) of
765+ Left err -> pure (Left err)
766+ Right relType -> do
767+ let expectedAttributes = attributes relType
599− let tcMap = typeConstructorMapping ctx
768+ tcMap = typeConstructorMapping (dbc_context dbstate)
600− eitherRel <- generate $ runReaderT (arbitraryRelation expectedAttributes range) tcMap
769+ eitherRel <- liftIO $ generate $ runReaderT (arbitraryRelation expectedAttributes range) tcMap
601− case eitherRel of
770+ case eitherRel of
602− Left err -> pure $ Left err
771+ Left err -> pure $ Left err
603− Right rel ->
772+ Right rel ->
604− case runState (setRelVar relVarName rel) elems of
773+ case runDatabaseContextEvalMonad currentContext evalEnv (setRelVar relVarName (ExistingRelation rel)) of
605− (Left err,_) -> pure (Left err)
774+ Left err -> pure (Left err)
606− (Right (), (ctx',_,_)) -> pure $ Right ctx'
775+ Right dbstate' -> putDBCIOContext (dbc_context dbstate')
607−
776+
777+{-
608−updateTupleWithAtomExprs :: M.Map AttributeName AtomExpr -> DatabaseContext -> RelationTuple -> Either RelationalError RelationTuple
778+updateTupleWithAtomExprs :: M.Map AttributeName AtomExpr -> DatabaseContext -> TransactionGraph -> RelationTuple -> Either RelationalError RelationTuple
609−updateTupleWithAtomExprs exprMap context tupIn = do
779+updateTupleWithAtomExprs exprMap context graph tupIn = do
610 --resolve all atom exprs
780 --resolve all atom exprs
781+ let
611 atomsAssoc <- mapM (\(attrName, atomExpr) -> do
782 atomsAssoc <- mapM (\(attrName, atomExpr) -> do
783+ let atom = unimplemented
612− atom <- runReader (evalAtomExpr tupIn atomExpr) (RelationalExprStateElems context)
784+ --atom <- runReader (evalAtomExpr tupIn atomExpr) (mkRelationalExprState context graph)
613 pure (attrName, atom)
785 pure (attrName, atom)
614 ) (M.toList exprMap)
786 ) (M.toList exprMap)
615 pure (updateTupleWithAtoms (M.fromList atomsAssoc) tupIn)
787 pure (updateTupleWithAtoms (M.fromList atomsAssoc) tupIn)
616−
788+-}
617--run verification on all constraints
789--run verification on all constraints
618−checkConstraints :: DatabaseContext -> Either RelationalError ()
790+checkConstraints :: DatabaseContext -> TransactionId -> TransactionGraph -> Either RelationalError ()
619−checkConstraints context = do
791+checkConstraints context transId graph@(TransactionGraph graphHeads transSet) =
620 mapM_ (uncurry checkIncDep) (M.toList deps)
792 mapM_ (uncurry checkIncDep) (M.toList deps)
621− pure ()
622 where
793 where
794+ potentialGraph = TransactionGraph graphHeads (S.insert tempTrans transSet)
795+ tempStamp = UTCTime { utctDay = fromGregorian 2000 1 1,
796+ utctDayTime = secondsToDiffTime 0 }
797+ tempSchemas = Schemas context M.empty
798+ tempTrans = Transaction U.nil tempTransInfo tempSchemas
799+ tempTransInfo = TransactionInfo { parents = transId NE.:| [],
800+ stamp = tempStamp,
801+ merkleHash = mempty
802+ }
803+
623 deps = inclusionDependencies context
804 deps = inclusionDependencies context
624− eval expr = evalReader (evalRelationalExpr expr)
805+ -- no optimization available here, really? perhaps the optimizer should be passed down to here or the eval function should be passed through the environment
625− evalReader f = runReader f (RelationalExprStateElems context)
626 checkIncDep depName (InclusionDependency subsetExpr supersetExpr) = do
806 checkIncDep depName (InclusionDependency subsetExpr supersetExpr) = do
807+ let process = runProcessExprM UncommittedContextMarker
808+ gfSubsetExpr = process (processRelationalExpr subsetExpr)
809+ gfSupersetExpr = process (processRelationalExpr supersetExpr)
627 --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.
810 --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.
628− typeSub <- evalReader (typeForRelationalExpr subsetExpr)
811+ let gfEnv = freshGraphRefRelationalExprEnv (Just context) graph
629− typeSuper <- evalReader (typeForRelationalExpr supersetExpr)
812+ runGfRel = runGraphRefRelationalExprM gfEnv
813+ typeSub <- runGfRel (typeForGraphRefRelationalExpr gfSubsetExpr)
814+ typeSuper <- runGfRel (typeForGraphRefRelationalExpr gfSupersetExpr)
630 when (typeSub /= typeSuper) (Left (RelationTypeMismatchError (attributes typeSub) (attributes typeSuper)))
815 when (typeSub /= typeSuper) (Left (RelationTypeMismatchError (attributes typeSub) (attributes typeSuper)))
631− let checkExpr = Equals supersetExpr (Union subsetExpr supersetExpr)
816+ let checkExpr = Equals gfSupersetExpr (Union gfSubsetExpr gfSupersetExpr)
632− case eval checkExpr of
817+ gfEvald = runGraphRefRelationalExprM gfEnv' (evalGraphRefRelationalExpr checkExpr)
818+ gfEnv' = freshGraphRefRelationalExprEnv (Just context) potentialGraph
819+ case gfEvald of
633 Left err -> Left err
820 Left err -> Left err
634 Right resultRel -> if resultRel == relationTrue then
821 Right resultRel -> if resultRel == relationTrue then
635 pure ()
822 pure ()
@@ -639,88 +826,90 @@ checkConstraints context = do
639-- 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
826-- 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
640-- furthermore, the type of a relational expression is the resultant header of the evaluated empty-tupled relation
827-- furthermore, the type of a relational expression is the resultant header of the evaluated empty-tupled relation
641
828
642−typeForRelationalExpr :: RelationalExpr -> RelationalExprState (Either RelationalError Relation)
829+typeForRelationalExpr :: RelationalExpr -> RelationalExprM Relation
643typeForRelationalExpr expr = do
830typeForRelationalExpr expr = do
644− rstate <- ask
645− let context = stateElemsContext rstate
646 --replace the relationVariables context element with a cloned set of relation devoid of tuples
831 --replace the relationVariables context element with a cloned set of relation devoid of tuples
647− let context' = contextWithEmptyTupleSets context
832+ --evalRelationalExpr could still return an existing relation with tuples, so strip them
648− rstate' = setStateElemsContext rstate context'
833+ graph <- reGraph
649− pure (runReader (evalRelationalExpr expr) rstate')
834+ context <- reContext
835+ let gfExpr = runProcessExprM UncommittedContextMarker (processRelationalExpr expr)
836+ gfEnv = freshGraphRefRelationalExprEnv (Just context) graph
837+ runGf = runGraphRefRelationalExprM gfEnv (typeForGraphRefRelationalExpr gfExpr)
838+ lift $ except runGf
650
839
651--returns a database context with all tuples removed
840--returns a database context with all tuples removed
652--this is useful for type checking and optimization
841--this is useful for type checking and optimization
842+{-
653contextWithEmptyTupleSets :: DatabaseContext -> DatabaseContext
843contextWithEmptyTupleSets :: DatabaseContext -> DatabaseContext
654contextWithEmptyTupleSets contextIn = contextIn { relationVariables = relVars }
844contextWithEmptyTupleSets contextIn = contextIn { relationVariables = relVars }
655 where
845 where
656− relVars = M.map (\rel -> Relation (attributes rel) emptyTupleSet) (relationVariables contextIn)
846+ relVars = M.map (\rel -> ExistingRelation (Relation (attributes rel) emptyTupleSet)) (relationVariables contextIn)
847+-}
657
848
658liftE :: (Monad m) => m (Either a b) -> ExceptT a m b
849liftE :: (Monad m) => m (Either a b) -> ExceptT a m b
659liftE v = do
850liftE v = do
660 y <- lift v
851 y <- lift v
661 case y of
852 case y of
662− Left err -> throwE err
853+ Left err -> throwError err
663 Right val -> pure val
854 Right val -> pure val
664
855
665{- used for restrictions- take the restrictionpredicate and return the corresponding filter function -}
856{- used for restrictions- take the restrictionpredicate and return the corresponding filter function -}
666−predicateRestrictionFilter :: Attributes -> RestrictionPredicateExpr -> RelationalExprState (Either RelationalError RestrictionFilter)
857+predicateRestrictionFilter :: Attributes -> GraphRefRestrictionPredicateExpr -> GraphRefRelationalExprM RestrictionFilter
667−predicateRestrictionFilter attrs (AndPredicate expr1 expr2) =
858+predicateRestrictionFilter attrs (AndPredicate expr1 expr2) = do
668− runExceptT $ do
669− expr1v <- liftE (predicateRestrictionFilter attrs expr1)
859+ expr1v <- predicateRestrictionFilter attrs expr1
670− expr2v <- liftE (predicateRestrictionFilter attrs expr2)
860+ expr2v <- predicateRestrictionFilter attrs expr2
671− pure (\x -> do
861+ pure (\x -> do
672− ev1 <- expr1v x
862+ ev1 <- expr1v x
673− ev2 <- expr2v x
863+ ev2 <- expr2v x
674− pure (ev1 && ev2))
864+ pure (ev1 && ev2))
675
865
676−predicateRestrictionFilter attrs (OrPredicate expr1 expr2) =
866+predicateRestrictionFilter attrs (OrPredicate expr1 expr2) = do
677− runExceptT $ do
678− expr1v <- liftE (predicateRestrictionFilter attrs expr1)
867+ expr1v <- predicateRestrictionFilter attrs expr1
679− expr2v <- liftE (predicateRestrictionFilter attrs expr2)
868+ expr2v <- predicateRestrictionFilter attrs expr2
680 pure (\x -> do
869 pure (\x -> do
681 ev1 <- expr1v x
870 ev1 <- expr1v x
682 ev2 <- expr2v x
871 ev2 <- expr2v x
683 pure (ev1 || ev2))
872 pure (ev1 || ev2))
684
873
685−predicateRestrictionFilter _ TruePredicate = pure (Right (\_ -> pure True))
874+predicateRestrictionFilter _ TruePredicate = pure (\_ -> pure True)
686
875
687−predicateRestrictionFilter attrs (NotPredicate expr) =
876+predicateRestrictionFilter attrs (NotPredicate expr) = do
688− runExceptT $ do
689− exprv <- liftE (predicateRestrictionFilter attrs expr)
877+ exprv <- predicateRestrictionFilter attrs expr
690− pure (fmap not . exprv)
878+ pure (fmap not . exprv)
691
879
692--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
880--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
693predicateRestrictionFilter _ (RelationalExprPredicate relExpr) = do
881predicateRestrictionFilter _ (RelationalExprPredicate relExpr) = do
694− rstate <- ask
882+ renv <- askEnv
695− pure (Right (\tup -> case runReader (evalRelationalExpr relExpr) (mergeTuplesIntoRelationalExprState tup rstate) of
883+ let eval :: RelationTuple -> Either RelationalError Relation
884+ eval tup =
885+ let gfEnv = mergeTuplesIntoGraphRefRelationalExprEnv tup renv in
886+ runGraphRefRelationalExprM gfEnv (evalGraphRefRelationalExpr relExpr)
887+ pure (\tup -> case eval tup of
696 Left err -> Left err
888 Left err -> Left err
697 Right rel -> if arity rel /= 0 then
889 Right rel -> if arity rel /= 0 then
698 Left (PredicateExpressionError "Relational restriction filter must evaluate to 'true' or 'false'")
890 Left (PredicateExpressionError "Relational restriction filter must evaluate to 'true' or 'false'")
699 else
891 else
700− pure (rel == relationTrue)))
892+ pure (rel == relationTrue))
701
893
702predicateRestrictionFilter attrs (AttributeEqualityPredicate attrName atomExpr) = do
894predicateRestrictionFilter attrs (AttributeEqualityPredicate attrName atomExpr) = do
703− rstate <- ask
895+ env <- askEnv
704− let (attrs', ctxtup') = case rstate of
896+ let attrs' = A.union attrs (envAttributes env)
705− RelationalExprStateElems _ -> (attrs, emptyTuple)
897+ ctxtup' = envTuple env
706− RelationalExprStateAttrsElems _ _ -> (attrs, emptyTuple)
707− RelationalExprStateTupleElems _ ctxtup -> (A.union attrs (tupleAttributes ctxtup), ctxtup)
708− runExceptT $ do
709− atomExprType <- liftE (typeFromAtomExpr attrs' atomExpr)
898+ atomExprType <- typeForGraphRefAtomExpr attrs' atomExpr
710− attr <- either throwE pure $ case A.attributeForName attrName attrs of
899+ attr <- lift $ except $ case A.attributeForName attrName attrs of
711 Right attr -> Right attr
900 Right attr -> Right attr
712 Left (NoSuchAttributeNamesError _) -> case A.attributeForName attrName (tupleAttributes ctxtup') of
901 Left (NoSuchAttributeNamesError _) -> case A.attributeForName attrName (tupleAttributes ctxtup') of
713 Right ctxattr -> Right ctxattr
902 Right ctxattr -> Right ctxattr
714 Left err2@(NoSuchAttributeNamesError _) -> Left err2
903 Left err2@(NoSuchAttributeNamesError _) -> Left err2
715 Left err -> Left err
904 Left err -> Left err
716 Left err -> Left err
905 Left err -> Left err
717− if atomExprType /= A.atomType attr then
906+ if atomExprType /= A.atomType attr then
718− throwE (TupleAttributeTypeMismatchError (A.attributesFromList [attr]))
907+ throwError (TupleAttributeTypeMismatchError (A.attributesFromList [attr]))
719− else
908+ else
720 pure $ \tupleIn -> let evalAndCmp atomIn = case atomEvald of
909 pure $ \tupleIn -> let evalAndCmp atomIn = case atomEvald of
721 Right atomCmp -> atomCmp == atomIn
910 Right atomCmp -> atomCmp == atomIn
722 Left _ -> False
911 Left _ -> False
723− atomEvald = runReader (evalAtomExpr tupleIn atomExpr) rstate
912+ atomEvald = runGraphRefRelationalExprM env (evalGraphRefAtomExpr tupleIn atomExpr)
724 in
913 in
725 pure $ case atomForAttributeName attrName tupleIn of
914 pure $ case atomForAttributeName attrName tupleIn of
726 Left (NoSuchAttributeNamesError _) -> case atomForAttributeName attrName ctxtup' of
915 Left (NoSuchAttributeNamesError _) -> case atomForAttributeName attrName ctxtup' of
@@ -731,48 +920,99 @@ predicateRestrictionFilter attrs (AttributeEqualityPredicate attrName atomExpr)
731-- in the future, it would be useful to do typechecking on the attribute and atom expr filters in advance
920-- in the future, it would be useful to do typechecking on the attribute and atom expr filters in advance
732predicateRestrictionFilter attrs (AtomExprPredicate atomExpr) = do
921predicateRestrictionFilter attrs (AtomExprPredicate atomExpr) = do
733 --merge attrs into the state attributes
922 --merge attrs into the state attributes
734− rstate <- ask
923+ renv <- askEnv
735− runExceptT $ do
736− aType <- liftE (typeFromAtomExpr attrs atomExpr)
924+ aType <- typeForGraphRefAtomExpr attrs atomExpr
737− if aType /= BoolAtomType then
925+ if aType /= BoolAtomType then
738− throwE (AtomTypeMismatchError aType BoolAtomType)
926+ throwError (AtomTypeMismatchError aType BoolAtomType)
739− else
927+ else
740 pure (\tupleIn ->
928 pure (\tupleIn ->
741− pure $ case runReader (evalAtomExpr tupleIn atomExpr) rstate of
929+ case runGraphRefRelationalExprM renv (evalGraphRefAtomExpr tupleIn atomExpr) of
742− Left _ -> False
930+ Left err -> Left err
743− Right boolAtomValue -> boolAtomValue == BoolAtom True)
931+ Right boolAtomValue -> pure (boolAtomValue == BoolAtom True))
744
932
745tupleExprCheckNewAttrName :: AttributeName -> Relation -> Either RelationalError Relation
933tupleExprCheckNewAttrName :: AttributeName -> Relation -> Either RelationalError Relation
746tupleExprCheckNewAttrName attrName rel = if isRight (attributeForName attrName rel) then
934tupleExprCheckNewAttrName attrName rel = if isRight (attributeForName attrName rel) then
747− Left (error "SPAMMIT" $ AttributeNameInUseError attrName)
935+ Left (AttributeNameInUseError attrName)
748 else
936 else
749 Right rel
937 Right rel
750
938
751−extendTupleExpressionProcessor :: Relation -> ExtendTupleExpr -> RelationalExprState (Either RelationalError (Attributes, RelationTuple -> Either RelationalError RelationTuple))
939+extendGraphRefTupleExpressionProcessor :: Relation -> GraphRefExtendTupleExpr -> GraphRefRelationalExprM (Attributes, RelationTuple -> Either RelationalError RelationTuple)
752−extendTupleExpressionProcessor relIn (AttributeExtendTupleExpr newAttrName atomExpr) = do
940+extendGraphRefTupleExpressionProcessor relIn (AttributeExtendTupleExpr newAttrName atomExpr) =
753− rstate <- ask
941+-- renv <- askEnv
754 -- check that the attribute name is not in use
942 -- check that the attribute name is not in use
755 case tupleExprCheckNewAttrName newAttrName relIn of
943 case tupleExprCheckNewAttrName newAttrName relIn of
756− Left err -> pure (Left err)
944+ Left err -> throwError err
757− Right _ -> runExceptT $ do
945+ Right _ -> do
758− atomExprType <- liftE (typeFromAtomExpr (attributes relIn) atomExpr)
946+ atomExprType <- typeForGraphRefAtomExpr (attributes relIn) atomExpr
759− atomExprType' <- liftE (verifyAtomExprTypes relIn atomExpr atomExprType)
947+ atomExprType' <- verifyGraphRefAtomExprTypes relIn atomExpr atomExprType
760 let newAttrs = A.attributesFromList [Attribute newAttrName atomExprType']
948 let newAttrs = A.attributesFromList [Attribute newAttrName atomExprType']
761 newAndOldAttrs = A.addAttributes (attributes relIn) newAttrs
949 newAndOldAttrs = A.addAttributes (attributes relIn) newAttrs
762− pure (newAndOldAttrs, \tup -> let substate = mergeTuplesIntoRelationalExprState tup rstate in case runReader (evalAtomExpr tup atomExpr) substate of
950+ env <- ask
763− Left err -> Left err
951+ pure (newAndOldAttrs, \tup -> do
952+ let gfEnv = mergeTuplesIntoGraphRefRelationalExprEnv tup env
953+ atom <- runGraphRefRelationalExprM gfEnv (evalGraphRefAtomExpr tup atomExpr)
764− Right atom -> Right (tupleAtomExtend newAttrName atom tup)
954+ Right (tupleAtomExtend newAttrName atom tup)
765 )
955 )
766
956
957+evalGraphRefAtomExpr :: RelationTuple -> GraphRefAtomExpr -> GraphRefRelationalExprM Atom
958+evalGraphRefAtomExpr tupIn (AttributeAtomExpr attrName) =
959+ case atomForAttributeName attrName tupIn of
960+ Right atom -> pure atom
961+ Left err@(NoSuchAttributeNamesError _) -> do
962+ env <- askEnv
963+ case gre_extra env of
964+ Nothing -> throwError err
965+ Just (Left ctxtup) -> lift $ except $ atomForAttributeName attrName ctxtup
966+ Just (Right _) -> throwError err
967+ Left err -> throwError err
968+evalGraphRefAtomExpr _ (NakedAtomExpr atom) = pure atom
969+evalGraphRefAtomExpr tupIn (FunctionAtomExpr funcName arguments tid) = do
970+ argTypes <- mapM (typeForGraphRefAtomExpr (tupleAttributes tupIn)) arguments
971+ context <- gfDatabaseContextForMarker tid
972+ let functions = atomFunctions context
973+ func <- lift $ except (atomFunctionForName funcName functions)
974+ let expectedArgCount = length (atomFuncType func) - 1
975+ actualArgCount = length argTypes
976+ safeInit [] = [] -- different behavior from normal init
977+ safeInit xs = init xs
978+ if expectedArgCount /= actualArgCount then
979+ throwError (FunctionArgumentCountMismatchError expectedArgCount actualArgCount)
980+ else do
981+ let zippedArgs = zip (safeInit (atomFuncType func)) argTypes
982+ mapM_ (\(expType, actType) ->
983+ lift $ except (atomTypeVerify expType actType)) zippedArgs
984+ evaldArgs <- mapM (evalGraphRefAtomExpr tupIn) arguments
985+ case evalAtomFunction func evaldArgs of
986+ Left err -> throwError (AtomFunctionUserError err)
987+ Right result -> do
988+ --validate that the result matches the expected type
989+ _ <- lift $ except (atomTypeVerify (last (atomFuncType func)) (atomTypeForAtom result))
990+ pure result
991+evalGraphRefAtomExpr tupIn (RelationAtomExpr relExpr) = do
992+ --merge existing state tuple context into new state tuple context to support an arbitrary number of levels, but new attributes trounce old attributes
993+ env <- ask
994+ let gfEnv = mergeTuplesIntoGraphRefRelationalExprEnv tupIn env
995+ relAtom <- lift $ except $ runGraphRefRelationalExprM gfEnv (evalGraphRefRelationalExpr relExpr)
996+ pure (RelationAtom relAtom)
997+evalGraphRefAtomExpr tupIn cons@(ConstructedAtomExpr dConsName dConsArgs _) = do --why is the tid unused here? suspicious
998+ let mergeEnv = mergeTuplesIntoGraphRefRelationalExprEnv tupIn
999+ aType <- local mergeEnv (typeForGraphRefAtomExpr (tupleAttributes tupIn) cons)
1000+ argAtoms <- local mergeEnv $
1001+ mapM (evalGraphRefAtomExpr tupIn) dConsArgs
1002+ pure (ConstructedAtom dConsName aType argAtoms)
1003+
1004+{-
767−evalAtomExpr :: RelationTuple -> AtomExpr -> RelationalExprState (Either RelationalError Atom)
1005+evalAtomExpr :: RelationTuple -> AtomExpr -> RelationalExprM Atom
1006+evalAtomExpr tupIn expr =
1007+ -}
1008+{-
1009+
768evalAtomExpr tupIn (AttributeAtomExpr attrName) = case atomForAttributeName attrName tupIn of
1010evalAtomExpr tupIn (AttributeAtomExpr attrName) = case atomForAttributeName attrName tupIn of
769 Right atom -> pure (Right atom)
1011 Right atom -> pure (Right atom)
770 err@(Left (NoSuchAttributeNamesError _)) -> do
1012 err@(Left (NoSuchAttributeNamesError _)) -> do
771 rstate <- ask
1013 rstate <- ask
772− case rstate of
1014+ let stateTup = stateTuple rstate
773− RelationalExprStateElems _ -> pure err
774− RelationalExprStateAttrsElems _ _ -> pure err
775− RelationalExprStateTupleElems _ ctxtup -> pure (atomForAttributeName attrName ctxtup)
1015+ pure (atomForAttributeName attrName stateTup)
776 Left err -> pure (Left err)
1016 Left err -> pure (Left err)
777evalAtomExpr _ (NakedAtomExpr atom) = pure (Right atom)
1017evalAtomExpr _ (NakedAtomExpr atom) = pure (Right atom)
778evalAtomExpr tupIn (FunctionAtomExpr funcName arguments ()) = do
1018evalAtomExpr tupIn (FunctionAtomExpr funcName arguments ()) = do
@@ -783,13 +1023,15 @@ evalAtomExpr tupIn (FunctionAtomExpr funcName arguments ()) = do
783 func <- either throwE pure (atomFunctionForName funcName functions)
1023 func <- either throwE pure (atomFunctionForName funcName functions)
784 let expectedArgCount = length (atomFuncType func) - 1
1024 let expectedArgCount = length (atomFuncType func) - 1
785 actualArgCount = length argTypes
1025 actualArgCount = length argTypes
786− safeInit [_] = []
787 safeInit [] = [] -- different behavior from normal init
1026 safeInit [] = [] -- different behavior from normal init
788− safeInit (_:xs) = safeInit xs
1027+ safeInit xs = init xs
789 if expectedArgCount /= actualArgCount then
1028 if expectedArgCount /= actualArgCount then
790 throwE (FunctionArgumentCountMismatchError expectedArgCount actualArgCount)
1029 throwE (FunctionArgumentCountMismatchError expectedArgCount actualArgCount)
791 else do
1030 else do
1031+ let zippedArgs = zip (safeInit (atomFuncType func)) argTypes
1032+ mapM_ (\(expType, eActType) -> do
1033+ actType <- either throwE pure eActType
792− mapM_ (\(expType, actType) -> either throwE pure (atomTypeVerify expType actType)) (safeInit (zip (atomFuncType func) argTypes))
1034+ either throwE pure (atomTypeVerify expType actType)) zippedArgs
793 evaldArgs <- mapM (liftE . evalAtomExpr tupIn) arguments
1035 evaldArgs <- mapM (liftE . evalAtomExpr tupIn) arguments
794 case evalAtomFunction func evaldArgs of
1036 case evalAtomFunction func evaldArgs of
795 Left err -> throwE (AtomFunctionUserError err)
1037 Left err -> throwE (AtomFunctionUserError err)
@@ -810,124 +1052,182 @@ evalAtomExpr tupIn cons@(ConstructedAtomExpr dConsName dConsArgs ()) = runExcept
810 aType <- either throwE pure (runReader (typeFromAtomExpr (tupleAttributes tupIn) cons) newState)
1052 aType <- either throwE pure (runReader (typeFromAtomExpr (tupleAttributes tupIn) cons) newState)
811 argAtoms <- mapM (\arg -> either throwE pure (runReader (evalAtomExpr tupIn arg) newState)) dConsArgs
1053 argAtoms <- mapM (\arg -> either throwE pure (runReader (evalAtomExpr tupIn arg) newState)) dConsArgs
812 pure (ConstructedAtom dConsName aType argAtoms)
1054 pure (ConstructedAtom dConsName aType argAtoms)
813−
1055+-}
814−typeFromAtomExpr :: Attributes -> AtomExpr -> RelationalExprState (Either RelationalError AtomType)
1056+typeForGraphRefAtomExpr :: Attributes -> GraphRefAtomExpr -> GraphRefRelationalExprM AtomType
815−typeFromAtomExpr attrs (AttributeAtomExpr attrName) = do
1057+typeForGraphRefAtomExpr attrs (AttributeAtomExpr attrName) = do
816− rstate <- ask
1058+ renv <- askEnv
817 case A.atomTypeForAttributeName attrName attrs of
1059 case A.atomTypeForAttributeName attrName attrs of
818− Right aType -> pure (Right aType)
1060+ Right aType -> pure aType
819− Left err@(NoSuchAttributeNamesError _) -> case rstate of
1061+ Left err@(NoSuchAttributeNamesError _) ->
1062+ let envTup = envTuple renv
1063+ envAttrs = envAttributes renv in
820− RelationalExprStateAttrsElems _ attrs' -> case A.attributeForName attrName attrs' of
1064+ case A.attributeForName attrName envAttrs of
821− Left err' -> pure (Left err')
822− Right attr -> pure (Right (A.atomType attr))
1065+ Right attr -> pure (A.atomType attr)
823− RelationalExprStateElems _ -> pure (Left err)
824− RelationalExprStateTupleElems _ tup -> case atomForAttributeName attrName tup of
1066+ Left _ -> case atomForAttributeName attrName envTup of
825− Left err' -> pure (Left err')
1067+ Right atom -> pure (atomTypeForAtom atom)
826− Right atom -> pure (Right (atomTypeForAtom atom))
1068+ Left _ -> --throwError (traceStack (show ("typeForGRAtomExpr", attrs, envTup)) err)
1069+ throwError err
827− Left err -> pure (Left err)
1070+ Left err -> throwError err
1071+
828−typeFromAtomExpr _ (NakedAtomExpr atom) = pure (Right (atomTypeForAtom atom))
1072+typeForGraphRefAtomExpr _ (NakedAtomExpr atom) = pure (atomTypeForAtom atom)
829−typeFromAtomExpr attrs (FunctionAtomExpr funcName atomArgs _) = do
1073+typeForGraphRefAtomExpr attrs (FunctionAtomExpr funcName atomArgs transId) = do
830− context <- fmap stateElemsContext ask
1074+ funcs <- atomFunctions <$> gfDatabaseContextForMarker transId
831− let funcs = atomFunctions context
832 case atomFunctionForName funcName funcs of
1075 case atomFunctionForName funcName funcs of
833− Left err -> pure (Left err)
1076+ Left err -> throwError err
834 Right func -> do
1077 Right func -> do
835 let funcRetType = last (atomFuncType func)
1078 let funcRetType = last (atomFuncType func)
836 funcArgTypes = init (atomFuncType func)
1079 funcArgTypes = init (atomFuncType func)
837− eArgTypes <- mapM (typeFromAtomExpr attrs) atomArgs
1080+ argTypes <- mapM (typeForGraphRefAtomExpr attrs) atomArgs
838− case lefts eArgTypes of
839− errs@(_:_) -> pure (Left (someErrors errs))
840− [] -> do
841− let eTvMap = resolveTypeVariables funcArgTypes argTypes
1081+ let eTvMap = resolveTypeVariables funcArgTypes argTypes
842− argTypes = rights eArgTypes
843− case eTvMap of
1082+ case eTvMap of
844− Left err -> pure (Left err)
1083+ Left err -> throwError err
845− Right tvMap -> pure (resolveFunctionReturnValue funcName tvMap funcRetType)
1084+ Right tvMap -> lift $ except $ resolveFunctionReturnValue funcName tvMap funcRetType
846−typeFromAtomExpr attrs (RelationAtomExpr relExpr) = runExceptT $ do
1085+typeForGraphRefAtomExpr attrs (RelationAtomExpr relExpr) = do
847− rstate <- lift ask
1086+ relType <- R.local (mergeAttributesIntoGraphRefRelationalExprEnv attrs) (typeForGraphRefRelationalExpr relExpr)
848− relType <- either throwE pure (runReader (typeForRelationalExpr relExpr) (mergeAttributesIntoRelationalExprState attrs rstate))
849 pure (RelationAtomType (attributes relType))
1087 pure (RelationAtomType (attributes relType))
850-- grab the type of the data constructor, then validate that the args match the expected types
1088-- grab the type of the data constructor, then validate that the args match the expected types
851−typeFromAtomExpr attrs (ConstructedAtomExpr dConsName dConsArgs _) =
1089+typeForGraphRefAtomExpr attrs (ConstructedAtomExpr dConsName dConsArgs tid) =
852− runExceptT $ do
1090+ do
853− argsTypes <- mapM (liftE . typeFromAtomExpr attrs) dConsArgs
1091+ argsTypes <- mapM (typeForGraphRefAtomExpr attrs) dConsArgs
854− context <- fmap stateElemsContext (lift ask)
1092+ tConsMap <- typeConstructorMapping <$> gfDatabaseContextForMarker tid
855− either throwE pure (atomTypeForDataConstructor (typeConstructorMapping context) dConsName argsTypes)
1093+ lift $ except $ atomTypeForDataConstructor tConsMap dConsName argsTypes
856
1094
857-- | Validate that the type of the AtomExpr matches the expected type.
1095-- | Validate that the type of the AtomExpr matches the expected type.
858−verifyAtomExprTypes :: Relation -> AtomExpr -> AtomType -> RelationalExprState (Either RelationalError AtomType)
1096+verifyGraphRefAtomExprTypes :: Relation -> GraphRefAtomExpr -> AtomType -> GraphRefRelationalExprM AtomType
859−verifyAtomExprTypes relIn (AttributeAtomExpr attrName) expectedType = runExceptT $ do
1097+verifyGraphRefAtomExprTypes relIn (AttributeAtomExpr attrName) expectedType = do
860− rstate <- lift ask
1098+ env <- askEnv
861 case A.atomTypeForAttributeName attrName (attributes relIn) of
1099 case A.atomTypeForAttributeName attrName (attributes relIn) of
862− Right aType -> either throwE pure (atomTypeVerify expectedType aType)
1100+ Right aType -> lift $ except $ atomTypeVerify expectedType aType
863− (Left err@(NoSuchAttributeNamesError _)) -> case rstate of
1101+ (Left err@(NoSuchAttributeNamesError _)) ->
864− RelationalExprStateTupleElems _ _ -> throwE err
1102+ let attrs' = envAttributes env in
865− RelationalExprStateElems _ -> throwE err
1103+ if attrs' == emptyAttributes then
1104+ throwError err
1105+ else
866− RelationalExprStateAttrsElems _ attrs -> case A.attributeForName attrName attrs of
1106+ case A.attributeForName attrName attrs' of
867− Left err' -> throwE err'
1107+ Left err' -> throwError err'
868− Right attrType -> either throwE pure (atomTypeVerify expectedType (A.atomType attrType))
1108+ Right attrType -> lift $ except $ atomTypeVerify expectedType (A.atomType attrType)
869− Left err -> throwE err
1109+ Left err -> throwError err
1110+
1111+verifyGraphRefAtomExprTypes _ (NakedAtomExpr atom) expectedType =
870−verifyAtomExprTypes _ (NakedAtomExpr atom) expectedType = pure (atomTypeVerify expectedType (atomTypeForAtom atom))
1112+ lift $ except $ atomTypeVerify expectedType (atomTypeForAtom atom)
871−verifyAtomExprTypes relIn (FunctionAtomExpr funcName funcArgExprs _) expectedType = do
1113+verifyGraphRefAtomExprTypes relIn (FunctionAtomExpr funcName funcArgExprs tid) expectedType = do
872− rstate <- ask
1114+ context <- gfDatabaseContextForMarker tid
873 let functions = atomFunctions context
1115 let functions = atomFunctions context
874− context = stateElemsContext rstate
875− runExceptT $ do
876− func <- either throwE pure (atomFunctionForName funcName functions)
1116+ func <- lift $ except $ atomFunctionForName funcName functions
877− let expectedArgTypes = atomFuncType func
1117+ let expectedArgTypes = atomFuncType func
878− funcArgTypes <- mapM (\(atomExpr,expectedType2,argCount) -> case runReader (verifyAtomExprTypes relIn atomExpr expectedType2) rstate of
1118+ funcArgVerifier (atomExpr, expectedType2, argCount) = do
1119+ let handler :: RelationalError -> GraphRefRelationalExprM AtomType
879− Left (AtomTypeMismatchError expSubType actSubType) -> throwE (AtomFunctionTypeError funcName argCount expSubType actSubType)
1120+ handler (AtomTypeMismatchError expSubType actSubType) = throwError (AtomFunctionTypeError funcName argCount expSubType actSubType)
880− Left err -> throwE err
1121+ handler err = throwError err
881− Right x -> pure x
1122+ verifyGraphRefAtomExprTypes relIn atomExpr expectedType2 `catchError` handler
882− ) $ zip3 funcArgExprs expectedArgTypes [1..]
1123+ funcArgTypes <- mapM funcArgVerifier $ zip3 funcArgExprs expectedArgTypes [1..]
883− if length funcArgTypes /= length expectedArgTypes - 1 then
1124+ if length funcArgTypes /= length expectedArgTypes - 1 then
884− throwE (AtomTypeCountError funcArgTypes expectedArgTypes)
1125+ throwError (AtomTypeCountError funcArgTypes expectedArgTypes)
885 else
1126 else
886− either throwE pure (atomTypeVerify expectedType (last expectedArgTypes))
1127+ lift $ except $ atomTypeVerify expectedType (last expectedArgTypes)
887−verifyAtomExprTypes relIn (RelationAtomExpr relationExpr) expectedType = runExceptT $ do
1128+verifyGraphRefAtomExprTypes relIn (RelationAtomExpr relationExpr) expectedType =
888− rstate <- lift ask
1129+ do
889− relType <- either throwE pure (runReader (typeForRelationalExpr relationExpr) (mergeAttributesIntoRelationalExprState (attributes relIn) rstate))
1130+ let mergedAttrsEnv e = mergeAttributesIntoGraphRefRelationalExprEnv (attributes relIn) e
1131+ relType <- R.local mergedAttrsEnv (typeForGraphRefRelationalExpr relationExpr)
890− either throwE pure (atomTypeVerify expectedType (RelationAtomType (attributes relType)))
1132+ lift $ except $ atomTypeVerify expectedType (RelationAtomType (attributes relType))
891−verifyAtomExprTypes rel cons@ConstructedAtomExpr{} expectedType = runExceptT $ do
1133+verifyGraphRefAtomExprTypes rel cons@ConstructedAtomExpr{} expectedType = do
892− cType <- liftE (typeFromAtomExpr (attributes rel) cons)
1134+ cType <- typeForGraphRefAtomExpr (attributes rel) cons
893− either throwE pure (atomTypeVerify expectedType cType)
1135+ lift $ except $ atomTypeVerify expectedType cType
894
1136
895-- | Look up the type's name and create a new attribute.
1137-- | Look up the type's name and create a new attribute.
896−evalAttrExpr :: TypeConstructorMapping -> AttributeExpr -> Either RelationalError Attribute
1138+evalGraphRefAttrExpr :: GraphRefAttributeExpr -> GraphRefRelationalExprM Attribute
897−evalAttrExpr aTypes (AttributeAndTypeNameExpr attrName tCons ()) = do
1139+evalGraphRefAttrExpr (AttributeAndTypeNameExpr attrName tCons transId) = do
1140+ tConsMap <- typeConstructorMapping <$> gfDatabaseContextForMarker transId
898− aType <- atomTypeForTypeConstructorValidate True tCons aTypes M.empty
1141+ aType <- lift $ except $ atomTypeForTypeConstructorValidate True tCons tConsMap M.empty
899− validateAtomType aType aTypes
1142+ lift $ except $ validateAtomType aType tConsMap
900− Right (Attribute attrName aType)
1143+ pure $ Attribute attrName aType
901
1144
902−evalAttrExpr _ (NakedAttributeExpr attr) = Right attr
1145+evalGraphRefAttrExpr (NakedAttributeExpr attr) = pure attr
903−
1146+
904−evalTupleExpr :: Maybe Attributes -> TupleExpr -> RelationalExprState (Either RelationalError RelationTuple)
1147+-- 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
1148+evalGraphRefTupleExprs :: Maybe Attributes -> GraphRefTupleExprs -> GraphRefRelationalExprM [RelationTuple]
1149+evalGraphRefTupleExprs _ (TupleExprs _ []) = pure []
1150+evalGraphRefTupleExprs mAttrs (TupleExprs fixedMarker tupleExprL) = do
1151+ tuples <- mapM (evalGraphRefTupleExpr mAttrs) tupleExprL
1152+ finalAttrs <- case mAttrs of
1153+ Just attrs -> pure attrs
1154+ Nothing ->
1155+ case tuples of
1156+ [] -> pure emptyAttributes
1157+ (headTuple:tailTuples) -> do
1158+ --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])
1159+ let
1160+ processTupleAttrs (tupAttr, accAttr) =
1161+ --if the attribute is a constructedatomtype, we can recurse into it to potentially resolve type variables
1162+ if isResolvedAttribute accAttr && tupAttr == accAttr then
1163+ pure accAttr
1164+ else
1165+ lift $ except $ resolveAttributes accAttr tupAttr
1166+ mostResolvedTypes <-
1167+ foldM (\acc tup -> do
1168+ let zipped = zip (V.toList $ tupleAttributes tup) acc
1169+ accNames = S.fromList $ map A.attributeName acc
1170+ tupNames = A.attributeNameSet (tupleAttributes tup)
1171+ attrNamesDiff = S.union (S.difference accNames tupNames) (S.difference tupNames accNames)
1172+ unless (null attrNamesDiff) (throwError (AttributeNamesMismatchError attrNamesDiff))
1173+ nextTupleAttrs <- mapM processTupleAttrs zipped
1174+ let diff = A.attributesDifference (A.attributesFromList nextTupleAttrs) (A.attributesFromList acc)
1175+ if diff == A.emptyAttributes then
1176+ pure nextTupleAttrs
1177+ else
1178+ throwError (TupleAttributeTypeMismatchError diff)
1179+ ) (V.toList $ tupleAttributes headTuple) tailTuples
1180+ pure (A.attributesFromList mostResolvedTypes)
1181+ --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
1182+ tConsMap <- case singularTransactions tupleExprL of
1183+ SingularTransactionRef commonTransId ->
1184+ typeConstructorMapping <$> gfDatabaseContextForMarker commonTransId
1185+ NoTransactionsRef ->
1186+ typeConstructorMapping <$> gfDatabaseContextForMarker fixedMarker
1187+ -- 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
1188+ _ -> throwError TupleExprsReferenceMultipleMarkersError
1189+ lift $ except $ validateAttributes tConsMap finalAttrs
1190+ mapM (lift . except . resolveTypesInTuple finalAttrs tConsMap) tuples
1191+
1192+
1193+--resolveAttributes (Attribute "gonk" (ConstructedAtomType "Either" (fromList [("a",IntegerAtomType),("b",TypeVariableType "b")]))) (Attribute "gonk" (ConstructedAtomType "Either" (fromList [("a",TypeVariableType "a"),("b",TextAtomType)])))
1194+
1195+evalGraphRefTupleExpr :: Maybe Attributes -> GraphRefTupleExpr -> GraphRefRelationalExprM RelationTuple
905−evalTupleExpr attrs (TupleExpr tupMap) = do
1196+evalGraphRefTupleExpr mAttrs (TupleExpr tupMap) = do
906− context <- fmap stateElemsContext ask
907− runExceptT $ do
908 -- 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
1197 -- 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
909 -- 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
1198 -- 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
1199+ let attrs = fromMaybe A.emptyAttributes mAttrs
910− attrAtoms <- mapM (\(attrName, aExpr) -> do
1200+ resolveOneAtom (attrName, aExpr) =
911− newAtomType <- liftE (typeFromAtomExpr A.emptyAttributes aExpr)
1201+ do
1202+ --provided when the relation header is available
1203+ let eExpectedAtomType = A.atomTypeForAttributeName attrName attrs
1204+ unresolvedType <- typeForGraphRefAtomExpr attrs aExpr
1205+ resolvedType <- case eExpectedAtomType of
1206+ Left _ -> pure unresolvedType
1207+ Right typeHint -> lift $ except $ resolveAtomType typeHint unresolvedType
1208+ --resolve atom typevars based on resolvedType?
912− newAtom <- liftE (evalAtomExpr emptyTuple aExpr)
1209+ newAtom <- evalGraphRefAtomExpr emptyTuple aExpr
913− pure (attrName, newAtom, newAtomType)
1210+ pure (attrName, newAtom, resolvedType)
914− ) (M.toList tupMap)
1211+ attrAtoms <- mapM resolveOneAtom (M.toList tupMap)
915− let tupAttrs = A.attributesFromList $ map (\(attrName, _, aType) -> Attribute attrName aType) attrAtoms
1212+ let tupAttrs = A.attributesFromList $ map (\(attrName, _, aType) -> Attribute attrName aType) attrAtoms
916− atoms = V.fromList $ map (\(_, atom, _) -> atom) attrAtoms
1213+ atoms = V.fromList $ map (\(_, atom, _) -> atom) attrAtoms
917− tup = mkRelationTuple tupAttrs atoms
1214+ tup = mkRelationTuple tupAttrs atoms
918− tConss = typeConstructorMapping context
919− finalAttrs = fromMaybe tupAttrs attrs
1215+ finalAttrs = fromMaybe tupAttrs mAttrs
920 --verify that the attributes match
1216 --verify that the attributes match
921− when (A.attributeNameSet finalAttrs /= A.attributeNameSet tupAttrs) $ throwE (TupleAttributeTypeMismatchError tupAttrs)
1217+ when (A.attributeNameSet finalAttrs /= A.attributeNameSet tupAttrs) $ throwError (TupleAttributeTypeMismatchError tupAttrs)
1218+ --we can't resolve types here- they have to be resolved at the atom level where the graph ref is held
922− tup' <- either throwE pure (resolveTypesInTuple finalAttrs (reorderTuple finalAttrs tup))
1219+ --tup' <- lift $ except (resolveTypesInTuple finalAttrs tConss (reorderTuple finalAttrs tup))
1220+ let tup' = reorderTuple finalAttrs tup
1221+ --TODO: restore type resolution
923− _ <- either throwE pure (validateTuple tup' tConss)
1222+-- _ <- lift $ except (validateTuple tup' tConss)
924− pure tup'
1223+ pure tup'
925
1224
1225+{-
926−evalAttributeNames :: AttributeNames -> RelationalExpr -> RelationalExprState (Either RelationalError (S.Set AttributeName))
1226+evalAttributeNames :: AttributeNames -> RelationalExpr -> RelationalExprM (Either RelationalError (S.Set AttributeName))
927evalAttributeNames attrNames expr = do
1227evalAttributeNames attrNames expr = do
928 eExprType <- typeForRelationalExpr expr
1228 eExprType <- typeForRelationalExpr expr
929 case eExprType of
1229 case eExprType of
930− Left err -> pure (Left err)
1230+ Left err -> throwError err
931 Right exprTyp -> do
1231 Right exprTyp -> do
932 let typeNameSet = S.fromList (V.toList (A.attributeNames (attributes exprTyp)))
1232 let typeNameSet = S.fromList (V.toList (A.attributeNames (attributes exprTyp)))
933 case attrNames of
1233 case attrNames of
@@ -970,4 +1270,346 @@ evalAttributeNames attrNames expr = do
970 case eAttrExprType of
1270 case eAttrExprType of
971 Left err -> pure (Left err)
1271 Left err -> pure (Left err)
972 Right attrExprType -> pure (Right (A.attributeNameSet (attributes attrExprType)))
1272 Right attrExprType -> pure (Right (A.attributeNameSet (attributes attrExprType)))
973−
1273+-}
1274+
1275+--temporary implementation until we have a proper planner+executor
1276+evalGraphRefRelationalExpr :: GraphRefRelationalExpr -> GraphRefRelationalExprM Relation
1277+evalGraphRefRelationalExpr (MakeRelationFromExprs mAttrExprs tupleExprs) = do
1278+ mAttrs <- case mAttrExprs of
1279+ Just _ ->
1280+ Just . A.attributesFromList <$> mapM evalGraphRefAttrExpr (fromMaybe [] mAttrExprs)
1281+ Nothing -> pure Nothing
1282+ tuples <- evalGraphRefTupleExprs mAttrs tupleExprs
1283+ let attrs = fromMaybe firstTupleAttrs mAttrs
1284+ firstTupleAttrs = if null tuples then A.emptyAttributes else tupleAttributes (head tuples)
1285+ lift $ except $ mkRelation attrs (RelationTupleSet tuples)
1286+evalGraphRefRelationalExpr (MakeStaticRelation attributeSet tupleSet) =
1287+ lift $ except $ mkRelation attributeSet tupleSet
1288+evalGraphRefRelationalExpr (ExistingRelation rel) = pure rel
1289+evalGraphRefRelationalExpr (RelationVariable name tid) = do
1290+ ctx <- gfDatabaseContextForMarker tid
1291+ case M.lookup name (relationVariables ctx) of
1292+ Nothing -> throwError (RelVarNotDefinedError name)
1293+ Just rv -> evalGraphRefRelationalExpr rv
1294+evalGraphRefRelationalExpr (Project attrNames expr) = do
1295+ attrNameSet <- evalGraphRefAttributeNames attrNames expr
1296+ rel <- evalGraphRefRelationalExpr expr
1297+ lift $ except $ project attrNameSet rel
1298+evalGraphRefRelationalExpr (Union exprA exprB) = do
1299+ relA <- evalGraphRefRelationalExpr exprA
1300+ relB <- evalGraphRefRelationalExpr exprB
1301+ lift $ except $ union relA relB
1302+evalGraphRefRelationalExpr (Join exprA exprB) = do
1303+ relA <- evalGraphRefRelationalExpr exprA
1304+ relB <- evalGraphRefRelationalExpr exprB
1305+ lift $ except $ join relA relB
1306+evalGraphRefRelationalExpr (Rename oldName newName expr) = do
1307+ rel <- evalGraphRefRelationalExpr expr
1308+ lift $ except $ rename oldName newName rel
1309+evalGraphRefRelationalExpr (Difference exprA exprB) = do
1310+ relA <- evalGraphRefRelationalExpr exprA
1311+ relB <- evalGraphRefRelationalExpr exprB
1312+ lift $ except $ difference relA relB
1313+evalGraphRefRelationalExpr (Group groupAttrNames newAttrName expr) = do
1314+ groupNames <- evalGraphRefAttributeNames groupAttrNames expr
1315+ rel <- evalGraphRefRelationalExpr expr
1316+ lift $ except $ group groupNames newAttrName rel
1317+evalGraphRefRelationalExpr (Ungroup groupAttrName expr) = do
1318+ rel <- evalGraphRefRelationalExpr expr
1319+ lift $ except $ ungroup groupAttrName rel
1320+evalGraphRefRelationalExpr (Restrict predExpr expr) = do
1321+ rel <- evalGraphRefRelationalExpr expr
1322+ filt <- predicateRestrictionFilter (attributes rel) predExpr
1323+ lift $ except $ restrict filt rel
1324+evalGraphRefRelationalExpr (Equals exprA exprB) = do
1325+ relA <- evalGraphRefRelationalExpr exprA
1326+ relB <- evalGraphRefRelationalExpr exprB
1327+ pure $ if relA == relB then relationTrue else relationFalse
1328+evalGraphRefRelationalExpr (NotEquals exprA exprB) = do
1329+ relA <- evalGraphRefRelationalExpr exprA
1330+ relB <- evalGraphRefRelationalExpr exprB
1331+ pure $ if relA == relB then relationFalse else relationTrue
1332+evalGraphRefRelationalExpr (Extend extendTupleExpr expr) = do
1333+ rel <- evalGraphRefRelationalExpr expr
1334+ (newAttrs, tupProc) <- extendGraphRefTupleExpressionProcessor rel extendTupleExpr
1335+ lift $ except $ relMogrify tupProc newAttrs rel
1336+evalGraphRefRelationalExpr expr@With{} =
1337+ --strategy A: add relation variables to the contexts in the graph
1338+ --strategy B: drop in macros in place (easier programmatically)
1339+ --strategy B implementation
1340+ evalGraphRefRelationalExpr (substituteWithNameMacros [] expr)
1341+
1342+dbContextForTransId :: TransactionId -> TransactionGraph -> Either RelationalError DatabaseContext
1343+dbContextForTransId tid graph = do
1344+ trans <- transactionForId tid graph
1345+ pure (concreteDatabaseContext trans)
1346+
1347+transactionForId :: TransactionId -> TransactionGraph -> Either RelationalError Transaction
1348+transactionForId tid graph
1349+ | tid == U.nil =
1350+ Left RootTransactionTraversalError
1351+ | S.null matchingTrans =
1352+ Left $ NoSuchTransactionError tid
1353+ | otherwise =
1354+ Right $ head (S.toList matchingTrans)
1355+ where
1356+ matchingTrans = S.filter (\(Transaction idMatch _ _) -> idMatch == tid) (transactionsForGraph graph)
1357+
1358+typeForGraphRefRelationalExpr :: GraphRefRelationalExpr -> GraphRefRelationalExprM Relation
1359+typeForGraphRefRelationalExpr (MakeStaticRelation attrs _) = lift $ except $ mkRelation attrs emptyTupleSet
1360+typeForGraphRefRelationalExpr (ExistingRelation rel) = pure (emptyRelationWithAttrs (attributes rel))
1361+typeForGraphRefRelationalExpr (MakeRelationFromExprs mAttrExprs tupleExprs) = do
1362+ mAttrs <- case mAttrExprs of
1363+ Just attrExprs -> do
1364+ attrs <- mapM evalGraphRefAttributeExpr attrExprs
1365+ pure (Just (attributesFromList attrs))
1366+ Nothing -> pure Nothing
1367+ tuples <- evalGraphRefTupleExprs mAttrs tupleExprs
1368+ let retAttrs = case tuples of
1369+ (tup:_) -> tupleAttributes tup
1370+ [] -> fromMaybe A.emptyAttributes mAttrs
1371+ pure $ emptyRelationWithAttrs retAttrs
1372+
1373+typeForGraphRefRelationalExpr (RelationVariable rvName tid) = do
1374+ relVars <- relationVariables <$> gfDatabaseContextForMarker tid
1375+ case M.lookup rvName relVars of
1376+ Nothing -> throwError (RelVarNotDefinedError rvName)
1377+ Just rvExpr ->
1378+ typeForGraphRefRelationalExpr rvExpr
1379+typeForGraphRefRelationalExpr (Project attrNames expr) = do
1380+ exprType' <- typeForGraphRefRelationalExpr expr
1381+ projectionAttrs <- evalGraphRefAttributeNames attrNames expr
1382+ lift $ except $ project projectionAttrs exprType'
1383+typeForGraphRefRelationalExpr (Union exprA exprB) = do
1384+ exprA' <- typeForGraphRefRelationalExpr exprA
1385+ exprB' <- typeForGraphRefRelationalExpr exprB
1386+ lift $ except $ union exprA' exprB'
1387+typeForGraphRefRelationalExpr (Join exprA exprB) = do
1388+ exprA' <- typeForGraphRefRelationalExpr exprA
1389+ exprB' <- typeForGraphRefRelationalExpr exprB
1390+ lift $ except $ join exprA' exprB'
1391+typeForGraphRefRelationalExpr (Rename oldAttr newAttr expr) = do
1392+ expr' <- typeForGraphRefRelationalExpr expr
1393+ lift $ except $ rename oldAttr newAttr expr'
1394+typeForGraphRefRelationalExpr (Difference exprA exprB) = do
1395+ exprA' <- typeForGraphRefRelationalExpr exprA
1396+ exprB' <- typeForGraphRefRelationalExpr exprB
1397+ lift $ except $ difference exprA' exprB'
1398+typeForGraphRefRelationalExpr (Group groupNames attrName expr) = do
1399+ expr' <- typeForGraphRefRelationalExpr expr
1400+ groupNames' <- evalGraphRefAttributeNames groupNames expr
1401+ lift $ except $ group groupNames' attrName expr'
1402+typeForGraphRefRelationalExpr (Ungroup groupAttrName expr) = do
1403+ expr' <- typeForGraphRefRelationalExpr expr
1404+ lift $ except $ ungroup groupAttrName expr'
1405+typeForGraphRefRelationalExpr (Restrict pred' expr) = do
1406+ expr' <- typeForGraphRefRelationalExpr expr
1407+ filt <- predicateRestrictionFilter (attributes expr') pred'
1408+ lift $ except $ restrict filt expr'
1409+typeForGraphRefRelationalExpr Equals{} =
1410+ pure relationFalse
1411+typeForGraphRefRelationalExpr NotEquals{} =
1412+ pure relationFalse
1413+typeForGraphRefRelationalExpr (Extend extendTupleExpr expr) = do
1414+ rel <- typeForGraphRefRelationalExpr expr
1415+ evalGraphRefRelationalExpr (Extend extendTupleExpr (ExistingRelation rel))
1416+typeForGraphRefRelationalExpr expr@(With withs _) = do
1417+ let expr' = substituteWithNameMacros [] expr
1418+ checkMacroName (WithNameExpr macroName tid) = do
1419+ rvs <- relationVariables <$> gfDatabaseContextForMarker tid
1420+ case M.lookup macroName rvs of
1421+ Just _ -> lift $ except $ Left (RelVarAlreadyDefinedError macroName) --this error does not include the transaction marker, but should be good enough to identify the cause
1422+ Nothing -> pure ()
1423+ mapM_ (checkMacroName . fst) withs
1424+ typeForGraphRefRelationalExpr expr'
1425+
1426+evalGraphRefAttributeNames :: GraphRefAttributeNames -> GraphRefRelationalExpr -> GraphRefRelationalExprM (S.Set AttributeName)
1427+evalGraphRefAttributeNames attrNames expr = do
1428+ exprType' <- typeForGraphRefRelationalExpr expr
1429+ let typeNameSet = S.fromList (V.toList (A.attributeNames (attributes exprType')))
1430+ case attrNames of
1431+ AttributeNames names ->
1432+ case A.projectionAttributesForNames names (attributes exprType') of
1433+ Left err -> throwError err
1434+ Right attrs -> pure (S.fromList (V.toList (A.attributeNames attrs)))
1435+
1436+ InvertedAttributeNames names -> do
1437+ let nonExistentAttributeNames = A.attributeNamesNotContained names typeNameSet
1438+ if not (S.null nonExistentAttributeNames) then
1439+ throwError $ AttributeNamesMismatchError nonExistentAttributeNames
1440+ else
1441+ pure (A.nonMatchingAttributeNameSet names typeNameSet)
1442+
1443+ UnionAttributeNames namesA namesB -> do
1444+ nameSetA <- evalGraphRefAttributeNames namesA expr
1445+ nameSetB <- evalGraphRefAttributeNames namesB expr
1446+ pure (S.union nameSetA nameSetB)
1447+
1448+ IntersectAttributeNames namesA namesB -> do
1449+ nameSetA <- evalGraphRefAttributeNames namesA expr
1450+ nameSetB <- evalGraphRefAttributeNames namesB expr
1451+ pure (S.intersection nameSetA nameSetB)
1452+
1453+ RelationalExprAttributeNames attrExpr -> do
1454+ attrExprType <- typeForGraphRefRelationalExpr attrExpr
1455+ pure (A.attributeNameSet (attributes attrExprType))
1456+
1457+evalGraphRefAttributeExpr :: GraphRefAttributeExpr -> GraphRefRelationalExprM Attribute
1458+evalGraphRefAttributeExpr (AttributeAndTypeNameExpr attrName tCons tid) = do
1459+ tConsMap <- typeConstructorMapping <$> gfDatabaseContextForMarker tid
1460+ case atomTypeForTypeConstructorValidate True tCons tConsMap M.empty of
1461+ Left err -> throwError err
1462+ Right aType -> do
1463+ case validateAtomType aType tConsMap of
1464+ Left err -> throwError err
1465+ Right _ -> pure (Attribute attrName aType)
1466+evalGraphRefAttributeExpr (NakedAttributeExpr attr) = pure attr
1467+
1468+mkEmptyRelVars :: RelationVariables -> RelationVariables
1469+mkEmptyRelVars = M.map mkEmptyRelVar
1470+ where
1471+ mkEmptyRelVar expr@MakeRelationFromExprs{} = expr --do not truncate here because we might lose essential type information in emptying the tuples
1472+ mkEmptyRelVar (MakeStaticRelation attrs _) = MakeStaticRelation attrs emptyTupleSet
1473+ mkEmptyRelVar (ExistingRelation rel) = ExistingRelation (emptyRelationWithAttrs (attributes rel))
1474+ mkEmptyRelVar rv@RelationVariable{} = Restrict (NotPredicate TruePredicate) rv
1475+ mkEmptyRelVar (Project attrNames expr) = Project attrNames (mkEmptyRelVar expr)
1476+ mkEmptyRelVar (Union exprA exprB) = Union (mkEmptyRelVar exprA) (mkEmptyRelVar exprB)
1477+ mkEmptyRelVar (Join exprA exprB) = Join (mkEmptyRelVar exprA) (mkEmptyRelVar exprB)
1478+ mkEmptyRelVar (Rename nameA nameB expr) = Rename nameA nameB (mkEmptyRelVar expr)
1479+ mkEmptyRelVar (Difference exprA exprB) = Difference (mkEmptyRelVar exprA) (mkEmptyRelVar exprB)
1480+ mkEmptyRelVar (Group attrNames attrName expr) = Group attrNames attrName (mkEmptyRelVar expr)
1481+ mkEmptyRelVar (Ungroup attrName expr) = Ungroup attrName (mkEmptyRelVar expr)
1482+ mkEmptyRelVar (Restrict pred' expr) = Restrict pred' (mkEmptyRelVar expr)
1483+ mkEmptyRelVar (Equals exprA exprB) = Equals (mkEmptyRelVar exprA) (mkEmptyRelVar exprB)
1484+ mkEmptyRelVar (NotEquals exprA exprB) = NotEquals (mkEmptyRelVar exprA) (mkEmptyRelVar exprB)
1485+ mkEmptyRelVar (Extend extTuple expr) = Extend extTuple (mkEmptyRelVar expr)
1486+ mkEmptyRelVar (With macros expr) = With (map (second mkEmptyRelVar) macros) (mkEmptyRelVar expr)
1487+
1488+
1489+dbErr :: RelationalError -> DatabaseContextEvalMonad ()
1490+dbErr err = lift (except (Left err))
1491+
1492+-- | Return a Relation describing the relation variables.
1493+relationVariablesAsRelation :: DatabaseContext -> TransactionGraph -> Either RelationalError Relation
1494+relationVariablesAsRelation ctx graph = do
1495+ let subrelAttrs = A.attributesFromList [Attribute "attribute" TextAtomType, Attribute "type" TextAtomType]
1496+ attrs = A.attributesFromList [Attribute "name" TextAtomType,
1497+ Attribute "attributes" (RelationAtomType subrelAttrs)]
1498+ relVars = relationVariables ctx
1499+ mkRvDesc (rvName, gfExpr) = do
1500+ let gfEnv = freshGraphRefRelationalExprEnv (Just ctx) graph
1501+ gfType <- runGraphRefRelationalExprM gfEnv (typeForGraphRefRelationalExpr gfExpr)
1502+ pure (rvName, gfType)
1503+ relVarToAtomList (rvName, rel) = [TextAtom rvName, attributesToRel (attributes rel)]
1504+ attrAtoms a = [TextAtom (A.attributeName a), TextAtom (prettyAtomType (A.atomType a))]
1505+ attributesToRel attrl = case mkRelationFromList subrelAttrs (map attrAtoms (V.toList attrl)) of
1506+ Left err -> error ("relationVariablesAsRelation pooped " ++ show err)
1507+ Right rel -> RelationAtom rel
1508+ rvs <- mapM mkRvDesc (M.toList relVars)
1509+ let tups = map relVarToAtomList rvs
1510+ mkRelationFromList attrs tups
1511+
1512+-- | An unoptimized variant of evalGraphRefRelationalExpr for testing.
1513+evalRelationalExpr :: RelationalExpr -> RelationalExprM Relation
1514+evalRelationalExpr expr = do
1515+ graph <- reGraph
1516+ context <- reContext
1517+ let expr' = runProcessExprM UncommittedContextMarker (processRelationalExpr expr)
1518+ gfEnv = freshGraphRefRelationalExprEnv (Just context) graph
1519+ case runGraphRefRelationalExprM gfEnv (evalGraphRefRelationalExpr expr') of
1520+ Left err -> throwError err
1521+ Right rel -> pure rel
1522+
1523+{-
1524+relVarByName :: RelVarName -> GraphRefRelationalExprM GraphRefRelationalExpr
1525+relVarByName = do
1526+ relvars <- relationVariables <$> getStateContext
1527+ case M.lookup relVarName relvars of
1528+ Nothing -> dbErr (RelVarNotDefinedError relVarName)
1529+ Just gfexpr -> pure gfExpr
1530+-}
1531+
1532+class (MonadError RelationalError m, Monad m) => DatabaseContextM m where
1533+ getContext :: m DatabaseContext
1534+
1535+instance DatabaseContextM (ReaderT GraphRefRelationalExprEnv (ExceptT RelationalError Identity)) where
1536+ getContext = gfDatabaseContextForMarker UncommittedContextMarker
1537+
1538+instance DatabaseContextM (RWST DatabaseContextEvalEnv () DatabaseContextEvalState (ExceptT RelationalError Identity)) where
1539+ getContext = getStateContext
1540+
1541+relVarByName :: DatabaseContextM m => RelVarName -> m GraphRefRelationalExpr
1542+relVarByName rvName = do
1543+ relvars <- relationVariables <$> getContext
1544+ case M.lookup rvName relvars of
1545+ Nothing -> throwError (RelVarNotDefinedError rvName)
1546+ Just gfexpr -> pure gfexpr
1547+
1548+-- | resolve UncommittedTransactionMarker whenever possible- this is important in the DatabaseContext in order to mitigate self-referencing loops for updates
1549+class ResolveGraphRefTransactionMarker a where
1550+ resolve :: a -> DatabaseContextEvalMonad a
1551+
1552+-- s := s union t
1553+instance ResolveGraphRefTransactionMarker GraphRefRelationalExpr where
1554+ resolve (MakeRelationFromExprs mAttrs tupleExprs) =
1555+ MakeRelationFromExprs mAttrs <$> resolve tupleExprs
1556+ resolve orig@MakeStaticRelation{} = pure orig
1557+ resolve orig@ExistingRelation{} = pure orig
1558+ resolve orig@(RelationVariable rvName UncommittedContextMarker) = do
1559+ rvMap <- relationVariables <$> getStateContext
1560+ case M.lookup rvName rvMap of
1561+ Nothing -> pure orig
1562+ Just resolvedRv -> resolve resolvedRv
1563+ resolve orig@RelationVariable{} = pure orig
1564+ resolve (Project attrNames relExpr) = Project <$> resolve attrNames <*> resolve relExpr
1565+ resolve (Union exprA exprB) = Union <$> resolve exprA <*> resolve exprB
1566+ resolve (Join exprA exprB) = Join <$> resolve exprA <*> resolve exprB
1567+ resolve (Rename attrA attrB expr) = Rename attrA attrB <$> resolve expr
1568+ resolve (Difference exprA exprB) = Difference <$> resolve exprA <*> resolve exprB
1569+ resolve (Group namesA nameB expr) = Group <$> resolve namesA <*> pure nameB <*> resolve expr
1570+ resolve (Ungroup nameA expr) = Ungroup nameA <$> resolve expr
1571+ resolve (Restrict restrictExpr relExpr) = Restrict <$> resolve restrictExpr <*> resolve relExpr
1572+ resolve (Equals exprA exprB) = Equals <$> resolve exprA <*> resolve exprB
1573+ resolve (NotEquals exprA exprB) = NotEquals <$> resolve exprA <*> resolve exprB
1574+ resolve (Extend extendExpr relExpr) = Extend <$> resolve extendExpr <*> resolve relExpr
1575+ resolve (With withExprs relExpr) = With <$> mapM (\(nam, expr) -> (,) <$> resolve nam <*> resolve expr) withExprs <*> resolve relExpr
1576+
1577+instance ResolveGraphRefTransactionMarker GraphRefTupleExprs where
1578+ resolve (TupleExprs marker tupleExprs) =
1579+ TupleExprs marker <$> mapM resolve tupleExprs
1580+
1581+instance ResolveGraphRefTransactionMarker GraphRefTupleExpr where
1582+ resolve (TupleExpr tupMap) = do
1583+ tupMap' <- mapM (\(attrName, expr) -> (,) attrName <$> resolve expr ) (M.toList tupMap)
1584+ pure (TupleExpr (M.fromList tupMap'))
1585+
1586+instance ResolveGraphRefTransactionMarker GraphRefAttributeNames where
1587+ resolve orig@AttributeNames{} = pure orig
1588+ resolve orig@InvertedAttributeNames{} = pure orig
1589+ resolve (UnionAttributeNames namesA namesB) = UnionAttributeNames <$> resolve namesA <*> resolve namesB
1590+ resolve (IntersectAttributeNames namesA namesB) = IntersectAttributeNames <$> resolve namesA <*> resolve namesB
1591+ resolve (RelationalExprAttributeNames expr) = RelationalExprAttributeNames <$> resolve expr
1592+
1593+instance ResolveGraphRefTransactionMarker GraphRefRestrictionPredicateExpr where
1594+ resolve TruePredicate = pure TruePredicate
1595+ resolve (AndPredicate exprA exprB) = AndPredicate <$> resolve exprA <*> resolve exprB
1596+ resolve (OrPredicate exprA exprB) = OrPredicate <$> resolve exprA <*> resolve exprB
1597+ resolve (NotPredicate expr) = NotPredicate <$> resolve expr
1598+ resolve (RelationalExprPredicate expr) = RelationalExprPredicate <$> resolve expr
1599+ resolve (AtomExprPredicate expr) = AtomExprPredicate <$> resolve expr
1600+ resolve (AttributeEqualityPredicate nam expr)= AttributeEqualityPredicate nam <$> resolve expr
1601+
1602+instance ResolveGraphRefTransactionMarker GraphRefExtendTupleExpr where
1603+ resolve (AttributeExtendTupleExpr nam atomExpr) = AttributeExtendTupleExpr nam <$> resolve atomExpr
1604+
1605+instance ResolveGraphRefTransactionMarker GraphRefWithNameExpr where
1606+ resolve orig@WithNameExpr{} = pure orig -- match uncommitted marker?
1607+
1608+instance ResolveGraphRefTransactionMarker GraphRefAtomExpr where
1609+ resolve orig@AttributeAtomExpr{} = pure orig
1610+ resolve orig@NakedAtomExpr{} = pure orig
1611+ resolve (FunctionAtomExpr nam atomExprs marker) =
1612+ FunctionAtomExpr nam <$> mapM resolve atomExprs <*> pure marker
1613+ resolve (RelationAtomExpr expr) = RelationAtomExpr <$> resolve expr
1614+ resolve (ConstructedAtomExpr dConsName atomExprs marker) =
1615+ ConstructedAtomExpr dConsName <$> mapM resolve atomExprs <*> pure marker
src/lib/ProjectM36/ScriptSession.hs+97−37
@@ -1,8 +1,12 @@
1−{-# LANGUAGE MagicHash, UnboxedTuples #-}
1+{-# LANGUAGE UnboxedTuples, KindSignatures, DataKinds #-}
2+#ifdef PM36_HASKELL_SCRIPTING
3+{-# LANGUAGE MagicHash #-}
4+#endif
2module ProjectM36.ScriptSession where
5module ProjectM36.ScriptSession where
3
6
7+#ifdef PM36_HASKELL_SCRIPTING
4import ProjectM36.Error
8import ProjectM36.Error
5−
9+import GHC
6import Control.Exception
10import Control.Exception
7import Control.Monad
11import Control.Monad
8import System.IO.Error
12import System.IO.Error
@@ -13,37 +17,60 @@ import System.FilePath
13import System.Info (os, arch)
17import System.Info (os, arch)
14import Data.Text (Text, unpack)
18import Data.Text (Text, unpack)
15import Data.Maybe
19import Data.Maybe
16−
17−import GHC
18import GHC.Paths (libdir)
20import GHC.Paths (libdir)
21+import System.Environment
19#if __GLASGOW_HASKELL__ >= 800
22#if __GLASGOW_HASKELL__ >= 800
20import GHC.LanguageExtensions
23import GHC.LanguageExtensions
21import GHCi.ObjLink
24import GHCi.ObjLink
22#else
25#else
23import ObjLink
26import ObjLink
24#endif
27#endif
28+#if __GLASGOW_HASKELL__ >= 802
29+import BasicTypes
30+#endif
25import DynFlags
31import DynFlags
26import Panic
32import Panic
27import Outputable --hiding ((<>))
33import Outputable --hiding ((<>))
28import PprTyThing
34import PprTyThing
29import Unsafe.Coerce
35import Unsafe.Coerce
36+#if __GLASGOW_HASKELL__ >= 802
30import Type
37import Type
31−
38+#elif __GLASGOW_HASKELL__ >= 710
39+import Type hiding (pprTyThing)
40+#else
41+#endif
32import GHC.Exts (addrToAny#)
42import GHC.Exts (addrToAny#)
33import GHC.Ptr (Ptr(..))
43import GHC.Ptr (Ptr(..))
34import Encoding
44import Encoding
45+#endif
46+
35
47
36data ScriptSession = ScriptSession {
48data ScriptSession = ScriptSession {
49+#ifdef PM36_HASKELL_SCRIPTING
37− hscEnv :: HscEnv,
50+ hscEnv :: HscEnv,
38 atomFunctionBodyType :: Type,
51 atomFunctionBodyType :: Type,
39 dbcFunctionBodyType :: Type
52 dbcFunctionBodyType :: Type
53+#endif
40 }
54 }
41−
55+
56+#ifdef PM36_HASKELL_SCRIPTING
42−newtype ScriptSessionError = ScriptSessionLoadError GhcException
57+data ScriptSessionError = ScriptSessionLoadError GhcException
58+ | ScriptingDisabled
43 deriving (Show)
59 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
44
68
45-- | Configure a GHC environment/session which we will use for all script compilation.
69-- | Configure a GHC environment/session which we will use for all script compilation.
46initScriptSession :: [String] -> IO (Either ScriptSessionError ScriptSession)
70initScriptSession :: [String] -> IO (Either ScriptSessionError ScriptSession)
71+#if !defined(PM36_HASKELL_SCRIPTING)
72+initScriptSession _ = pure (Left ScriptingDisabled)
73+#else
47initScriptSession ghcPkgPaths = do
74initScriptSession ghcPkgPaths = do
48 --for the sake of convenience, for developers' builds, include the local cabal sandbox package database and the cabal new-build package database
75 --for the sake of convenience, for developers' builds, include the local cabal sandbox package database and the cabal new-build package database
49 eHomeDir <- tryJust (guard . isDoesNotExistError) getHomeDirectory
76 eHomeDir <- tryJust (guard . isDoesNotExistError) getHomeDirectory
@@ -52,40 +79,47 @@ initScriptSession ghcPkgPaths = do
52 handleGhcException excHandler $ runGhc (Just libdir) $ do
79 handleGhcException excHandler $ runGhc (Just libdir) $ do
53 dflags <- getSessionDynFlags
80 dflags <- getSessionDynFlags
54 let ghcVersion = projectVersion dflags
81 let ghcVersion = projectVersion dflags
82+ -- get nix packages dir, if available
83+ mNixLibDir <- liftIO $ lookupEnv "NIX_GHC_LIBDIR"
55
84
56 sandboxPkgPaths <- liftIO $ concat <$> mapM glob [
85 sandboxPkgPaths <- liftIO $ concat <$> mapM glob [
57− "./dist-newstyle/packagedb/ghc-" ++ ghcVersion,
86+ --"./dist-newstyle/packagedb/ghc-" ++ ghcVersion, --rely on cabal 3's ghc.environment install: "cabal install --lib project-m36"
58 ".cabal-sandbox/*ghc-" ++ ghcVersion ++ "-packages.conf.d",
87 ".cabal-sandbox/*ghc-" ++ ghcVersion ++ "-packages.conf.d",
59 ".stack-work/install/*/*/" ++ ghcVersion ++ "/pkgdb",
88 ".stack-work/install/*/*/" ++ ghcVersion ++ "/pkgdb",
60 ".stack-work/install/*/pkgdb/", --windows stack build
89 ".stack-work/install/*/pkgdb/", --windows stack build
61 "C:/sr/snapshots/b201cfe6/pkgdb", --windows stack build- ideally, we could run `stack path --snapshot-pkg-db, but this is sufficient to pass CI
90 "C:/sr/snapshots/b201cfe6/pkgdb", --windows stack build- ideally, we could run `stack path --snapshot-pkg-db, but this is sufficient to pass CI
62− homeDir </> ".stack/snapshots/*/*/" ++ ghcVersion ++ "/pkgdb",
91+ homeDir </> ".stack/snapshots/*/*/" ++ ghcVersion ++ "/pkgdb"
63− homeDir </> ".cabal/store/ghc-" ++ ghcVersion ++ "/package.db"
92+ --homeDir </> ".cabal/store/ghc-" ++ ghcVersion ++ "/package.db"
64 ]
93 ]
65−
94+
66− let localPkgPaths = map PkgConfFile (ghcPkgPaths ++ sandboxPkgPaths)
95+ let localPkgPaths = map PkgConfFile (ghcPkgPaths ++ sandboxPkgPaths ++ maybeToList mNixLibDir)
67−
96+
68− let dflags' = applyGopts . applyXopts $ dflags { hscTarget = HscInterpreted ,
97+ let dflags' = applyGopts . applyXopts $ dflags { hscTarget = HscInterpreted ,
69− ghcLink = LinkInMemory,
98+ ghcLink = LinkInMemory,
70 safeHaskell = Sf_Trustworthy,
99 safeHaskell = Sf_Trustworthy,
71 safeInfer = True,
100 safeInfer = True,
72 safeInferred = True,
101 safeInferred = True,
73 --verbosity = 3,
102 --verbosity = 3,
74−#if __GLASGOW_HASKELL__ >= 800
103+#if __GLASGOW_HASKELL__ >= 800
75 trustFlags = map TrustPackage required_packages,
104 trustFlags = map TrustPackage required_packages,
76−#endif
105+#endif
77 packageFlags = packageFlags dflags ++ packages,
106 packageFlags = packageFlags dflags ++ packages,
107+#if __GLASGOW_HASKELL__ >= 802
108+ packageDBFlags = map PackageDB localPkgPaths
109+#else
78 extraPkgConfs = const (localPkgPaths ++ [UserPkgConf, GlobalPkgConf])
110 extraPkgConfs = const (localPkgPaths ++ [UserPkgConf, GlobalPkgConf])
111+#endif
112+
79 }
113 }
80 applyGopts flags = foldl gopt_set flags gopts
114 applyGopts flags = foldl gopt_set flags gopts
81 applyXopts flags = foldl xopt_set flags xopts
115 applyXopts flags = foldl xopt_set flags xopts
82#if __GLASGOW_HASKELL__ >= 800
116#if __GLASGOW_HASKELL__ >= 800
83 xopts = [OverloadedStrings, ExtendedDefaultRules, ImplicitPrelude, ScopedTypeVariables]
117 xopts = [OverloadedStrings, ExtendedDefaultRules, ImplicitPrelude, ScopedTypeVariables]
84−#else
118+#else
85 xopts = [Opt_OverloadedStrings, Opt_ExtendedDefaultRules, Opt_ImplicitPrelude, Opt_ScopedTypeVariables]
119 xopts = [Opt_OverloadedStrings, Opt_ExtendedDefaultRules, Opt_ImplicitPrelude, Opt_ScopedTypeVariables]
86#endif
120#endif
87 gopts = [] --[Opt_DistrustAllPackages, Opt_PackageTrust]
121 gopts = [] --[Opt_DistrustAllPackages, Opt_PackageTrust]
88− required_packages = ["base",
122+ required_packages = ["base",
89 "containers",
123 "containers",
90 "Glob",
124 "Glob",
91 "directory",
125 "directory",
@@ -107,16 +141,33 @@ initScriptSession ghcPkgPaths = do
107 --liftIO $ traceShowM (showSDoc dflags' (ppr packages))
141 --liftIO $ traceShowM (showSDoc dflags' (ppr packages))
108 _ <- setSessionDynFlags dflags'
142 _ <- setSessionDynFlags dflags'
109 let safeImportDecl mn mQual = ImportDecl {
143 let safeImportDecl mn mQual = ImportDecl {
144+#if __GLASGOW_HASKELL__ >= 802
145+ ideclSourceSrc = NoSourceText,
146+#else
110 ideclSourceSrc = Nothing,
147 ideclSourceSrc = Nothing,
148+#endif
149+
150+#if __GLASGOW_HASKELL__ >= 810
151+ ideclExt = noExtField,
152+#elif __GLASGOW_HASKELL__ >= 806
153+ ideclExt = NoExt,
154+#endif
111 ideclName = noLoc mn,
155 ideclName = noLoc mn,
112 ideclPkgQual = Nothing,
156 ideclPkgQual = Nothing,
113 ideclSource = False,
157 ideclSource = False,
114 ideclSafe = True,
158 ideclSafe = True,
115 ideclImplicit = False,
159 ideclImplicit = False,
160+#if __GLASGOW_HASKELL__ >= 810
161+ ideclQualified = if isJust mQual then QualifiedPre else NotQualified,
162+#else
116 ideclQualified = isJust mQual,
163 ideclQualified = isJust mQual,
164+#endif
117 ideclAs = mQual,
165 ideclAs = mQual,
118 ideclHiding = Nothing
166 ideclHiding = Nothing
119 }
167 }
168+#if __GLASGOW_HASKELL__ >= 806
169+ :: ImportDecl (GhcPass (c :: Pass))
170+#endif
120 unqualifiedModules = map (\modn -> IIDecl $ safeImportDecl (mkModuleName modn) Nothing) [
171 unqualifiedModules = map (\modn -> IIDecl $ safeImportDecl (mkModuleName modn) Nothing) [
121 "Prelude",
172 "Prelude",
122 "Data.Map",
173 "Data.Map",
@@ -129,7 +180,12 @@ initScriptSession ghcPkgPaths = do
129 "ProjectM36.DatabaseContextFunctionError",
180 "ProjectM36.DatabaseContextFunctionError",
130 "ProjectM36.DatabaseContextFunctionUtils",
181 "ProjectM36.DatabaseContextFunctionUtils",
131 "ProjectM36.RelationalExpression"]
182 "ProjectM36.RelationalExpression"]
183+#if __GLASGOW_HASKELL__ >= 802
184+ mkModName = noLoc . mkModuleName
185+#else
186+ mkModName = mkModuleName
187+#endif
132− qualifiedModules = map (\(modn, qualNam) -> IIDecl $ safeImportDecl (mkModuleName modn) (Just (mkModuleName qualNam))) [
188+ qualifiedModules = map (\(modn, qualNam) -> IIDecl $ safeImportDecl (mkModuleName modn) (Just (mkModName qualNam))) [
133 ("Data.Text", "T")
189 ("Data.Text", "T")
134 ]
190 ]
135 setContext (unqualifiedModules ++ qualifiedModules)
191 setContext (unqualifiedModules ++ qualifiedModules)
@@ -141,8 +197,8 @@ initScriptSession ghcPkgPaths = do
141addImport :: String -> Ghc ()
197addImport :: String -> Ghc ()
142addImport moduleNam = do
198addImport moduleNam = do
143 ctx <- getContext
199 ctx <- getContext
144− setContext ( (IIDecl $ simpleImportDecl (mkModuleName moduleNam)) : ctx )
200+ setContext (IIDecl (simpleImportDecl (mkModuleName moduleNam)) : ctx)
145−
201+
146showType :: DynFlags -> Type -> String
202showType :: DynFlags -> Type -> String
147showType dflags ty = showSDocForUser dflags alwaysQualify (pprTypeForUser ty)
203showType dflags ty = showSDocForUser dflags alwaysQualify (pprTypeForUser ty)
148
204
@@ -167,37 +223,40 @@ compileScript funcType script = do
167 mErr <- typeCheckScript funcType script
223 mErr <- typeCheckScript funcType script
168 case mErr of
224 case mErr of
169 Just err -> pure (Left err)
225 Just err -> pure (Left err)
170− Nothing ->
226+ Nothing ->
171 --catch exception here
227 --catch exception here
172 --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.
228 --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.
173 -- we can't use dynCompileExpr here because
229 -- we can't use dynCompileExpr here because
174 Right . unsafeCoerce <$> compileExpr sScript
230 Right . unsafeCoerce <$> compileExpr sScript
175−
231+
176−typeCheckScript :: Type -> Text -> Ghc (Maybe ScriptCompilationError)
232+typeCheckScript :: Type -> Text -> Ghc (Maybe ScriptCompilationError)
177typeCheckScript expectedType inp = do
233typeCheckScript expectedType inp = do
178− dflags <- getSessionDynFlags
234+ dflags <- getSessionDynFlags
179 --catch exception for SyntaxError
235 --catch exception for SyntaxError
236+#if __GLASGOW_HASKELL__ >= 802
237+ funcType <- GHC.exprType TM_Inst (unpack inp)
238+#else
180 funcType <- GHC.exprType (unpack inp)
239 funcType <- GHC.exprType (unpack inp)
240+#endif
181− --liftIO $ putStrLn $ showType dflags expectedType ++ ":::" ++ showType dflags funcType
241+ --liftIO $ putStrLn $ showType dflags expectedType ++ ":::" ++ showType dflags funcType
182 if eqType funcType expectedType then
242 if eqType funcType expectedType then
183 pure Nothing
243 pure Nothing
184 else
244 else
185 pure (Just (TypeCheckCompilationError (showType dflags expectedType) (showType dflags funcType)))
245 pure (Just (TypeCheckCompilationError (showType dflags expectedType) (showType dflags funcType)))
186−
246+
187mangleSymbol :: Maybe String -> String -> String -> String
247mangleSymbol :: Maybe String -> String -> String -> String
188mangleSymbol pkg module' valsym =
248mangleSymbol pkg module' valsym =
189 prefixUnderscore ++
249 prefixUnderscore ++
190 maybe "" (\p -> zEncodeString p ++ "_") pkg ++
250 maybe "" (\p -> zEncodeString p ++ "_") pkg ++
191 zEncodeString module' ++ "_" ++ zEncodeString valsym ++ "_closure"
251 zEncodeString module' ++ "_" ++ zEncodeString valsym ++ "_closure"
192−
193−type ModName = String
194−type FuncName = String
195−
196−data LoadSymbolError = LoadSymbolError
197
252
198loadFunction :: ModName -> FuncName -> FilePath -> IO (Either LoadSymbolError a)
253loadFunction :: ModName -> FuncName -> FilePath -> IO (Either LoadSymbolError a)
199loadFunction modName funcName objPath = do
254loadFunction modName funcName objPath = do
255+#if __GLASGOW_HASKELL__ >= 802
256+ initObjLinker RetainCAFs
257+#else
200 initObjLinker
258 initObjLinker
259+#endif
201 loadObj objPath
260 loadObj objPath
202 _ <- resolveObjs
261 _ <- resolveObjs
203 ptr <- lookupSymbol (mangleSymbol Nothing modName funcName)
262 ptr <- lookupSymbol (mangleSymbol Nothing modName funcName)
@@ -205,8 +264,8 @@ loadFunction modName funcName objPath = do
205 Nothing -> pure (Left LoadSymbolError)
264 Nothing -> pure (Left LoadSymbolError)
206 Just (Ptr addr) -> case addrToAny# addr of
265 Just (Ptr addr) -> case addrToAny# addr of
207 (# hval #) -> pure (Right hval)
266 (# hval #) -> pure (Right hval)
208−
267+
209−prefixUnderscore :: String
268+prefixUnderscore :: String
210prefixUnderscore =
269prefixUnderscore =
211 case (os,arch) of
270 case (os,arch) of
212 ("mingw32","x86_64") -> ""
271 ("mingw32","x86_64") -> ""
@@ -214,4 +273,5 @@ prefixUnderscore =
214 ("mingw32",_) -> "_"
273 ("mingw32",_) -> "_"
215 ("darwin",_) -> "_"
274 ("darwin",_) -> "_"
216 ("cygwin",_) -> "_"
275 ("cygwin",_) -> "_"
217− _ -> ""
276+ _ -> ""
277+#endif
src/lib/ProjectM36/Server.hs+13−6
@@ -8,7 +8,11 @@ import ProjectM36.Server.Config (ServerConfig(..))
8import ProjectM36.FSType
8import ProjectM36.FSType
9
9
10import Control.Monad.IO.Class (liftIO)
10import Control.Monad.IO.Class (liftIO)
11+#if MIN_VERSION_network_transport_tcp(0,7,0)
12+import Network.Transport.TCP (createTransport, defaultTCPParameters, defaultTCPAddr)
13+#else
11import Network.Transport.TCP (createTransport, defaultTCPParameters)
14import Network.Transport.TCP (createTransport, defaultTCPParameters)
15+#endif
12import Network.Transport (EndPointAddress(..), newEndPoint, address)
16import Network.Transport (EndPointAddress(..), newEndPoint, address)
13import Control.Distributed.Process.Node (initRemoteTable, runProcess, newLocalNode, initRemoteTable)
17import Control.Distributed.Process.Node (initRemoteTable, runProcess, newLocalNode, initRemoteTable)
14import Control.Distributed.Process.Extras.Time (Delay(..))
18import Control.Distributed.Process.Extras.Time (Delay(..))
@@ -26,6 +30,7 @@ serverDefinition testBool ti = defaultProcess {
26 apiHandlers = [
30 apiHandlers = [
27 handleCall (\conn (ExecuteHeadName sessionId) -> handleExecuteHeadName ti sessionId conn),
31 handleCall (\conn (ExecuteHeadName sessionId) -> handleExecuteHeadName ti sessionId conn),
28 handleCall (\conn (ExecuteRelationalExpr sessionId expr) -> handleExecuteRelationalExpr ti sessionId conn expr),
32 handleCall (\conn (ExecuteRelationalExpr sessionId expr) -> handleExecuteRelationalExpr ti sessionId conn expr),
33+ handleCall (\conn (ExecuteDataFrameExpr sessionId expr) -> handleExecuteDataFrameExpr ti sessionId conn expr),
29 handleCall (\conn (ExecuteDatabaseContextExpr sessionId expr) -> handleExecuteDatabaseContextExpr ti sessionId conn expr),
34 handleCall (\conn (ExecuteDatabaseContextExpr sessionId expr) -> handleExecuteDatabaseContextExpr ti sessionId conn expr),
30 handleCall (\conn (ExecuteDatabaseContextIOExpr sessionId expr) -> handleExecuteDatabaseContextIOExpr ti sessionId conn expr),
35 handleCall (\conn (ExecuteDatabaseContextIOExpr sessionId expr) -> handleExecuteDatabaseContextIOExpr ti sessionId conn expr),
31 handleCall (\conn (ExecuteGraphExpr sessionId expr) -> handleExecuteGraphExpr ti sessionId conn expr),
36 handleCall (\conn (ExecuteGraphExpr sessionId expr) -> handleExecuteGraphExpr ti sessionId conn expr),
@@ -48,17 +53,14 @@ serverDefinition testBool ti = defaultProcess {
48 handleCall (\conn (RetrieveSessionIsDirty sessionId) -> handleRetrieveSessionIsDirty ti sessionId conn),
53 handleCall (\conn (RetrieveSessionIsDirty sessionId) -> handleRetrieveSessionIsDirty ti sessionId conn),
49 handleCall (\conn (ExecuteAutoMergeToHead sessionId strat headName') -> handleExecuteAutoMergeToHead ti sessionId conn strat headName'),
54 handleCall (\conn (ExecuteAutoMergeToHead sessionId strat headName') -> handleExecuteAutoMergeToHead ti sessionId conn strat headName'),
50 handleCall (\conn (RetrieveTypeConstructorMapping sessionId) -> handleRetrieveTypeConstructorMapping ti sessionId conn),
55 handleCall (\conn (RetrieveTypeConstructorMapping sessionId) -> handleRetrieveTypeConstructorMapping ti sessionId conn),
56+ handleCall (\conn (ExecuteValidateMerkleHashes sessionId) -> handleValidateMerkleHashes ti sessionId conn),
51 handleCall (\conn Logout -> handleLogout ti conn)
57 handleCall (\conn Logout -> handleLogout ti conn)
52 ] ++ testModeHandlers,
58 ] ++ testModeHandlers,
53 unhandledMessagePolicy = Terminate
59 unhandledMessagePolicy = Terminate
54 --unhandledMessagePolicy = Log
60 --unhandledMessagePolicy = Log
55 }
61 }
56 where
62 where
57− testModeHandlers = if not testBool then
58− []
59− else
60− [handleCall (\conn (TestTimeout sessionId) -> handleTestTimeout ti sessionId conn)]
63+ testModeHandlers = [handleCall (\conn (TestTimeout sessionId) -> handleTestTimeout ti sessionId conn) | testBool]
61−
62
64
63initServer :: InitHandler (Connection, DatabaseName, Maybe (MVar EndPointAddress), EndPointAddress) Connection
65initServer :: InitHandler (Connection, DatabaseName, Maybe (MVar EndPointAddress), EndPointAddress) Connection
64initServer (conn, dbname, mAddressMVar, saddress) = do
66initServer (conn, dbname, mAddressMVar, saddress) = do
@@ -116,7 +118,13 @@ launchServer daemonConfig mAddressMVar = do
116 Right conn -> do
118 Right conn -> do
117 let hostname = bindHost daemonConfig
119 let hostname = bindHost daemonConfig
118 port = bindPort daemonConfig
120 port = bindPort daemonConfig
121+#if MIN_VERSION_network_transport_tcp(0,7,0)
122+ etransport <- createTransport (defaultTCPAddr hostname (show port)) defaultTCPParameters
123+#elif MIN_VERSION_network_transport_tcp(0,6,0)
124+ etransport <- createTransport hostname (show port) (\nam -> (hostname, nam)) defaultTCPParameters
125+#else
119 etransport <- createTransport hostname (show port) defaultTCPParameters
126 etransport <- createTransport hostname (show port) defaultTCPParameters
127+#endif
120 case etransport of
128 case etransport of
121 Left err -> error ("failed to create transport: " ++ show err)
129 Left err -> error ("failed to create transport: " ++ show err)
122 Right transport -> do
130 Right transport -> do
@@ -132,4 +140,3 @@ launchServer daemonConfig mAddressMVar = do
132 serve (conn, databaseName daemonConfig, mAddressMVar, address endpoint) initServer (serverDefinition testBool reqTimeout)
140 serve (conn, databaseName daemonConfig, mAddressMVar, address endpoint) initServer (serverDefinition testBool reqTimeout)
133 liftIO $ putStrLn "serve returned"
141 liftIO $ putStrLn "serve returned"
134 pure True
142 pure True
135−
src/lib/ProjectM36/Server/EntryPoints.hs+15−4
@@ -1,3 +1,4 @@
1+{-# LANGUAGE MonoLocalBinds #-}
1module ProjectM36.Server.EntryPoints where
2module ProjectM36.Server.EntryPoints where
2import ProjectM36.Base hiding (inclusionDependencies)
3import ProjectM36.Base hiding (inclusionDependencies)
3import ProjectM36.IsomorphicSchema
4import ProjectM36.IsomorphicSchema
@@ -7,12 +8,13 @@ import Control.Distributed.Process (Process, ProcessId)
7import Control.Distributed.Process.ManagedProcess (ProcessReply)
8import Control.Distributed.Process.ManagedProcess (ProcessReply)
8import Control.Distributed.Process.ManagedProcess.Server (reply)
9import Control.Distributed.Process.ManagedProcess.Server (reply)
9import Control.Distributed.Process.Async (async, task, waitCancelTimeout, AsyncResult(..))
10import Control.Distributed.Process.Async (async, task, waitCancelTimeout, AsyncResult(..))
10−import Control.Distributed.Process.Serializable (Serializable)
11import Control.Monad.IO.Class (liftIO)
11import Control.Monad.IO.Class (liftIO)
12import Data.Map
12import Data.Map
13import Control.Concurrent (threadDelay)
13import Control.Concurrent (threadDelay)
14+import Data.Typeable
15+import Data.Binary
14
16
15−timeoutOrDie :: Serializable a => Timeout -> IO a -> Process (Either ServerError a)
17+timeoutOrDie :: (Binary a, Typeable a) => Timeout -> IO a -> Process (Either ServerError a)
16timeoutOrDie micros act =
18timeoutOrDie micros act =
17 if micros == 0 then
19 if micros == 0 then
18 liftIO act >>= \x -> pure (Right x)
20 liftIO act >>= \x -> pure (Right x)
@@ -34,6 +36,11 @@ handleExecuteRelationalExpr :: Timeout -> SessionId -> Connection -> RelationalE
34handleExecuteRelationalExpr ti sessionId conn expr = do
36handleExecuteRelationalExpr ti sessionId conn expr = do
35 ret <- timeoutOrDie ti (executeRelationalExpr sessionId conn expr)
37 ret <- timeoutOrDie ti (executeRelationalExpr sessionId conn expr)
36 reply ret conn
38 reply ret conn
39+
40+handleExecuteDataFrameExpr :: Timeout -> SessionId -> Connection -> DataFrameExpr -> Reply (Either RelationalError DataFrame)
41+handleExecuteDataFrameExpr ti sessionId conn expr = do
42+ ret <- timeoutOrDie ti (executeDataFrameExpr sessionId conn expr)
43+ reply ret conn
37
44
38handleExecuteDatabaseContextExpr :: Timeout -> SessionId -> Connection -> DatabaseContextExpr -> Reply (Either RelationalError ())
45handleExecuteDatabaseContextExpr :: Timeout -> SessionId -> Connection -> DatabaseContextExpr -> Reply (Either RelationalError ())
39handleExecuteDatabaseContextExpr ti sessionId conn dbexpr = do
46handleExecuteDatabaseContextExpr ti sessionId conn dbexpr = do
@@ -77,7 +84,7 @@ handleRetrieveInclusionDependencies ti sessionId conn = do
77 ret <- timeoutOrDie ti (inclusionDependencies sessionId conn)
84 ret <- timeoutOrDie ti (inclusionDependencies sessionId conn)
78 reply ret conn
85 reply ret conn
79
86
80−handleRetrievePlanForDatabaseContextExpr :: Timeout -> SessionId -> Connection -> DatabaseContextExpr -> Reply (Either RelationalError DatabaseContextExpr)
87+handleRetrievePlanForDatabaseContextExpr :: Timeout -> SessionId -> Connection -> DatabaseContextExpr -> Reply (Either RelationalError GraphRefDatabaseContextExpr)
81handleRetrievePlanForDatabaseContextExpr ti sessionId conn dbExpr = do
88handleRetrievePlanForDatabaseContextExpr ti sessionId conn dbExpr = do
82 ret <- timeoutOrDie ti (planForDatabaseContextExpr sessionId conn dbExpr)
89 ret <- timeoutOrDie ti (planForDatabaseContextExpr sessionId conn dbExpr)
83 reply ret conn
90 reply ret conn
@@ -164,4 +171,8 @@ handleRetrieveTypeConstructorMapping :: Timeout -> SessionId -> Connection -> Re
164handleRetrieveTypeConstructorMapping ti sessionId conn = do
171handleRetrieveTypeConstructorMapping ti sessionId conn = do
165 ret <- timeoutOrDie ti (C.typeConstructorMapping sessionId conn)
172 ret <- timeoutOrDie ti (C.typeConstructorMapping sessionId conn)
166 reply ret conn
173 reply ret conn
167−
174+
175+handleValidateMerkleHashes :: Timeout -> SessionId -> Connection -> Reply (Either RelationalError ())
176+handleValidateMerkleHashes ti sessionId conn = do
177+ ret <- timeoutOrDie ti (C.validateMerkleHashes sessionId conn)
178+ reply ret conn
src/lib/ProjectM36/Server/ParseArgs.hs+29−11
@@ -3,18 +3,20 @@ import ProjectM36.Base
3import ProjectM36.Client
3import ProjectM36.Client
4import Options.Applicative
4import Options.Applicative
5import ProjectM36.Server.Config
5import ProjectM36.Server.Config
6+#if __GLASGOW_HASKELL__ < 804
6import Data.Monoid
7import Data.Monoid
8+#endif
7
9
8parseArgsWithDefaults :: ServerConfig -> Parser ServerConfig
10parseArgsWithDefaults :: ServerConfig -> Parser ServerConfig
9−parseArgsWithDefaults defaults = ServerConfig <$>
11+parseArgsWithDefaults defaults = ServerConfig <$>
10− parsePersistenceStrategy <*>
12+ parsePersistenceStrategy <*>
11− parseCheckFS <*>
13+ parseCheckFS <*>
12− parseDatabaseName <*>
14+ parseDatabaseName <*>
13− parseHostname (bindHost defaults) <*>
15+ parseHostname (bindHost defaults) <*>
14− parsePort (bindPort defaults) <*>
16+ parsePort (bindPort defaults) <*>
15− many parseGhcPkgPath <*>
17+ many parseGhcPkgPath <*>
16− parseTimeout (perRequestTimeout defaults) <*>
18+ parseTimeout (perRequestTimeout defaults) <*>
17− pure False
19+ parseTestMode
18
20
19parsePersistenceStrategy :: Parser PersistenceStrategy
21parsePersistenceStrategy :: Parser PersistenceStrategy
20parsePersistenceStrategy = CrashSafePersistence <$> (dbdirOpt <* fsyncOpt) <|>
22parsePersistenceStrategy = CrashSafePersistence <$> (dbdirOpt <* fsyncOpt) <|>
@@ -29,6 +31,9 @@ parsePersistenceStrategy = CrashSafePersistence <$> (dbdirOpt <* fsyncOpt) <|>
29 fsyncOpt = switch (short 'f' <>
31 fsyncOpt = switch (short 'f' <>
30 long "fsync" <>
32 long "fsync" <>
31 help "Fsync all new transactions.")
33 help "Fsync all new transactions.")
34+
35+parseTestMode :: Parser Bool
36+parseTestMode = flag True False (long "test-mode" <> hidden)
32
37
33parseCheckFS :: Parser Bool
38parseCheckFS :: Parser Bool
34parseCheckFS = flag True False (long "disable-fscheck" <>
39parseCheckFS = flag True False (long "disable-fscheck" <>
@@ -38,7 +43,7 @@ parseDatabaseName :: Parser DatabaseName
38parseDatabaseName = strOption (short 'n' <>
43parseDatabaseName = strOption (short 'n' <>
39 long "database" <>
44 long "database" <>
40 metavar "DATABASE_NAME")
45 metavar "DATABASE_NAME")
41−
46+
42parseHostname :: Hostname -> Parser Hostname
47parseHostname :: Hostname -> Parser Hostname
43parseHostname defHostname = strOption (short 'h' <>
48parseHostname defHostname = strOption (short 'h' <>
44 long "hostname" <>
49 long "hostname" <>
@@ -64,4 +69,17 @@ parseConfig :: IO ServerConfig
64parseConfig = parseConfigWithDefaults defaultServerConfig
69parseConfig = parseConfigWithDefaults defaultServerConfig
65
70
66parseConfigWithDefaults :: ServerConfig -> IO ServerConfig
71parseConfigWithDefaults :: ServerConfig -> IO ServerConfig
67−parseConfigWithDefaults defaults = execParser (info (parseArgsWithDefaults defaults) idm)
72+parseConfigWithDefaults defaults = execParser (info (parseArgsWithDefaults defaults <**> helpOption) idm)
73+
74+
75+helpOption :: Parser (a -> a)
76+helpOption = abortOption helpText $ mconcat
77+ [ long "help"
78+ , help "Show this help text"
79+ , hidden ]
80+ where
81+#if MIN_VERSION_optparse_applicative(0,16,0)
82+ helpText = ShowHelpText Nothing
83+#else
84+ helpText = ShowHelpText
85+#endif
src/lib/ProjectM36/Server/RemoteCallTypes.hs+7−1
@@ -3,6 +3,7 @@ module ProjectM36.Server.RemoteCallTypes where
3import ProjectM36.Base
3import ProjectM36.Base
4import ProjectM36.IsomorphicSchema
4import ProjectM36.IsomorphicSchema
5import ProjectM36.TransactionGraph
5import ProjectM36.TransactionGraph
6+import ProjectM36.DataFrame
6import ProjectM36.TransGraphRelationalExpression
7import ProjectM36.TransGraphRelationalExpression
7import ProjectM36.Session
8import ProjectM36.Session
8import GHC.Generics
9import GHC.Generics
@@ -18,6 +19,8 @@ data Logout = Logout
18 deriving (Binary, Generic)
19 deriving (Binary, Generic)
19data ExecuteRelationalExpr = ExecuteRelationalExpr SessionId RelationalExpr
20data ExecuteRelationalExpr = ExecuteRelationalExpr SessionId RelationalExpr
20 deriving (Binary, Generic)
21 deriving (Binary, Generic)
22+data ExecuteDataFrameExpr = ExecuteDataFrameExpr SessionId DataFrameExpr
23+ deriving (Binary, Generic)
21data ExecuteDatabaseContextExpr = ExecuteDatabaseContextExpr SessionId DatabaseContextExpr
24data ExecuteDatabaseContextExpr = ExecuteDatabaseContextExpr SessionId DatabaseContextExpr
22 deriving (Binary, Generic)
25 deriving (Binary, Generic)
23data ExecuteDatabaseContextIOExpr = ExecuteDatabaseContextIOExpr SessionId DatabaseContextIOExpr
26data ExecuteDatabaseContextIOExpr = ExecuteDatabaseContextIOExpr SessionId DatabaseContextIOExpr
@@ -65,4 +68,7 @@ data RetrieveSessionIsDirty = RetrieveSessionIsDirty SessionId
65data ExecuteAutoMergeToHead = ExecuteAutoMergeToHead SessionId MergeStrategy HeadName
68data ExecuteAutoMergeToHead = ExecuteAutoMergeToHead SessionId MergeStrategy HeadName
66 deriving (Binary, Generic)
69 deriving (Binary, Generic)
67data RetrieveTypeConstructorMapping = RetrieveTypeConstructorMapping SessionId
70data RetrieveTypeConstructorMapping = RetrieveTypeConstructorMapping SessionId
68− deriving (Binary, Generic)
71+ deriving (Binary, Generic)
72+
73+data ExecuteValidateMerkleHashes = ExecuteValidateMerkleHashes SessionId
74+ deriving (Binary, Generic)
src/lib/ProjectM36/Session.hs+3−2
@@ -3,6 +3,7 @@ import ProjectM36.Base
3import Data.UUID
3import Data.UUID
4import qualified Data.Map as M
4import qualified Data.Map as M
5import ProjectM36.Error
5import ProjectM36.Error
6+import qualified ProjectM36.DisconnectedTransaction as Discon
6
7
7type SessionId = UUID
8type SessionId = UUID
8
9
@@ -18,7 +19,7 @@ disconnectedTransaction :: Session -> DisconnectedTransaction
18disconnectedTransaction (Session discon _) = discon
19disconnectedTransaction (Session discon _) = discon
19
20
20isDirty :: Session -> DirtyFlag
21isDirty :: Session -> DirtyFlag
21−isDirty (Session (DisconnectedTransaction _ _ dirtyFlag) _) = dirtyFlag
22+isDirty (Session discon _) = Discon.isDirty discon
22
23
23concreteDatabaseContext :: Session -> DatabaseContext
24concreteDatabaseContext :: Session -> DatabaseContext
24concreteDatabaseContext (Session (DisconnectedTransaction _ (Schemas context _) _) _) = context
25concreteDatabaseContext (Session (DisconnectedTransaction _ (Schemas context _) _) _) = context
@@ -40,4 +41,4 @@ setSchemaName sname session = if sname == defaultSchemaName || M.member sname (s
40 pure (Session (disconnectedTransaction session) sname)
41 pure (Session (disconnectedTransaction session) sname)
41 else
42 else
42 Left (SubschemaNameNotInUseError sname)
43 Left (SubschemaNameNotInUseError sname)
43−
44+
src/lib/ProjectM36/Sessions.hs+29−7
@@ -1,18 +1,42 @@
1+{-# LANGUAGE PackageImports #-}
1module ProjectM36.Sessions where
2module ProjectM36.Sessions where
2import Control.Concurrent.STM
3import Control.Concurrent.STM
4+#if MIN_VERSION_stm_containers(1,0,0)
5+import qualified StmContainers.Map as StmMap
6+import qualified StmContainers.Set as StmSet
7+#else
3−import qualified STMContainers.Map as STMMap
8+import qualified STMContainers.Map as StmMap
4−import ListT
9+import qualified STMContainers.Set as StmSet
10+#endif
5import ProjectM36.Attribute
11import ProjectM36.Attribute
6import ProjectM36.Base
12import ProjectM36.Base
7import ProjectM36.Session
13import ProjectM36.Session
8import ProjectM36.Relation
14import ProjectM36.Relation
9import ProjectM36.Error
15import ProjectM36.Error
10import qualified Data.UUID as U
16import qualified Data.UUID as U
17+#if MIN_VERSION_stm_containers(1,0,0)
18+import qualified Control.Foldl as Foldl
19+import qualified DeferredFolds.UnfoldlM as UF
20+#else
21+import "list-t" ListT
22+#endif
11
23
12−type Sessions = STMMap.Map SessionId Session
24+type Sessions = StmMap.Map SessionId Session
13
25
26+--from https://github.com/nikita-volkov/stm-containers/blob/master/test/Main/MapTests.hs
14−stmMapToList :: STMMap.Map k v -> STM [(k, v)]
27+stmMapToList :: StmMap.Map k v -> STM [(k, v)]
28+#if MIN_VERSION_stm_containers(1,0,0)
29+stmMapToList = UF.foldM (Foldl.generalize Foldl.list) . StmMap.unfoldlM
30+#else
31+stmMapToList = ListT.fold (\l -> return . (:l)) [] . StmMap.stream
32+#endif
33+
34+stmSetToList :: StmSet.Set v -> STM [v]
35+#if MIN_VERSION_stm_containers(1,0,0)
36+stmSetToList = UF.foldM (Foldl.generalize Foldl.list) . StmSet.unfoldlM
37+#else
15−stmMapToList = ListT.fold (\l -> return . (:l)) [] . STMMap.stream
38+stmSetToList = ListT.fold (\l -> return . (:l)) [] . StmSet.stream
39+#endif
16
40
17uuidAtom :: U.UUID -> Atom
41uuidAtom :: U.UUID -> Atom
18uuidAtom = TextAtom . U.toText
42uuidAtom = TextAtom . U.toText
@@ -23,5 +47,3 @@ sessionsAsRelation sessions = do
23 let atomMatrix = map (\(sessionId, session) -> [uuidAtom sessionId, uuidAtom (parentId session)]) sessionAssocs
47 let atomMatrix = map (\(sessionId, session) -> [uuidAtom sessionId, uuidAtom (parentId session)]) sessionAssocs
24 pure $ mkRelationFromList (attributesFromList [Attribute "sessionid" TextAtomType,
48 pure $ mkRelationFromList (attributesFromList [Attribute "sessionid" TextAtomType,
25 Attribute "parentCommit" TextAtomType]) atomMatrix
49 Attribute "parentCommit" TextAtomType]) atomMatrix
26−
27−
src/lib/ProjectM36/StaticOptimizer.hs+372−248
@@ -1,287 +1,402 @@
1+{-# LANGUAGE FlexibleInstances #-}
2+{-# LANGUAGE FlexibleContexts #-}
1module ProjectM36.StaticOptimizer where
3module ProjectM36.StaticOptimizer where
2import ProjectM36.Base
4import ProjectM36.Base
3−import ProjectM36.RelationalExpression
5+import ProjectM36.GraphRefRelationalExpr
4import ProjectM36.Relation
6import ProjectM36.Relation
7+import ProjectM36.RelationalExpression
8+import ProjectM36.TransGraphRelationalExpression as TGRE hiding (askGraph)
5import ProjectM36.Error
9import ProjectM36.Error
10+import ProjectM36.Transaction
11+import ProjectM36.NormalizeExpr
6import qualified ProjectM36.Attribute as A
12import qualified ProjectM36.Attribute as A
7import qualified ProjectM36.AttributeNames as AS
13import qualified ProjectM36.AttributeNames as AS
8import ProjectM36.TupleSet
14import ProjectM36.TupleSet
9import Control.Monad.State
15import Control.Monad.State
10−import Data.Either (rights, lefts)
16+import Control.Monad.Reader
17+import Control.Monad.Except
11−import Control.Monad.Trans.Reader
18+import Control.Monad.Trans.Except
19+import Data.Functor.Identity
12import qualified Data.Map as M
20import qualified Data.Map as M
13import qualified Data.Set as S
21import qualified Data.Set as S
14
22
15-- the static optimizer performs optimizations which need not take any specific-relation statistics into account
23-- the static optimizer performs optimizations which need not take any specific-relation statistics into account
16−optimizeRelationalExpr :: DatabaseContext -> RelationalExpr -> Either RelationalError RelationalExpr
24+
17−optimizeRelationalExpr context expr = runReader (optimizeRelationalExprReader expr) (mkRelationalExprState context)
25+--import Debug.Trace
18−
26+
19−optimizeRelationalExprReader :: RelationalExpr -> RelationalExprState (Either RelationalError RelationalExpr)
27+data GraphRefSOptRelationalExprEnv =
20−optimizeRelationalExprReader expr = do
28+ GraphRefSOptRelationalExprEnv
21− eOptExpr <- applyStaticRelationalOptimization expr
29+ {
30+ ore_graph :: TransactionGraph,
31+ ore_mcontext :: Maybe DatabaseContext
32+ }
33+
34+type GraphRefSOptRelationalExprM a = ReaderT GraphRefSOptRelationalExprEnv (ExceptT RelationalError Identity) a
35+
36+data GraphRefSOptDatabaseContextExprEnv =
37+ GraphRefSOptDatabaseContextExprEnv
38+ {
39+ odce_graph :: TransactionGraph,
40+ odce_context :: DatabaseContext, --not optional for DatabaseContextExpr evaluation
41+ odce_transId :: TransactionId -- parent if context is committed- needed because MultipleExpr optimization requires running the DatabaseContextExprs (with empty relvars)
42+ }
43+
44+type GraphRefSOptDatabaseContextExprM a = ReaderT GraphRefSOptDatabaseContextExprEnv (ExceptT RelationalError Identity) a
45+
46+-- | A temporary function to be replaced by IO-based implementation.
47+optimizeAndEvalRelationalExpr :: RelationalExprEnv -> RelationalExpr -> Either RelationalError Relation
48+optimizeAndEvalRelationalExpr env expr = do
49+ 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)
50+ graph = re_graph env
51+ ctx = re_context env
52+ gfEnv = freshGraphRefRelationalExprEnv (Just ctx) graph
53+ optExpr <- runGraphRefSOptRelationalExprM (Just ctx) (re_graph env) (fullOptimizeGraphRefRelationalExpr gfExpr)
54+ runGraphRefRelationalExprM gfEnv (evalGraphRefRelationalExpr optExpr)
55+
56+class Monad m => AskGraphContext m where
57+ askGraph :: m TransactionGraph
58+ askContext :: m DatabaseContext
59+
60+instance AskGraphContext (ReaderT GraphRefSOptDatabaseContextExprEnv (ExceptT RelationalError Identity)) where
61+ askGraph = asks odce_graph
62+ askContext = asks odce_context
63+
64+instance AskGraphContext (ReaderT GraphRefSOptRelationalExprEnv (ExceptT RelationalError Identity)) where
65+ askGraph = asks ore_graph
66+ askContext = do
67+ mctx <- asks ore_mcontext
68+ case mctx of
69+ Nothing -> throwError NoUncommittedContextInEvalError
70+ Just ctx -> pure ctx
71+
72+askTransId :: GraphRefSOptDatabaseContextExprM TransactionId
73+askTransId = asks odce_transId
74+
75+askMaybeContext :: GraphRefSOptRelationalExprM (Maybe DatabaseContext)
76+askMaybeContext = asks ore_mcontext
77+
78+optimizeDatabaseContextExpr :: DatabaseContextExpr -> GraphRefSOptDatabaseContextExprM GraphRefDatabaseContextExpr
79+optimizeDatabaseContextExpr expr = do
80+ let gfExpr = runProcessExprM UncommittedContextMarker (processDatabaseContextExpr expr)
81+ optimizeGraphRefDatabaseContextExpr gfExpr
82+
83+optimizeAndEvalDatabaseContextExpr :: Bool -> DatabaseContextExpr -> DatabaseContextEvalMonad ()
84+optimizeAndEvalDatabaseContextExpr optimize expr = do
85+ graph <- asks dce_graph
86+ transId <- asks dce_transId
87+ context <- getStateContext
88+ let gfExpr = runProcessExprM UncommittedContextMarker (processDatabaseContextExpr expr)
89+ eOptExpr = if optimize then
90+ runGraphRefSOptDatabaseContextExprM transId context graph (optimizeGraphRefDatabaseContextExpr gfExpr)
91+ else
92+ pure gfExpr
93+ case eOptExpr of
94+ Left err -> throwError err
95+ Right optExpr -> evalGraphRefDatabaseContextExpr optExpr
96+
97+
98+optimizeAndEvalTransGraphRelationalExpr :: TransactionGraph -> TransGraphRelationalExpr -> Either RelationalError Relation
99+optimizeAndEvalTransGraphRelationalExpr graph tgExpr = do
100+ gfExpr <- TGRE.process (TransGraphEvalEnv graph) tgExpr
101+ optExpr <- runGraphRefSOptRelationalExprM Nothing graph (fullOptimizeGraphRefRelationalExpr gfExpr)
102+ let gfEnv = freshGraphRefRelationalExprEnv Nothing graph
103+ runGraphRefRelationalExprM gfEnv (evalGraphRefRelationalExpr optExpr)
104+
105+optimizeAndEvalDatabaseContextIOExpr :: DatabaseContextIOExpr -> DatabaseContextIOEvalMonad (Either RelationalError ())
106+optimizeAndEvalDatabaseContextIOExpr expr = do
107+ transId <- asks dbcio_transId
108+ ctx <- getDBCIOContext
109+ graph <- asks dbcio_graph
110+ let gfExpr = runProcessExprM UncommittedContextMarker (processDatabaseContextIOExpr expr)
111+ eOptExpr = runGraphRefSOptDatabaseContextExprM transId ctx graph (optimizeDatabaseContextIOExpr gfExpr)
22 case eOptExpr of
112 case eOptExpr of
23 Left err -> pure (Left err)
113 Left err -> pure (Left err)
24 Right optExpr ->
114 Right optExpr ->
115+ evalGraphRefDatabaseContextIOExpr optExpr
116+
117+{-
118+runStaticOptimizerMonad :: RelationalExprEnv -> StaticOptimizerMonad a -> Either RelationalError a
119+runStaticOptimizerMonad env m = runIdentity (runExceptT (runReaderT m env))
120+-}
121+
122+runGraphRefSOptRelationalExprM ::
123+ Maybe DatabaseContext ->
124+ TransactionGraph ->
125+ GraphRefSOptRelationalExprM a ->
126+ Either RelationalError a
127+runGraphRefSOptRelationalExprM mctx graph m = runIdentity (runExceptT (runReaderT m env))
128+ where
129+ env = GraphRefSOptRelationalExprEnv {
130+ ore_graph = graph,
131+ ore_mcontext = mctx
132+ }
133+
134+
135+runGraphRefSOptDatabaseContextExprM ::
136+ TransactionId ->
137+ DatabaseContext ->
138+ TransactionGraph ->
139+ GraphRefSOptDatabaseContextExprM a ->
140+ Either RelationalError a
141+runGraphRefSOptDatabaseContextExprM tid ctx graph m =
142+ runIdentity (runExceptT (runReaderT m env))
143+ where
144+ env = GraphRefSOptDatabaseContextExprEnv {
145+ odce_graph = graph,
146+ odce_context = ctx,
147+ odce_transId = tid
148+ }
149+
150+optimizeGraphRefRelationalExpr' ::
151+ Maybe DatabaseContext ->
152+ TransactionGraph ->
153+ GraphRefRelationalExpr ->
154+ Either RelationalError GraphRefRelationalExpr
155+optimizeGraphRefRelationalExpr' mctx graph expr =
156+ runIdentity (runExceptT (runReaderT (optimizeGraphRefRelationalExpr expr) env))
157+ where
158+ env = GraphRefSOptRelationalExprEnv {
159+ ore_graph = graph,
160+ ore_mcontext = mctx
161+ }
162+
163+-- | optimize relational expression within database context expr monad
164+liftGraphRefRelExpr :: GraphRefSOptRelationalExprM a -> GraphRefSOptDatabaseContextExprM a
165+liftGraphRefRelExpr m = do
166+ context <- asks odce_context
167+ graph <- asks odce_graph
168+ lift $ except $ runGraphRefSOptRelationalExprM (Just context) graph m
169+
170+fullOptimizeGraphRefRelationalExpr :: GraphRefRelationalExpr -> GraphRefSOptRelationalExprM GraphRefRelationalExpr
171+fullOptimizeGraphRefRelationalExpr expr = do
172+ optExpr <- optimizeGraphRefRelationalExpr expr
25− applyStaticJoinElimination (applyStaticRestrictionPushdown (applyStaticRestrictionCollapse optExpr))
173+ let optExpr' = applyStaticRestrictionPushdown (applyStaticRestrictionCollapse optExpr)
174+ applyStaticJoinElimination optExpr'
26
175
27−optimizeDatabaseContextExpr :: DatabaseContext -> DatabaseContextExpr -> Either RelationalError DatabaseContextExpr
28−optimizeDatabaseContextExpr context dbExpr = evalState (applyStaticDatabaseOptimization dbExpr) (freshDatabaseState context)
29-- apply optimizations which merely remove steps to become no-ops: example: projection of a relation across all of its attributes => original relation
176-- apply optimizations which merely remove steps to become no-ops: example: projection of a relation across all of its attributes => original relation
30
177
31--should optimizations offer the possibility to pure errors? If they perform the up-front type-checking, maybe so
178--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)
179+optimizeGraphRefRelationalExpr :: GraphRefRelationalExpr -> GraphRefSOptRelationalExprM GraphRefRelationalExpr
33−applyStaticRelationalOptimization e@(MakeStaticRelation _ _) = pure $ Right e
180+optimizeGraphRefRelationalExpr e@(MakeStaticRelation _ _) = pure e
34
181
35−applyStaticRelationalOptimization e@(MakeRelationFromExprs _ _) = pure $ Right e
182+optimizeGraphRefRelationalExpr e@(MakeRelationFromExprs _ _) = pure e
36
183
37−applyStaticRelationalOptimization e@(ExistingRelation _) = pure $ Right e
184+optimizeGraphRefRelationalExpr e@(ExistingRelation _) = pure e
38
185
39−applyStaticRelationalOptimization e@(RelationVariable _ _) = pure $ Right e
186+optimizeGraphRefRelationalExpr e@(RelationVariable _ _) = pure e
40
187
41--remove project of attributes which removes no attributes
188--remove project of attributes which removes no attributes
42−applyStaticRelationalOptimization (Project attrNameSet expr) = do
189+optimizeGraphRefRelationalExpr (Project attrNameSet expr) = do
43− relType <- typeForRelationalExpr expr
190+ graph <- askGraph
191+ mctx <- askMaybeContext
192+ let relType = runGraphRefRelationalExprM gfEnv (typeForGraphRefRelationalExpr expr)
193+ gfEnv = freshGraphRefRelationalExprEnv mctx graph
44 case relType of
194 case relType of
45− Left err -> pure $ Left err
195+ Left err -> throwError err
46 Right relType2
196 Right relType2
47− | AS.all == attrNameSet ->
197+ | AS.all == attrNameSet ->
48− applyStaticRelationalOptimization expr
198+ optimizeGraphRefRelationalExpr expr
49 | AttributeNames (attributeNames relType2) == attrNameSet ->
199 | AttributeNames (attributeNames relType2) == attrNameSet ->
50− applyStaticRelationalOptimization expr
200+ optimizeGraphRefRelationalExpr expr
51 | otherwise -> do
201 | otherwise -> do
52− optimizedSubExpression <- applyStaticRelationalOptimization expr
202+ optSubExpr <- optimizeGraphRefRelationalExpr expr
53− case optimizedSubExpression of
54− Left err -> pure $ Left err
55− Right optSubExpr -> pure (Right (Project attrNameSet optSubExpr))
203+ pure (Project attrNameSet optSubExpr)
56
204
57−applyStaticRelationalOptimization (Union exprA exprB) = do
205+optimizeGraphRefRelationalExpr (Union exprA exprB) = do
58− eOptExprA <- applyStaticRelationalOptimization exprA
206+ optExprA <- optimizeGraphRefRelationalExpr exprA
59− eOptExprB <- applyStaticRelationalOptimization exprB
207+ optExprB <- optimizeGraphRefRelationalExpr 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)
208+ -- (x where pred1) union (x where pred2) -> (x where pred1 or pred2)
65− case (optExprA, optExprB) of
209+ case (optExprA, optExprB) of
66− (Restrict predA (RelationVariable nameA ()),
210+ (Restrict predA (RelationVariable nameA sA),
67− Restrict predB (RelationVariable nameB ())) | nameA == nameB -> pure (Right (Restrict (AndPredicate predA predB) (RelationVariable nameA ())))
211+ Restrict predB (RelationVariable nameB sB)) | nameA == nameB && sA == sB -> pure (Restrict (AndPredicate predA predB) (RelationVariable nameA sA))
68 _ -> if optExprA == optExprB then
212 _ -> if optExprA == optExprB then
69− pure (Right optExprA)
213+ pure optExprA
70 else
214 else
71− pure $ Right $ Union optExprA optExprB
215+ pure $ Union optExprA optExprB
72
216
73−applyStaticRelationalOptimization (Join exprA exprB) = do
217+optimizeGraphRefRelationalExpr (Join exprA exprB) = do
74− eOptExprA <- applyStaticRelationalOptimization exprA
218+ optExprA <- optimizeGraphRefRelationalExpr exprA
75− eOptExprB <- applyStaticRelationalOptimization exprB
219+ optExprB <- optimizeGraphRefRelationalExpr 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
220+ -- if the relvars to join are the same but with predicates, then just AndPredicate the predicates
82− case (optExprA, optExprB) of
221+ case (optExprA, optExprB) of
83− (Restrict predA (RelationVariable nameA ()),
222+ (Restrict predA (RelationVariable nameA sA),
84− Restrict predB (RelationVariable nameB ())) | nameA == nameB -> pure (Right (Restrict (AndPredicate predA predB) (RelationVariable nameA ())))
223+ Restrict predB (RelationVariable nameB sB)) | nameA == nameB && sA == sB -> pure (Restrict (AndPredicate predA predB) (RelationVariable nameA sA))
85 _ -> if optExprA == optExprB then --A join A == A
224 _ -> if optExprA == optExprB then --A join A == A
86− pure (Right optExprA)
225+ pure optExprA
87 else
226 else
88− pure (Right (Join optExprA optExprB))
227+ pure (Join optExprA optExprB)
89
228
90−applyStaticRelationalOptimization (Difference exprA exprB) = do
229+optimizeGraphRefRelationalExpr (Difference exprA exprB) = do
91− optExprA <- applyStaticRelationalOptimization exprA
230+ graph <- askGraph
92− optExprB <- applyStaticRelationalOptimization exprB
231+ context <- askMaybeContext
93− case optExprA of
232+ optExprA <- optimizeGraphRefRelationalExpr exprA
94− Left err -> pure $ Left err
233+ optExprB <- optimizeGraphRefRelationalExpr exprB
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
234+ if optExprA == optExprB then do --A difference A == A where false
98− eEmptyRel <- typeForRelationalExpr optExprA2
235+ let eEmptyRel = runGraphRefRelationalExprM gfEnv (typeForGraphRefRelationalExpr optExprA)
236+ gfEnv = freshGraphRefRelationalExprEnv context graph
99− case eEmptyRel of
237+ case eEmptyRel of
100− Left err -> pure (Left err)
238+ Left err -> throwError err
101− Right emptyRel -> pure (Right (ExistingRelation emptyRel))
239+ Right emptyRel -> pure (ExistingRelation emptyRel)
102− else
240+ else
103− pure $ Right (Difference optExprA2 optExprB2)
241+ pure (Difference optExprA optExprB)
104
242
105−applyStaticRelationalOptimization e@Rename{} = pure $ Right e
243+optimizeGraphRefRelationalExpr e@Rename{} = pure e
106
244
107−applyStaticRelationalOptimization (Group oldAttrNames newAttrName expr) =
245+optimizeGraphRefRelationalExpr (Group oldAttrNames newAttrName expr) =
108− pure $ Right $ Group oldAttrNames newAttrName expr
246+ pure $ Group oldAttrNames newAttrName expr
109
247
110−applyStaticRelationalOptimization (Ungroup attrName expr) =
248+optimizeGraphRefRelationalExpr (Ungroup attrName expr) =
111− pure $ Right $ Ungroup attrName expr
249+ pure $ Ungroup attrName expr
112
250
113--remove restriction of nothing
251--remove restriction of nothing
114−applyStaticRelationalOptimization (Restrict predicate expr) = do
252+optimizeGraphRefRelationalExpr (Restrict predicate expr) = do
253+ graph <- askGraph
254+ mctx <- askMaybeContext
115 optimizedPredicate <- applyStaticPredicateOptimization predicate
255 optimizedPredicate <- applyStaticPredicateOptimization predicate
116 case optimizedPredicate of
256 case optimizedPredicate of
117− Left err -> pure $ Left err
257+ optimizedPredicate' | isTrueExpr optimizedPredicate' -> optimizeGraphRefRelationalExpr expr -- remove predicate entirely
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
258+ optimizedPredicate' | isFalseExpr optimizedPredicate' -> do -- replace where false predicate with empty relation with attributes from relexpr
121− attributesRel <- typeForRelationalExpr expr
259+ let attributesRel = runGraphRefRelationalExprM gfEnv (typeForGraphRefRelationalExpr expr)
260+ gfEnv = freshGraphRefRelationalExprEnv mctx graph
122 case attributesRel of
261 case attributesRel of
123− Left err -> pure $ Left err
262+ Left err -> throwError err
124− Right attributesRelA -> pure $ Right $ MakeStaticRelation (attributes attributesRelA) emptyTupleSet
263+ Right attributesRelA -> pure $ MakeStaticRelation (attributes attributesRelA) emptyTupleSet
125 | otherwise -> do
264 | otherwise -> do
126− optimizedSubExpression <- applyStaticRelationalOptimization expr
265+ optSubExpr <- optimizeGraphRefRelationalExpr expr
127− case optimizedSubExpression of
128− Left err -> pure $ Left err
129− Right optSubExpr -> pure $ Right $ Restrict optimizedPredicate2 optSubExpr
266+ pure $ Restrict optimizedPredicate' optSubExpr
130
267
131−applyStaticRelationalOptimization e@(Equals _ _) = pure $ Right e
268+optimizeGraphRefRelationalExpr e@(Equals _ _) = pure e
132
269
133−applyStaticRelationalOptimization e@(NotEquals _ _) = pure $ Right e
270+optimizeGraphRefRelationalExpr e@(NotEquals _ _) = pure e
134
271
135−applyStaticRelationalOptimization e@(Extend _ _) = pure $ Right e
272+optimizeGraphRefRelationalExpr e@(Extend _ _) = pure e
136
273
137−applyStaticDatabaseOptimization :: DatabaseContextExpr -> DatabaseState (Either RelationalError DatabaseContextExpr)
274+optimizeGraphRefRelationalExpr e@(With _ _) = pure e
138−applyStaticDatabaseOptimization x@NoOperation = pure $ Right x
139−applyStaticDatabaseOptimization x@(Define _ _) = pure $ Right x
140
275
141−applyStaticDatabaseOptimization x@(Undefine _) = pure $ Right x
276+-- database context expr
277+optimizeGraphRefDatabaseContextExpr :: GraphRefDatabaseContextExpr -> GraphRefSOptDatabaseContextExprM GraphRefDatabaseContextExpr
278+optimizeGraphRefDatabaseContextExpr x@NoOperation = pure x
279+optimizeGraphRefDatabaseContextExpr x@(Define _ _) = pure x
142
280
143−applyStaticDatabaseOptimization (Assign name expr) = do
281+optimizeGraphRefDatabaseContextExpr x@(Undefine _) = pure x
144− context <- getStateContext
282+
145− let optimizedExpr = optimizeRelationalExpr context expr
283+optimizeGraphRefDatabaseContextExpr (Assign name expr) = do
146− case optimizedExpr of
284+ optExpr <- liftGraphRefRelExpr (fullOptimizeGraphRefRelationalExpr expr)
147− Left err -> pure $ Left err
285+ pure $ Assign name optExpr
148− Right optimizedExpr2 -> pure $ Right (Assign name optimizedExpr2)
149
286
150−applyStaticDatabaseOptimization (Insert targetName expr) = do
287+optimizeGraphRefDatabaseContextExpr (Insert targetName expr) = do
151− context <- getStateContext
288+ optimizedExpr <- liftGraphRefRelExpr (fullOptimizeGraphRefRelationalExpr expr)
152− let optimizedExpr = optimizeRelationalExpr context expr
153− case optimizedExpr of
154− Left err -> pure $ Left err
155− Right optimizedExpr2 -> if isEmptyRelationExpr optimizedExpr2 then -- if we are trying to insert an empty relation, do nothing
289+ if isEmptyRelationExpr optimizedExpr then -- if we are trying to insert an empty relation, do nothing
156− pure (Right NoOperation)
290+ pure NoOperation
157− else
291+ else
158− case optimizedExpr2 of
292+ case optimizedExpr of
159− -- if the target relvar and the insert relvar are the same, there is nothing to do
293+ -- if the target relvar and the insert relvar are the same, there is nothing to do
160− -- insert s s -> NoOperation
294+ -- insert s s -> NoOperation
161− RelationVariable insName () | insName == targetName -> pure (Right NoOperation)
295+ RelationVariable insName _ | insName == targetName -> pure NoOperation
162− _ -> pure $ Right (Insert targetName optimizedExpr2)
296+ _ -> pure (Insert targetName optimizedExpr)
163
297
164−applyStaticDatabaseOptimization (Delete name predicate) = do
298+optimizeGraphRefDatabaseContextExpr (Delete name predicate) =
165− context <- getStateContext
166− let optimizedPredicate = runReader (applyStaticPredicateOptimization predicate) (RelationalExprStateElems context)
299+ Delete name <$> liftGraphRefRelExpr (applyStaticPredicateOptimization predicate)
167− case optimizedPredicate of
168− Left err -> pure $ Left err
169− Right optimizedPredicate2 -> pure $ Right (Delete name optimizedPredicate2)
170
300
171−applyStaticDatabaseOptimization (Update name upmap predicate) = do
301+optimizeGraphRefDatabaseContextExpr (Update name upmap predicate) =
172− context <- getStateContext
173− let optimizedPredicate = runReader (applyStaticPredicateOptimization predicate) (RelationalExprStateElems context)
302+ Update name upmap <$> liftGraphRefRelExpr (applyStaticPredicateOptimization predicate)
174− case optimizedPredicate of
175− Left err -> pure $ Left err
176− Right optimizedPredicate2 -> pure $ Right (Update name upmap optimizedPredicate2)
177
303
178−applyStaticDatabaseOptimization dep@(AddInclusionDependency _ _) = pure $ Right dep
304+optimizeGraphRefDatabaseContextExpr dep@(AddInclusionDependency _ _) = pure dep
179
305
180−applyStaticDatabaseOptimization (RemoveInclusionDependency name) = pure $ Right (RemoveInclusionDependency name)
306+optimizeGraphRefDatabaseContextExpr (RemoveInclusionDependency name) = pure (RemoveInclusionDependency name)
181
307
182−applyStaticDatabaseOptimization (AddNotification name triggerExpr resultOldExpr resultNewExpr) = do
308+optimizeGraphRefDatabaseContextExpr (AddNotification name triggerExpr resultOldExpr resultNewExpr) =
183− context <- getStateContext
309+ --we can't optimize these expressions until they run
184− let eTriggerExprOpt = optimizeRelationalExpr context triggerExpr
185− case eTriggerExprOpt of
186− Left err -> pure $ Left err
187− Right triggerExprOpt -> --it doesn't make sense to optimize queries when we don't have their proper contexts
188− pure (Right (AddNotification name triggerExprOpt resultOldExpr resultNewExpr))
310+ pure (AddNotification name triggerExpr resultOldExpr resultNewExpr)
189
311
190−applyStaticDatabaseOptimization notif@(RemoveNotification _) = pure (Right notif)
312+optimizeGraphRefDatabaseContextExpr notif@(RemoveNotification _) = pure notif
191
313
192−applyStaticDatabaseOptimization c@(AddTypeConstructor _ _) = pure (Right c)
314+optimizeGraphRefDatabaseContextExpr c@(AddTypeConstructor _ _) = pure c
193−applyStaticDatabaseOptimization c@(RemoveTypeConstructor _) = pure (Right c)
315+optimizeGraphRefDatabaseContextExpr c@(RemoveTypeConstructor _) = pure c
194−applyStaticDatabaseOptimization c@(RemoveAtomFunction _) = pure (Right c)
316+optimizeGraphRefDatabaseContextExpr c@(RemoveAtomFunction _) = pure c
195−applyStaticDatabaseOptimization c@(RemoveDatabaseContextFunction _) = pure (Right c)
317+optimizeGraphRefDatabaseContextExpr c@(RemoveDatabaseContextFunction _) = pure c
196−applyStaticDatabaseOptimization c@(ExecuteDatabaseContextFunction _ _) = pure (Right c)
318+optimizeGraphRefDatabaseContextExpr c@(ExecuteDatabaseContextFunction _ _) = pure c
197
319
198--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
320--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
199
321
200--applyStaticDatabaseOptimization (MultipleExpr exprs) = pure $ Right $ MultipleExpr exprs
322--applyStaticDatabaseOptimization (MultipleExpr exprs) = pure $ Right $ MultipleExpr exprs
201--for multiple expressions, we must evaluate
323--for multiple expressions, we must evaluate
202−applyStaticDatabaseOptimization (MultipleExpr exprs) = do
324+optimizeGraphRefDatabaseContextExpr (MultipleExpr exprs) = do
203− context <- getStateContext
204− let optExprs = evalState substateRunner (contextWithEmptyTupleSets context, M.empty, False)
205− let errors = lefts optExprs
206− if not (null errors) then
207− pure $ Left (head errors)
208− else
209− pure $ Right $ MultipleExpr (rights optExprs)
210− where
211− substateRunner = forM exprs $ \expr -> do
212− --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
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
213− _ <- evalDatabaseContextExpr expr
326+ context <- askContext
214− applyStaticDatabaseOptimization expr
327+ graph <- askGraph
215− --this error handling could be improved with some lifting presumably
328+ parentId <- askTransId
216− --restore original context
329+
217−
330+ let emptyRvs ctx = ctx { relationVariables = mkEmptyRelVars (relationVariables ctx) }
218−applyStaticPredicateOptimization :: RestrictionPredicateExpr -> RelationalExprState (Either RelationalError RestrictionPredicateExpr)
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
219applyStaticPredicateOptimization predi = do
346applyStaticPredicateOptimization predi = do
220− eOptPred <- case predi of
347+ optPred <- case predi of
221-- where x and x => where x
348-- where x and x => where x
222 AndPredicate pred1 pred2 -> do
349 AndPredicate pred1 pred2 -> do
223− eOptPred1 <- applyStaticPredicateOptimization pred1
350+ optPredA <- applyStaticPredicateOptimization pred1
224− case eOptPred1 of
225− Left err -> pure (Left err)
226− Right optPred1 -> do
227− eOptPred2 <- applyStaticPredicateOptimization pred2
351+ optPredB <- applyStaticPredicateOptimization pred2
228− case eOptPred2 of
352+ if optPredA == optPredB then
229− Left err -> pure (Left err)
353+ pure optPredA
230− Right optPred2 ->
231− if optPred1 == optPred2 then
232− pure (Right optPred1)
233− else
354+ else
234− pure (Right (AndPredicate optPred1 optPred2))
355+ pure (AndPredicate optPredA optPredB)
235-- where x or x => where x
356-- where x or x => where x
236 OrPredicate pred1 pred2 -> do
357 OrPredicate pred1 pred2 -> do
237− eOptPred1 <- applyStaticPredicateOptimization pred1
358+ optPredA <- applyStaticPredicateOptimization pred1
238− case eOptPred1 of
239− Left err -> pure (Left err)
240− Right optPred1 -> do
241− eOptPred2 <- applyStaticPredicateOptimization pred2
359+ optPredB <- applyStaticPredicateOptimization pred2
242− case eOptPred2 of
360+ if (optPredA == optPredB) || isTrueExpr optPredA then
243− Left err -> pure (Left err)
361+ pure optPredA
244− Right optPred2 | optPred1 == optPred2 -> pure (Right optPred1)
362+ else if isTrueExpr optPredB then
245− | isTrueExpr optPred1 -> pure (Right optPred1) -- True or x -> True
363+ pure optPredB
246− | isTrueExpr optPred2 -> pure (Right optPred2)
364+ else
247− | otherwise -> pure (Right (OrPredicate optPred1 optPred2))
365+ pure (OrPredicate optPredA optPredB)
248 AttributeEqualityPredicate attrNameA (AttributeAtomExpr attrNameB) ->
366 AttributeEqualityPredicate attrNameA (AttributeAtomExpr attrNameB) ->
249 if attrNameA == attrNameB then
367 if attrNameA == attrNameB then
250− pure (Right TruePredicate)
368+ pure TruePredicate
251 else
369 else
252− pure (Right predi)
370+ pure predi
253− AttributeEqualityPredicate{} -> pure (Right predi)
371+ AttributeEqualityPredicate{} -> pure predi
254− TruePredicate -> pure $ Right predi
372+ TruePredicate -> pure predi
255− NotPredicate{} -> pure $ Right predi
373+ NotPredicate{} -> pure predi
256− RelationalExprPredicate{} -> pure (Right predi)
374+ RelationalExprPredicate{} -> pure predi
257− AtomExprPredicate{} -> pure (Right predi)
375+ AtomExprPredicate{} -> pure predi
258− case eOptPred of
259− Left err -> pure (Left err)
260− Right optPred ->
261− let attrMap = findStaticRestrictionPredicates optPred in
376+ let attrMap = findStaticRestrictionPredicates optPred
262− pure (Right (replaceStaticAtomExprs optPred attrMap))
377+ pure (replaceStaticAtomExprs optPred attrMap)
263
378
264--determines if an atom expression is tautologically true
379--determines if an atom expression is tautologically true
265−isTrueExpr :: RestrictionPredicateExpr -> Bool
380+isTrueExpr :: RestrictionPredicateExprBase a -> Bool
266isTrueExpr TruePredicate = True
381isTrueExpr TruePredicate = True
267isTrueExpr (AtomExprPredicate (NakedAtomExpr (BoolAtom True))) = True
382isTrueExpr (AtomExprPredicate (NakedAtomExpr (BoolAtom True))) = True
268isTrueExpr _ = False
383isTrueExpr _ = False
269
384
270--determines if an atom expression is tautologically false
385--determines if an atom expression is tautologically false
271−isFalseExpr :: RestrictionPredicateExpr -> Bool
386+isFalseExpr :: RestrictionPredicateExprBase a -> Bool
272isFalseExpr (NotPredicate expr) = isTrueExpr expr
387isFalseExpr (NotPredicate expr) = isTrueExpr expr
273isFalseExpr (AtomExprPredicate (NakedAtomExpr (BoolAtom False))) = True
388isFalseExpr (AtomExprPredicate (NakedAtomExpr (BoolAtom False))) = True
274isFalseExpr _ = False
389isFalseExpr _ = False
275
390
276-- determine if the created relation can statically be determined to be empty
391-- determine if the created relation can statically be determined to be empty
277−isEmptyRelationExpr :: RelationalExpr -> Bool
392+isEmptyRelationExpr :: RelationalExprBase a -> Bool
278−isEmptyRelationExpr (MakeRelationFromExprs _ []) = True
393+isEmptyRelationExpr (MakeRelationFromExprs _ (TupleExprs _ [])) = True
279isEmptyRelationExpr (MakeStaticRelation _ tupSet) = null (asList tupSet)
394isEmptyRelationExpr (MakeStaticRelation _ tupSet) = null (asList tupSet)
280isEmptyRelationExpr (ExistingRelation rel) = rel == emptyRelationWithAttrs (attributes rel)
395isEmptyRelationExpr (ExistingRelation rel) = rel == emptyRelationWithAttrs (attributes rel)
281isEmptyRelationExpr _ = False
396isEmptyRelationExpr _ = False
282
397
283--transitive static variable optimization
398--transitive static variable optimization
284−replaceStaticAtomExprs :: RestrictionPredicateExpr -> M.Map AttributeName AtomExpr -> RestrictionPredicateExpr
399+replaceStaticAtomExprs :: GraphRefRestrictionPredicateExpr -> M.Map AttributeName GraphRefAtomExpr -> GraphRefRestrictionPredicateExpr
285replaceStaticAtomExprs predIn replaceMap = case predIn of
400replaceStaticAtomExprs predIn replaceMap = case predIn of
286 AttributeEqualityPredicate newAttrName (AttributeAtomExpr matchName) -> case M.lookup matchName replaceMap of
401 AttributeEqualityPredicate newAttrName (AttributeAtomExpr matchName) -> case M.lookup matchName replaceMap of
287 Nothing -> predIn
402 Nothing -> predIn
@@ -294,7 +409,7 @@ replaceStaticAtomExprs predIn replaceMap = case predIn of
294 RelationalExprPredicate{} -> predIn
409 RelationalExprPredicate{} -> predIn
295 AtomExprPredicate{} -> predIn
410 AtomExprPredicate{} -> predIn
296-- 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
411-- 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
297−findStaticRestrictionPredicates :: RestrictionPredicateExpr -> M.Map AttributeName AtomExpr
412+findStaticRestrictionPredicates :: GraphRefRestrictionPredicateExpr -> M.Map AttributeName GraphRefAtomExpr
298findStaticRestrictionPredicates (AttributeEqualityPredicate attrName atomExpr) =
413findStaticRestrictionPredicates (AttributeEqualityPredicate attrName atomExpr) =
299 case atomExpr of
414 case atomExpr of
300 val@NakedAtomExpr{} -> M.singleton attrName val
415 val@NakedAtomExpr{} -> M.singleton attrName val
@@ -318,66 +433,72 @@ isStaticAtomExpr FunctionAtomExpr{} = False
318isStaticAtomExpr RelationAtomExpr{} = False
433isStaticAtomExpr RelationAtomExpr{} = False
319
434
320--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
435--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
321−applyStaticJoinElimination :: RelationalExpr -> RelationalExprState (Either RelationalError RelationalExpr)
436+applyStaticJoinElimination :: GraphRefRelationalExpr -> GraphRefSOptRelationalExprM GraphRefRelationalExpr
322applyStaticJoinElimination expr@(Project attrNameSet (Join exprA exprB)) = do
437applyStaticJoinElimination expr@(Project attrNameSet (Join exprA exprB)) = do
323− relState <- ask
438+ graph <- askGraph
324− eProjType <- typeForRelationalExpr expr
439+ case inSameTransaction exprA exprB of
325− eTypeA <- typeForRelationalExpr exprA
440+ -- the sub exprs are in different transactions or none at all, so we cannot extract inclusion dependencies across transaction boundaries
326− eTypeB <- typeForRelationalExpr exprB
441+ Nothing -> pure expr
327− case eProjType of
442+ Just marker -> do
328− Left err -> pure (Left err)
443+ commonContext <- case marker of
329− Right projType ->
444+ UncommittedContextMarker -> askContext
330− case eTypeA of
445+ TransactionMarker tid -> concreteDatabaseContext <$> lift (except (transactionForId tid graph))
331− Left err -> pure (Left err)
446+ let typeForExpr e = lift $ except $ runGraphRefRelationalExprM gfEnv (typeForGraphRefRelationalExpr e)
332− Right typeA ->
447+ gfEnv = freshGraphRefRelationalExprEnv (Just commonContext) graph
333− case eTypeB of
448+
334− Left err -> pure (Left err)
449+ projType <- typeForExpr expr
335− Right typeB -> do
450+ typeA <- typeForExpr exprA
451+ typeB <- typeForExpr exprB
336− let matchesProjectionAttributes
452+ let matchesProjectionAttributes
337− | attrNames projType `S.isSubsetOf` attrNames typeA =
453+ | attrNames projType `S.isSubsetOf` attrNames typeA =
338− Just ((exprA, typeA), (exprB, typeB))
454+ Just ((exprA, typeA), (exprB, typeB))
339− | attrNames projType `S.isSubsetOf` attrNames typeB =
455+ | attrNames projType `S.isSubsetOf` attrNames typeB =
340− Just ((exprB, typeB), (exprA, typeA))
456+ Just ((exprB, typeB), (exprA, typeA))
341− | otherwise =
457+ | otherwise =
342− Nothing
458+ Nothing
343− attrNames = A.attributeNameSet . attributes
459+ attrNames = A.attributeNameSet . attributes
344− case matchesProjectionAttributes of
460+ case matchesProjectionAttributes of
345− Nothing -> -- this optimization does not apply
461+ Nothing -> -- this optimization does not apply
346− pure (Right expr)
462+ pure expr
347− Just ((joinedExpr, joinedType), (unjoinedExpr, _)) -> do
463+ Just ((joinedExpr, joinedType), (unjoinedExpr, _)) -> do
464+ --lookup transaction
348− --scan inclusion dependencies for a foreign key relationship
465+ --scan inclusion dependencies for a foreign key relationship
349− incDeps <- inclusionDependencies . stateElemsContext <$> ask
466+ let incDeps = inclusionDependencies commonContext
350− let fkConstraint = foldM isFkConstraint False incDeps
467+ fkConstraint = foldM isFkConstraint False incDeps
351− --search for matching fk constraint
468+ --search for matching fk constraint
352− isFkConstraint acc (InclusionDependency (Project subattrNames subrv) (Project _ superrv)) =
469+ isFkConstraint acc (InclusionDependency (Project subAttrNames subrv) (Project _ superrv)) = do
353− case runReader (evalAttributeNames subattrNames expr) relState of
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
354− Left _ -> pure acc
475+ Left _ -> pure acc
355− Right subAttrNameSet ->
476+ Right subAttrNameSet ->
356− pure (acc || (joinedExpr == subrv &&
477+ pure (acc || (joinedExpr == gfSubRv &&
357− unjoinedExpr == superrv &&
478+ unjoinedExpr == gfSuperRv &&
358− -- the fk attribute is one of the projection attributes
479+ -- the fk attribute is one of the projection attributes
359− A.attributeNamesContained subAttrNameSet (A.attributeNameSet (attributes joinedType))
480+ A.attributeNamesContained subAttrNameSet (A.attributeNameSet (attributes joinedType))
360 ))
481 ))
361− isFkConstraint acc _ = pure acc
482+ isFkConstraint acc _ = pure acc
362− case fkConstraint of
483+ case fkConstraint of
363− Right True -> --join elimination optimization applies
484+ Right True -> --join elimination optimization applies
364− applyStaticRelationalOptimization (Project attrNameSet joinedExpr)
485+ optimizeGraphRefRelationalExpr (Project attrNameSet joinedExpr)
365− Right False -> --join elimination optimization does not apply
486+ Right False -> --join elimination optimization does not apply
366− pure (Right expr)
487+ pure expr
367− Left err ->
488+ Left err -> throwError err
368− pure (Left err)
369
489
370−applyStaticJoinElimination expr = pure (Right expr)
490+applyStaticJoinElimination expr = pure expr
371
491
372--restriction collapse converts chained restrictions into (Restrict (And pred1 pred2 pred3...))
492--restriction collapse converts chained restrictions into (Restrict (And pred1 pred2 pred3...))
373 --this optimization should be fairly uncontroversial- performing a tuple scan once is cheaper than twice- parallelization can still take place
493 --this optimization should be fairly uncontroversial- performing a tuple scan once is cheaper than twice- parallelization can still take place
374−applyStaticRestrictionCollapse :: RelationalExpr -> RelationalExpr
494+applyStaticRestrictionCollapse :: GraphRefRelationalExpr -> GraphRefRelationalExpr
375applyStaticRestrictionCollapse expr =
495applyStaticRestrictionCollapse expr =
376 case expr of
496 case expr of
377 MakeRelationFromExprs _ _ -> expr
497 MakeRelationFromExprs _ _ -> expr
378 MakeStaticRelation _ _ -> expr
498 MakeStaticRelation _ _ -> expr
379 ExistingRelation _ -> expr
499 ExistingRelation _ -> expr
380 RelationVariable _ _ -> expr
500 RelationVariable _ _ -> expr
501+ With _ _ -> expr
381 Project attrs subexpr ->
502 Project attrs subexpr ->
382 Project attrs (applyStaticRestrictionCollapse subexpr)
503 Project attrs (applyStaticRestrictionCollapse subexpr)
383 Union sub1 sub2 ->
504 Union sub1 sub2 ->
@@ -407,19 +528,20 @@ applyStaticRestrictionCollapse expr =
407 andPreds = foldr (\(Restrict subpred _) acc -> AndPredicate acc subpred) firstPred (tail restrictions) in
528 andPreds = foldr (\(Restrict subpred _) acc -> AndPredicate acc subpred) firstPred (tail restrictions) in
408 Restrict andPreds optFinalExpr
529 Restrict andPreds optFinalExpr
409
530
410−sequentialRestrictions :: RelationalExpr -> [RelationalExpr]
531+sequentialRestrictions :: RelationalExprBase a -> [RelationalExprBase a]
411sequentialRestrictions expr@(Restrict _ subexpr) = expr:sequentialRestrictions subexpr
532sequentialRestrictions expr@(Restrict _ subexpr) = expr:sequentialRestrictions subexpr
412sequentialRestrictions _ = []
533sequentialRestrictions _ = []
413
534
414--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
535--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
415-- x{proj} where c1 -> (x where c1){proj} #project on fewer tuples
536-- x{proj} where c1 -> (x where c1){proj} #project on fewer tuples
416-- (x union y) where c -> (x where c) union (y where c) #with a selective restriction, fewer tuples will need to be joined
537-- (x union y) where c -> (x where c) union (y where c) #with a selective restriction, fewer tuples will need to be joined
417−applyStaticRestrictionPushdown :: RelationalExpr -> RelationalExpr
538+applyStaticRestrictionPushdown :: GraphRefRelationalExpr -> GraphRefRelationalExpr
418applyStaticRestrictionPushdown expr = case expr of
539applyStaticRestrictionPushdown expr = case expr of
419 MakeRelationFromExprs _ _ -> expr
540 MakeRelationFromExprs _ _ -> expr
420 MakeStaticRelation _ _ -> expr
541 MakeStaticRelation _ _ -> expr
421 ExistingRelation _ -> expr
542 ExistingRelation _ -> expr
422 RelationVariable _ _ -> expr
543 RelationVariable _ _ -> expr
544+ With _ _ -> expr
423 Project _ _ -> expr
545 Project _ _ -> expr
424 --this transformation cannot be inverted because the projection attributes might not exist in the inverted version
546 --this transformation cannot be inverted because the projection attributes might not exist in the inverted version
425 Restrict restrictAttrs (Project projAttrs subexpr) ->
547 Restrict restrictAttrs (Project projAttrs subexpr) ->
@@ -450,4 +572,6 @@ applyStaticRestrictionPushdown expr = case expr of
450 Extend n sub ->
572 Extend n sub ->
451 Extend n (applyStaticRestrictionPushdown sub)
573 Extend n (applyStaticRestrictionPushdown sub)
452
574
453−
575+-- no optimizations available
576+optimizeDatabaseContextIOExpr :: GraphRefDatabaseContextIOExpr -> GraphRefSOptDatabaseContextExprM GraphRefDatabaseContextIOExpr
577+optimizeDatabaseContextIOExpr = pure
src/lib/ProjectM36/TransGraphRelationalExpression.hs+140−118
@@ -1,16 +1,15 @@
1−{-# LANGUAGE TypeSynonymInstances, FlexibleInstances #-}
1+{-# LANGUAGE FlexibleInstances #-}
2{-# OPTIONS_GHC -fno-warn-orphans #-}
2{-# OPTIONS_GHC -fno-warn-orphans #-}
3--really, a better name for this module could be "TransTransactionGraphRelationalExpr", but that name is too long
3--really, a better name for this module could be "TransTransactionGraphRelationalExpr", but that name is too long
4module ProjectM36.TransGraphRelationalExpression where
4module ProjectM36.TransGraphRelationalExpression where
5import ProjectM36.Base
5import ProjectM36.Base
6import ProjectM36.TransactionGraph
6import ProjectM36.TransactionGraph
7−import ProjectM36.Transaction
8−import ProjectM36.RelationalExpression
9import ProjectM36.Error
7import ProjectM36.Error
10−import ProjectM36.Tuple
11−import ProjectM36.AtomType
12import qualified Data.Map as M
8import qualified Data.Map as M
13import Control.Monad.Trans.Reader
9import Control.Monad.Trans.Reader
10+import Control.Monad.Trans.Class
11+import Control.Monad.Trans.Except
12+import Data.Functor.Identity
14import Data.Binary
13import Data.Binary
15
14
16-- | The TransGraphRelationalExpression is equivalent to a relational expression except that relation variables can reference points in the transaction graph (at previous points in time).
15-- | The TransGraphRelationalExpression is equivalent to a relational expression except that relation variables can reference points in the transaction graph (at previous points in time).
@@ -30,6 +29,10 @@ type TransGraphTupleExpr = TupleExprBase TransactionIdLookup
30
29
31instance Binary TransGraphTupleExpr
30instance Binary TransGraphTupleExpr
32
31
32+type TransGraphTupleExprs = TupleExprsBase TransactionIdLookup
33+
34+instance Binary TransGraphTupleExprs
35+
33type TransGraphRestrictionPredicateExpr = RestrictionPredicateExprBase TransactionIdLookup
36type TransGraphRestrictionPredicateExpr = RestrictionPredicateExprBase TransactionIdLookup
34
37
35instance Binary TransGraphRestrictionPredicateExpr
38instance Binary TransGraphRestrictionPredicateExpr
@@ -40,136 +43,155 @@ instance Binary TransGraphAtomExpr
40
43
41type TransGraphAttributeExpr = AttributeExprBase TransactionIdLookup
44type TransGraphAttributeExpr = AttributeExprBase TransactionIdLookup
42
45
46+type TransGraphWithNameExpr = WithNameExprBase TransactionIdLookup
47+
48+instance Binary TransGraphWithNameExpr
49+
50+newtype TransGraphEvalEnv = TransGraphEvalEnv {
51+ tge_graph :: TransactionGraph
52+ }
53+
54+type TransGraphEvalMonad a = ReaderT TransGraphEvalEnv (ExceptT RelationalError Identity) a
55+
56+process :: TransGraphEvalEnv -> TransGraphRelationalExpr -> Either RelationalError GraphRefRelationalExpr
57+process env texpr = runIdentity (runExceptT (runReaderT (processTransGraphRelationalExpr texpr) env))
58+
59+liftE :: Either RelationalError a -> TransGraphEvalMonad a
60+liftE = lift . except
61+
62+askGraph :: TransGraphEvalMonad TransactionGraph
63+askGraph = tge_graph <$> ask
64+
65+findTransId :: TransactionIdLookup -> TransGraphEvalMonad GraphRefTransactionMarker
66+findTransId tlook = TransactionMarker . transactionId <$> findTrans tlook
67+
68+findTrans :: TransactionIdLookup -> TransGraphEvalMonad Transaction
69+findTrans tlook = do
70+ graph <- askGraph
71+ liftE $ lookupTransaction graph tlook
72+
43-- 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.
73-- 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
74+processTransGraphRelationalExpr :: TransGraphRelationalExpr -> TransGraphEvalMonad GraphRefRelationalExpr
45−evalTransGraphRelationalExpr (MakeRelationFromExprs mAttrExprs tupleExprs) graph = do
75+processTransGraphRelationalExpr (MakeRelationFromExprs mAttrExprs tupleExprs) = do
46− tupleExprs' <- mapM (evalTransGraphTupleExpr graph) tupleExprs
76+ tupleExprs' <- processTransGraphTupleExprs tupleExprs
47 case mAttrExprs of
77 case mAttrExprs of
48 Nothing -> pure (MakeRelationFromExprs Nothing tupleExprs')
78 Nothing -> pure (MakeRelationFromExprs Nothing tupleExprs')
49 Just attrExprs -> do
79 Just attrExprs -> do
50− attrExprs' <- mapM (evalTransGraphAttributeExpr graph) attrExprs
80+ attrExprs' <- mapM processTransGraphAttributeExpr attrExprs
51 pure (MakeRelationFromExprs (Just attrExprs') tupleExprs')
81 pure (MakeRelationFromExprs (Just attrExprs') tupleExprs')
52−evalTransGraphRelationalExpr (MakeStaticRelation attrs tupSet) _ = pure (MakeStaticRelation attrs tupSet)
82+processTransGraphRelationalExpr (MakeStaticRelation attrs tupSet) = pure (MakeStaticRelation attrs tupSet)
53−evalTransGraphRelationalExpr (ExistingRelation rel) _ = pure (ExistingRelation rel)
83+processTransGraphRelationalExpr (ExistingRelation rel) = pure (ExistingRelation rel)
54−evalTransGraphRelationalExpr (RelationVariable rvname transLookup) graph = do
84+processTransGraphRelationalExpr (RelationVariable rvname transLookup) =
55− trans <- lookupTransaction graph transLookup
85+ RelationVariable rvname <$> findTransId transLookup
56− rel <- runReader (evalRelationalExpr (RelationVariable rvname ())) (RelationalExprStateElems (concreteDatabaseContext trans))
57− pure (ExistingRelation rel)
58−evalTransGraphRelationalExpr (Project transAttrNames expr) graph = do
86+processTransGraphRelationalExpr (Project transAttrNames expr) =
59− expr' <- evalTransGraphRelationalExpr expr graph
87+ Project <$> processTransGraphAttributeNames transAttrNames <*> processTransGraphRelationalExpr expr
60− attrNames <- evalTransAttributeNames transAttrNames graph
88+processTransGraphRelationalExpr (Union exprA exprB) =
61− pure (Project attrNames expr')
89+ Union <$> processTransGraphRelationalExpr exprA <*> processTransGraphRelationalExpr exprB
62−evalTransGraphRelationalExpr (Union exprA exprB) graph = do
90+processTransGraphRelationalExpr (Join exprA exprB) =
63− exprA' <- evalTransGraphRelationalExpr exprA graph
91+ Join <$> processTransGraphRelationalExpr exprA <*> processTransGraphRelationalExpr exprB
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
92+processTransGraphRelationalExpr (Rename attrName1 attrName2 expr) =
71− let expr' = evalTransGraphRelationalExpr expr graph
72− Rename attrName1 attrName2 <$> expr'
93+ Rename attrName1 attrName2 <$> processTransGraphRelationalExpr expr
73−evalTransGraphRelationalExpr (Difference exprA exprB) graph = do
94+processTransGraphRelationalExpr (Difference exprA exprB) =
74− exprA' <- evalTransGraphRelationalExpr exprA graph
95+ Difference <$> processTransGraphRelationalExpr exprA <*> processTransGraphRelationalExpr exprB
75− exprB' <- evalTransGraphRelationalExpr exprB graph
76− pure (Difference exprA' exprB')
77−evalTransGraphRelationalExpr (Group transAttrNames attrName expr) graph = do
96+processTransGraphRelationalExpr (Group transAttrNames attrName expr) =
78− expr' <- evalTransGraphRelationalExpr expr graph
97+ Group <$>
79− attrNames <- evalTransAttributeNames transAttrNames graph
98+ processTransGraphAttributeNames transAttrNames <*>
80− pure (Group attrNames attrName expr')
99+ pure attrName <*>
81−evalTransGraphRelationalExpr (Ungroup attrName expr) graph = do
100+ processTransGraphRelationalExpr expr
82− let expr' = evalTransGraphRelationalExpr expr graph
101+processTransGraphRelationalExpr (Ungroup attrName expr) =
83− Ungroup attrName <$> expr'
102+ Ungroup attrName <$> processTransGraphRelationalExpr expr
84−evalTransGraphRelationalExpr (Restrict predicateExpr expr) graph = do
103+processTransGraphRelationalExpr (Restrict predicateExpr expr) =
85− expr' <- evalTransGraphRelationalExpr expr graph
86− predicateExpr' <- evalTransGraphRestrictionPredicateExpr predicateExpr graph
104+ Restrict <$> evalTransGraphRestrictionPredicateExpr predicateExpr <*>
87− pure (Restrict predicateExpr' expr')
105+ processTransGraphRelationalExpr expr
88−evalTransGraphRelationalExpr (Equals exprA exprB) graph = do
106+processTransGraphRelationalExpr (Equals exprA exprB) = do
89− exprA' <- evalTransGraphRelationalExpr exprA graph
107+ exprA' <- processTransGraphRelationalExpr exprA
90− exprB' <- evalTransGraphRelationalExpr exprB graph
108+ exprB' <- processTransGraphRelationalExpr exprB
91 pure (Equals exprA' exprB')
109 pure (Equals exprA' exprB')
92−evalTransGraphRelationalExpr (NotEquals exprA exprB) graph = do
110+processTransGraphRelationalExpr (NotEquals exprA exprB) = do
93− exprA' <- evalTransGraphRelationalExpr exprA graph
111+ exprA' <- processTransGraphRelationalExpr exprA
94− exprB' <- evalTransGraphRelationalExpr exprB graph
112+ exprB' <- processTransGraphRelationalExpr exprB
95 pure (NotEquals exprA' exprB')
113 pure (NotEquals exprA' exprB')
96−evalTransGraphRelationalExpr (Extend extendExpr expr) graph = do
114+processTransGraphRelationalExpr (Extend extendExpr expr) = do
97− extendExpr' <- evalTransGraphExtendTupleExpr extendExpr graph
115+ extendExpr' <- processTransGraphExtendTupleExpr extendExpr
98− expr' <- evalTransGraphRelationalExpr expr graph
116+ expr' <- processTransGraphRelationalExpr expr
99 pure (Extend extendExpr' expr')
117 pure (Extend extendExpr' expr')
100−
118+processTransGraphRelationalExpr (With views expr) = do
101−evalTransGraphTupleExpr :: TransactionGraph -> TransGraphTupleExpr -> Either RelationalError TupleExpr
119+ evaldViews <- mapM (\(wnexpr, vexpr) -> do
120+ wnexpr' <- processTransGraphWithNameExpr wnexpr
121+ vexpr' <- processTransGraphRelationalExpr vexpr
122+ pure (wnexpr', vexpr')
123+ ) views
124+ expr' <- processTransGraphRelationalExpr expr
125+ pure (With evaldViews expr')
126+
127+processTransGraphTupleExprs :: TransGraphTupleExprs -> TransGraphEvalMonad GraphRefTupleExprs
128+processTransGraphTupleExprs (TupleExprs marker texprs) =
129+ TupleExprs <$> findTransId marker <*> mapM processTransGraphTupleExpr texprs
130+
131+processTransGraphTupleExpr :: TransGraphTupleExpr -> TransGraphEvalMonad GraphRefTupleExpr
102−evalTransGraphTupleExpr graph (TupleExpr attrMap) = do
132+processTransGraphTupleExpr (TupleExpr attrMap) = do
103 let attrAssoc = mapM (\(attrName, atomExpr) -> do
133 let attrAssoc = mapM (\(attrName, atomExpr) -> do
104− aExpr <- evalTransGraphAtomExpr graph atomExpr
134+ aExpr <- processTransGraphAtomExpr atomExpr
105 pure (attrName, aExpr)
135 pure (attrName, aExpr)
106 ) (M.toList attrMap)
136 ) (M.toList attrMap)
107 TupleExpr . M.fromList <$> attrAssoc
137 TupleExpr . M.fromList <$> attrAssoc
108
138
109−evalTransGraphAtomExpr :: TransactionGraph -> TransGraphAtomExpr -> Either RelationalError AtomExpr
139+processTransGraphAtomExpr :: TransGraphAtomExpr -> TransGraphEvalMonad GraphRefAtomExpr
110−evalTransGraphAtomExpr _ (AttributeAtomExpr aname) = pure $ AttributeAtomExpr aname
140+processTransGraphAtomExpr (AttributeAtomExpr aname) = pure $ AttributeAtomExpr aname
111−evalTransGraphAtomExpr _ (NakedAtomExpr atom) = pure $ NakedAtomExpr atom
141+processTransGraphAtomExpr (NakedAtomExpr atom) = pure $ NakedAtomExpr atom
112−evalTransGraphAtomExpr graph (FunctionAtomExpr funcName args tLookup) = do
142+processTransGraphAtomExpr (FunctionAtomExpr funcName args tLookup) =
113− trans <- lookupTransaction graph tLookup
143+ FunctionAtomExpr funcName <$> mapM processTransGraphAtomExpr args <*> findTransId tLookup
114− --I can't return a FunctionAtomExpr because the function needs to be resolved at a specific context
115− args' <- mapM (evalTransGraphAtomExpr graph) args
116− atom <- runReader (evalAtomExpr emptyTuple (FunctionAtomExpr funcName args' ())) (RelationalExprStateElems (concreteDatabaseContext trans))
117− pure (NakedAtomExpr atom)
118−evalTransGraphAtomExpr graph (RelationAtomExpr expr) = do
144+processTransGraphAtomExpr (RelationAtomExpr expr) =
119− let expr' = evalTransGraphRelationalExpr expr graph
120− RelationAtomExpr <$> expr'
145+ RelationAtomExpr <$> processTransGraphRelationalExpr expr
121−evalTransGraphAtomExpr graph (ConstructedAtomExpr dConsName args tLookup) = do
146+processTransGraphAtomExpr (ConstructedAtomExpr dConsName args tLookup) =
122− trans <- lookupTransaction graph tLookup
147+ ConstructedAtomExpr dConsName <$> mapM processTransGraphAtomExpr args <*> findTransId tLookup
123− args' <- mapM (evalTransGraphAtomExpr graph) args
124− atom <- runReader (evalAtomExpr emptyTuple (ConstructedAtomExpr dConsName args' ())) (RelationalExprStateElems (concreteDatabaseContext trans))
125− pure (NakedAtomExpr atom)
126−
127−evalTransGraphRestrictionPredicateExpr :: TransGraphRestrictionPredicateExpr -> TransactionGraph -> Either RelationalError RestrictionPredicateExpr
148+evalTransGraphRestrictionPredicateExpr :: TransGraphRestrictionPredicateExpr -> TransGraphEvalMonad GraphRefRestrictionPredicateExpr
128−evalTransGraphRestrictionPredicateExpr TruePredicate _ = pure TruePredicate
149+evalTransGraphRestrictionPredicateExpr TruePredicate = pure TruePredicate
129−evalTransGraphRestrictionPredicateExpr (AndPredicate exprA exprB) graph = do
150+evalTransGraphRestrictionPredicateExpr (AndPredicate exprA exprB) = do
130− exprA' <- evalTransGraphRestrictionPredicateExpr exprA graph
151+ exprA' <- evalTransGraphRestrictionPredicateExpr exprA
131− exprB' <- evalTransGraphRestrictionPredicateExpr exprB graph
152+ exprB' <- evalTransGraphRestrictionPredicateExpr exprB
132 pure (AndPredicate exprA' exprB')
153 pure (AndPredicate exprA' exprB')
133−evalTransGraphRestrictionPredicateExpr (OrPredicate exprA exprB) graph = do
154+evalTransGraphRestrictionPredicateExpr (OrPredicate exprA exprB) = do
134− exprA' <- evalTransGraphRestrictionPredicateExpr exprA graph
155+ exprA' <- evalTransGraphRestrictionPredicateExpr exprA
135− exprB' <- evalTransGraphRestrictionPredicateExpr exprB graph
156+ exprB' <- evalTransGraphRestrictionPredicateExpr exprB
136 pure (OrPredicate exprA' exprB')
157 pure (OrPredicate exprA' exprB')
137−evalTransGraphRestrictionPredicateExpr (NotPredicate expr) graph = do
158+evalTransGraphRestrictionPredicateExpr (NotPredicate expr) = do
138− let expr' = evalTransGraphRestrictionPredicateExpr expr graph
159+ let expr' = evalTransGraphRestrictionPredicateExpr expr
139 NotPredicate <$> expr'
160 NotPredicate <$> expr'
140−evalTransGraphRestrictionPredicateExpr (RelationalExprPredicate expr) graph = do
161+evalTransGraphRestrictionPredicateExpr (RelationalExprPredicate expr) = do
141− let expr' = evalTransGraphRelationalExpr expr graph
162+ let expr' = processTransGraphRelationalExpr expr
142 RelationalExprPredicate <$> expr'
163 RelationalExprPredicate <$> expr'
143−evalTransGraphRestrictionPredicateExpr (AtomExprPredicate expr) graph = do
164+evalTransGraphRestrictionPredicateExpr (AtomExprPredicate expr) = do
144− let expr' = evalTransGraphAtomExpr graph expr
165+ let expr' = processTransGraphAtomExpr expr
145 AtomExprPredicate <$> expr'
166 AtomExprPredicate <$> expr'
146−evalTransGraphRestrictionPredicateExpr (AttributeEqualityPredicate attrName expr) graph = do
167+evalTransGraphRestrictionPredicateExpr (AttributeEqualityPredicate attrName expr) = do
147− let expr' = evalTransGraphAtomExpr graph expr
168+ let expr' = processTransGraphAtomExpr expr
148 AttributeEqualityPredicate attrName <$> expr'
169 AttributeEqualityPredicate attrName <$> expr'
149
170
150−evalTransGraphExtendTupleExpr :: TransGraphExtendTupleExpr -> TransactionGraph -> Either RelationalError ExtendTupleExpr
171+processTransGraphExtendTupleExpr :: TransGraphExtendTupleExpr -> TransGraphEvalMonad GraphRefExtendTupleExpr
151−evalTransGraphExtendTupleExpr (AttributeExtendTupleExpr attrName expr) graph = do
172+processTransGraphExtendTupleExpr (AttributeExtendTupleExpr attrName expr) =
152− let expr' = evalTransGraphAtomExpr graph expr
153− AttributeExtendTupleExpr attrName <$> expr'
173+ AttributeExtendTupleExpr attrName <$> processTransGraphAtomExpr expr
154−
174+
155−evalTransGraphAttributeExpr :: TransactionGraph -> TransGraphAttributeExpr -> Either RelationalError AttributeExpr
175+processTransGraphAttributeExpr :: TransGraphAttributeExpr -> TransGraphEvalMonad GraphRefAttributeExpr
156−evalTransGraphAttributeExpr graph (AttributeAndTypeNameExpr attrName tCons tLookup) = do
176+processTransGraphAttributeExpr (AttributeAndTypeNameExpr attrName tCons tLookup) =
157− trans <- lookupTransaction graph tLookup
177+ AttributeAndTypeNameExpr attrName tCons <$> findTransId tLookup
158− aType <- atomTypeForTypeConstructor tCons (typeConstructorMapping (concreteDatabaseContext trans)) M.empty
159− pure (NakedAttributeExpr (Attribute attrName aType))
160−evalTransGraphAttributeExpr _ (NakedAttributeExpr attr) = pure (NakedAttributeExpr attr)
178+processTransGraphAttributeExpr (NakedAttributeExpr attr) = pure (NakedAttributeExpr attr)
161−
179+
162−evalTransAttributeNames :: TransGraphAttributeNames -> TransactionGraph -> Either RelationalError AttributeNames
180+processTransGraphAttributeNames :: TransGraphAttributeNames -> TransGraphEvalMonad GraphRefAttributeNames
163−evalTransAttributeNames (AttributeNames names) _ = Right (AttributeNames names)
181+processTransGraphAttributeNames (AttributeNames names) = pure (AttributeNames names)
164−evalTransAttributeNames (InvertedAttributeNames names) _ = Right (InvertedAttributeNames names)
182+processTransGraphAttributeNames (InvertedAttributeNames names) = pure (InvertedAttributeNames names)
165−evalTransAttributeNames (UnionAttributeNames namesA namesB) graph = do
183+processTransGraphAttributeNames (UnionAttributeNames namesA namesB) = do
166− nA <- evalTransAttributeNames namesA graph
184+ nA <- processTransGraphAttributeNames namesA
167− nB <- evalTransAttributeNames namesB graph
185+ nB <- processTransGraphAttributeNames namesB
168− Right (UnionAttributeNames nA nB)
186+ pure (UnionAttributeNames nA nB)
169−evalTransAttributeNames (IntersectAttributeNames namesA namesB) graph = do
187+processTransGraphAttributeNames (IntersectAttributeNames namesA namesB) = do
170− nA <- evalTransAttributeNames namesA graph
188+ nA <- processTransGraphAttributeNames namesA
171− nB <- evalTransAttributeNames namesB graph
189+ nB <- processTransGraphAttributeNames namesB
172− Right (IntersectAttributeNames nA nB)
190+ pure (IntersectAttributeNames nA nB)
173−evalTransAttributeNames (RelationalExprAttributeNames expr) graph = do
191+processTransGraphAttributeNames (RelationalExprAttributeNames expr) = do
174− evaldExpr <- evalTransGraphRelationalExpr expr graph
192+ evaldExpr <- processTransGraphRelationalExpr expr
175− Right (RelationalExprAttributeNames evaldExpr)
193+ pure (RelationalExprAttributeNames evaldExpr)
194+
195+processTransGraphWithNameExpr :: TransGraphWithNameExpr -> TransGraphEvalMonad GraphRefWithNameExpr
196+processTransGraphWithNameExpr (WithNameExpr rvname tlookup) =
197+ WithNameExpr rvname <$> findTransId tlookup
src/lib/ProjectM36/Transaction.hs+24−16
@@ -3,28 +3,24 @@ import ProjectM36.Base
3import qualified Data.Set as S
3import qualified Data.Set as S
4import qualified Data.UUID as U
4import qualified Data.UUID as U
5import Data.Time.Clock
5import Data.Time.Clock
6+import qualified Data.List.NonEmpty as NE
6
7
7−transactionTimestamp :: Transaction -> UTCTime
8+parentIds :: Transaction -> S.Set TransactionId
8−transactionTimestamp (Transaction _ (TransactionInfo _ _ stamp) _) = stamp
9+parentIds (Transaction _ tinfo _) = S.fromList (NE.toList (parents tinfo))
9−transactionTimestamp (Transaction _ (MergeTransactionInfo _ _ _ stamp) _) = stamp
10
10
11−transactionParentIds :: Transaction -> S.Set TransactionId
11+rootParent :: TransactionParents
12−transactionParentIds (Transaction _ (TransactionInfo pId _ _) _) = S.singleton pId
12+rootParent = singleParent U.nil
13−transactionParentIds (Transaction _ (MergeTransactionInfo pId1 pId2 _ _) _) = S.fromList [pId1, pId2]
14
13
15−transactionChildIds :: Transaction -> S.Set TransactionId
14+singleParent :: TransactionId -> TransactionParents
16−transactionChildIds (Transaction _ (TransactionInfo _ children _) _) = children
15+singleParent tid = tid NE.:| []
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'
23
16
24-- | 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.
17-- | 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.
25filterTransactionInfoTransactions :: S.Set TransactionId -> TransactionInfo -> TransactionInfo
18filterTransactionInfoTransactions :: S.Set TransactionId -> TransactionInfo -> TransactionInfo
26−filterTransactionInfoTransactions filterIds (TransactionInfo parentId childIds stamp) = TransactionInfo (filterParent parentId filterIds) (S.intersection childIds filterIds) stamp
19+filterTransactionInfoTransactions filterIds tinfo =
27−filterTransactionInfoTransactions filterIds (MergeTransactionInfo parentIdA parentIdB childIds stamp) = MergeTransactionInfo (filterParent parentIdA filterIds) (filterParent parentIdB filterIds) (S.intersection childIds filterIds) stamp
20+ tinfo { parents = case
21+ NE.filter (`S.member` filterIds) (parents tinfo) of
22+ [] -> rootParent
23+ xs -> NE.fromList xs}
28
24
29filterParent :: TransactionId -> S.Set TransactionId -> TransactionId
25filterParent :: TransactionId -> S.Set TransactionId -> TransactionId
30filterParent parentId validIds = if S.member parentId validIds then parentId else U.nil
26filterParent parentId validIds = if S.member parentId validIds then parentId else U.nil
@@ -44,3 +40,15 @@ schemas (Transaction _ _ schemas') = schemas'
44-- | Returns all subschemas which are isomorphic or sub-isomorphic to the concrete schema.
40-- | Returns all subschemas which are isomorphic or sub-isomorphic to the concrete schema.
45subschemas :: Transaction -> Subschemas
41subschemas :: Transaction -> Subschemas
46subschemas (Transaction _ _ (Schemas _ sschemas)) = sschemas
42subschemas (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+48−40
@@ -1,3 +1,4 @@
1+{-# LANGUAGE TypeApplications #-}
1module ProjectM36.Transaction.Persist where
2module ProjectM36.Transaction.Persist where
2import ProjectM36.Base
3import ProjectM36.Base
3import ProjectM36.Error
4import ProjectM36.Error
@@ -8,19 +9,18 @@ import ProjectM36.Persist (writeBSFileSync, DiskSync, renameSync)
8import qualified Data.Map as M
9import qualified Data.Map as M
9import qualified Data.HashSet as HS
10import qualified Data.HashSet as HS
10import qualified Data.Binary as B
11import qualified Data.Binary as B
11−--import qualified Data.ByteString as BS
12import System.FilePath
12import System.FilePath
13import System.Directory
13import System.Directory
14import qualified Data.Text as T
14import qualified Data.Text as T
15import Control.Monad
15import Control.Monad
16import ProjectM36.ScriptSession
16import ProjectM36.ScriptSession
17import ProjectM36.AtomFunctions.Basic (precompiledAtomFunctions)
17import ProjectM36.AtomFunctions.Basic (precompiledAtomFunctions)
18−import Control.Exception
18+
19+#ifdef PM36_HASKELL_SCRIPTING
19import GHC
20import GHC
21+import Control.Exception
20import GHC.Paths
22import GHC.Paths
21−import Codec.Compression.GZip
23+#endif
22−import qualified Data.ByteString as BS
23−import qualified Data.ByteString.Lazy as BSL
24
24
25getDirectoryNames :: FilePath -> IO [FilePath]
25getDirectoryNames :: FilePath -> IO [FilePath]
26getDirectoryNames path =
26getDirectoryNames path =
@@ -36,8 +36,8 @@ transactionDir dbdir transId = dbdir </> show transId
36transactionInfoPath :: FilePath -> FilePath
36transactionInfoPath :: FilePath -> FilePath
37transactionInfoPath transdir = transdir </> "info"
37transactionInfoPath transdir = transdir </> "info"
38
38
39−relvarsDir :: FilePath -> FilePath
39+relvarsPath :: FilePath -> FilePath
40−relvarsDir transdir = transdir </> "relvars"
40+relvarsPath transdir = transdir </> "relvars"
41
41
42incDepsDir :: FilePath -> FilePath
42incDepsDir :: FilePath -> FilePath
43incDepsDir transdir = transdir </> "incdeps"
43incDepsDir transdir = transdir </> "incdeps"
@@ -85,7 +85,7 @@ writeTransaction sync dbdir trans = do
85 transDirExists <- doesDirectoryExist finalTransDir
85 transDirExists <- doesDirectoryExist finalTransDir
86 unless transDirExists $ do
86 unless transDirExists $ do
87 --create sub directories
87 --create sub directories
88− mapM_ createDirectory [tempTransDir, relvarsDir tempTransDir, incDepsDir tempTransDir, dbcFuncsDir tempTransDir]
88+ mapM_ createDirectory [tempTransDir, incDepsDir tempTransDir, dbcFuncsDir tempTransDir]
89 writeRelVars sync tempTransDir (relationVariables context)
89 writeRelVars sync tempTransDir (relationVariables context)
90 writeIncDeps sync tempTransDir (inclusionDependencies context)
90 writeIncDeps sync tempTransDir (inclusionDependencies context)
91 writeAtomFuncs sync tempTransDir (atomFunctions context)
91 writeAtomFuncs sync tempTransDir (atomFunctions context)
@@ -95,24 +95,15 @@ writeTransaction sync dbdir trans = do
95 B.encodeFile (transactionInfoPath tempTransDir) (transactionInfo trans)
95 B.encodeFile (transactionInfoPath tempTransDir) (transactionInfo trans)
96 --move the temp directory to final location
96 --move the temp directory to final location
97 renameSync sync tempTransDir finalTransDir
97 renameSync sync tempTransDir finalTransDir
98− pure ()
99−
100−writeRelVar :: DiskSync -> FilePath -> (RelVarName, Relation) -> IO ()
101−writeRelVar sync transDir (relvarName, rel) = do
102− let relvarPath = relvarsDir transDir </> T.unpack relvarName
103− writeBSFileSync sync relvarPath (compress (B.encode rel))
104−
105−writeRelVars :: DiskSync -> FilePath -> M.Map RelVarName Relation -> IO ()
106−writeRelVars sync transDir relvars = mapM_ (writeRelVar sync transDir) $ M.toList relvars
107
98
108−readRelVars :: FilePath -> IO (M.Map RelVarName Relation)
99+writeRelVars :: DiskSync -> FilePath -> RelationVariables -> IO ()
109−readRelVars transDir = do
100+writeRelVars sync transDir relvars = do
110− let relvarsPath = relvarsDir transDir
101+ let path = relvarsPath transDir
111− relvarNames <- getDirectoryNames relvarsPath
102+ writeBSFileSync sync path (B.encode relvars)
112− let relvars = mapM (\name -> do
103+
113− rel <- B.decode . decompress . BSL.fromStrict <$> BS.readFile (relvarsPath </> name)
104+readRelVars :: FilePath -> IO RelationVariables
114− return (T.pack name, rel)) relvarNames
105+readRelVars transDir =
115− M.fromList <$> relvars
106+ B.decodeFile (relvarsPath transDir)
116
107
117writeAtomFuncs :: DiskSync -> FilePath -> AtomFunctions -> IO ()
108writeAtomFuncs :: DiskSync -> FilePath -> AtomFunctions -> IO ()
118writeAtomFuncs sync transDir funcs = do
109writeAtomFuncs sync transDir funcs = do
@@ -129,33 +120,40 @@ readAtomFuncs transDir mScriptSession = do
129 pure (HS.union precompiledAtomFunctions (HS.fromList funcs))
120 pure (HS.union precompiledAtomFunctions (HS.fromList funcs))
130
121
131loadAtomFunc :: AtomFunctions -> Maybe ScriptSession -> AtomFunctionName -> [AtomType] -> Maybe AtomFunctionBodyScript -> IO AtomFunction
122loadAtomFunc :: AtomFunctions -> Maybe ScriptSession -> AtomFunctionName -> [AtomType] -> Maybe AtomFunctionBodyScript -> IO AtomFunction
132−loadAtomFunc precompiledFuncs mScriptSession funcName funcType mFuncScript = case mFuncScript of
123+loadAtomFunc precompiledFuncs _mScriptSession funcName _funcType mFuncScript = case mFuncScript of
133 --handle pre-compiled case- pull it from the precompiled list
124 --handle pre-compiled case- pull it from the precompiled list
134 Nothing -> case atomFunctionForName funcName precompiledFuncs of
125 Nothing -> case atomFunctionForName funcName precompiledFuncs of
135 --WARNING: possible landmine here if we remove a precompiled atom function in the future, then the transaction cannot be restored
126 --WARNING: possible landmine here if we remove a precompiled atom function in the future, then the transaction cannot be restored
136 Left _ -> error ("expected precompiled atom function: " ++ T.unpack funcName)
127 Left _ -> error ("expected precompiled atom function: " ++ T.unpack funcName)
137 Right realFunc -> pure realFunc
128 Right realFunc -> pure realFunc
138 --handle a real Haskell scripted function- compile and load
129 --handle a real Haskell scripted function- compile and load
139− Just funcScript ->
130+ Just _funcScript ->
140− case mScriptSession of
131+#ifdef PM36_HASKELL_SCRIPTING
132+ case _mScriptSession of
141 Nothing -> error "attempted to read serialized AtomFunction without scripting enabled"
133 Nothing -> error "attempted to read serialized AtomFunction without scripting enabled"
142 Just scriptSession -> do
134 Just scriptSession -> do
143 --risk of GHC exception during compilation here
135 --risk of GHC exception during compilation here
144 eCompiledScript <- runGhc (Just libdir) $ do
136 eCompiledScript <- runGhc (Just libdir) $ do
145 setSession (hscEnv scriptSession)
137 setSession (hscEnv scriptSession)
146− compileScript (atomFunctionBodyType scriptSession) funcScript
138+ compileScript (atomFunctionBodyType scriptSession) _funcScript
147 case eCompiledScript of
139 case eCompiledScript of
148 Left err -> throwIO err
140 Left err -> throwIO err
149 Right compiledScript -> pure AtomFunction { atomFuncName = funcName,
141 Right compiledScript -> pure AtomFunction { atomFuncName = funcName,
150− atomFuncType = funcType,
142+ atomFuncType = _funcType,
151− atomFuncBody = AtomFunctionBody (Just funcScript) compiledScript }
143+ atomFuncBody = AtomFunctionBody (Just _funcScript) compiledScript }
144+#else
145+ error "Haskell scripting is disabled"
146+#endif
152
147
153--if the script session is enabled, compile the script, otherwise, hard error!
148--if the script session is enabled, compile the script, otherwise, hard error!
154
149
155readAtomFunc :: FilePath -> AtomFunctionName -> Maybe ScriptSession -> AtomFunctions -> IO AtomFunction
150readAtomFunc :: FilePath -> AtomFunctionName -> Maybe ScriptSession -> AtomFunctions -> IO AtomFunction
151+#if !defined(PM36_HASKELL_SCRIPTING)
152+readAtomFunc _ _ _ _ = error "Haskell scripting is disabled"
153+#else
156readAtomFunc transDir funcName mScriptSession precompiledFuncs = do
154readAtomFunc transDir funcName mScriptSession precompiledFuncs = do
157 let atomFuncPath = atomFuncsPath transDir
155 let atomFuncPath = atomFuncsPath transDir
158− (funcType, mFuncScript) <- B.decodeFile atomFuncPath
156+ (funcType, mFuncScript) <- B.decodeFile @([AtomType],Maybe T.Text) atomFuncPath
159 case mFuncScript of
157 case mFuncScript of
160 --handle pre-compiled case- pull it from the precompiled list
158 --handle pre-compiled case- pull it from the precompiled list
161 Nothing -> case atomFunctionForName funcName precompiledFuncs of
159 Nothing -> case atomFunctionForName funcName precompiledFuncs of
@@ -163,7 +161,8 @@ readAtomFunc transDir funcName mScriptSession precompiledFuncs = do
163 Left _ -> error ("expected precompiled atom function: " ++ T.unpack funcName)
161 Left _ -> error ("expected precompiled atom function: " ++ T.unpack funcName)
164 Right realFunc -> pure realFunc
162 Right realFunc -> pure realFunc
165 --handle a real Haskell scripted function- compile and load
163 --handle a real Haskell scripted function- compile and load
166− Just funcScript ->
164+ Just funcScript ->
165+
167 case mScriptSession of
166 case mScriptSession of
168 Nothing -> error "attempted to read serialized AtomFunction without scripting enabled"
167 Nothing -> error "attempted to read serialized AtomFunction without scripting enabled"
169 Just scriptSession -> do
168 Just scriptSession -> do
@@ -176,6 +175,7 @@ readAtomFunc transDir funcName mScriptSession precompiledFuncs = do
176 Right compiledScript -> pure AtomFunction { atomFuncName = funcName,
175 Right compiledScript -> pure AtomFunction { atomFuncName = funcName,
177 atomFuncType = funcType,
176 atomFuncType = funcType,
178 atomFuncBody = AtomFunctionBody (Just funcScript) compiledScript }
177 atomFuncBody = AtomFunctionBody (Just funcScript) compiledScript }
178+#endif
179
179
180
180
181writeDBCFuncs :: DiskSync -> FilePath -> DatabaseContextFunctions -> IO ()
181writeDBCFuncs :: DiskSync -> FilePath -> DatabaseContextFunctions -> IO ()
@@ -194,26 +194,34 @@ readDBCFuncs transDir mScriptSession = do
194 let funcs = mapM ((\name -> readDBCFunc transDir name mScriptSession precompiledDatabaseContextFunctions) . T.pack) funcNames
194 let funcs = mapM ((\name -> readDBCFunc transDir name mScriptSession precompiledDatabaseContextFunctions) . T.pack) funcNames
195 HS.union basicDatabaseContextFunctions . HS.fromList <$> funcs
195 HS.union basicDatabaseContextFunctions . HS.fromList <$> funcs
196
196
197−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
198readDBCFunc transDir funcName mScriptSession precompiledFuncs = do
201readDBCFunc transDir funcName mScriptSession precompiledFuncs = do
202+#endif
199 let dbcFuncPath = dbcFuncsDir transDir </> T.unpack funcName
203 let dbcFuncPath = dbcFuncsDir transDir </> T.unpack funcName
200− (funcType, mFuncScript) <- B.decodeFile dbcFuncPath
204+ (_funcType, mFuncScript) <- B.decodeFile @([AtomType], Maybe T.Text) dbcFuncPath
201 case mFuncScript of
205 case mFuncScript of
202 Nothing -> case databaseContextFunctionForName funcName precompiledFuncs of
206 Nothing -> case databaseContextFunctionForName funcName precompiledFuncs of
203 Left _ -> error ("expected precompiled dbc function: " ++ T.unpack funcName)
207 Left _ -> error ("expected precompiled dbc function: " ++ T.unpack funcName)
204 Right realFunc -> pure realFunc --return precompiled function
208 Right realFunc -> pure realFunc --return precompiled function
205− Just funcScript ->
209+ Just _funcScript ->
210+#ifdef PM36_HASKELL_SCRIPTING
206 case mScriptSession of
211 case mScriptSession of
207 Nothing -> error "attempted to read serialized AtomFunction without scripting enabled"
212 Nothing -> error "attempted to read serialized AtomFunction without scripting enabled"
208 Just scriptSession -> do
213 Just scriptSession -> do
209 eCompiledScript <- runGhc (Just libdir) $ do
214 eCompiledScript <- runGhc (Just libdir) $ do
210 setSession (hscEnv scriptSession)
215 setSession (hscEnv scriptSession)
211− compileScript (dbcFunctionBodyType scriptSession) funcScript
216+ compileScript (dbcFunctionBodyType scriptSession) _funcScript
212 case eCompiledScript of
217 case eCompiledScript of
213 Left err -> throwIO err
218 Left err -> throwIO err
214 Right compiledScript -> pure DatabaseContextFunction { dbcFuncName = funcName,
219 Right compiledScript -> pure DatabaseContextFunction { dbcFuncName = funcName,
215− dbcFuncType = funcType,
220+ dbcFuncType = _funcType,
216− dbcFuncBody = DatabaseContextFunctionBody (Just funcScript) compiledScript}
221+ dbcFuncBody = DatabaseContextFunctionBody (Just _funcScript) compiledScript}
222+#else
223+ error "Haskell scripting is disabled"
224+#endif
217
225
218writeIncDep :: DiskSync -> FilePath -> (IncDepName, InclusionDependency) -> IO ()
226writeIncDep :: DiskSync -> FilePath -> (IncDepName, InclusionDependency) -> IO ()
219writeIncDep sync transDir (incDepName, incDep) =
227writeIncDep sync transDir (incDepName, incDep) =
@@ -253,4 +261,4 @@ readTypeConstructorMapping path = do
253 let atPath = typeConsPath path
261 let atPath = typeConsPath path
254 B.decodeFile atPath
262 B.decodeFile atPath
255
263
256−
264+
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+233−145
@@ -1,35 +1,39 @@
1−{-# LANGUAGE DeriveAnyClass, DeriveGeneric #-}
1+{-# LANGUAGE DeriveAnyClass, DeriveGeneric, CPP, FlexibleContexts #-}
2module ProjectM36.TransactionGraph where
2module ProjectM36.TransactionGraph where
3import ProjectM36.Base
3import ProjectM36.Base
4import ProjectM36.Error
4import ProjectM36.Error
5import ProjectM36.Transaction
5import ProjectM36.Transaction
6+import ProjectM36.TransactionInfo as TI
6import ProjectM36.Relation
7import ProjectM36.Relation
7import ProjectM36.TupleSet
8import ProjectM36.TupleSet
8import ProjectM36.Tuple
9import ProjectM36.Tuple
9import ProjectM36.RelationalExpression
10import ProjectM36.RelationalExpression
10import ProjectM36.TransactionGraph.Merge
11import ProjectM36.TransactionGraph.Merge
12+import ProjectM36.MerkleHash
11import qualified ProjectM36.DisconnectedTransaction as Discon
13import qualified ProjectM36.DisconnectedTransaction as Discon
14+import qualified ProjectM36.Attribute as A
12
15
16+import Control.Monad.Except hiding (join)
17+import Control.Monad.Reader hiding (join)
13import qualified Data.Vector as V
18import qualified Data.Vector as V
14−import qualified ProjectM36.Attribute as A
15import qualified Data.UUID as U
19import qualified Data.UUID as U
16import qualified Data.Set as S
20import qualified Data.Set as S
17import qualified Data.Map as M
21import qualified Data.Map as M
18−import Control.Monad
22+import qualified Data.List.NonEmpty as NE
19import Data.Time.Clock
23import Data.Time.Clock
20import qualified Data.Text as T
24import qualified Data.Text as T
21import GHC.Generics
25import GHC.Generics
22−import Data.Binary
26+import Data.Binary as B
23import Data.Either (lefts, rights, isRight)
27import Data.Either (lefts, rights, isRight)
28+#if __GLASGOW_HASKELL__ < 804
24import Data.Monoid
29import Data.Monoid
30+#endif
25import Control.Arrow
31import Control.Arrow
26import Data.Maybe
32import Data.Maybe
27−
33+import Data.UUID.V4
28−{-
34+import qualified Data.ByteString.Lazy as BL
29−--import Debug.Trace
35+import ProjectM36.DatabaseContext as DBC
30−import Control.Monad.Reader
36+import Crypto.Hash.SHA256
31−import qualified ProjectM36.DisconnectedTransaction as D
32−-}
33
37
34-- | Record a lookup for a specific transaction in the graph.
38-- | Record a lookup for a specific transaction in the graph.
35data TransactionIdLookup = TransactionIdLookup TransactionId |
39data TransactionIdLookup = TransactionIdLookup TransactionId |
@@ -58,16 +62,25 @@ isCommit :: TransactionGraphOperator -> Bool
58isCommit Commit = True
62isCommit Commit = True
59isCommit _ = False
63isCommit _ = False
60
64
61−data ROTransactionGraphOperator = ShowGraph
65+data ROTransactionGraphOperator = ShowGraph | ValidateMerkleHashes
62 deriving Show
66 deriving Show
63
67
64bootstrapTransactionGraph :: UTCTime -> TransactionId -> DatabaseContext -> TransactionGraph
68bootstrapTransactionGraph :: UTCTime -> TransactionId -> DatabaseContext -> TransactionGraph
65−bootstrapTransactionGraph stamp freshId context = TransactionGraph bootstrapHeads bootstrapTransactions
69+bootstrapTransactionGraph stamp' freshId context = TransactionGraph bootstrapHeads bootstrapTransactions
66 where
70 where
67 bootstrapHeads = M.singleton "master" freshTransaction
71 bootstrapHeads = M.singleton "master" freshTransaction
68 newSchemas = Schemas context M.empty
72 newSchemas = Schemas context M.empty
69− freshTransaction = Transaction freshId (TransactionInfo U.nil S.empty stamp) newSchemas
73+ freshTransaction = fresh freshId stamp' newSchemas
74+ hashedTransaction = Transaction freshId ((transactionInfo freshTransaction) { merkleHash = calculateMerkleHash freshTransaction emptyTransactionGraph }) newSchemas
70− bootstrapTransactions = S.singleton freshTransaction
75+ bootstrapTransactions = S.singleton hashedTransaction
76+
77+-- | Create a transaction graph from a context.
78+freshTransactionGraph :: DatabaseContext -> IO (TransactionGraph, TransactionId)
79+freshTransactionGraph ctx = do
80+ now <- getCurrentTime
81+ freshId <- nextRandom
82+ pure (bootstrapTransactionGraph now freshId ctx, freshId)
83+
71
84
72emptyTransactionGraph :: TransactionGraph
85emptyTransactionGraph :: TransactionGraph
73emptyTransactionGraph = TransactionGraph M.empty S.empty
86emptyTransactionGraph = TransactionGraph M.empty S.empty
@@ -86,75 +99,79 @@ headNameForTransaction transaction (TransactionGraph heads _) = if M.null matchi
86 where
99 where
87 matchingTrans = M.filter (transaction ==) heads
100 matchingTrans = M.filter (transaction ==) heads
88
101
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−
100transactionsForIds :: S.Set TransactionId -> TransactionGraph -> Either RelationalError (S.Set Transaction)
102transactionsForIds :: S.Set TransactionId -> TransactionGraph -> Either RelationalError (S.Set Transaction)
101transactionsForIds idSet graph =
103transactionsForIds idSet graph =
102 S.fromList <$> forM (S.toList idSet) (`transactionForId` graph)
104 S.fromList <$> forM (S.toList idSet) (`transactionForId` graph)
103
105
106+-- | A root transaction terminates a graph and has no parents.
104−isRootTransaction :: Transaction -> TransactionGraph -> Bool
107+isRootTransaction :: Transaction -> Bool
105−isRootTransaction (Transaction _ (TransactionInfo pId _ _) _) _ = U.null pId
108+isRootTransaction trans = parentIds trans == S.singleton U.nil
106−isRootTransaction (Transaction _ MergeTransactionInfo{} _) _ = False
109+
110+rootTransactions :: TransactionGraph -> S.Set Transaction
111+rootTransactions graph = S.filter isRootTransaction (transactionsForGraph graph)
107
112
108-- the first transaction has no parent - all other do have parents- merges have two parents
113-- the first transaction has no parent - all other do have parents- merges have two parents
109parentTransactions :: Transaction -> TransactionGraph -> Either RelationalError (S.Set Transaction)
114parentTransactions :: Transaction -> TransactionGraph -> Either RelationalError (S.Set Transaction)
110−parentTransactions (Transaction _ (TransactionInfo pId _ _) _) graph =
115+parentTransactions trans = transactionsForIds (parentIds trans)
111− S.singleton <$> transactionForId pId graph
112−
113−
114−parentTransactions (Transaction _ (MergeTransactionInfo pId1 pId2 _ _) _ ) graph = transactionsForIds (S.fromList [pId1, pId2]) graph
115−
116
116
117childTransactions :: Transaction -> TransactionGraph -> Either RelationalError (S.Set Transaction)
117childTransactions :: Transaction -> TransactionGraph -> Either RelationalError (S.Set Transaction)
118−childTransactions (Transaction _ (TransactionInfo _ children _) _) = transactionsForIds children
118+childTransactions trans graph = transactionsForIds childIds graph
119−childTransactions (Transaction _ (MergeTransactionInfo _ _ children _) _) = transactionsForIds children
119+ where
120+ childIds = S.map transactionId (S.filter filt (transactionsForGraph graph))
121+ filt trans' = S.member (transactionId trans) (parentIds trans')
120
122
121-- create a new commit and add it to the heads
123-- create a new commit and add it to the heads
122-- 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)
124-- 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)
123addBranch :: UTCTime -> TransactionId -> HeadName -> TransactionId -> TransactionGraph -> Either RelationalError (Transaction, TransactionGraph)
125addBranch :: UTCTime -> TransactionId -> HeadName -> TransactionId -> TransactionGraph -> Either RelationalError (Transaction, TransactionGraph)
124−addBranch stamp newId newBranchName branchPointId graph = do
126+addBranch stamp' newId newBranchName branchPointId graph = do
125 parentTrans <- transactionForId branchPointId graph
127 parentTrans <- transactionForId branchPointId graph
126− let newTrans = Transaction newId (TransactionInfo branchPointId S.empty stamp) (schemas parentTrans)
128+ let newTrans = Transaction newId (TI.singleParent branchPointId stamp') (schemas parentTrans)
127 addTransactionToGraph newBranchName newTrans graph
129 addTransactionToGraph newBranchName newTrans graph
128
130
129--adds a disconnected transaction to a transaction graph at some head
131--adds a disconnected transaction to a transaction graph at some head
130addDisconnectedTransaction :: UTCTime -> TransactionId -> HeadName -> DisconnectedTransaction -> TransactionGraph -> Either RelationalError (Transaction, TransactionGraph)
132addDisconnectedTransaction :: 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')
133+addDisconnectedTransaction stamp' newId headName (DisconnectedTransaction parentId schemas' _) graph = addTransactionToGraph headName newTrans' graph
132−
134+ where
133−
135+ newTrans = Transaction newId newTInfo schemas'
136+ newTInfo = TI.singleParent parentId stamp'
137+ newTrans' = Transaction newId (newTInfo { merkleHash = newHash }) schemas'
138+ newHash = calculateMerkleHash newTrans graph--lookup parents in graph to calculate
139+--LOOP
134addTransactionToGraph :: HeadName -> Transaction -> TransactionGraph -> Either RelationalError (Transaction, TransactionGraph)
140addTransactionToGraph :: HeadName -> Transaction -> TransactionGraph -> Either RelationalError (Transaction, TransactionGraph)
135addTransactionToGraph headName newTrans graph = do
141addTransactionToGraph headName newTrans graph = do
136− let parentIds = transactionParentIds newTrans
142+ let parentIds' = parentIds newTrans
137− childIds = transactionChildIds newTrans
138 newId = transactionId newTrans
143 newId = transactionId newTrans
139 validateIds ids = mapM (`transactionForId` graph) (S.toList ids)
144 validateIds ids = mapM (`transactionForId` graph) (S.toList ids)
140− addChildTransaction trans = transactionSetChildren trans (S.insert newId (transactionChildIds trans))
145+ childTs <- childTransactions newTrans graph
141 --validate that the parent transactions are in the graph
146 --validate that the parent transactions are in the graph
142− _ <- validateIds parentIds
147+ _ <- validateIds parentIds'
143− when (S.size parentIds < 1) (Left $ NewTransactionMissingParentError newId)
148+ when (S.size parentIds' < 1) (Left $ NewTransactionMissingParentError newId)
144 --if the headName already exists, ensure that it refers to a parent
149 --if the headName already exists, ensure that it refers to a parent
145 case transactionForHead headName graph of
150 case transactionForHead headName graph of
146 Nothing -> pure () -- any headName is OK
151 Nothing -> pure () -- any headName is OK
147− Just trans -> when (S.notMember (transactionId trans) parentIds) (Left (HeadNameSwitchingHeadProhibitedError headName))
152+ Just trans -> when (S.notMember (transactionId trans) parentIds') (Left (HeadNameSwitchingHeadProhibitedError headName))
148 --validate that the transaction has no children
153 --validate that the transaction has no children
149− unless (S.null childIds) (Left $ NewTransactionMayNotHaveChildrenError newId)
154+ unless (S.null childTs) (Left $ NewTransactionMayNotHaveChildrenError newId)
150 --validate that the trasaction's id is unique
155 --validate that the trasaction's id is unique
151 when (isRight (transactionForId newId graph)) (Left (TransactionIdInUseError newId))
156 when (isRight (transactionForId newId graph)) (Left (TransactionIdInUseError newId))
152− --update the parent transactions to point to the new transaction
157+ --replace all references to UncommittedTransactionMarker to new transaction id
153− parents <- mapM (`transactionForId` graph) (S.toList parentIds)
158+ let newTrans' = newTransUncommittedReplace newTrans
154− let updatedParents = S.map addChildTransaction (S.fromList parents)
155− updatedTransSet = S.insert newTrans (S.union updatedParents (transactionsForGraph graph))
159+ updatedTransSet = S.insert newTrans' (transactionsForGraph graph)
156− updatedHeads = M.insert headName newTrans (transactionHeadsForGraph graph)
160+ updatedHeads = M.insert headName newTrans' (transactionHeadsForGraph graph)
157− pure (newTrans, TransactionGraph updatedHeads updatedTransSet)
161+ pure (newTrans', TransactionGraph updatedHeads updatedTransSet)
162+
163+--replace all occurrences of the uncommitted context marker
164+newTransUncommittedReplace :: Transaction -> Transaction
165+newTransUncommittedReplace trans@(Transaction tid tinfo (Schemas ctx sschemas)) =
166+ Transaction tid tinfo (Schemas fixedContext sschemas)
167+ where
168+ uncommittedReplace UncommittedContextMarker = TransactionMarker tid
169+ uncommittedReplace marker = marker
170+ relvars = relationVariables (concreteDatabaseContext trans)
171+ fixedRelvars = M.map (fmap uncommittedReplace) relvars
172+ fixedContext = ctx { relationVariables = fixedRelvars }
173+
174+
158
175
159validateGraph :: TransactionGraph -> Maybe [RelationalError]
176validateGraph :: TransactionGraph -> Maybe [RelationalError]
160validateGraph graph@(TransactionGraph _ transSet) = do
177validateGraph graph@(TransactionGraph _ transSet) = do
@@ -226,7 +243,7 @@ evalGraphOp _ _ discon graph (WalkBackToTime backTime) = do
226 case transactionForId jumpDest graph of
243 case transactionForId jumpDest graph of
227 Left err -> Left err
244 Left err -> Left err
228 Right trans -> do
245 Right trans -> do
229− let disconnectedTrans = DisconnectedTransaction (transactionId trans) (schemas trans) False
246+ let disconnectedTrans = Discon.freshTransaction (transactionId trans) (schemas trans)
230 Right (disconnectedTrans, graph)
247 Right (disconnectedTrans, graph)
231
248
232-- add new head pointing to branchPoint
249-- add new head pointing to branchPoint
@@ -244,15 +261,15 @@ evalGraphOp newId discon@(DisconnectedTransaction parentId disconContext) graph
244
261
245-- create a new commit and add it to the heads
262-- create a new commit and add it to the heads
246-- 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)
263-- 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
264+evalGraphOp stamp' newId (DisconnectedTransaction parentId schemas' _) graph (Branch newBranchName) = do
248− let newDiscon = DisconnectedTransaction newId schemas' False
265+ let newDiscon = Discon.freshTransaction newId schemas'
249− case addBranch stamp newId newBranchName parentId graph of
266+ case addBranch stamp' newId newBranchName parentId graph of
250 Left err -> Left err
267 Left err -> Left err
251 Right (_, newGraph) -> Right (newDiscon, newGraph)
268 Right (_, newGraph) -> Right (newDiscon, newGraph)
252
269
253-- add the disconnected transaction to the graph
270-- add the disconnected transaction to the graph
254-- affects graph and disconnectedtransaction- the new disconnectedtransaction's parent is the freshly committed transaction
271-- 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
272+evalGraphOp stamp' newTransId discon@(DisconnectedTransaction parentId schemas' _) graph Commit = case transactionForId parentId graph of
256 Left err -> Left err
273 Left err -> Left err
257 Right parentTransaction -> case headNameForTransaction parentTransaction graph of
274 Right parentTransaction -> case headNameForTransaction parentTransaction graph of
258 Nothing -> Left $ TransactionIsNotAHeadError parentId
275 Nothing -> Left $ TransactionIsNotAHeadError parentId
@@ -260,17 +277,20 @@ evalGraphOp stamp newTransId discon@(DisconnectedTransaction parentId schemas' _
260 Left err-> Left err
277 Left err-> Left err
261 Right (_, updatedGraph) -> Right (newDisconnectedTrans, updatedGraph)
278 Right (_, updatedGraph) -> Right (newDisconnectedTrans, updatedGraph)
262 where
279 where
263− newDisconnectedTrans = DisconnectedTransaction newTransId schemas' False
280+ newDisconnectedTrans = Discon.freshTransaction newTransId schemas'
264− maybeUpdatedGraph = addDisconnectedTransaction stamp newTransId headName discon graph
281+ maybeUpdatedGraph = addDisconnectedTransaction stamp' newTransId headName discon graph
265
282
266-- refresh the disconnected transaction, return the same graph
283-- refresh the disconnected transaction, return the same graph
267evalGraphOp _ _ (DisconnectedTransaction parentId _ _) graph Rollback = case transactionForId parentId graph of
284evalGraphOp _ _ (DisconnectedTransaction parentId _ _) graph Rollback = case transactionForId parentId graph of
268 Left err -> Left err
285 Left err -> Left err
269 Right parentTransaction -> Right (newDiscon, graph)
286 Right parentTransaction -> Right (newDiscon, graph)
270 where
287 where
271− newDiscon = DisconnectedTransaction parentId (schemas parentTransaction) False
288+ newDiscon = Discon.freshTransaction parentId (schemas parentTransaction)
272
289
273−evalGraphOp stamp newId (DisconnectedTransaction parentId _ _) graph (MergeTransactions mergeStrategy headNameA headNameB) = mergeTransactions stamp newId parentId mergeStrategy (headNameA, headNameB) graph
290+evalGraphOp stamp' newId (DisconnectedTransaction parentId _ _) graph (MergeTransactions mergeStrategy headNameA headNameB) =
291+ runGraphRefRelationalExprM env $ mergeTransactions stamp' newId parentId mergeStrategy (headNameA, headNameB)
292+ where
293+ env = freshGraphRefRelationalExprEnv Nothing graph
274
294
275evalGraphOp _ _ discon graph@(TransactionGraph graphHeads transSet) (DeleteBranch branchName) = case transactionForHead branchName graph of
295evalGraphOp _ _ discon graph@(TransactionGraph graphHeads transSet) (DeleteBranch branchName) = case transactionForHead branchName graph of
276 Nothing -> Left (NoSuchHeadNameError branchName)
296 Nothing -> Left (NoSuchHeadNameError branchName)
@@ -283,6 +303,7 @@ graphAsRelation (DisconnectedTransaction parentId _ _) graph@(TransactionGraph _
283 mkRelationFromList attrs tupleMatrix
303 mkRelationFromList attrs tupleMatrix
284 where
304 where
285 attrs = A.attributesFromList [Attribute "id" TextAtomType,
305 attrs = A.attributesFromList [Attribute "id" TextAtomType,
306+ Attribute "hash" ByteStringAtomType,
286 Attribute "stamp" DateTimeAtomType,
307 Attribute "stamp" DateTimeAtomType,
287 Attribute "parents" (RelationAtomType parentAttributes),
308 Attribute "parents" (RelationAtomType parentAttributes),
288 Attribute "current" BoolAtomType,
309 Attribute "current" BoolAtomType,
@@ -292,7 +313,8 @@ graphAsRelation (DisconnectedTransaction parentId _ _) graph@(TransactionGraph _
292 tupleGenerator transaction = case transactionParentsRelation transaction graph of
313 tupleGenerator transaction = case transactionParentsRelation transaction graph of
293 Left err -> Left err
314 Left err -> Left err
294 Right parentTransRel -> Right [TextAtom $ T.pack $ show (transactionId transaction),
315 Right parentTransRel -> Right [TextAtom $ T.pack $ show (transactionId transaction),
316+ ByteStringAtom $ _unMerkleHash (merkleHash (transactionInfo transaction)),
295− DateTimeAtom (transactionTimestamp transaction),
317+ DateTimeAtom (timestamp transaction),
296 RelationAtom parentTransRel,
318 RelationAtom parentTransRel,
297 BoolAtom $ parentId == transactionId transaction,
319 BoolAtom $ parentId == transactionId transaction,
298 TextAtom $ fromMaybe "" (headNameForTransaction transaction graph)
320 TextAtom $ fromMaybe "" (headNameForTransaction transaction graph)
@@ -300,7 +322,7 @@ graphAsRelation (DisconnectedTransaction parentId _ _) graph@(TransactionGraph _
300
322
301transactionParentsRelation :: Transaction -> TransactionGraph -> Either RelationalError Relation
323transactionParentsRelation :: Transaction -> TransactionGraph -> Either RelationalError Relation
302transactionParentsRelation trans graph =
324transactionParentsRelation trans graph =
303− if isRootTransaction trans graph then
325+ if isRootTransaction trans then
304 mkRelation attrs emptyTupleSet
326 mkRelation attrs emptyTupleSet
305 else do
327 else do
306 parentTransSet <- parentTransactions trans graph
328 parentTransSet <- parentTransactions trans graph
@@ -319,39 +341,47 @@ evalROGraphOp discon graph ShowGraph = do
319-}
341-}
320
342
321-- | Execute the merge strategy against the transactions, returning a new transaction which can be then added to the transaction graph
343-- | 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
344+createMergeTransaction :: UTCTime -> TransactionId -> MergeStrategy -> (Transaction, Transaction) -> GraphRefRelationalExprM Transaction
323−createMergeTransaction stamp newId (SelectedBranchMergeStrategy selectedBranch) graph t2@(trans1, trans2) = do
345+createMergeTransaction stamp' newId (SelectedBranchMergeStrategy selectedBranch) t2@(trans1, trans2) = do
346+ graph <- gfGraph
324− let selectedTrans = validateHeadName selectedBranch graph t2
347+ selectedTrans <- validateHeadName selectedBranch graph t2
325− Transaction newId (MergeTransactionInfo (transactionId trans1) (transactionId trans2) S.empty stamp) . schemas <$> selectedTrans
348+ pure $ addMerkleHash graph $
349+ Transaction newId (TransactionInfo {
350+ parents = NE.fromList [transactionId trans1,
351+ transactionId trans2],
352+ stamp = stamp',
353+ merkleHash = mempty }) (schemas selectedTrans)
326
354
327-- merge functions, relvars, individually
355-- merge functions, relvars, individually
328−createMergeTransaction stamp newId strat@UnionMergeStrategy graph t2 = createUnionMergeTransaction stamp newId strat graph t2
356+createMergeTransaction stamp' newId strat@UnionMergeStrategy t2 =
357+ createUnionMergeTransaction stamp' newId strat t2
329
358
330-- merge function, relvars, but, on error, just take the component from the preferred branch
359-- 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
360+createMergeTransaction stamp' newId strat@(UnionPreferMergeStrategy _) t2 =
361+ createUnionMergeTransaction stamp' newId strat t2
332
362
333-- | 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.
363-- | 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
364+validateHeadName :: HeadName -> TransactionGraph -> (Transaction, Transaction) -> GraphRefRelationalExprM Transaction
335validateHeadName headName graph (t1, t2) =
365validateHeadName headName graph (t1, t2) =
336 case transactionForHead headName graph of
366 case transactionForHead headName graph of
337− Nothing -> Left SelectedHeadMismatchMergeError
367+ Nothing -> throwError (MergeTransactionError SelectedHeadMismatchMergeError)
338 Just trans -> if trans /= t1 && trans /= t2 then
368 Just trans -> if trans /= t1 && trans /= t2 then
339− Left SelectedHeadMismatchMergeError
369+ throwError (MergeTransactionError SelectedHeadMismatchMergeError)
340 else
370 else
341− Right trans
371+ pure trans
342
372
343-- 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.
373-- 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.
344subGraphOfFirstCommonAncestor :: TransactionGraph -> TransactionHeads -> Transaction -> Transaction -> S.Set Transaction -> Either RelationalError TransactionGraph
374subGraphOfFirstCommonAncestor :: TransactionGraph -> TransactionHeads -> Transaction -> Transaction -> S.Set Transaction -> Either RelationalError TransactionGraph
345−subGraphOfFirstCommonAncestor origGraph resultHeads currentTrans goalTrans traverseSet = do
375+subGraphOfFirstCommonAncestor origGraph resultHeads currentTrans' goalTrans traverseSet = do
346− let currentid = transactionId currentTrans
376+ let currentid = transactionId currentTrans'
347 goalid = transactionId goalTrans
377 goalid = transactionId goalTrans
348− if currentTrans == goalTrans then
378+ if currentTrans' == goalTrans then
349 Right (TransactionGraph resultHeads traverseSet) -- add filter
379 Right (TransactionGraph resultHeads traverseSet) -- add filter
350 --catch root transaction to improve error?
380 --catch root transaction to improve error?
351 else do
381 else do
352− currentTransChildren <- S.fromList <$> mapM (`transactionForId` origGraph) (S.toList (transactionChildIds currentTrans))
382+ currentTransChildren <- childTransactions currentTrans' origGraph
353− let searchChildren = S.difference (S.insert currentTrans traverseSet) currentTransChildren
383+ let searchChildren = S.difference (S.insert currentTrans' traverseSet) currentTransChildren
354− searchChild start = pathToTransaction origGraph start goalTrans (S.insert currentTrans traverseSet)
384+ searchChild start = pathToTransaction origGraph start goalTrans (S.insert currentTrans' traverseSet)
355 childSearches = map searchChild (S.toList searchChildren)
385 childSearches = map searchChild (S.toList searchChildren)
356 errors = lefts childSearches
386 errors = lefts childSearches
357 pathsFound = rights childSearches
387 pathsFound = rights childSearches
@@ -360,17 +390,16 @@ subGraphOfFirstCommonAncestor origGraph resultHeads currentTrans goalTrans trave
360 unless (null realErrors) (Left (head realErrors))
390 unless (null realErrors) (Left (head realErrors))
361 -- if no paths found, search the parent
391 -- if no paths found, search the parent
362 if null pathsFound then
392 if null pathsFound then
363− case oneParent currentTrans of
393+ case oneParent currentTrans' of
364 Left RootTransactionTraversalError -> Left (NoCommonTransactionAncestorError currentid goalid)
394 Left RootTransactionTraversalError -> Left (NoCommonTransactionAncestorError currentid goalid)
365 Left err -> Left err
395 Left err -> Left err
366 Right currentTransParent ->
396 Right currentTransParent ->
367− subGraphOfFirstCommonAncestor origGraph resultHeads currentTransParent goalTrans (S.insert currentTrans traverseSet)
397+ subGraphOfFirstCommonAncestor origGraph resultHeads currentTransParent goalTrans (S.insert currentTrans' traverseSet)
368 else -- we found a path
398 else -- we found a path
369 Right (TransactionGraph resultHeads (S.unions (traverseSet : pathsFound)))
399 Right (TransactionGraph resultHeads (S.unions (traverseSet : pathsFound)))
370 where
400 where
371− oneParent (Transaction _ (TransactionInfo parentId _ _) _) = transactionForId parentId origGraph
401+ oneParent (Transaction _ tinfo _) = transactionForId (NE.head (parents tinfo)) origGraph
372− oneParent (Transaction _ (MergeTransactionInfo parentId _ _ _) _) = transactionForId parentId origGraph
402+
373−
374-- | Search from a past graph point to all following heads for a specific transaction. If found, return the transaction path, otherwise a RelationalError.
403-- | Search from a past graph point to all following heads for a specific transaction. If found, return the transaction path, otherwise a RelationalError.
375pathToTransaction :: TransactionGraph -> Transaction -> Transaction -> S.Set Transaction -> Either RelationalError (S.Set Transaction)
404pathToTransaction :: TransactionGraph -> Transaction -> Transaction -> S.Set Transaction -> Either RelationalError (S.Set Transaction)
376pathToTransaction graph currentTransaction targetTransaction accumTransSet = do
405pathToTransaction graph currentTransaction targetTransaction accumTransSet = do
@@ -378,11 +407,11 @@ pathToTransaction graph currentTransaction targetTransaction accumTransSet = do
378 if transactionId targetTransaction == transactionId currentTransaction then
407 if transactionId targetTransaction == transactionId currentTransaction then
379 Right accumTransSet
408 Right accumTransSet
380 else do
409 else do
381− currentTransChildren <- mapM (`transactionForId` graph) (S.toList (transactionChildIds currentTransaction))
410+ currentTransChildren <- childTransactions currentTransaction graph
382 if null currentTransChildren then
411 if null currentTransChildren then
383 Left (FailedToFindTransactionError targetId)
412 Left (FailedToFindTransactionError targetId)
384 else do
413 else do
385− let searches = map (\t -> pathToTransaction graph t targetTransaction (S.insert t accumTransSet)) currentTransChildren
414+ let searches = map (\t -> pathToTransaction graph t targetTransaction (S.insert t accumTransSet)) (S.toList currentTransChildren)
386 let realErrors = filter (/= FailedToFindTransactionError targetId) (lefts searches)
415 let realErrors = filter (/= FailedToFindTransactionError targetId) (lefts searches)
387 paths = rights searches
416 paths = rights searches
388 if not (null realErrors) then -- found some real errors
417 if not (null realErrors) then -- found some real errors
@@ -392,35 +421,39 @@ pathToTransaction graph currentTransaction targetTransaction accumTransSet = do
392 else --we have some paths!
421 else --we have some paths!
393 Right (S.unions paths)
422 Right (S.unions paths)
394
423
395−mergeTransactions :: UTCTime -> TransactionId -> TransactionId -> MergeStrategy -> (HeadName, HeadName) -> TransactionGraph -> Either RelationalError (DisconnectedTransaction, TransactionGraph)
424+mergeTransactions :: UTCTime -> TransactionId -> TransactionId -> MergeStrategy -> (HeadName, HeadName) -> GraphRefRelationalExprM (DisconnectedTransaction, TransactionGraph)
396−mergeTransactions stamp newId parentId mergeStrategy (headNameA, headNameB) graph = do
425+mergeTransactions stamp' newId parentId mergeStrategy (headNameA, headNameB) = do
426+ graph <- gfGraph
397 let transactionForHeadErr name = case transactionForHead name graph of
427 let transactionForHeadErr name = case transactionForHead name graph of
398− Nothing -> Left (NoSuchHeadNameError name)
428+ Nothing -> throwError (NoSuchHeadNameError name)
399− Just t -> Right t
429+ Just t -> pure t
430+ runE e = case e of
431+ Left e' -> throwError e'
432+ Right v -> pure v
400− transA <- transactionForHeadErr headNameA
433+ transA <- transactionForHeadErr headNameA
401− transB <- transactionForHeadErr headNameB
434+ transB <- transactionForHeadErr headNameB
402− disconParent <- transactionForId parentId graph
435+ disconParent <- gfTransForId parentId
403− let subHeads = M.filterWithKey (\k _ -> elem k [headNameA, headNameB]) (transactionHeadsForGraph graph)
436+ let subHeads = M.filterWithKey (\k _ -> k `elem` [headNameA, headNameB]) (transactionHeadsForGraph graph)
404− subGraph <- subGraphOfFirstCommonAncestor graph subHeads transA transB S.empty
437+ subGraph <- runE $ subGraphOfFirstCommonAncestor graph subHeads transA transB S.empty
405− subGraph' <- filterSubGraph subGraph subHeads
438+ subGraph' <- runE $ filterSubGraph subGraph subHeads
406− case createMergeTransaction stamp newId mergeStrategy subGraph' (transA, transB) of
439+ mergedTrans <- local (const (freshGraphRefRelationalExprEnv Nothing subGraph')) $ createMergeTransaction stamp' newId mergeStrategy (transA, transB)
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
440+ case headNameForTransaction disconParent graph of
411− Nothing -> Left (TransactionIsNotAHeadError parentId)
441+ Nothing -> throwError (TransactionIsNotAHeadError parentId)
412 Just headName -> do
442 Just headName -> do
413− (newTrans, newGraph) <- addTransactionToGraph headName mergedTrans graph
443+ (newTrans, newGraph) <- runE $ addTransactionToGraph headName mergedTrans graph
444+ case checkConstraints (concreteDatabaseContext mergedTrans) newId graph of
445+ Left err -> throwError err
446+ Right _ -> do
414− let newGraph' = TransactionGraph (transactionHeadsForGraph newGraph) (transactionsForGraph newGraph)
447+ let newGraph' = TransactionGraph (transactionHeadsForGraph newGraph) (transactionsForGraph newGraph)
415− newDiscon = DisconnectedTransaction newId (schemas newTrans) False
448+ newDiscon = Discon.freshTransaction newId (schemas newTrans)
416− pure (newDiscon, newGraph')
449+ pure (newDiscon, newGraph')
417
450
418--TEMPORARY COPY/PASTE
451--TEMPORARY COPY/PASTE
419showTransactionStructureX :: Transaction -> TransactionGraph -> String
452showTransactionStructureX :: Transaction -> TransactionGraph -> String
420showTransactionStructureX trans graph = headInfo ++ " " ++ show (transactionId trans) ++ " " ++ parentTransactionsInfo
453showTransactionStructureX trans graph = headInfo ++ " " ++ show (transactionId trans) ++ " " ++ parentTransactionsInfo
421 where
454 where
422 headInfo = maybe "" show (headNameForTransaction trans graph)
455 headInfo = maybe "" show (headNameForTransaction trans graph)
423− parentTransactionsInfo = if isRootTransaction trans graph then "root" else case parentTransactions trans graph of
456+ parentTransactionsInfo = if isRootTransaction trans then "root" else case parentTransactions trans graph of
424 Left err -> show err
457 Left err -> show err
425 Right parentTransSet -> concat $ S.toList $ S.map (show . transactionId) parentTransSet
458 Right parentTransSet -> concat $ S.toList $ S.map (show . transactionId) parentTransSet
426
459
@@ -439,25 +472,29 @@ filterSubGraph graph heads = Right $ TransactionGraph newHeads newTransSet
439 newHeads = M.map (filterTransaction validIds) heads
472 newHeads = M.map (filterTransaction validIds) heads
440
473
441--helper function for commonalities in union merge
474--helper function for commonalities in union merge
442−createUnionMergeTransaction :: UTCTime -> TransactionId -> MergeStrategy -> TransactionGraph -> (Transaction, Transaction) -> Either MergeError Transaction
475+createUnionMergeTransaction :: UTCTime -> TransactionId -> MergeStrategy -> (Transaction, Transaction) -> GraphRefRelationalExprM Transaction
443−createUnionMergeTransaction stamp newId strategy graph (t1,t2) = do
476+createUnionMergeTransaction stamp' newId strategy (t1,t2) = do
444 let contextA = concreteDatabaseContext t1
477 let contextA = concreteDatabaseContext t1
445 contextB = concreteDatabaseContext t2
478 contextB = concreteDatabaseContext t2
446−
479+ liftMergeE x = case x of
480+ Left e -> throwError (MergeTransactionError e)
481+ Right t -> pure t
482+
483+ graph <- gfGraph
447 preference <- case strategy of
484 preference <- case strategy of
448 UnionMergeStrategy -> pure PreferNeither
485 UnionMergeStrategy -> pure PreferNeither
449 UnionPreferMergeStrategy preferBranch ->
486 UnionPreferMergeStrategy preferBranch ->
450 case transactionForHead preferBranch graph of
487 case transactionForHead preferBranch graph of
451− Nothing -> Left (PreferredHeadMissingMergeError preferBranch)
488+ Nothing -> throwError (MergeTransactionError (PreferredHeadMissingMergeError preferBranch))
452 Just preferredTrans -> pure $ if t1 == preferredTrans then PreferFirst else PreferSecond
489 Just preferredTrans -> pure $ if t1 == preferredTrans then PreferFirst else PreferSecond
453− badStrat -> Left (InvalidMergeStrategyError badStrat)
490+ badStrat -> throwError (MergeTransactionError (InvalidMergeStrategyError badStrat))
454
491
455− incDeps <- unionMergeMaps preference (inclusionDependencies contextA) (inclusionDependencies contextB)
492+ incDeps <- liftMergeE $ unionMergeMaps preference (inclusionDependencies contextA) (inclusionDependencies contextB)
456 relVars <- unionMergeRelVars preference (relationVariables contextA) (relationVariables contextB)
493 relVars <- unionMergeRelVars preference (relationVariables contextA) (relationVariables contextB)
457− atomFuncs <- unionMergeAtomFunctions preference (atomFunctions contextA) (atomFunctions contextB)
494+ atomFuncs <- liftMergeE $ unionMergeAtomFunctions preference (atomFunctions contextA) (atomFunctions contextB)
458− notifs <- unionMergeMaps preference (notifications contextA) (notifications contextB)
495+ notifs <- liftMergeE $ unionMergeMaps preference (notifications contextA) (notifications contextB)
459− types <- unionMergeTypeConstructorMapping preference (typeConstructorMapping contextA) (typeConstructorMapping contextB)
496+ types <- liftMergeE $ unionMergeTypeConstructorMapping preference (typeConstructorMapping contextA) (typeConstructorMapping contextB)
460− dbcFuncs <- unionMergeDatabaseContextFunctions preference (dbcFunctions contextA) (dbcFunctions contextB)
497+ dbcFuncs <- liftMergeE $ unionMergeDatabaseContextFunctions preference (dbcFunctions contextA) (dbcFunctions contextB)
461 -- TODO: add merge of subschemas
498 -- TODO: add merge of subschemas
462 let newContext = DatabaseContext {
499 let newContext = DatabaseContext {
463 inclusionDependencies = incDeps,
500 inclusionDependencies = incDeps,
@@ -468,7 +505,12 @@ createUnionMergeTransaction stamp newId strategy graph (t1,t2) = do
468 typeConstructorMapping = types
505 typeConstructorMapping = types
469 }
506 }
470 newSchemas = Schemas newContext (subschemas t1)
507 newSchemas = Schemas newContext (subschemas t1)
471− pure (Transaction newId (MergeTransactionInfo (transactionId t1) (transactionId t2) S.empty stamp) newSchemas)
508+ pure $ addMerkleHash graph $
509+ Transaction newId (TransactionInfo {
510+ parents = NE.fromList [transactionId t1,
511+ transactionId t2],
512+ stamp = stamp',
513+ merkleHash = mempty }) newSchemas
472
514
473lookupTransaction :: TransactionGraph -> TransactionIdLookup -> Either RelationalError Transaction
515lookupTransaction :: TransactionGraph -> TransactionIdLookup -> Either RelationalError Transaction
474lookupTransaction graph (TransactionIdLookup tid) = transactionForId tid graph
516lookupTransaction graph (TransactionIdLookup tid) = transactionForId tid graph
@@ -485,56 +527,57 @@ backtrackGraph :: TransactionGraph -> TransactionId -> TransactionIdHeadBacktrac
485-- tilde, step back one parent link- if a choice must be made, choose the "first" link arbitrarily
527-- tilde, step back one parent link- if a choice must be made, choose the "first" link arbitrarily
486backtrackGraph graph currentTid (TransactionIdHeadParentBacktrack steps) = do
528backtrackGraph graph currentTid (TransactionIdHeadParentBacktrack steps) = do
487 trans <- transactionForId currentTid graph
529 trans <- transactionForId currentTid graph
530+
488− let parents = S.toAscList (transactionParentIds trans)
531+ let parentIds' = S.toAscList (parentIds trans)
489− if length parents < 1 then
532+ case parentIds' of
490− Left RootTransactionTraversalError
533+ [] -> Left RootTransactionTraversalError
491− else do
534+ firstParentId:_ -> do
492− parentTrans <- transactionForId (head parents) graph
535+ parentTrans <- transactionForId firstParentId graph
493− if steps == 1 then
536+ if steps == 1 then
494− pure (transactionId parentTrans)
537+ pure (transactionId parentTrans)
495− else
538+ else
496− backtrackGraph graph (transactionId parentTrans) (TransactionIdHeadParentBacktrack (steps - 1))
539+ backtrackGraph graph (transactionId parentTrans) (TransactionIdHeadParentBacktrack (steps - 1))
497
540
498backtrackGraph graph currentTid (TransactionIdHeadBranchBacktrack steps) = do
541backtrackGraph graph currentTid (TransactionIdHeadBranchBacktrack steps) = do
499 trans <- transactionForId currentTid graph
542 trans <- transactionForId currentTid graph
500− let parents = transactionParentIds trans
543+ let parentIds' = parentIds trans
501− if S.size parents < 1 then
544+ if S.size parentIds' < 1 then
502 Left RootTransactionTraversalError
545 Left RootTransactionTraversalError
503− else if S.size parents < steps then
546+ else if S.size parentIds' < steps then
504− Left (ParentCountTraversalError (S.size parents) steps)
547+ Left (ParentCountTraversalError (S.size parentIds') steps)
505 else
548 else
506− pure (S.elemAt (steps - 1) parents)
549+ pure (S.elemAt (steps - 1) parentIds')
507
550
508−backtrackGraph graph currentTid btrack@(TransactionStampHeadBacktrack stamp) = do
551+backtrackGraph graph currentTid btrack@(TransactionStampHeadBacktrack stamp') = do
509 trans <- transactionForId currentTid graph
552 trans <- transactionForId currentTid graph
510− let parents = transactionParentIds trans
553+ let parentIds' = parentIds trans
511− if transactionTimestamp trans <= stamp then
554+ if timestamp trans <= stamp' then
512 pure currentTid
555 pure currentTid
513− else if S.null parents then
556+ else if S.null parentIds' then
514 Left RootTransactionTraversalError
557 Left RootTransactionTraversalError
515 else
558 else
516− let arbitraryParent = head (S.toList parents) in
559+ let arbitraryParent = head (S.toList parentIds') in
517 backtrackGraph graph arbitraryParent btrack
560 backtrackGraph graph arbitraryParent btrack
518
561
519-- | 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.
562-- | 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.
520--this is not a GraphOp because it combines multiple graph operations
563--this is not a GraphOp because it combines multiple graph operations
521autoMergeToHead :: UTCTime -> (TransactionId, TransactionId, TransactionId) -> DisconnectedTransaction -> HeadName -> MergeStrategy -> TransactionGraph -> Either RelationalError (DisconnectedTransaction, TransactionGraph)
564autoMergeToHead :: UTCTime -> (TransactionId, TransactionId, TransactionId) -> DisconnectedTransaction -> HeadName -> MergeStrategy -> TransactionGraph -> Either RelationalError (DisconnectedTransaction, TransactionGraph)
522−autoMergeToHead stamp (tempBranchTransId, tempCommitTransId, mergeTransId) discon mergeToHeadName strat graph = do
565+autoMergeToHead stamp' (tempBranchTransId, tempCommitTransId, mergeTransId) discon mergeToHeadName strat graph = do
523 let tempBranchName = "mergebranch_" <> U.toText tempBranchTransId
566 let tempBranchName = "mergebranch_" <> U.toText tempBranchTransId
524 --create the temp branch
567 --create the temp branch
525− (discon', graph') <- evalGraphOp stamp tempBranchTransId discon graph (Branch tempBranchName)
568+ (discon', graph') <- evalGraphOp stamp' tempBranchTransId discon graph (Branch tempBranchName)
526
569
527 --commit to the new branch- possible future optimization: don't require fsync for this- create a temp commit type
570 --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
571+ (discon'', graph'') <- evalGraphOp stamp' tempCommitTransId discon' graph' Commit
529
572
530 --jump to merge head
573 --jump to merge head
531− (discon''', graph''') <- evalGraphOp stamp tempBranchTransId discon'' graph'' (JumpToHead mergeToHeadName)
574+ (discon''', graph''') <- evalGraphOp stamp' tempBranchTransId discon'' graph'' (JumpToHead mergeToHeadName)
532
575
533 --create the merge
576 --create the merge
534− (discon'''', graph'''') <- evalGraphOp stamp mergeTransId discon''' graph''' (MergeTransactions strat tempBranchName mergeToHeadName)
577+ (discon'''', graph'''') <- evalGraphOp stamp' mergeTransId discon''' graph''' (MergeTransactions strat tempBranchName mergeToHeadName)
535
578
536 --delete the temp branch
579 --delete the temp branch
537− (discon''''', graph''''') <- evalGraphOp stamp tempBranchTransId discon'''' graph'''' (DeleteBranch tempBranchName)
580+ (discon''''', graph''''') <- evalGraphOp stamp' tempBranchTransId discon'''' graph'''' (DeleteBranch tempBranchName)
538 {-
581 {-
539 let rel = runReader (evalRelationalExpr (RelationVariable "s" ())) (mkRelationalExprState $ D.concreteDatabaseContext discon'''')
582 let rel = runReader (evalRelationalExpr (RelationVariable "s" ())) (mkRelationalExprState $ D.concreteDatabaseContext discon'''')
540 traceShowM rel
583 traceShowM rel
@@ -542,4 +585,49 @@ autoMergeToHead stamp (tempBranchTransId, tempCommitTransId, mergeTransId) disco
542
585
543 pure (discon''''', graph''''')
586 pure (discon''''', graph''''')
544
587
588+
589+addMerkleHash :: TransactionGraph -> Transaction -> Transaction
590+addMerkleHash graph trans = Transaction (transactionId trans) newInfo (schemas trans)
591+ where
592+ newInfo = (transactionInfo trans) { merkleHash = calculateMerkleHash trans graph }
545
593
594+-- the new hash includes the parents' ids, the current id, and the hash of the context, and the merkle hashes of the parent transactions
595+calculateMerkleHash :: Transaction -> TransactionGraph -> MerkleHash
596+calculateMerkleHash trans graph = MerkleHash $ hashlazy (mconcat [transIds,
597+ dbcBytes,
598+ schemasBytes,
599+ parentMerkleHashes])
600+ where
601+ parentMerkleHashes = BL.fromChunks $ map (_unMerkleHash . getMerkleHash) parentTranses
602+ parentTranses =
603+ case transactionsForIds (parentIds trans) graph of
604+ Left RootTransactionTraversalError -> []
605+ Left e -> error ("failed to find transaction in Merkle hash construction: " ++ show e)
606+ Right t -> S.toList t
607+ getMerkleHash t = merkleHash (transactionInfo t)
608+ transIds = B.encode (transactionId trans : S.toList (parentIds trans))
609+ dbcBytes = DBC.hashBytes (concreteDatabaseContext trans)
610+ schemasBytes = B.encode (subschemas trans)
611+
612+validateMerkleHash :: Transaction -> TransactionGraph -> Either MerkleValidationError ()
613+validateMerkleHash trans graph =
614+ if expectedHash /= actualHash then
615+ Left (MerkleValidationError (transactionId trans) expectedHash actualHash)
616+ else
617+ pure ()
618+ where
619+ expectedHash = merkleHash (transactionInfo trans)
620+ actualHash = calculateMerkleHash trans graph
621+
622+data MerkleValidationError = MerkleValidationError TransactionId MerkleHash MerkleHash
623+ deriving (Show, Eq, Generic)
624+
625+validateMerkleHashes :: TransactionGraph -> Either [MerkleValidationError] ()
626+validateMerkleHashes graph =
627+ if null errs then pure () else Left errs
628+ where
629+ errs = S.foldr validateTrans [] (transactionsForGraph graph)
630+ validateTrans trans acc =
631+ case validateMerkleHash trans graph of
632+ Left err -> err : acc
633+ _ -> acc
src/lib/ProjectM36/TransactionGraph/Merge.hs+16−12
@@ -2,10 +2,11 @@
2module ProjectM36.TransactionGraph.Merge where
2module ProjectM36.TransactionGraph.Merge where
3import ProjectM36.Base
3import ProjectM36.Base
4import ProjectM36.Error
4import ProjectM36.Error
5+import ProjectM36.RelationalExpression
6+import Control.Monad.Except hiding (join)
5import qualified Data.Set as S
7import qualified Data.Set as S
6import qualified Data.Map as M
8import qualified Data.Map as M
7import qualified ProjectM36.TypeConstructorDef as TCD
9import qualified ProjectM36.TypeConstructorDef as TCD
8−import ProjectM36.Relation
9import Control.Monad (foldM)
10import Control.Monad (foldM)
10import qualified Data.HashSet as HS
11import qualified Data.HashSet as HS
11
12
@@ -22,19 +23,22 @@ unionMergeMaps prefer mapA mapB = case prefer of
22 Left StrategyViolatesComponentMergeError
23 Left StrategyViolatesComponentMergeError
23
24
24-- perform the merge even if the attributes are different- is this what we want? Obviously, we need finer-grained merge options.
25-- 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 :: MergePreference -> GraphRefRelationalExpr -> GraphRefRelationalExpr -> GraphRefRelationalExprM GraphRefRelationalExpr
26−unionMergeRelation prefer relA relB = case relA `union` relB of
27+unionMergeRelation prefer relA relB = do
27− Right unionRel -> pure unionRel
28+ let unioned = Union relA relB
28− Left (AttributeNamesMismatchError _) -> preferredRelVar
29− Left _ -> Left StrategyViolatesRelationVariableMergeError
29+ mergeErr = MergeTransactionError StrategyViolatesRelationVariableMergeError
30− where
31− preferredRelVar = case prefer of
30+ preferredRelVar =
31+ case prefer of
32− PreferFirst -> Right relA
32+ PreferFirst -> pure relA
33− PreferSecond -> Right relB
33+ PreferSecond -> pure relB
34− PreferNeither -> Left StrategyViolatesRelationVariableMergeError
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
35
39
36--try to execute unions against the relvars contents -- if a relvar only appears in one context, include it
40--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
38unionMergeRelVars prefer relvarsA relvarsB = do
42unionMergeRelVars prefer relvarsA relvarsB = do
39 let allNames = S.toList (S.union (M.keysSet relvarsA) (M.keysSet relvarsB))
43 let allNames = S.toList (S.union (M.keysSet relvarsA) (M.keysSet relvarsB))
40 foldM (\acc name -> do
44 foldM (\acc name -> do
src/lib/ProjectM36/TransactionGraph/Persist.hs+8−5
@@ -1,8 +1,8 @@
1module ProjectM36.TransactionGraph.Persist where
1module ProjectM36.TransactionGraph.Persist where
2import ProjectM36.Error
2import ProjectM36.Error
3−import ProjectM36.TransactionGraph
4import ProjectM36.Transaction
3import ProjectM36.Transaction
5import ProjectM36.Transaction.Persist
4import ProjectM36.Transaction.Persist
5+import ProjectM36.RelationalExpression
6import ProjectM36.Base
6import ProjectM36.Base
7import ProjectM36.ScriptSession
7import ProjectM36.ScriptSession
8import ProjectM36.Persist (writeFileSync, renameSync, DiskSync)
8import ProjectM36.Persist (writeFileSync, renameSync, DiskSync)
@@ -24,7 +24,9 @@ import Control.Exception.Base
24import qualified Data.ByteString as BS
24import qualified Data.ByteString as BS
25import qualified Data.Text.Encoding as TE
25import qualified Data.Text.Encoding as TE
26import Data.ByteString (ByteString)
26import Data.ByteString (ByteString)
27+#if __GLASGOW_HASKELL__ < 804
27import Data.Monoid
28import Data.Monoid
29+#endif
28import qualified Crypto.Hash.SHA256 as SHA256
30import qualified Crypto.Hash.SHA256 as SHA256
29import Control.Arrow
31import Control.Arrow
30import Data.Time.Clock
32import Data.Time.Clock
@@ -192,12 +194,12 @@ writeGraphTransactionIdFile sync destDirectory (TransactionGraph _ transSet) = w
192 uuidInfo = T.intercalate "\n" graphLines
194 uuidInfo = T.intercalate "\n" graphLines
193 digest = SHA256.hash (encodeUtf8 uuidInfo)
195 digest = SHA256.hash (encodeUtf8 uuidInfo)
194 graphLines = S.toList $ S.map graphLine transSet
196 graphLines = S.toList $ S.map graphLine transSet
195− epochTime = realToFrac . utcTimeToPOSIXSeconds . transactionTimestamp :: Transaction -> Double
197+ epochTime = realToFrac . utcTimeToPOSIXSeconds . timestamp :: Transaction -> Double
196 graphLine trans = U.toText (transactionId trans)
198 graphLine trans = U.toText (transactionId trans)
197 <> " "
199 <> " "
198 <> T.pack (show (epochTime trans))
200 <> T.pack (show (epochTime trans))
199 <> " "
201 <> " "
200− <> T.intercalate " " (S.toList (S.map U.toText $ transactionParentIds trans))
202+ <> T.intercalate " " (S.toList (S.map U.toText $ parentIds trans))
201
203
202readGraphTransactionIdFileDigest :: FilePath -> IO LockFileHash
204readGraphTransactionIdFileDigest :: FilePath -> IO LockFileHash
203readGraphTransactionIdFileDigest dbdir = do
205readGraphTransactionIdFileDigest dbdir = do
@@ -207,8 +209,8 @@ readGraphTransactionIdFileDigest dbdir = do
207readGraphTransactionIdFile :: FilePath -> IO (Either PersistenceError [(TransactionId, UTCTime, [TransactionId])])
209readGraphTransactionIdFile :: FilePath -> IO (Either PersistenceError [(TransactionId, UTCTime, [TransactionId])])
208readGraphTransactionIdFile dbdir = do
210readGraphTransactionIdFile dbdir = do
209 --read in all transactions' uuids
211 --read in all transactions' uuids
210− let grapher line = let tid:epochText:parentIds = T.words line in
212+ let grapher line = let tid:epochText:parentIds' = T.words line in
211− (readUUID tid, readEpoch epochText, map readUUID parentIds)
213+ (readUUID tid, readEpoch epochText, map readUUID parentIds')
212 readUUID uuidText = fromMaybe (error "failed to read uuid") (U.fromText uuidText)
214 readUUID uuidText = fromMaybe (error "failed to read uuid") (U.fromText uuidText)
213 readEpoch t = posixSecondsToUTCTime (realToFrac (either (error "failed to read epoch") fst (double t)))
215 readEpoch t = posixSecondsToUTCTime (realToFrac (either (error "failed to read epoch") fst (double t)))
214 Right . map grapher . T.lines <$> readUTF8FileOrError (transactionLogPath dbdir)
216 Right . map grapher . T.lines <$> readUTF8FileOrError (transactionLogPath dbdir)
@@ -223,3 +225,4 @@ readUTF8FileOrError pathIn = do
223 case TE.decodeUtf8' fileBytes of
225 case TE.decodeUtf8' fileBytes of
224 Left err -> error (show err)
226 Left err -> error (show err)
225 Right utf8Bytes -> pure utf8Bytes
227 Right utf8Bytes -> pure utf8Bytes
228+
src/lib/ProjectM36/TransactionGraph/Show.hs+3−4
@@ -1,17 +1,16 @@
1module ProjectM36.TransactionGraph.Show where
1module ProjectM36.TransactionGraph.Show where
2import ProjectM36.Base
2import ProjectM36.Base
3import ProjectM36.TransactionGraph
3import ProjectM36.TransactionGraph
4−import ProjectM36.Transaction
5import qualified Data.Set as S
4import qualified Data.Set as S
6
5
7showTransactionStructure :: Transaction -> TransactionGraph -> String
6showTransactionStructure :: 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
9 where
8 where
10 headInfo = maybe "" show (headNameForTransaction trans graph)
9 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
12 Left err -> show err
11 Left err -> show err
13 Right parentTransSet -> concat $ S.toList $ S.map (show . transactionId) parentTransSet
12 Right parentTransSet -> concat $ S.toList $ S.map (show . transactionId) parentTransSet
14− childTransactionsInfo = show (S.toList (transactionChildIds trans))
13+
15
14
16showGraphStructure :: TransactionGraph -> String
15showGraphStructure :: TransactionGraph -> String
17showGraphStructure graph@(TransactionGraph _ transSet) = S.foldr folder "" transSet
16showGraphStructure 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+2−9
@@ -48,13 +48,6 @@ atomForAttributeName attrName (RelationTuple tupAttrs tupVec) = case V.findIndex
48 Nothing -> Left (NoSuchAttributeNamesError (S.singleton attrName))
48 Nothing -> Left (NoSuchAttributeNamesError (S.singleton attrName))
49 Just atom -> Right atom
49 Just atom -> Right atom
50
50
51−{- -- resolve naming clash with Attribute and Relation later
52−atomTypeForAttributeName :: AttributeName -> RelationTuple -> Either RelationalError Atom
53−atomTypeForAttributeName attrName tup = do
54− atom <- atomForAttributeName attrName tup
55− return $ atomTypeForAtom atom
56−-}
57−
58atomsForAttributeNames :: V.Vector AttributeName -> RelationTuple -> Either RelationalError (V.Vector Atom)
51atomsForAttributeNames :: V.Vector AttributeName -> RelationTuple -> Either RelationalError (V.Vector Atom)
59atomsForAttributeNames attrNames tuple =
52atomsForAttributeNames attrNames tuple =
60 V.map (\index -> tupleAtoms tuple V.! index) <$> vectorIndicesForAttributeNames attrNames (tupleAttributes tuple)
53 V.map (\index -> tupleAtoms tuple V.! index) <$> vectorIndicesForAttributeNames attrNames (tupleAttributes tuple)
@@ -93,7 +86,7 @@ mkRelationTuples attrs = map mapper
93 mapper = mkRelationTuple attrs
86 mapper = mkRelationTuple attrs
94
87
95mkRelationTupleFromMap :: M.Map AttributeName Atom -> RelationTuple
88mkRelationTupleFromMap :: M.Map AttributeName Atom -> RelationTuple
96−mkRelationTupleFromMap attrMap = RelationTuple attrs (V.map (\attrName -> attrMap M.! attrName) attrNames)
89+mkRelationTupleFromMap attrMap = RelationTuple attrs (V.map (attrMap M.!) attrNames)
97 where
90 where
98 attrNames = V.fromList (M.keys attrMap)
91 attrNames = V.fromList (M.keys attrMap)
99 attrs = V.map (\attrName -> Attribute attrName (atomTypeForAtom (attrMap M.! attrName))) attrNames
92 attrs = V.map (\attrName -> Attribute attrName (atomTypeForAtom (attrMap M.! attrName))) attrNames
@@ -214,4 +207,4 @@ reorderTuple attrs tupIn = if tupleAttributes tupIn == attrs then
214
207
215--used in Generics derivation for ADTs without named attributes
208--used in Generics derivation for ADTs without named attributes
216trimTuple :: Int -> RelationTuple -> RelationTuple
209trimTuple :: Int -> RelationTuple -> RelationTuple
217−trimTuple index (RelationTuple attrs vals) = RelationTuple (V.drop index attrs) (V.drop index vals)
210+trimTuple index (RelationTuple attrs vals) = RelationTuple (V.drop index attrs) (V.drop index vals)
src/lib/ProjectM36/Tupleable.hs+106−27
@@ -4,13 +4,35 @@
4{-# LANGUAGE ScopedTypeVariables #-}
4{-# LANGUAGE ScopedTypeVariables #-}
5{-# LANGUAGE TypeOperators #-}
5{-# LANGUAGE TypeOperators #-}
6{-# LANGUAGE UndecidableInstances #-}
6{-# LANGUAGE UndecidableInstances #-}
7−
7+{-# LANGUAGE CPP #-}
8+
8−module ProjectM36.Tupleable where
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
9
29
10import Data.Foldable
30import Data.Foldable
11import Data.List (partition)
31import Data.List (partition)
12import qualified Data.Map as Map
32import qualified Data.Map as Map
33+#if __GLASGOW_HASKELL__ < 804
13import Data.Monoid
34import Data.Monoid
35+#endif
14import Data.Proxy
36import Data.Proxy
15import qualified Data.Text as T
37import qualified Data.Text as T
16import qualified Data.Vector as V
38import qualified Data.Vector as V
@@ -118,56 +140,109 @@ validateAttributes actualAttrs expectedAttrs val
118 where
140 where
119 nonMatchingAttrs = attributeNamesNotContained actualAttrs expectedAttrs
141 nonMatchingAttrs = attributeNamesNotContained actualAttrs expectedAttrs
120
142
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
122class Tupleable a where
164class Tupleable a where
123 toTuple :: a -> RelationTuple
165 toTuple :: a -> RelationTuple
124
166
125 fromTuple :: RelationTuple -> Either RelationalError a
167 fromTuple :: RelationTuple -> Either RelationalError a
126
168
127− toAttributes :: proxy a -> Attributes
169+ toAttributes :: Proxy a -> Attributes
128
170
129 default toTuple :: (Generic a, TupleableG (Rep a)) => a -> RelationTuple
171 default toTuple :: (Generic a, TupleableG (Rep a)) => a -> RelationTuple
130− toTuple v = toTupleG (from v)
172+ toTuple = genericToTuple defaultTupleableOptions
131
173
132 default fromTuple :: (Generic a, TupleableG (Rep a)) => RelationTuple -> Either RelationalError a
174 default fromTuple :: (Generic a, TupleableG (Rep a)) => RelationTuple -> Either RelationalError a
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
133− fromTuple tup = to <$> fromTupleG tup
208+genericFromTuple opts tup = to <$> fromTupleG opts tup
134
209
135− default toAttributes :: (Generic a, TupleableG (Rep a)) => proxy a -> Attributes
210+genericToAttributes :: forall a. (Generic a, TupleableG (Rep a)) => TupleableOptions -> Proxy a -> Attributes
136− toAttributes _ = toAttributesG (from (undefined :: a))
211+genericToAttributes opts _ = toAttributesG opts (from (undefined :: a))
137
212
138class TupleableG g where
213class TupleableG g where
139− toTupleG :: g a -> RelationTuple
214+ toTupleG :: TupleableOptions -> g a -> RelationTuple
140− toAttributesG :: g a -> Attributes
215+ toAttributesG :: TupleableOptions -> g a -> Attributes
141− fromTupleG :: RelationTuple -> Either RelationalError (g a)
216+ fromTupleG :: TupleableOptions -> RelationTuple -> Either RelationalError (g a)
142 isRecordTypeG :: g a -> Bool
217 isRecordTypeG :: g a -> Bool
143
218
144--data type metadata
219--data type metadata
145instance (Datatype c, TupleableG a) => TupleableG (M1 D c a) where
220instance (Datatype c, TupleableG a) => TupleableG (M1 D c a) where
146− toTupleG (M1 v) = toTupleG v
221+ toTupleG opts (M1 v) = toTupleG opts v
147− toAttributesG (M1 v) = toAttributesG v
222+ toAttributesG opts (M1 v) = toAttributesG opts v
148− fromTupleG v = M1 <$> fromTupleG v
223+ fromTupleG opts v = M1 <$> fromTupleG opts v
149 isRecordTypeG (M1 v) = isRecordTypeG v
224 isRecordTypeG (M1 v) = isRecordTypeG v
150
225
151--constructor metadata
226--constructor metadata
152instance (Constructor c, TupleableG a, AtomableG a) => TupleableG (M1 C c a) where
227instance (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
154 where
229 where
155− attrsToCheck = toAttributesG v
230+ attrsToCheck = toAttributesG opts v
156 counter = V.generate (V.length attrsToCheck) id
231 counter = V.generate (V.length attrsToCheck) id
157 attrs = V.zipWith (\num attr@(Attribute name typ) -> if T.null name then
232 attrs = V.zipWith (\num attr@(Attribute name typ) -> if T.null name then
158 Attribute ("attr" <> T.pack (show (num + 1))) typ
233 Attribute ("attr" <> T.pack (show (num + 1))) typ
159 else
234 else
160 attr) counter attrsToCheck
235 attr) counter attrsToCheck
161 atoms = V.fromList (toAtomsG v)
236 atoms = V.fromList (toAtomsG v)
162− toAttributesG (M1 v) = toAttributesG v
237+ toAttributesG opts (M1 v) = toAttributesG opts v
163− fromTupleG tup = M1 <$> fromTupleG tup
238+ fromTupleG opts tup = M1 <$> fromTupleG opts tup
164 isRecordTypeG (M1 v) = isRecordTypeG v
239 isRecordTypeG (M1 v) = isRecordTypeG v
165
240
166-- product types
241-- product types
167instance (TupleableG a, TupleableG b) => TupleableG (a :*: b) where
242instance (TupleableG a, TupleableG b) => TupleableG (a :*: b) where
168 toTupleG = error "toTupleG"
243 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
244+ toAttributesG opts ~(x :*: y) = toAttributesG opts x V.++ toAttributesG opts 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+ fromTupleG opts tup = (:*:) <$> fromTupleG opts tup <*> fromTupleG opts processedTuple
171 where
246 where
172 processedTuple = if isRecordTypeG (undefined :: a x) then
247 processedTuple = if isRecordTypeG (undefined :: a x) then
173 tup
248 tup
@@ -178,18 +253,22 @@ instance (TupleableG a, TupleableG b) => TupleableG (a :*: b) where
178--selector/record
253--selector/record
179instance (Selector c, AtomableG a) => TupleableG (M1 S c a) where
254instance (Selector c, AtomableG a) => TupleableG (M1 S c a) where
180 toTupleG = error "toTupleG"
255 toTupleG = error "toTupleG"
181− toAttributesG m@(M1 v) = V.singleton (Attribute name aType)
256+ toAttributesG opts m@(M1 v) = V.singleton (Attribute modifiedName aType)
182 where
257 where
183 name = T.pack (selName m)
258 name = T.pack (selName m)
259+ modifiedName = if T.null name then
260+ name
261+ else
262+ fieldModifier opts name
184 aType = toAtomTypeG v
263 aType = toAtomTypeG v
185− fromTupleG tup = if null name then -- non-record type, just pull off the first tuple item
264+ fromTupleG opts tup = if null name then -- non-record type, just pull off the first tuple item
186 M1 <$> atomv (V.head (tupleAtoms tup))
265 M1 <$> atomv (V.head (tupleAtoms tup))
187 else do
266 else do
188− atom <- atomForAttributeName (T.pack name) tup
267+ atom <- atomForAttributeName (fieldModifier opts (T.pack name)) tup
189 val <- atomv atom
268 val <- atomv atom
190 pure (M1 val)
269 pure (M1 val)
191 where
270 where
192− expectedAtomType = atomType (V.head (toAttributesG (undefined :: M1 S c a x)))
271+ expectedAtomType = atomType (V.head (toAttributesG opts (undefined :: M1 S c a x)))
193 atomv atom = maybe (Left (AtomTypeMismatchError
272 atomv atom = maybe (Left (AtomTypeMismatchError
194 expectedAtomType
273 expectedAtomType
195 (atomTypeForAtom atom)
274 (atomTypeForAtom atom)
@@ -200,8 +279,8 @@ instance (Selector c, AtomableG a) => TupleableG (M1 S c a) where
200--constructors with no arguments
279--constructors with no arguments
201--basically useless but orthoganal to relationTrue
280--basically useless but orthoganal to relationTrue
202instance TupleableG U1 where
281instance TupleableG U1 where
203− toTupleG _= emptyTuple
282+ toTupleG _ _ = emptyTuple
204− toAttributesG _ = emptyAttributes
283+ toAttributesG _ _ = emptyAttributes
205− fromTupleG _ = pure U1
284+ fromTupleG _ _ = pure U1
206 isRecordTypeG _ = False
285 isRecordTypeG _ = False
207
286
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/Win32Handle.hs+4−1
@@ -53,5 +53,8 @@ withHandleToHANDLE haskell_handle action =
53 -- Do what the user originally wanted
53 -- Do what the user originally wanted
54 action windows_handle
54 action windows_handle
55
55
56+#if MIN_VERSION_Win32(2,5,1)
57+#else
56withStablePtr :: a -> (StablePtr a -> IO b) -> IO b
58withStablePtr :: a -> (StablePtr a -> IO b) -> IO b
57−withStablePtr value = bracket (newStablePtr value) freeStablePtr
59+withStablePtr value = bracket (newStablePtr value) freeStablePtr
60+#endif
src/lib/ProjectM36/WithNameExpr.hsnew file+84
@@ -0,0 +1,84 @@
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 override existing macros and recurse
46+ let newMacros = foldr macroFolder macros moreMacros
47+ macroFolder (wnexpr, mexpr) acc = filter (\(w,_) -> w /= wnexpr) acc ++ [(wnexpr, mexpr)] in
48+ --scan for a match- if it exists, replace it (representing a with clause at a lower level
49+ substituteWithNameMacros newMacros expr
50+
51+
52+substituteWithNameMacrosRestrictionPredicate :: WithNameAssocs -> GraphRefRestrictionPredicateExpr -> GraphRefRestrictionPredicateExpr
53+substituteWithNameMacrosRestrictionPredicate macros pred' =
54+ let sub = substituteWithNameMacrosRestrictionPredicate macros in
55+ case pred' of
56+ TruePredicate -> pred'
57+ AndPredicate exprA exprB ->
58+ AndPredicate (sub exprA) (sub exprB)
59+ OrPredicate exprA exprB ->
60+ OrPredicate (sub exprA) (sub exprB)
61+ NotPredicate expr ->
62+ NotPredicate (sub expr)
63+ RelationalExprPredicate reexpr ->
64+ RelationalExprPredicate (substituteWithNameMacros macros reexpr)
65+ AtomExprPredicate atomExpr ->
66+ AtomExprPredicate (substituteWithNameMacrosAtomExpr macros atomExpr)
67+ AttributeEqualityPredicate attrName atomExpr ->
68+ AttributeEqualityPredicate attrName (substituteWithNameMacrosAtomExpr macros atomExpr)
69+
70+substituteWitNameMacrosExtendTupleExpr :: WithNameAssocs -> GraphRefExtendTupleExpr -> GraphRefExtendTupleExpr
71+substituteWitNameMacrosExtendTupleExpr macros (AttributeExtendTupleExpr attrName atomExpr) =
72+ AttributeExtendTupleExpr attrName (substituteWithNameMacrosAtomExpr macros atomExpr)
73+
74+substituteWithNameMacrosAtomExpr :: WithNameAssocs -> GraphRefAtomExpr -> GraphRefAtomExpr
75+substituteWithNameMacrosAtomExpr macros atomExpr =
76+ case atomExpr of
77+ e@AttributeAtomExpr{} -> e
78+ e@NakedAtomExpr{} -> e
79+ FunctionAtomExpr fname atomExprs tid ->
80+ FunctionAtomExpr fname (map (substituteWithNameMacrosAtomExpr macros) atomExprs) tid
81+ RelationAtomExpr reExpr ->
82+ RelationAtomExpr (substituteWithNameMacros macros reExpr)
83+ ConstructedAtomExpr dconsName atomExprs tid ->
84+ ConstructedAtomExpr dconsName (map (substituteWithNameMacrosAtomExpr macros) atomExprs) tid
stack.yaml → stack.ghc8.0.yamlrenamed+1
@@ -19,6 +19,7 @@ extra-deps:
19- distributed-process-async-0.2.4
19- distributed-process-async-0.2.4
20- distributed-process-client-server-0.2.3
20- distributed-process-client-server-0.2.3
21- distributed-process-extras-0.3.2
21- distributed-process-extras-0.3.2
22+- deferred-folds-0.6.12
22- rset-1.0.0
23- rset-1.0.0
23
24
24# Override default flag values for local packages and extra-deps
25# Override default flag values for local packages and extra-deps
stack.ghc7.10.yaml → stack.ghc8.2.yamlrenamed+6−6
@@ -2,7 +2,7 @@
2# For more information, see: http://docs.haskellstack.org/en/stable/yaml_configuration/
2# For more information, see: http://docs.haskellstack.org/en/stable/yaml_configuration/
3
3
4# Specifies the GHC version and set of packages available (e.g., lts-3.5, nightly-2015-09-21, ghc-7.10.2)
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-6.35
5+resolver: lts-11.20
6
6
7# Local packages, usually specified by relative directory name
7# Local packages, usually specified by relative directory name
8packages:
8packages:
@@ -15,16 +15,16 @@ extra-deps:
15- gnuplot-0.5.4.1
15- gnuplot-0.5.4.1
16- text-1.2.2.1
16- text-1.2.2.1
17- aeson-1.2.1.00
17- aeson-1.2.1.00
18−- distributed-process-0.6.6
18+- distributed-process-0.7.3
19−- distributed-process-async-0.2.4
19+- distributed-process-async-0.2.4.1
20- distributed-process-client-server-0.2.3
20- distributed-process-client-server-0.2.3
21- distributed-process-extras-0.3.2
21- distributed-process-extras-0.3.2
22−- cryptohash-sha256-0.11.100.1
23−- megaparsec-5.3.1
24- rset-1.0.0
22- rset-1.0.0
25
23
26# Override default flag values for local packages and extra-deps
24# Override default flag values for local packages and extra-deps
27−flags: {}
25+flags:
26+ project-m36:
27+ stack: true
28
28
29# Extra package databases containing global packages
29# Extra package databases containing global packages
30extra-package-dbs: []
30extra-package-dbs: []
stack.ghc8.4.yamlnew file+48
@@ -0,0 +1,48 @@
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-12.26
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-interval-1.3.0
13+- extended-reals-0.2.3.0
14+- distributed-process-0.7.4
15+- distributed-process-async-0.2.6
16+- distributed-process-client-server-0.2.5.1
17+- distributed-process-extras-0.3.5
18+- rset-1.0.0
19+- hashable-time-0.2.0.2
20+- network-transport-tcp-0.6.0
21+
22+# Override default flag values for local packages and extra-deps
23+flags:
24+ project-m36:
25+ stack: true
26+
27+# Extra package databases containing global packages
28+extra-package-dbs: []
29+
30+# Control whether we use the GHC we find on the path
31+# system-ghc: true
32+
33+# Require a specific version of stack, using version ranges
34+# require-stack-version: -any # Default
35+# require-stack-version: >= 1.0.0
36+
37+# Override the architecture used by stack, especially useful on Windows
38+# arch: i386
39+# arch: x86_64
40+
41+# Extra directories used by stack for building
42+# extra-include-dirs: [/path/to/dir]
43+# extra-lib-dirs: [/path/to/dir]
44+
45+# Allow a newer minor version of GHC than the snapshot specifies
46+# compiler-check: newer-minor
47+
48+allow-newer: true
stack.ghc8.6.yamlnew file+53
@@ -0,0 +1,53 @@
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-14.3
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+- git: https://github.com/haskell-distributed/distributed-process.git
13+ commit: 660d554f6acd2dba8b605c84e8fa69e45708bc14
14+- extended-reals-0.2.3.0
15+- data-interval-2.0.1
16+- stm-containers-1.1.0.4
17+- distributed-static-0.3.9
18+- stm-hamt-1.2.0.4
19+- distributed-process-async-0.2.6
20+- distributed-process-client-server-0.2.5.1
21+- distributed-process-extras-0.3.5
22+- rset-1.0.0
23+- hashable-time-0.2.0.2
24+- network-transport-tcp-0.6.0
25+- megaparsec-7.0.5
26+
27+# Override default flag values for local packages and extra-deps
28+flags:
29+ project-m36:
30+ stack: true
31+
32+# Extra package databases containing global packages
33+extra-package-dbs: []
34+
35+# Control whether we use the GHC we find on the path
36+# system-ghc: true
37+
38+# Require a specific version of stack, using version ranges
39+# require-stack-version: -any # Default
40+# require-stack-version: >= 1.0.0
41+
42+# Override the architecture used by stack, especially useful on Windows
43+# arch: i386
44+# arch: x86_64
45+
46+# Extra directories used by stack for building
47+# extra-include-dirs: [/path/to/dir]
48+# extra-lib-dirs: [/path/to/dir]
49+
50+# Allow a newer minor version of GHC than the snapshot specifies
51+# compiler-check: newer-minor
52+
53+allow-newer: true
stack.ghc8.8.yamlnew file+56
@@ -0,0 +1,56 @@
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-16.4
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+- git: https://github.com/agentm/distributed-process.git
13+ commit: 688a5b96d4b7b36d90c3db676230b2c943604288
14+- extended-reals-0.2.3.0
15+- data-interval-2.0.1
16+- stm-containers-1.1.0.4
17+- distributed-static-0.3.9
18+- stm-hamt-1.2.0.4
19+- distributed-process-async-0.2.6
20+- distributed-process-client-server-0.2.5.1
21+- distributed-process-extras-0.3.5
22+- rset-1.0.0
23+- hashable-time-0.2.0.2
24+- network-transport-tcp-0.7.0
25+- megaparsec-7.0.5
26+- network-2.8.0.1
27+- primitive-extras-0.8
28+- primitive-unlifted-0.1.3.0
29+
30+# Override default flag values for local packages and extra-deps
31+flags:
32+ project-m36:
33+ stack: true
34+
35+# Extra package databases containing global packages
36+extra-package-dbs: []
37+
38+# Control whether we use the GHC we find on the path
39+# system-ghc: true
40+
41+# Require a specific version of stack, using version ranges
42+# require-stack-version: -any # Default
43+# require-stack-version: >= 1.0.0
44+
45+# Override the architecture used by stack, especially useful on Windows
46+# arch: i386
47+# arch: x86_64
48+
49+# Extra directories used by stack for building
50+# extra-include-dirs: [/path/to/dir]
51+# extra-lib-dirs: [/path/to/dir]
52+
53+# Allow a newer minor version of GHC than the snapshot specifies
54+# compiler-check: newer-minor
55+
56+allow-newer: true
test/DataFrame.hsnew file+61
@@ -0,0 +1,61 @@
1+import ProjectM36.Client
2+import ProjectM36.DataFrame
3+import TutorialD.Interpreter.TestBase
4+
5+import Test.HUnit
6+import System.Exit
7+import qualified Data.Set as S
8+
9+testList :: Test
10+testList = TestList [testOrderBy, testLimit, testOffset]
11+
12+main :: IO ()
13+main = do
14+ tcounts <- runTestTT testList
15+ if errors tcounts + failures tcounts > 0 then exitFailure else exitSuccess
16+
17+testOrderBy :: Test
18+testOrderBy = TestCase $ do
19+ (sessionId, dbconn) <- dateExamplesConnection emptyNotificationCallback
20+ Right df <- executeDataFrameExpr sessionId dbconn (
21+ DataFrameExpr {
22+ convertExpr = Project (AttributeNames (S.singleton "status")) (RelationVariable "s" ()),
23+ orderExprs = [AttributeOrderExpr "status" AscendingOrder],
24+ offset = Nothing,
25+ limit = Nothing
26+ })
27+ let vals = map (\tup -> case atomForAttributeName "status" tup of
28+ Left err -> error (show err)
29+ Right atom -> atom) (tuples df)
30+ assertEqual "sort order of s" [IntegerAtom 10, IntegerAtom 20, IntegerAtom 30] vals
31+
32+testOffset :: Test
33+testOffset = TestCase $ do
34+ (sessionId, dbconn) <- dateExamplesConnection emptyNotificationCallback
35+ Right df <- executeDataFrameExpr sessionId dbconn (
36+ DataFrameExpr {
37+ convertExpr = Project (AttributeNames (S.singleton "status")) (RelationVariable "s" ()),
38+ orderExprs = [AttributeOrderExpr "status" AscendingOrder],
39+ offset = Just 1,
40+ limit = Nothing
41+ })
42+ let vals = map (\tup -> case atomForAttributeName "status" tup of
43+ Left err -> error (show err)
44+ Right atom -> atom) (tuples df)
45+ assertEqual "sort + offset" [IntegerAtom 20, IntegerAtom 30] vals
46+
47+testLimit :: Test
48+testLimit = TestCase $ do
49+ (sessionId, dbconn) <- dateExamplesConnection emptyNotificationCallback
50+ Right df <- executeDataFrameExpr sessionId dbconn (
51+ DataFrameExpr {
52+ convertExpr = Project (AttributeNames (S.singleton "status")) (RelationVariable "s" ()),
53+ orderExprs = [AttributeOrderExpr "status" DescendingOrder],
54+ offset = Nothing,
55+ limit = Just 1
56+ })
57+ let vals = map (\tup -> case atomForAttributeName "status" tup of
58+ Left err -> error (show err)
59+ Right atom -> atom) (tuples df)
60+ assertEqual "sort + limit" [IntegerAtom 30] vals
61+
test/IsomorphicSchema.hs+43−33
@@ -4,13 +4,13 @@ import ProjectM36.Error
4import ProjectM36.IsomorphicSchema
4import ProjectM36.IsomorphicSchema
5import ProjectM36.Relation
5import ProjectM36.Relation
6import ProjectM36.RelationalExpression
6import ProjectM36.RelationalExpression
7+import ProjectM36.TransactionGraph
8+import ProjectM36.StaticOptimizer
7import qualified ProjectM36.DatabaseContext as DBC
9import qualified ProjectM36.DatabaseContext as DBC
8import qualified ProjectM36.Attribute as A
10import qualified ProjectM36.Attribute as A
9import System.Exit
11import System.Exit
10import qualified Data.Map as M
12import qualified Data.Map as M
11import qualified Data.Set as S
13import qualified Data.Set as S
12−import Control.Monad.State
13−import Control.Monad.Trans.Reader
14
14
15testList :: Test
15testList :: Test
16testList = TestList [testIsoRename, testIsoRestrict, testIsoUnion, testSchemaValidation]
16testList = TestList [testIsoRename, testIsoRestrict, testIsoUnion, testSchemaValidation]
@@ -36,7 +36,7 @@ assertMaybe x msg = case x of
36testSchemaValidation :: Test
36testSchemaValidation :: Test
37testSchemaValidation = TestCase $ do
37testSchemaValidation = TestCase $ do
38 let potentialSchema = DBC.basicDatabaseContext {
38 let potentialSchema = DBC.basicDatabaseContext {
39− relationVariables = M.singleton "anotherRel" relationTrue
39+ relationVariables = M.singleton "anotherRel" (ExistingRelation relationTrue)
40 }
40 }
41 -- missing relvars failure
41 -- missing relvars failure
42 morphs = [IsoRename "true" "true", IsoRename "false" "false"]
42 morphs = [IsoRename "true" "true", IsoRename "false" "false"]
@@ -50,15 +50,17 @@ testSchemaValidation = TestCase $ do
50testIsoRename :: Test
50testIsoRename :: Test
51testIsoRename = TestCase $ do
51testIsoRename = TestCase $ do
52 -- create a schema with two relvars and rename one while the other remains the same in the isomorphic schema
52 -- 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 {
53+ let ctx = DBC.empty {
54− relationVariables = M.fromList [("employee", relationTrue),
54+ relationVariables = M.fromList [("employee", ExistingRelation relationTrue),
55− ("department", relationFalse)]
55+ ("department", ExistingRelation relationFalse)]
56 }
56 }
57+ (graph, _) <- freshTransactionGraph ctx
57− isomorphsAtoB = [IsoRename "emp" "employee",
58+ let isomorphsAtoB = [IsoRename "emp" "employee",
58 IsoRename "department" "department"]
59 IsoRename "department" "department"]
59− unionExpr = Union (RelationVariable "emp" ()) (RelationVariable "department" ())
60+ unionExpr = Union (RelationVariable "emp" ()) (RelationVariable "department" ())
61+ env = mkRelationalExprEnv ctx graph
60 relExpr <- assertEither (applyRelationalExprSchemaIsomorphs isomorphsAtoB unionExpr)
62 relExpr <- assertEither (applyRelationalExprSchemaIsomorphs isomorphsAtoB unionExpr)
61− let relResult = runReader (evalRelationalExpr relExpr) schemaA
63+ let relResult = optimizeAndEvalRelationalExpr env relExpr
62 assertEqual "employee relation morph" (Right relationTrue) relResult
64 assertEqual "employee relation morph" (Right relationTrue) relResult
63
65
64testIsoRestrict :: Test
66testIsoRestrict :: Test
@@ -67,62 +69,70 @@ testIsoRestrict = TestCase $ do
67 -- the virtual schema has an employee
69 -- the virtual schema has an employee
68 let empattrs = A.attributesFromList [Attribute "name" TextAtomType,
70 let empattrs = A.attributesFromList [Attribute "name" TextAtomType,
69 Attribute "boss" TextAtomType]
71 Attribute "boss" TextAtomType]
72+ (graph, transId) <- freshTransactionGraph DBC.empty
70 emprel <- assertEither $ mkRelationFromList empattrs
73 emprel <- assertEither $ mkRelationFromList empattrs
71 [[TextAtom "Steve", TextAtom ""],
74 [[TextAtom "Steve", TextAtom ""],
72 [TextAtom "Cindy", TextAtom "Steve"],
75 [TextAtom "Cindy", TextAtom "Steve"],
73 [TextAtom "Sam", TextAtom "Steve"]]
76 [TextAtom "Sam", TextAtom "Steve"]]
74 let predicate = AttributeEqualityPredicate "boss" (NakedAtomExpr (TextAtom ""))
77 let predicate = AttributeEqualityPredicate "boss" (NakedAtomExpr (TextAtom ""))
78+ reenv = mkRelationalExprEnv DBC.empty graph
75− bossRel <- assertEither $ runReader (evalRelationalExpr (Restrict predicate (ExistingRelation emprel))) (mkRelationalExprState DBC.empty)
79+ bossRel <- assertEither $ runRelationalExprM reenv (evalRelationalExpr (Restrict predicate (ExistingRelation emprel)))
76− nonBossRel <- assertEither $ runReader (evalRelationalExpr (Restrict (NotPredicate predicate) (ExistingRelation emprel))) (mkRelationalExprState DBC.empty)
80+ nonBossRel <- assertEither $ runRelationalExprM reenv (evalRelationalExpr (Restrict (NotPredicate predicate) (ExistingRelation emprel)))
77
81
78− let schemaA = mkRelationalExprState DBC.empty {
82+ let schemaA = mkRelationalExprEnv baseContext graph
83+ baseContext = DBC.empty {
79− relationVariables = M.fromList [("nonboss", nonBossRel),
84+ relationVariables = M.fromList [("nonboss", ExistingRelation nonBossRel),
80− ("boss", bossRel)]
85+ ("boss", ExistingRelation bossRel)]
81 }
86 }
82−
83 isomorphsAtoB = [IsoRestrict "employee" predicate ("boss", "nonboss")]
87 isomorphsAtoB = [IsoRestrict "employee" predicate ("boss", "nonboss")]
84 bossq = RelationVariable "boss" ()
88 bossq = RelationVariable "boss" ()
85 nonbossq = RelationVariable "nonboss" ()
89 nonbossq = RelationVariable "nonboss" ()
86 employeeq = RelationVariable "employee" ()
90 employeeq = RelationVariable "employee" ()
87 unionq = Union bossq nonbossq
91 unionq = Union bossq nonbossq
88 empExpr <- assertEither (applyRelationalExprSchemaIsomorphs isomorphsAtoB employeeq)
92 empExpr <- assertEither (applyRelationalExprSchemaIsomorphs isomorphsAtoB employeeq)
89− let empResult = runReader (evalRelationalExpr empExpr) schemaA
93+ let empResult = evalRelExpr (evalRelationalExpr empExpr)
90− unionResult = runReader (evalRelationalExpr unionq) schemaA
94+ unionResult = evalRelExpr (evalRelationalExpr unionq)
95+ evalRelExpr = runRelationalExprM schemaA
91 assertEqual "boss/nonboss isorestrict" unionResult empResult
96 assertEqual "boss/nonboss isorestrict" unionResult empResult
92 --execute database context expr
97 --execute database context expr
93 bobRel <- assertEither (mkRelationFromList empattrs [[TextAtom "Bob", TextAtom ""]])
98 bobRel <- assertEither (mkRelationFromList empattrs [[TextAtom "Bob", TextAtom ""]])
94 let schemaBInsertExpr = Insert "employee" (ExistingRelation bobRel)
99 let schemaBInsertExpr = Insert "employee" (ExistingRelation bobRel)
95 schemaBInsertExpr' <- assertEither (processDatabaseContextExprInSchema (Schema isomorphsAtoB) schemaBInsertExpr)
100 schemaBInsertExpr' <- assertEither (processDatabaseContextExprInSchema (Schema isomorphsAtoB) schemaBInsertExpr)
96− let (postInsertContext,_,_) = execState (evalDatabaseContextExpr schemaBInsertExpr') (freshDatabaseState (stateElemsContext schemaA))
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
97− expectedRel = runReader (evalRelationalExpr (Union (RelationVariable "boss" ()) (RelationVariable "nonboss" ()))) (mkRelationalExprState postInsertContext)
105+ expectedRel = runRelationalExprM postInsertEnv (evalRelationalExpr (Union (RelationVariable "boss" ()) (RelationVariable "nonboss" ())))
106+ postInsertEnv = mkRelationalExprEnv postInsertContext graph
98 --execute the expression against the schema and compare against the base context
107 --execute the expression against the schema and compare against the base context
99 processedExpr <- assertEither (processRelationalExprInSchema (Schema isomorphsAtoB) (RelationVariable "employee" ()))
108 processedExpr <- assertEither (processRelationalExprInSchema (Schema isomorphsAtoB) (RelationVariable "employee" ()))
100− let processedRel = runReader (evalRelationalExpr processedExpr) (mkRelationalExprState postInsertContext)
109+ let processedRel = runRelationalExprM postInsertEnv (evalRelationalExpr processedExpr)
101 assertEqual "insert bob boss" expectedRel processedRel
110 assertEqual "insert bob boss" expectedRel processedRel
102
111
103testIsoUnion :: Test
112testIsoUnion :: Test
104testIsoUnion = TestCase $ do
113testIsoUnion = TestCase $ do
105 --create motors relation which is split into low-power (<50 horsepower) and high-power (>=50 horsepower) motors
114 --create motors relation which is split into low-power (<50 horsepower) and high-power (>=50 horsepower) motors
106 --the schema is contains the split relvars
115 --the schema is contains the split relvars
116+ (graph, _) <- freshTransactionGraph DBC.empty
107 motorsRel <- assertEither $ mkRelationFromList (A.attributesFromList [Attribute "name" TextAtomType,
117 motorsRel <- assertEither $ mkRelationFromList (A.attributesFromList [Attribute "name" TextAtomType,
108− Attribute "power" IntAtomType])
118+ Attribute "power" IntegerAtomType])
109− [[TextAtom "Puny", IntAtom 10],
119+ [[TextAtom "Puny", IntegerAtom 10],
110− [TextAtom "Scooter", IntAtom 49],
120+ [TextAtom "Scooter", IntegerAtom 49],
111− [TextAtom "Auto", IntAtom 200],
121+ [TextAtom "Auto", IntegerAtom 200],
112− [TextAtom "Tractor", IntAtom 500]]
122+ [TextAtom "Tractor", IntegerAtom 500]]
113− let baseSchema = mkRelationalExprState DBC.basicDatabaseContext {
123+ let env = mkRelationalExprEnv DBC.basicDatabaseContext {
114− relationVariables = M.singleton "motor" motorsRel
124+ relationVariables = M.singleton "motor" (ExistingRelation motorsRel)
115− }
125+ } graph
116− splitPredicate = AtomExprPredicate (FunctionAtomExpr "lt" [AttributeAtomExpr "power", NakedAtomExpr (IntAtom 50)] ())
126+ splitPredicate = AtomExprPredicate (FunctionAtomExpr "lt" [AttributeAtomExpr "power", NakedAtomExpr (IntegerAtom 50)] ())
117 splitIsomorphs = [IsoUnion ("lowpower", "highpower") splitPredicate "motor",
127 splitIsomorphs = [IsoUnion ("lowpower", "highpower") splitPredicate "motor",
118 IsoRename "true" "true",
128 IsoRename "true" "true",
119 IsoRename "false" "false"]
129 IsoRename "false" "false"]
120− lowmotors = runReader (evalRelationalExpr (Restrict splitPredicate (RelationVariable "motor" ()))) baseSchema
130+ lowmotors = runRelationalExprM env (evalRelationalExpr (Restrict splitPredicate (RelationVariable "motor" ())))
121− highmotors = runReader (evalRelationalExpr (Restrict (NotPredicate splitPredicate) (RelationVariable "motor" ()))) baseSchema
131+ highmotors = runRelationalExprM env (evalRelationalExpr (Restrict (NotPredicate splitPredicate) (RelationVariable "motor" ())))
122− relResult expr = runReader (evalRelationalExpr expr) baseSchema
132+ relResult expr = runRelationalExprM env (evalRelationalExpr expr)
123 lowpowerExpr <- assertEither (processRelationalExprInSchema (Schema splitIsomorphs) (RelationVariable "lowpower" ()))
133 lowpowerExpr <- assertEither (processRelationalExprInSchema (Schema splitIsomorphs) (RelationVariable "lowpower" ()))
124 lowpowerRel <- assertEither (relResult lowpowerExpr)
134 lowpowerRel <- assertEither (relResult lowpowerExpr)
125 highpowerExpr <- assertEither (processRelationalExprInSchema (Schema splitIsomorphs) (RelationVariable "highpower" ()))
135 highpowerExpr <- assertEither (processRelationalExprInSchema (Schema splitIsomorphs) (RelationVariable "highpower" ()))
126 highpowerRel <- assertEither (relResult highpowerExpr)
136 highpowerRel <- assertEither (relResult highpowerExpr)
127 assertEqual "lowpower relation difference" (Right lowpowerRel) lowmotors
137 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+67−5
@@ -1,5 +1,5 @@
1--Test Atomable typeclass which allows users to use existing Haskell datatypes to marshal them to and from the database as ConstructedAtoms.
1--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 #-}
3import Test.HUnit
3import Test.HUnit
4import ProjectM36.Client
4import ProjectM36.Client
5import Data.Binary
5import Data.Binary
@@ -31,6 +31,9 @@ data Test4T = Test4Ca Integer |
31data TestListT = TestListC [Integer]
31data TestListT = TestListC [Integer]
32 deriving (Show, Generic, Eq, Binary, NFData, Atomable)
32 deriving (Show, Generic, Eq, Binary, NFData, Atomable)
33
33
34+data TestNonEmptyT = TestNonEmptyC [Integer]
35+ deriving (Show, Generic, Eq, Binary, NFData, Atomable)
36+
34data Test5T = Test5C {
37data Test5T = Test5C {
35 con1 :: Integer,
38 con1 :: Integer,
36 con2 :: Integer
39 con2 :: Integer
@@ -41,14 +44,38 @@ data Test6T = Test6C (Maybe Integer)
41
44
42data Test7T = Test7C (Either Integer Integer)
45data Test7T = Test7C (Either Integer Integer)
43 deriving (Show, Generic, Eq, Binary, NFData, Atomable)
46 deriving (Show, Generic, Eq, Binary, NFData, Atomable)
44−
47+
48+data Test8T = Test8C Test1T
49+ deriving (Show, Generic, Eq, Binary, NFData, Atomable)
50+
51+data User = User
52+ { userFirstName :: Text
53+ , userLastName :: Text
54+ } deriving (Eq, Ord, Show, Generic, NFData, Binary, Atomable)
55+
56+data Test9_4T = Test9_4C {
57+ f9_41 :: Int,
58+ f9_42 :: Int,
59+ f9_43 :: Int,
60+ f9_44 :: Int }
61+ deriving (Show, Generic, Eq, Binary, NFData, Atomable)
62+
63+data Test9_5T = Test9_5C {
64+ f9_51 :: Int,
65+ f9_52 :: Int,
66+ f9_53 :: Int,
67+ f9_54 :: Int,
68+ f9_55 :: Int
69+ }
70+ deriving (Show, Generic, Eq, Binary, NFData, Atomable)
71+
45main :: IO ()
72main :: IO ()
46main = do
73main = do
47 tcounts <- runTestTT testList
74 tcounts <- runTestTT testList
48 if errors tcounts + failures tcounts > 0 then exitFailure else exitSuccess
75 if errors tcounts + failures tcounts > 0 then exitFailure else exitSuccess
49
76
50testList :: Test
77testList :: Test
51−testList = TestList [testHaskell2DB, testADT1, testADT2, testADT3, testADT4, testADT5, testBasicMarshaling, testListInstance, testADT6Maybe, testADT7Either]
78+testList = TestList [testHaskell2DB, testADT1, testADT2, testADT3, testADT4, testADT5, testBasicMarshaling, testSimpleList, testListInstance, testNonEmptyInstance, testADT6Maybe, testADT7Either, testNonPrimitiveValues, testRecordType, testManyFields]
52
79
53-- test some basic data types like int, day, etc.
80-- test some basic data types like int, day, etc.
54testBasicMarshaling :: Test
81testBasicMarshaling :: Test
@@ -77,7 +104,7 @@ testHaskell2DB = TestCase $ do
77 let createRelExpr = Assign "x" rel
104 let createRelExpr = Assign "x" rel
78
105
79 rel = MakeRelationFromExprs Nothing
106 rel = MakeRelationFromExprs Nothing
80− [TupleExpr (M.singleton "a1" (NakedAtomExpr atomVal))]
107+ (TupleExprs () [TupleExpr (M.singleton "a1" (NakedAtomExpr atomVal))])
81 atomVal = toAtom exampleVal
108 atomVal = toAtom exampleVal
82 exampleVal = Test1C 10
109 exampleVal = Test1C 10
83 checkExecuteDatabaseContextExpr sessionId dbconn createRelExpr
110 checkExecuteDatabaseContextExpr sessionId dbconn createRelExpr
@@ -131,4 +158,39 @@ checkExecuteDatabaseContextExpr sessionId dbconn expr = executeDatabaseContextEx
131testListInstance :: Test
158testListInstance :: Test
132testListInstance = TestCase $ do
159testListInstance = TestCase $ do
133 let example = TestListC [3,4,5]
160 let example = TestListC [3,4,5]
134− assertEqual "List instance" example (fromAtom (toAtom example))
161+ assertEqual "List instance" example (fromAtom (toAtom example))
162+
163+testSimpleList :: Test
164+testSimpleList = TestCase $ do
165+ let example = toAtom @[Integer] [1,2,3]
166+ 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)])) []]]]
167+ assertEqual "simple list" expected example
168+
169+testNonEmptyInstance :: Test
170+testNonEmptyInstance = TestCase $ do
171+ let example = TestNonEmptyC [3,4,5]
172+ assertEqual "NonEmpty instance" example (fromAtom (toAtom example))
173+
174+testNonPrimitiveValues :: Test
175+testNonPrimitiveValues = TestCase $ do
176+ let example = Test8C (Test1C 3)
177+ assertEqual "non-primitive values" example (fromAtom (toAtom example))
178+
179+testRecordType :: Test
180+testRecordType = TestCase $ do
181+ let example = User { userFirstName = "Bob"
182+ ,userLastName = "Smith"
183+ }
184+ assertEqual "User record" example (fromAtom (toAtom example))
185+ let expected = AddTypeConstructor (ADTypeConstructorDef "User" []) [DataConstructorDef "User" [DataConstructorDefTypeConstructorArg (PrimitiveTypeConstructor "Text" TextAtomType),DataConstructorDefTypeConstructorArg (PrimitiveTypeConstructor "Text" TextAtomType)]]
186+
187+ assertEqual "User record to database context expr" expected (toAddTypeExpr (Proxy :: Proxy User))
188+
189+--test both odd and even product types with more than 2 fields
190+testManyFields :: Test
191+testManyFields = TestCase $ do
192+ let example4 = Test9_4C 1 2 3 4
193+ assertEqual "four fields product type" example4 (fromAtom (toAtom example4))
194+
195+ let example5 = Test9_5C 1 2 3 4 5
196+ assertEqual "five fields product type" example5 (fromAtom (toAtom example5))
test/Relation/Basic.hs+18−6
@@ -7,9 +7,9 @@ import ProjectM36.TupleSet
7import ProjectM36.Attribute hiding (null, attributeNames)
7import ProjectM36.Attribute hiding (null, attributeNames)
8import ProjectM36.DataTypes.Primitive
8import ProjectM36.DataTypes.Primitive
9import ProjectM36.RelationalExpression
9import ProjectM36.RelationalExpression
10+import ProjectM36.TransactionGraph
10import ProjectM36.Tuple
11import ProjectM36.Tuple
11import qualified ProjectM36.DatabaseContext as DBC
12import qualified ProjectM36.DatabaseContext as DBC
12−import Control.Monad.Trans.Reader
13import qualified ProjectM36.Attribute as A
13import qualified ProjectM36.Attribute as A
14import qualified Data.Map as M
14import qualified Data.Map as M
15import qualified Data.Vector as V
15import qualified Data.Vector as V
@@ -25,7 +25,8 @@ testList = TestList [testRelation "relationTrue" relationTrue, testRelation "rel
25 testRelation "products" productsRel,
25 testRelation "products" productsRel,
26 testRelation "supplierProducts" supplierProductsRel,
26 testRelation "supplierProducts" supplierProductsRel,
27 testMkRelationFromExprsBadAttrs,
27 testMkRelationFromExprsBadAttrs,
28− testDuplicateAttributes
28+ testDuplicateAttributes,
29+ testExistingRelationType
29 ]
30 ]
30
31
31main :: IO ()
32main :: IO ()
@@ -63,7 +64,7 @@ validateAttrTypesMatchTupleAttrTypes rel@(Relation attrs tupSet) = foldr (\tuple
63 tupleAtomCheck tuple = V.all (== True) (attrChecks tuple)
64 tupleAtomCheck tuple = V.all (== True) (attrChecks tuple)
64 attrChecks tuple = V.map (\attr -> case atomForAttributeName (A.attributeName attr) tuple of
65 attrChecks tuple = V.map (\attr -> case atomForAttributeName (A.attributeName attr) tuple of
65 Left _ -> False
66 Left _ -> False
66− Right atom -> (Right $ atomTypeForAtom atom) ==
67+ Right atom -> Right (atomTypeForAtom atom) ==
67 A.atomTypeForAttributeName (A.attributeName attr) attrs) (attributes rel)
68 A.atomTypeForAttributeName (A.attributeName attr) attrs) (attributes rel)
68
69
69simpleRel :: Relation
70simpleRel :: Relation
@@ -93,8 +94,12 @@ testMkRelation1 = TestCase $ assertEqual "key mismatch" expectedError (mkRelatio
93
94
94testMkRelationFromExprsBadAttrs :: Test
95testMkRelationFromExprsBadAttrs :: Test
95testMkRelationFromExprsBadAttrs = TestCase $ do
96testMkRelationFromExprsBadAttrs = TestCase $ do
96− let context = DBC.empty
97+ let context = DBC.empty
98+ (graph,_) <- freshTransactionGraph context
99+ let reenv = mkRelationalExprEnv context graph
97− case runReader (evalRelationalExpr (MakeRelationFromExprs (Just [AttributeAndTypeNameExpr "badAttr1" (PrimitiveTypeConstructor "Int" IntAtomType) ()]) [TupleExpr (M.singleton "badAttr2" (NakedAtomExpr (IntAtom 1)))])) (mkRelationalExprState context) of
100+ reExpr = MakeRelationFromExprs (Just [AttributeAndTypeNameExpr "badAttr1" (PrimitiveTypeConstructor "Int" IntAtomType) ()]) (TupleExprs () [TupleExpr (M.singleton "badAttr2" (NakedAtomExpr (IntAtom 1)))])
101+ evald = runRelationalExprM reenv (evalRelationalExpr reExpr)
102+ case evald of
98 Left err -> assertEqual "tuple type mismatch" (TupleAttributeTypeMismatchError (A.attributesFromList [Attribute "badAttr2" IntAtomType])) err
103 Left err -> assertEqual "tuple type mismatch" (TupleAttributeTypeMismatchError (A.attributesFromList [Attribute "badAttr2" IntAtomType])) err
99 Right _ -> assertFailure "expected tuple type mismatch"
104 Right _ -> assertFailure "expected tuple type mismatch"
100
105
@@ -103,4 +108,11 @@ testDuplicateAttributes :: Test
103testDuplicateAttributes = TestCase $ do
108testDuplicateAttributes = TestCase $ do
104 let eRel = mkRelation attrs emptyTupleSet
109 let eRel = mkRelation attrs emptyTupleSet
105 attrs = attributesFromList [Attribute "a" IntAtomType, Attribute "a" TextAtomType]
110 attrs = attributesFromList [Attribute "a" IntAtomType, Attribute "a" TextAtomType]
106− assertEqual "duplicate attribute names" (Left (DuplicateAttributeNamesError (S.singleton "a"))) eRel
111+ assertEqual "duplicate attribute names" (Left (DuplicateAttributeNamesError (S.singleton "a"))) eRel
112+
113+testExistingRelationType :: Test
114+testExistingRelationType = TestCase $ do
115+ (graph, _) <- freshTransactionGraph dateExamples
116+ let typeResult = runRelationalExprM reenv (typeForRelationalExpr (ExistingRelation relationTrue))
117+ reenv = mkRelationalExprEnv dateExamples graph
118+ assertEqual "ExistingRelation with tuples type" (Right relationFalse) typeResult
test/Relation/Export/CSV.hs+23−18
@@ -1,3 +1,5 @@
1+{-# LANGUAGE CPP #-}
2+
1import ProjectM36.Base
3import ProjectM36.Base
2import ProjectM36.Relation.Show.CSV
4import ProjectM36.Relation.Show.CSV
3import ProjectM36.Relation.Parse.CSV
5import ProjectM36.Relation.Parse.CSV
@@ -11,7 +13,11 @@ import System.Exit
11import Test.HUnit
13import Test.HUnit
12import Data.Time.Calendar
14import Data.Time.Calendar
13import Data.Time.Clock
15import Data.Time.Clock
16+
17+#if __GLASGOW_HASKELL__ < 804
14import Data.Monoid
18import Data.Monoid
19+#endif
20+
15{-
21{-
16import qualified Data.Text.Lazy as TL
22import qualified Data.Text.Lazy as TL
17import qualified Data.Text.Lazy.Encoding as TE
23import qualified Data.Text.Lazy.Encoding as TE
@@ -19,9 +25,9 @@ import ProjectM36.Relation.Show.Term
19import qualified Data.ByteString.Lazy as BS
25import qualified Data.ByteString.Lazy as BS
20-}
26-}
21
27
22−main :: IO ()
28+main :: IO ()
23−main = do
29+main = do
24− tcounts <- runTestTT $ TestList [testCSVExport,
30+ tcounts <- runTestTT $ TestList [testCSVExport,
25 testADTExport]
31 testADTExport]
26 if errors tcounts + failures tcounts > 0 then exitFailure else exitSuccess
32 if errors tcounts + failures tcounts > 0 then exitFailure else exitSuccess
27
33
@@ -31,8 +37,8 @@ assertEither x = do
31 case res of
37 case res of
32 Left err -> assertFailure (show err) >> undefined
38 Left err -> assertFailure (show err) >> undefined
33 Right val -> pure val
39 Right val -> pure val
34−
40+
35−testADTExport :: Test
41+testADTExport :: Test
36testADTExport = TestCase $ do
42testADTExport = TestCase $ do
37 let adtCSV = "a\nCons 4 (Cons 5 Empty)\n"
43 let adtCSV = "a\nCons 4 (Cons 5 Empty)\n"
38 attrs = A.attributesFromList [Attribute "a" (listAtomType IntegerAtomType)]
44 attrs = A.attributesFromList [Attribute "a" (listAtomType IntegerAtomType)]
@@ -40,17 +46,17 @@ testADTExport = TestCase $ do
40 case csvAsRelation attrs basicTypeConstructorMapping adtCSV of
46 case csvAsRelation attrs basicTypeConstructorMapping adtCSV of
41 Left err -> assertFailure ("import failure: " <> show err)
47 Left err -> assertFailure ("import failure: " <> show err)
42 Right rel -> assertEqual "import cons list" expectedRel (Right rel)
48 Right rel -> assertEqual "import cons list" expectedRel (Right rel)
43−
49+
44--round-trip various atom types through CSV export/import
50--round-trip various atom types through CSV export/import
45testCSVExport :: Test
51testCSVExport :: Test
46testCSVExport = TestCase $ do
52testCSVExport = TestCase $ do
47 now <- getCurrentTime
53 now <- getCurrentTime
48− testInterval <- assertEither $ pure (createInterval
54+ testInterval <- assertEither $ pure (createInterval
49− (DateTimeAtom now)
55+ (DateTimeAtom now)
50 (DateTimeAtom (addUTCTime 86400 now))
56 (DateTimeAtom (addUTCTime 86400 now))
51 True
57 True
52 False)
58 False)
53− let attrs = A.attributesFromList [Attribute "textattr" TextAtomType,
59+ let attrs = A.attributesFromList [Attribute "textattr" TextAtomType,
54 Attribute "integerattr" IntegerAtomType,
60 Attribute "integerattr" IntegerAtomType,
55 Attribute "dayattr" DayAtomType,
61 Attribute "dayattr" DayAtomType,
56 Attribute "datetimeattr" DateTimeAtomType,
62 Attribute "datetimeattr" DateTimeAtomType,
@@ -61,8 +67,8 @@ testCSVExport = TestCase $ do
61 ]
67 ]
62 sampleByteString = "\1\0\244\34\150"
68 sampleByteString = "\1\0\244\34\150"
63 relOrErr = mkRelationFromList attrs [
69 relOrErr = mkRelationFromList attrs [
64− [TextAtom "text atom with \"quote\"",
70+ [TextAtom "text atom with \"quote\"",
65− IntegerAtom 123,
71+ IntegerAtom 123,
66 DayAtom (fromGregorian 2017 4 10),
72 DayAtom (fromGregorian 2017 4 10),
67 DateTimeAtom now,
73 DateTimeAtom now,
68 ByteStringAtom sampleByteString,
74 ByteStringAtom sampleByteString,
@@ -70,19 +76,19 @@ testCSVExport = TestCase $ do
70 listCons TextAtomType [TextAtom "text1", TextAtom "text2"],
76 listCons TextAtomType [TextAtom "text1", TextAtom "text2"],
71 testInterval
77 testInterval
72 ],
78 ],
73− [TextAtom "second text atom with 漢字",
79+ [TextAtom "second text atom with 漢字",
74− IntegerAtom 314,
80+ IntegerAtom 314,
75 DayAtom (fromGregorian 1001 6 28),
81 DayAtom (fromGregorian 1001 6 28),
76 DateTimeAtom (addUTCTime 360 now),
82 DateTimeAtom (addUTCTime 360 now),
77− ByteStringAtom sampleByteString,
83+ ByteStringAtom sampleByteString,
78 listCons IntegerAtomType [IntegerAtom 10, IntegerAtom 11, IntegerAtom 12],
84 listCons IntegerAtomType [IntegerAtom 10, IntegerAtom 11, IntegerAtom 12],
79 listCons TextAtomType [TextAtom "text5\"", TextAtom "text6\r\n"],
85 listCons TextAtomType [TextAtom "text5\"", TextAtom "text6\r\n"],
80 testInterval
86 testInterval
81 ]]
87 ]]
82−
88+
83− case relOrErr of
89+ case relOrErr of
84 Left err -> assertFailure $ "export relation creation failure: " ++ show err
90 Left err -> assertFailure $ "export relation creation failure: " ++ show err
85− Right rel ->
91+ Right rel ->
86 case relationAsCSV rel of
92 case relationAsCSV rel of
87 Left err -> assertFailure $ "export failed: " ++ show err
93 Left err -> assertFailure $ "export failed: " ++ show err
88 Right csvData ->
94 Right csvData ->
@@ -91,4 +97,3 @@ testCSVExport = TestCase $ do
91 case csvAsRelation attrs basicTypeConstructorMapping csvData of -- import csv data back to relation
97 case csvAsRelation attrs basicTypeConstructorMapping csvData of -- import csv data back to relation
92 Left err -> assertFailure $ "re-import failed: " ++ show err
98 Left err -> assertFailure $ "re-import failed: " ++ show err
93 Right rel' -> assertEqual "relation CSV comparison" rel rel'
99 Right rel' -> assertEqual "relation CSV comparison" rel rel'
94−
test/Relation/StaticOptimizer.hs+76−51
@@ -1,13 +1,12 @@
1import ProjectM36.Base
1import ProjectM36.Base
2import ProjectM36.Relation
2import ProjectM36.Relation
3−import ProjectM36.RelationalExpression
3+import ProjectM36.TransactionGraph
4import ProjectM36.DateExamples
4import ProjectM36.DateExamples
5−import ProjectM36.Error
6import ProjectM36.TupleSet
5import ProjectM36.TupleSet
7import ProjectM36.StaticOptimizer
6import ProjectM36.StaticOptimizer
7+import ProjectM36.DatabaseContext as DBC
8import System.Exit
8import System.Exit
9import Control.Monad.State
9import Control.Monad.State
10−import Control.Monad.Trans.Reader
11import Test.HUnit
10import Test.HUnit
12import qualified Data.Set as S
11import qualified Data.Set as S
13
12
@@ -16,100 +15,126 @@ main = do
16 tcounts <- runTestTT (TestList tests)
15 tcounts <- runTestTT (TestList tests)
17 if errors tcounts + failures tcounts > 0 then exitFailure else exitSuccess
16 if errors tcounts + failures tcounts > 0 then exitFailure else exitSuccess
18 where
17 where
19− tests = relationOptTests ++ databaseOptTests ++ [testTransitiveOptimization,
18+ tests = [testTransitiveOptimization,
20− testImpossiblePredicates,
19+ testImpossiblePredicates,
21− testJoinElimination,
20+ testJoinElimination,
22− testRestrictionPredicateCollapse,
21+ testRestrictionPredicateCollapse,
23− testPushDownRestrictionPredicate]
22+ testPushDownRestrictionPredicate,
24− optDBCTest = map (\(name, expr, unopt) -> TestCase $ assertEqual name expr (evalState (applyStaticDatabaseOptimization unopt) (freshDatabaseState dateExamples)))
23+ testOptimizeRelationalExpr,
25− relvar nam = RelationVariable nam ()
24+ testOptimizeDatabaseContextExpr]
26− startState = mkRelationalExprState dateExamples
25+
27− optRelTest = map (\(name, expr, unopt) -> TestCase $ assertEqual name expr (runReader (applyStaticRelationalOptimization unopt) startState))
26+testOptimizeDatabaseContextExpr :: Test
28− relationOptTests = optRelTest [
27+testOptimizeDatabaseContextExpr = TestCase $ do
29− ("StaticProject", Right $ relvar "s", Project (AttributeNames (attributeNames suppliersRel)) (relvar "s")),
28+ (graph, transId) <- freshTransactionGraph DBC.empty
30− ("StaticUnion", Right $ relvar "s", Union (relvar "s") (relvar "s")),
29+ let relvar nam = RelationVariable nam ()
31− ("StaticJoin", Right $ relvar "s", Join (relvar "s") (relvar "s"))
30+ relvarId nam = RelationVariable nam UncommittedContextMarker
32− ]
31+ testInfos = [
33− databaseOptTests = optDBCTest [
34− ("StaticAssign",
32+ ("StaticAssign",
35− Right $ Assign "z" (relvar "s"),
33+ Right $ Assign "z" (relvarId "s"),
36− Assign "z" (Restrict TruePredicate (relvar "s"))
34+ Assign "z" (Restrict TruePredicate (relvar "s"))
37− ),
35+ ),
38− ("StaticMultipleExpr",
36+ ("StaticMultipleExpr",
39− Right $ MultipleExpr [Assign "z" (relvar "s"),
37+ Right $ MultipleExpr [Assign "z" (relvarId "s"),
40− Assign "z" (relvar "s")],
38+ Assign "z" (relvarId "s")],
41− MultipleExpr [Assign "z" (Restrict TruePredicate (relvar "s")),
39+ MultipleExpr [Assign "z" (Restrict TruePredicate (relvar "s")),
42− Assign "z" (Restrict TruePredicate (relvar "s"))])
40+ Assign "z" (Restrict TruePredicate (relvar "s"))])
43− ]
41+ ]
42+ forM_ testInfos $ \(name, expectedExpr, unoptExpr) -> do
43+ let optExpr = runGraphRefSOptDatabaseContextExprM transId dateExamples graph (optimizeDatabaseContextExpr unoptExpr)
44+ assertEqual name expectedExpr optExpr
44
45
45testTransitiveOptimization :: Test
46testTransitiveOptimization :: Test
46testTransitiveOptimization = TestCase $ do
47testTransitiveOptimization = TestCase $ do
48+ (graph, _) <- freshTransactionGraph dateExamples
47 let expr atomexpr = AndPredicate (AttributeEqualityPredicate "a" (NakedAtomExpr (IntegerAtom 300))) (AttributeEqualityPredicate "b" atomexpr)
49 let expr atomexpr = AndPredicate (AttributeEqualityPredicate "a" (NakedAtomExpr (IntegerAtom 300))) (AttributeEqualityPredicate "b" atomexpr)
48 exprIn = expr (AttributeAtomExpr "a")
50 exprIn = expr (AttributeAtomExpr "a")
49 exprOut = expr (NakedAtomExpr (IntegerAtom 300))
51 exprOut = expr (NakedAtomExpr (IntegerAtom 300))
52+ optExpr = runGraphRefSOptRelationalExprM Nothing graph (applyStaticPredicateOptimization exprIn)
50− assertEqual "transitive property" (Right exprOut) (runReader (applyStaticPredicateOptimization exprIn) (RelationalExprStateElems dateExamples))
53+ assertEqual "transitive property" (Right exprOut) optExpr
51−
54+
52−optRelExpr :: RelationalExpr -> Either RelationalError RelationalExpr
55+
53−optRelExpr expr = runReader (applyStaticRelationalOptimization expr) (RelationalExprStateElems dateExamples)
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
54
74
55testImpossiblePredicates :: Test
75testImpossiblePredicates :: Test
56testImpossiblePredicates = TestCase $ do
76testImpossiblePredicates = TestCase $ do
77+ (graph, _) <- freshTransactionGraph dateExamples
57 let tautTrue = Restrict (AtomExprPredicate (NakedAtomExpr (BoolAtom True))) rel
78 let tautTrue = Restrict (AtomExprPredicate (NakedAtomExpr (BoolAtom True))) rel
58 tautTrue2 = Restrict TruePredicate rel
79 tautTrue2 = Restrict TruePredicate rel
59 tautFalse = Restrict (AtomExprPredicate (NakedAtomExpr (BoolAtom False))) rel
80 tautFalse = Restrict (AtomExprPredicate (NakedAtomExpr (BoolAtom False))) rel
60 tautFalse2 = Restrict (NotPredicate TruePredicate) rel
81 tautFalse2 = Restrict (NotPredicate TruePredicate) rel
61 emptyRel = MakeStaticRelation (attributes suppliersRel) emptyTupleSet
82 emptyRel = MakeStaticRelation (attributes suppliersRel) emptyTupleSet
62− rel = RelationVariable "s" ()
83+ rel = RelationVariable "s" UncommittedContextMarker
84+ optRelExpr expr = optimizeGraphRefRelationalExpr' (Just dateExamples) graph expr
63 assertEqual "remove tautology where true" (Right rel) (optRelExpr tautTrue)
85 assertEqual "remove tautology where true" (Right rel) (optRelExpr tautTrue)
64 assertEqual "remove tautology where true2" (Right rel) (optRelExpr tautTrue2)
86 assertEqual "remove tautology where true2" (Right rel) (optRelExpr tautTrue2)
65 assertEqual "remove tautology where false" (Right emptyRel) (optRelExpr tautFalse)
87 assertEqual "remove tautology where false" (Right emptyRel) (optRelExpr tautFalse)
66 assertEqual "remove tautology where false2" (Right emptyRel) (optRelExpr tautFalse2)
88 assertEqual "remove tautology where false2" (Right emptyRel) (optRelExpr tautFalse2)
67−
68−optJoinExpr :: RelationalExpr -> Either RelationalError RelationalExpr
69−optJoinExpr expr = runReader (applyStaticJoinElimination expr) (RelationalExprStateElems dateExamples)
70
89
71testJoinElimination :: Test
90testJoinElimination :: Test
72testJoinElimination = TestCase $ do
91testJoinElimination = 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+
73 -- (s join sp){s#,qty,p#} == sp
97 -- (s join sp){s#,qty,p#} == sp
74− let unoptExpr = Project (AttributeNames (S.fromList ["p#", "qty", "s#"])) (Join (RelationVariable "sp" ()) (RelationVariable "s" ()))
98+ let unoptExpr = Project (AttributeNames (S.fromList ["p#", "qty", "s#"])) (Join (relvar "sp") (relvar "s"))
75− assertEqual "remove extraneous join" (Right (RelationVariable "sp" ())) (optJoinExpr unoptExpr)
99+ assertEqual "remove extraneous join" (Right (relvar "sp")) (optJoinExpr unoptExpr)
76
100
77-- (sp join s){s#,qty,p#} == sp --flip relvar names
101-- (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" ()))
102+ let unoptExpr2 = Project (AttributeNames (S.fromList ["p#", "qty", "s#"])) (Join (relvar "s") (relvar "sp"))
79− assertEqual "remove extraneous join2" (Right (RelationVariable "sp" ())) (optJoinExpr unoptExpr2)
103+ assertEqual "remove extraneous join2" (Right (relvar "sp")) (optJoinExpr unoptExpr2)
80
104
81-- (sp join s){s#,qty,sname} != sp - attribute from s included
105-- (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"))
83 assertEqual "retain join" (Right expr3) (optJoinExpr expr3)
107 assertEqual "retain join" (Right expr3) (optJoinExpr expr3)
84
108
85 -- (sp join s){qty} != sp --projection does not include foreign key attribute
109 -- (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"))
87 assertEqual "retain join2" (Right expr4) (optJoinExpr expr4)
111 assertEqual "retain join2" (Right expr4) (optJoinExpr expr4)
88
112
89 -- (sp join s){s#,qty} == sp - a subset of attributes in the projection are in the foreign key
113 -- (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" ()))
114+ let expr5 = Project (AttributeNames (S.fromList ["s#", "qty"])) (Join (relvar "sp") (relvar "s"))
91− let expect5 = Project (AttributeNames (S.fromList ["s#", "qty"])) (RelationVariable "sp" ())
115+ let expect5 = Project (AttributeNames (S.fromList ["s#", "qty"])) (relvar "sp")
92 assertEqual "remove extraneous join (attribute subset)" (Right expect5) (optJoinExpr expr5)
116 assertEqual "remove extraneous join (attribute subset)" (Right expect5) (optJoinExpr expr5)
93
117
94 -- (s join p){s#,p#} != sp -- no foreign key
118 -- (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"))
96 assertEqual "retain join- no foreign key" (Right expr6) (optJoinExpr expr6)
120 assertEqual "retain join- no foreign key" (Right expr6) (optJoinExpr expr6)
97
121
98 -- (s join p){s#,qty,p#,sname} != sp -- all sp attributes plus one s attributes
122 -- (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"))
100 assertEqual "retain join- attributes from both relvars" (Right expr7) (optJoinExpr expr7)
124 assertEqual "retain join- attributes from both relvars" (Right expr7) (optJoinExpr expr7)
101
125
102testRestrictionPredicateCollapse :: Test
126testRestrictionPredicateCollapse :: Test
103testRestrictionPredicateCollapse = TestCase $ do
127testRestrictionPredicateCollapse = TestCase $ do
104 let expr1 = Restrict (NotPredicate TruePredicate) rv
128 let expr1 = Restrict (NotPredicate TruePredicate) rv
105− rv = RelationVariable "a" ()
129+ rv = RelationVariable "a" UncommittedContextMarker
130+ relvar name = RelationVariable name UncommittedContextMarker
106 assertEqual "one restriction" expr1 (applyStaticRestrictionCollapse expr1)
131 assertEqual "one restriction" expr1 (applyStaticRestrictionCollapse expr1)
107
132
108 let attrEqualsPred = AttributeEqualityPredicate "x" (NakedAtomExpr (IntAtom 3))
133 let attrEqualsPred = AttributeEqualityPredicate "x" (NakedAtomExpr (IntAtom 3))
109− expr2 = Restrict TruePredicate (Restrict attrEqualsPred (RelationVariable "a" ()))
134+ expr2 = Restrict TruePredicate (Restrict attrEqualsPred (relvar "a"))
110− assertEqual "two restrictions" (Restrict (AndPredicate TruePredicate attrEqualsPred) (RelationVariable "a" ())) (applyStaticRestrictionCollapse expr2)
135+ assertEqual "two restrictions" (Restrict (AndPredicate TruePredicate attrEqualsPred) (relvar "a")) (applyStaticRestrictionCollapse expr2)
111
136
112− let expr3 = Restrict pred1 (Restrict pred2 (Restrict pred3 (RelationVariable "a" ())))
137+ let expr3 = Restrict pred1 (Restrict pred2 (Restrict pred3 (relvar "a")))
113 pred1 = NotPredicate TruePredicate
138 pred1 = NotPredicate TruePredicate
114 pred2 = attrEqualsPred
139 pred2 = attrEqualsPred
115 pred3 = AtomExprPredicate (NakedAtomExpr (BoolAtom True))
140 pred3 = AtomExprPredicate (NakedAtomExpr (BoolAtom True))
@@ -123,7 +148,7 @@ testRestrictionPredicateCollapse = TestCase $ do
123testPushDownRestrictionPredicate :: Test
148testPushDownRestrictionPredicate :: Test
124testPushDownRestrictionPredicate = TestCase $ do
149testPushDownRestrictionPredicate = TestCase $ do
125 -- (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)
150 -- (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
127 let status30 = AttributeEqualityPredicate "status" (NakedAtomExpr (IntAtom 30))
152 let status30 = AttributeEqualityPredicate "status" (NakedAtomExpr (IntAtom 30))
128 relationsOrError = do
153 relationsOrError = do
129 stevens <- mkRelationFromList (attributes suppliersRel) [[TextAtom "S6", TextAtom "Stevens", IntegerAtom 50, TextAtom "Boston"]]
154 stevens <- mkRelationFromList (attributes suppliersRel) [[TextAtom "S6", TextAtom "Stevens", IntegerAtom 50, TextAtom "Boston"]]
test/Relation/Tupleable.hs+171−5
@@ -1,13 +1,22 @@
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+ #-}
2import Test.HUnit
12import Test.HUnit
3−import ProjectM36.Tupleable
13+import ProjectM36.Tupleable.Deriving
4import ProjectM36.Atomable
14import ProjectM36.Atomable
5import ProjectM36.Attribute
15import ProjectM36.Attribute
6import ProjectM36.Error
16import ProjectM36.Error
7import Data.Binary
17import Data.Binary
8import ProjectM36.Base
18import ProjectM36.Base
9import Control.DeepSeq (NFData)
19import Control.DeepSeq (NFData)
10−import GHC.Generics
11import qualified Data.Vector as V
20import qualified Data.Vector as V
12import qualified Data.Map as M
21import qualified Data.Map as M
13import qualified Data.Text as T
22import qualified Data.Text as T
@@ -58,6 +67,13 @@ data Test9T = Test9C
58 attr9C :: Double
67 attr9C :: Double
59 }
68 }
60 deriving (Generic, Show, Eq)
69 deriving (Generic, Show, Eq)
70+
71+data Test10T = Test10C {
72+ longAttrNameA10 :: Integer,
73+ long_attr_name_b10 :: Integer,
74+ longMixed_attr_NameC10 :: Integer
75+ }
76+ deriving (Generic, Show, Eq)
61
77
62instance Tupleable Test1T
78instance Tupleable Test1T
63
79
@@ -83,7 +99,7 @@ main = do
83 if errors tcounts + failures tcounts > 0 then exitFailure else exitSuccess
99 if errors tcounts + failures tcounts > 0 then exitFailure else exitSuccess
84
100
85testList :: Test
101testList :: Test
86−testList = TestList [testADT1, testADT2, testADT3, testADT4, testADT6, testADT7, testADT8, testInsertExpr, testDefineExpr, testUpdateExpr, testUpdateExprEmptyAttrs, testDeleteExpr, testUpdateExprWrongAttr, testReorderedTuple]
102+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]
87
103
88testADT1 :: Test
104testADT1 :: Test
89testADT1 = TestCase $ assertEqual "one record constructor" (Right example) (fromTuple (toTuple example))
105testADT1 = TestCase $ assertEqual "one record constructor" (Right example) (fromTuple (toTuple example))
@@ -199,4 +215,154 @@ testReorderedTuple = TestCase $ do
199 expected = Test2C {attrB = 3,
215 expected = Test2C {attrB = 3,
200 attrC = 4}
216 attrC = 4}
201 actual = fromTuple . tupleRev . toTuple $ expected
217 actual = fromTuple . tupleRev . toTuple $ expected
202− assertEqual "reordered tuple" (Right expected) actual
218+ assertEqual "reordered tuple" (Right expected) actual
219+
220+testCodec :: forall tag. ModifyOptions tag => String -> [AttributeName] -> Test
221+testCodec msg expected = TestCase $
222+ assertEqual msg (S.fromList expected) actual
223+ where
224+ actual = attributeNameSet $ toAttributes (Proxy :: Proxy (Codec tag Test10T))
225+
226+testAddPrefixField :: Test
227+testAddPrefixField = testCodec
228+ @(Field (AddPrefix "prefix_"))
229+ "codec field add prefix attributes"
230+ ["prefix_longAttrNameA10",
231+ "prefix_long_attr_name_b10",
232+ "prefix_longMixed_attr_NameC10"]
233+
234+testDropPrefixField :: Test
235+testDropPrefixField = testCodec
236+ @(Field (DropPrefix "long"))
237+ "codec field drop prefix"
238+ ["AttrNameA10",
239+ "_attr_name_b10",
240+ "Mixed_attr_NameC10"]
241+
242+testAddSuffixField :: Test
243+testAddSuffixField = testCodec
244+ @(Field (AddSuffix "_suffix"))
245+ "codec field add suffix"
246+ ["longAttrNameA10_suffix",
247+ "long_attr_name_b10_suffix",
248+ "longMixed_attr_NameC10_suffix"]
249+
250+testDropSuffixField :: Test
251+testDropSuffixField = testCodec
252+ @(Field (DropSuffix "10"))
253+ "codec field drop suffix"
254+ ["longAttrNameA",
255+ "long_attr_name_b",
256+ "longMixed_attr_NameC"]
257+
258+testUpperCaseField :: Test
259+testUpperCaseField = testCodec
260+ @(Field UpperCase)
261+ "codec field uppercase"
262+ ["LONGATTRNAMEA10",
263+ "LONG_ATTR_NAME_B10",
264+ "LONGMIXED_ATTR_NAMEC10"]
265+
266+testLowerCaseField :: Test
267+testLowerCaseField = testCodec
268+ @(Field LowerCase)
269+ "codec field lowercase"
270+ ["longattrnamea10",
271+ "long_attr_name_b10",
272+ "longmixed_attr_namec10"]
273+
274+testTitleCaseField :: Test
275+testTitleCaseField = testCodec
276+ @(Field TitleCase)
277+ "codec field title case"
278+ ["Long Attr Name A10",
279+ "Long Attr Name B10",
280+ "Long Mixed Attr Name C10"]
281+
282+testCamelCaseField :: Test
283+testCamelCaseField = testCodec
284+ @(Field CamelCase)
285+ "codec field camel case"
286+ ["longAttrNameA10",
287+ "longAttrNameB10",
288+ "longMixedAttrNameC10"]
289+
290+testPascalCaseField :: Test
291+testPascalCaseField = testCodec
292+ @(Field PascalCase)
293+ "codec field pascal case"
294+ ["LongAttrNameA10",
295+ "LongAttrNameB10",
296+ "LongMixedAttrNameC10"]
297+
298+testSnakeCaseField :: Test
299+testSnakeCaseField = testCodec
300+ @(Field SnakeCase)
301+ "codec field snake case"
302+ ["long_attr_name_a10",
303+ "long_attr_name_b10",
304+ "long_mixed_attr_name_c10"]
305+
306+testSpinalCaseField :: Test
307+testSpinalCaseField = testCodec
308+ @(Field SpinalCase)
309+ "codec field spinal case"
310+ ["long-attr-name-a10",
311+ "long-attr-name-b10",
312+ "long-mixed-attr-name-c10"]
313+
314+testTrainCaseField :: Test
315+testTrainCaseField = testCodec
316+ @(Field TrainCase)
317+ "codec field train case"
318+ ["Long-Attr-Name-A10",
319+ "Long-Attr-Name-B10",
320+ "Long-Mixed-Attr-Name-C10"]
321+
322+testAsIsCodec :: Test
323+testAsIsCodec = testCodec
324+ @AsIs
325+ "codec as is"
326+ ["longAttrNameA10",
327+ "long_attr_name_b10",
328+ "longMixed_attr_NameC10"]
329+
330+testAsIsField :: Test
331+testAsIsField = testCodec
332+ @(Field AsIs)
333+ "codec field as is"
334+ ["longAttrNameA10",
335+ "long_attr_name_b10",
336+ "longMixed_attr_NameC10"]
337+
338+testComposeRLCodec :: Test
339+testComposeRLCodec = testCodec
340+ @(Field UpperCase <<< Field (DropPrefix "long"))
341+ "codec (<<<)"
342+ ["ATTRNAMEA10",
343+ "_ATTR_NAME_B10",
344+ "MIXED_ATTR_NAMEC10"]
345+
346+testComposeRLField :: Test
347+testComposeRLField = testCodec
348+ @(Field (UpperCase <<< DropPrefix "long"))
349+ "codec field (<<<)"
350+ ["ATTRNAMEA10",
351+ "_ATTR_NAME_B10",
352+ "MIXED_ATTR_NAMEC10"]
353+
354+testComposeLRCodec :: Test
355+testComposeLRCodec = testCodec
356+ @(Field (DropPrefix "long") >>> Field UpperCase)
357+ "codec (>>>)"
358+ ["ATTRNAMEA10",
359+ "_ATTR_NAME_B10",
360+ "MIXED_ATTR_NAMEC10"]
361+
362+testComposeLRField :: Test
363+testComposeLRField = testCodec
364+ @(Field (DropPrefix "long" >>> UpperCase))
365+ "codec field (>>>)"
366+ ["ATTRNAMEA10",
367+ "_ATTR_NAME_B10",
368+ "MIXED_ATTR_NAMEC10"]
test/Server/Main.hs+13−5
@@ -17,7 +17,13 @@ import System.Exit
17
17
18import Control.Concurrent
18import Control.Concurrent
19import Network.Transport (EndPointAddress)
19import Network.Transport (EndPointAddress)
20+
21+#if MIN_VERSION_network_transport_tcp(0,6,0)
22+import Network.Transport.TCP.Internal (encodeEndPointAddress, decodeEndPointAddress)
23+#else
20import Network.Transport.TCP (encodeEndPointAddress, decodeEndPointAddress)
24import Network.Transport.TCP (encodeEndPointAddress, decodeEndPointAddress)
25+#endif
26+
21import Data.Either (isRight)
27import Data.Either (isRight)
22import Control.Exception
28import Control.Exception
23import System.IO.Temp
29import System.IO.Temp
@@ -88,7 +94,8 @@ launchTestServer ti = do
88 persistenceStrategy = CrashSafePersistence (tempdir </> "db"),
94 persistenceStrategy = CrashSafePersistence (tempdir </> "db"),
89 perRequestTimeout = ti,
95 perRequestTimeout = ti,
90 testMode = True,
96 testMode = True,
91− bindPort = 0
97+ bindPort = 0,
98+ checkFS = False --not stricly needed for these tests
92 }
99 }
93
100
94 launchServer config (Just addressMVar) >> pure ()
101 launchServer config (Just addressMVar) >> pure ()
@@ -140,10 +147,11 @@ testPlanForDatabaseContextExpr sessionId conn = TestCase $ do
140 let attrExprs = [AttributeAndTypeNameExpr "x" (PrimitiveTypeConstructor "Int" IntAtomType) ()]
147 let attrExprs = [AttributeAndTypeNameExpr "x" (PrimitiveTypeConstructor "Int" IntAtomType) ()]
141 testrv = "testrv"
148 testrv = "testrv"
142 dbExpr = Define testrv attrExprs
149 dbExpr = Define testrv attrExprs
150+ expected = Define testrv [AttributeAndTypeNameExpr "x" (PrimitiveTypeConstructor "Int" IntAtomType) UncommittedContextMarker]
143 planResult <- planForDatabaseContextExpr sessionId conn dbExpr
151 planResult <- planForDatabaseContextExpr sessionId conn dbExpr
144 case planResult of
152 case planResult of
145 Left err -> assertFailure (show err)
153 Left err -> assertFailure (show err)
146− Right plan -> assertEqual "planForDatabaseContextExpr failure" dbExpr plan
154+ Right plan -> assertEqual "planForDatabaseContextExpr failure" expected plan
147
155
148testTransactionGraphAsRelation :: SessionId -> Connection -> Test
156testTransactionGraphAsRelation :: SessionId -> Connection -> Test
149testTransactionGraphAsRelation sessionId conn = TestCase $ do
157testTransactionGraphAsRelation sessionId conn = TestCase $ do
@@ -216,12 +224,12 @@ testFileDescriptorCount :: Test
216#if defined(linux_HOST_OS)
224#if defined(linux_HOST_OS)
217--validate that creating a server, connecting a client, and then disconnecting doesn't leak file descriptors
225--validate that creating a server, connecting a client, and then disconnecting doesn't leak file descriptors
218testFileDescriptorCount = TestCase $ do
226testFileDescriptorCount = TestCase $ do
219− (serverAddress, serverTid) <- launchTestServer 1000
227+ (serverAddress, serverTid) <- launchTestServer 0
220 unusedMVar <- newEmptyMVar
228 unusedMVar <- newEmptyMVar
221 startCount <- fdCount
229 startCount <- fdCount
222 Right (sess, testConn) <- testConnection serverAddress unusedMVar
230 Right (sess, testConn) <- testConnection serverAddress unusedMVar
223 --add a test commit to trigger the fsync machinery
231 --add a test commit to trigger the fsync machinery
224− executeDatabaseContextExpr sess testConn (Assign "x" (ExistingRelation relationFalse)) >>= eitherFail
232+ executeDatabaseContextExpr sess testConn (Assign "x" (ExistingRelation relationFalse)) >>= eitherFail
225 commit sess testConn >>= eitherFail
233 commit sess testConn >>= eitherFail
226 close testConn
234 close testConn
227 endCount <- fdCount
235 endCount <- fdCount
@@ -238,4 +246,4 @@ fdCount = do
238#else
246#else
239--pass on non-linux platforms
247--pass on non-linux platforms
240testFileDescriptorCount = TestCase (pure ())
248testFileDescriptorCount = TestCase (pure ())
241−#endif
249+#endif
test/Server/WebSocket.hs+11−3
@@ -1,3 +1,4 @@
1+{-# LANGUAGE CPP #-}
1-- test the websocket server
2-- test the websocket server
2import Test.HUnit
3import Test.HUnit
3import qualified Network.WebSockets as WS
4import qualified Network.WebSockets as WS
@@ -17,7 +18,12 @@ import Data.Aeson
17import qualified Data.Map as M
18import qualified Data.Map as M
18import qualified Data.ByteString.Lazy as BS
19import qualified Data.ByteString.Lazy as BS
19import ProjectM36.Relation
20import ProjectM36.Relation
21+#if MIN_VERSION_network_transport_tcp(0,6,0)
22+import Network.Transport.TCP.Internal (decodeEndPointAddress)
23+#else
20import Network.Transport.TCP (decodeEndPointAddress)
24import Network.Transport.TCP (decodeEndPointAddress)
25+#endif
26+
21
27
22--start the websocket server
28--start the websocket server
23-- run some tutoriald against it
29-- run some tutoriald against it
@@ -26,7 +32,8 @@ launchTestServer :: IO (PortNumber, DatabaseName)
26launchTestServer = do
32launchTestServer = do
27 addressMVar <- newEmptyMVar
33 addressMVar <- newEmptyMVar
28 let config = defaultServerConfig { databaseName = testDatabaseName,
34 let config = defaultServerConfig { databaseName = testDatabaseName,
29− bindPort = 0 }
35+ bindPort = 0,
36+ checkFS = False}
30 testDatabaseName = "test"
37 testDatabaseName = "test"
31 -- start normal server
38 -- start normal server
32 _ <- forkIO (launchServer config (Just addressMVar) >> pure ())
39 _ <- forkIO (launchServer config (Just addressMVar) >> pure ())
@@ -50,13 +57,14 @@ waitForListenSocket secondsToTry port =
50 if secondsToTry <= 0 then
57 if secondsToTry <= 0 then
51 throw WaitForSocketListenException
58 throw WaitForSocketListenException
52 else do
59 else do
53− hostaddr <- inet_addr "127.0.0.1"
60+ --hostaddr <- inet_addr "127.0.0.1"
61+ hostaddr:_ <- getAddrInfo Nothing (Just "127.0.0.1") (Just (show port))
54 sock <- socket AF_INET Stream defaultProtocol
62 sock <- socket AF_INET Stream defaultProtocol
55 let handler :: IOException -> IO ()
63 let handler :: IOException -> IO ()
56 handler _ = do
64 handler _ = do
57 threadDelay 1000000
65 threadDelay 1000000
58 waitForListenSocket (secondsToTry - 1) port
66 waitForListenSocket (secondsToTry - 1) port
59− catch (connect sock (SockAddrInet port hostaddr)) handler
67+ catch (connect sock (addrAddress hostaddr)) handler
60
68
61main :: IO ()
69main :: IO ()
62main = do
70main = do
test/TransactionGraph/Merge.hs+70−39
@@ -4,15 +4,28 @@ import ProjectM36.Base
4import ProjectM36.Attribute
4import ProjectM36.Attribute
5import ProjectM36.Relation
5import ProjectM36.Relation
6import ProjectM36.Transaction
6import ProjectM36.Transaction
7+import ProjectM36.TransactionInfo as TI
7import ProjectM36.TransactionGraph
8import ProjectM36.TransactionGraph
8import ProjectM36.Error
9import ProjectM36.Error
9import ProjectM36.Key
10import ProjectM36.Key
10import qualified ProjectM36.DisconnectedTransaction as Discon
11import qualified ProjectM36.DisconnectedTransaction as Discon
11import qualified ProjectM36.DatabaseContext as DBC
12import qualified ProjectM36.DatabaseContext as DBC
12import ProjectM36.RelationalExpression
13import ProjectM36.RelationalExpression
14+import ProjectM36.StaticOptimizer
13
15
14import qualified Data.ByteString.Lazy as BS
16import qualified Data.ByteString.Lazy as BS
15import System.Exit
17import System.Exit
18+
19+
20+
21+
22+
23+
24+
25+
26+
27+
28+
16import Data.Word
29import Data.Word
17import qualified Data.UUID as U
30import qualified Data.UUID as U
18import qualified Data.Set as S
31import qualified Data.Set as S
@@ -21,8 +34,6 @@ import Data.Maybe
21import Data.Time.Clock
34import Data.Time.Clock
22import Data.Time.Calendar
35import Data.Time.Calendar
23
36
24−import Control.Monad.State
25−
26{-# ANN module ("HLint: ignore Reduce duplication" :: String) #-}
37{-# ANN module ("HLint: ignore Reduce duplication" :: String) #-}
27
38
28testTime :: UTCTime
39testTime :: UTCTime
@@ -62,8 +73,8 @@ basicTransactionGraph = do
62 uuidB = fakeUUID 11
73 uuidB = fakeUUID 11
63 uuidRoot = fakeUUID 1
74 uuidRoot = fakeUUID 1
64 rootContext = concreteDatabaseContext rootTrans
75 rootContext = concreteDatabaseContext rootTrans
65− (_, bsGraph') <- addTransaction "branchA" (createTrans uuidA (TransactionInfo uuidRoot S.empty testTime) rootContext) bsGraph
76+ (_, bsGraph') <- addTransaction "branchA" (createTrans uuidA (TI.singleParent uuidRoot testTime) rootContext) bsGraph
66− (_, bsGraph'') <- addTransaction "branchB" (createTrans uuidB (TransactionInfo uuidRoot S.empty testTime) rootContext) bsGraph'
77+ (_, bsGraph'') <- addTransaction "branchB" (createTrans uuidB (TI.singleParent uuidRoot testTime) rootContext) bsGraph'
67 pure bsGraph''
78 pure bsGraph''
68
79
69addTransaction :: HeadName -> Transaction -> TransactionGraph -> IO (Transaction, TransactionGraph)
80addTransaction :: HeadName -> Transaction -> TransactionGraph -> IO (Transaction, TransactionGraph)
@@ -107,7 +118,7 @@ testSubGraphToFirstAncestorSnipBranch = TestCase $ do
107 baseGraph <- basicTransactionGraph
118 baseGraph <- basicTransactionGraph
108 transA <- assertMaybe (transactionForHead "branchA" baseGraph) "failed to get branchA"
119 transA <- assertMaybe (transactionForHead "branchA" baseGraph) "failed to get branchA"
109 transB <- assertMaybe (transactionForHead "branchB" baseGraph) "failed to get branchB"
120 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
111 subgraph <- assertEither $ subGraphOfFirstCommonAncestor graph (transactionHeadsForGraph baseGraph) transA transB S.empty
122 subgraph <- assertEither $ subGraphOfFirstCommonAncestor graph (transactionHeadsForGraph baseGraph) transA transB S.empty
112 assertGraph subgraph
123 assertGraph subgraph
113 let graphEq graphArg = S.map transactionId (transactionsForGraph graphArg)
124 let graphEq graphArg = S.map transactionId (transactionsForGraph graphArg)
@@ -121,16 +132,18 @@ testSubGraphToFirstAncestorMoreTransactions = TestCase $ do
121
132
122-- add another relvar to branchB
133-- add another relvar to branchB
123 branchBTrans <- assertMaybe (transactionForHead "branchB" graph) "failed to get branchB head"
134 branchBTrans <- assertMaybe (transactionForHead "branchB" graph) "failed to get branchB head"
135+ let env = mkDatabaseContextEvalEnv (transactionId branchBTrans) graph
136+ branchBContext = concreteDatabaseContext branchBTrans
124− (updatedBranchBContext,_,_) <- case runState (evalDatabaseContextExpr (Assign "branchBOnlyRelvar" (ExistingRelation relationTrue))) (freshDatabaseState (concreteDatabaseContext branchBTrans)) of
137+ updatedBranchBContext <- case runDatabaseContextEvalMonad branchBContext env (optimizeAndEvalDatabaseContextExpr True (Assign "branchBOnlyRelvar" (ExistingRelation relationTrue))) of
125− (Left err, _) -> assertFailure (show err) >> undefined
138+ Left err -> assertFailure (show err) >> undefined
126− (Right (), context) -> pure context
139+ Right st -> pure $ dbc_context st
127− (_, graph') <- addTransaction "branchB" (createTrans (fakeUUID 3) (TransactionInfo (transactionId branchBTrans) S.empty testTime) updatedBranchBContext) graph
140+ (_, graph') <- addTransaction "branchB" (createTrans (fakeUUID 3) (TI.singleParent (transactionId branchBTrans) testTime) updatedBranchBContext) graph
128 branchBTrans' <- assertMaybe (transactionForHead "branchB" graph') "failed to get branchB head"
141 branchBTrans' <- assertMaybe (transactionForHead "branchB" graph') "failed to get branchB head"
129 assertEqual "branchB id 3" (fakeUUID 3) (transactionId branchBTrans')
142 assertEqual "branchB id 3" (fakeUUID 3) (transactionId branchBTrans')
130
143
131 -- add another transaction to branchA
144 -- add another transaction to branchA
132 branchATrans <- assertMaybe (transactionForHead "branchA" graph) "failed to get branchA head"
145 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'
134 branchATrans' <- assertMaybe (transactionForHead "branchA" graph'') "failed to get branchA head"
147 branchATrans' <- assertMaybe (transactionForHead "branchA" graph'') "failed to get branchA head"
135 assertEqual "branchA id 4" (fakeUUID 4) (transactionId branchATrans')
148 assertEqual "branchA id 4" (fakeUUID 4) (transactionId branchATrans')
136
149
@@ -148,12 +161,15 @@ testSelectedBranchMerge = TestCase $ do
148
161
149 -- add another relvar to branchB
162 -- add another relvar to branchB
150 branchBTrans <- assertMaybe (transactionForHead "branchB" graph) "failed to get branchB head"
163 branchBTrans <- assertMaybe (transactionForHead "branchB" graph) "failed to get branchB head"
151− (updatedBranchBContext,_,_) <- case runState (evalDatabaseContextExpr (Assign "branchBOnlyRelvar" (ExistingRelation relationTrue))) (freshDatabaseState (concreteDatabaseContext branchBTrans)) of
164+ let env = mkDatabaseContextEvalEnv (transactionId branchBTrans) graph
165+ branchBContext = concreteDatabaseContext branchBTrans
166+ updatedBranchBContext <- case runDatabaseContextEvalMonad branchBContext env (optimizeAndEvalDatabaseContextExpr True (Assign "branchBOnlyRelvar" (ExistingRelation relationTrue))) of
152− (Left err, _) -> assertFailure (show err) >> undefined
167+ Left err -> assertFailure (show err) >> undefined
153− (Right (), context) -> pure context
168+ Right st -> pure (dbc_context st)
154− (_, graph') <- addTransaction "branchB" (createTrans (fakeUUID 3) (TransactionInfo (transactionId branchBTrans) S.empty testTime) updatedBranchBContext) graph
169+ (_, graph') <- addTransaction "branchB" (createTrans (fakeUUID 3) (TI.singleParent (transactionId branchBTrans) testTime) updatedBranchBContext) graph
155 --create the merge transaction in the graph
170 --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'
157
173
158 (_, graph'') <- assertEither eGraph'
174 (_, graph'') <- assertEither eGraph'
159
175
@@ -175,18 +191,22 @@ testUnionPreferMergeStrategy = TestCase $ do
175 branchBTrans <- assertMaybe (transactionForHead "branchB" graph) "branchBTrans"
191 branchBTrans <- assertMaybe (transactionForHead "branchB" graph) "branchBTrans"
176 branchBRelVar <- assertEither $ mkRelationFromList (attributesFromList [Attribute "conflict" IntAtomType]) []
192 branchBRelVar <- assertEither $ mkRelationFromList (attributesFromList [Attribute "conflict" IntAtomType]) []
177 let branchAContext = (concreteDatabaseContext branchATrans) {relationVariables = M.insert conflictRelVarName branchARelVar (relationVariables (concreteDatabaseContext branchATrans))}
193 let branchAContext = (concreteDatabaseContext branchATrans) {relationVariables = M.insert conflictRelVarName branchARelVar (relationVariables (concreteDatabaseContext branchATrans))}
178− branchARelVar = relationTrue
194+ branchARelVar = ExistingRelation relationTrue
179− branchBContext = (concreteDatabaseContext branchBTrans) {relationVariables = M.insert conflictRelVarName branchBRelVar (relationVariables (concreteDatabaseContext branchBTrans))}
195+ branchBContext = (concreteDatabaseContext branchBTrans) {relationVariables = M.insert conflictRelVarName (ExistingRelation branchBRelVar) (relationVariables (concreteDatabaseContext branchBTrans))}
180− conflictRelVarName = "conflictRelVar"
196+ conflictRelVarName = "conflictRelVar"
181
197
182− (_, graph') <- addTransaction "branchA" (createTrans (fakeUUID 3) (TransactionInfo (transactionId branchATrans) S.empty testTime) branchAContext) graph
198+ (_, graph') <- addTransaction "branchA" (createTrans (fakeUUID 3) (TI.singleParent (transactionId branchATrans) testTime) branchAContext) graph
183− (_, graph'') <- addTransaction "branchB" (createTrans (fakeUUID 4) (TransactionInfo (transactionId branchBTrans) S.empty testTime) branchBContext) graph'
199+ (_, graph'') <- addTransaction "branchB" (createTrans (fakeUUID 4) (TI.singleParent (transactionId branchBTrans) testTime) branchBContext) graph'
184 -- validate that the conflict is hidden because we preferred a branch
200 -- 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''
186 case merged of
203 case merged of
187 Left err -> assertFailure ("expected merge success: " ++ show err)
204 Left err -> assertFailure ("expected merge success: " ++ show err)
188− Right (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)
189− assertEqual "branchB relvar preferred in conflict" (Just branchBRelVar) (M.lookup conflictRelVarName (relationVariables (Discon.concreteDatabaseContext discon)))
209+ assertEqual "branchB relvar preferred in conflict" (Right branchBRelVar) eRvRel
190
210
191-- try various individual component conflicts and check for merge failure
211-- try various individual component conflicts and check for merge failure
192testUnionMergeStrategy :: Test
212testUnionMergeStrategy :: Test
@@ -201,31 +221,41 @@ testUnionMergeStrategy = TestCase $ do
201
221
202 let updatedBranchBContext = (concreteDatabaseContext branchBTrans) {relationVariables = M.insert branchBOnlyRelVarName branchBOnlyRelVar (relationVariables (concreteDatabaseContext branchBTrans)) }
222 let updatedBranchBContext = (concreteDatabaseContext branchBTrans) {relationVariables = M.insert branchBOnlyRelVarName branchBOnlyRelVar (relationVariables (concreteDatabaseContext branchBTrans)) }
203 updatedBranchAContext = (concreteDatabaseContext branchATrans) {inclusionDependencies = M.insert branchAOnlyIncDepName branchAOnlyIncDep (inclusionDependencies (concreteDatabaseContext branchATrans)) }
223 updatedBranchAContext = (concreteDatabaseContext branchATrans) {inclusionDependencies = M.insert branchAOnlyIncDepName branchAOnlyIncDep (inclusionDependencies (concreteDatabaseContext branchATrans)) }
204− branchBOnlyRelVar = relationTrue
224+ branchBOnlyRelVar = ExistingRelation relationTrue
205 branchAOnlyIncDepName = "branchAOnlyIncDep"
225 branchAOnlyIncDepName = "branchAOnlyIncDep"
206 branchBOnlyRelVarName = "branchBOnlyRelVar"
226 branchBOnlyRelVarName = "branchBOnlyRelVar"
207 branchAOnlyIncDep = InclusionDependency (ExistingRelation relationTrue) (ExistingRelation relationTrue)
227 branchAOnlyIncDep = InclusionDependency (ExistingRelation relationTrue) (ExistingRelation relationTrue)
208− (_, graph') <- addTransaction "branchB" (createTrans (fakeUUID 3) (TransactionInfo (transactionId branchBTrans) S.empty testTime) updatedBranchBContext) graph
228+ (_, graph') <- addTransaction "branchB" (createTrans (fakeUUID 3) (TI.singleParent (transactionId branchBTrans) testTime) updatedBranchBContext) graph
229+ let env = freshGraphRefRelationalExprEnv Nothing graph'
209− (discon, _) <- assertEither $ mergeTransactions testTime (fakeUUID 5) (fakeUUID 10) UnionMergeStrategy ("branchA", "branchB") 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+
210− assertEqual "branchBOnlyRelVar should appear in the merge" (M.lookup branchBOnlyRelVarName (relationVariables (Discon.concreteDatabaseContext discon))) (Just relationTrue)
235+ assertEqual "branchBOnlyRelVar should appear in the merge" relationTrue rvRel
211− (_, graph'') <- addTransaction "branchA" (createTrans (fakeUUID 4) (TransactionInfo (transactionId branchATrans) S.empty testTime) updatedBranchAContext) graph'
236+ (_, graph'') <- addTransaction "branchA" (createTrans (fakeUUID 4) (TI.singleParent (transactionId branchATrans) testTime) updatedBranchAContext) graph'
212− let eMergeGraph = mergeTransactions testTime (fakeUUID 5) (fakeUUID 3) UnionMergeStrategy ("branchA", "branchB") graph''
237+ let eMergeGraph = runGraphRefRelationalExprM gfEnv $ mergeTransactions testTime (fakeUUID 5) (fakeUUID 3) UnionMergeStrategy ("branchA", "branchB")
238+ gfEnv = freshGraphRefRelationalExprEnv Nothing graph''
213 case eMergeGraph of
239 case eMergeGraph of
214 Left err -> assertFailure ("expected merge success: " ++ show err)
240 Left err -> assertFailure ("expected merge success: " ++ show err)
215 Right (_, mergeGraph) -> do
241 Right (_, mergeGraph) -> do
216 -- check that the new merge transaction has the correct parents
242 -- check that the new merge transaction has the correct parents
217 mergeTrans <- assertEither $ transactionForId (fakeUUID 5) mergeGraph
243 mergeTrans <- assertEither $ transactionForId (fakeUUID 5) mergeGraph
218 let mergeContext = concreteDatabaseContext mergeTrans
244 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])
220 -- check that the new merge tranasction has elements from both A and B branches
246 -- 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'
222 assertEqual "merge transaction incdeps" (Just branchAOnlyIncDep) (M.lookup branchAOnlyIncDepName (inclusionDependencies mergeContext))
251 assertEqual "merge transaction incdeps" (Just branchAOnlyIncDep) (M.lookup branchAOnlyIncDepName (inclusionDependencies mergeContext))
223 -- test an expected conflict- add branchBOnlyRelVar with same name but different attributes
252 -- test an expected conflict- add branchBOnlyRelVar with same name but different attributes
224 conflictRelVar <- assertEither $ mkRelationFromList (attributesFromList [Attribute "conflict" IntAtomType]) []
253 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) }
226 conflictBranchATrans <- assertMaybe (transactionForHead "branchA" graph'') "retrieving head transaction for expected conflict"
255 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''
256+ (_, graph''') <- addTransaction "branchA" (createTrans (fakeUUID 6) (TI.singleParent (transactionId conflictBranchATrans) testTime) conflictContextA) graph''
228− let failingMerge = mergeTransactions testTime (fakeUUID 5) (fakeUUID 3) UnionMergeStrategy ("branchA", "branchB") graph'''
257+ let failingMerge = runGraphRefRelationalExprM gfEnv' $ mergeTransactions testTime (fakeUUID 5) (fakeUUID 3) UnionMergeStrategy ("branchA", "branchB")
258+ gfEnv' = freshGraphRefRelationalExprEnv Nothing graph'''
229 case failingMerge of
259 case failingMerge of
230 Right _ -> assertFailure "expected merge failure"
260 Right _ -> assertFailure "expected merge failure"
231 Left err -> assertEqual "merge failure" err (MergeTransactionError StrategyViolatesRelationVariableMergeError)
261 Left err -> assertEqual "merge failure" err (MergeTransactionError StrategyViolatesRelationVariableMergeError)
@@ -244,20 +274,21 @@ testUnionMergeIncDepViolation = TestCase $ do
244 rvName = "x"
274 rvName = "x"
245 Right branchArv = eRel 2
275 Right branchArv = eRel 2
246 Right branchBrv = eRel 3
276 Right branchBrv = eRel 3
247− branchAContext = (concreteDatabaseContext branchBTrans) {relationVariables = M.singleton rvName branchArv}
277+ branchAContext = (concreteDatabaseContext branchBTrans) {relationVariables = M.singleton rvName (ExistingRelation branchArv)}
248− branchBContext = (concreteDatabaseContext branchBTrans) {relationVariables = M.singleton rvName branchBrv,
278+ branchBContext = (concreteDatabaseContext branchBTrans) {relationVariables = M.singleton rvName (ExistingRelation branchBrv),
249 inclusionDependencies = M.singleton incDepName incDep}
279 inclusionDependencies = M.singleton incDepName incDep}
250 incDepName = "x_key"
280 incDepName = "x_key"
251 incDep = inclusionDependencyForKey (AttributeNames (S.singleton "x")) (RelationVariable "x" ())
281 incDep = inclusionDependencyForKey (AttributeNames (S.singleton "x")) (RelationVariable "x" ())
252
282
253
283
254 --add the rv in new commits to both branches
284 --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
256
286
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'
258
288
259 --check that the union merge fails due to a violated constraint
289 --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''
261 case eMerge of
292 case eMerge of
262 Left (InclusionDependencyCheckError incDepName') -> assertEqual "incdep violation name" incDepName incDepName'
293 Left (InclusionDependencyCheckError incDepName') -> assertEqual "incdep violation name" incDepName incDepName'
263 Left err -> assertFailure ("other error: " ++ show err)
294 Left err -> assertFailure ("other error: " ++ show err)
test/TransactionGraph/Persist.hs+83−18
@@ -1,14 +1,14 @@
1+{-# LANGUAGE CPP #-}
1import Test.HUnit
2import Test.HUnit
2import ProjectM36.Base
3import ProjectM36.Base
3import ProjectM36.Persist (DiskSync(NoDiskSync))
4import ProjectM36.Persist (DiskSync(NoDiskSync))
4import ProjectM36.TransactionGraph.Persist
5import ProjectM36.TransactionGraph.Persist
5−import ProjectM36.TransactionGraph
6+import ProjectM36.TransactionGraph as TG
6import ProjectM36.Transaction
7import ProjectM36.Transaction
7import ProjectM36.DateExamples
8import ProjectM36.DateExamples
8−import ProjectM36.Client
9−import ProjectM36.Relation
10import System.IO.Temp
9import System.IO.Temp
11import System.Exit
10import System.Exit
11+import System.Directory
12import Data.Either
12import Data.Either
13import Data.UUID.V4 (nextRandom)
13import Data.UUID.V4 (nextRandom)
14import System.FilePath
14import System.FilePath
@@ -17,6 +17,9 @@ import qualified Data.Map as M
17import qualified Data.Set as S
17import qualified Data.Set as S
18import Data.Time.Clock
18import Data.Time.Clock
19import Data.Time.Calendar
19import Data.Time.Calendar
20+import ProjectM36.Client as C
21+import ProjectM36.Relation
22+import ProjectM36.Transaction.Persist
20
23
21main :: IO ()
24main :: IO ()
22main = do
25main = do
@@ -25,11 +28,13 @@ main = do
25
28
26testList :: Test
29testList :: Test
27testList = TestList [testBootstrapDB,
30testList = TestList [testBootstrapDB,
28− testDBSimplePersistence,
31+ testDBSimplePersistence,
29− testFunctionPersistence]
32+ testFunctionPersistence,
33+ testMerkleHashValidation]
34+
30
35
31−stamp :: UTCTime
36+stamp' :: UTCTime
32−stamp = UTCTime (fromGregorian 1980 01 01) (secondsToDiffTime 1000)
37+stamp' = UTCTime (fromGregorian 1980 01 01) (secondsToDiffTime 1000)
33
38
34{- bootstrap a database, ensure that it can be read -}
39{- bootstrap a database, ensure that it can be read -}
35testBootstrapDB :: Test
40testBootstrapDB :: Test
@@ -37,7 +42,7 @@ testBootstrapDB = TestCase $ withSystemTempDirectory "m36testdb" $ \tempdir -> d
37 let dbdir = tempdir </> "dbdir"
42 let dbdir = tempdir </> "dbdir"
38 freshId <- nextRandom
43 freshId <- nextRandom
39
44
40− _ <- bootstrapDatabaseDir NoDiskSync dbdir (bootstrapTransactionGraph stamp freshId dateExamples)
45+ _ <- bootstrapDatabaseDir NoDiskSync dbdir (bootstrapTransactionGraph stamp' freshId dateExamples)
41 loadedGraph <- transactionGraphLoad dbdir emptyTransactionGraph Nothing
46 loadedGraph <- transactionGraphLoad dbdir emptyTransactionGraph Nothing
42 assertBool "transactionGraphLoad" $ isRight loadedGraph
47 assertBool "transactionGraphLoad" $ isRight loadedGraph
43
48
@@ -47,17 +52,17 @@ testDBSimplePersistence = TestCase $ withSystemTempDirectory "m36testdb" $ \temp
47 let dbdir = tempdir </> "dbdir"
52 let dbdir = tempdir </> "dbdir"
48 freshId <- nextRandom
53 freshId <- nextRandom
49
54
50− let graph = bootstrapTransactionGraph stamp freshId dateExamples
55+ let graph = bootstrapTransactionGraph stamp' freshId dateExamples
51 _ <- bootstrapDatabaseDir NoDiskSync dbdir graph
56 _ <- bootstrapDatabaseDir NoDiskSync dbdir graph
52 case transactionForHead "master" graph of
57 case transactionForHead "master" graph of
53 Nothing -> assertFailure "Failed to retrieve head transaction for master branch."
58 Nothing -> assertFailure "Failed to retrieve head transaction for master branch."
54 Just headTrans ->
59 Just headTrans ->
55− case interpretDatabaseContextExpr (concreteDatabaseContext headTrans) "x:=s" of
60+ case interpretDatabaseContextExpr (concreteDatabaseContext headTrans) (transactionId headTrans) graph "x:=s" of
56 Left err -> assertFailure (show err)
61 Left err -> assertFailure (show err)
57 Right context' -> do
62 Right context' -> do
58 freshId' <- nextRandom
63 freshId' <- nextRandom
59− let newdiscon = DisconnectedTransaction (transactionId headTrans) (Schemas context' M.empty) True
64+ let newdiscon = DisconnectedTransaction (transactionId headTrans) (Schemas context' M.empty) False
60− addTrans = addDisconnectedTransaction stamp freshId' "master" newdiscon graph
65+ addTrans = addDisconnectedTransaction stamp' freshId' "master" newdiscon graph
61 --add a transaction to the graph
66 --add a transaction to the graph
62 case addTrans of
67 case addTrans of
63 Left err -> assertFailure (show err)
68 Left err -> assertFailure (show err)
@@ -70,11 +75,70 @@ testDBSimplePersistence = TestCase $ withSystemTempDirectory "m36testdb" $ \temp
70 case graphErr of
75 case graphErr of
71 Left err -> assertFailure (show err)
76 Left err -> assertFailure (show err)
72 Right graph'' -> assertBool "graph equality" (mapEq graph'' == mapEq graph')
77 Right graph'' -> assertBool "graph equality" (mapEq graph'' == mapEq graph')
73−
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+
74
134
75--only Haskell-scripted dbc and atom functions can be serialized
135--only Haskell-scripted dbc and atom functions can be serialized
76testFunctionPersistence :: Test
136testFunctionPersistence :: Test
137+#if !defined(PM36_HASKELL_SCRIPTING)
138+testFunctionPersistence = TestCase $ pure ()
139+#else
140+testFunctionPersistence = TestCase $
77−testFunctionPersistence = TestCase $ withSystemTempDirectory "m36testdb" $ \tempdir -> do
141+ withSystemTempDirectory "m36testdb" $ \tempdir -> do
78 let dbdir = tempdir </> "dbdir"
142 let dbdir = tempdir </> "dbdir"
79 connInfo = InProcessConnectionInfo (MinimalPersistence dbdir) emptyNotificationCallback []
143 connInfo = InProcessConnectionInfo (MinimalPersistence dbdir) emptyNotificationCallback []
80 conn <- assertIOEither $ connectProjectM36 connInfo
144 conn <- assertIOEither $ connectProjectM36 connInfo
@@ -85,17 +149,18 @@ testFunctionPersistence = TestCase $ withSystemTempDirectory "m36testdb" $ \temp
85 ADTypeConstructor "Either" [ADTypeConstructor "AtomFunctionError" [],
149 ADTypeConstructor "Either" [ADTypeConstructor "AtomFunctionError" [],
86 intTCons]] "(\\(x:_) -> pure x) :: [Atom] -> Either AtomFunctionError Atom"
150 intTCons]] "(\\(x:_) -> pure x) :: [Atom] -> Either AtomFunctionError Atom"
87 _ <- assertIOEither $ executeDatabaseContextIOExpr sess conn addfunc
151 _ <- assertIOEither $ executeDatabaseContextIOExpr sess conn addfunc
88−
89 _ <- assertIOEither $ commit sess conn
152 _ <- assertIOEither $ commit sess conn
90− close conn
153+ --close conn - pauses indefinitely on Windows
91 --re-open the connection to reload the graph
154 --re-open the connection to reload the graph
92 conn2 <- assertIOEither $ connectProjectM36 connInfo
155 conn2 <- assertIOEither $ connectProjectM36 connInfo
93 sess2 <- assertIOEither $ createSessionAtHead conn2 "master"
156 sess2 <- assertIOEither $ createSessionAtHead conn2 "master"
94
157
95− 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)] ()))]))
96 let expectedRel = mkRelationFromList (attributesFromList [Attribute "a" IntAtomType]) [[IntAtom 3]]
159 let expectedRel = mkRelationFromList (attributesFromList [Attribute "a" IntAtomType]) [[IntAtom 3]]
97 assertEqual "testdisk dbc function run" expectedRel res
160 assertEqual "testdisk dbc function run" expectedRel res
98−
161+
162+#endif
163+
99assertIOEither :: (Show a) => IO (Either a b) -> IO b
164assertIOEither :: (Show a) => IO (Either a b) -> IO b
100assertIOEither x = do
165assertIOEither x = do
101 ret <- x
166 ret <- x
test/TutorialD/Interpreter.hs+159−36
@@ -3,14 +3,17 @@ import TutorialD.Interpreter.TestBase
3import TutorialD.Interpreter
3import TutorialD.Interpreter
4import TutorialD.Interpreter.Base
4import TutorialD.Interpreter.Base
5import Test.HUnit
5import Test.HUnit
6−import ProjectM36.Relation
6+import ProjectM36.Relation as R
7import ProjectM36.Tuple
7import ProjectM36.Tuple
8import ProjectM36.TupleSet
8import ProjectM36.TupleSet
9import ProjectM36.Error
9import ProjectM36.Error
10import ProjectM36.DatabaseContext
10import ProjectM36.DatabaseContext
11import ProjectM36.AtomFunctions.Primitive
11import ProjectM36.AtomFunctions.Primitive
12+import ProjectM36.RelationalExpression
12import ProjectM36.DataTypes.Either
13import ProjectM36.DataTypes.Either
13import ProjectM36.DataTypes.Interval
14import ProjectM36.DataTypes.Interval
15+import ProjectM36.DataTypes.NonEmptyList
16+import ProjectM36.DataTypes.List
14import ProjectM36.DateExamples
17import ProjectM36.DateExamples
15import ProjectM36.Base hiding (Finite)
18import ProjectM36.Base hiding (Finite)
16import ProjectM36.TransactionGraph
19import ProjectM36.TransactionGraph
@@ -37,8 +40,9 @@ main = do
37 tcounts <- runTestTT (TestList tests)
40 tcounts <- runTestTT (TestList tests)
38 if errors tcounts + failures tcounts > 0 then exitFailure else exitSuccess
41 if errors tcounts + failures tcounts > 0 then exitFailure else exitSuccess
39 where
42 where
40− tests = map (\(tutd, expected) -> TestCase $ assertTutdEqual basicDatabaseContext expected tutd) simpleRelTests ++
43+ tests = [
41− map (\(tutd, expected) -> TestCase $ assertTutdEqual dateExamples expected tutd) dateExampleRelTests ++ [
44+ simpleRelTests,
45+ dateExampleRelTests,
42 transactionGraphBasicTest,
46 transactionGraphBasicTest,
43 transactionGraphAddCommitTest,
47 transactionGraphAddCommitTest,
44 transactionRollbackTest,
48 transactionRollbackTest,
@@ -67,9 +71,24 @@ main = do
67 testAssignWithTypeVar,
71 testAssignWithTypeVar,
68 testDefineWithTypeVar,
72 testDefineWithTypeVar,
69 testIntervalType,
73 testIntervalType,
70− testArbitraryRelation
74+ testArbitraryRelation,
75+ testNonEmptyListType,
76+ testUnresolvedAtomTypes,
77+ testWithClause,
78+ testAtomFunctionArgumentMismatch,
79+ testInvalidDataConstructor,
80+ testBasicList,
81+ testRelationDeclarationMismatch,
82+ testInvalidTuples,
83+ testSelfReferencingUncommittedContext
71 ]
84 ]
85+
86+simpleRelTests :: Test
87+simpleRelTests = TestCase $ do
88+ (graph, transId) <- freshTransactionGraph dateExamples
89+ mapM_ (\(tutd, expected) -> assertTutdEqual basicDatabaseContext transId graph expected tutd) testTups
90+ where
72− simpleRelTests = [("x:=true", Right relationTrue),
91+ testTups = [("x:=true", Right relationTrue),
73 ("x:=false", Right relationFalse),
92 ("x:=false", Right relationFalse),
74 ("x:=true union false", Right relationTrue),
93 ("x:=true union false", Right relationTrue),
75 ("x:=true minus false", Right relationTrue),
94 ("x:=true minus false", Right relationTrue),
@@ -102,39 +121,46 @@ main = do
102 ("x:=relation{tuple{a 5}} : {b:=6}", mkRelationFromTuples simpleDAttributes [RelationTuple simpleDAttributes (V.fromList [IntegerAtom 5, IntegerAtom 6])]),
121 ("x:=relation{tuple{a 5}} : {b:=6}", mkRelationFromTuples simpleDAttributes [RelationTuple simpleDAttributes (V.fromList [IntegerAtom 5, IntegerAtom 6])]),
103 ("x:=relation{tuple{a 5}} : {b:=add(@a,5)}", mkRelationFromTuples simpleDAttributes [RelationTuple simpleDAttributes (V.fromList [IntegerAtom 5, IntegerAtom 10])]),
122 ("x:=relation{tuple{a 5}} : {b:=add(@a,5)}", mkRelationFromTuples simpleDAttributes [RelationTuple simpleDAttributes (V.fromList [IntegerAtom 5, IntegerAtom 10])]),
104 ("x:=relation{tuple{a 5}} : {b:=add(@a,\"spam\")}", Left (AtomFunctionTypeError "add" 2 IntegerAtomType TextAtomType)),
123 ("x:=relation{tuple{a 5}} : {b:=add(@a,\"spam\")}", Left (AtomFunctionTypeError "add" 2 IntegerAtomType TextAtomType)),
105− ("x:=relation{tuple{a 5}} : {b:=add(add(@a,2),5)}", mkRelationFromTuples simpleDAttributes [RelationTuple simpleDAttributes (V.fromList [IntegerAtom 5, IntegerAtom 12])])
124+ ("x:=relation{tuple{a 5}} : {b:=add(add(@a,2),5)}", mkRelationFromTuples simpleDAttributes [RelationTuple simpleDAttributes (V.fromList [IntegerAtom 5, IntegerAtom 12])]),
125+ ("x:=false:{a:=1,b:=2}", mkRelationFromTuples simpleDAttributes [])
106 ]
126 ]
107 simpleAAttributes = A.attributesFromList [Attribute "a" IntegerAtomType]
127 simpleAAttributes = A.attributesFromList [Attribute "a" IntegerAtomType]
108 simpleBAttributes = A.attributesFromList [Attribute "d" IntegerAtomType]
128 simpleBAttributes = A.attributesFromList [Attribute "d" IntegerAtomType]
109 simpleCAttributes = A.attributesFromList [Attribute "a" TextAtomType, Attribute "b" IntegerAtomType]
129 simpleCAttributes = A.attributesFromList [Attribute "a" TextAtomType, Attribute "b" IntegerAtomType]
110 simpleDAttributes = A.attributesFromList [Attribute "a" IntegerAtomType, Attribute "b" IntegerAtomType]
130 simpleDAttributes = A.attributesFromList [Attribute "a" IntegerAtomType, Attribute "b" IntegerAtomType]
111− maybeTextAtomType = ConstructedAtomType "Maybe" (M.singleton "a" TextAtomType)
131+ simpleProjectionAttributes = A.attributesFromList [Attribute "c" IntegerAtomType]
132+ nestedRelationAttributes = A.attributesFromList [Attribute "a" IntegerAtomType, Attribute "b" (RelationAtomType $ A.attributesFromList [Attribute "a" IntegerAtomType])]
133+
134+dateExampleRelTests :: Test
135+dateExampleRelTests = TestCase $ do
136+ (graph, transId) <- freshTransactionGraph dateExamples
137+ mapM_ (\(tutd, expected) -> assertTutdEqual dateExamples transId graph expected tutd) testTups
138+ where
139+ simpleEitherIntTextAttributes = A.attributesFromList [Attribute "a" (eitherAtomType IntegerAtomType TextAtomType)]
112 maybeIntegerAtomType = ConstructedAtomType "Maybe" (M.singleton "a" IntegerAtomType)
140 maybeIntegerAtomType = ConstructedAtomType "Maybe" (M.singleton "a" IntegerAtomType)
141+ maybeTextAtomType = ConstructedAtomType "Maybe" (M.singleton "a" TextAtomType)
113 simpleMaybeTextAttributes = A.attributesFromList [Attribute "a" maybeTextAtomType]
142 simpleMaybeTextAttributes = A.attributesFromList [Attribute "a" maybeTextAtomType]
114 simpleMaybeIntAttributes = A.attributesFromList [Attribute "a" maybeIntegerAtomType]
143 simpleMaybeIntAttributes = A.attributesFromList [Attribute "a" maybeIntegerAtomType]
115− simpleEitherIntTextAttributes = A.attributesFromList [Attribute "a" (eitherAtomType IntegerAtomType TextAtomType)]
116− simpleProjectionAttributes = A.attributesFromList [Attribute "c" IntegerAtomType]
117− nestedRelationAttributes = A.attributesFromList [Attribute "a" IntegerAtomType, Attribute "b" (RelationAtomType $ A.attributesFromList [Attribute "a" IntegerAtomType])]
118− extendTestAttributes = A.attributesFromList [Attribute "a" IntegerAtomType, Attribute "b" $ RelationAtomType (attributes suppliersRel)]
119 byteStringAttributes = A.attributesFromList [Attribute "y" ByteStringAtomType]
144 byteStringAttributes = A.attributesFromList [Attribute "y" ByteStringAtomType]
120− groupCountAttrs = A.attributesFromList [Attribute "z" IntegerAtomType]
121 minMaxAttrs = A.attributesFromList [Attribute "s#" TextAtomType, Attribute "z" IntegerAtomType]
145 minMaxAttrs = A.attributesFromList [Attribute "s#" TextAtomType, Attribute "z" IntegerAtomType]
146+ groupCountAttrs = A.attributesFromList [Attribute "z" IntegerAtomType]
122 updateParisPlus10 = relMap (\tuple -> do
147 updateParisPlus10 = relMap (\tuple -> do
123 statusAtom <- atomForAttributeName "status" tuple
148 statusAtom <- atomForAttributeName "status" tuple
124 cityAtom <- atomForAttributeName "city" tuple
149 cityAtom <- atomForAttributeName "city" tuple
125 if cityAtom == TextAtom "Paris" then
150 if cityAtom == TextAtom "Paris" then
126 Right $ updateTupleWithAtoms (M.singleton "status" (IntegerAtom (castInteger statusAtom + 10))) tuple
151 Right $ updateTupleWithAtoms (M.singleton "status" (IntegerAtom (castInteger statusAtom + 10))) tuple
127 else Right tuple) suppliersRel
152 else Right tuple) suppliersRel
153+ extendTestAttributes = A.attributesFromList [Attribute "a" IntegerAtomType, Attribute "b" $ RelationAtomType (R.attributes suppliersRel)]
128− dateExampleRelTests = [("x:=s where true", Right suppliersRel),
154+ testTups = [("x:=s where true", Right suppliersRel),
129− ("x:=s where city = \"London\"", restrict (\tuple -> pure $ atomForAttributeName "city" tuple == (Right $ TextAtom "London")) suppliersRel),
155+ ("x:=s where city = \"London\"", restrict (\tuple -> pure $ atomForAttributeName "city" tuple == Right (TextAtom "London")) suppliersRel),
130− ("x:=s where false", Right $ Relation (attributes suppliersRel) emptyTupleSet),
156+ ("x:=s where false", Right $ Relation (R.attributes suppliersRel) emptyTupleSet),
131− ("x:=p where color=\"Blue\" and city=\"Paris\"", mkRelationFromList (attributes productsRel) [[TextAtom "P5", TextAtom "Cam", TextAtom "Blue", IntegerAtom 12, TextAtom "Paris"]]),
157+ ("x:=p where color=\"Blue\" and city=\"Paris\"", mkRelationFromList (R.attributes productsRel) [[TextAtom "P5", TextAtom "Cam", TextAtom "Blue", IntegerAtom 12, TextAtom "Paris"]]),
132 ("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])])),
158 ("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])])),
133− ("x:=s minus (s where status=20)", mkRelationFromList (attributes suppliersRel) [[TextAtom "S2", TextAtom "Jones", IntegerAtom 10, TextAtom "Paris"], [TextAtom "S3", TextAtom "Blake", IntegerAtom 30, TextAtom "Paris"], [TextAtom "S5", TextAtom "Adams", IntegerAtom 30, TextAtom "Athens"]]),
159+ ("x:=s minus (s where status=20)", mkRelationFromList (R.attributes suppliersRel) [[TextAtom "S2", TextAtom "Jones", IntegerAtom 10, TextAtom "Paris"], [TextAtom "S3", TextAtom "Blake", IntegerAtom 30, TextAtom "Paris"], [TextAtom "S5", TextAtom "Adams", IntegerAtom 30, TextAtom "Athens"]]),
134 --atom function tests
160 --atom function tests
135 ("x:=((s : {status2 := add(10,@status)}) where status2=add(10,@status)){city,s#,sname,status}", Right suppliersRel),
161 ("x:=((s : {status2 := add(10,@status)}) where status2=add(10,@status)){city,s#,sname,status}", Right suppliersRel),
136 ("x:=relation{tuple{a 5}} : {b:=s}", mkRelation extendTestAttributes (RelationTupleSet [mkRelationTuple extendTestAttributes (V.fromList [IntegerAtom 5, RelationAtom suppliersRel])])),
162 ("x:=relation{tuple{a 5}} : {b:=s}", mkRelation extendTestAttributes (RelationTupleSet [mkRelationTuple extendTestAttributes (V.fromList [IntegerAtom 5, RelationAtom suppliersRel])])),
137− ("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),
163+ ("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),
138 ("x:=s; update x where city=\"Paris\" (status:=add(@status,10))", updateParisPlus10),
164 ("x:=s; update x where city=\"Paris\" (status:=add(@status,10))", updateParisPlus10),
139 --relatom function tests
165 --relatom function tests
140 ("x:=((s group ({city} as y)):{z:=count(@y)}){z}", mkRelation groupCountAttrs (RelationTupleSet [mkRelationTuple groupCountAttrs (V.singleton $ IntegerAtom 1)])),
166 ("x:=((s group ({city} as y)):{z:=count(@y)}){z}", mkRelation groupCountAttrs (RelationTupleSet [mkRelationTuple groupCountAttrs (V.singleton $ IntegerAtom 1)])),
@@ -143,11 +169,11 @@ main = do
143 ("x:=((sp{s#,qty}) group ({qty} as x):{z:=min(@x)}){s#,z}", mkRelationFromList minMaxAttrs (map (\(s,i) -> [TextAtom s,IntegerAtom i]) [("S1", 100), ("S2", 300), ("S3", 200), ("S4", 200)])),
169 ("x:=((sp{s#,qty}) group ({qty} as x):{z:=min(@x)}){s#,z}", mkRelationFromList minMaxAttrs (map (\(s,i) -> [TextAtom s,IntegerAtom i]) [("S1", 100), ("S2", 300), ("S3", 200), ("S4", 200)])),
144 ("x:=((sp{s#,qty}) group ({qty} as x):{z:=sum(@x)}){s#,z}", mkRelationFromList minMaxAttrs (map (\(s,i) -> [TextAtom s,IntegerAtom i]) [("S1", 1000), ("S2", 700), ("S3", 200), ("S4", 900)])),
170 ("x:=((sp{s#,qty}) group ({qty} as x):{z:=sum(@x)}){s#,z}", mkRelationFromList minMaxAttrs (map (\(s,i) -> [TextAtom s,IntegerAtom i]) [("S1", 1000), ("S2", 700), ("S3", 200), ("S4", 900)])),
145 --boolean function restriction
171 --boolean function restriction
146− ("x:=s where ^lt(@status,20)", mkRelationFromList (attributes suppliersRel) [[TextAtom "S2", TextAtom "Jones", IntegerAtom 10, TextAtom "Paris"]]),
172+ ("x:=s where ^lt(@status,20)", mkRelationFromList (R.attributes suppliersRel) [[TextAtom "S2", TextAtom "Jones", IntegerAtom 10, TextAtom "Paris"]]),
147− ("x:=s where ^gt(@status,20)", mkRelationFromList (attributes suppliersRel) [[TextAtom "S3", TextAtom "Blake", IntegerAtom 30, TextAtom "Paris"],
173+ ("x:=s where ^gt(@status,20)", mkRelationFromList (R.attributes suppliersRel) [[TextAtom "S3", TextAtom "Blake", IntegerAtom 30, TextAtom "Paris"],
148 [TextAtom "S5", TextAtom "Adams", IntegerAtom 30, TextAtom "Athens"]]),
174 [TextAtom "S5", TextAtom "Adams", IntegerAtom 30, TextAtom "Athens"]]),
149 ("x:=s where ^sum(@status)", Left $ AtomTypeMismatchError IntegerAtomType BoolAtomType),
175 ("x:=s where ^sum(@status)", Left $ AtomTypeMismatchError IntegerAtomType BoolAtomType),
150− ("x:=s where ^not(gte(@status,20))", mkRelationFromList (attributes suppliersRel) [[TextAtom "S2", TextAtom "Jones", IntegerAtom 10, TextAtom "Paris"]]),
176+ ("x:=s where ^not(gte(@status,20))", mkRelationFromList (R.attributes suppliersRel) [[TextAtom "S2", TextAtom "Jones", IntegerAtom 10, TextAtom "Paris"]]),
151 --test "all but" attribute inversion syntax
177 --test "all but" attribute inversion syntax
152 ("x:=s{all but s#} = s{city,sname,status}", Right relationTrue),
178 ("x:=s{all but s#} = s{city,sname,status}", Right relationTrue),
153 --test key syntax
179 --test key syntax
@@ -160,7 +186,7 @@ main = do
160 --test Maybe Integer
186 --test Maybe Integer
161 ("x:=relation{tuple{a Just 3}}", mkRelationFromList simpleMaybeIntAttributes [[ConstructedAtom "Just" maybeIntegerAtomType [IntegerAtom 3]]]),
187 ("x:=relation{tuple{a Just 3}}", mkRelationFromList simpleMaybeIntAttributes [[ConstructedAtom "Just" maybeIntegerAtomType [IntegerAtom 3]]]),
162 --test Either Integer Text
188 --test Either Integer Text
163− ("x:=relation{tuple{a Left 3}}", Left (TypeConstructorTypeVarsMismatch (S.fromList ["a","b"]) (S.fromList ["a"]))), -- Left 3, alone is not enough information to imply the type
189+ ("x:=relation{tuple{a Left 3}}", Left (TypeConstructorTypeVarMissing "b")), -- Left 3, alone is not enough information to imply the type
164 ("x:=relation{a Either Integer Text}{tuple{a Left 3}}", mkRelationFromList simpleEitherIntTextAttributes [[ConstructedAtom "Left" (eitherAtomType IntegerAtomType TextAtomType) [IntegerAtom 3]]]),
190 ("x:=relation{a Either Integer Text}{tuple{a Left 3}}", mkRelationFromList simpleEitherIntTextAttributes [[ConstructedAtom "Left" (eitherAtomType IntegerAtomType TextAtomType) [IntegerAtom 3]]]),
165 --test datetime constructor
191 --test datetime constructor
166 ("x:=relation{tuple{a dateTimeFromEpochSeconds(1495199790)}}", mkRelationFromList (A.attributesFromList [Attribute "a" DateTimeAtomType]) [[DateTimeAtom (posixSecondsToUTCTime(realToFrac (1495199790 :: Int)))]]),
192 ("x:=relation{tuple{a dateTimeFromEpochSeconds(1495199790)}}", mkRelationFromList (A.attributesFromList [Attribute "a" DateTimeAtomType]) [[DateTimeAtom (posixSecondsToUTCTime(realToFrac (1495199790 :: Int)))]]),
@@ -168,14 +194,17 @@ main = do
168 ("x:=relation{tuple{a fromGregorian(2017,05,30)}}", mkRelationFromList (A.attributesFromList [Attribute "a" DayAtomType]) [[DayAtom (fromGregorian 2017 05 30)]])
194 ("x:=relation{tuple{a fromGregorian(2017,05,30)}}", mkRelationFromList (A.attributesFromList [Attribute "a" DayAtomType]) [[DayAtom (fromGregorian 2017 05 30)]])
169 ]
195 ]
170
196
171−assertTutdEqual :: DatabaseContext -> Either RelationalError Relation -> Text -> Assertion
197+assertTutdEqual :: DatabaseContext -> TransactionId -> TransactionGraph -> Either RelationalError Relation -> Text -> Assertion
172−assertTutdEqual databaseContext expected tutd = assertEqual (unpack tutd) expected interpreted
198+assertTutdEqual databaseContext transId graph expected tutd = assertEqual (unpack tutd) expected interpreted
173 where
199 where
174− interpreted = case interpretDatabaseContextExpr databaseContext tutd of
200+ interpreted = case interpretDatabaseContextExpr databaseContext transId graph tutd of
175 Left err -> Left err
201 Left err -> Left err
176 Right context -> case M.lookup "x" (relationVariables context) of
202 Right context -> case M.lookup "x" (relationVariables context) of
177 Nothing -> Left $ RelVarNotDefinedError "x"
203 Nothing -> Left $ RelVarNotDefinedError "x"
178− Just rel -> Right rel
204+ Just relExpr -> do
205+ let env = freshGraphRefRelationalExprEnv (Just context) graph
206+ runGraphRefRelationalExprM env (evalGraphRefRelationalExpr relExpr)
207+
179
208
180transactionGraphBasicTest :: Test
209transactionGraphBasicTest :: Test
181transactionGraphBasicTest = TestCase $ do
210transactionGraphBasicTest = TestCase $ do
@@ -196,13 +225,14 @@ transactionGraphAddCommitTest = TestCase $ do
196 DisplayResult _ -> assertFailure "display?"
225 DisplayResult _ -> assertFailure "display?"
197 DisplayIOResult _ -> assertFailure "displayIO?"
226 DisplayIOResult _ -> assertFailure "displayIO?"
198 DisplayRelationResult _ -> assertFailure "displayrelation?"
227 DisplayRelationResult _ -> assertFailure "displayrelation?"
228+ DisplayDataFrameResult _ -> assertFailure "displaydataframe?"
199 DisplayParseErrorResult _ _ -> assertFailure "displayparseerror?"
229 DisplayParseErrorResult _ _ -> assertFailure "displayparseerror?"
200 DisplayErrorResult err -> assertFailure (show err)
230 DisplayErrorResult err -> assertFailure (show err)
201 QuietSuccessResult -> do
231 QuietSuccessResult -> do
202 commit sessionId dbconn >>= eitherFail
232 commit sessionId dbconn >>= eitherFail
203 discon <- disconnectedTransaction_ sessionId dbconn
233 discon <- disconnectedTransaction_ sessionId dbconn
204 let context = Discon.concreteDatabaseContext discon
234 let context = Discon.concreteDatabaseContext discon
205− assertEqual "ensure x was added" (M.lookup "x" (relationVariables context)) (Just suppliersRel)
235+ assertEqual "ensure x was added" (M.lookup "x" (relationVariables context)) (Just (ExistingRelation suppliersRel))
206
236
207transactionRollbackTest :: Test
237transactionRollbackTest :: Test
208transactionRollbackTest = TestCase $ do
238transactionRollbackTest = TestCase $ do
@@ -244,12 +274,16 @@ transactionBranchTest = TestCase $ do
244
274
245-- test that overlapping attribute names with different types fail with an error
275-- test that overlapping attribute names with different types fail with an error
246failJoinTest :: Test
276failJoinTest :: Test
277+failJoinTest = TestCase $ do
278+ (graph, transId) <- freshTransactionGraph dateExamples
247−failJoinTest = TestCase $ assertTutdEqual basicDatabaseContext err "x:=relation{tuple{test 4}} join relation{tuple{test \"test\"}}"
279+ assertTutdEqual basicDatabaseContext transId graph err "x:=relation{tuple{test 4}} join relation{tuple{test \"test\"}}"
248 where
280 where
249 err = Left (TupleAttributeTypeMismatchError (A.attributesFromList [Attribute "test" IntegerAtomType]))
281 err = Left (TupleAttributeTypeMismatchError (A.attributesFromList [Attribute "test" IntegerAtomType]))
250
282
251simpleJoinTest :: Test
283simpleJoinTest :: Test
284+simpleJoinTest = TestCase $ do
285+ (graph, transId) <- freshTransactionGraph dateExamples
252−simpleJoinTest = TestCase $ assertTutdEqual dateExamples joinedRel "x:=s join sp"
286+ assertTutdEqual dateExamples transId graph joinedRel "x:=s join sp"
253 where
287 where
254 attrs = A.attributesFromList [Attribute "city" TextAtomType,
288 attrs = A.attributesFromList [Attribute "city" TextAtomType,
255 Attribute "qty" IntegerAtomType,
289 Attribute "qty" IntegerAtomType,
@@ -376,7 +410,9 @@ testTransGraphRelationalExpr = TestCase $ do
376 _ -> assertFailure "failed to delete branch"
410 _ -> assertFailure "failed to delete branch"
377
411
378testMultiAttributeRename :: Test
412testMultiAttributeRename :: Test
413+testMultiAttributeRename = TestCase $ do
414+ (graph, transId) <- freshTransactionGraph dateExamples
379−testMultiAttributeRename = TestCase $ assertTutdEqual dateExamples renamedRel "x:=s rename {city as town, status as price} where false"
415+ assertTutdEqual dateExamples transId graph renamedRel "x:=s rename {city as town, status as price} where false"
380 where
416 where
381 sattrs = attributesFromList [Attribute "town" TextAtomType,
417 sattrs = attributesFromList [Attribute "town" TextAtomType,
382 Attribute "sname" TextAtomType,
418 Attribute "sname" TextAtomType,
@@ -461,16 +497,22 @@ testEmptyCommits = TestCase $ do
461 assertEqual "empty insert empty commit" (Right False) dirty'
497 assertEqual "empty insert empty commit" (Right False) dirty'
462 Right () <- commit sessionId dbconn
498 Right () <- commit sessionId dbconn
463
499
464− --update no tuples
500+ --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
465 Right () <- executeDatabaseContextExpr sessionId dbconn (Update "s" (M.singleton "sname" (NakedAtomExpr (TextAtom "Bob"))) (AttributeEqualityPredicate "sname" (NakedAtomExpr (TextAtom "Mike"))))
501 Right () <- executeDatabaseContextExpr sessionId dbconn (Update "s" (M.singleton "sname" (NakedAtomExpr (TextAtom "Bob"))) (AttributeEqualityPredicate "sname" (NakedAtomExpr (TextAtom "Mike"))))
466 dirty'' <- disconnectedTransactionIsDirty sessionId dbconn
502 dirty'' <- disconnectedTransactionIsDirty sessionId dbconn
467− assertEqual "empty update empty commit" (Right False) dirty''
503+ assertEqual "empty update empty commit" (Right True) dirty''
504+ Right () <- commit sessionId dbconn
505+
506+ --assign the same rel expr
507+ Right () <- executeDatabaseContextExpr sessionId dbconn (Assign "true" (ExistingRelation relationTrue))
508+ sameREdirty <- disconnectedTransactionIsDirty sessionId dbconn
509+ assertEqual "same relexpr assigned" (Right False) sameREdirty
468 Right () <- commit sessionId dbconn
510 Right () <- commit sessionId dbconn
469
511
470 --delete no tuples
512 --delete no tuples
471 Right () <- executeDatabaseContextExpr sessionId dbconn (Delete "s" (AttributeEqualityPredicate "sname" (NakedAtomExpr (TextAtom "Mike"))))
513 Right () <- executeDatabaseContextExpr sessionId dbconn (Delete "s" (AttributeEqualityPredicate "sname" (NakedAtomExpr (TextAtom "Mike"))))
472 dirty''' <- disconnectedTransactionIsDirty sessionId dbconn
514 dirty''' <- disconnectedTransactionIsDirty sessionId dbconn
473− assertEqual "empty delete empty commit" (Right False) dirty'''
515+ assertEqual "empty delete empty commit" (Right True) dirty'''
474
516
475testIntervalAtom :: Test
517testIntervalAtom :: Test
476testIntervalAtom = TestCase $ do
518testIntervalAtom = TestCase $ do
@@ -516,7 +558,7 @@ testRestrictionPredicateExprs = TestCase $ do
516 -- and
558 -- and
517 executeTutorialD sessionId dbconn "x:=s where status=20 and status=10"
559 executeTutorialD sessionId dbconn "x:=s where status=20 and status=10"
518 eRvAnd <- executeRelationalExpr sessionId dbconn (RelationVariable "x" ())
560 eRvAnd <- executeRelationalExpr sessionId dbconn (RelationVariable "x" ())
519− let expectedRelAnd = Right (emptyRelationWithAttrs (attributes suppliersRel))
561+ let expectedRelAnd = Right (emptyRelationWithAttrs (R.attributes suppliersRel))
520 assertEqual "status 20 and 10" expectedRelAnd eRvAnd
562 assertEqual "status 20 and 10" expectedRelAnd eRvAnd
521
563
522testRelationalAttributeNames :: Test
564testRelationalAttributeNames :: Test
@@ -527,7 +569,7 @@ testRelationalAttributeNames = TestCase $ do
527 case eRv of
569 case eRv of
528 Left err -> assertFailure (show err)
570 Left err -> assertFailure (show err)
529 Right rel ->
571 Right rel ->
530− assertEqual "attributes from sp" (attributes supplierProductsRel) (attributes rel)
572+ assertEqual "attributes from sp" (R.attributes supplierProductsRel) (R.attributes rel)
531
573
532testSemijoin :: Test
574testSemijoin :: Test
533testSemijoin = TestCase $ do
575testSemijoin = TestCase $ do
@@ -587,4 +629,85 @@ testArbitraryRelation = TestCase $ do
587 (sessionId, dbconn) <- dateExamplesConnection emptyNotificationCallback
629 (sessionId, dbconn) <- dateExamplesConnection emptyNotificationCallback
588 executeTutorialD sessionId dbconn "createarbitraryrelation rv1 {a Integer} 5-10"
630 executeTutorialD sessionId dbconn "createarbitraryrelation rv1 {a Integer} 5-10"
589 executeTutorialD sessionId dbconn "createarbitraryrelation rv2 {a Integer, b relation{c Integer}} 10-100"
631 executeTutorialD sessionId dbconn "createarbitraryrelation rv2 {a Integer, b relation{c Integer}} 10-100"
590− executeTutorialD sessionId dbconn "createarbitraryrelation rv3 {a Int, b relation{c Interval Int}} 3-100"
632+ executeTutorialD sessionId dbconn "createarbitraryrelation rv3 {a Int, b relation{c Interval Int}} 3-100"
633+
634+testNonEmptyListType :: Test
635+testNonEmptyListType = TestCase $ do
636+ --create a NonEmptyList
637+ (sessionId, dbconn) <- dateExamplesConnection emptyNotificationCallback
638+ executeTutorialD sessionId dbconn "x:=relation{tuple{a NECons 3 (Cons 4 Empty)}} : {x:=nonEmptyListHead(@a)}"
639+ eX <- executeRelationalExpr sessionId dbconn (RelationVariable "x" ())
640+ let expected = mkRelationFromList attrs [[nelist, nehead]]
641+ attrs = attributesFromList [Attribute "a" neListType,
642+ Attribute "x" IntegerAtomType]
643+ neListType = nonEmptyListAtomType IntegerAtomType
644+ listType = listAtomType IntegerAtomType
645+ nelist = ConstructedAtom "NECons" (nonEmptyListAtomType IntegerAtomType) [
646+ IntegerAtom 3,
647+ ConstructedAtom "Cons" listType [IntegerAtom 4, ConstructedAtom "Empty" listType []]]
648+ nehead = IntegerAtom 3
649+ assertEqual "non-empty list type construction" expected eX
650+
651+testUnresolvedAtomTypes :: Test
652+testUnresolvedAtomTypes = TestCase $ do
653+ (sessionId, dbconn) <- dateExamplesConnection emptyNotificationCallback
654+ let err1 = "TypeConstructorTypeVarMissing"
655+ expectTutorialDErr sessionId dbconn (T.isPrefixOf err1) "x:=relation{tuple{a Empty}}"
656+ executeTutorialD sessionId dbconn "x:=relation{a List Int}{tuple{a Empty}}"
657+
658+-- with (x as s) s
659+testWithClause :: Test
660+testWithClause = TestCase $ do
661+ (sessionId, dbconn) <- dateExamplesConnection emptyNotificationCallback
662+ executeTutorialD sessionId dbconn "x:=with (x as s) x"
663+ eX <- executeRelationalExpr sessionId dbconn (RelationVariable "x" ())
664+ assertEqual "with x as s" (Right suppliersRel) eX
665+
666+ let err1 = "RelVarAlreadyDefinedError"
667+ expectTutorialDErr sessionId dbconn (T.isPrefixOf err1) "x:=with (s as s) s"
668+
669+ expectTutorialDErr sessionId dbconn (T.isPrefixOf err1) "x:=with (s as sp) s"
670+
671+testAtomFunctionArgumentMismatch :: Test
672+testAtomFunctionArgumentMismatch = TestCase $ do
673+ (sessionId, dbconn) <- dateExamplesConnection emptyNotificationCallback
674+ let err1 = "AtomTypeMismatchError"
675+ --atom function type mismatch
676+ expectTutorialDErr sessionId dbconn (T.isPrefixOf err1) "x:=relation{tuple{a 5}} where ^gt(@a,1.5)"
677+ --wrong argument count
678+ let err2 = "FunctionArgumentCountMismatchError"
679+ expectTutorialDErr sessionId dbconn (T.isPrefixOf err2) "x:=relation{tuple{a 5}} where ^gt(@a,1,3)"
680+
681+testInvalidDataConstructor :: Test
682+testInvalidDataConstructor = TestCase $ do
683+ --test that a referenced TypeConstructor in a DataConstructor definition matches the expected count of arguments
684+ (sessionId, dbconn) <- dateExamplesConnection emptyNotificationCallback
685+ let err1 = "ConstructedAtomArgumentCountMismatchError"
686+ expectTutorialDErr sessionId dbconn (T.isPrefixOf err1) "data TestT = TestT Maybe Int"
687+
688+testBasicList :: Test
689+testBasicList = TestCase $ do
690+ (sessionId, dbconn) <- dateExamplesConnection emptyNotificationCallback
691+ executeTutorialD sessionId dbconn "x := relation{tuple{ a (Cons 1 (Cons 2 Empty)) }}"
692+
693+testRelationDeclarationMismatch :: Test
694+testRelationDeclarationMismatch = TestCase $ do
695+ (sessionId, dbconn) <- dateExamplesConnection emptyNotificationCallback
696+ expectTutorialDErr sessionId dbconn (T.isPrefixOf "AtomTypeMismatchError") "data A a = A a | B | C; a := relation{a A Integer}{tuple{a A \"1\"}}"
697+
698+--generate errors when the tuples in a new relation don't match
699+testInvalidTuples :: Test
700+testInvalidTuples = TestCase $ do
701+ (sessionId, dbconn) <- dateExamplesConnection emptyNotificationCallback
702+ expectTutorialDErr sessionId dbconn (T.isPrefixOf "AttributeNamesMismatchError") ":showexpr relation{tuple{a 1},tuple{b 2}}"
703+ expectTutorialDErr sessionId dbconn (T.isPrefixOf "AttributeNamesMismatchError") ":showexpr relation{tuple{a 1},tuple{a 2, b 3}}"
704+-- expectTutorialDErr sessionId dbconn (T.isPrefixOf "ParseErrorBundle") ":showexpr relation{tuple{a 2, a 3}}" --parse failure can't be validated with this function
705+
706+testSelfReferencingUncommittedContext :: Test
707+testSelfReferencingUncommittedContext = TestCase $ do
708+ (sessionId, dbconn) <- dateExamplesConnection emptyNotificationCallback
709+ executeTutorialD sessionId dbconn "s:=s union s"
710+ eS <- executeRelationalExpr sessionId dbconn (RelationVariable "s" ())
711+ _ <- rollback sessionId dbconn
712+ eSorig <- executeRelationalExpr sessionId dbconn (RelationVariable "s" ())
713+ assertEqual "s=s'" eSorig eS
test/TutorialD/Interpreter/AtomFunctionScript.hs+25−17
@@ -1,25 +1,32 @@
1−import TutorialD.Interpreter.TestBase
1+{-# LANGUAGE CPP #-}
2import System.Exit
2import System.Exit
3import Test.HUnit
3import Test.HUnit
4+#ifdef PM36_HASKELL_SCRIPTING
5+import TutorialD.Interpreter.TestBase
4import ProjectM36.Client
6import ProjectM36.Client
5import ProjectM36.Relation
7import ProjectM36.Relation
6import ProjectM36.DataTypes.Maybe
8import ProjectM36.DataTypes.Maybe
7import qualified Data.Vector as V
9import qualified Data.Vector as V
8import qualified Data.Map as M
10import qualified Data.Map as M
11+#endif
9
12
10{-# ANN module ("HLint: ignore Reduce duplication" :: String) #-}
13{-# ANN module ("HLint: ignore Reduce duplication" :: String) #-}
11main :: IO ()
14main :: IO ()
12main = do
15main = do
13− tcounts <- runTestTT (TestList [testBasicAtomFunction,
16+ tcounts <- runTestTT (TestList [
17+#ifdef PM36_HASKELL_SCRIPTING
18+ testBasicAtomFunction,
14− testExceptionAtomFunction,
19+ testExceptionAtomFunction,
15− testErrorAtomFunction,
20+ testErrorAtomFunction,
16− testNoArgumentAtomFunction,
21+ testNoArgumentAtomFunction,
17− testArgumentTypeMismatch,
22+ testArgumentTypeMismatch,
18− testPolymorphicReturnType,
23+ testPolymorphicReturnType,
19− testScriptedTypeVariable
24+ testScriptedTypeVariable
25+#endif
20− ])
26+ ])
21 if errors tcounts + failures tcounts > 0 then exitFailure else exitSuccess
27 if errors tcounts + failures tcounts > 0 then exitFailure else exitSuccess
22
28
29+#ifdef PM36_HASKELL_SCRIPTING
23--add an atom function and run it
30--add an atom function and run it
24testBasicAtomFunction :: Test
31testBasicAtomFunction :: Test
25testBasicAtomFunction = TestCase $ do
32testBasicAtomFunction = TestCase $ do
@@ -29,7 +36,7 @@ testBasicAtomFunction = TestCase $ do
29 funcAtomExpr = FunctionAtomExpr "mkTest" [NakedAtomExpr (IntegerAtom 3)] ()
36 funcAtomExpr = FunctionAtomExpr "mkTest" [NakedAtomExpr (IntegerAtom 3)] ()
30 tupleExprs = [TupleExpr (M.singleton "x" funcAtomExpr)]
37 tupleExprs = [TupleExpr (M.singleton "x" funcAtomExpr)]
31 expectedResult = mkRelationFromList (V.fromList attrs) [[IntegerAtom 3]]
38 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))
33
40
34 assertEqual "simple atom function equality" expectedResult result
41 assertEqual "simple atom function equality" expectedResult result
35
42
@@ -40,7 +47,7 @@ testExceptionAtomFunction = TestCase $ do
40 executeTutorialD sess conn "addatomfunction \"mkTest\" Integer -> Either AtomFunctionError Integer \"\"\"(\\(IntegerAtom x:xs) -> (error (show 1))) :: [Atom] -> Either AtomFunctionError Atom\"\"\""
47 executeTutorialD sess conn "addatomfunction \"mkTest\" Integer -> Either AtomFunctionError Integer \"\"\"(\\(IntegerAtom x:xs) -> (error (show 1))) :: [Atom] -> Either AtomFunctionError Atom\"\"\""
41 let attrs = [Attribute "x" IntegerAtomType]
48 let attrs = [Attribute "x" IntegerAtomType]
42 funcAtomExpr = FunctionAtomExpr "mkTest" [NakedAtomExpr (IntegerAtom 3)] ()
49 funcAtomExpr = FunctionAtomExpr "mkTest" [NakedAtomExpr (IntegerAtom 3)] ()
43− tupleExprs = [TupleExpr (M.singleton "x" funcAtomExpr)]
50+ tupleExprs = TupleExprs () [TupleExpr (M.singleton "x" funcAtomExpr)]
44 result <- executeRelationalExpr sess conn (MakeRelationFromExprs (Just (map NakedAttributeExpr attrs)) tupleExprs)
51 result <- executeRelationalExpr sess conn (MakeRelationFromExprs (Just (map NakedAttributeExpr attrs)) tupleExprs)
45 assertBool "catch error exception from script" (case result of
52 assertBool "catch error exception from script" (case result of
46 Left (UnhandledExceptionError _) -> True
53 Left (UnhandledExceptionError _) -> True
@@ -57,7 +64,7 @@ testNoArgumentAtomFunction = TestCase $ do
57 executeTutorialD sess conn "addatomfunction \"mkTest\" Either AtomFunctionError Integer \"\"\"(\\x -> pure (IntegerAtom 5)) :: [Atom] -> Either AtomFunctionError Atom\"\"\""
64 executeTutorialD sess conn "addatomfunction \"mkTest\" Either AtomFunctionError Integer \"\"\"(\\x -> pure (IntegerAtom 5)) :: [Atom] -> Either AtomFunctionError Atom\"\"\""
58 let attrs = [Attribute "x" IntegerAtomType]
65 let attrs = [Attribute "x" IntegerAtomType]
59 funcAtomExpr = FunctionAtomExpr "mkTest" [] ()
66 funcAtomExpr = FunctionAtomExpr "mkTest" [] ()
60− tupleExprs = [TupleExpr (M.singleton "x" funcAtomExpr)]
67+ tupleExprs = TupleExprs () [TupleExpr (M.singleton "x" funcAtomExpr)]
61 expectedResult = mkRelationFromList (V.fromList attrs) [[IntegerAtom 5]]
68 expectedResult = mkRelationFromList (V.fromList attrs) [[IntegerAtom 5]]
62 result <- executeRelationalExpr sess conn (MakeRelationFromExprs (Just (map NakedAttributeExpr attrs)) tupleExprs)
69 result <- executeRelationalExpr sess conn (MakeRelationFromExprs (Just (map NakedAttributeExpr attrs)) tupleExprs)
63 assertEqual "no argument scripted function" expectedResult result
70 assertEqual "no argument scripted function" expectedResult result
@@ -66,7 +73,7 @@ testArgumentTypeMismatch :: Test
66testArgumentTypeMismatch = TestCase $ do
73testArgumentTypeMismatch = TestCase $ do
67 (sess, conn) <- dateExamplesConnection emptyNotificationCallback
74 (sess, conn) <- dateExamplesConnection emptyNotificationCallback
68 executeTutorialD sess conn "addatomfunction \"mkTest\" Integer -> Either AtomFunctionError Integer \"\"\"(\\(IntegerAtom x:_) -> pure $ TextAtom \"wrong type\") :: [Atom] -> Either AtomFunctionError Atom\"\"\""
75 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)]
70 funcAtomExpr = FunctionAtomExpr "mkTest" [NakedAtomExpr (IntegerAtom 3)] ()
77 funcAtomExpr = FunctionAtomExpr "mkTest" [NakedAtomExpr (IntegerAtom 3)] ()
71 attrs = [Attribute "x" IntegerAtomType]
78 attrs = [Attribute "x" IntegerAtomType]
72 expectedResult = Left (AtomTypeMismatchError IntegerAtomType TextAtomType)
79 expectedResult = Left (AtomTypeMismatchError IntegerAtomType TextAtomType)
@@ -80,7 +87,7 @@ testPolymorphicReturnType = TestCase $ do
80 let funcAtomExpr = FunctionAtomExpr "fromMaybe" [NakedAtomExpr (IntegerAtom 5),
87 let funcAtomExpr = FunctionAtomExpr "fromMaybe" [NakedAtomExpr (IntegerAtom 5),
81 NakedAtomExpr maybeAtom] ()
88 NakedAtomExpr maybeAtom] ()
82 maybeAtom = ConstructedAtom "Just" (maybeAtomType IntegerAtomType) [IntegerAtom 3]
89 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)])
84 mRelType <- typeForRelationalExpr sess conn relExpr
91 mRelType <- typeForRelationalExpr sess conn relExpr
85 case mRelType of
92 case mRelType of
86 Left err -> assertFailure (show err)
93 Left err -> assertFailure (show err)
@@ -94,7 +101,7 @@ testPolymorphicReturnType = TestCase $ do
94 let failFuncAtomExpr = FunctionAtomExpr "fromMaybe" [NakedAtomExpr (IntegerAtom 5),
101 let failFuncAtomExpr = FunctionAtomExpr "fromMaybe" [NakedAtomExpr (IntegerAtom 5),
95 NakedAtomExpr mismatchAtom] ()
102 NakedAtomExpr mismatchAtom] ()
96 mismatchAtom = ConstructedAtom "Just" (maybeAtomType TextAtomType) [TextAtom "fail"]
103 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)])
98 mFailRes <- executeRelationalExpr sess conn failRelExpr
105 mFailRes <- executeRelationalExpr sess conn failRelExpr
99 let expectedErr = Left (AtomFunctionTypeVariableMismatch "a" IntegerAtomType TextAtomType)
106 let expectedErr = Left (AtomFunctionTypeVariableMismatch "a" IntegerAtomType TextAtomType)
100 assertEqual "expected type variable mismatch" expectedErr mFailRes
107 assertEqual "expected type variable mismatch" expectedErr mFailRes
@@ -106,9 +113,10 @@ testScriptedTypeVariable = TestCase $ do
106 executeTutorialD sess conn "addatomfunction \"idTest\" a -> Either AtomFunctionError a \"(\\\\(x:_) -> pure x) :: [Atom] -> Either AtomFunctionError Atom\""
113 executeTutorialD sess conn "addatomfunction \"idTest\" a -> Either AtomFunctionError a \"(\\\\(x:_) -> pure x) :: [Atom] -> Either AtomFunctionError Atom\""
107 let attrs = [Attribute "x" IntegerAtomType]
114 let attrs = [Attribute "x" IntegerAtomType]
108 funcAtomExpr = FunctionAtomExpr "idTest" [NakedAtomExpr (IntegerAtom 3)] ()
115 funcAtomExpr = FunctionAtomExpr "idTest" [NakedAtomExpr (IntegerAtom 3)] ()
109− tupleExprs = [TupleExpr (M.singleton "x" funcAtomExpr)]
116+ tupleExprs = TupleExprs () [TupleExpr (M.singleton "x" funcAtomExpr)]
110 expectedResult = mkRelationFromList (V.fromList attrs) [[IntegerAtom 3]]
117 expectedResult = mkRelationFromList (V.fromList attrs) [[IntegerAtom 3]]
111 result <- executeRelationalExpr sess conn (MakeRelationFromExprs (Just (map NakedAttributeExpr attrs)) tupleExprs)
118 result <- executeRelationalExpr sess conn (MakeRelationFromExprs (Just (map NakedAttributeExpr attrs)) tupleExprs)
112
119
113 assertEqual "id function equality" expectedResult result
120 assertEqual "id function equality" expectedResult result
114−
121+
122+#endif
test/TutorialD/Interpreter/DatabaseContextFunctionScript.hs+16−8
@@ -1,28 +1,36 @@
1−import TutorialD.Interpreter.TestBase
1+{-# LANGUAGE CPP #-}
2import System.Exit
2import System.Exit
3import Test.HUnit
3import Test.HUnit
4+#ifdef PM36_HASKELL_SCRIPTING
5+import TutorialD.Interpreter.TestBase
4import ProjectM36.Client
6import ProjectM36.Client
5import ProjectM36.Relation
7import ProjectM36.Relation
6import qualified Data.Text as T
8import qualified Data.Text as T
9+#endif
7
10
8main :: IO ()
11main :: IO ()
9main = do
12main = do
10− tcounts <- runTestTT (TestList [testBasicDBCFunction,
13+ tcounts <- runTestTT (TestList [
14+#ifdef PM36_HASKELL_SCRIPTING
15+ testBasicDBCFunction,
11− testErrorDBCFunction,
16+ testErrorDBCFunction,
12− testExceptionDBCFunction,
17+ testExceptionDBCFunction,
13− testDBCFunctionWithAtomArguments
18+ testDBCFunctionWithAtomArguments
19+#endif
14 ])
20 ])
15 if errors tcounts + failures tcounts > 0 then exitFailure else exitSuccess
21 if errors tcounts + failures tcounts > 0 then exitFailure else exitSuccess
16
22
23+#ifdef PM36_HASKELL_SCRIPTING
17testBasicDBCFunction :: Test
24testBasicDBCFunction :: Test
18testBasicDBCFunction = TestCase $ do
25testBasicDBCFunction = TestCase $ do
19 (sess, conn) <- dateExamplesConnection emptyNotificationCallback
26 (sess, conn) <- dateExamplesConnection emptyNotificationCallback
20 let addfunc = "adddatabasecontextfunction \"addTrue2\" DatabaseContext -> Either DatabaseContextFunctionError DatabaseContext \"\"\"(\\[] ctx -> executeDatabaseContextExpr (Assign \"true2\" (ExistingRelation relationTrue)) ctx) :: [Atom] -> DatabaseContext -> Either DatabaseContextFunctionError DatabaseContext\"\"\""
27 let addfunc = "adddatabasecontextfunction \"addTrue2\" DatabaseContext -> Either DatabaseContextFunctionError DatabaseContext \"\"\"(\\[] ctx -> executeDatabaseContextExpr (Assign \"true2\" (ExistingRelation relationTrue)) ctx) :: [Atom] -> DatabaseContext -> Either DatabaseContextFunctionError DatabaseContext\"\"\""
21 executeTutorialD sess conn addfunc
28 executeTutorialD sess conn addfunc
22 executeTutorialD sess conn "execute addTrue2()"
29 executeTutorialD sess conn "execute addTrue2()"
30+ {-
23 let true2Expr = RelationVariable "true2" ()
31 let true2Expr = RelationVariable "true2" ()
24 result <- executeRelationalExpr sess conn true2Expr
32 result <- executeRelationalExpr sess conn true2Expr
25− assertEqual "simple atom function equality" (Right relationTrue) result
33+ assertEqual "simple atom function equality" (Right relationTrue) result-}
26
34
27testErrorDBCFunction :: Test
35testErrorDBCFunction :: Test
28testErrorDBCFunction = TestCase $ do
36testErrorDBCFunction = TestCase $ do
@@ -37,7 +45,7 @@ testExceptionDBCFunction = TestCase $ do
37 (sess, conn) <- dateExamplesConnection emptyNotificationCallback
45 (sess, conn) <- dateExamplesConnection emptyNotificationCallback
38 let addfunc = "adddatabasecontextfunction \"bomb\" DatabaseContext -> Either DatabaseContextFunctionError DatabaseContext \"\"\"(\\[] _ -> error \"boom\") :: [Atom] -> DatabaseContext -> Either DatabaseContextFunctionError DatabaseContext\"\"\""
46 let addfunc = "adddatabasecontextfunction \"bomb\" DatabaseContext -> Either DatabaseContextFunctionError DatabaseContext \"\"\"(\\[] _ -> error \"boom\") :: [Atom] -> DatabaseContext -> Either DatabaseContextFunctionError DatabaseContext\"\"\""
39 executeTutorialD sess conn addfunc
47 executeTutorialD sess conn addfunc
40− expectTutorialDErr sess conn (\err -> "UnhandledExceptionError" `T.isPrefixOf` err) "execute bomb()"
48+ expectTutorialDErr sess conn ("UnhandledExceptionError" `T.isPrefixOf`) "execute bomb()"
41
49
42
50
43testDBCFunctionWithAtomArguments :: Test
51testDBCFunctionWithAtomArguments :: Test
@@ -54,4 +62,4 @@ testDBCFunctionWithAtomArguments = TestCase $ do
54 assertEqual "person relation" expectedPerson result
62 assertEqual "person relation" expectedPerson result
55 expectTutorialDErr sess conn (T.isPrefixOf "AtomTypeMismatchError") "execute multiArgFunc(\"fail\", \"fail\")"
63 expectTutorialDErr sess conn (T.isPrefixOf "AtomTypeMismatchError") "execute multiArgFunc(\"fail\", \"fail\")"
56
64
57−
65+#endif
test/TutorialD/Interpreter/Import/TutorialD.hs+2−2
@@ -20,10 +20,10 @@ testTutdImport = TestCase $
20 hClose handle
20 hClose handle
21 let expectedExpr = MultipleExpr [
21 let expectedExpr = MultipleExpr [
22 Assign "x" (MakeRelationFromExprs Nothing
22 Assign "x" (MakeRelationFromExprs Nothing
23− [TupleExpr (M.fromList [("a", NakedAtomExpr $ IntegerAtom 5),
23+ $ TupleExprs () [TupleExpr (M.fromList [("a", NakedAtomExpr $ IntegerAtom 5),
24 ("b", NakedAtomExpr $ TextAtom "spam")])]),
24 ("b", NakedAtomExpr $ TextAtom "spam")])]),
25 Assign "y" (MakeRelationFromExprs Nothing
25 Assign "y" (MakeRelationFromExprs Nothing
26− [TupleExpr (M.fromList [("b", NakedAtomExpr (TextAtom "漢字"))])])]
26+ $ TupleExprs () [TupleExpr (M.fromList [("b", NakedAtomExpr (TextAtom "漢字"))])])]
27 imported <- importTutorialD tempPath
27 imported <- importTutorialD tempPath
28 assertEqual "import tutd" (Right expectedExpr) imported
28 assertEqual "import tutd" (Right expectedExpr) imported
29
29
test/TutorialD/Interpreter/TestBase.hs+7−8
@@ -2,16 +2,14 @@ module TutorialD.Interpreter.TestBase where
2import ProjectM36.Client
2import ProjectM36.Client
3import TutorialD.Interpreter
3import TutorialD.Interpreter
4import TutorialD.Interpreter.Base
4import TutorialD.Interpreter.Base
5−import qualified ProjectM36.Base as Base
6import ProjectM36.DateExamples
5import ProjectM36.DateExamples
6+import ProjectM36.DatabaseContext
7import Test.HUnit
7import Test.HUnit
8−import qualified Data.Map as M
9import Data.Text
8import Data.Text
10
9
11dateExamplesConnection :: NotificationCallback -> IO (SessionId, Connection)
10dateExamplesConnection :: NotificationCallback -> IO (SessionId, Connection)
12dateExamplesConnection callback = do
11dateExamplesConnection callback = do
13 dbconn <- connectProjectM36 (InProcessConnectionInfo NoPersistence callback [])
12 dbconn <- connectProjectM36 (InProcessConnectionInfo NoPersistence callback [])
14− let incDeps = Base.inclusionDependencies dateExamples
15 case dbconn of
13 case dbconn of
16 Left err -> error (show err)
14 Left err -> error (show err)
17 Right conn -> do
15 Right conn -> do
@@ -19,8 +17,7 @@ dateExamplesConnection callback = do
19 case eSessionId of
17 case eSessionId of
20 Left err -> error (show err)
18 Left err -> error (show err)
21 Right sessionId -> do
19 Right sessionId -> do
22− mapM_ (\(rvName,rvRel) -> executeDatabaseContextExpr sessionId conn (Assign rvName (Base.ExistingRelation rvRel))) (M.toList (Base.relationVariables dateExamples))
20+ executeDatabaseContextExpr sessionId conn (databaseContextAsDatabaseContextExpr dateExamples) >>= eitherFail
23− mapM_ (\(idName,incDep) -> executeDatabaseContextExpr sessionId conn (AddInclusionDependency idName incDep)) (M.toList incDeps)
24 --skipping atom functions for now- there are no atom function manipulation operators yet
21 --skipping atom functions for now- there are no atom function manipulation operators yet
25 commit sessionId conn >>= eitherFail
22 commit sessionId conn >>= eitherFail
26 pure (sessionId, conn)
23 pure (sessionId, conn)
@@ -35,8 +32,9 @@ executeTutorialD sessionId conn tutd = case parseTutorialD tutd of
35 DisplayResult _ -> assertFailure "display?"
32 DisplayResult _ -> assertFailure "display?"
36 DisplayIOResult _ -> assertFailure "displayIO?"
33 DisplayIOResult _ -> assertFailure "displayIO?"
37 DisplayRelationResult _ -> assertFailure "displayrelation?"
34 DisplayRelationResult _ -> assertFailure "displayrelation?"
35+ DisplayDataFrameResult _ -> assertFailure "displaydataframe?"
38 DisplayParseErrorResult _ _ -> assertFailure "displayparseerrorresult?"
36 DisplayParseErrorResult _ _ -> assertFailure "displayparseerrorresult?"
39− DisplayErrorResult err -> assertFailure (show err)
37+ DisplayErrorResult err -> assertFailure (show tutd ++ ": " ++ show err)
40 QuietSuccessResult -> pure ()
38 QuietSuccessResult -> pure ()
41
39
42expectTutorialDErr :: SessionId -> Connection -> (Text -> Bool) -> Text -> IO ()
40expectTutorialDErr :: SessionId -> Connection -> (Text -> Bool) -> Text -> IO ()
@@ -49,10 +47,11 @@ expectTutorialDErr sessionId conn matchFunc tutd = case parseTutorialD tutd of
49 DisplayResult _ -> assertFailure "display?"
47 DisplayResult _ -> assertFailure "display?"
50 DisplayIOResult _ -> assertFailure "displayIO?"
48 DisplayIOResult _ -> assertFailure "displayIO?"
51 DisplayRelationResult _ -> assertFailure "displayrelation?"
49 DisplayRelationResult _ -> assertFailure "displayrelation?"
50+ DisplayDataFrameResult _ -> assertFailure "displaydataframe?"
52 DisplayParseErrorResult _ _ -> assertFailure "displayparseerrorresult?"
51 DisplayParseErrorResult _ _ -> assertFailure "displayparseerrorresult?"
53− DisplayErrorResult err -> assertBool ("match error on: " ++ unpack err) (matchFunc err)
52+ DisplayErrorResult err -> assertBool (unpack tutd ++ " match error on: " ++ unpack err) (matchFunc err)
54 QuietSuccessResult -> pure ()
53 QuietSuccessResult -> pure ()
55
54
56eitherFail :: Either RelationalError a -> IO ()
55eitherFail :: Either RelationalError a -> IO ()
57eitherFail (Left err) = assertFailure (show err)
56eitherFail (Left err) = assertFailure (show err)
58−eitherFail (Right _) = pure ()
57+eitherFail (Right _) = pure ()