on master help sign in
.github/workflows/build.yaml+3−3
since splitsnapshots
unifiedsplit
@@ -9,14 +9,14 @@ jobs:
9 persist-credentials: false
9 persist-credentials: false
10 submodules: true
10 submodules: true
11
11
12− - uses: cachix/install-nix-action@v12
12+ - uses: cachix/install-nix-action@v14.1
13 with:
13 with:
14 nix_path: nixpkgs=channel:nixos-unstable
14 nix_path: nixpkgs=channel:nixos-unstable
15 extra_nix_config: |
15 extra_nix_config: |
16 trusted-public-keys = cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY= hydra.iohk.io:f/Ea+s+dFdN+3Y/G+FDgSq+a5NEWhJGzdjvKNGv0/EQ=
16 trusted-public-keys = cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY= hydra.iohk.io:f/Ea+s+dFdN+3Y/G+FDgSq+a5NEWhJGzdjvKNGv0/EQ=
17− substituters = https://cache.nixos.org/ https://hydra.iohk.io
17+ substituters = https://cache.nixos.org/ https://cache.iog.io
18
18
19− - uses: cachix/cachix-action@v8
19+ - uses: cachix/cachix-action@v10
20 with:
20 with:
21 name: rel8
21 name: rel8
22 authToken: '${{ secrets.CACHIX_AUTH_TOKEN }}'
22 authToken: '${{ secrets.CACHIX_AUTH_TOKEN }}'
Changelog.md+128−1
@@ -1,13 +1,140 @@
1−# 1.1.0.0 (??)
1+# 1.4.0.0 (2002-08-17)
2
2
3## Breaking changes
3## Breaking changes
4
4
5+* The behavior of `greatest`/`least` has been corrected, and was previously flipped. ([#183](https://github.com/circuithub/rel8/pull/183))
6+
7+## New features
8+
9+* `NullTable`/`HNull` have been added. This is an alternative to `MaybeTable` that doesn't use a tag columns. It's less flexible (no `Functor` or `Applicative` instance) and is meaningless when used with a table that has no non-nullable columns (so nesting `NullTable` is redundant). But in situations where the underlying `Table` does have non-nullable columns, it can losslessly converted to and from `MaybeTable`. It is useful for embedding into a base table when you don't want to store the extra tag column in your schema. ([#173](https://github.com/circuithub/rel8/pull/173))
10+* Add `fromMaybeTable`. ([#179](https://github.com/circuithub/rel8/pull/179))
11+* Add `alignMaybeTable`. ([#196](https://github.com/circuithub/rel8/pull/196))
12+
13+## Improvements
14+
15+* Optimize implementation of `AltTable` for `Tabulation` ([#178](https://github.com/circuithub/rel8/pull/178))
16+
17+## Other
18+
19+* Documentation improvements for `HADT`. ([#177](https://github.com/circuithub/rel8/pull/177))
20+* Document example usage of `groupBy`. ([#184](https://github.com/circuithub/rel8/pull/184))
21+* Build with and require Opaleye >= 0.9.3.3. ([#190](https://github.com/circuithub/rel8/pull/190))
22+* Build with `hasql` 1.6. ([#195](https://github.com/circuithub/rel8/pull/195))
23+
24+# 1.3.1.0 (2022-01-20)
25+
26+## Other
27+
28+* Rel8 now requires Opaleye >= 0.9.1. ([#165](https://github.com/circuithub/rel8/pull/165))
29+
30+# 1.3.0.0 (2022-01-31)
31+
32+## Breaking changes
33+
34+* `div` and `mod` have been changed to match Haskell semantics. If you need the PostgreSQL `div()` and `mod()` functions, use `quot` and `rem`. While this is not an API change, we feel this is a breaking change in semantics and have bumped the major version number. ([#155](https://github.com/circuithub/rel8/pull/155))
35+
36+## New features
37+
38+* `divMod` and `quotRem` functions have been added, matching Haskell's `Prelude` functions. ([#155](https://github.com/circuithub/rel8/pull/155))
39+* `avg` and `mode` aggregation functions to find the mean value of an expression, or the most common row in a query, respectively. ([#152](https://github.com/circuithub/rel8/pull/152))
40+* The full `EqTable` and `OrdTable` classes have been exported, allowing for instances to be manually created. ([#157](https://github.com/circuithub/rel8/pull/157))
41+* Added `like` and `ilike` (for the `LIKE` and `ILIKE` operators). ([#146](https://github.com/circuithub/rel8/pull/146))
42+
43+## Other
44+
45+* Rel8 now requires Opaleye 0.9. ([#158](https://github.com/circuithub/rel8/pull/158))
46+* Rel8's test suite supports Hedgehog 1.1. ([#160](https://github.com/circuithub/rel8/pull/160))
47+* The documentation for binary operations has been corrected. ([#162](https://github.com/circuithub/rel8/pull/162))
48+
49+# 1.2.2.0 (2021-11-21)
50+
51+## Other
52+
53+* Support GHC 9.2 ([#145](https://github.com/circuithub/rel8/pull/145))
54+* Correct the documentation for `except` ([#147](https://github.com/circuithub/rel8/pull/147))
55+* Support `hasql` 1.5 ([#149](https://github.com/circuithub/rel8/pull/149))
56+
57+# 1.2.1.0 (2021-11-21)
58+
59+## New features
60+
61+* `castTable` has been added, which casts all columns selected from in `Query` according to the types of columns. This can occasionally be useful when using `many`/`some` on older PostgreSQL versions. ([#137](https://github.com/circuithub/rel8/pull/137))
62+
63+* Added `<:`, `<=:`, `>:`, `>=:`, `greatest` and `least`, which sort all columns in a table lexicographically. These operators are like the `<.` operators which operate on `Expr`s, but the `<:` operate on entire tables. ([#139](https://github.com/circuithub/rel8/pull/139))
64+
65+## Other
66+
67+* Support opaleye-0.8 ([#142](https://github.com/circuithub/rel8/pull/142))
68+
69+# 1.2.0.0 (2021-10-22)
70+
71+## New features
72+
73+* New `$*` and `$+` operators for projecting out of `ListTable` and `NonEmptyTable` respectively (analogous to the existing `$?` for `MaybeTable`). ([#125](https://github.com/circuithub/rel8/pull/125))
74+
75+## Bug fixes
76+
77+* Fix `UPSERT` support (and add tests), which was broken due to a typo inside Rel8 that made it impossible to construct `Projection`s which are needed by `UPSERT`. ([#134](https://github.com/circuithub/rel8/pull/134))
78+
79+* Remove `DBMin` and `DBMax` instances for `Bool`, which are invalid as far as Postgres is concerned. `and` and `or` can be used to achieve the same thing. ([#126](https://github.com/circuithub/rel8/pull/126))
80+
81+* Fix `aggregateMaybeTable`, `aggregateEitherTable` and `aggregateTheseTable`, which generated invalid SQL previously. ([#127](https://github.com/circuithub/rel8/pull/127))
82+
83+## Breaking changes
84+
85+* `rebind` now takes an additional argument for the "name" of the binding. ([#128](https://github.com/circuithub/rel8/pull/128))
86+
87+# 1.1.0.0 (2021-07-16)
88+
89+## New features
90+
91+* You can derive `Rel8able` for "vanilla" higher-kinded data types - data types that don't use the `Column` type family. For example, the following is now possible:
92+
93+ ```haskell
94+ data MyTable f = MyTable
95+ { myTableX :: f Int32
96+ , myTableY :: f Text
97+ } deriving (Generic, Rel8able)
98+ ```
99+
100+* The `Projectable` and `Biprojectable` type classes have been introduced. These classes model a type of functors and bifunctors (respectively) on tables, where the mapping function is only able to rearrange columns. For example, the following is now possible:
101+
102+ ```haskell
103+ x <- project myTableX <$> many ...
104+ ```
105+
106+* `Insert`'s `onConflict` field now has a new option - `DoUpdate`. This maps to PostgreSQL's `ON CONFLICT DO UPDATE` syntax, which provides upsert support. ([#85](https://github.com/circuithub/rel8/pull/85))
107+
108+* `Insert`, `Update` and `Delete` has all been expanded to work with `Query`s. In particular:
109+
110+ * `Delete` now supports a `USING` sub-query
111+ * `Update` now supports a `FROM` sub-query
112+ * `Insert` can delete the result of any arbitrary `Query` (providing the types match)
113+
114+* The new `Rel8.Tabulate` module has been added, which gives a `Map`-esque interface to writing and composing queries. ([#70](https://github.com/circuithub/rel8/pull/70))
115+
116+* The new `indexed` `Query -> Query` function was added. This function augments each row in a query with it's 0-based index. ([#117](https://github.com/circuithub/rel8/pull/117))
117+
118+## Breaking changes
119+
120+* `Insert`, `Delete` and `Update` have all changed. In particular, for `Insert` users should now replace `rows = xs` with `rows = values xs`. ([#85](https://github.com/circuithub/rel8/pull/85))
121+
5* Rename `whereExists` and `whereNotExists` to `present` and `absent` respectively. ([#57](https://github.com/circuithub/rel8/pull/57))
122* Rename `whereExists` and `whereNotExists` to `present` and `absent` respectively. ([#57](https://github.com/circuithub/rel8/pull/57))
6
123
7* Simplify `evaluate` to run directly inside the `Query` monad, rendering the `Evaluate` monad unnecessary. ([#56](https://github.com/circuithub/rel8/pull/56))
124* Simplify `evaluate` to run directly inside the `Query` monad, rendering the `Evaluate` monad unnecessary. ([#56](https://github.com/circuithub/rel8/pull/56))
8
125
9* The `Labelable` type class has been removed as it's no longer necessary. This class was mostly internal, though was visible in some public API functions. ([#76](https://github.com/circuithub/rel8/pull/76))
126* The `Labelable` type class has been removed as it's no longer necessary. This class was mostly internal, though was visible in some public API functions. ([#76](https://github.com/circuithub/rel8/pull/76))
10
127
128+* `EitherTable`, `ListTable`, `MaybeTable`, `NonEmptyTable` and `TheseTable` now all have an extra parameter which tracks the context of the table. If you manually specified any types before, you need to provide this parameter - usually `Expr` will be the correct choice. ([#101](https://github.com/circuithub/rel8/pull/101))
129+
130+* We've done a lot of work to simplify the internals of Rel8, but some of these are breaking changes. However, most of these API changes shouldn't affect users as they are mostly types used in type inference, or affect classes where users don't need to define their own instances.
131+
132+ * The kind of a `Rel8able` is now `(Type -> Type) -> Type`. Previously it was `(X -> Type) -> Type`.
133+ * `Table` has a new associated type - `FromExprs`. This was previously an open type family.
134+ * `Table` has a new associated type - `Transpose` - and `Recontextualise` has been renamed to `Transposes`. This `Transposes` class now operates in terms of `Transpose`.
135+
136+* `select`, `insert`, `update` and `delete` now produce Hasql `Statement`s, rather than actually running the statement as IO. This allows Rel8 to be used with transaction/connection-managing monads like [`hasql-transaction`](https://hackage.haskell.org/package/hasql-transaction). ([#94](https://github.com/circuithub/rel8/pull/94))
137+
11## Bug fixes
138## Bug fixes
12
139
13* Fixes a bug where cartesian products of queries using `catListTable`, `catNonEmptyTable`, `catList` and `catNonEmpty` would incorrectly be zipped instead. ([#61](https://github.com/circuithub/rel8/pull/61))
140* Fixes a bug where cartesian products of queries using `catListTable`, `catNonEmptyTable`, `catList` and `catNonEmpty` would incorrectly be zipped instead. ([#61](https://github.com/circuithub/rel8/pull/61))
cabal.project−5
@@ -1,6 +1 @@
1packages: .
1packages: .
2−
3−allow-newer: generic-monoid:base
4−allow-newer: cryptohash-sha1:base
5−allow-newer: cryptohash-md5:base
6−allow-newer: entropy:Cabal
cabal.project.haskell-nix−6
@@ -2,9 +2,3 @@
2-- will interpret them as local packages, and try to build them when we cabal
2-- will interpret them as local packages, and try to build them when we cabal
3-- build. The only reason we have to specify these is for Haskell.nix to know to
3-- build. The only reason we have to specify these is for Haskell.nix to know to
4-- override these packages by fetching them rather than using Hackage.
4-- override these packages by fetching them rather than using Hackage.
5−
6−source-repository-package
7− type: git
8− location: git://github.com/jcpetruzza/barbies
9− tag: f99b05454874192e3511bd133555dfb6cc6a6ecb
10− --sha256: 0yy2i2jbllwavv5d2176rf8lmm4l1ws90lxkmdlfgvfzqxidx0gi
default.nix+2−2
@@ -1,11 +1,11 @@
1let
1let
2 haskellNix = import (import ./nix/sources.nix)."haskell.nix" {};
2 haskellNix = import (import ./nix/sources.nix)."haskell.nix" {};
3
3
4− nixpkgsSrc = haskellNix.sources.nixpkgs-2009;
4+ nixpkgsSrc = haskellNix.sources.nixpkgs-unstable;
5
5
6 nixpkgsArgs = haskellNix.nixpkgsArgs;
6 nixpkgsArgs = haskellNix.nixpkgsArgs;
7
7
8− compiler-nix-name = "ghc901";
8+ compiler-nix-name = "ghc924";
9
9
10 pkgs = import nixpkgsSrc nixpkgsArgs;
10 pkgs = import nixpkgsSrc nixpkgsArgs;
11
11
docs/concepts/insert.rst+37−10
@@ -21,9 +21,16 @@ using ``delete``. ``Delete`` takes:
21``from``
21``from``
22 The ``TableSchema`` for the table to delete rows from.
22 The ``TableSchema`` for the table to delete rows from.
23
23
24+``using``
25+ This is a simple ``Query`` that forms the ``USING`` clause of the ``DELETE``
26+ statement. This can be used to join against other tables, and the results
27+ can be referenced in the ``deleteWhere`` parameter. For simple ``DELETE``\s
28+ where you don't need to do this, you can set ``using = pure ()``.
29+
24``deleteWhere``
30``deleteWhere``
25 The ``WHERE`` clause of the ``DELETE`` statement. This is a function that
31 The ``WHERE`` clause of the ``DELETE`` statement. This is a function that
26− takes a single ``Expr`` table as input.
32+ takes two inputs: the result of the ``using`` query, and the current value
33+ of the row.
27
34
28``returning``
35``returning``
29 What to return - see :ref:`returning`.
36 What to return - see :ref:`returning`.
@@ -37,16 +44,23 @@ using ``update``. ``Update`` takes:
37``target``
44``target``
38 The ``TableSchema`` for the table to update rows in.
45 The ``TableSchema`` for the table to update rows in.
39
46
40−``updateWhere``
47+``from``
41− The ``WHERE`` clause of the ``UPDATE`` statement. This is a function that
48+ This is a simple ``Query`` that forms the ``FROM`` clause of the ``UPDATE``
42− takes a single ``Expr`` table as input.
49+ statement. This can be used to join against other tables, and the results
50+ can be referenced in the ``set`` and ``updateWhere`` parameters. For simple
51+ ``UPDATE``\s where you don't need to do this, you can set ``from = pure ()``.
43
52
44``set``
53``set``
45 A row to row transformation function, indicating how to update selected rows.
54 A row to row transformation function, indicating how to update selected rows.
46 This function takes rows of the same shape as ``target`` but in the ``Expr``
55 This function takes rows of the same shape as ``target`` but in the ``Expr``
47 context. One way to write this function is to use record update syntax::
56 context. One way to write this function is to use record update syntax::
48
57
49− set = \row -> row { rowName = "new name" }
58+ set = \from row -> row { rowName = "new name" }
59+
60+``updateWhere``
61+ The ``WHERE`` clause of the ``UPDATE`` statement. This is a function that
62+ takes two inputs: the result of the ``from`` query, and the current value of
63+ the row.
50
64
51``returning``
65``returning``
52 What to return - see :ref:`returning`.
66 What to return - see :ref:`returning`.
@@ -64,11 +78,11 @@ using ``insert``. ``Insert`` takes:
64 The rows to insert. These are the same as ``into``, but in the ``Expr``
78 The rows to insert. These are the same as ``into``, but in the ``Expr``
65 context. You can construct rows from their individual fields::
79 context. You can construct rows from their individual fields::
66
80
67− rows = [ MyTable { myTableA = lit "A", myTableB = lit 42 }
81+ rows = values [ MyTable { myTableA = lit "A", myTableB = lit 42 }
68
82
69 or you can use ``lit`` on a table value in the ``Result`` context::
83 or you can use ``lit`` on a table value in the ``Result`` context::
70
84
71− rows = [ lit MyTable { myTableA = "A", myTableB = 42 }
85+ rows = values [ lit MyTable { myTableA = "A", myTableB = 42 }
72
86
73``onConflict``
87``onConflict``
74 What should happen if an insert clashes with rows that already exist. This
88 What should happen if an insert clashes with rows that already exist. This
@@ -80,6 +94,10 @@ using ``insert``. ``Insert`` takes:
80 ``DoNothing``
94 ``DoNothing``
81 PostgreSQL should not insert the duplicate rows.
95 PostgreSQL should not insert the duplicate rows.
82
96
97+ ``DoUpdate``
98+ PostgreSQL should instead try to update any existing rows that conflict
99+ with rows proposed for insertion.
100+
83``returning``
101``returning``
84 What to return - see :ref:`returning`.
102 What to return - see :ref:`returning`.
85
103
@@ -99,11 +117,20 @@ For example, if we are inserting orders, we might want the order ids returned::
99
117
100 insert Insert
118 insert Insert
101 { into = orderSchema
119 { into = orderSchema
102− , rows = [ order ]
120+ , rows = values [ order ]
103 , onConflict = Abort
121 , onConflict = Abort
104 , returning = Projection orderId
122 , returning = Projection orderId
105 }
123 }
106
124
125+If we don't want to return anything, we can use ``pure ()``::
126+
127+ insert Insert
128+ { into = orderSchema
129+ , rows = values [ order ]
130+ , onConflict = Abort
131+ , returning = pure ()
132+ }
133+
107Default values
134Default values
108--------------
135--------------
109
136
@@ -119,7 +146,7 @@ construct the ``DEFAULT`` expression::
119
146
120 insert Insert
147 insert Insert
121 { into = orderSchema
148 { into = orderSchema
122− , rows = [ Order { orderId = unsafeDefault, ... } ]
149+ , rows = values [ Order { orderId = unsafeDefault, ... } ]
123 , onConflict = Abort
150 , onConflict = Abort
124 , returning = Projection orderId
151 , returning = Projection orderId
125 }
152 }
@@ -148,7 +175,7 @@ them in Rel8, rather than in your database schema.
148
175
149 insert Insert
176 insert Insert
150 { into = orderSchema
177 { into = orderSchema
151− , rows = [ Order { orderId = nextval "order_id_seq", ... } ]
178+ , rows = values [ Order { orderId = nextval "order_id_seq", ... } ]
152 , onConflict = Abort
179 , onConflict = Abort
153 , returning = Projection orderId
180 , returning = Projection orderId
154 }
181 }
docs/cookbook.rst+9−7
@@ -142,23 +142,25 @@ rows, but can also return *tree*\s.
142To understand what this means, we'll consider a small example query for blog
142To understand what this means, we'll consider a small example query for blog
143posts. We want our query to return:
143posts. We want our query to return:
144
144
145−1. The latest 5 blog posts.
145+1. The latest 5 blog posts that have at least one tag each.
1462. For each blog post, all tags.
1462. For each blog post, all tags.
147−3. For each blog post, the latest 3 comments.
147+3. For each blog post, the latest 3 comments if they exist.
148
148
149In Rel8, we can write this query as::
149In Rel8, we can write this query as::
150
150
151 latestBlogPosts = do
151 latestBlogPosts = do
152 post <- each postSchema
152 post <- each postSchema
153
153
154+ -- Returns a `NonEmptyTable a` which ends up as a `Data.List.NonEmpty a` after the query is run
154− tags <- aggregate do
155+ tags <- some $ do
155 tag <- each tagSchema
156 tag <- each tagSchema
156 where_ (tagPostId tag ==. postId post)
157 where_ (tagPostId tag ==. postId post)
157− return (listAgg (tagName tag))
158+ return (tagName tag)
158
159
160+ -- Returns a `ListTable a` which ends up as a `[a]` after the query is run
159− latestComments <-
161+ latestComments <-
160− many $
162+ many $
161− limit 3 $
163+ limit 3 $
162 orderBy (commentCreatedAt >$< desc) do
164 orderBy (commentCreatedAt >$< desc) do
163 comment <- each commentSchema
165 comment <- each commentSchema
164 where_ (commentPostId comment ==. postId post)
166 where_ (commentPostId comment ==. postId post)
nix/sources.json+9−9
@@ -5,10 +5,10 @@
5 "homepage": "https://input-output-hk.github.io/haskell.nix",
5 "homepage": "https://input-output-hk.github.io/haskell.nix",
6 "owner": "input-output-hk",
6 "owner": "input-output-hk",
7 "repo": "haskell.nix",
7 "repo": "haskell.nix",
8− "rev": "3856d2d24dca0ecc71fcfc314253a2a2d07a3c4f",
8+ "rev": "0837156c56cb5350dd9bd84eb424187e00aa1e8a",
9− "sha256": "0s69nasqhkv8n0qmdv075k83p3z584ja9vkzdnp2291mymghvx87",
9+ "sha256": "1djmv5a0vfj78csw2cad6nicrs8iqrp928b9b3v4h7lwwhhzliwl",
10 "type": "tarball",
10 "type": "tarball",
11− "url": "https://github.com/input-output-hk/haskell.nix/archive/3856d2d24dca0ecc71fcfc314253a2a2d07a3c4f.tar.gz",
11+ "url": "https://github.com/input-output-hk/haskell.nix/archive/0837156c56cb5350dd9bd84eb424187e00aa1e8a.tar.gz",
12 "url_template": "https://github.com/<owner>/<repo>/archive/<rev>.tar.gz"
12 "url_template": "https://github.com/<owner>/<repo>/archive/<rev>.tar.gz"
13 },
13 },
14 "niv": {
14 "niv": {
@@ -17,10 +17,10 @@
17 "homepage": "https://github.com/nmattia/niv",
17 "homepage": "https://github.com/nmattia/niv",
18 "owner": "nmattia",
18 "owner": "nmattia",
19 "repo": "niv",
19 "repo": "niv",
20− "rev": "e0ca65c81a2d7a4d82a189f1e23a48d59ad42070",
20+ "rev": "acdb1726783637852c01e0ad639ac9cbec28d8c8",
21− "sha256": "1pq9nh1d8nn3xvbdny8fafzw87mj7gsmp6pxkdl65w2g18rmcmzx",
21+ "sha256": "1wszl8q70z6wfgkh2dvgmhhry6qp9nar421qq2ifd17hq2jj9ck3",
22 "type": "tarball",
22 "type": "tarball",
23− "url": "https://github.com/nmattia/niv/archive/e0ca65c81a2d7a4d82a189f1e23a48d59ad42070.tar.gz",
23+ "url": "https://github.com/nmattia/niv/archive/acdb1726783637852c01e0ad639ac9cbec28d8c8.tar.gz",
24 "url_template": "https://github.com/<owner>/<repo>/archive/<rev>.tar.gz"
24 "url_template": "https://github.com/<owner>/<repo>/archive/<rev>.tar.gz"
25 },
25 },
26 "nixpkgs": {
26 "nixpkgs": {
@@ -29,10 +29,10 @@
29 "homepage": null,
29 "homepage": null,
30 "owner": "nixos",
30 "owner": "nixos",
31 "repo": "nixpkgs",
31 "repo": "nixpkgs",
32− "rev": "59b8d9cf24e9fcf10341a0923c9bdca088dca8c8",
32+ "rev": "1c1f5649bb9c1b0d98637c8c365228f57126f361",
33− "sha256": "08f38v4b2kcxnbapdwrb54bglka92cxj9qlnqlk5px206jyq9v4c",
33+ "sha256": "0f2nvdijyxfgl5kwyb4465pppd5vkhqxddx6v40k2s0z9jfhj0xl",
34 "type": "tarball",
34 "type": "tarball",
35− "url": "https://github.com/nixos/nixpkgs/archive/59b8d9cf24e9fcf10341a0923c9bdca088dca8c8.tar.gz",
35+ "url": "https://github.com/nixos/nixpkgs/archive/1c1f5649bb9c1b0d98637c8c365228f57126f361.tar.gz",
36 "url_template": "https://github.com/<owner>/<repo>/archive/<rev>.tar.gz"
36 "url_template": "https://github.com/<owner>/<repo>/archive/<rev>.tar.gz"
37 }
37 }
38}
38}
nix/sources.nix+21−1
@@ -31,8 +31,28 @@ let
31 if spec ? branch then "refs/heads/${spec.branch}" else
31 if spec ? branch then "refs/heads/${spec.branch}" else
32 if spec ? tag then "refs/tags/${spec.tag}" else
32 if spec ? tag then "refs/tags/${spec.tag}" else
33 abort "In git source '${name}': Please specify `ref`, `tag` or `branch`!";
33 abort "In git source '${name}': Please specify `ref`, `tag` or `branch`!";
34+ submodules = if spec ? submodules then spec.submodules else false;
35+ submoduleArg =
36+ let
37+ nixSupportsSubmodules = builtins.compareVersions builtins.nixVersion "2.4" >= 0;
38+ emptyArgWithWarning =
39+ if submodules == true
40+ then
41+ builtins.trace
42+ (
43+ "The niv input \"${name}\" uses submodules "
44+ + "but your nix's (${builtins.nixVersion}) builtins.fetchGit "
45+ + "does not support them"
46+ )
47+ {}
48+ else {};
49+ in
50+ if nixSupportsSubmodules
51+ then { inherit submodules; }
52+ else emptyArgWithWarning;
34 in
53 in
54+ builtins.fetchGit
35− builtins.fetchGit { url = spec.repo; inherit (spec) rev; inherit ref; };
55+ ({ url = spec.repo; inherit (spec) rev; inherit ref; } // submoduleArg);
36
56
37 fetch_local = spec: spec.path;
57 fetch_local = spec: spec.path;
38
58
rel8.cabal+31−11
@@ -1,6 +1,6 @@
1cabal-version: 2.0
1cabal-version: 2.0
2name: rel8
2name: rel8
3−version: 1.0.0.1
3+version: 1.4.0.0
4synopsis: Hey! Hey! Can u rel8?
4synopsis: Hey! Hey! Can u rel8?
5license: BSD3
5license: BSD3
6license-file: LICENSE
6license-file: LICENSE
@@ -20,21 +20,23 @@ source-repository head
20library
20library
21 build-depends:
21 build-depends:
22 aeson
22 aeson
23− , base ^>= 4.14 || ^>=4.15
23+ , base ^>= 4.14 || ^>=4.15 || ^>=4.16
24+ , bifunctors
24 , bytestring
25 , bytestring
25 , case-insensitive
26 , case-insensitive
26 , comonad
27 , comonad
27 , contravariant
28 , contravariant
28− , hasql ^>= 1.4.5.1
29+ , hasql ^>= 1.4.5.1 || ^>= 1.5.0.0 || ^>= 1.6.0.0
29− , opaleye ^>= 0.7.3.0
30+ , opaleye ^>= 0.9.6.1
31+ , pretty
30 , profunctors
32 , profunctors
33+ , product-profunctors
31 , scientific
34 , scientific
32 , semialign
35 , semialign
33 , semigroupoids
36 , semigroupoids
34 , text
37 , text
35 , these
38 , these
36 , time
39 , time
37− , transformers
38 , uuid
40 , uuid
39 default-language:
41 default-language:
40 Haskell2010
42 Haskell2010
@@ -44,6 +46,7 @@ library
44 -Wno-missing-import-lists -Wno-prepositive-qualified-module
46 -Wno-missing-import-lists -Wno-prepositive-qualified-module
45 -Wno-monomorphism-restriction
47 -Wno-monomorphism-restriction
46 -Wno-missing-local-signatures
48 -Wno-missing-local-signatures
49+ -Wno-missing-kind-signatures
47 hs-source-dirs:
50 hs-source-dirs:
48 src
51 src
49 exposed-modules:
52 exposed-modules:
@@ -51,6 +54,7 @@ library
51 Rel8.Expr.Num
54 Rel8.Expr.Num
52 Rel8.Expr.Text
55 Rel8.Expr.Text
53 Rel8.Expr.Time
56 Rel8.Expr.Time
57+ Rel8.Tabulate
54
58
55 other-modules:
59 other-modules:
56 Rel8.Aggregate
60 Rel8.Aggregate
@@ -62,6 +66,7 @@ library
62 Rel8.Column.List
66 Rel8.Column.List
63 Rel8.Column.Maybe
67 Rel8.Column.Maybe
64 Rel8.Column.NonEmpty
68 Rel8.Column.NonEmpty
69+ Rel8.Column.Null
65 Rel8.Column.These
70 Rel8.Column.These
66
71
67 Rel8.Expr
72 Rel8.Expr
@@ -77,6 +82,7 @@ library
77 Rel8.Expr.Order
82 Rel8.Expr.Order
78 Rel8.Expr.Sequence
83 Rel8.Expr.Sequence
79 Rel8.Expr.Serialize
84 Rel8.Expr.Serialize
85+ Rel8.Expr.Window
80
86
81 Rel8.FCF
87 Rel8.FCF
82
88
@@ -103,20 +109,23 @@ library
103 Rel8.Query.Evaluate
109 Rel8.Query.Evaluate
104 Rel8.Query.Exists
110 Rel8.Query.Exists
105 Rel8.Query.Filter
111 Rel8.Query.Filter
112+ Rel8.Query.Indexed
106 Rel8.Query.Limit
113 Rel8.Query.Limit
107 Rel8.Query.List
114 Rel8.Query.List
108 Rel8.Query.Maybe
115 Rel8.Query.Maybe
109 Rel8.Query.Null
116 Rel8.Query.Null
110 Rel8.Query.Opaleye
117 Rel8.Query.Opaleye
111 Rel8.Query.Order
118 Rel8.Query.Order
119+ Rel8.Query.Rebind
112 Rel8.Query.Set
120 Rel8.Query.Set
113 Rel8.Query.SQL
121 Rel8.Query.SQL
114 Rel8.Query.These
122 Rel8.Query.These
115 Rel8.Query.Values
123 Rel8.Query.Values
124+ Rel8.Query.Window
116
125
117 Rel8.Schema.Context.Nullify
126 Rel8.Schema.Context.Nullify
118− Rel8.Schema.Context.Virtual
119 Rel8.Schema.Dict
127 Rel8.Schema.Dict
128+ Rel8.Schema.Field
120 Rel8.Schema.HTable
129 Rel8.Schema.HTable
121 Rel8.Schema.HTable.Either
130 Rel8.Schema.HTable.Either
122 Rel8.Schema.HTable.Identity
131 Rel8.Schema.HTable.Identity
@@ -134,15 +143,19 @@ library
134 Rel8.Schema.Null
143 Rel8.Schema.Null
135 Rel8.Schema.Result
144 Rel8.Schema.Result
136 Rel8.Schema.Spec
145 Rel8.Schema.Spec
137− Rel8.Schema.Spec.Constrain
138 Rel8.Schema.Table
146 Rel8.Schema.Table
139
147
140 Rel8.Statement.Delete
148 Rel8.Statement.Delete
141 Rel8.Statement.Insert
149 Rel8.Statement.Insert
150+ Rel8.Statement.OnConflict
142 Rel8.Statement.Returning
151 Rel8.Statement.Returning
143 Rel8.Statement.Select
152 Rel8.Statement.Select
153+ Rel8.Statement.Set
154+ Rel8.Statement.SQL
144 Rel8.Statement.Update
155 Rel8.Statement.Update
156+ Rel8.Statement.Using
145 Rel8.Statement.View
157 Rel8.Statement.View
158+ Rel8.Statement.Where
146
159
147 Rel8.Table
160 Rel8.Table
148 Rel8.Table.ADT
161 Rel8.Table.ADT
@@ -157,15 +170,18 @@ library
157 Rel8.Table.Maybe
170 Rel8.Table.Maybe
158 Rel8.Table.Name
171 Rel8.Table.Name
159 Rel8.Table.NonEmpty
172 Rel8.Table.NonEmpty
173+ Rel8.Table.Null
160 Rel8.Table.Nullify
174 Rel8.Table.Nullify
161 Rel8.Table.Opaleye
175 Rel8.Table.Opaleye
162 Rel8.Table.Ord
176 Rel8.Table.Ord
163 Rel8.Table.Order
177 Rel8.Table.Order
164− Rel8.Table.Recontextualize
178+ Rel8.Table.Projection
165 Rel8.Table.Rel8able
179 Rel8.Table.Rel8able
166 Rel8.Table.Serialize
180 Rel8.Table.Serialize
167 Rel8.Table.These
181 Rel8.Table.These
182+ Rel8.Table.Transpose
168 Rel8.Table.Undefined
183 Rel8.Table.Undefined
184+ Rel8.Table.Window
169
185
170 Rel8.Type
186 Rel8.Type
171 Rel8.Type.Array
187 Rel8.Type.Array
@@ -184,6 +200,9 @@ library
184 Rel8.Type.Sum
200 Rel8.Type.Sum
185 Rel8.Type.Tag
201 Rel8.Type.Tag
186
202
203+ Rel8.Window
204+
205+
187test-suite tests
206test-suite tests
188 type: exitcode-stdio-1.0
207 type: exitcode-stdio-1.0
189 build-depends:
208 build-depends:
@@ -192,9 +211,9 @@ test-suite tests
192 , case-insensitive
211 , case-insensitive
193 , containers
212 , containers
194 , hasql
213 , hasql
214+ , hasql-transaction
195− , hedgehog ^>=1.0.2
215+ , hedgehog ^>= 1.0 || ^>= 1.1
196− , lifted-base ^>=0.2.3.12
216+ , mmorph
197− , monad-control ^>=1.0.2.3
198 , rel8
217 , rel8
199 , scientific
218 , scientific
200 , tasty
219 , tasty
@@ -202,6 +221,7 @@ test-suite tests
202 , text
221 , text
203 , time
222 , time
204 , tmp-postgres ^>=1.34.1.0
223 , tmp-postgres ^>=1.34.1.0
224+ , transformers
205 , uuid
225 , uuid
206
226
207 other-modules:
227 other-modules:
shell.nix+1−1
@@ -1,6 +1,6 @@
1let
1let
2 sources = import ./nix/sources.nix;
2 sources = import ./nix/sources.nix;
3− pkgs = import sources.nixpkgs {};
3+ pkgs = import sources.nixpkgs {overlays = [];};
4 hsPkgs = import ./default.nix;
4 hsPkgs = import ./default.nix;
5in
5in
6 hsPkgs.shellFor {
6 hsPkgs.shellFor {
src/Rel8.hs+297−10
@@ -38,24 +38,27 @@ module Rel8
38 , HMaybe
38 , HMaybe
39 , HList
39 , HList
40 , HNonEmpty
40 , HNonEmpty
41+ , HNull
41 , HThese
42 , HThese
42 , Lift
43 , Lift
43
44
44 , Table(..)
45 , Table(..)
45 , HTable
46 , HTable
46− , Recontextualize
47+ , Transposes
47 , AltTable((<|>:))
48 , AltTable((<|>:))
48 , AlternativeTable( emptyTable )
49 , AlternativeTable( emptyTable )
49− , EqTable, (==:), (/=:)
50+ , EqTable(..), (==:), (/=:)
50− , OrdTable, ascTable, descTable
51+ , OrdTable(..), (<:), (<=:), (>:), (>=:), ascTable, descTable, greatest, least
51 , lit
52 , lit
52 , bool
53 , bool
53 , case_
54 , case_
55+ , castTable
54
56
55 -- ** @MaybeTable@
57 -- ** @MaybeTable@
56 , MaybeTable
58 , MaybeTable
57 , maybeTable, ($?), nothingTable, justTable
59 , maybeTable, ($?), nothingTable, justTable
58 , isNothingTable, isJustTable
60 , isNothingTable, isJustTable
61+ , fromMaybeTable
59 , optional
62 , optional
60 , catMaybeTable
63 , catMaybeTable
61 , traverseMaybeTable
64 , traverseMaybeTable
@@ -78,6 +81,7 @@ module Rel8
78 , isThisTable, isThatTable, isThoseTable
81 , isThisTable, isThatTable, isThoseTable
79 , hasHereTable, hasThereTable
82 , hasHereTable, hasThereTable
80 , justHereTable, justThereTable
83 , justHereTable, justThereTable
84+ , alignMaybeTable
81 , alignBy
85 , alignBy
82 , keepHereTable, loseHereTable
86 , keepHereTable, loseHereTable
83 , keepThereTable, loseThereTable
87 , keepThereTable, loseThereTable
@@ -90,7 +94,7 @@ module Rel8
90
94
91 -- ** @ListTable@
95 -- ** @ListTable@
92 , ListTable
96 , ListTable
93− , listTable
97+ , listTable, ($*)
94 , nameListTable
98 , nameListTable
95 , many
99 , many
96 , manyExpr
100 , manyExpr
@@ -99,21 +103,44 @@ module Rel8
99
103
100 -- ** @NonEmptyTable@
104 -- ** @NonEmptyTable@
101 , NonEmptyTable
105 , NonEmptyTable
102− , nonEmptyTable
106+ , nonEmptyTable, ($+)
103 , nameNonEmptyTable
107 , nameNonEmptyTable
104 , some
108 , some
105 , someExpr
109 , someExpr
106 , catNonEmptyTable
110 , catNonEmptyTable
107 , catNonEmpty
111 , catNonEmpty
108
112
109− -- ** @ADT@
113+ -- ** @NullTable@
114+ , NullTable
115+ , nullableTable, nullTable, nullifyTable
116+ , isNullTable, isNonNullTable
117+ , catNullTable
118+ , nameNullTable
119+ , toNullTable, toMaybeTable
120+
121+ -- ** Algebraic data types / sum types
122+ -- $adts
123+
124+ -- *** Naming of ADTs
125+ -- $naming
126+ , NameADT, nameADT
110 , ADT, ADTable
127 , ADT, ADTable
128+
129+ -- *** Deconstruction of ADTs
130+ -- $deconstruction
131+ , DeconstructADT, deconstructADT
132+
133+ -- *** Construction of ADTs
134+ -- $construction
111 , BuildADT, buildADT
135 , BuildADT, buildADT
112 , ConstructADT, constructADT
136 , ConstructADT, constructADT
113− , DeconstructADT, deconstructADT
137+
114− , NameADT, nameADT
138+ -- *** Other ADT operations
115 , AggregateADT, aggregateADT
139 , AggregateADT, aggregateADT
116
140
141+ -- *** Miscellaneous notes
142+ -- $misc-notes
143+
117 -- ** @HKD@
144 -- ** @HKD@
118 , HKD, HKDable
145 , HKD, HKDable
119 , BuildHKD, buildHKD
146 , BuildHKD, buildHKD
@@ -138,6 +165,7 @@ module Rel8
138 -- ** @null@
165 -- ** @null@
139 , NotNull
166 , NotNull
140 , Nullable
167 , Nullable
168+ , Homonullable
141 , null
169 , null
142 , nullify
170 , nullify
143 , nullable
171 , nullable
@@ -156,6 +184,7 @@ module Rel8
156 , (==.), (/=.), (==?), (/=?)
184 , (==.), (/=.), (==?), (/=?)
157 , in_
185 , in_
158 , boolExpr, caseExpr
186 , boolExpr, caseExpr
187+ , like, ilike
159
188
160 -- ** Ordering
189 -- ** Ordering
161 , DBOrd
190 , DBOrd
@@ -173,6 +202,13 @@ module Rel8
173 , Query
202 , Query
174 , showQuery
203 , showQuery
175
204
205+ -- ** Projection
206+ , Projection
207+ , Projectable( project )
208+ , Biprojectable( biproject )
209+ , Projecting
210+ , Field
211+
176 -- ** Selecting rows
212 -- ** Selecting rows
177 , Selects
213 , Selects
178 , each
214 , each
@@ -217,10 +253,11 @@ module Rel8
217 , countRows
253 , countRows
218 , groupBy
254 , groupBy
219 , listAgg, listAggExpr
255 , listAgg, listAggExpr
256+ , mode
220 , nonEmptyAgg, nonEmptyAggExpr
257 , nonEmptyAgg, nonEmptyAggExpr
221 , DBMax, max
258 , DBMax, max
222 , DBMin, min
259 , DBMin, min
223− , DBSum, sum, sumWhere
260+ , DBSum, sum, sumWhere, avg
224 , DBString, stringAgg
261 , DBString, stringAgg
225 , count
262 , count
226 , countStar
263 , countStar
@@ -237,6 +274,32 @@ module Rel8
237 , nullsFirst
274 , nullsFirst
238 , nullsLast
275 , nullsLast
239
276
277+ -- ** Window functions
278+ , Window
279+ , window
280+ , Partition
281+ , over
282+ , partitionBy
283+ , orderPartitionBy
284+ , cumulative
285+ , cumulative_
286+ , currentRow
287+ , rowNumber
288+ , rank
289+ , denseRank
290+ , percentRank
291+ , cumeDist
292+ , ntile
293+ , lag
294+ , lead
295+ , firstValue
296+ , lastValue
297+ , nthValue
298+ , indexed
299+
300+ -- ** Bindings
301+ , rebind
302+
240 -- * IO
303 -- * IO
241 , Serializable
304 , Serializable
242 , ToExprs
305 , ToExprs
@@ -251,22 +314,27 @@ module Rel8
251 -- ** @INSERT@
314 -- ** @INSERT@
252 , Insert(..)
315 , Insert(..)
253 , OnConflict(..)
316 , OnConflict(..)
317+ , Upsert(..)
254 , insert
318 , insert
255 , unsafeDefault
319 , unsafeDefault
320+ , showInsert
256
321
257 -- ** @DELETE@
322 -- ** @DELETE@
258 , Delete(..)
323 , Delete(..)
259 , delete
324 , delete
325+ , showDelete
260
326
261 -- ** @UPDATE@
327 -- ** @UPDATE@
262 , Update(..)
328 , Update(..)
263 , update
329 , update
330+ , showUpdate
264
331
265 -- ** @.. RETURNING@
332 -- ** @.. RETURNING@
266 , Returning(..)
333 , Returning(..)
267
334
268 -- ** @CREATE VIEW@
335 -- ** @CREATE VIEW@
269 , createView
336 , createView
337+ , createOrReplaceView
270
338
271 -- ** Sequences
339 -- ** Sequences
272 , nextval
340 , nextval
@@ -285,6 +353,7 @@ import Rel8.Column.Lift
285import Rel8.Column.List
353import Rel8.Column.List
286import Rel8.Column.Maybe
354import Rel8.Column.Maybe
287import Rel8.Column.NonEmpty
355import Rel8.Column.NonEmpty
356+import Rel8.Column.Null
288import Rel8.Column.These
357import Rel8.Column.These
289import Rel8.Expr
358import Rel8.Expr
290import Rel8.Expr.Aggregate
359import Rel8.Expr.Aggregate
@@ -298,6 +367,8 @@ import Rel8.Expr.Ord
298import Rel8.Expr.Order
367import Rel8.Expr.Order
299import Rel8.Expr.Serialize
368import Rel8.Expr.Serialize
300import Rel8.Expr.Sequence
369import Rel8.Expr.Sequence
370+import Rel8.Expr.Text ( like, ilike )
371+import Rel8.Expr.Window hiding ( cumulative )
301import Rel8.Generic.Rel8able ( KRel8able, Rel8able )
372import Rel8.Generic.Rel8able ( KRel8able, Rel8able )
302import Rel8.Order
373import Rel8.Order
303import Rel8.Query
374import Rel8.Query
@@ -308,15 +379,19 @@ import Rel8.Query.Either
308import Rel8.Query.Evaluate
379import Rel8.Query.Evaluate
309import Rel8.Query.Exists
380import Rel8.Query.Exists
310import Rel8.Query.Filter
381import Rel8.Query.Filter
382+import Rel8.Query.Indexed
311import Rel8.Query.Limit
383import Rel8.Query.Limit
312import Rel8.Query.List
384import Rel8.Query.List
313import Rel8.Query.Maybe
385import Rel8.Query.Maybe
314import Rel8.Query.Null
386import Rel8.Query.Null
315import Rel8.Query.Order
387import Rel8.Query.Order
388+import Rel8.Query.Rebind
316import Rel8.Query.SQL (showQuery)
389import Rel8.Query.SQL (showQuery)
317import Rel8.Query.Set
390import Rel8.Query.Set
318import Rel8.Query.These
391import Rel8.Query.These
319import Rel8.Query.Values
392import Rel8.Query.Values
393+import Rel8.Query.Window
394+import Rel8.Schema.Field
320import Rel8.Schema.HTable
395import Rel8.Schema.HTable
321import Rel8.Schema.Name
396import Rel8.Schema.Name
322import Rel8.Schema.Null hiding ( nullable )
397import Rel8.Schema.Null hiding ( nullable )
@@ -324,8 +399,10 @@ import Rel8.Schema.Result ( Result )
324import Rel8.Schema.Table
399import Rel8.Schema.Table
325import Rel8.Statement.Delete
400import Rel8.Statement.Delete
326import Rel8.Statement.Insert
401import Rel8.Statement.Insert
402+import Rel8.Statement.OnConflict
327import Rel8.Statement.Returning
403import Rel8.Statement.Returning
328import Rel8.Statement.Select
404import Rel8.Statement.Select
405+import Rel8.Statement.SQL
329import Rel8.Statement.Update
406import Rel8.Statement.Update
330import Rel8.Statement.View
407import Rel8.Statement.View
331import Rel8.Table
408import Rel8.Table
@@ -340,12 +417,16 @@ import Rel8.Table.List
340import Rel8.Table.Maybe
417import Rel8.Table.Maybe
341import Rel8.Table.Name
418import Rel8.Table.Name
342import Rel8.Table.NonEmpty
419import Rel8.Table.NonEmpty
420+import Rel8.Table.Null
421+import Rel8.Table.Opaleye ( castTable )
343import Rel8.Table.Ord
422import Rel8.Table.Ord
344import Rel8.Table.Order
423import Rel8.Table.Order
345−import Rel8.Table.Recontextualize
424+import Rel8.Table.Projection
346import Rel8.Table.Rel8able ()
425import Rel8.Table.Rel8able ()
347import Rel8.Table.Serialize
426import Rel8.Table.Serialize
348import Rel8.Table.These
427import Rel8.Table.These
428+import Rel8.Table.Transpose
429+import Rel8.Table.Window
349import Rel8.Type
430import Rel8.Type
350import Rel8.Type.Composite
431import Rel8.Type.Composite
351import Rel8.Type.Eq
432import Rel8.Type.Eq
@@ -360,6 +441,7 @@ import Rel8.Type.ReadShow
360import Rel8.Type.Semigroup
441import Rel8.Type.Semigroup
361import Rel8.Type.String
442import Rel8.Type.String
362import Rel8.Type.Sum
443import Rel8.Type.Sum
444+import Rel8.Window
363
445
364
446
365-- $running
447-- $running
@@ -367,3 +449,208 @@ import Rel8.Type.Sum
367-- provides 'select', 'insert', 'update' and 'delete' functions. Note that
449-- provides 'select', 'insert', 'update' and 'delete' functions. Note that
368-- 'insert', 'update' and 'delete' will generally need the
450-- 'insert', 'update' and 'delete' will generally need the
369-- `DuplicateRecordFields` language extension enabled.
451-- `DuplicateRecordFields` language extension enabled.
452+
453+-- $adts
454+-- Algebraic data types can be modelled between Haskell and SQL.
455+--
456+-- * Your SQL table needs a certain text field that tags which Haskell constructor is in use.
457+-- * You have to use a few combinators to specify the sum type's individual constructors.
458+-- * If you want to do case analysis at the @Expr@ (SQL) level, you can use 'maybe'/'either'-like eliminators.
459+--
460+-- The documentation in this section will assume a set of database types like this:
461+--
462+-- @
463+-- data Thing f = ThingEmployer (Employer f) | ThingPotato (Potato f) | Nullary
464+-- deriving stock Generic
465+--
466+-- data Employer f = Employer { employerId :: f Int32, employerName :: f Text}
467+-- deriving stock Generic
468+-- deriving anyclass Rel8able
469+--
470+-- data Potato f = Potato { size :: f Int32, grower :: f Text }
471+-- deriving stock Generic
472+-- deriving anyclass Rel8able
473+-- @
474+
475+-- $naming
476+--
477+-- First, in your 'TableSchema', name your type like this:
478+--
479+-- @
480+-- thingSchema :: TableSchema (ADT Thing Name)
481+-- thingSchema =
482+-- TableSchema
483+-- { schema = Nothing,
484+-- name = \"thing\",
485+-- columns =
486+-- nameADT @Thing
487+-- \"tag\"
488+-- Employer
489+-- { employerName = \"name\",
490+-- employerId = \"id\"
491+-- }
492+-- Potato {size = \"size\", grower = \"Mary\"}
493+-- }
494+-- @
495+--
496+-- Note that @nameADT \@Thing "tag"@ is variadic: it accepts one
497+-- argument per constructor, except the nullary ones (Nullary) because
498+-- there's nothing to do for them.
499+
500+-- $deconstruction
501+--
502+-- To deconstruct sum types at the SQL level, use 'deconstructADT',
503+-- which is also variadic, and has one argument for each
504+-- constructor. Similar to 'maybe'.
505+--
506+-- @
507+-- query :: Query (ADT Thing Expr)
508+-- query = do
509+-- thingExpr <- each thingSchema
510+-- where_ $
511+-- deconstructADT @Thing
512+-- (\employer -> employerName employer ==. lit \"Mary\")
513+-- (\potato -> grower potato ==. lit \"Mary\")
514+-- (lit False) -- Nullary case
515+-- thingExpr
516+-- pure thingExpr
517+-- @
518+--
519+-- SQL output:
520+--
521+-- @
522+-- SELECT
523+-- CAST("tag0_1" AS text) as "tag",
524+-- CAST("id1_1" AS int4) as "ThingEmployer/_1/employerId",
525+-- CAST("name2_1" AS text) as "ThingEmployer/_1/employerName",
526+-- CAST("size3_1" AS int4) as "ThingPotato/_1/size",
527+-- CAST("Mary4_1" AS text) as "ThingPotato/_1/grower"
528+-- FROM (SELECT
529+-- *
530+-- FROM (SELECT
531+-- "tag" as "tag0_1",
532+-- "id" as "id1_1",
533+-- "name" as "name2_1",
534+-- "size" as "size3_1",
535+-- "Mary" as "Mary4_1"
536+-- FROM "thing" as "T1") as "T1"
537+-- WHERE (CASE WHEN ("tag0_1") = (CAST(E'ThingPotato' AS text)) THEN ("Mary4_1") = (CAST(E'Mary' AS text))
538+-- WHEN ("tag0_1") = (CAST(E'Nullary' AS text)) THEN CAST(FALSE AS bool) ELSE ("name2_1") = (CAST(E'Mary' AS text)) END)) as "T1"
539+-- @
540+
541+-- $construction
542+--
543+-- To construct an ADT, you can use 'buildADT' or 'constructADT'. Consider the following type:
544+--
545+-- @
546+-- data Task f = Pending | Complete (CompletedTask f)
547+-- @
548+--
549+-- 'buildADT' is for constructing values of 'Task' in the 'Expr'
550+-- context. 'buildADT' needs two type-level arguments before its type
551+-- makes any sense. The first argument is the type of the "ADT", which
552+-- in our case is 'Task'. The second is the name of the constructor we
553+-- want to use. So that means we have the following possible
554+-- instantiations of 'buildADT' for 'Task':
555+--
556+-- @
557+-- > :t buildADT @Task @\"Pending\"
558+-- buildADT @Task @\"Pending\" :: ADT Task Expr
559+-- > :t buildADT @Task @\"Complete\"
560+-- buildADT @Task @\"Complete\" :: CompletedTask Expr -> ADT Task Expr
561+-- @
562+--
563+-- Note that as the "Pending" constructor has no fields, @buildADT
564+-- \@Task \@"Pending"@ is equivalent to @lit Pending@. But @buildADT
565+-- \@Task \@"Complete"@ is not the same as @lit . Complete@:
566+--
567+-- @
568+-- > :t lit . Complete
569+-- lit . Complete :: CompletedTask Result -> ADT Task Expr
570+-- @
571+--
572+--
573+-- Note that the former takes a @CompletedTask Expr@ while the latter
574+-- takes a @CompletedTask Result@. The former is more powerful because
575+-- you can construct @Task@s using dynamic values coming a database
576+-- query.
577+--
578+-- To show what this can look like in SQL, consider:
579+--
580+-- @
581+-- > :{
582+-- showQuery $ values
583+-- [ buildADT @Task @\"Pending\"
584+-- , buildADT @Task @\"Complete\" CompletedTask {date = Rel8.Expr.Time.now}
585+-- ]
586+-- :}
587+-- @
588+--
589+-- This produces the following SQL:
590+--
591+-- @
592+-- SELECT
593+-- CAST(\"values0_1\" AS text) as \"tag\",
594+-- CAST(\"values1_1\" AS timestamptz) as \"Complete/_1/date\"
595+-- FROM (SELECT
596+-- *
597+-- FROM (SELECT \"column1\" as \"values0_1\",
598+-- \"column2\" as \"values1_1\"
599+-- FROM
600+-- (VALUES
601+-- (CAST(E'Pending' AS text),CAST(NULL AS timestamptz)),
602+-- (CAST(E'Complete' AS text),CAST(now() AS timestamptz))) as \"V\") as \"T1\") as \"T1\"
603+-- @
604+--
605+-- This is what you get if you run it in @psql@:
606+--
607+--
608+-- @
609+-- tag | Complete/_1/date
610+-- ----------+-------------------------------
611+-- Pending |
612+-- Complete | 2022-05-19 21:28:23.969065+00
613+-- (2 rows)
614+-- @
615+--
616+-- "constructADT" is less convenient but more general alternative to
617+-- "buildADT". It requires only one type-level argument for its type
618+-- to make sense:
619+--
620+-- @
621+-- > :t constructADT @Task
622+-- constructADT @Task
623+-- :: (forall r. r -> (CompletedTask Expr -> r) -> r) -> ADT Task Expr
624+-- @
625+--
626+-- This might still seem a bit opaque, but basically it gives you a
627+-- Church-encoded constructor for arbitrary algebraic data types. You
628+-- might use it as follows:
629+--
630+-- @
631+-- let
632+-- pending :: ADT Task Expr
633+-- pending = constructADT @Task $ \pending _complete -> pending
634+--
635+-- complete :: ADT Task Expr
636+-- complete = constructADT @Task $ \_pending complete -> complete CompletedTask {date = Rel8.Expr.Time.now}
637+-- @
638+--
639+-- These values are otherwise identical to the ones we saw above with
640+-- @buildADT@, it's just a different style of constructing them.
641+--
642+
643+-- $misc-notes
644+--
645+-- 1. Note that the order of the arguments for all of these functions
646+-- is determined by the order of the constructors in the data
647+-- definition. If it were @data Task = Complete (CompletedTask f) |
648+-- Pending@ then the order of all the invocations of @constructADT@
649+-- and @deconstructADT@ would need to change.
650+--
651+-- 2. Maybe this is obvious, but just to spell it out: once you're in
652+-- the @Result@ context, you can of course construct @Task@ values
653+-- normally and use standard Haskell pattern-matching. @constructADT@
654+-- and @deconstructADT@ are specifically only needed in the @Expr@
655+-- context, and they allow you to do the equivalent of pattern
656+-- matching in PostgreSQL.
src/Rel8/Aggregate.hs+34−82
@@ -1,131 +1,83 @@
1{-# language DataKinds #-}
1{-# language DataKinds #-}
2{-# language FlexibleContexts #-}
2{-# language FlexibleContexts #-}
3{-# language FlexibleInstances #-}
3{-# language FlexibleInstances #-}
4−{-# language GADTs #-}
5{-# language MultiParamTypeClasses #-}
4{-# language MultiParamTypeClasses #-}
6−{-# language NamedFieldPuns #-}
7−{-# language PolyKinds #-}
8{-# language RankNTypes #-}
5{-# language RankNTypes #-}
9{-# language StandaloneKindSignatures #-}
6{-# language StandaloneKindSignatures #-}
10{-# language TypeFamilies #-}
7{-# language TypeFamilies #-}
11{-# language UndecidableInstances #-}
8{-# language UndecidableInstances #-}
12−{-# language UndecidableSuperClasses #-}
13
9
14module Rel8.Aggregate
10module Rel8.Aggregate
15− ( Aggregate(..), foldInputs, mapInputs
11+ ( Aggregate(..), zipOutputs
16− , Aggregator(..), unsafeMakeAggregate
12+ , unsafeMakeAggregate
17 , Aggregates
13 , Aggregates
18 )
14 )
19where
15where
20
16
21-- base
17-- base
22−import Data.Functor.Const ( Const( Const ), getConst )
18+import Control.Applicative ( liftA2 )
19+import Data.Functor.Identity ( Identity( Identity ) )
23import Data.Kind ( Constraint, Type )
20import Data.Kind ( Constraint, Type )
24import Prelude
21import Prelude
25
22
23+-- profunctors
24+import Data.Profunctor ( dimap )
25+
26-- opaleye
26-- opaleye
27−import qualified Opaleye.Internal.Aggregate as Opaleye
27+import qualified Opaleye.Aggregate as Opaleye
28import qualified Opaleye.Internal.HaskellDB.PrimQuery as Opaleye
28import qualified Opaleye.Internal.HaskellDB.PrimQuery as Opaleye
29−import qualified Opaleye.Internal.PackMap as Opaleye
29+import qualified Opaleye.Internal.Column as Opaleye
30
30
31-- rel8
31-- rel8
32import Rel8.Expr ( Expr )
32import Rel8.Expr ( Expr )
33−import Rel8.Schema.HTable.Identity ( HIdentity(..), HType )
33+import Rel8.Schema.HTable.Identity ( HIdentity(..) )
34−import Rel8.Schema.Name ( Name )
34+import qualified Rel8.Schema.Kind as K
35import Rel8.Schema.Null ( Sql )
35import Rel8.Schema.Null ( Sql )
36−import Rel8.Schema.Result ( Result( R ) )
37−import Rel8.Schema.Spec ( Spec( Spec ) )
38import Rel8.Table
36import Rel8.Table
39 ( Table, Columns, Context, fromColumns, toColumns
37 ( Table, Columns, Context, fromColumns, toColumns
40 , FromExprs, fromResult, toResult
38 , FromExprs, fromResult, toResult
39+ , Transpose
41 )
40 )
42−import Rel8.Table.Recontextualize ( Recontextualize )
41+import Rel8.Table.Transpose ( Transposes )
43import Rel8.Type ( DBType )
42import Rel8.Type ( DBType )
44
43
45
44
46−-- | An @Aggregate a@ describes how to aggregate @Table@s of type @a@. You can
45+-- | 'Aggregate' is a special context used by 'Rel8.aggregate'.
47−-- unpack an @Aggregate@ back to @a@ by running it with 'Rel8.aggregate'. As
48−-- @Aggregate@ is almost an 'Applicative' functor - but there is no 'pure'
49−-- operation. This means 'Aggregate' is an instance of 'Apply', and you can
50−-- combine @Aggregate@s using the @<.>@ combinator.
51−type Aggregate :: k -> Type
46+type Aggregate :: K.Context
52−data Aggregate a where
53− Aggregate :: forall (a :: Type). !(Opaleye.Aggregator () (Expr a)) -> Aggregate a
47+newtype Aggregate a = Aggregate (Opaleye.Aggregator () (Expr a))
54− A :: { unA :: !(Aggregate a) } -> Aggregate ('Spec a)
55
48
56
49
57instance Sql DBType a => Table Aggregate (Aggregate a) where
50instance Sql DBType a => Table Aggregate (Aggregate a) where
58− type Columns (Aggregate a) = HType a
51+ type Columns (Aggregate a) = HIdentity a
59 type Context (Aggregate a) = Aggregate
52 type Context (Aggregate a) = Aggregate
60 type FromExprs (Aggregate a) = a
53 type FromExprs (Aggregate a) = a
54+ type Transpose to (Aggregate a) = to a
61
55
62− toColumns = HIdentity . A
56+ toColumns = HIdentity
63− fromColumns (HIdentity (A a)) = a
57+ fromColumns (HIdentity a) = a
64− toResult = HIdentity . R
58+ toResult = HIdentity . Identity
65− fromResult (HIdentity (R a)) = a
59+ fromResult (HIdentity (Identity a)) = a
66−
67−
68−instance Sql DBType a =>
69− Recontextualize Aggregate Aggregate (Aggregate a) (Aggregate a)
70−
71−
72−instance Sql DBType a =>
73− Recontextualize Aggregate Expr (Aggregate a) (Expr a)
74−
75−
76−instance Sql DBType a =>
77− Recontextualize Aggregate Name (Aggregate a) (Name a)
78−
79
60
80−instance Sql DBType a =>
81− Recontextualize Expr Aggregate (Expr a) (Aggregate a)
82
61
83−
84−instance Sql DBType a =>
85− Recontextualize Name Aggregate (Name a) (Aggregate a)
86−
87−
88−-- | @Aggregates a b@ means that the columns in @a@ are all 'Aggregate' 'Expr's
62+-- | @Aggregates a b@ means that the columns in @a@ are all 'Aggregate's
89−-- for the columns in @b@.
63+-- for the 'Expr' columns in @b@.
90type Aggregates :: Type -> Type -> Constraint
64type Aggregates :: Type -> Type -> Constraint
91−class Recontextualize Aggregate Expr aggregates exprs => Aggregates aggregates exprs
65+class Transposes Aggregate Expr aggregates exprs => Aggregates aggregates exprs
92−instance Recontextualize Aggregate Expr aggregates exprs => Aggregates aggregates exprs
66+instance Transposes Aggregate Expr aggregates exprs => Aggregates aggregates exprs
93−
94−
95−foldInputs :: forall (a :: Type) (b :: Type). Monoid b
96− => (Maybe Aggregator -> Opaleye.PrimExpr -> b) -> Aggregate a -> b
97−foldInputs f (Aggregate (Opaleye.Aggregator (Opaleye.PackMap agg))) =
98− getConst $ flip agg () $ \(aggregator, a) ->
99− Const $ f (detuplize <$> aggregator) a
100− where
101− detuplize (operation, ordering, distinction) =
102− Aggregator {operation, ordering, distinction}
103−
104−
105−mapInputs :: forall (a :: Type). ()
106− => (Opaleye.PrimExpr -> Opaleye.PrimExpr) -> Aggregate a -> Aggregate a
107−mapInputs transform (Aggregate (Opaleye.Aggregator (Opaleye.PackMap agg))) =
108− Aggregate $ Opaleye.Aggregator $ Opaleye.PackMap $ agg . \f input ->
109− f (fmap transform input)
110
67
111
68
112−type Aggregator :: Type
69+zipOutputs :: ()
113−data Aggregator = Aggregator
70+ => (Expr a -> Expr b -> Expr c) -> Aggregate a -> Aggregate b -> Aggregate c
114− { operation :: Opaleye.AggrOp
71+zipOutputs f (Aggregate a) (Aggregate b) = Aggregate (liftA2 f a b)
115− , ordering :: [Opaleye.OrderExpr]
116− , distinction :: Opaleye.AggrDistinct
117− }
118
72
119
73
120−unsafeMakeAggregate :: forall (input :: Type) (output :: Type). ()
74+unsafeMakeAggregate :: forall (input :: Type) (output :: Type) n n' a a'. ()
121 => (Expr input -> Opaleye.PrimExpr)
75 => (Expr input -> Opaleye.PrimExpr)
122 -> (Opaleye.PrimExpr -> Expr output)
76 -> (Opaleye.PrimExpr -> Expr output)
123− -> Maybe Aggregator
77+ -> Opaleye.Aggregator (Opaleye.Field_ n a) (Opaleye.Field_ n' a')
124 -> Expr input
78 -> Expr input
125 -> Aggregate output
79 -> Aggregate output
126unsafeMakeAggregate input output aggregator expr =
80unsafeMakeAggregate input output aggregator expr =
127− Aggregate $ Opaleye.Aggregator $ Opaleye.PackMap $ \f _ ->
81+ Aggregate $ dimap in_ out aggregator
128− output <$> f (tuplize <$> aggregator, input expr)
82+ where out = output . Opaleye.unColumn
129− where
83+ in_ = Opaleye.Column . input . const expr
130− tuplize Aggregator {operation, ordering, distinction} =
131− (operation, ordering, distinction)
src/Rel8/Column.hs+2−7
@@ -13,11 +13,8 @@ import Data.Kind ( Type )
13import Prelude ()
13import Prelude ()
14
14
15-- rel8
15-- rel8
16−import Rel8.Aggregate ( Aggregate )
17−import Rel8.Expr ( Expr )
18import Rel8.FCF ( Eval, Exp )
16import Rel8.FCF ( Eval, Exp )
19import qualified Rel8.Schema.Kind as K
17import qualified Rel8.Schema.Kind as K
20−import Rel8.Schema.Name ( Name(..) )
21import Rel8.Schema.Result ( Result )
18import Rel8.Schema.Result ( Result )
22
19
23
20
@@ -26,10 +23,8 @@ import Rel8.Schema.Result ( Result )
26-- 'Rel8able' definitions), and @a@ is the type of the column.
23-- 'Rel8able' definitions), and @a@ is the type of the column.
27type Column :: K.Context -> Type -> Type
24type Column :: K.Context -> Type -> Type
28type family Column context a where
25type family Column context a where
29− Column Aggregate a = Aggregate a
30− Column Expr a = Expr a
31− Column Name a = Name a
32− Column Result a = a
26+ Column Result a = a
27+ Column context a = context a
33
28
34
29
35data TColumn :: K.Context -> Type -> Exp Type
30data TColumn :: K.Context -> Type -> Exp Type
src/Rel8/Column/Either.hs+1−6
@@ -12,10 +12,7 @@ import Data.Kind ( Type )
12import Prelude
12import Prelude
13
13
14-- rel8
14-- rel8
15−import Rel8.Aggregate ( Aggregate )
16−import Rel8.Expr ( Expr )
17import qualified Rel8.Schema.Kind as K
15import qualified Rel8.Schema.Kind as K
18−import Rel8.Schema.Name ( Name )
19import Rel8.Schema.Result ( Result )
16import Rel8.Schema.Result ( Result )
20import Rel8.Table.Either ( EitherTable )
17import Rel8.Table.Either ( EitherTable )
21
18
@@ -25,7 +22,5 @@ import Rel8.Table.Either ( EitherTable )
25-- 'Result' context.
22-- 'Result' context.
26type HEither :: K.Context -> Type -> Type -> Type
23type HEither :: K.Context -> Type -> Type -> Type
27type family HEither context = either | either -> context where
24type family HEither context = either | either -> context where
28− HEither Aggregate = EitherTable Aggregate
29− HEither Expr = EitherTable Expr
30− HEither Name = EitherTable Name
31 HEither Result = Either
25 HEither Result = Either
26+ HEither context = EitherTable context
src/Rel8/Column/List.hs+1−6
@@ -12,10 +12,7 @@ import Data.Kind ( Type )
12import Prelude ()
12import Prelude ()
13
13
14-- rel8
14-- rel8
15−import Rel8.Aggregate ( Aggregate )
16−import Rel8.Expr ( Expr )
17import qualified Rel8.Schema.Kind as K
15import qualified Rel8.Schema.Kind as K
18−import Rel8.Schema.Name ( Name )
19import Rel8.Schema.Result ( Result )
16import Rel8.Schema.Result ( Result )
20import Rel8.Table.List ( ListTable )
17import Rel8.Table.List ( ListTable )
21
18
@@ -24,7 +21,5 @@ import Rel8.Table.List ( ListTable )
24-- @a@ in the 'Expr' context, and a @[a]@ in the 'Result' context.
21-- @a@ in the 'Expr' context, and a @[a]@ in the 'Result' context.
25type HList :: K.Context -> Type -> Type
22type HList :: K.Context -> Type -> Type
26type family HList context = list | list -> context where
23type family HList context = list | list -> context where
27− HList Aggregate = ListTable Aggregate
28− HList Expr = ListTable Expr
29− HList Name = ListTable Name
30 HList Result = []
24 HList Result = []
25+ HList context = ListTable context
src/Rel8/Column/Maybe.hs+1−6
@@ -12,10 +12,7 @@ import Data.Kind ( Type )
12import Prelude
12import Prelude
13
13
14-- rel8
14-- rel8
15−import Rel8.Aggregate ( Aggregate )
16−import Rel8.Expr ( Expr )
17import qualified Rel8.Schema.Kind as K
15import qualified Rel8.Schema.Kind as K
18−import Rel8.Schema.Name ( Name )
19import Rel8.Schema.Result ( Result )
16import Rel8.Schema.Result ( Result )
20import Rel8.Table.Maybe ( MaybeTable )
17import Rel8.Table.Maybe ( MaybeTable )
21
18
@@ -25,7 +22,5 @@ import Rel8.Table.Maybe ( MaybeTable )
25-- context.
22-- context.
26type HMaybe :: K.Context -> Type -> Type
23type HMaybe :: K.Context -> Type -> Type
27type family HMaybe context = maybe | maybe -> context where
24type family HMaybe context = maybe | maybe -> context where
28− HMaybe Aggregate = MaybeTable Aggregate
29− HMaybe Expr = MaybeTable Expr
30− HMaybe Name = MaybeTable Name
31 HMaybe Result = Maybe
25 HMaybe Result = Maybe
26+ HMaybe context = MaybeTable context
src/Rel8/Column/NonEmpty.hs+1−6
@@ -13,10 +13,7 @@ import Data.List.NonEmpty ( NonEmpty )
13import Prelude ()
13import Prelude ()
14
14
15-- rel8
15-- rel8
16−import Rel8.Aggregate ( Aggregate )
17−import Rel8.Expr ( Expr )
18import qualified Rel8.Schema.Kind as K
16import qualified Rel8.Schema.Kind as K
19−import Rel8.Schema.Name ( Name )
20import Rel8.Schema.Result ( Result )
17import Rel8.Schema.Result ( Result )
21import Rel8.Table.NonEmpty ( NonEmptyTable )
18import Rel8.Table.NonEmpty ( NonEmptyTable )
22
19
@@ -26,7 +23,5 @@ import Rel8.Table.NonEmpty ( NonEmptyTable )
26-- 'Result' context.
23-- 'Result' context.
27type HNonEmpty :: K.Context -> Type -> Type
24type HNonEmpty :: K.Context -> Type -> Type
28type family HNonEmpty context = nonEmpty | nonEmpty -> context where
25type family HNonEmpty context = nonEmpty | nonEmpty -> context where
29− HNonEmpty Aggregate = NonEmptyTable Aggregate
30− HNonEmpty Expr = NonEmptyTable Expr
31− HNonEmpty Name = NonEmptyTable Name
32 HNonEmpty Result = NonEmpty
26 HNonEmpty Result = NonEmpty
27+ HNonEmpty context = NonEmptyTable context
src/Rel8/Column/Null.hsnew file+26
@@ -0,0 +1,26 @@
1+{-# language DataKinds #-}
2+{-# language StandaloneKindSignatures #-}
3+{-# language TypeFamilyDependencies #-}
4+
5+module Rel8.Column.Null
6+ ( HNull
7+ )
8+where
9+
10+-- base
11+import Data.Kind ( Type )
12+import Prelude
13+
14+-- rel8
15+import qualified Rel8.Schema.Kind as K
16+import Rel8.Schema.Result ( Result )
17+import Rel8.Table.Null ( NullTable )
18+
19+
20+-- | Nest a 'Null' value within a 'Rel8able'. @HNull f a@ will produce a
21+-- 'NullTable' @a@ in the 'Expr' context, and a @'Maybe' a@ in the 'Result'
22+-- context.
23+type HNull :: K.Context -> Type -> Type
24+type family HNull context = maybe | maybe -> context where
25+ HNull Result = Maybe
26+ HNull context = NullTable context
src/Rel8/Column/These.hs+1−6
@@ -12,10 +12,7 @@ import Data.Kind ( Type )
12import Prelude ()
12import Prelude ()
13
13
14-- rel8
14-- rel8
15−import Rel8.Aggregate ( Aggregate )
16−import Rel8.Expr ( Expr )
17import qualified Rel8.Schema.Kind as K
15import qualified Rel8.Schema.Kind as K
18−import Rel8.Schema.Name ( Name )
19import Rel8.Schema.Result ( Result )
16import Rel8.Schema.Result ( Result )
20import Rel8.Table.These ( TheseTable )
17import Rel8.Table.These ( TheseTable )
21
18
@@ -28,7 +25,5 @@ import Data.These ( These )
28-- 'Result' context.
25-- 'Result' context.
29type HThese :: K.Context -> Type -> Type -> Type
26type HThese :: K.Context -> Type -> Type -> Type
30type family HThese context = these | these -> context where
27type family HThese context = these | these -> context where
31− HThese Aggregate = TheseTable Aggregate
32− HThese Expr = TheseTable Expr
33− HThese Name = TheseTable Name
34 HThese Result = These
28 HThese Result = These
29+ HThese context = TheseTable context
src/Rel8/Expr.hs+18−26
@@ -1,22 +1,21 @@
1{-# language DataKinds #-}
1{-# language DataKinds #-}
2{-# language DerivingStrategies #-}
2{-# language DerivingStrategies #-}
3+{-# language FlexibleContexts #-}
3{-# language FlexibleInstances #-}
4{-# language FlexibleInstances #-}
4−{-# language GADTs #-}
5{-# language MultiParamTypeClasses #-}
5{-# language MultiParamTypeClasses #-}
6−{-# language PolyKinds #-}
7−{-# language RoleAnnotations #-}
8{-# language ScopedTypeVariables #-}
6{-# language ScopedTypeVariables #-}
9−{-# language StandaloneDeriving #-}
10{-# language StandaloneKindSignatures #-}
7{-# language StandaloneKindSignatures #-}
11{-# language TypeApplications #-}
8{-# language TypeApplications #-}
12{-# language TypeFamilies #-}
9{-# language TypeFamilies #-}
13{-# language UndecidableInstances #-}
10{-# language UndecidableInstances #-}
14−{-# language UndecidableSuperClasses #-}
15
11
16−module Rel8.Expr ( Expr(..) ) where
12+module Rel8.Expr
13+ ( Expr(..)
14+ )
15+where
17
16
18-- base
17-- base
19−import Data.Kind ( Type )
18+import Data.Functor.Identity ( Identity( Identity ) )
20import Data.String ( IsString, fromString )
19import Data.String ( IsString, fromString )
21import Prelude hiding ( null )
20import Prelude hiding ( null )
22
21
@@ -33,15 +32,14 @@ import Rel8.Expr.Opaleye
33 , zipPrimExprsWith
32 , zipPrimExprsWith
34 )
33 )
35import Rel8.Expr.Serialize ( litExpr )
34import Rel8.Expr.Serialize ( litExpr )
36−import Rel8.Schema.HTable.Identity ( HIdentity( HType ), HType )
35+import Rel8.Schema.HTable.Identity ( HIdentity( HIdentity ) )
36+import qualified Rel8.Schema.Kind as K
37import Rel8.Schema.Null ( Nullity( Null, NotNull ), Sql, nullable )
37import Rel8.Schema.Null ( Nullity( Null, NotNull ), Sql, nullable )
38−import Rel8.Schema.Result ( Result( R ) )
39−import Rel8.Schema.Spec ( Spec( Spec ) )
40import Rel8.Table
38import Rel8.Table
41 ( Table, Columns, Context, fromColumns, toColumns
39 ( Table, Columns, Context, fromColumns, toColumns
42 , FromExprs, fromResult, toResult
40 , FromExprs, fromResult, toResult
41+ , Transpose
43 )
42 )
44−import Rel8.Table.Recontextualize ( Recontextualize )
45import Rel8.Type ( DBType )
43import Rel8.Type ( DBType )
46import Rel8.Type.Monoid ( DBMonoid, memptyExpr )
44import Rel8.Type.Monoid ( DBMonoid, memptyExpr )
47import Rel8.Type.Num ( DBFloating, DBFractional, DBNum )
45import Rel8.Type.Num ( DBFloating, DBFractional, DBNum )
@@ -49,13 +47,9 @@ import Rel8.Type.Semigroup ( DBSemigroup, (<>.) )
49
47
50
48
51-- | Typed SQL expressions.
49-- | Typed SQL expressions.
52−type Expr :: k -> Type
50+type Expr :: K.Context
53−data Expr a where
54− Expr :: forall (a :: Type). !Opaleye.PrimExpr -> Expr a
51+newtype Expr a = Expr Opaleye.PrimExpr
55− E :: { unE :: !(Expr a) } -> Expr ('Spec a)
56−
57−
58−deriving stock instance Show (Expr a)
52+ deriving stock Show
59
53
60
54
61instance Sql DBSemigroup a => Semigroup (Expr a) where
55instance Sql DBSemigroup a => Semigroup (Expr a) where
@@ -120,14 +114,12 @@ instance Sql DBFloating a => Floating (Expr a) where
120
114
121
115
122instance Sql DBType a => Table Expr (Expr a) where
116instance Sql DBType a => Table Expr (Expr a) where
123− type Columns (Expr a) = HType a
117+ type Columns (Expr a) = HIdentity a
124 type Context (Expr a) = Expr
118 type Context (Expr a) = Expr
125 type FromExprs (Expr a) = a
119 type FromExprs (Expr a) = a
120+ type Transpose to (Expr a) = to a
126
121
127− toColumns a = HType (E a)
122+ toColumns a = HIdentity a
128− fromColumns (HType (E a)) = a
123+ fromColumns (HIdentity a) = a
129− toResult a = HType (R a)
124+ toResult a = HIdentity (Identity a)
130− fromResult (HType (R a)) = a
125+ fromResult (HIdentity (Identity a)) = a
131−
132−
133−instance Sql DBType a => Recontextualize Expr Expr (Expr a) (Expr a)
src/Rel8/Expr.hs-boot+4−10
@@ -1,8 +1,4 @@
1{-# language DataKinds #-}
1{-# language DataKinds #-}
2−{-# language GADTs #-}
3−{-# language PolyKinds #-}
4−{-# language RankNTypes #-}
5−{-# language RoleAnnotations #-}
6{-# language StandaloneKindSignatures #-}
2{-# language StandaloneKindSignatures #-}
7
3
8module Rel8.Expr
4module Rel8.Expr
@@ -11,16 +7,14 @@ module Rel8.Expr
11where
7where
12
8
13-- base
9-- base
14−import Data.Kind ( Type )
15import Prelude ()
10import Prelude ()
16
11
17-- opaleye
12-- opaleye
18import qualified Opaleye.Internal.HaskellDB.PrimQuery as Opaleye
13import qualified Opaleye.Internal.HaskellDB.PrimQuery as Opaleye
19
14
15+-- rel8
20−import Rel8.Schema.Spec ( Spec(..) )
16+import Rel8.Schema.Kind ( Context )
21
17
22
18
23−type Expr :: k -> Type
19+type Expr :: Context
24−data Expr a where
25− Expr :: forall (a :: Type). !Opaleye.PrimExpr -> Expr a
20+newtype Expr a = Expr Opaleye.PrimExpr
26− E :: { unE :: !(Expr a) } -> Expr ('Spec a)
src/Rel8/Expr/Aggregate.hs+25−64
@@ -10,6 +10,7 @@ module Rel8.Expr.Aggregate
10 , and, or
10 , and, or
11 , min, max
11 , min, max
12 , sum, sumWhere
12 , sum, sumWhere
13+ , avg
13 , stringAgg
14 , stringAgg
14 , groupByExpr
15 , groupByExpr
15 , listAggExpr, nonEmptyAggExpr
16 , listAggExpr, nonEmptyAggExpr
@@ -23,10 +24,12 @@ import Data.List.NonEmpty ( NonEmpty )
23import Prelude hiding ( and, max, min, null, or, sum )
24import Prelude hiding ( and, max, min, null, or, sum )
24
25
25-- opaleye
26-- opaleye
26−import qualified Opaleye.Internal.HaskellDB.PrimQuery as Opaleye
27+import qualified Opaleye.Internal.Aggregate as Opaleye
28+import Opaleye.Internal.Column ( Field_( Column ) )
29+import qualified Opaleye.Aggregate as Opaleye
27
30
28-- rel8
31-- rel8
29−import Rel8.Aggregate ( Aggregate, Aggregator(..), unsafeMakeAggregate )
32+import Rel8.Aggregate ( Aggregate, unsafeMakeAggregate )
30import Rel8.Expr ( Expr )
33import Rel8.Expr ( Expr )
31import Rel8.Expr.Bool ( caseExpr )
34import Rel8.Expr.Bool ( caseExpr )
32import Rel8.Expr.Opaleye
35import Rel8.Expr.Opaleye
@@ -50,23 +53,13 @@ import Rel8.Type.Sum ( DBSum )
50
53
51-- | Count the occurances of a single column. Corresponds to @COUNT(a)@
54-- | Count the occurances of a single column. Corresponds to @COUNT(a)@
52count :: Expr a -> Aggregate Int64
55count :: Expr a -> Aggregate Int64
53−count = unsafeMakeAggregate toPrimExpr fromPrimExpr $
56+count = unsafeMakeAggregate toPrimExpr fromPrimExpr Opaleye.count
54− Just Aggregator
55− { operation = Opaleye.AggrCount
56− , ordering = []
57− , distinction = Opaleye.AggrAll
58− }
59−
60
57
61-- | Count the number of distinct occurances of a single column. Corresponds to
58-- | Count the number of distinct occurances of a single column. Corresponds to
62-- @COUNT(DISTINCT a)@
59-- @COUNT(DISTINCT a)@
63countDistinct :: Sql DBEq a => Expr a -> Aggregate Int64
60countDistinct :: Sql DBEq a => Expr a -> Aggregate Int64
64countDistinct = unsafeMakeAggregate toPrimExpr fromPrimExpr $
61countDistinct = unsafeMakeAggregate toPrimExpr fromPrimExpr $
65− Just Aggregator
62+ Opaleye.distinctAggregator Opaleye.count
66− { operation = Opaleye.AggrCount
67− , ordering = []
68− , distinction = Opaleye.AggrDistinct
69− }
70
63
71
64
72-- | Corresponds to @COUNT(*)@.
65-- | Corresponds to @COUNT(*)@.
@@ -81,56 +74,39 @@ countWhere condition = count (caseExpr [(condition, litExpr (Just True))] null)
81
74
82-- | Corresponds to @bool_and@.
75-- | Corresponds to @bool_and@.
83and :: Expr Bool -> Aggregate Bool
76and :: Expr Bool -> Aggregate Bool
84−and = unsafeMakeAggregate toPrimExpr fromPrimExpr $
77+and = unsafeMakeAggregate toPrimExpr fromPrimExpr Opaleye.boolAnd
85− Just Aggregator
86− { operation = Opaleye.AggrBoolAnd
87− , ordering = []
88− , distinction = Opaleye.AggrAll
89− }
90
78
91
79
92-- | Corresponds to @bool_or@.
80-- | Corresponds to @bool_or@.
93or :: Expr Bool -> Aggregate Bool
81or :: Expr Bool -> Aggregate Bool
94−or = unsafeMakeAggregate toPrimExpr fromPrimExpr $
82+or = unsafeMakeAggregate toPrimExpr fromPrimExpr Opaleye.boolOr
95− Just Aggregator
96− { operation = Opaleye.AggrBoolOr
97− , ordering = []
98− , distinction = Opaleye.AggrAll
99− }
100
83
101
84
102-- | Produce an aggregation for @Expr a@ using the @max@ function.
85-- | Produce an aggregation for @Expr a@ using the @max@ function.
103max :: Sql DBMax a => Expr a -> Aggregate a
86max :: Sql DBMax a => Expr a -> Aggregate a
104−max = unsafeMakeAggregate toPrimExpr fromPrimExpr $
87+max = unsafeMakeAggregate toPrimExpr fromPrimExpr Opaleye.unsafeMax
105− Just Aggregator
106− { operation = Opaleye.AggrMax
107− , ordering = []
108− , distinction = Opaleye.AggrAll
109− }
110
88
111
89
112-- | Produce an aggregation for @Expr a@ using the @max@ function.
90-- | Produce an aggregation for @Expr a@ using the @max@ function.
113min :: Sql DBMin a => Expr a -> Aggregate a
91min :: Sql DBMin a => Expr a -> Aggregate a
114−min = unsafeMakeAggregate toPrimExpr fromPrimExpr $
92+min = unsafeMakeAggregate toPrimExpr fromPrimExpr Opaleye.unsafeMin
115− Just Aggregator
116− { operation = Opaleye.AggrMin
117− , ordering = []
118− , distinction = Opaleye.AggrAll
119− }
120
93
121-- | Corresponds to @sum@. Note that in SQL, @sum@ is type changing - for
94-- | Corresponds to @sum@. Note that in SQL, @sum@ is type changing - for
122-- example the @sum@ of @integer@ returns a @bigint@. Rel8 doesn't support
95-- example the @sum@ of @integer@ returns a @bigint@. Rel8 doesn't support
123−-- this, and will add explicit cast back to the original input type. This can
96+-- this, and will add explicit casts back to the original input type. This can
124-- lead to overflows, and if you anticipate very large sums, you should upcast
97-- lead to overflows, and if you anticipate very large sums, you should upcast
125-- your input.
98-- your input.
126sum :: Sql DBSum a => Expr a -> Aggregate a
99sum :: Sql DBSum a => Expr a -> Aggregate a
127−sum = unsafeMakeAggregate toPrimExpr (castExpr . fromPrimExpr) $
100+sum = unsafeMakeAggregate toPrimExpr (castExpr . fromPrimExpr) Opaleye.unsafeSum
128− Just Aggregator
101+
129− { operation = Opaleye.AggrSum
130− , ordering = []
131− , distinction = Opaleye.AggrAll
132− }
133
102
103+-- | Corresponds to @avg@. Note that in SQL, @avg@ is type changing - for
104+-- example, the @avg@ of @integer@ returns a @numeric@. Rel8 doesn't support
105+-- this, and will add explicit casts back to the original input type. If you
106+-- need a fractional result on an integral column, you should cast your input
107+-- to 'Double' or 'Data.Scientific.Scientific' before calling 'avg'.
108+avg :: Sql DBSum a => Expr a -> Aggregate a
109+avg = unsafeMakeAggregate toPrimExpr (castExpr . fromPrimExpr) Opaleye.unsafeAvg
134
110
135-- | Take the sum of all expressions that satisfy a predicate.
111-- | Take the sum of all expressions that satisfy a predicate.
136sumWhere :: (Sql DBNum a, Sql DBSum a)
112sumWhere :: (Sql DBNum a, Sql DBSum a)
@@ -142,17 +118,12 @@ sumWhere condition a = sum (caseExpr [(condition, a)] 0)
142stringAgg :: Sql DBString a
118stringAgg :: Sql DBString a
143 => Expr db -> Expr a -> Aggregate a
119 => Expr db -> Expr a -> Aggregate a
144stringAgg delimiter =
120stringAgg delimiter =
145− unsafeMakeAggregate toPrimExpr (castExpr . fromPrimExpr) $
121+ unsafeMakeAggregate toPrimExpr (castExpr . fromPrimExpr) (Opaleye.stringAgg (Column (toPrimExpr delimiter)))
146− Just Aggregator
147− { operation = Opaleye.AggrStringAggr (toPrimExpr delimiter)
148− , ordering = []
149− , distinction = Opaleye.AggrAll
150− }
151
122
152
123
153-- | Aggregate a value by grouping by it.
124-- | Aggregate a value by grouping by it.
154groupByExpr :: Sql DBEq a => Expr a -> Aggregate a
125groupByExpr :: Sql DBEq a => Expr a -> Aggregate a
155−groupByExpr = unsafeMakeAggregate toPrimExpr fromPrimExpr Nothing
126+groupByExpr = unsafeMakeAggregate toPrimExpr fromPrimExpr Opaleye.groupBy
156
127
157
128
158-- | Collect expressions values as a list.
129-- | Collect expressions values as a list.
@@ -167,23 +138,13 @@ nonEmptyAggExpr = snonEmptyAggExpr typeInformation
167
138
168slistAggExpr :: ()
139slistAggExpr :: ()
169 => TypeInformation (Unnullify a) -> Expr a -> Aggregate [a]
140 => TypeInformation (Unnullify a) -> Expr a -> Aggregate [a]
170−slistAggExpr info = unsafeMakeAggregate to fromPrimExpr $ Just
141+slistAggExpr info = unsafeMakeAggregate to fromPrimExpr Opaleye.arrayAgg
171− Aggregator
172− { operation = Opaleye.AggrArr
173− , ordering = []
174− , distinction = Opaleye.AggrAll
175− }
176 where
142 where
177 to = encodeArrayElement info . toPrimExpr
143 to = encodeArrayElement info . toPrimExpr
178
144
179
145
180snonEmptyAggExpr :: ()
146snonEmptyAggExpr :: ()
181 => TypeInformation (Unnullify a) -> Expr a -> Aggregate (NonEmpty a)
147 => TypeInformation (Unnullify a) -> Expr a -> Aggregate (NonEmpty a)
182−snonEmptyAggExpr info = unsafeMakeAggregate to fromPrimExpr $ Just
148+snonEmptyAggExpr info = unsafeMakeAggregate to fromPrimExpr Opaleye.arrayAgg
183− Aggregator
184− { operation = Opaleye.AggrArr
185− , ordering = []
186− , distinction = Opaleye.AggrAll
187− }
188 where
149 where
189 to = encodeArrayElement info . toPrimExpr
150 to = encodeArrayElement info . toPrimExpr
src/Rel8/Expr/Num.hs+39−6
@@ -4,18 +4,24 @@
4{-# options_ghc -fno-warn-redundant-constraints #-}
4{-# options_ghc -fno-warn-redundant-constraints #-}
5
5
6module Rel8.Expr.Num
6module Rel8.Expr.Num
7+ ( fromIntegral
8+ , realToFrac
9+ , div, mod, divMod
10+ , quot, rem, quotRem
7− ( fromIntegral, realToFrac, div, mod, ceiling, floor, round, truncate
11+ , ceiling, floor, round, truncate
8 )
12 )
9where
13where
10
14
11-- base
15-- base
12−import Prelude ()
16+import Prelude ( (+), (-), fst, negate, signum, snd )
13
17
14-- rel
18-- rel
15import Rel8.Expr ( Expr( Expr ) )
19import Rel8.Expr ( Expr( Expr ) )
20+import Rel8.Expr.Eq ( (==.) )
16import Rel8.Expr.Function ( function )
21import Rel8.Expr.Function ( function )
17import Rel8.Expr.Opaleye ( castExpr )
22import Rel8.Expr.Opaleye ( castExpr )
18import Rel8.Schema.Null ( Homonullable, Sql )
23import Rel8.Schema.Null ( Homonullable, Sql )
24+import Rel8.Table.Bool ( bool )
19import Rel8.Type.Num ( DBFractional, DBIntegral, DBNum )
25import Rel8.Type.Num ( DBFractional, DBIntegral, DBNum )
20
26
21
27
@@ -42,14 +48,41 @@ ceiling :: (Sql DBFractional a, Sql DBIntegral b, Homonullable a b)
42ceiling = function "ceiling"
48ceiling = function "ceiling"
43
49
44
50
45−-- | Perform integral division. Corresponds to the @div()@ function.
51+-- | Emulates the behaviour of the Haskell function 'Prelude.div' in
52+-- PostgreSQL.
46div :: Sql DBIntegral a => Expr a -> Expr a -> Expr a
53div :: Sql DBIntegral a => Expr a -> Expr a -> Expr a
47−div = function "div"
54+div n d = fst (divMod n d)
48
55
49
56
50−-- | Corresponds to the @mod()@ function.
57+-- | Emulates the behaviour of the Haskell function 'Prelude.mod' in
58+-- PostgreSQL.
51mod :: Sql DBIntegral a => Expr a -> Expr a -> Expr a
59mod :: Sql DBIntegral a => Expr a -> Expr a -> Expr a
52−mod = function "mod"
60+mod n d = snd (divMod n d)
61+
62+
63+-- | Simultaneous 'div' and 'mod'.
64+divMod :: Sql DBIntegral a => Expr a -> Expr a -> (Expr a, Expr a)
65+divMod n d = bool qr (q - 1, r + d) (signum r ==. negate (signum d))
66+ where
67+ qr@(q, r) = quotRem n d
68+
69+
70+-- | Perform integral division. Corresponds to the @div()@ function in
71+-- PostgreSQL, which behaves like Haskell's 'Prelude.quot' rather than
72+-- 'Prelude.div'.
73+quot :: Sql DBIntegral a => Expr a -> Expr a -> Expr a
74+quot = function "div"
75+
76+
77+-- | Corresponds to the @mod()@ function in PostgreSQL, which behaves like
78+-- Haskell's 'Prelude.rem' rather than 'Prelude.mod'.
79+rem :: Sql DBIntegral a => Expr a -> Expr a -> Expr a
80+rem = function "mod"
81+
82+
83+-- | Simultaneous 'quot' and 'rem'.
84+quotRem :: Sql DBIntegral a => Expr a -> Expr a -> (Expr a, Expr a)
85+quotRem n d = (quot n d, rem n d)
53
86
54
87
55-- | Round a 'DFractional' to a 'DBIntegral' by rounding to the nearest smaller
88-- | Round a 'DFractional' to a 'DBIntegral' by rounding to the nearest smaller
src/Rel8/Expr/Opaleye.hs+12−3
@@ -10,7 +10,7 @@ module Rel8.Expr.Opaleye
10 , scastExpr, sunsafeCastExpr
10 , scastExpr, sunsafeCastExpr
11 , unsafeLiteral
11 , unsafeLiteral
12 , fromPrimExpr, toPrimExpr, mapPrimExpr, zipPrimExprsWith, traversePrimExpr
12 , fromPrimExpr, toPrimExpr, mapPrimExpr, zipPrimExprsWith, traversePrimExpr
13− , toColumn, fromColumn
13+ , toColumn, fromColumn, traverseFieldP
14 )
14 )
15where
15where
16
16
@@ -27,6 +27,9 @@ import Rel8.Schema.Null ( Unnullify, Sql )
27import Rel8.Type ( DBType, typeInformation )
27import Rel8.Type ( DBType, typeInformation )
28import Rel8.Type.Information ( TypeInformation(..) )
28import Rel8.Type.Information ( TypeInformation(..) )
29
29
30+-- profunctors
31+import Data.Profunctor ( Profunctor, dimap )
32+
30
33
31castExpr :: Sql DBType a => Expr a -> Expr a
34castExpr :: Sql DBType a => Expr a -> Expr a
32castExpr = scastExpr typeInformation
35castExpr = scastExpr typeInformation
@@ -80,9 +83,15 @@ traversePrimExpr :: Functor f
80traversePrimExpr f = fmap fromPrimExpr . f . toPrimExpr
83traversePrimExpr f = fmap fromPrimExpr . f . toPrimExpr
81
84
82
85
86+traverseFieldP :: Profunctor p
87+ => p (Opaleye.Field_ n x) (Opaleye.Field_ m y)
88+ -> p (Expr a) (Expr b)
89+traverseFieldP = dimap (toColumn . toPrimExpr) (fromPrimExpr . fromColumn)
90+
91+
83−toColumn :: Opaleye.PrimExpr -> Opaleye.Column b
92+toColumn :: Opaleye.PrimExpr -> Opaleye.Field_ n b
84toColumn = Opaleye.Column
93toColumn = Opaleye.Column
85
94
86
95
87−fromColumn :: Opaleye.Column b -> Opaleye.PrimExpr
96+fromColumn :: Opaleye.Field_ n b -> Opaleye.PrimExpr
88fromColumn (Opaleye.Column a) = a
97fromColumn (Opaleye.Column a) = a
src/Rel8/Expr/Sequence.hs+2−1
@@ -11,6 +11,7 @@ import Prelude
11import Rel8.Expr ( Expr )
11import Rel8.Expr ( Expr )
12import Rel8.Expr.Function ( function )
12import Rel8.Expr.Function ( function )
13import Rel8.Expr.Serialize ( litExpr )
13import Rel8.Expr.Serialize ( litExpr )
14+import Rel8.Expr.Text ( quoteIdent )
14
15
15-- text
16-- text
16import Data.Text ( pack )
17import Data.Text ( pack )
@@ -18,4 +19,4 @@ import Data.Text ( pack )
18
19
19-- | See https://www.postgresql.org/docs/current/functions-sequence.html
20-- | See https://www.postgresql.org/docs/current/functions-sequence.html
20nextval :: String -> Expr Int64
21nextval :: String -> Expr Int64
21−nextval = function "nextval" . litExpr . pack
22+nextval = function "nextval" . quoteIdent . litExpr . pack
src/Rel8/Expr/Text.hs+23−2
@@ -17,6 +17,9 @@ module Rel8.Expr.Text
17 , pgClientEncoding, quoteIdent, quoteLiteral, quoteNullable, regexpReplace
17 , pgClientEncoding, quoteIdent, quoteLiteral, quoteNullable, regexpReplace
18 , regexpSplitToArray, repeat, replace, reverse, right, rpad, rtrim
18 , regexpSplitToArray, repeat, replace, reverse, right, rpad, rtrim
19 , splitPart, strpos, substr, translate
19 , splitPart, strpos, substr, translate
20+
21+ -- * @LIKE@ and @ILIKE@
22+ , like, ilike
20 )
23 )
21where
24where
22
25
@@ -24,7 +27,7 @@ where
24import Data.Bool ( Bool )
27import Data.Bool ( Bool )
25import Data.Int ( Int32 )
28import Data.Int ( Int32 )
26import Data.Maybe ( Maybe( Nothing, Just ) )
29import Data.Maybe ( Maybe( Nothing, Just ) )
27−import Prelude ()
30+import Prelude ( flip )
28
31
29-- bytestring
32-- bytestring
30import Data.ByteString ( ByteString )
33import Data.ByteString ( ByteString )
@@ -49,7 +52,7 @@ infixr 6 ++.
49
52
50
53
51-- | Matches regular expression, case sensitive
54-- | Matches regular expression, case sensitive
52−--
55+--
53-- Corresponds to the @~.@ operator.
56-- Corresponds to the @~.@ operator.
54(~.) :: Expr Text -> Expr Text -> Expr Bool
57(~.) :: Expr Text -> Expr Text -> Expr Bool
55(~.) = binaryOperator "~."
58(~.) = binaryOperator "~."
@@ -273,3 +276,21 @@ substr a b Nothing = function "substr" a b
273-- | Corresponds to the @translate@ function.
276-- | Corresponds to the @translate@ function.
274translate :: Expr Text -> Expr Text -> Expr Text -> Expr Text
277translate :: Expr Text -> Expr Text -> Expr Text -> Expr Text
275translate = function "translate"
278translate = function "translate"
279+
280+
281+-- | @like x y@ corresponds to the expression @y LIKE x@.
282+--
283+-- Note that the arguments to @like@ are swapped. This is to aid currying, so
284+-- you can write expressions like
285+-- @filter (like "Rel%" . packageName) =<< each haskellPackages@
286+like :: Expr Text -> Expr Text -> Expr Bool
287+like = flip (binaryOperator "LIKE")
288+
289+
290+-- | @ilike x y@ corresponds to the expression @y ILIKE x@.
291+--
292+-- Note that the arguments to @ilike@ are swapped. This is to aid currying, so
293+-- you can write expressions like
294+-- @filter (ilike "Rel%" . packageName) =<< each haskellPackages@
295+ilike :: Expr Text -> Expr Text -> Expr Bool
296+ilike = flip (binaryOperator "ILIKE")
src/Rel8/Expr/Window.hsnew file+121
@@ -0,0 +1,121 @@
1+module Rel8.Expr.Window
2+ ( cumulative
3+ , rowNumber
4+ , rank
5+ , denseRank
6+ , percentRank
7+ , cumeDist
8+ , ntile
9+ , lag
10+ , lead
11+ , firstValue
12+ , lastValue
13+ , nthValue
14+ )
15+where
16+
17+-- base
18+import Data.Int ( Int32, Int64 )
19+import Prelude
20+
21+-- opaleye
22+import qualified Opaleye.Internal.Aggregate as Opaleye
23+import qualified Opaleye.Internal.PackMap as Opaleye
24+import qualified Opaleye.Internal.Window as Opaleye
25+import qualified Opaleye.Window as Opaleye
26+
27+-- profunctors
28+import Data.Profunctor (dimap)
29+
30+-- rel8
31+import Rel8.Aggregate ( Aggregate( Aggregate ) )
32+import Rel8.Expr ( Expr )
33+import Rel8.Expr.Opaleye ( fromColumn, fromPrimExpr, toColumn, toPrimExpr )
34+import Rel8.Schema.Null ( Nullify )
35+import Rel8.Window ( Window( Window ) )
36+
37+
38+cumulative :: (a -> Aggregate b) -> Window a (Expr b)
39+cumulative f =
40+ fromWindowFunction $ Opaleye.aggregatorWindowFunction (fromAggregate f) id
41+
42+
43+-- | [@row_number()@](https://www.postgresql.org/docs/current/functions-window.html)
44+rowNumber :: Window a (Expr Int64)
45+rowNumber = fromWindowFunction $ fromPrimExpr . fromColumn <$> Opaleye.rowNumber
46+
47+
48+-- | [@rank()@](https://www.postgresql.org/docs/current/functions-window.html)
49+rank :: Window a (Expr Int64)
50+rank = fromWindowFunction $ fromPrimExpr . fromColumn <$> Opaleye.rank
51+
52+
53+-- | [@dense_rank()@](https://www.postgresql.org/docs/current/functions-window.html)
54+denseRank :: Window a (Expr Int64)
55+denseRank = fromWindowFunction $ fromPrimExpr . fromColumn <$> Opaleye.denseRank
56+
57+
58+-- | [@percent_rank()@](https://www.postgresql.org/docs/current/functions-window.html)
59+percentRank :: Window a (Expr Double)
60+percentRank = fromWindowFunction $ fromPrimExpr . fromColumn <$> Opaleye.percentRank
61+
62+
63+-- | [@cume_dist()@](https://www.postgresql.org/docs/current/functions-window.html)
64+cumeDist :: Window a (Expr Double)
65+cumeDist = fromWindowFunction $ fromPrimExpr . fromColumn <$> Opaleye.cumeDist
66+
67+
68+-- | [@ntile(num_buckets)@](https://www.postgresql.org/docs/current/functions-window.html)
69+ntile :: Expr Int32 -> Window a (Expr Int32)
70+ntile buckets = fromWindowFunction $ fromPrimExpr . fromColumn <$>
71+ Opaleye.ntile (toColumn (toPrimExpr buckets))
72+
73+
74+-- | [@lag(value, offset, default)@](https://www.postgresql.org/docs/current/functions-window.html)
75+lag :: Expr Int32 -> Expr a -> Window (Expr a) (Expr a)
76+lag offset def =
77+ fromWindowFunction $
78+ dimap (toColumn . toPrimExpr) (fromPrimExpr . fromColumn) $
79+ Opaleye.lag (toColumn (toPrimExpr offset)) (toColumn (toPrimExpr def))
80+
81+
82+-- | [@lead(value, offset, default)@](https://www.postgresql.org/docs/current/functions-window.html)
83+lead :: Expr Int32 -> Expr a -> Window (Expr a) (Expr a)
84+lead offset def =
85+ fromWindowFunction $
86+ dimap (toColumn . toPrimExpr) (fromPrimExpr . fromColumn) $
87+ Opaleye.lead (toColumn (toPrimExpr offset)) (toColumn (toPrimExpr def))
88+
89+
90+-- | [@first_value(value)@](https://www.postgresql.org/docs/current/functions-window.html)
91+firstValue :: Window (Expr a) (Expr a)
92+firstValue =
93+ fromWindowFunction $
94+ dimap (toColumn . toPrimExpr) (fromPrimExpr . fromColumn)
95+ Opaleye.firstValue
96+
97+
98+-- | [@last_value(value)@](https://www.postgresql.org/docs/current/functions-window.html)
99+lastValue :: Window (Expr a) (Expr a)
100+lastValue =
101+ fromWindowFunction $
102+ dimap (toColumn . toPrimExpr) (fromPrimExpr . fromColumn)
103+ Opaleye.lastValue
104+
105+
106+-- | [@nth_value(value, n)@](https://www.postgresql.org/docs/current/functions-window.html)
107+nthValue :: Expr Int32 -> Window (Expr a) (Expr (Nullify a))
108+nthValue n =
109+ fromWindowFunction $
110+ dimap (toColumn . toPrimExpr) (fromPrimExpr . fromColumn) $
111+ Opaleye.nthValue (toColumn (toPrimExpr n))
112+
113+
114+fromAggregate :: (a -> Aggregate b) -> Opaleye.Aggregator a (Expr b)
115+fromAggregate f = Opaleye.Aggregator $ Opaleye.PackMap $ \w a -> case f a of
116+ Aggregate (Opaleye.Aggregator (Opaleye.PackMap x)) -> x w ()
117+
118+
119+fromWindowFunction :: Opaleye.WindowFunction a b -> Window a b
120+fromWindowFunction (Opaleye.WindowFunction (Opaleye.PackMap w)) =
121+ Window $ Opaleye.Windows $ Opaleye.PackMap $ \f -> w $ \o -> f (o, mempty)
src/Rel8/Generic/Construction.hs+24−24
@@ -29,8 +29,8 @@ import GHC.TypeLits ( Symbol )
29import Prelude
29import Prelude
30
30
31-- rel8
31-- rel8
32−import Rel8.Aggregate ( Aggregate( A, Aggregate ) )
32+import Rel8.Aggregate ( Aggregate( Aggregate ) )
33−import Rel8.Expr ( Expr( E ) )
33+import Rel8.Expr ( Expr )
34import Rel8.Expr.Aggregate ( groupByExpr )
34import Rel8.Expr.Aggregate ( groupByExpr )
35import Rel8.Expr.Eq ( (==.) )
35import Rel8.Expr.Eq ( (==.) )
36import Rel8.Expr.Null ( nullify, snull, unsafeUnnullify )
36import Rel8.Expr.Null ( nullify, snull, unsafeUnnullify )
@@ -57,11 +57,11 @@ import Rel8.Kind.Algebra
57import qualified Rel8.Kind.Algebra as K
57import qualified Rel8.Kind.Algebra as K
58import Rel8.Schema.Context.Nullify ( sguard, snullify )
58import Rel8.Schema.Context.Nullify ( sguard, snullify )
59import Rel8.Schema.HTable ( HTable )
59import Rel8.Schema.HTable ( HTable )
60−import Rel8.Schema.HTable.Identity ( HIdentity( HType ) )
60+import Rel8.Schema.HTable.Identity ( HIdentity( HIdentity ) )
61import qualified Rel8.Schema.Kind as K
61import qualified Rel8.Schema.Kind as K
62−import Rel8.Schema.Name ( Name( N, Name ) )
62+import Rel8.Schema.Name ( Name( Name ) )
63import Rel8.Schema.Null ( Nullity( Null, NotNull ) )
63import Rel8.Schema.Null ( Nullity( Null, NotNull ) )
64−import Rel8.Schema.Spec ( SSpec( SSpec, nullity, info ) )
64+import Rel8.Schema.Spec ( Spec( Spec, nullity, info ) )
65import Rel8.Table
65import Rel8.Table
66 ( TTable, TColumns
66 ( TTable, TColumns
67 , Table, fromColumns, toColumns
67 , Table, fromColumns, toColumns
@@ -127,11 +127,11 @@ ggbuild gfromColumns = case algebraSing @algebra of
127 @name
127 @name
128 @(Eval (rep Expr))
128 @(Eval (rep Expr))
129 (const toColumns)
129 (const toColumns)
130− (\SSpec {info} -> E (snull info))
130+ (\Spec {info} -> snull info)
131− (\SSpec {nullity} -> case nullity of
131+ (\Spec {nullity} -> case nullity of
132 Null -> id
132 Null -> id
133− NotNull -> \(E a) -> E (nullify a))
133+ NotNull -> nullify)
134− (HType . E . litExpr)
134+ (HIdentity . litExpr)
135
135
136
136
137type GGConstructable :: K.Algebra -> (K.Context -> Exp (Type -> Type)) -> Constraint
137type GGConstructable :: K.Algebra -> (K.Context -> Exp (Type -> Type)) -> Constraint
@@ -198,11 +198,11 @@ ggconstruct gfromColumns f = case algebraSing @algebra of
198 @Expr
198 @Expr
199 @(Eval (rep Expr))
199 @(Eval (rep Expr))
200 (const toColumns)
200 (const toColumns)
201− (\SSpec {info} -> E (snull info))
201+ (\Spec {info} -> snull info)
202− (\SSpec {nullity} -> case nullity of
202+ (\Spec {nullity} -> case nullity of
203 Null -> id
203 Null -> id
204− NotNull -> \(E a) -> E (nullify a))
204+ NotNull -> nullify)
205− (HType . E . litExpr)
205+ (HIdentity . litExpr)
206
206
207
207
208type GGDeconstruct :: K.Algebra -> (K.Context -> Exp (Type -> Type)) -> Type -> Type -> Type
208type GGDeconstruct :: K.Algebra -> (K.Context -> Exp (Type -> Type)) -> Type -> Type -> Type
@@ -230,7 +230,7 @@ ggdeconstruct gtoColumns = case algebraSing @algebra of
230 SSum ->
230 SSum ->
231 gctabulate @Id @(Eval (rep Expr)) @r @(a -> r) $ \constructors as ->
231 gctabulate @Id @(Eval (rep Expr)) @r @(a -> r) $ \constructors as ->
232 let
232 let
233− (HType (E tag), cases) =
233+ (HIdentity tag, cases) =
234 gdeconstructADT
234 gdeconstructADT
235 @(TTable Expr)
235 @(TTable Expr)
236 @TColumns
236 @TColumns
@@ -238,9 +238,9 @@ ggdeconstruct gtoColumns = case algebraSing @algebra of
238 @Expr
238 @Expr
239 @(Eval (rep Expr))
239 @(Eval (rep Expr))
240 (const fromColumns)
240 (const fromColumns)
241− (\SSpec {nullity} -> case nullity of
241+ (\Spec {nullity} -> case nullity of
242 Null -> id
242 Null -> id
243− NotNull -> \(E a) -> E (unsafeUnnullify a))
243+ NotNull -> unsafeUnnullify)
244 constructors $
244 constructors $
245 gtoColumns as
245 gtoColumns as
246 in
246 in
@@ -279,8 +279,8 @@ ggname gfromColumns = case algebraSing @algebra of
279 @Name
279 @Name
280 @(Eval (rep Name))
280 @(Eval (rep Name))
281 (const toColumns)
281 (const toColumns)
282− (\_ _ (N (Name a)) -> N (Name a))
282+ (\_ _ (Name a) -> Name a)
283− (HType (N tag))
283+ (HIdentity tag)
284
284
285
285
286type GGAggregate :: K.Algebra -> (K.Context -> Exp (Type -> Type)) -> Type -> Type
286type GGAggregate :: K.Algebra -> (K.Context -> Exp (Type -> Type)) -> Type -> Type
@@ -330,15 +330,15 @@ ggaggregate gfromColumns gtoColumns agg es = case algebraSing @algebra of
330 @Aggregate
330 @Aggregate
331 @(Eval (rep Aggregate))
331 @(Eval (rep Aggregate))
332 (const toColumns)
332 (const toColumns)
333− (\tag' SSpec {nullity} (A (Aggregate a)) ->
333+ (\tag' Spec {nullity} (Aggregate a) ->
334− A $ Aggregate $ sguard (tag ==. litExpr tag') . snullify nullity <$> a)
334+ Aggregate $ sguard (tag ==. litExpr tag') . snullify nullity <$> a)
335− (HType (A (groupByExpr tag)))
335+ (HIdentity (groupByExpr tag))
336 where
336 where
337 f =
337 f =
338 gfindex @Id @(Eval (rep Expr)) @agg .
338 gfindex @Id @(Eval (rep Expr)) @agg .
339 agg .
339 agg .
340 gftabulate @Id @(Eval (rep Aggregate)) @agg
340 gftabulate @Id @(Eval (rep Aggregate)) @agg
341− (HType (E tag), exprs) =
341+ (HIdentity tag, exprs) =
342 gunbuildADT
342 gunbuildADT
343 @(TTable Expr)
343 @(TTable Expr)
344 @TColumns
344 @TColumns
@@ -346,7 +346,7 @@ ggaggregate gfromColumns gtoColumns agg es = case algebraSing @algebra of
346 @Expr
346 @Expr
347 @(Eval (rep Expr))
347 @(Eval (rep Expr))
348 (const fromColumns)
348 (const fromColumns)
349− (\SSpec {nullity} -> case nullity of
349+ (\Spec {nullity} -> case nullity of
350 Null -> id
350 Null -> id
351− NotNull -> \(E a) -> E (unsafeUnnullify a)) $
351+ NotNull -> unsafeUnnullify) $
352 gtoColumns es
352 gtoColumns es
src/Rel8/Generic/Construction/ADT.hs+13−20
@@ -1,6 +1,7 @@
1{-# language AllowAmbiguousTypes #-}
1{-# language AllowAmbiguousTypes #-}
2{-# language BlockArguments #-}
2{-# language BlockArguments #-}
3{-# language DataKinds #-}
3{-# language DataKinds #-}
4+{-# language FlexibleContexts #-}
4{-# language FlexibleInstances #-}
5{-# language FlexibleInstances #-}
5{-# language MultiParamTypeClasses #-}
6{-# language MultiParamTypeClasses #-}
6{-# language RankNTypes #-}
7{-# language RankNTypes #-}
@@ -49,12 +50,12 @@ import Rel8.Generic.Construction.Record
49import Rel8.Generic.Table.ADT ( GColumnsADT, GColumnsADT' )
50import Rel8.Generic.Table.ADT ( GColumnsADT, GColumnsADT' )
50import Rel8.Generic.Table.Record ( GColumns )
51import Rel8.Generic.Table.Record ( GColumns )
51import Rel8.Schema.HTable ( HTable )
52import Rel8.Schema.HTable ( HTable )
52−import Rel8.Schema.HTable.Identity ( HType )
53+import Rel8.Schema.HTable.Identity ( HIdentity )
53import Rel8.Schema.HTable.Label ( HLabel, hlabel, hunlabel )
54import Rel8.Schema.HTable.Label ( HLabel, hlabel, hunlabel )
54import Rel8.Schema.HTable.Nullify ( HNullify, hnulls, hnullify, hunnullify )
55import Rel8.Schema.HTable.Nullify ( HNullify, hnulls, hnullify, hunnullify )
55import Rel8.Schema.HTable.Product ( HProduct( HProduct ) )
56import Rel8.Schema.HTable.Product ( HProduct( HProduct ) )
56import Rel8.Schema.Null ( Nullify )
57import Rel8.Schema.Null ( Nullify )
57−import Rel8.Schema.Spec ( Spec( Spec ), SSpec )
58+import Rel8.Schema.Spec ( Spec )
58import qualified Rel8.Schema.Kind as K
59import qualified Rel8.Schema.Kind as K
59import Rel8.Type.Tag ( Tag( Tag ) )
60import Rel8.Type.Tag ( Tag( Tag ) )
60
61
@@ -63,23 +64,15 @@ import Data.Text ( pack )
63
64
64
65
65type Null :: K.Context -> Type
66type Null :: K.Context -> Type
66−type Null context = forall a. ()
67+type Null context = forall a. Spec a -> context (Nullify a)
67− => SSpec ('Spec a)
68− -> context ('Spec (Nullify a))
69
68
70
69
71type Nullifier :: K.Context -> Type
70type Nullifier :: K.Context -> Type
72−type Nullifier context = forall a. ()
71+type Nullifier context = forall a. Spec a -> context a -> context (Nullify a)
73− => SSpec ('Spec a)
74− -> context ('Spec a)
75− -> context ('Spec (Nullify a))
76
72
77
73
78type Unnullifier :: K.Context -> Type
74type Unnullifier :: K.Context -> Type
79−type Unnullifier context = forall a. ()
75+type Unnullifier context = forall a. Spec a -> context (Nullify a) -> context a
80− => SSpec ('Spec a)
81− -> context ('Spec (Nullify a))
82− -> context ('Spec a)
83
76
84
77
85type NoConstructor :: Symbol -> Symbol -> ErrorMessage
78type NoConstructor :: Symbol -> Symbol -> ErrorMessage
@@ -193,7 +186,7 @@ class GConstructableADT _Table _Columns f context rep where
193 gbuildADT :: ()
186 gbuildADT :: ()
194 => ToColumns _Table _Columns f context
187 => ToColumns _Table _Columns f context
195 -> (Tag -> Nullifier context)
188 -> (Tag -> Nullifier context)
196− -> HType Tag context
189+ -> HIdentity Tag context
197 -> GFieldsADT f rep
190 -> GFieldsADT f rep
198 -> GColumnsADT _Columns rep context
191 -> GColumnsADT _Columns rep context
199
192
@@ -201,13 +194,13 @@ class GConstructableADT _Table _Columns f context rep where
201 => FromColumns _Table _Columns f context
194 => FromColumns _Table _Columns f context
202 -> Unnullifier context
195 -> Unnullifier context
203 -> GColumnsADT _Columns rep context
196 -> GColumnsADT _Columns rep context
204− -> (HType Tag context, GFieldsADT f rep)
197+ -> (HIdentity Tag context, GFieldsADT f rep)
205
198
206 gconstructADT :: ()
199 gconstructADT :: ()
207 => ToColumns _Table _Columns f context
200 => ToColumns _Table _Columns f context
208 -> Null context
201 -> Null context
209 -> Nullifier context
202 -> Nullifier context
210− -> (Tag -> HType Tag context)
203+ -> (Tag -> HIdentity Tag context)
211 -> GConstructors f rep (GColumnsADT _Columns rep context)
204 -> GConstructors f rep (GColumnsADT _Columns rep context)
212
205
213 gdeconstructADT :: ()
206 gdeconstructADT :: ()
@@ -215,11 +208,11 @@ class GConstructableADT _Table _Columns f context rep where
215 -> Unnullifier context
208 -> Unnullifier context
216 -> GConstructors f rep r
209 -> GConstructors f rep r
217 -> GColumnsADT _Columns rep context
210 -> GColumnsADT _Columns rep context
218− -> (HType Tag context, NonEmpty (Tag, r))
211+ -> (HIdentity Tag context, NonEmpty (Tag, r))
219
212
220
213
221instance
214instance
222− ( htable ~ HLabel "tag" (HType Tag)
215+ ( htable ~ HLabel "tag" (HIdentity Tag)
223 , GConstructableADT' _Table _Columns f context htable rep
216 , GConstructableADT' _Table _Columns f context htable rep
224 )
217 )
225 => GConstructableADT _Table _Columns f context (M1 D meta rep)
218 => GConstructableADT _Table _Columns f context (M1 D meta rep)
@@ -389,13 +382,13 @@ class GMakeableADT _Table _Columns f context name rep where
389 => ToColumns _Table _Columns f context
382 => ToColumns _Table _Columns f context
390 -> Null context
383 -> Null context
391 -> Nullifier context
384 -> Nullifier context
392− -> (Tag -> HType Tag context)
385+ -> (Tag -> HIdentity Tag context)
393 -> GFields f (GConstructorADT name rep)
386 -> GFields f (GConstructorADT name rep)
394 -> GColumnsADT _Columns rep context
387 -> GColumnsADT _Columns rep context
395
388
396
389
397instance
390instance
398− ( htable ~ HLabel "tag" (HType Tag)
391+ ( htable ~ HLabel "tag" (HIdentity Tag)
399 , meta ~ 'MetaData datatype _module _package _newtype
392 , meta ~ 'MetaData datatype _module _package _newtype
400 , fallback ~ TypeError (NoConstructor datatype name)
393 , fallback ~ TypeError (NoConstructor datatype name)
401 , fields ~ GFields f (GConstructorADT' name rep fallback)
394 , fields ~ GFields f (GConstructorADT' name rep fallback)
src/Rel8/Generic/Map.hs+20
@@ -2,9 +2,11 @@
2{-# language StandaloneKindSignatures #-}
2{-# language StandaloneKindSignatures #-}
3{-# language TypeFamilies #-}
3{-# language TypeFamilies #-}
4{-# language TypeOperators #-}
4{-# language TypeOperators #-}
5+{-# language UndecidableInstances #-}
5
6
6module Rel8.Generic.Map
7module Rel8.Generic.Map
7 ( GMap
8 ( GMap
9+ , Map
8 )
10 )
9where
11where
10
12
@@ -27,3 +29,21 @@ type family GMap f rep where
27 GMap _ U1 = U1
29 GMap _ U1 = U1
28 GMap f (rep1 :*: rep2) = GMap f rep1 :*: GMap f rep2
30 GMap f (rep1 :*: rep2) = GMap f rep1 :*: GMap f rep2
29 GMap f (K1 i a) = K1 i (Eval (f a))
31 GMap f (K1 i a) = K1 i (Eval (f a))
32+
33+
34+-- | Map a @Type -> Type@ function over the @Type@-kinded type variables in
35+-- of a type constructor.
36+type Map :: (Type -> Exp Type) -> Type -> Type
37+type family Map f a where
38+ Map p (t a b c d e f g) =
39+ t (Eval (p a)) (Eval (p b)) (Eval (p c)) (Eval (p d)) (Eval (p e))
40+ (Eval (p f)) (Eval (p g))
41+ Map p (t a b c d e f) =
42+ t (Eval (p a)) (Eval (p b)) (Eval (p c)) (Eval (p d)) (Eval (p e))
43+ (Eval (p f))
44+ Map p (t a b c d e) =
45+ t (Eval (p a)) (Eval (p b)) (Eval (p c)) (Eval (p d)) (Eval (p e))
46+ Map p (t a b c d) = t (Eval (p a)) (Eval (p b)) (Eval (p c)) (Eval (p d))
47+ Map p (t a b c) = t (Eval (p a)) (Eval (p b)) (Eval (p c))
48+ Map p (t a b) = t (Eval (p a)) (Eval (p b))
49+ Map p (t a) = t (Eval (p a))
src/Rel8/Generic/Record.hs+2
@@ -1,5 +1,6 @@
1{-# language AllowAmbiguousTypes #-}
1{-# language AllowAmbiguousTypes #-}
2{-# language DataKinds #-}
2{-# language DataKinds #-}
3+{-# language FlexibleContexts #-}
3{-# language FlexibleInstances #-}
4{-# language FlexibleInstances #-}
4{-# language MultiParamTypeClasses #-}
5{-# language MultiParamTypeClasses #-}
5{-# language PolyKinds #-}
6{-# language PolyKinds #-}
@@ -141,6 +142,7 @@ instance {-# OVERLAPPABLE #-} Snd (Count n rep) ~ rep => Countable n rep where
141 uncount = id
142 uncount = id
142
143
143
144
145+type Record :: Type -> Type
144newtype Record a = Record
146newtype Record a = Record
145 { unrecord :: a
147 { unrecord :: a
146 }
148 }
src/Rel8/Generic/Rel8able.hs+150−65
@@ -3,12 +3,16 @@
3{-# language DataKinds #-}
3{-# language DataKinds #-}
4{-# language DefaultSignatures #-}
4{-# language DefaultSignatures #-}
5{-# language FlexibleContexts #-}
5{-# language FlexibleContexts #-}
6+{-# language FlexibleInstances #-}
6{-# language LambdaCase #-}
7{-# language LambdaCase #-}
8+{-# language MultiParamTypeClasses #-}
9+{-# language PolyKinds #-}
10+{-# language QuantifiedConstraints #-}
7{-# language ScopedTypeVariables #-}
11{-# language ScopedTypeVariables #-}
8{-# language StandaloneKindSignatures #-}
12{-# language StandaloneKindSignatures #-}
9{-# language TypeApplications #-}
13{-# language TypeApplications #-}
10−{-# language TypeFamilies #-}
11{-# language TypeFamilyDependencies #-}
14{-# language TypeFamilyDependencies #-}
15+{-# language TypeOperators #-}
12{-# language UndecidableInstances #-}
16{-# language UndecidableInstances #-}
13
17
14module Rel8.Generic.Rel8able
18module Rel8.Generic.Rel8able
@@ -17,31 +21,38 @@ module Rel8.Generic.Rel8able
17 , GRep
21 , GRep
18 , GColumns, gfromColumns, gtoColumns
22 , GColumns, gfromColumns, gtoColumns
19 , GFromExprs, gfromResult, gtoResult
23 , GFromExprs, gfromResult, gtoResult
24+ , TSerialize, serialize, deserialize
20 )
25 )
21where
26where
22
27
23-- base
28-- base
29+import Data.Functor.Identity ( Identity )
24import Data.Kind ( Constraint, Type )
30import Data.Kind ( Constraint, Type )
31+import Data.Type.Bool ( type (&&) )
25import GHC.Generics ( Generic, Rep, from, to )
32import GHC.Generics ( Generic, Rep, from, to )
26import Prelude
33import Prelude
27
34
28-- rel8
35-- rel8
29import Rel8.Aggregate ( Aggregate )
36import Rel8.Aggregate ( Aggregate )
30import Rel8.Expr ( Expr )
37import Rel8.Expr ( Expr )
31−import Rel8.Generic.Map ( GMap )
38+import Rel8.FCF ( Exp, Eval )
32import Rel8.Generic.Record ( Record(..) )
39import Rel8.Generic.Record ( Record(..) )
33import Rel8.Generic.Table ( GAlgebra )
40import Rel8.Generic.Table ( GAlgebra )
34import qualified Rel8.Generic.Table.Record as G
41import qualified Rel8.Generic.Table.Record as G
35import qualified Rel8.Kind.Algebra as K ( Algebra(..) )
42import qualified Rel8.Kind.Algebra as K ( Algebra(..) )
36−import Rel8.Schema.Context.Virtual ( Abstract(..) )
43+import Rel8.Kind.Context ( SContext(..) )
44+import Rel8.Schema.Field ( Field )
37import Rel8.Schema.HTable ( HTable )
45import Rel8.Schema.HTable ( HTable )
38import qualified Rel8.Schema.Kind as K
46import qualified Rel8.Schema.Kind as K
39import Rel8.Schema.Name ( Name )
47import Rel8.Schema.Name ( Name )
40import Rel8.Schema.Result ( Result )
48import Rel8.Schema.Result ( Result )
41import Rel8.Table
49import Rel8.Table
50+ ( Table, Columns, Context, fromColumns, toColumns
42− ( fromColumns, toColumns, fromResult, toResult
51+ , FromExprs, fromResult, toResult
52+ , Transpose
43− , TTable, TColumns, TFromExprs
53+ , TTable, TColumns
44 )
54 )
55+import Rel8.Table.Transpose ( Transposes )
45
56
46
57
47-- | The kind of 'Rel8able' types
58-- | The kind of 'Rel8able' types
@@ -49,6 +60,59 @@ type KRel8able :: Type
49type KRel8able = K.Rel8able
60type KRel8able = K.Rel8able
50
61
51
62
63+-- This is almost 'Data.Type.Equality.==', but we add an extra case.
64+type (==) :: k -> k -> Bool
65+type family a == b where
66+ -- This extra case is needed to solve the equation "a == a" (where a is a
67+ -- KRel8able), which occurs when we have polymorphic Rel8ables
68+ -- (e.g., newtype T t f = T { x :: t a })
69+ (a :: KRel8able) == (a :: KRel8able) = 'True
70+
71+ -- This extra case is needed to solve the equation "a == Identity a",
72+ -- which occurs when we have polymorphic Rel8ables
73+ -- (e.g., newtype T a f = T { x :: Column f a })
74+ a == Identity a = 'False
75+
76+ -- These cases are exactly the same as those in 'Data.Type.Equality.==.
77+ f a == g b = f == g && a == b
78+ a == a = 'True
79+ _ == _ = 'False
80+
81+
82+type Serialize :: Bool -> Type -> Type -> Constraint
83+class transposition ~ (a == Transpose Result expr) =>
84+ Serialize transposition expr a
85+ where
86+ serialize :: a -> Columns expr Result
87+ deserialize :: Columns expr Result -> a
88+
89+
90+instance
91+ ( (a == Transpose Result expr) ~ 'True
92+ , Transposes Expr Result expr a
93+ )
94+ => Serialize 'True expr a
95+ where
96+ serialize = toColumns
97+ deserialize = fromColumns
98+
99+
100+instance
101+ ( (a == Transpose Result expr) ~ 'False
102+ , Table (Context expr) expr
103+ , FromExprs expr ~ a
104+ )
105+ => Serialize 'False expr a
106+ where
107+ serialize = toResult @_ @expr
108+ deserialize = fromResult @_ @expr
109+
110+
111+data TSerialize :: Type -> Type -> Exp Constraint
112+type instance Eval (TSerialize expr a) =
113+ Serialize (a == Transpose Result expr) expr a
114+
115+
52-- | This type class allows you to define custom 'Table's using higher-kinded
116-- | This type class allows you to define custom 'Table's using higher-kinded
53-- data types. Higher-kinded data types are data types of the pattern:
117-- data types. Higher-kinded data types are data types of the pattern:
54--
118--
@@ -82,7 +146,7 @@ type KRel8able = K.Rel8able
82-- [Supplying @Rel8able@ instances]
146-- [Supplying @Rel8able@ instances]
83--
147--
84-- This type class should be derived generically for all table types in your
148-- This type class should be derived generically for all table types in your
85−-- project. To do this, enable the @DeriveAnyType@ and @DeriveGeneric@ language
149+-- project. To do this, enable the @DeriveAnyClass@ and @DeriveGeneric@ language
86-- extensions:
150-- extensions:
87--
151--
88-- @
152-- @
@@ -96,8 +160,8 @@ class HTable (GColumns t) => Rel8able t where
96 type GColumns t :: K.HTable
160 type GColumns t :: K.HTable
97 type GFromExprs t :: Type
161 type GFromExprs t :: Type
98
162
99− gfromColumns :: Abstract context -> GColumns t context -> t context
163+ gfromColumns :: SContext context -> GColumns t context -> t context
100− gtoColumns :: Abstract context -> t context -> GColumns t context
164+ gtoColumns :: SContext context -> t context -> GColumns t context
101
165
102 gfromResult :: GColumns t Result -> GFromExprs t
166 gfromResult :: GColumns t Result -> GFromExprs t
103 gtoResult :: GFromExprs t -> GColumns t Result
167 gtoResult :: GFromExprs t -> GColumns t Result
@@ -106,62 +170,42 @@ class HTable (GColumns t) => Rel8able t where
106 type GFromExprs t = t Result
170 type GFromExprs t = t Result
107
171
108 default gfromColumns :: forall context.
172 default gfromColumns :: forall context.
109− ( VRel8able t Aggregate
173+ ( SRel8able t Aggregate
110− , VRel8able t Expr
174+ , SRel8able t Expr
111− , VRel8able t Name
175+ , forall table. SRel8able t (Field table)
176+ , SRel8able t Name
177+ , SSerialize t
112 )
178 )
113− => Abstract context -> GColumns t context -> t context
179+ => SContext context -> GColumns t context -> t context
114 gfromColumns = \case
180 gfromColumns = \case
115− VAggregate -> vfromColumns
181+ SAggregate -> sfromColumns
116− VExpr -> vfromColumns
182+ SExpr -> sfromColumns
117− VName -> vfromColumns
183+ SField -> sfromColumns
184+ SName -> sfromColumns
185+ SResult -> sfromResult
118
186
119 default gtoColumns :: forall context.
187 default gtoColumns :: forall context.
120− ( VRel8able t Aggregate
188+ ( SRel8able t Aggregate
121− , VRel8able t Expr
189+ , SRel8able t Expr
122− , VRel8able t Name
190+ , forall table. SRel8able t (Field table)
191+ , SRel8able t Name
192+ , SSerialize t
123 )
193 )
124− => Abstract context -> t context -> GColumns t context
194+ => SContext context -> t context -> GColumns t context
125 gtoColumns = \case
195 gtoColumns = \case
126− VAggregate -> vtoColumns
196+ SAggregate -> stoColumns
127− VExpr -> vtoColumns
197+ SExpr -> stoColumns
128− VName -> vtoColumns
198+ SField -> stoColumns
129−
199+ SName -> stoColumns
200+ SResult -> stoResult
201+
130− default gfromResult ::
202+ default gfromResult :: (SSerialize t, GFromExprs t ~ t Result)
131− ( Generic (Record (t Result))
132− , G.GTable (TTable Expr) TColumns TFromExprs (GRep t Expr)
133− , G.GColumns TColumns (GRep t Expr) ~ GColumns t
134− , Rep (Record (t Result)) ~ GMap TFromExprs (GRep t Expr)
135− , GFromExprs t ~ t Result
136− )
137 => GColumns t Result -> GFromExprs t
203 => GColumns t Result -> GFromExprs t
138− gfromResult =
204+ gfromResult = sfromResult
139− unrecord .
205+
140− to .
141− G.gfromResult
142− @(TTable Expr)
143− @TColumns
144− @TFromExprs
145− @(GRep t Expr)
146− (\(_ :: proxy x) -> fromResult @Expr @x)
147−
148− default gtoResult ::
149− ( Generic (Record (t Result))
150− , G.GTable (TTable Expr) TColumns TFromExprs (GRep t Expr)
151− , G.GColumns TColumns (GRep t Expr) ~ GColumns t
152− , Rep (Record (t Result)) ~ GMap TFromExprs (GRep t Expr)
153− , GFromExprs t ~ t Result
206+ default gtoResult :: (SSerialize t, GFromExprs t ~ t Result)
154− )
155 => GFromExprs t -> GColumns t Result
207 => GFromExprs t -> GColumns t Result
156− gtoResult =
208+ gtoResult = stoResult
157− G.gtoResult
158− @(TTable Expr)
159− @TColumns
160− @TFromExprs
161− @(GRep t Expr)
162− (\(_ :: proxy x) -> toResult @Expr @x) .
163− from .
164− Record
165
209
166
210
167type Algebra :: K.Rel8able -> K.Algebra
211type Algebra :: K.Rel8able -> K.Algebra
@@ -172,25 +216,66 @@ type GRep :: K.Rel8able -> K.Context -> Type -> Type
172type GRep t context = Rep (Record (t context))
216type GRep t context = Rep (Record (t context))
173
217
174
218
175−type VRel8able :: K.Rel8able -> K.Context -> Constraint
219+type SRel8able :: K.Rel8able -> K.Context -> Constraint
176−type VRel8able t context =
220+class
221+ ( Generic (Record (t context))
222+ , G.GTable (TTable context) TColumns (GRep t context)
223+ , G.GColumns TColumns (GRep t context) ~ GColumns t
224+ )
225+ => SRel8able t context
226+instance
177 ( Generic (Record (t context))
227 ( Generic (Record (t context))
178− , G.GTable (TTable context) TColumns TFromExprs (GRep t context)
228+ , G.GTable (TTable context) TColumns (GRep t context)
179 , G.GColumns TColumns (GRep t context) ~ GColumns t
229 , G.GColumns TColumns (GRep t context) ~ GColumns t
180 )
230 )
231+ => SRel8able t context
181
232
182
233
234+type SSerialize :: K.Rel8able -> Constraint
235+type SSerialize t =
236+ ( Generic (Record (t Result))
237+ , G.GSerialize TSerialize TColumns (GRep t Expr) (GRep t Result)
238+ , G.GColumns TColumns (GRep t Expr) ~ GColumns t
239+ )
240+
241+
183−vfromColumns :: forall t context. VRel8able t context
242+sfromColumns :: forall t context. SRel8able t context
184 => GColumns t context -> t context
243 => GColumns t context -> t context
185−vfromColumns =
244+sfromColumns =
186 unrecord .
245 unrecord .
187 to .
246 to .
188− G.gfromColumns @(TTable context) @TColumns @TFromExprs fromColumns
247+ G.gfromColumns @(TTable context) @TColumns fromColumns
189
248
190
249
191−vtoColumns :: forall t context. VRel8able t context
250+stoColumns :: forall t context. SRel8able t context
192 => t context -> GColumns t context
251 => t context -> GColumns t context
193−vtoColumns =
252+stoColumns =
194− G.gtoColumns @(TTable context) @TColumns @TFromExprs toColumns .
253+ G.gtoColumns @(TTable context) @TColumns toColumns .
254+ from .
255+ Record
256+
257+
258+sfromResult :: forall t. SSerialize t
259+ => GColumns t Result -> t Result
260+sfromResult =
261+ unrecord .
262+ to .
263+ G.gfromResult
264+ @TSerialize
265+ @TColumns
266+ @(GRep t Expr)
267+ @(GRep t Result)
268+ (\(_ :: proxy x) -> deserialize @_ @x)
269+
270+
271+stoResult :: forall t. SSerialize t
272+ => t Result -> GColumns t Result
273+stoResult =
274+ G.gtoResult
275+ @TSerialize
276+ @TColumns
277+ @(GRep t Expr)
278+ @(GRep t Result)
279+ (\(_ :: proxy x) -> serialize @_ @x) .
195 from .
280 from .
196 Record
281 Record
src/Rel8/Generic/Table.hs+26−27
@@ -12,7 +12,7 @@
12{-# language UndecidableInstances #-}
12{-# language UndecidableInstances #-}
13
13
14module Rel8.Generic.Table
14module Rel8.Generic.Table
15− ( GGTable, GGColumns, ggfromResult, ggtoResult
15+ ( GGSerialize, GGColumns, ggfromResult, ggtoResult
16 , GAlgebra
16 , GAlgebra
17 )
17 )
18where
18where
@@ -24,11 +24,10 @@ import Prelude ()
24
24
25-- rel8
25-- rel8
26import Rel8.FCF ( Eval, Exp )
26import Rel8.FCF ( Eval, Exp )
27−import Rel8.Generic.Map ( GMap )
28import Rel8.Generic.Table.ADT
27import Rel8.Generic.Table.ADT
29− ( GTableADT, GColumnsADT, gtoResultADT, gfromResultADT
28+ ( GSerializeADT, GColumnsADT, gtoResultADT, gfromResultADT
30 )
29 )
31−import Rel8.Generic.Table.Record ( GTable, GColumns, gtoResult, gfromResult )
30+import Rel8.Generic.Table.Record ( GSerialize, GColumns, gtoResult, gfromResult )
32import Rel8.Kind.Algebra
31import Rel8.Kind.Algebra
33 ( Algebra( Product, Sum )
32 ( Algebra( Product, Sum )
34 , SAlgebra( SProduct, SSum )
33 , SAlgebra( SProduct, SSum )
@@ -38,21 +37,21 @@ import qualified Rel8.Schema.Kind as K
38import Rel8.Schema.Result ( Result )
37import Rel8.Schema.Result ( Result )
39
38
40
39
41−data GGTable
40+data GGSerialize
42 :: Algebra
41 :: Algebra
43− -> (Type -> Exp Constraint)
42+ -> (Type -> Type -> Exp Constraint)
44 -> (Type -> Exp K.HTable)
43 -> (Type -> Exp K.HTable)
45− -> (Type -> Exp Type)
44+ -> (Type -> Type)
46 -> (Type -> Type)
45 -> (Type -> Type)
47 -> Exp Constraint
46 -> Exp Constraint
48
47
49
48
50−type instance Eval (GGTable 'Product _Table _Columns _FromExprs rep) =
49+type instance Eval (GGSerialize 'Product _Serialize _Columns exprs rep) =
51− GTable _Table _Columns _FromExprs rep
50+ GSerialize _Serialize _Columns exprs rep
52
51
53
52
54−type instance Eval (GGTable 'Sum _Table _Columns _FromExprs rep) =
53+type instance Eval (GGSerialize 'Sum _Serialize _Columns exprs rep) =
55− GTableADT _Table _Columns _FromExprs rep
54+ GSerializeADT _Serialize _Columns exprs rep
56
55
57
56
58data GGColumns
57data GGColumns
@@ -78,27 +77,27 @@ type family GAlgebra rep where
78 GAlgebra (K1 _ _) = 'Product
77 GAlgebra (K1 _ _) = 'Product
79
78
80
79
81−ggfromResult :: forall algebra _Table _Columns _FromExprs rep x.
80+ggfromResult :: forall algebra _Serialize _Columns exprs rep x.
82 ( KnownAlgebra algebra
81 ( KnownAlgebra algebra
83− , Eval (GGTable algebra _Table _Columns _FromExprs rep)
82+ , Eval (GGSerialize algebra _Serialize _Columns exprs rep)
84 )
83 )
85− => (forall a proxy. Eval (_Table a)
84+ => (forall expr a proxy. Eval (_Serialize expr a)
86− => proxy a -> Eval (_Columns a) Result -> Eval (_FromExprs a))
85+ => proxy expr -> Eval (_Columns expr) Result -> a)
87− -> Eval (GGColumns algebra _Columns rep) Result
86+ -> Eval (GGColumns algebra _Columns exprs) Result
88− -> GMap _FromExprs rep x
87+ -> rep x
89ggfromResult f x = case algebraSing @algebra of
88ggfromResult f x = case algebraSing @algebra of
90− SProduct -> gfromResult @_Table @_Columns @_FromExprs @rep f x
89+ SProduct -> gfromResult @_Serialize @_Columns @exprs @rep f x
91− SSum -> gfromResultADT @_Table @_Columns @_FromExprs @rep f x
90+ SSum -> gfromResultADT @_Serialize @_Columns @exprs @rep f x
92
91
93
92
94−ggtoResult :: forall algebra _Table _Columns _FromExprs rep x.
93+ggtoResult :: forall algebra _Serialize _Columns exprs rep x.
95 ( KnownAlgebra algebra
94 ( KnownAlgebra algebra
96− , Eval (GGTable algebra _Table _Columns _FromExprs rep)
95+ , Eval (GGSerialize algebra _Serialize _Columns exprs rep)
97 )
96 )
98− => (forall a proxy. Eval (_Table a)
97+ => (forall expr a proxy. Eval (_Serialize expr a)
99− => proxy a -> Eval (_FromExprs a) -> Eval (_Columns a) Result)
98+ => proxy expr -> a -> Eval (_Columns expr) Result)
100− -> GMap _FromExprs rep x
99+ -> rep x
101− -> Eval (GGColumns algebra _Columns rep) Result
100+ -> Eval (GGColumns algebra _Columns exprs) Result
102ggtoResult f x = case algebraSing @algebra of
101ggtoResult f x = case algebraSing @algebra of
103− SProduct -> gtoResult @_Table @_Columns @_FromExprs @rep f x
102+ SProduct -> gtoResult @_Serialize @_Columns @exprs @rep f x
104− SSum -> gtoResultADT @_Table @_Columns @_FromExprs @rep f x
103+ SSum -> gtoResultADT @_Serialize @_Columns @exprs @rep f x
src/Rel8/Generic/Table/ADT.hs+64−68
@@ -1,5 +1,6 @@
1{-# language AllowAmbiguousTypes #-}
1{-# language AllowAmbiguousTypes #-}
2{-# language DataKinds #-}
2{-# language DataKinds #-}
3+{-# language FlexibleContexts #-}
3{-# language FlexibleInstances #-}
4{-# language FlexibleInstances #-}
4{-# language LambdaCase #-}
5{-# language LambdaCase #-}
5{-# language MultiParamTypeClasses #-}
6{-# language MultiParamTypeClasses #-}
@@ -12,12 +13,13 @@
12{-# language UndecidableInstances #-}
13{-# language UndecidableInstances #-}
13
14
14module Rel8.Generic.Table.ADT
15module Rel8.Generic.Table.ADT
15− ( GTableADT, GColumnsADT, gfromResultADT, gtoResultADT
16+ ( GSerializeADT, GColumnsADT, gfromResultADT, gtoResultADT
16− , GTableADT', GColumnsADT'
17+ , GSerializeADT', GColumnsADT'
17 )
18 )
18where
19where
19
20
20-- base
21-- base
22+import Data.Functor.Identity ( Identity( Identity ) )
21import Data.Kind ( Constraint, Type )
23import Data.Kind ( Constraint, Type )
22import Data.Proxy ( Proxy( Proxy ) )
24import Data.Proxy ( Proxy( Proxy ) )
23import GHC.Generics
25import GHC.Generics
@@ -30,18 +32,14 @@ import Prelude hiding ( null )
30
32
31-- rel8
33-- rel8
32import Rel8.FCF ( Eval, Exp )
34import Rel8.FCF ( Eval, Exp )
33−import Rel8.Generic.Map ( GMap )
34−import Rel8.Generic.Table.Record ( GTable, GColumns, gfromResult, gtoResult )
35+import Rel8.Generic.Table.Record ( GSerialize, GColumns, gfromResult, gtoResult )
35import Rel8.Schema.HTable ( HTable )
36import Rel8.Schema.HTable ( HTable )
36−import Rel8.Schema.HTable.Identity ( HIdentity( HType ), HType )
37+import Rel8.Schema.HTable.Identity ( HIdentity( HIdentity ) )
37import Rel8.Schema.HTable.Label ( HLabel, hlabel, hunlabel )
38import Rel8.Schema.HTable.Label ( HLabel, hlabel, hunlabel )
38import Rel8.Schema.HTable.Nullify ( HNullify, hnulls, hnullify, hunnullify )
39import Rel8.Schema.HTable.Nullify ( HNullify, hnulls, hnullify, hunnullify )
39import Rel8.Schema.HTable.Product ( HProduct( HProduct ) )
40import Rel8.Schema.HTable.Product ( HProduct( HProduct ) )
40import qualified Rel8.Schema.Kind as K
41import qualified Rel8.Schema.Kind as K
41−import Rel8.Schema.Result
42− ( Result( R )
43− , null, nullifier, unnullifier
42+import Rel8.Schema.Result ( Result, null, nullifier, unnullifier )
44− )
45import Rel8.Type.Tag ( Tag( Tag ) )
43import Rel8.Type.Tag ( Tag( Tag ) )
46
44
47-- text
45-- text
@@ -53,7 +51,7 @@ type GColumnsADT
53 -> (Type -> Type) -> K.HTable
51 -> (Type -> Type) -> K.HTable
54type family GColumnsADT _Columns rep where
52type family GColumnsADT _Columns rep where
55 GColumnsADT _Columns (M1 D _ rep) =
53 GColumnsADT _Columns (M1 D _ rep) =
56− GColumnsADT' _Columns (HLabel "tag" (HType Tag)) rep
54+ GColumnsADT' _Columns (HLabel "tag" (HIdentity Tag)) rep
57
55
58
56
59type GColumnsADT'
57type GColumnsADT'
@@ -67,120 +65,118 @@ type family GColumnsADT' _Columns htable rep where
67 HProduct htable (HLabel label (HNullify (GColumns _Columns rep)))
65 HProduct htable (HLabel label (HNullify (GColumns _Columns rep)))
68
66
69
67
70−type GTableADT
68+type GSerializeADT
71− :: (Type -> Exp Constraint)
69+ :: (Type -> Type -> Exp Constraint)
72 -> (Type -> Exp K.HTable)
70 -> (Type -> Exp K.HTable)
73− -> (Type -> Exp Type)
74− -> (Type -> Type) -> Constraint
71+ -> (Type -> Type) -> (Type -> Type) -> Constraint
75−class GTableADT _Table _Columns _FromExprs rep where
72+class GSerializeADT _Serialize _Columns exprs rep where
76 gfromResultADT :: ()
73 gfromResultADT :: ()
77− => (forall a proxy. Eval (_Table a)
74+ => (forall expr a proxy. Eval (_Serialize expr a)
78− => proxy a -> Eval (_Columns a) Result -> Eval (_FromExprs a))
75+ => proxy expr -> Eval (_Columns expr) Result -> a)
79− -> GColumnsADT _Columns rep Result
76+ -> GColumnsADT _Columns exprs Result
80− -> GMap _FromExprs rep x
77+ -> rep x
81
78
82 gtoResultADT :: ()
79 gtoResultADT :: ()
83− => (forall a proxy. Eval (_Table a)
80+ => (forall expr a proxy. Eval (_Serialize expr a)
84− => proxy a -> Eval (_FromExprs a) -> Eval (_Columns a) Result)
81+ => proxy expr -> a -> Eval (_Columns expr) Result)
85− -> GMap _FromExprs rep x
82+ -> rep x
86− -> GColumnsADT _Columns rep Result
83+ -> GColumnsADT _Columns exprs Result
87
84
88
85
89instance
86instance
90− ( htable ~ HLabel "tag" (HType Tag)
87+ ( htable ~ HLabel "tag" (HIdentity Tag)
91− , GTableADT' _Table _Columns _FromExprs htable rep
88+ , GSerializeADT' _Serialize _Columns htable exprs rep
92 )
89 )
93− => GTableADT _Table _Columns _FromExprs (M1 D meta rep)
90+ => GSerializeADT _Serialize _Columns (M1 D meta exprs) (M1 D meta rep)
94 where
91 where
95 gfromResultADT fromResult columns =
92 gfromResultADT fromResult columns =
96− case gfromResultADT' @_Table @_Columns @_FromExprs @htable @rep fromResult tag columns of
93+ case gfromResultADT' @_Serialize @_Columns @htable @exprs @rep fromResult tag columns of
97 Just rep -> M1 rep
94 Just rep -> M1 rep
98 _ -> error "ADT.fromColumns: mismatch between tag and data"
95 _ -> error "ADT.fromColumns: mismatch between tag and data"
99 where
96 where
100− tag = (\(HType (R a)) -> a) . hunlabel @"tag"
97+ tag = (\(HIdentity (Identity a)) -> a) . hunlabel @"tag"
101
98
102 gtoResultADT toResult (M1 rep) =
99 gtoResultADT toResult (M1 rep) =
103− gtoResultADT' @_Table @_Columns @_FromExprs @htable @rep toResult tag (Just rep)
100+ gtoResultADT' @_Serialize @_Columns @htable @exprs @rep toResult tag (Just rep)
104 where
101 where
105− tag = hlabel @"tag" . HType . R
102+ tag = hlabel @"tag" . HIdentity . Identity
106
103
107
104
108−type GTableADT'
105+type GSerializeADT'
109− :: (Type -> Exp Constraint)
106+ :: (Type -> Type -> Exp Constraint)
110 -> (Type -> Exp K.HTable)
107 -> (Type -> Exp K.HTable)
111− -> (Type -> Exp Type)
112− -> K.HTable -> (Type -> Type) -> Constraint
108+ -> K.HTable -> (Type -> Type) -> (Type -> Type) -> Constraint
113−class GTableADT' _Table _Columns _FromExprs htable rep where
109+class GSerializeADT' _Serialize _Columns htable exprs rep where
114 gfromResultADT' :: context ~ Result
110 gfromResultADT' :: context ~ Result
115− => (forall a proxy. Eval (_Table a)
111+ => (forall expr a proxy. Eval (_Serialize expr a)
116− => proxy a -> Eval (_Columns a) context -> Eval (_FromExprs a))
112+ => proxy expr -> Eval (_Columns expr) context -> a)
117 -> (htable Result -> Tag)
113 -> (htable Result -> Tag)
118− -> GColumnsADT' _Columns htable rep context
114+ -> GColumnsADT' _Columns htable exprs context
119− -> Maybe (GMap _FromExprs rep x)
115+ -> Maybe (rep x)
120
116
121 gtoResultADT' :: context ~ Result
117 gtoResultADT' :: context ~ Result
122− => (forall a proxy. Eval (_Table a)
118+ => (forall expr a proxy. Eval (_Serialize expr a)
123− => proxy a -> Eval (_FromExprs a) -> Eval (_Columns a) context)
119+ => proxy expr -> a -> Eval (_Columns expr) context)
124 -> (Tag -> htable Result)
120 -> (Tag -> htable Result)
125− -> Maybe (GMap _FromExprs rep x)
121+ -> Maybe (rep x)
126− -> GColumnsADT' _Columns htable rep context
122+ -> GColumnsADT' _Columns htable exprs context
127
123
128− extract :: GColumnsADT' _Columns htable rep context -> htable context
124+ extract :: GColumnsADT' _Columns htable exprs context -> htable context
129
125
130
126
131instance
127instance
132− ( htable' ~ GColumnsADT' _Columns htable a
128+ ( htable' ~ GColumnsADT' _Columns htable exprs1
133− , GTableADT' _Table _Columns _FromExprs htable a
129+ , GSerializeADT' _Serialize _Columns htable exprs1 a
134− , GTableADT' _Table _Columns _FromExprs htable' b
130+ , GSerializeADT' _Serialize _Columns htable' exprs2 b
135 )
131 )
136− => GTableADT' _Table _Columns _FromExprs htable (a :+: b)
132+ => GSerializeADT' _Serialize _Columns htable (exprs1 :+: exprs2) (a :+: b)
137 where
133 where
138 gfromResultADT' fromResult f columns =
134 gfromResultADT' fromResult f columns =
139 case ma of
135 case ma of
140 Just a -> Just (L1 a)
136 Just a -> Just (L1 a)
141 Nothing -> R1 <$>
137 Nothing -> R1 <$>
142− gfromResultADT' @_Table @_Columns @_FromExprs @_ @b
138+ gfromResultADT' @_Serialize @_Columns @_ @exprs2 @b
143 fromResult
139 fromResult
144− (f . extract @_Table @_Columns @_FromExprs @_ @a)
140+ (f . extract @_Serialize @_Columns @_ @exprs1 @a)
145 columns
141 columns
146 where
142 where
147 ma =
143 ma =
148− gfromResultADT' @_Table @_Columns @_FromExprs @_ @a
144+ gfromResultADT' @_Serialize @_Columns @_ @exprs1 @a
149 fromResult
145 fromResult
150 f
146 f
151− (extract @_Table @_Columns @_FromExprs @_ @b columns)
147+ (extract @_Serialize @_Columns @_ @exprs2 @b columns)
152
148
153 gtoResultADT' toResult tag = \case
149 gtoResultADT' toResult tag = \case
154 Just (L1 a) ->
150 Just (L1 a) ->
155− gtoResultADT' @_Table @_Columns @_FromExprs @_ @b
151+ gtoResultADT' @_Serialize @_Columns @_ @exprs2 @b
156 toResult
152 toResult
157− (\_ -> gtoResultADT' @_Table @_Columns @_FromExprs @_ @a
153+ (\_ -> gtoResultADT' @_Serialize @_Columns @_ @exprs1 @a
158 toResult
154 toResult
159 tag
155 tag
160 (Just a))
156 (Just a))
161 Nothing
157 Nothing
162 Just (R1 b) ->
158 Just (R1 b) ->
163− gtoResultADT' @_Table @_Columns @_FromExprs @_ @b
159+ gtoResultADT' @_Serialize @_Columns @_ @exprs2 @b
164 toResult
160 toResult
165 (\tag' ->
161 (\tag' ->
166− gtoResultADT' @_Table @_Columns @_FromExprs @_ @a
162+ gtoResultADT' @_Serialize @_Columns @_ @exprs1 @a
167 toResult
163 toResult
168 (\_ -> tag tag')
164 (\_ -> tag tag')
169 Nothing)
165 Nothing)
170 (Just b)
166 (Just b)
171 Nothing ->
167 Nothing ->
172− gtoResultADT' @_Table @_Columns @_FromExprs @_ @b
168+ gtoResultADT' @_Serialize @_Columns @_ @exprs2 @b
173 toResult
169 toResult
174− (\_ -> gtoResultADT' @_Table @_Columns @_FromExprs @_ @a toResult tag Nothing)
170+ (\_ -> gtoResultADT' @_Serialize @_Columns @_ @exprs1 @a toResult tag Nothing)
175 Nothing
171 Nothing
176
172
177 extract =
173 extract =
178− extract @_Table @_Columns @_FromExprs @_ @a .
174+ extract @_Serialize @_Columns @_ @exprs1 @a .
179− extract @_Table @_Columns @_FromExprs @_ @b
175+ extract @_Serialize @_Columns @_ @exprs2 @b
180
176
181
177
182instance (meta ~ 'MetaCons label _fixity _isRecord, KnownSymbol label) =>
178instance (meta ~ 'MetaCons label _fixity _isRecord, KnownSymbol label) =>
183− GTableADT' _Table _Columns _FromExprs htable (M1 C meta U1)
179+ GSerializeADT' _Serialize _Columns _htable (M1 C meta U1) (M1 C meta U1)
184 where
180 where
185 gfromResultADT' _ tag columns
181 gfromResultADT' _ tag columns
186 | tag columns == tag' = Just (M1 U1)
182 | tag columns == tag' = Just (M1 U1)
@@ -196,18 +192,18 @@ instance (meta ~ 'MetaCons label _fixity _isRecord, KnownSymbol label) =>
196
192
197
193
198instance {-# OVERLAPPABLE #-}
194instance {-# OVERLAPPABLE #-}
199− ( HTable (GColumns _Columns rep)
195+ ( HTable (GColumns _Columns exprs)
200− , GTable _Table _Columns _FromExprs rep
196+ , GSerialize _Serialize _Columns exprs rep
201 , meta ~ 'MetaCons label _fixity _isRecord
197 , meta ~ 'MetaCons label _fixity _isRecord
202 , KnownSymbol label
198 , KnownSymbol label
203− , GColumnsADT' _Columns htable (M1 C ('MetaCons label _fixity _isRecord) rep) ~
199+ , GColumnsADT' _Columns htable (M1 C ('MetaCons label _fixity _isRecord) exprs) ~
204− HProduct htable (HLabel label (HNullify (GColumns _Columns rep)))
200+ HProduct htable (HLabel label (HNullify (GColumns _Columns exprs)))
205 )
201 )
206− => GTableADT' _Table _Columns _FromExprs htable (M1 C meta rep)
202+ => GSerializeADT' _Serialize _Columns htable (M1 C meta exprs) (M1 C meta rep)
207 where
203 where
208 gfromResultADT' fromResult tag (HProduct a b)
204 gfromResultADT' fromResult tag (HProduct a b)
209 | tag a == tag' =
205 | tag a == tag' =
210− M1 . gfromResult @_Table @_Columns @_FromExprs @rep fromResult <$>
206+ M1 . gfromResult @_Serialize @_Columns @exprs @rep fromResult <$>
211 hunnullify unnullifier (hunlabel b)
207 hunnullify unnullifier (hunlabel b)
212 | otherwise = Nothing
208 | otherwise = Nothing
213 where
209 where
@@ -218,7 +214,7 @@ instance {-# OVERLAPPABLE #-}
218 Just (M1 rep) -> HProduct (tag tag') $
214 Just (M1 rep) -> HProduct (tag tag') $
219 hlabel $
215 hlabel $
220 hnullify nullifier $
216 hnullify nullifier $
221− gtoResult @_Table @_Columns @_FromExprs @rep toResult rep
217+ gtoResult @_Serialize @_Columns @exprs @rep toResult rep
222 where
218 where
223 tag' = Tag $ pack $ symbolVal (Proxy @label)
219 tag' = Tag $ pack $ symbolVal (Proxy @label)
224
220
src/Rel8/Generic/Table/Record.hs+78−50
@@ -13,8 +13,8 @@
13{-# language UndecidableInstances #-}
13{-# language UndecidableInstances #-}
14
14
15module Rel8.Generic.Table.Record
15module Rel8.Generic.Table.Record
16− ( GTable, GColumns, GContext
16+ ( GTable, GColumns, GContext, gfromColumns, gtoColumns, gtable
17− , gfromColumns, gtoColumns, gfromResult, gtoResult, gtable
17+ , GSerialize, gfromResult, gtoResult
18 )
18 )
19where
19where
20
20
@@ -30,7 +30,6 @@ import Prelude hiding ( null )
30
30
31-- rel8
31-- rel8
32import Rel8.FCF ( Eval, Exp )
32import Rel8.FCF ( Eval, Exp )
33−import Rel8.Generic.Map ( GMap )
34import Rel8.Schema.HTable.Label ( HLabel, hlabel, hunlabel )
33import Rel8.Schema.HTable.Label ( HLabel, hlabel, hunlabel )
35import Rel8.Schema.HTable.Product ( HProduct(..) )
34import Rel8.Schema.HTable.Product ( HProduct(..) )
36import qualified Rel8.Schema.Kind as K
35import qualified Rel8.Schema.Kind as K
@@ -56,9 +55,8 @@ type family GContext _Context rep where
56type GTable
55type GTable
57 :: (Type -> Exp Constraint)
56 :: (Type -> Exp Constraint)
58 -> (Type -> Exp K.HTable)
57 -> (Type -> Exp K.HTable)
59− -> (Type -> Exp Type)
60 -> (Type -> Type) -> Constraint
58 -> (Type -> Type) -> Constraint
61−class GTable _Table _Columns _FromExprs rep
59+class GTable _Table _Columns rep
62 where
60 where
63 gfromColumns :: ()
61 gfromColumns :: ()
64 => (forall a. Eval (_Table a) => Eval (_Columns a) context -> a)
62 => (forall a. Eval (_Table a) => Eval (_Columns a) context -> a)
@@ -70,73 +68,93 @@ class GTable _Table _Columns _FromExprs rep
70 -> rep x
68 -> rep x
71 -> GColumns _Columns rep context
69 -> GColumns _Columns rep context
72
70
73− gfromResult :: ()
74− => (forall a proxy. Eval (_Table a)
75− => proxy a -> Eval (_Columns a) context -> Eval (_FromExprs a))
76− -> GColumns _Columns rep context
77− -> GMap _FromExprs rep x
78−
79− gtoResult :: ()
80− => (forall a proxy. Eval (_Table a)
81− => proxy a -> Eval (_FromExprs a) -> Eval (_Columns a) context)
82− -> GMap _FromExprs rep x
83− -> GColumns _Columns rep context
84−
85 gtable :: ()
71 gtable :: ()
86 => (forall a proxy. Eval (_Table a) => proxy a -> Eval (_Columns a) context)
72 => (forall a proxy. Eval (_Table a) => proxy a -> Eval (_Columns a) context)
87 -> GColumns _Columns rep context
73 -> GColumns _Columns rep context
88
74
89
75
76+type GSerialize
77+ :: (Type -> Type -> Exp Constraint)
78+ -> (Type -> Exp K.HTable)
79+ -> (Type -> Type) -> (Type -> Type) -> Constraint
80+class GSerialize _Serialize _Columns exprs rep
81+ where
82+ gfromResult :: ()
83+ => (forall expr a proxy. Eval (_Serialize expr a)
84+ => proxy expr -> Eval (_Columns expr) context -> a)
85+ -> GColumns _Columns exprs context
86+ -> rep x
87+
88+ gtoResult :: ()
89+ => (forall expr a proxy. Eval (_Serialize expr a)
90+ => proxy expr -> a -> Eval (_Columns expr) context)
91+ -> rep x
92+ -> GColumns _Columns exprs context
93+
94+
90−instance GTable _Table _Columns _FromExprs rep =>
95+instance GTable _Table _Columns rep => GTable _Table _Columns (M1 D c rep)
91− GTable _Table _Columns _FromExprs (M1 D c rep)
92 where
96 where
93 gfromColumns fromColumns =
97 gfromColumns fromColumns =
94− M1 . gfromColumns @_Table @_Columns @_FromExprs @rep fromColumns
98+ M1 . gfromColumns @_Table @_Columns @rep fromColumns
95 gtoColumns toColumns (M1 a) =
99 gtoColumns toColumns (M1 a) =
96− gtoColumns @_Table @_Columns @_FromExprs @rep toColumns a
100+ gtoColumns @_Table @_Columns @rep toColumns a
101+ gtable = gtable @_Table @_Columns @rep
102+
103+
104+instance GSerialize _Serialize _Columns exprs rep =>
105+ GSerialize _Serialize _Columns (M1 D c exprs) (M1 D c rep)
106+ where
97 gfromResult fromResult =
107 gfromResult fromResult =
98− M1 . gfromResult @_Table @_Columns @_FromExprs @rep fromResult
108+ M1 . gfromResult @_Serialize @_Columns @exprs @rep fromResult
99 gtoResult toResult (M1 a) =
109 gtoResult toResult (M1 a) =
100− gtoResult @_Table @_Columns @_FromExprs @rep toResult a
110+ gtoResult @_Serialize @_Columns @exprs @rep toResult a
101− gtable = gtable @_Table @_Columns @_FromExprs @rep
102
111
103
112
104−instance GTable _Table _Columns _FromExprs rep =>
113+instance GTable _Table _Columns rep => GTable _Table _Columns (M1 C c rep)
105− GTable _Table _Columns _FromExprs (M1 C c rep)
106 where
114 where
107 gfromColumns fromColumns =
115 gfromColumns fromColumns =
108− M1 . gfromColumns @_Table @_Columns @_FromExprs @rep fromColumns
116+ M1 . gfromColumns @_Table @_Columns @rep fromColumns
109 gtoColumns toColumns (M1 a) =
117 gtoColumns toColumns (M1 a) =
110− gtoColumns @_Table @_Columns @_FromExprs @rep toColumns a
118+ gtoColumns @_Table @_Columns @rep toColumns a
119+ gtable = gtable @_Table @_Columns @rep
120+
121+
122+instance GSerialize _Serialize _Columns exprs rep =>
123+ GSerialize _Serialize _Columns (M1 C c exprs) (M1 C c rep)
124+ where
111 gfromResult fromResult =
125 gfromResult fromResult =
112− M1 . gfromResult @_Table @_Columns @_FromExprs @rep fromResult
126+ M1 . gfromResult @_Serialize @_Columns @exprs @rep fromResult
113 gtoResult toResult (M1 a) =
127 gtoResult toResult (M1 a) =
114− gtoResult @_Table @_Columns @_FromExprs @rep toResult a
128+ gtoResult @_Serialize @_Columns @exprs @rep toResult a
115− gtable = gtable @_Table @_Columns @_FromExprs @rep
116
129
117
130
118−instance
119− ( GTable _Table _Columns _FromExprs rep1
131+instance (GTable _Table _Columns rep1, GTable _Table _Columns rep2) =>
120− , GTable _Table _Columns _FromExprs rep2
121− )
122− => GTable _Table _Columns _FromExprs (rep1 :*: rep2)
132+ GTable _Table _Columns (rep1 :*: rep2)
123 where
133 where
124 gfromColumns fromColumns (HProduct a b) =
134 gfromColumns fromColumns (HProduct a b) =
125− gfromColumns @_Table @_Columns @_FromExprs @rep1 fromColumns a :*:
135+ gfromColumns @_Table @_Columns @rep1 fromColumns a :*:
126− gfromColumns @_Table @_Columns @_FromExprs @rep2 fromColumns b
136+ gfromColumns @_Table @_Columns @rep2 fromColumns b
127 gtoColumns toColumns (a :*: b) = HProduct
137 gtoColumns toColumns (a :*: b) = HProduct
128− (gtoColumns @_Table @_Columns @_FromExprs @rep1 toColumns a)
138+ (gtoColumns @_Table @_Columns @rep1 toColumns a)
129− (gtoColumns @_Table @_Columns @_FromExprs @rep2 toColumns b)
139+ (gtoColumns @_Table @_Columns @rep2 toColumns b)
140+ gtable table = HProduct
141+ (gtable @_Table @_Columns @rep1 table)
142+ (gtable @_Table @_Columns @rep2 table)
143+
144+
145+instance
146+ ( GSerialize _Serialize _Columns expr1 rep1
147+ , GSerialize _Serialize _Columns expr2 rep2
148+ )
149+ => GSerialize _Serialize _Columns (expr1 :*: expr2) (rep1 :*: rep2)
150+ where
130 gfromResult fromResult (HProduct a b) =
151 gfromResult fromResult (HProduct a b) =
131− gfromResult @_Table @_Columns @_FromExprs @rep1 fromResult a :*:
152+ gfromResult @_Serialize @_Columns @expr1 @rep1 fromResult a :*:
132− gfromResult @_Table @_Columns @_FromExprs @rep2 fromResult b
153+ gfromResult @_Serialize @_Columns @expr2 @rep2 fromResult b
133 gtoResult toResult (a :*: b) =
154 gtoResult toResult (a :*: b) =
134 HProduct
155 HProduct
135− (gtoResult @_Table @_Columns @_FromExprs @rep1 toResult a)
156+ (gtoResult @_Serialize @_Columns @expr1 @rep1 toResult a)
136− (gtoResult @_Table @_Columns @_FromExprs @rep2 toResult b)
157+ (gtoResult @_Serialize @_Columns @expr2 @rep2 toResult b)
137− gtable table = HProduct
138− (gtable @_Table @_Columns @_FromExprs @rep1 table)
139− (gtable @_Table @_Columns @_FromExprs @rep2 table)
140
158
141
159
142instance
160instance
@@ -144,10 +162,20 @@ instance
144 , meta ~ 'MetaSel ('Just label) _su _ss _ds
162 , meta ~ 'MetaSel ('Just label) _su _ss _ds
145 , k1 ~ K1 i a
163 , k1 ~ K1 i a
146 )
164 )
147− => GTable _Table _Columns _FromExprs (M1 S meta k1)
165+ => GTable _Table _Columns (M1 S meta k1)
148 where
166 where
149 gfromColumns fromColumns = M1 . K1 . fromColumns . hunlabel
167 gfromColumns fromColumns = M1 . K1 . fromColumns . hunlabel
150 gtoColumns toColumns (M1 (K1 a)) = hlabel (toColumns a)
168 gtoColumns toColumns (M1 (K1 a)) = hlabel (toColumns a)
151− gfromResult fromResult = M1 . K1 . fromResult (Proxy @a) . hunlabel
152− gtoResult toResult (M1 (K1 a)) = hlabel (toResult (Proxy @a) a)
153 gtable table = hlabel (table (Proxy @a))
169 gtable table = hlabel (table (Proxy @a))
170+
171+
172+instance
173+ ( Eval (_Serialize expr a)
174+ , meta ~ 'MetaSel ('Just label) _su _ss _ds
175+ , k1 ~ K1 i expr
176+ , k1' ~ K1 i a
177+ )
178+ => GSerialize _Serialize _Columns (M1 S meta k1) (M1 S meta k1')
179+ where
180+ gfromResult fromResult = M1 . K1 . fromResult (Proxy @expr) . hunlabel
181+ gtoResult toResult (M1 (K1 a)) = hlabel (toResult (Proxy @expr) a)
src/Rel8/Kind/Context.hs+7
@@ -1,6 +1,7 @@
1{-# language DataKinds #-}
1{-# language DataKinds #-}
2{-# language GADTs #-}
2{-# language GADTs #-}
3{-# language StandaloneKindSignatures #-}
3{-# language StandaloneKindSignatures #-}
4+{-# language TypeSynonymInstances #-}
4
5
5module Rel8.Kind.Context
6module Rel8.Kind.Context
6 ( Reifiable( contextSing )
7 ( Reifiable( contextSing )
@@ -15,6 +16,7 @@ import Prelude ()
15-- rel8
16-- rel8
16import Rel8.Aggregate ( Aggregate )
17import Rel8.Aggregate ( Aggregate )
17import Rel8.Expr ( Expr )
18import Rel8.Expr ( Expr )
19+import Rel8.Schema.Field ( Field )
18import Rel8.Schema.Kind ( Context )
20import Rel8.Schema.Kind ( Context )
19import Rel8.Schema.Name ( Name )
21import Rel8.Schema.Name ( Name )
20import Rel8.Schema.Result ( Result )
22import Rel8.Schema.Result ( Result )
@@ -24,6 +26,7 @@ type SContext :: Context -> Type
24data SContext context where
26data SContext context where
25 SAggregate :: SContext Aggregate
27 SAggregate :: SContext Aggregate
26 SExpr :: SContext Expr
28 SExpr :: SContext Expr
29+ SField :: SContext (Field table)
27 SName :: SContext Name
30 SName :: SContext Name
28 SResult :: SContext Result
31 SResult :: SContext Result
29
32
@@ -41,6 +44,10 @@ instance Reifiable Expr where
41 contextSing = SExpr
44 contextSing = SExpr
42
45
43
46
47+instance Reifiable (Field table) where
48+ contextSing = SField
49+
50+
44instance Reifiable Result where
51instance Reifiable Result where
45 contextSing = SResult
52 contextSing = SResult
46
53
src/Rel8/Order.hs+1−8
@@ -4,7 +4,6 @@
4
4
5module Rel8.Order
5module Rel8.Order
6 ( Order(..)
6 ( Order(..)
7− , toOrderExprs
8 )
7 )
9where
8where
10
9
@@ -17,8 +16,7 @@ import Prelude
17import Data.Functor.Contravariant.Divisible ( Decidable, Divisible )
16import Data.Functor.Contravariant.Divisible ( Decidable, Divisible )
18
17
19-- opaleye
18-- opaleye
20−import qualified Opaleye.Internal.HaskellDB.PrimQuery as Opaleye
19+import qualified Opaleye.Order as Opaleye
21−import qualified Opaleye.Internal.Order as Opaleye
22
20
23
21
24-- | An ordering expression for @a@. Primitive orderings are defined with
22-- | An ordering expression for @a@. Primitive orderings are defined with
@@ -30,8 +28,3 @@ import qualified Opaleye.Internal.Order as Opaleye
30type Order :: Type -> Type
28type Order :: Type -> Type
31newtype Order a = Order (Opaleye.Order a)
29newtype Order a = Order (Opaleye.Order a)
32 deriving newtype (Contravariant, Divisible, Decidable, Semigroup, Monoid)
30 deriving newtype (Contravariant, Divisible, Decidable, Semigroup, Monoid)
33−
34−
35−toOrderExprs :: Order a -> a -> [Opaleye.OrderExpr]
36−toOrderExprs (Order (Opaleye.Order order)) a =
37− uncurry Opaleye.OrderExpr <$> order a
src/Rel8/Query.hs+28−9
@@ -1,4 +1,6 @@
1+{-# language FlexibleContexts #-}
1{-# language StandaloneKindSignatures #-}
2{-# language StandaloneKindSignatures #-}
3+{-# language UndecidableInstances #-}
2
4
3module Rel8.Query
5module Rel8.Query
4 ( Query( Query )
6 ( Query( Query )
@@ -15,18 +17,21 @@ import Prelude
15-- opaleye
17-- opaleye
16import qualified Opaleye.Internal.HaskellDB.PrimQuery as Opaleye
18import qualified Opaleye.Internal.HaskellDB.PrimQuery as Opaleye
17import qualified Opaleye.Internal.PackMap as Opaleye
19import qualified Opaleye.Internal.PackMap as Opaleye
18−import qualified Opaleye.Internal.PrimQuery as Opaleye
20+import qualified Opaleye.Internal.PrimQuery as Opaleye hiding (lateral)
19import qualified Opaleye.Internal.QueryArr as Opaleye
21import qualified Opaleye.Internal.QueryArr as Opaleye
20import qualified Opaleye.Internal.Tag as Opaleye
22import qualified Opaleye.Internal.Tag as Opaleye
21
23
22-- rel8
24-- rel8
25+import Rel8.Expr ( Expr )
23import Rel8.Query.Set ( unionAll )
26import Rel8.Query.Set ( unionAll )
24import Rel8.Query.Opaleye ( fromOpaleye )
27import Rel8.Query.Opaleye ( fromOpaleye )
25import Rel8.Query.Values ( values )
28import Rel8.Query.Values ( values )
29+import Rel8.Table ( Table, fromColumns, toColumns )
26import Rel8.Table.Alternative
30import Rel8.Table.Alternative
27 ( AltTable, (<|>:)
31 ( AltTable, (<|>:)
28 , AlternativeTable, emptyTable
32 , AlternativeTable, emptyTable
29 )
33 )
34+import Rel8.Table.Projection ( Projectable, apply, project )
30
35
31-- semigroupoids
36-- semigroupoids
32import Data.Functor.Apply ( Apply, (<.>) )
37import Data.Functor.Apply ( Apply, (<.>) )
@@ -151,6 +156,10 @@ newtype Query a =
151 )
156 )
152
157
153
158
159+instance Projectable Query where
160+ project f = fmap (fromColumns . apply f . toColumns)
161+
162+
154instance Functor Query where
163instance Functor Query where
155 fmap f (Query a) = Query (fmap (fmap (fmap f)) a)
164 fmap f (Query a) = Query (fmap (fmap (fmap f)) a)
156
165
@@ -169,14 +178,14 @@ instance Bind Query where
169
178
170
179
171instance Monad Query where
180instance Monad Query where
172− Query q >>= f = Query $ \dummies -> Opaleye.QueryArr $ \(_, tag) ->
181+ Query q >>= f = Query $ \dummies -> Opaleye.stateQueryArr $ \_ tag ->
173 let
182 let
174− Opaleye.QueryArr qa = q dummies
183+ qa = q dummies
175− ((m, a), query, tag') = qa ((), tag)
184+ ((m, a), query, tag') = Opaleye.runStateQueryArr qa () tag
176 Query q' = f a
185 Query q' = f a
177 (dummies', query', tag'') =
186 (dummies', query', tag'') =
178 ( dummy : dummies
187 ( dummy : dummies
179− , \lateral -> Opaleye.Rebind True bindings . query lateral
188+ , query <> Opaleye.aRebind bindings
180 , Opaleye.next tag'
189 , Opaleye.next tag'
181 )
190 )
182 where
191 where
@@ -184,11 +193,11 @@ instance Monad Query where
184 where
193 where
185 random = Opaleye.FunExpr "random" []
194 random = Opaleye.FunExpr "random" []
186 name = Opaleye.extractAttr "dummy" tag'
195 name = Opaleye.extractAttr "dummy" tag'
187− Opaleye.QueryArr qa' = Opaleye.lateral $ \_ -> q' dummies'
196+ qa' = Opaleye.lateral $ \_ -> q' dummies'
188− ((m'@(Any needsDummies), b), query'', tag''') = qa' ((), tag'')
197+ ((m'@(Any needsDummies), b), query'', tag''') = Opaleye.runStateQueryArr qa' () tag''
189 query'''
198 query'''
190− | needsDummies = \lateral -> query'' lateral . query' lateral
199+ | needsDummies = query' <> query''
191− | otherwise = \lateral -> query'' lateral . query lateral
200+ | otherwise = query <> query''
192 m'' = m <> m'
201 m'' = m <> m'
193 in
202 in
194 ((m'', b), query''', tag''')
203 ((m'', b), query''', tag''')
@@ -202,3 +211,13 @@ instance AltTable Query where
202-- | 'emptyTable' = 'values' @[]@.
211-- | 'emptyTable' = 'values' @[]@.
203instance AlternativeTable Query where
212instance AlternativeTable Query where
204 emptyTable = values []
213 emptyTable = values []
214+
215+
216+-- | '<>' = 'unionAll'.
217+instance Table Expr a => Semigroup (Query a) where
218+ (<>) = (<|>:)
219+
220+
221+-- | 'mempty' = @'values' []@.
222+instance Table Expr a => Monoid (Query a) where
223+ mempty = emptyTable
src/Rel8/Query/Aggregate.hs+19
@@ -1,13 +1,17 @@
1{-# language FlexibleContexts #-}
1{-# language FlexibleContexts #-}
2{-# language MonoLocalBinds #-}
2{-# language MonoLocalBinds #-}
3+{-# language ScopedTypeVariables #-}
4+{-# language TypeApplications #-}
3
5
4module Rel8.Query.Aggregate
6module Rel8.Query.Aggregate
5 ( aggregate
7 ( aggregate
6 , countRows
8 , countRows
9+ , mode
7 )
10 )
8where
11where
9
12
10-- base
13-- base
14+import Data.Functor.Contravariant ( (>$<) )
11import Data.Int ( Int64 )
15import Data.Int ( Int64 )
12import Prelude
16import Prelude
13
17
@@ -18,9 +22,16 @@ import qualified Opaleye.Aggregate as Opaleye
18import Rel8.Aggregate ( Aggregates )
22import Rel8.Aggregate ( Aggregates )
19import Rel8.Expr ( Expr )
23import Rel8.Expr ( Expr )
20import Rel8.Expr.Aggregate ( countStar )
24import Rel8.Expr.Aggregate ( countStar )
25+import Rel8.Expr.Order ( desc )
21import Rel8.Query ( Query )
26import Rel8.Query ( Query )
27+import Rel8.Query.Limit ( limit )
22import Rel8.Query.Maybe ( optional )
28import Rel8.Query.Maybe ( optional )
23import Rel8.Query.Opaleye ( mapOpaleye )
29import Rel8.Query.Opaleye ( mapOpaleye )
30+import Rel8.Query.Order ( orderBy )
31+import Rel8.Table ( toColumns )
32+import Rel8.Table.Aggregate ( hgroupBy )
33+import Rel8.Table.Cols ( Cols( Cols ), fromCols )
34+import Rel8.Table.Eq ( EqTable, eqTable )
24import Rel8.Table.Opaleye ( aggregator )
35import Rel8.Table.Opaleye ( aggregator )
25import Rel8.Table.Maybe ( maybeTable )
36import Rel8.Table.Maybe ( maybeTable )
26
37
@@ -35,3 +46,11 @@ aggregate = mapOpaleye (Opaleye.aggregate aggregator)
35-- will return @0@.
46-- will return @0@.
36countRows :: Query a -> Query (Expr Int64)
47countRows :: Query a -> Query (Expr Int64)
37countRows = fmap (maybeTable 0 id) . optional . aggregate . fmap (const countStar)
48countRows = fmap (maybeTable 0 id) . optional . aggregate . fmap (const countStar)
49+
50+
51+-- | Return the most common row in a query.
52+mode :: forall a. EqTable a => Query a -> Query a
53+mode rows = limit 1 $ fmap (fromCols . snd) $ orderBy (fst >$< desc) $ do
54+ aggregate $ do
55+ row <- toColumns <$> rows
56+ pure (countStar, Cols $ hgroupBy (eqTable @a) row)
src/Rel8/Query/Distinct.hs+4−9
@@ -1,5 +1,3 @@
1−{-# options_ghc -fno-warn-redundant-constraints #-}
2−
3module Rel8.Query.Distinct
1module Rel8.Query.Distinct
4 ( distinct
2 ( distinct
5 , distinctOn
3 , distinctOn
@@ -8,12 +6,11 @@ module Rel8.Query.Distinct
8where
6where
9
7
10-- base
8-- base
11−import Prelude
9+import Prelude ()
12
10
13-- opaleye
11-- opaleye
14import qualified Opaleye.Distinct as Opaleye
12import qualified Opaleye.Distinct as Opaleye
15−import qualified Opaleye.Internal.Order as Opaleye
13+import qualified Opaleye.Order as Opaleye
16−import qualified Opaleye.Internal.QueryArr as Opaleye
17
14
18-- rel8
15-- rel8
19import Rel8.Order ( Order( Order ) )
16import Rel8.Order ( Order( Order ) )
@@ -33,13 +30,11 @@ distinct = mapOpaleye (Opaleye.distinctExplicit distinctspec)
33-- to a projection. If multiple rows have the same projection, it is
30-- to a projection. If multiple rows have the same projection, it is
34-- unspecified which row will be returned. If this matters, use 'distinctOnBy'.
31-- unspecified which row will be returned. If this matters, use 'distinctOnBy'.
35distinctOn :: EqTable b => (a -> b) -> Query a -> Query a
32distinctOn :: EqTable b => (a -> b) -> Query a -> Query a
36−distinctOn proj =
37− mapOpaleye (\q -> Opaleye.productQueryArr (Opaleye.distinctOn unpackspec proj . Opaleye.runSimpleQueryArr q))
33+distinctOn proj = mapOpaleye (Opaleye.distinctOnExplicit unpackspec proj)
38
34
39
35
40-- | Select all distinct rows from a query, where rows are equivalent according
36-- | Select all distinct rows from a query, where rows are equivalent according
41-- to a projection. If there are multiple rows with the same projection, the
37-- to a projection. If there are multiple rows with the same projection, the
42-- first row according to the specified 'Order' will be returned.
38-- first row according to the specified 'Order' will be returned.
43distinctOnBy :: EqTable b => (a -> b) -> Order a -> Query a -> Query a
39distinctOnBy :: EqTable b => (a -> b) -> Order a -> Query a -> Query a
44−distinctOnBy proj (Order order) =
40+distinctOnBy proj (Order order) = mapOpaleye (Opaleye.distinctOnByExplicit unpackspec proj order)
45− mapOpaleye (\q -> Opaleye.productQueryArr (Opaleye.distinctOnBy unpackspec proj order . Opaleye.runSimpleQueryArr q))
src/Rel8/Query/Evaluate.hs+3−22
@@ -3,7 +3,6 @@
3
3
4module Rel8.Query.Evaluate
4module Rel8.Query.Evaluate
5 ( evaluate
5 ( evaluate
6− , rebind
7 )
6 )
8where
7where
9
8
@@ -16,28 +15,23 @@ import Prelude hiding ( undefined )
16
15
17-- opaleye
16-- opaleye
18import qualified Opaleye.Internal.HaskellDB.PrimQuery as Opaleye
17import qualified Opaleye.Internal.HaskellDB.PrimQuery as Opaleye
19−import qualified Opaleye.Internal.PackMap as Opaleye
20−import qualified Opaleye.Internal.PrimQuery as Opaleye
21−import qualified Opaleye.Internal.QueryArr as Opaleye
22−import qualified Opaleye.Internal.Tag as Opaleye
23−import qualified Opaleye.Internal.Unpackspec as Opaleye
24
18
25-- rel8
19-- rel8
26import Rel8.Expr ( Expr )
20import Rel8.Expr ( Expr )
27import Rel8.Expr.Bool ( (&&.) )
21import Rel8.Expr.Bool ( (&&.) )
28import Rel8.Expr.Opaleye ( fromPrimExpr )
22import Rel8.Expr.Opaleye ( fromPrimExpr )
29import Rel8.Query ( Query( Query ) )
23import Rel8.Query ( Query( Query ) )
24+import Rel8.Query.Rebind ( rebind )
30import Rel8.Table ( Table )
25import Rel8.Table ( Table )
31import Rel8.Table.Bool ( case_ )
26import Rel8.Table.Bool ( case_ )
32−import Rel8.Table.Opaleye ( unpackspec )
27+import Rel8.Table.Undefined ( undefined )
33−import Rel8.Table.Undefined
34
28
35
29
36-- | 'evaluate' takes expressions that could potentially have side effects and
30-- | 'evaluate' takes expressions that could potentially have side effects and
37-- \"runs\" them in the 'Query' monad. The returned expressions have no side
31-- \"runs\" them in the 'Query' monad. The returned expressions have no side
38-- effects and can safely be reused.
32-- effects and can safely be reused.
39evaluate :: Table Expr a => a -> Query a
33evaluate :: Table Expr a => a -> Query a
40−evaluate = laterally >=> rebind
34+evaluate = laterally >=> rebind "eval"
41
35
42
36
43laterally :: Table Expr a => a -> Query a
37laterally :: Table Expr a => a -> Query a
@@ -51,18 +45,5 @@ laterally a = Query $ \bindings -> pure $ (Any True,) $
51 go = fromPrimExpr . Opaleye.UnExpr Opaleye.OpIsNotNull
45 go = fromPrimExpr . Opaleye.UnExpr Opaleye.OpIsNotNull
52
46
53
47
54−-- | 'rebind' takes some expressions, and binds each of them to a new
55−-- variable in the SQL. The @a@ returned consists only of these
56−-- variables. It's essentially a @let@ binding for Postgres expressions.
57−rebind :: Table Expr a => a -> Query a
58−rebind a = Query $ \_ -> Opaleye.QueryArr $ \(_, tag) ->
59− let
60− tag' = Opaleye.next tag
61− (a', bindings) = Opaleye.run $
62− Opaleye.runUnpackspec unpackspec (Opaleye.extractAttr "eval" tag') a
63− in
64− ((mempty, a'), \_ -> Opaleye.Rebind True bindings, tag')
65−
66−
67foldl1' :: (a -> a -> a) -> NonEmpty a -> a
48foldl1' :: (a -> a -> a) -> NonEmpty a -> a
68foldl1' f (a :| as) = foldl' f a as
49foldl1' f (a :| as) = foldl' f a as
src/Rel8/Query/Exists.hs+1−1
@@ -12,7 +12,7 @@ import Prelude hiding ( filter )
12
12
13-- opaleye
13-- opaleye
14import qualified Opaleye.Exists as Opaleye
14import qualified Opaleye.Exists as Opaleye
15−import qualified Opaleye.Operators as Opaleye hiding ( exists )
15+import qualified Opaleye.Operators as Opaleye
16
16
17-- rel8
17-- rel8
18import Rel8.Expr ( Expr )
18import Rel8.Expr ( Expr )
src/Rel8/Query/Indexed.hsnew file+21
@@ -0,0 +1,21 @@
1+module Rel8.Query.Indexed
2+ ( indexed
3+ )
4+where
5+
6+-- base
7+import Control.Applicative ( liftA2 )
8+import Data.Int ( Int64 )
9+import Prelude
10+
11+-- rel8
12+import Rel8.Expr ( Expr )
13+import Rel8.Expr.Window ( rowNumber )
14+import Rel8.Query ( Query )
15+import Rel8.Query.Window ( window )
16+import Rel8.Table.Window ( currentRow )
17+
18+
19+-- | Pair each row of a query with its index within the query.
20+indexed :: Query a -> Query (Expr Int64, a)
21+indexed = window (liftA2 (,) (subtract 1 <$> rowNumber) currentRow)
src/Rel8/Query/List.hs+11−9
@@ -19,16 +19,16 @@ import Prelude
19import qualified Opaleye.Internal.HaskellDB.PrimQuery as Opaleye
19import qualified Opaleye.Internal.HaskellDB.PrimQuery as Opaleye
20
20
21-- rel8
21-- rel8
22−import Rel8.Expr ( Expr( E, unE ) )
22+import Rel8.Expr ( Expr )
23import Rel8.Expr.Aggregate ( listAggExpr, nonEmptyAggExpr )
23import Rel8.Expr.Aggregate ( listAggExpr, nonEmptyAggExpr )
24import Rel8.Expr.Opaleye ( mapPrimExpr )
24import Rel8.Expr.Opaleye ( mapPrimExpr )
25import Rel8.Query ( Query )
25import Rel8.Query ( Query )
26import Rel8.Query.Aggregate ( aggregate )
26import Rel8.Query.Aggregate ( aggregate )
27−import Rel8.Query.Evaluate ( rebind )
28import Rel8.Query.Maybe ( optional )
27import Rel8.Query.Maybe ( optional )
28+import Rel8.Query.Rebind ( rebind )
29import Rel8.Schema.HTable.Vectorize ( hunvectorize )
29import Rel8.Schema.HTable.Vectorize ( hunvectorize )
30import Rel8.Schema.Null ( Sql, Unnullify )
30import Rel8.Schema.Null ( Sql, Unnullify )
31−import Rel8.Schema.Spec ( SSpec( SSpec, info ) )
31+import Rel8.Schema.Spec ( Spec( Spec, info ) )
32import Rel8.Table ( Table, fromColumns )
32import Rel8.Table ( Table, fromColumns )
33import Rel8.Table.Cols ( toCols )
33import Rel8.Table.Cols ( toCols )
34import Rel8.Table.Aggregate ( listAgg, nonEmptyAgg )
34import Rel8.Table.Aggregate ( listAgg, nonEmptyAgg )
@@ -85,8 +85,9 @@ someExpr = aggregate . fmap nonEmptyAggExpr
85--
85--
86-- @catListTable@ is an inverse to 'many'.
86-- @catListTable@ is an inverse to 'many'.
87catListTable :: Table Expr a => ListTable Expr a -> Query a
87catListTable :: Table Expr a => ListTable Expr a -> Query a
88+catListTable (ListTable as) =
88−catListTable (ListTable as) = rebind $ fromColumns $ runIdentity $
89+ rebind "unnest" $ fromColumns $ runIdentity $
89− hunvectorize (\SSpec {info} -> pure . E . sunnest info . unE) as
90+ hunvectorize (\Spec {info} -> pure . sunnest info) as
90
91
91
92
92-- | Expand a 'NonEmptyTable' into a 'Query', where each row in the query is an
93-- | Expand a 'NonEmptyTable' into a 'Query', where each row in the query is an
@@ -94,8 +95,9 @@ catListTable (ListTable as) = rebind $ fromColumns $ runIdentity $
94--
95--
95-- @catNonEmptyTable@ is an inverse to 'some'.
96-- @catNonEmptyTable@ is an inverse to 'some'.
96catNonEmptyTable :: Table Expr a => NonEmptyTable Expr a -> Query a
97catNonEmptyTable :: Table Expr a => NonEmptyTable Expr a -> Query a
97−catNonEmptyTable (NonEmptyTable as) = rebind $ fromColumns $ runIdentity $
98+catNonEmptyTable (NonEmptyTable as) =
99+ rebind "unnest" $ fromColumns $ runIdentity $
98− hunvectorize (\SSpec {info} -> pure . E . sunnest info . unE) as
100+ hunvectorize (\Spec {info} -> pure . sunnest info) as
99
101
100
102
101-- | Expand an expression that contains a list into a 'Query', where each row
103-- | Expand an expression that contains a list into a 'Query', where each row
@@ -103,7 +105,7 @@ catNonEmptyTable (NonEmptyTable as) = rebind $ fromColumns $ runIdentity $
103--
105--
104-- @catList@ is an inverse to 'manyExpr'.
106-- @catList@ is an inverse to 'manyExpr'.
105catList :: Sql DBType a => Expr [a] -> Query (Expr a)
107catList :: Sql DBType a => Expr [a] -> Query (Expr a)
106−catList = rebind . sunnest typeInformation
108+catList = rebind "unnest" . sunnest typeInformation
107
109
108
110
109-- | Expand an expression that contains a non-empty list into a 'Query', where
111-- | Expand an expression that contains a non-empty list into a 'Query', where
@@ -111,7 +113,7 @@ catList = rebind . sunnest typeInformation
111--
113--
112-- @catNonEmpty@ is an inverse to 'someExpr'.
114-- @catNonEmpty@ is an inverse to 'someExpr'.
113catNonEmpty :: Sql DBType a => Expr (NonEmpty a) -> Query (Expr a)
115catNonEmpty :: Sql DBType a => Expr (NonEmpty a) -> Query (Expr a)
114−catNonEmpty = rebind . sunnest typeInformation
116+catNonEmpty = rebind "unnest" . sunnest typeInformation
115
117
116
118
117sunnest :: TypeInformation (Unnullify a) -> Expr (list a) -> Expr a
119sunnest :: TypeInformation (Unnullify a) -> Expr (list a) -> Expr a
src/Rel8/Query/Maybe.hs+5−5
@@ -19,7 +19,7 @@ import Control.Comonad ( extract )
19import qualified Opaleye.Internal.MaybeFields as Opaleye
19import qualified Opaleye.Internal.MaybeFields as Opaleye
20
20
21-- rel8
21-- rel8
22−import Rel8.Expr ( Expr( E ) )
22+import Rel8.Expr ( Expr )
23import Rel8.Expr.Eq ( (==.) )
23import Rel8.Expr.Eq ( (==.) )
24import Rel8.Expr.Opaleye ( fromColumn, fromPrimExpr )
24import Rel8.Expr.Opaleye ( fromColumn, fromPrimExpr )
25import Rel8.Query ( Query )
25import Rel8.Query ( Query )
@@ -35,7 +35,7 @@ import Rel8.Table.Maybe ( MaybeTable(..), isJustTable )
35-- JOIN@s.
35-- JOIN@s.
36optional :: Query a -> Query (MaybeTable Expr a)
36optional :: Query a -> Query (MaybeTable Expr a)
37optional = mapOpaleye $ Opaleye.optionalInternal $ \tag a -> MaybeTable
37optional = mapOpaleye $ Opaleye.optionalInternal $ \tag a -> MaybeTable
38− { tag = E $ fromPrimExpr $ fromColumn tag
38+ { tag = fromPrimExpr $ fromColumn tag
39 , just = pure a
39 , just = pure a
40 }
40 }
41
41
@@ -61,8 +61,8 @@ catMaybeTable ma@(MaybeTable _ a) = do
61-- the input is @nothingTable@, you will always get exactly one @nothingTable@
61-- the input is @nothingTable@, you will always get exactly one @nothingTable@
62-- back.
62-- back.
63traverseMaybeTable :: (a -> Query b) -> MaybeTable Expr a -> Query (MaybeTable Expr b)
63traverseMaybeTable :: (a -> Query b) -> MaybeTable Expr a -> Query (MaybeTable Expr b)
64−traverseMaybeTable query ma@(MaybeTable (E input) _) = do
64+traverseMaybeTable query ma@(MaybeTable input _) = do
65 optional (query =<< catMaybeTable ma) >>= \case
65 optional (query =<< catMaybeTable ma) >>= \case
66− MaybeTable (E output) b -> do
66+ MaybeTable output b -> do
67 where_ $ output ==. input
67 where_ $ output ==. input
68− pure $ MaybeTable (E input) b
68+ pure $ MaybeTable input b
src/Rel8/Query/Null.hs+15
@@ -1,5 +1,8 @@
1+{-# language FlexibleContexts #-}
2+
1module Rel8.Query.Null
3module Rel8.Query.Null
2 ( catNull
4 ( catNull
5+ , catNullTable
3 )
6 )
4where
7where
5
8
@@ -9,6 +12,8 @@ import Prelude
9-- rel8
12-- rel8
10import Rel8.Expr ( Expr )
13import Rel8.Expr ( Expr )
11import Rel8.Expr.Null ( isNonNull, unsafeUnnullify )
14import Rel8.Expr.Null ( isNonNull, unsafeUnnullify )
15+import Rel8.Table ( Table )
16+import Rel8.Table.Null ( NullTable, isNonNullTable, unsafeUnnullifyTable )
12import Rel8.Query ( Query )
17import Rel8.Query ( Query )
13import Rel8.Query.Filter ( where_ )
18import Rel8.Query.Filter ( where_ )
14
19
@@ -21,3 +26,13 @@ catNull :: Expr (Maybe a) -> Query (Expr a)
21catNull a = do
26catNull a = do
22 where_ $ isNonNull a
27 where_ $ isNonNull a
23 pure $ unsafeUnnullify a
28 pure $ unsafeUnnullify a
29+
30+
31+-- | Filter a 'Query' that might return @nullTable@ to a 'Query' without any
32+-- @nullTable@s.
33+--
34+-- Corresponds to 'Data.Maybe.catMaybes'.
35+catNullTable :: Table Expr a => NullTable Expr a -> Query a
36+catNullTable a = do
37+ where_ $ isNonNullTable a
38+ pure $ unsafeUnnullifyTable a
src/Rel8/Query/Opaleye.hs+18−10
@@ -5,6 +5,7 @@ module Rel8.Query.Opaleye
5 , toOpaleye
5 , toOpaleye
6 , mapOpaleye
6 , mapOpaleye
7 , zipOpaleyeWith
7 , zipOpaleyeWith
8+ , unsafePeekQuery
8 )
9 )
9where
10where
10
11
@@ -14,6 +15,7 @@ import Prelude
14
15
15-- opaleye
16-- opaleye
16import qualified Opaleye.Internal.QueryArr as Opaleye
17import qualified Opaleye.Internal.QueryArr as Opaleye
18+import qualified Opaleye.Internal.Tag as Opaleye
17
19
18-- rel8
20-- rel8
19import {-# SOURCE #-} Rel8.Query ( Query( Query ) )
21import {-# SOURCE #-} Rel8.Query ( Query( Query ) )
@@ -37,26 +39,32 @@ zipOpaleyeWith :: ()
37zipOpaleyeWith f (Query a) (Query b) = Query $ liftA2 (zipping f) a b
39zipOpaleyeWith f (Query a) (Query b) = Query $ liftA2 (zipping f) a b
38
40
39
41
42+unsafePeekQuery :: Query a -> a
43+unsafePeekQuery (Query q) = case q mempty of
44+ f -> case Opaleye.runStateQueryArr f () Opaleye.start of
45+ ((_, a), _, _) -> a
46+
47+
40mapping :: ()
48mapping :: ()
41 => (Opaleye.Select a -> Opaleye.Select b)
49 => (Opaleye.Select a -> Opaleye.Select b)
42 -> Opaleye.Select (m, a) -> Opaleye.Select (m, b)
50 -> Opaleye.Select (m, a) -> Opaleye.Select (m, b)
43−mapping f q@(Opaleye.QueryArr qa) = Opaleye.QueryArr $ \(_, tag) ->
51+mapping f q = Opaleye.stateQueryArr $ \_ tag ->
44 let
52 let
45− ((m, _), _, _) = qa ((), tag)
53+ ((m, _), _, _) = Opaleye.runStateQueryArr q () tag
46− Opaleye.QueryArr qa' = (m,) <$> f (snd <$> q)
54+ q' = (m,) <$> f (snd <$> q)
47 in
55 in
48− qa' ((), tag)
56+ Opaleye.runStateQueryArr q' () tag
49
57
50
58
51zipping :: Semigroup m
59zipping :: Semigroup m
52 => (Opaleye.Select a -> Opaleye.Select b -> Opaleye.Select c)
60 => (Opaleye.Select a -> Opaleye.Select b -> Opaleye.Select c)
53 -> Opaleye.Select (m, a) -> Opaleye.Select (m, b) -> Opaleye.Select (m, c)
61 -> Opaleye.Select (m, a) -> Opaleye.Select (m, b) -> Opaleye.Select (m, c)
54−zipping f q@(Opaleye.QueryArr qa) q'@(Opaleye.QueryArr qa') =
62+zipping f q q' =
55− Opaleye.QueryArr $ \(_, tag) ->
63+ Opaleye.stateQueryArr $ \_ tag ->
56 let
64 let
57− ((m, _), _, _) = qa ((), tag)
65+ ((m, _), _, _) = Opaleye.runStateQueryArr q () tag
58− ((m', _), _, _) = qa' ((), tag)
66+ ((m', _), _, _) = Opaleye.runStateQueryArr q' () tag
59 m'' = m <> m'
67 m'' = m <> m'
60− Opaleye.QueryArr qa'' = (m'',) <$> f (snd <$> q) (snd <$> q')
68+ q'' = (m'',) <$> f (snd <$> q) (snd <$> q')
61 in
69 in
62− qa'' ((), tag)
70+ Opaleye.runStateQueryArr q'' () tag
src/Rel8/Query/Rebind.hsnew file+27
@@ -0,0 +1,27 @@
1+{-# language FlexibleContexts #-}
2+
3+module Rel8.Query.Rebind
4+ ( rebind
5+ )
6+where
7+
8+-- base
9+import Prelude
10+import Control.Arrow ((<<<))
11+
12+-- opaleye
13+import qualified Opaleye.Internal.Rebind as Opaleye
14+
15+-- rel8
16+import Rel8.Expr ( Expr )
17+import Rel8.Query ( Query )
18+import Rel8.Table ( Table )
19+import Rel8.Table.Opaleye ( unpackspec )
20+import Rel8.Query.Opaleye (fromOpaleye)
21+
22+
23+-- | 'rebind' takes a variable name, some expressions, and binds each of them
24+-- to a new variable in the SQL. The @a@ returned consists only of these
25+-- variables. It's essentially a @let@ binding for Postgres expressions.
26+rebind :: Table Expr a => String -> a -> Query a
27+rebind prefix a = fromOpaleye (Opaleye.rebindExplicitPrefix prefix unpackspec <<< pure a)
src/Rel8/Query/SQL.hs+6−60
@@ -1,75 +1,21 @@
1{-# language FlexibleContexts #-}
1{-# language FlexibleContexts #-}
2−{-# language TypeFamilies #-}
2+{-# language MonoLocalBinds #-}
3−{-# language ViewPatterns #-}
4
3
5module Rel8.Query.SQL
4module Rel8.Query.SQL
6 ( showQuery
5 ( showQuery
7− , sqlForQuery, sqlForQueryWithNames
8 )
6 )
9where
7where
10
8
11-- base
9-- base
12−import Data.Foldable ( fold )
13−import Data.Functor.Const ( Const( Const ), getConst )
14−import Data.Void ( Void )
15import Prelude
10import Prelude
16
11
17−-- opaleye
18−import qualified Opaleye.Internal.HaskellDB.Sql as Opaleye
19−import qualified Opaleye.Internal.PrimQuery as Opaleye
20−import qualified Opaleye.Internal.Print as Opaleye
21−import qualified Opaleye.Internal.Optimize as Opaleye
22−import qualified Opaleye.Internal.QueryArr as Opaleye hiding ( Select )
23−import qualified Opaleye.Internal.Sql as Opaleye
24−
25-- rel8
12-- rel8
26−import Rel8.Expr ( Expr( E ) )
13+import Rel8.Expr ( Expr )
27−import Rel8.Expr.Opaleye ( toPrimExpr )
28import Rel8.Query ( Query )
14import Rel8.Query ( Query )
29−import Rel8.Query.Opaleye ( toOpaleye )
15+import Rel8.Statement.Select ( ppSelect )
30−import Rel8.Schema.Name ( Name( N, Name ), Selects )
31−import Rel8.Schema.HTable ( htabulateA, hfield )
32−import Rel8.Table ( Table, toColumns )
33−import Rel8.Table.Cols ( toCols )
34−import Rel8.Table.Name ( namesFromLabels )
16+import Rel8.Table ( Table )
35−import Rel8.Table.Opaleye ( castTable )
36
17
37
18
38−-- | Convert a query to a 'String' containing the query as a @SELECT@
19+-- | Convert a 'Query' to a 'String' containing a @SELECT@ statement.
39−-- statement.
40showQuery :: Table Expr a => Query a -> String
20showQuery :: Table Expr a => Query a -> String
41−showQuery = fold . sqlForQuery
21+showQuery = show . ppSelect
42−
43−
44−sqlForQuery :: Table Expr a
45− => Query a -> Maybe String
46−sqlForQuery = sqlForQueryWithNames namesFromLabels . fmap toCols
47−
48−
49−sqlForQueryWithNames :: Selects names exprs
50− => names -> Query exprs -> Maybe String
51−sqlForQueryWithNames names query =
52− show . Opaleye.ppSql . selectFrom names exprs <$> optimize primQuery
53− where
54− (exprs, primQuery, _) =
55− Opaleye.runSimpleQueryArrStart (toOpaleye query) ()
56−
57−
58−optimize :: Opaleye.PrimQuery' a -> Maybe (Opaleye.PrimQuery' Void)
59−optimize = Opaleye.removeEmpty . Opaleye.optimize
60−
61−
62−selectFrom :: Selects names exprs
63− => names -> exprs -> Opaleye.PrimQuery' Void -> Opaleye.Select
64−selectFrom (toColumns -> names) (toColumns . castTable -> exprs) query =
65− Opaleye.SelectFrom $ Opaleye.newSelect
66− { Opaleye.attrs = Opaleye.SelectAttrs attributes
67− , Opaleye.tables = Opaleye.oneTable select
68− }
69− where
70− select = Opaleye.foldPrimQuery Opaleye.sqlQueryGenerator query
71− attributes = getConst $ htabulateA $ \field -> case hfield names field of
72− N (Name name) -> case hfield exprs field of
73− E (toPrimExpr -> expr) -> Const (pure (makeAttr name expr))
74− makeAttr label expr =
75− (Opaleye.sqlExpr expr, Just (Opaleye.SqlColumn label))
src/Rel8/Query/Set.hs+6−6
@@ -23,36 +23,36 @@ import Rel8.Table.Opaleye ( binaryspec )
23
23
24
24
25-- | Combine the results of two queries of the same type, collapsing
25-- | Combine the results of two queries of the same type, collapsing
26−-- duplicates. @union a b@ is the same as the SQL statement @x UNION b@.
26+-- duplicates. @union a b@ is the same as the SQL statement @a UNION b@.
27union :: EqTable a => Query a -> Query a -> Query a
27union :: EqTable a => Query a -> Query a -> Query a
28union = zipOpaleyeWith (Opaleye.unionExplicit binaryspec)
28union = zipOpaleyeWith (Opaleye.unionExplicit binaryspec)
29
29
30
30
31-- | Combine the results of two queries of the same type, retaining duplicates.
31-- | Combine the results of two queries of the same type, retaining duplicates.
32−-- @unionAll a b@ is the same as the SQL statement @x UNION ALL b@.
32+-- @unionAll a b@ is the same as the SQL statement @a UNION ALL b@.
33unionAll :: Table Expr a => Query a -> Query a -> Query a
33unionAll :: Table Expr a => Query a -> Query a -> Query a
34unionAll = zipOpaleyeWith (Opaleye.unionAllExplicit binaryspec)
34unionAll = zipOpaleyeWith (Opaleye.unionAllExplicit binaryspec)
35
35
36
36
37-- | Find the intersection of two queries, collapsing duplicates. @intersect a
37-- | Find the intersection of two queries, collapsing duplicates. @intersect a
38−-- b@ is the same as the SQL statement @x INTERSECT b@.
38+-- b@ is the same as the SQL statement @a INTERSECT b@.
39intersect :: EqTable a => Query a -> Query a -> Query a
39intersect :: EqTable a => Query a -> Query a -> Query a
40intersect = zipOpaleyeWith (Opaleye.intersectExplicit binaryspec)
40intersect = zipOpaleyeWith (Opaleye.intersectExplicit binaryspec)
41
41
42
42
43-- | Find the intersection of two queries, retaining duplicates. @intersectAll
43-- | Find the intersection of two queries, retaining duplicates. @intersectAll
44−-- a b@ is the same as the SQL statement @x INTERSECT ALL b@.
44+-- a b@ is the same as the SQL statement @a INTERSECT ALL b@.
45intersectAll :: EqTable a => Query a -> Query a -> Query a
45intersectAll :: EqTable a => Query a -> Query a -> Query a
46intersectAll = zipOpaleyeWith (Opaleye.intersectAllExplicit binaryspec)
46intersectAll = zipOpaleyeWith (Opaleye.intersectAllExplicit binaryspec)
47
47
48
48
49-- | Find the difference of two queries, collapsing duplicates @except a b@ is
49-- | Find the difference of two queries, collapsing duplicates @except a b@ is
50−-- the same as the SQL statement @x INTERSECT b@.
50+-- the same as the SQL statement @a EXCEPT b@.
51except :: EqTable a => Query a -> Query a -> Query a
51except :: EqTable a => Query a -> Query a -> Query a
52except = zipOpaleyeWith (Opaleye.exceptExplicit binaryspec)
52except = zipOpaleyeWith (Opaleye.exceptExplicit binaryspec)
53
53
54
54
55-- | Find the difference of two queries, retaining duplicates. @exceptAll a b@
55-- | Find the difference of two queries, retaining duplicates. @exceptAll a b@
56−-- is the same as the SQL statement @x EXCEPT ALL b@.
56+-- is the same as the SQL statement @a EXCEPT ALL b@.
57exceptAll :: EqTable a => Query a -> Query a -> Query a
57exceptAll :: EqTable a => Query a -> Query a -> Query a
58exceptAll = zipOpaleyeWith (Opaleye.exceptAllExplicit binaryspec)
58exceptAll = zipOpaleyeWith (Opaleye.exceptAllExplicit binaryspec)
src/Rel8/Query/These.hs+14−14
@@ -25,7 +25,7 @@ import qualified Opaleye.Internal.QueryArr as Opaleye
25import qualified Opaleye.Internal.Tag as Opaleye
25import qualified Opaleye.Internal.Tag as Opaleye
26
26
27-- rel8
27-- rel8
28−import Rel8.Expr ( Expr( E ) )
28+import Rel8.Expr ( Expr )
29import Rel8.Expr.Bool ( boolExpr, not_ )
29import Rel8.Expr.Bool ( boolExpr, not_ )
30import Rel8.Expr.Eq ( (==.) )
30import Rel8.Expr.Eq ( (==.) )
31import Rel8.Expr.Opaleye ( toPrimExpr, traversePrimExpr )
31import Rel8.Expr.Opaleye ( toPrimExpr, traversePrimExpr )
@@ -48,27 +48,27 @@ import Rel8.Type.Tag ( EitherTag( IsLeft, IsRight ) )
48alignBy :: ()
48alignBy :: ()
49 => (a -> b -> Expr Bool)
49 => (a -> b -> Expr Bool)
50 -> Query a -> Query b -> Query (TheseTable Expr a b)
50 -> Query a -> Query b -> Query (TheseTable Expr a b)
51−alignBy condition = zipOpaleyeWith $ \left right -> Opaleye.QueryArr $ \i -> case i of
51+alignBy condition = zipOpaleyeWith $ \left right -> Opaleye.stateQueryArr $ \_ t -> case t of
52− (_, tag) -> (tab, join', tag''')
52+ tag -> (tab, join', tag''')
53 where
53 where
54− (ma, left', tag') = Opaleye.runSimpleQueryArr (pure <$> left) ((), tag)
54+ (ma, left', tag') = Opaleye.runStateQueryArr (pure <$> left) () tag
55− (mb, right', tag'') = Opaleye.runSimpleQueryArr (pure <$> right) ((), tag')
55+ (mb, right', tag'') = Opaleye.runStateQueryArr (pure <$> right) () tag'
56− MaybeTable (E hasHere) a = ma
56+ MaybeTable hasHere a = ma
57− MaybeTable (E hasThere) b = mb
57+ MaybeTable hasThere b = mb
58 (hasHere', lbindings) = Opaleye.run $ do
58 (hasHere', lbindings) = Opaleye.run $ do
59 traversePrimExpr (Opaleye.extractAttr "hasHere" tag'') hasHere
59 traversePrimExpr (Opaleye.extractAttr "hasHere" tag'') hasHere
60 (hasThere', rbindings) = Opaleye.run $ do
60 (hasThere', rbindings) = Opaleye.run $ do
61 traversePrimExpr (Opaleye.extractAttr "hasThere" tag'') hasThere
61 traversePrimExpr (Opaleye.extractAttr "hasThere" tag'') hasThere
62 tag''' = Opaleye.next tag''
62 tag''' = Opaleye.next tag''
63− join lateral = Opaleye.Join Opaleye.FullJoin on left'' right''
63+ join = Opaleye.Join Opaleye.FullJoin on left'' right''
64 where
64 where
65 on = toPrimExpr $ condition (extract a) (extract b)
65 on = toPrimExpr $ condition (extract a) (extract b)
66− left'' = (lateral, Opaleye.Rebind True lbindings left')
66+ left'' = (Opaleye.NonLateral, Opaleye.toPrimQuery (left' <> Opaleye.aRebind lbindings))
67− right'' = (lateral, Opaleye.Rebind True rbindings right')
67+ right'' = (Opaleye.NonLateral, Opaleye.toPrimQuery (right' <> Opaleye.aRebind rbindings))
68− ma' = MaybeTable (E hasHere') a
68+ ma' = MaybeTable hasHere' a
69− mb' = MaybeTable (E hasThere') b
69+ mb' = MaybeTable hasThere' b
70 tab = TheseTable {here = ma', there = mb'}
70 tab = TheseTable {here = ma', there = mb'}
71− join' lateral input = Opaleye.times lateral input (join lateral)
71+ join' = Opaleye.aProduct join
72
72
73
73
74keepHereTable :: TheseTable Expr a b -> Query (a, MaybeTable Expr b)
74keepHereTable :: TheseTable Expr a b -> Query (a, MaybeTable Expr b)
@@ -120,7 +120,7 @@ keepThoseTable t@(TheseTable (MaybeTable _ a) (MaybeTable _ b)) = do
120loseThoseTable :: TheseTable Expr a b -> Query (EitherTable Expr a b)
120loseThoseTable :: TheseTable Expr a b -> Query (EitherTable Expr a b)
121loseThoseTable t@(TheseTable (MaybeTable _ a) (MaybeTable _ b)) = do
121loseThoseTable t@(TheseTable (MaybeTable _ a) (MaybeTable _ b)) = do
122 where_ $ not_ $ isThoseTable t
122 where_ $ not_ $ isThoseTable t
123− pure $ EitherTable (E tag) a b
123+ pure $ EitherTable tag a b
124 where
124 where
125 tag = boolExpr (litExpr IsLeft) (litExpr IsRight) (isThatTable t)
125 tag = boolExpr (litExpr IsLeft) (litExpr IsRight) (isThatTable t)
126
126
src/Rel8/Query/Window.hsnew file+26
@@ -0,0 +1,26 @@
1+module Rel8.Query.Window
2+ ( window
3+ )
4+where
5+
6+-- base
7+import Prelude ()
8+
9+-- opaleye
10+import qualified Opaleye.Window as Opaleye
11+
12+-- rel8
13+import Rel8.Query ( Query )
14+import Rel8.Query.Opaleye ( mapOpaleye )
15+import Rel8.Window ( Window( Window ) )
16+
17+
18+-- | 'window' runs a query composed of expressions containing
19+-- [window functions](https://www.postgresql.org/docs/current/tutorial-window.html).
20+-- 'window' is similar to 'Rel8.aggregate', with the main difference being
21+-- that in a window query, each input row corresponds to one output row,
22+-- whereas aggregation queries fold the entire input query down into a single
23+-- row. To put this into a Haskell context, 'Rel8.aggregate' is to 'foldl' as
24+-- 'window' is to 'scanl'.
25+window :: Window a b -> Query a -> Query b
26+window (Window a) = mapOpaleye (Opaleye.runWindows a)
src/Rel8/Schema/Context/Nullify.hs+38−44
@@ -16,28 +16,26 @@ where
16
16
17-- base
17-- base
18import Data.Bool ( bool )
18import Data.Bool ( bool )
19+import Data.Functor.Identity ( Identity( Identity ) )
19import Data.Kind ( Constraint, Type )
20import Data.Kind ( Constraint, Type )
20−import Data.Monoid ( getFirst )
21import Prelude hiding ( null )
21import Prelude hiding ( null )
22
22
23-- opaleye
23-- opaleye
24import qualified Opaleye.Internal.HaskellDB.PrimQuery as Opaleye
24import qualified Opaleye.Internal.HaskellDB.PrimQuery as Opaleye
25
25
26-- rel8
26-- rel8
27−import Rel8.Aggregate
27+import Rel8.Aggregate ( Aggregate(..), zipOutputs )
28− ( Aggregate( A, Aggregate )
29− , foldInputs, mapInputs
30− )
31−import Rel8.Expr ( Expr( E ) )
28+import Rel8.Expr ( Expr )
32import Rel8.Expr.Bool ( boolExpr )
29import Rel8.Expr.Bool ( boolExpr )
33import Rel8.Expr.Null ( nullify, unsafeUnnullify )
30import Rel8.Expr.Null ( nullify, unsafeUnnullify )
34−import Rel8.Expr.Opaleye ( fromPrimExpr, toPrimExpr )
31+import Rel8.Expr.Opaleye ( fromPrimExpr )
35import Rel8.Kind.Context ( SContext(..) )
32import Rel8.Kind.Context ( SContext(..) )
33+import Rel8.Schema.Field ( Field )
36import qualified Rel8.Schema.Kind as K
34import qualified Rel8.Schema.Kind as K
37−import Rel8.Schema.Name ( Name( N, Name ) )
35+import Rel8.Schema.Name ( Name( Name ) )
38import Rel8.Schema.Null ( Nullify, Nullity( Null, NotNull ) )
36import Rel8.Schema.Null ( Nullify, Nullity( Null, NotNull ) )
39−import Rel8.Schema.Result ( Result( R ) )
37+import Rel8.Schema.Result ( Result )
40−import Rel8.Schema.Spec ( Spec( Spec ), SSpec(..) )
38+import Rel8.Schema.Spec ( Spec(..) )
41
39
42
40
43type Nullifiability :: K.Context -> Type
41type Nullifiability :: K.Context -> Type
@@ -66,7 +64,8 @@ instance Nullifiable Name where
66
64
67type NonNullifiability :: K.Context -> Type
65type NonNullifiability :: K.Context -> Type
68data NonNullifiability context where
66data NonNullifiability context where
67+ NField :: NonNullifiability (Field table)
69− NNResult :: NonNullifiability Result
68+ NResult :: NonNullifiability Result
70
69
71
70
72nullifiableOrNot :: ()
71nullifiableOrNot :: ()
@@ -75,8 +74,9 @@ nullifiableOrNot :: ()
75nullifiableOrNot = \case
74nullifiableOrNot = \case
76 SAggregate -> Right NAggregate
75 SAggregate -> Right NAggregate
77 SExpr -> Right NExpr
76 SExpr -> Right NExpr
77+ SField -> Left NField
78 SName -> Right NName
78 SName -> Right NName
79− SResult -> Left NNResult
79+ SResult -> Left NResult
80
80
81
81
82absurd :: Nullifiability context -> NonNullifiability context -> a
82absurd :: Nullifiability context -> NonNullifiability context -> a
@@ -88,48 +88,42 @@ absurd = \case
88
88
89guarder :: ()
89guarder :: ()
90 => SContext context
90 => SContext context
91− -> context ('Spec tag)
91+ -> context tag
92 -> (tag -> Bool)
92 -> (tag -> Bool)
93 -> (Expr tag -> Expr Bool)
93 -> (Expr tag -> Expr Bool)
94− -> context ('Spec (Maybe a))
94+ -> context (Maybe a)
95− -> context ('Spec (Maybe a))
95+ -> context (Maybe a)
96+guarder = \case
96−guarder SAggregate (A tag) _ isNonNull (A (Aggregate a)) =
97+ SAggregate -> \tag _ isNonNull -> zipOutputs (sguard . isNonNull) tag
97− A $
98− mapInputs (toPrimExpr . run . fromPrimExpr) $
99− Aggregate $
100− run <$> a
101− where
102− mtag = foldInputs (\_ -> pure . fromPrimExpr) tag
103− run = maybe id (sguard . isNonNull) (getFirst mtag)
104−guarder SExpr (E tag) _ isNonNull (E a) = E $ sguard condition a
98+ SExpr -> \tag _ isNonNull -> sguard (isNonNull tag)
105− where
99+ SField -> \_ _ _ -> id
106− condition = isNonNull tag
107−guarder SName _ _ _ name = name
100+ SName -> \_ _ _ -> id
108−guarder SResult (R tag) isNonNull _ (R a) = R (bool Nothing a condition)
101+ SResult -> \(Identity tag) isNonNull _ (Identity a) ->
109− where
110− condition = isNonNull tag
102+ Identity (bool Nothing a (isNonNull tag))
111
103
112
104
113nullifier :: ()
105nullifier :: ()
114 => Nullifiability context
106 => Nullifiability context
115− -> SSpec ('Spec a)
107+ -> Spec a
116− -> context ('Spec a)
108+ -> context a
117− -> context ('Spec (Nullify a))
109+ -> context (Nullify a)
110+nullifier = \case
118−nullifier NAggregate SSpec {nullity} (A (Aggregate a)) =
111+ NAggregate -> \Spec {nullity} (Aggregate a) ->
119− A $ Aggregate $ snullify nullity <$> a
112+ Aggregate $ snullify nullity <$> a
120−nullifier NExpr SSpec {nullity} (E a) = E $ snullify nullity a
113+ NExpr -> \Spec {nullity} a -> snullify nullity a
121−nullifier NName _ (N (Name a)) = N $ Name a
114+ NName -> \_ (Name a) -> Name a
122
115
123
116
124unnullifier :: ()
117unnullifier :: ()
125 => Nullifiability context
118 => Nullifiability context
126− -> SSpec ('Spec a)
119+ -> Spec a
127− -> context ('Spec (Nullify a))
120+ -> context (Nullify a)
128− -> context ('Spec a)
121+ -> context a
122+unnullifier = \case
129−unnullifier NAggregate SSpec {nullity} (A (Aggregate a)) =
123+ NAggregate -> \Spec {nullity} (Aggregate a) ->
130− A $ Aggregate $ sunnullify nullity <$> a
124+ Aggregate $ sunnullify nullity <$> a
131−unnullifier NExpr SSpec {nullity} (E a) = E $ sunnullify nullity a
125+ NExpr -> \Spec {nullity} a -> sunnullify nullity a
132−unnullifier NName _ (N (Name a)) = N $ Name a
126+ NName -> \_ (Name a) -> Name a
133
127
134
128
135sguard :: Expr Bool -> Expr (Maybe a) -> Expr (Maybe a)
129sguard :: Expr Bool -> Expr (Maybe a) -> Expr (Maybe a)
src/Rel8/Schema/Context/Virtual.hsdeleted−70
@@ -1,70 +0,0 @@
1−{-# language EmptyCase #-}
2−{-# language DataKinds #-}
3−{-# language GADTs #-}
4−{-# language LambdaCase #-}
5−{-# language StandaloneKindSignatures #-}
6−{-# language TypeFamilies #-}
7−
8−module Rel8.Schema.Context.Virtual
9− ( Virtual, virtual
10− , Abstract(..), Concrete(..), abstractOrConcrete, absurd
11− )
12−where
13−
14−-- base
15−import Data.Kind ( Constraint, Type )
16−import Prelude
17−
18−-- rel8
19−import Rel8.Aggregate ( Aggregate )
20−import Rel8.Expr ( Expr )
21−import Rel8.Kind.Context ( SContext(..) )
22−import qualified Rel8.Schema.Kind as K
23−import Rel8.Schema.Name ( Name )
24−import Rel8.Schema.Result ( Result )
25−
26−
27−type Virtual :: K.Context -> Constraint
28−class Virtual context where
29− virtual :: Abstract context
30−
31−
32−instance Virtual Aggregate where
33− virtual = VAggregate
34−
35−
36−instance Virtual Expr where
37− virtual = VExpr
38−
39−
40−instance Virtual Name where
41− virtual = VName
42−
43−
44−type Abstract :: K.Context -> Type
45−data Abstract context where
46− VAggregate :: Abstract Aggregate
47− VExpr :: Abstract Expr
48− VName :: Abstract Name
49−
50−
51−type Concrete :: K.Context -> Type
52−data Concrete context where
53− VResult :: Concrete Result
54−
55−
56−abstractOrConcrete :: ()
57− => SContext context
58− -> Either (Concrete context) (Abstract context)
59−abstractOrConcrete = \case
60− SAggregate -> Right VAggregate
61− SExpr -> Right VExpr
62− SName -> Right VName
63− SResult -> Left VResult
64−
65−
66−absurd :: Abstract context -> Concrete context -> a
67−absurd = \case
68− VAggregate -> \case
69− VExpr -> \case
70− VName -> \case
src/Rel8/Schema/Field.hsnew file+50
@@ -0,0 +1,50 @@
1+{-# language DataKinds #-}
2+{-# language FlexibleContexts #-}
3+{-# language MultiParamTypeClasses #-}
4+{-# language StandaloneKindSignatures #-}
5+{-# language TypeFamilies #-}
6+
7+module Rel8.Schema.Field
8+ ( Field(..)
9+ , fields
10+ )
11+where
12+
13+-- base
14+import Data.Functor.Identity ( Identity( Identity ) )
15+import Data.Kind ( Type )
16+import Prelude
17+
18+-- rel8
19+import Rel8.Schema.HTable ( HField, htabulate )
20+import Rel8.Schema.HTable.Identity ( HIdentity( HIdentity ) )
21+import Rel8.Schema.Kind as K
22+import Rel8.Schema.Null ( Sql )
23+import Rel8.Table
24+ ( Table, Columns, Context, fromColumns, toColumns
25+ , FromExprs, fromResult, toResult
26+ , Transpose
27+ )
28+import Rel8.Table.Transpose ( Transposes )
29+import Rel8.Type ( DBType )
30+
31+
32+-- | A special context used in the construction of 'Rel8.Projection's.
33+type Field :: Type -> K.Context
34+newtype Field table a = Field (HField (Columns table) a)
35+
36+
37+instance Sql DBType a => Table (Field table) (Field table a) where
38+ type Columns (Field table a) = HIdentity a
39+ type Context (Field table a) = Field table
40+ type FromExprs (Field table a) = a
41+ type Transpose to (Field table a) = to a
42+
43+ toColumns = HIdentity
44+ fromColumns (HIdentity a) = a
45+ toResult a = HIdentity (Identity a)
46+ fromResult (HIdentity (Identity a)) = a
47+
48+
49+fields :: Transposes context (Field table) table fields => fields
50+fields = fromColumns $ htabulate Field
src/Rel8/Schema/HTable.hs+50−23
@@ -16,11 +16,12 @@
16module Rel8.Schema.HTable
16module Rel8.Schema.HTable
17 ( HTable (HField, HConstrainTable)
17 ( HTable (HField, HConstrainTable)
18 , hfield, htabulate, htraverse, hdicts, hspecs
18 , hfield, htabulate, htraverse, hdicts, hspecs
19− , hmap, htabulateA
19+ , hfoldMap, hmap, htabulateA, htraverseP, htraversePWithField
20 )
20 )
21where
21where
22
22
23-- base
23-- base
24+import Data.Functor.Const ( Const( Const ), getConst )
24import Data.Kind ( Constraint, Type )
25import Data.Kind ( Constraint, Type )
25import Data.Functor.Compose ( Compose( Compose ), getCompose )
26import Data.Functor.Compose ( Compose( Compose ), getCompose )
26import Data.Proxy ( Proxy )
27import Data.Proxy ( Proxy )
@@ -32,16 +33,21 @@ import GHC.Generics
32 )
33 )
33import Prelude
34import Prelude
34
35
36+-- profunctors
37+import Data.Profunctor ( rmap, Profunctor (lmap) )
38+
39+-- product-profunctors
40+import Data.Profunctor.Product ( ProductProfunctor ((****)) )
41+
35-- rel8
42-- rel8
36import Rel8.Schema.Dict ( Dict )
43import Rel8.Schema.Dict ( Dict )
37−import Rel8.Schema.Spec ( Spec, SSpec )
44+import Rel8.Schema.Spec ( Spec )
38import Rel8.Schema.HTable.Product ( HProduct( HProduct ) )
45import Rel8.Schema.HTable.Product ( HProduct( HProduct ) )
39import qualified Rel8.Schema.Kind as K
46import qualified Rel8.Schema.Kind as K
40
47
41-- semigroupoids
48-- semigroupoids
42import Data.Functor.Apply ( Apply, (<.>) )
49import Data.Functor.Apply ( Apply, (<.>) )
43
50
44−
45-- | A @HTable@ is a functor-indexed/higher-kinded data type that is
51-- | A @HTable@ is a functor-indexed/higher-kinded data type that is
46-- representable ('htabulate'/'hfield'), constrainable ('hdicts'), and
52-- representable ('htabulate'/'hfield'), constrainable ('hdicts'), and
47-- specified ('hspecs').
53-- specified ('hspecs').
@@ -50,14 +56,14 @@ import Data.Functor.Apply ( Apply, (<.>) )
50-- instances yourself or specify this constraint.
56-- instances yourself or specify this constraint.
51type HTable :: K.HTable -> Constraint
57type HTable :: K.HTable -> Constraint
52class HTable t where
58class HTable t where
53− type HField t = (field :: Spec -> Type) | field -> t
59+ type HField t = (field :: Type -> Type) | field -> t
54− type HConstrainTable t (c :: Spec -> Constraint) :: Constraint
60+ type HConstrainTable t (c :: Type -> Constraint) :: Constraint
55
61
56− hfield :: t context -> HField t spec -> context spec
62+ hfield :: t context -> HField t a -> context a
57− htabulate :: (forall spec. HField t spec -> context spec) -> t context
63+ htabulate :: (forall a. HField t a -> context a) -> t context
58− htraverse :: Apply m => (forall spec. f spec -> m (g spec)) -> t f -> m (t g)
64+ htraverse :: Apply m => (forall a. f a -> m (g a)) -> t f -> m (t g)
59 hdicts :: HConstrainTable t c => t (Dict c)
65 hdicts :: HConstrainTable t c => t (Dict c)
60− hspecs :: t SSpec
66+ hspecs :: t Spec
61
67
62 type HField t = GHField t
68 type HField t = GHField t
63 type HConstrainTable t c = HConstrainTable (GHColumns (Rep (t Proxy))) c
69 type HConstrainTable t c = HConstrainTable (GHColumns (Rep (t Proxy))) c
@@ -68,7 +74,7 @@ class HTable t where
68 , HField (GHColumns (Rep (t Proxy))) ~ HField (GHColumns (Rep (t context)))
74 , HField (GHColumns (Rep (t Proxy))) ~ HField (GHColumns (Rep (t context)))
69 , GHTable context (Rep (t context))
75 , GHTable context (Rep (t context))
70 )
76 )
71− => t context -> HField t spec -> context spec
77+ => t context -> HField t a -> context a
72 hfield table (GHField field) = hfield (toGHColumns (from table)) field
78 hfield table (GHField field) = hfield (toGHColumns (from table)) field
73
79
74 default htabulate ::
80 default htabulate ::
@@ -77,7 +83,7 @@ class HTable t where
77 , HField (GHColumns (Rep (t Proxy))) ~ HField (GHColumns (Rep (t context)))
83 , HField (GHColumns (Rep (t Proxy))) ~ HField (GHColumns (Rep (t context)))
78 , GHTable context (Rep (t context))
84 , GHTable context (Rep (t context))
79 )
85 )
80− => (forall spec. HField t spec -> context spec) -> t context
86+ => (forall a. HField t a -> context a) -> t context
81 htabulate f = to $ fromGHColumns $ htabulate (f . GHField)
87 htabulate f = to $ fromGHColumns $ htabulate (f . GHField)
82
88
83 default htraverse
89 default htraverse
@@ -87,7 +93,7 @@ class HTable t where
87 , Generic (t g), GHTable g (Rep (t g))
93 , Generic (t g), GHTable g (Rep (t g))
88 , GHColumns (Rep (t f)) ~ GHColumns (Rep (t g))
94 , GHColumns (Rep (t f)) ~ GHColumns (Rep (t g))
89 )
95 )
90− => (forall spec. f spec -> m (g spec)) -> t f -> m (t g)
96+ => (forall a. f a -> m (g a)) -> t f -> m (t g)
91 htraverse f = fmap (to . fromGHColumns) . htraverse f . toGHColumns . from
97 htraverse f = fmap (to . fromGHColumns) . htraverse f . toGHColumns . from
92
98
93 default hdicts
99 default hdicts
@@ -101,10 +107,10 @@ class HTable t where
101 hdicts = to $ fromGHColumns (hdicts @(GHColumns (Rep (t Proxy))) @c)
107 hdicts = to $ fromGHColumns (hdicts @(GHColumns (Rep (t Proxy))) @c)
102
108
103 default hspecs ::
109 default hspecs ::
104− ( Generic (t SSpec)
110+ ( Generic (t Spec)
105− , GHTable SSpec (Rep (t SSpec))
111+ , GHTable Spec (Rep (t Spec))
106 )
112 )
107− => t SSpec
113+ => t Spec
108 hspecs = to $ fromGHColumns hspecs
114 hspecs = to $ fromGHColumns hspecs
109
115
110 {-# INLINABLE hfield #-}
116 {-# INLINABLE hfield #-}
@@ -114,19 +120,40 @@ class HTable t where
114 {-# INLINABLE hspecs #-}
120 {-# INLINABLE hspecs #-}
115
121
116
122
123+hfoldMap :: (HTable t, Semigroup s)
124+ => (forall a. context a -> s) -> t context -> s
125+hfoldMap f a = getConst $ htraverse (Const . f) a
126+
127+
117hmap :: HTable t
128hmap :: HTable t
118− => (forall spec. context spec -> context' spec) -> t context -> t context'
129+ => (forall a. context a -> context' a) -> t context -> t context'
119hmap f a = htabulate $ \field -> f (hfield a field)
130hmap f a = htabulate $ \field -> f (hfield a field)
120
131
121
132
122htabulateA :: (HTable t, Apply m)
133htabulateA :: (HTable t, Apply m)
123− => (forall spec. HField t spec -> m (context spec)) -> m (t context)
134+ => (forall a. HField t a -> m (context a)) -> m (t context)
124htabulateA f = htraverse getCompose $ htabulate $ Compose . f
135htabulateA f = htraverse getCompose $ htabulate $ Compose . f
125{-# INLINABLE htabulateA #-}
136{-# INLINABLE htabulateA #-}
126
137
138+newtype ApplyP p a b = ApplyP { unApplyP :: p a b }
139+
140+instance Profunctor p => Functor (ApplyP p a) where
141+ fmap f = ApplyP . rmap f . unApplyP
142+
143+instance ProductProfunctor p => Apply (ApplyP p a) where
144+ ApplyP f <.> ApplyP x = ApplyP (rmap id f **** x)
145+
146+htraverseP :: (HTable t, ProductProfunctor p)
147+ => (forall a. p (f a) (g a)) -> p (t f) (t g)
148+htraverseP f = htraversePWithField (const f)
149+
150+htraversePWithField :: (HTable t, ProductProfunctor p)
151+ => (forall a. HField t a -> p (f a) (g a)) -> p (t f) (t g)
152+htraversePWithField f = unApplyP $ htabulateA $ \field -> ApplyP $
153+ lmap (flip hfield field) (f field)
127
154
128−type GHField :: K.HTable -> Spec -> Type
155+type GHField :: K.HTable -> Type -> Type
129−newtype GHField t spec = GHField (HField (GHColumns (Rep (t Proxy))) spec)
156+newtype GHField t a = GHField (HField (GHColumns (Rep (t Proxy))) a)
130
157
131
158
132type GHTable :: K.Context -> (Type -> Type) -> Constraint
159type GHTable :: K.Context -> (Type -> Type) -> Constraint
@@ -155,10 +182,10 @@ instance (GHTable context a, GHTable context b) => GHTable context (a :*: b) whe
155
182
156
183
157-- | A HField type for indexing into HProduct.
184-- | A HField type for indexing into HProduct.
158−type HProductField :: K.HTable -> K.HTable -> Spec -> Type
185+type HProductField :: K.HTable -> K.HTable -> Type -> Type
159−data HProductField x y spec
186+data HProductField x y a
160− = HFst (HField x spec)
187+ = HFst (HField x a)
161− | HSnd (HField y spec)
188+ | HSnd (HField y a)
162
189
163
190
164instance (HTable x, HTable y) => HTable (HProduct x y) where
191instance (HTable x, HTable y) => HTable (HProduct x y) where
src/Rel8/Schema/HTable/Either.hs+2−2
@@ -15,7 +15,7 @@ import Prelude ()
15
15
16-- rel8
16-- rel8
17import Rel8.Schema.HTable ( HTable )
17import Rel8.Schema.HTable ( HTable )
18−import Rel8.Schema.HTable.Identity ( HType )
18+import Rel8.Schema.HTable.Identity ( HIdentity )
19import Rel8.Schema.HTable.Label ( HLabel )
19import Rel8.Schema.HTable.Label ( HLabel )
20import Rel8.Schema.HTable.Nullify ( HNullify )
20import Rel8.Schema.HTable.Nullify ( HNullify )
21import qualified Rel8.Schema.Kind as K
21import qualified Rel8.Schema.Kind as K
@@ -24,7 +24,7 @@ import Rel8.Type.Tag ( EitherTag )
24
24
25type HEitherTable :: K.HTable -> K.HTable -> K.HTable
25type HEitherTable :: K.HTable -> K.HTable -> K.HTable
26data HEitherTable left right context = HEitherTable
26data HEitherTable left right context = HEitherTable
27− { htag :: HLabel "isRight" (HType EitherTag) context
27+ { htag :: HLabel "isRight" (HIdentity EitherTag) context
28 , hleft :: HLabel "Left" (HNullify left) context
28 , hleft :: HLabel "Left" (HNullify left) context
29 , hright :: HLabel "Right" (HNullify right) context
29 , hright :: HLabel "Right" (HNullify right) context
30 }
30 }
src/Rel8/Schema/HTable/Identity.hs+16−28
@@ -1,17 +1,17 @@
1{-# language DataKinds #-}
1{-# language DataKinds #-}
2−{-# language GADTs #-}
2+{-# language FlexibleContexts #-}
3−{-# language PatternSynonyms #-}
4{-# language StandaloneKindSignatures #-}
3{-# language StandaloneKindSignatures #-}
5{-# language TypeFamilies #-}
4{-# language TypeFamilies #-}
5+{-# language UndecidableInstances #-}
6
6
7module Rel8.Schema.HTable.Identity
7module Rel8.Schema.HTable.Identity
8− ( HIdentity( HIdentity, HType, unHIdentity )
8+ ( HIdentity( HIdentity, unHIdentity )
9− , HType
10 )
9 )
11where
10where
12
11
13-- base
12-- base
14import Data.Kind ( Type )
13import Data.Kind ( Type )
14+import Data.Type.Equality ( (:~:)( Refl ) )
15import Prelude
15import Prelude
16
16
17-- rel8
17-- rel8
@@ -21,35 +21,23 @@ import Rel8.Schema.HTable
21 , hfield, htabulate, htraverse, hdicts, hspecs
21 , hfield, htabulate, htraverse, hdicts, hspecs
22 )
22 )
23import qualified Rel8.Schema.Kind as K
23import qualified Rel8.Schema.Kind as K
24−import Rel8.Schema.Spec ( Spec( Spec ), KnownSpec, specSing )
24+import Rel8.Schema.Null ( Sql )
25+import Rel8.Schema.Spec ( specification )
26+import Rel8.Type ( DBType )
25
27
26
28
27−type HType :: Type -> K.HTable
29+type HIdentity :: Type -> K.HTable
28−type HType a = HIdentity ('Spec a)
29−
30−
31−pattern HType :: context ('Spec a) -> HType a context
32−pattern HType a = HIdentity a
33−{-# COMPLETE HType #-}
34−
35−
36−type HIdentity :: Spec -> K.HTable
37−newtype HIdentity spec context = HIdentity
30+newtype HIdentity a context = HIdentity
38− { unHIdentity :: context spec
31+ { unHIdentity :: context a
39 }
32 }
40
33
41
34
42−type HIdentityField :: Spec -> Spec -> Type
43−data HIdentityField _spec spec where
44− HIdentityField :: HIdentityField spec spec
45−
46−
47−instance KnownSpec spec => HTable (HIdentity spec) where
35+instance Sql DBType a => HTable (HIdentity a) where
48− type HConstrainTable (HIdentity spec) c = c spec
36+ type HConstrainTable (HIdentity a) constraint = constraint a
49− type HField (HIdentity spec) = HIdentityField spec
37+ type HField (HIdentity a) = (:~:) a
50
38
51− hfield (HIdentity a) HIdentityField = a
39+ hfield (HIdentity a) Refl = a
52− htabulate f = HIdentity $ f HIdentityField
40+ htabulate f = HIdentity $ f Refl
53 htraverse f (HIdentity a) = HIdentity <$> f a
41 htraverse f (HIdentity a) = HIdentity <$> f a
54 hdicts = HIdentity Dict
42 hdicts = HIdentity Dict
55− hspecs = HIdentity specSing
43+ hspecs = HIdentity specification
src/Rel8/Schema/HTable/Label.hs+15−4
@@ -1,4 +1,5 @@
1{-# language DataKinds #-}
1{-# language DataKinds #-}
2+{-# language RankNTypes #-}
2{-# language RecordWildCards #-}
3{-# language RecordWildCards #-}
3{-# language ScopedTypeVariables #-}
4{-# language ScopedTypeVariables #-}
4{-# language StandaloneKindSignatures #-}
5{-# language StandaloneKindSignatures #-}
@@ -7,6 +8,7 @@
7
8
8module Rel8.Schema.HTable.Label
9module Rel8.Schema.HTable.Label
9 ( HLabel, hlabel, hrelabel, hunlabel
10 ( HLabel, hlabel, hrelabel, hunlabel
11+ , hproject
10 )
12 )
11where
13where
12
14
@@ -18,16 +20,19 @@ import Prelude
18
20
19-- rel8
21-- rel8
20import Rel8.Schema.HTable
22import Rel8.Schema.HTable
23+ ( HTable, HConstrainTable, HField
24+ , htabulate, hfield, htraverse, hdicts, hspecs
25+ )
21import qualified Rel8.Schema.Kind as K
26import qualified Rel8.Schema.Kind as K
22−import Rel8.Schema.Spec ( Spec, SSpec(..) )
27+import Rel8.Schema.Spec ( Spec(..) )
23
28
24
29
25type HLabel :: Symbol -> K.HTable -> K.HTable
30type HLabel :: Symbol -> K.HTable -> K.HTable
26newtype HLabel label table context = HLabel (table context)
31newtype HLabel label table context = HLabel (table context)
27
32
28
33
29−type HLabelField :: Symbol -> K.HTable -> Spec -> Type
34+type HLabelField :: Symbol -> K.HTable -> Type -> Type
30−newtype HLabelField label table spec = HLabelField (HField table spec)
35+newtype HLabelField label table a = HLabelField (HField table a)
31
36
32
37
33instance (HTable table, KnownSymbol label) => HTable (HLabel label table) where
38instance (HTable table, KnownSymbol label) => HTable (HLabel label table) where
@@ -40,7 +45,7 @@ instance (HTable table, KnownSymbol label) => HTable (HLabel label table) where
40 htraverse f (HLabel a) = HLabel <$> htraverse f a
45 htraverse f (HLabel a) = HLabel <$> htraverse f a
41 hdicts = HLabel (hdicts @table)
46 hdicts = HLabel (hdicts @table)
42 hspecs = HLabel $ htabulate $ \field -> case hfield (hspecs @table) field of
47 hspecs = HLabel $ htabulate $ \field -> case hfield (hspecs @table) field of
43− SSpec {..} -> SSpec {labels = symbolVal (Proxy @label) : labels, ..}
48+ Spec {..} -> Spec {labels = symbolVal (Proxy @label) : labels, ..}
44 {-# INLINABLE hspecs #-}
49 {-# INLINABLE hspecs #-}
45
50
46
51
@@ -57,3 +62,9 @@ hrelabel = hlabel . hunlabel
57hunlabel :: forall label t context. HLabel label t context -> t context
62hunlabel :: forall label t context. HLabel label t context -> t context
58hunlabel (HLabel a) = a
63hunlabel (HLabel a) = a
59{-# INLINABLE hunlabel #-}
64{-# INLINABLE hunlabel #-}
65+
66+
67+hproject :: ()
68+ => (forall ctx. t ctx -> t' ctx)
69+ -> HLabel label t context -> HLabel label t' context
70+hproject f (HLabel a) = HLabel (f a)
src/Rel8/Schema/HTable/MapTable.hs+22−12
@@ -6,7 +6,7 @@
6{-# language GADTs #-}
6{-# language GADTs #-}
7{-# language InstanceSigs #-}
7{-# language InstanceSigs #-}
8{-# language MultiParamTypeClasses #-}
8{-# language MultiParamTypeClasses #-}
9−{-# language PolyKinds #-}
9+{-# language RankNTypes #-}
10{-# language ScopedTypeVariables #-}
10{-# language ScopedTypeVariables #-}
11{-# language StandaloneKindSignatures #-}
11{-# language StandaloneKindSignatures #-}
12{-# language TypeApplications #-}
12{-# language TypeApplications #-}
@@ -19,34 +19,38 @@ module Rel8.Schema.HTable.MapTable
19 , MapSpec(..)
19 , MapSpec(..)
20 , Precompose(..)
20 , Precompose(..)
21 , HMapTableField(..)
21 , HMapTableField(..)
22+ , hproject
22 )
23 )
23where
24where
24
25
25-- base
26-- base
26import Data.Kind ( Constraint, Type )
27import Data.Kind ( Constraint, Type )
27−import Prelude ( ($), (.), (<$>), fmap )
28+import Prelude
28
29
29-- rel8
30-- rel8
30−import Rel8.FCF
31+import Rel8.FCF ( Exp, Eval )
31import Rel8.Schema.HTable
32import Rel8.Schema.HTable
33+ ( HTable, HConstrainTable, HField
34+ , hfield, htabulate, htraverse, hdicts, hspecs
35+ )
32−import Rel8.Schema.Spec ( Spec, SSpec )
36+import Rel8.Schema.Spec ( Spec )
33import qualified Rel8.Schema.Kind as K
37import qualified Rel8.Schema.Kind as K
34import Rel8.Schema.Dict ( Dict( Dict ) )
38import Rel8.Schema.Dict ( Dict( Dict ) )
35
39
36
40
37−type HMapTable :: (a -> Exp b) -> ((a -> Type) -> Type) -> (b -> Type) -> Type
41+type HMapTable :: (Type -> Exp Type) -> K.HTable -> K.HTable
38−newtype HMapTable f t g = HMapTable
42+newtype HMapTable f t context = HMapTable
39− { unHMapTable :: t (Precompose f g)
43+ { unHMapTable :: t (Precompose f context)
40 }
44 }
41
45
42
46
43−type Precompose :: (a -> Exp b) -> (b -> Type) -> a -> Type
47+type Precompose :: (Type -> Exp Type) -> K.Context -> K.Context
44newtype Precompose f g x = Precompose
48newtype Precompose f g x = Precompose
45 { precomposed :: g (Eval (f x))
49 { precomposed :: g (Eval (f x))
46 }
50 }
47
51
48
52
49−type HMapTableField :: (Spec -> Exp a) -> K.HTable -> a -> Type
53+type HMapTableField :: (Type -> Exp Type) -> K.HTable -> K.Context
50data HMapTableField f t x where
54data HMapTableField f t x where
51 HMapTableField :: HField t a -> HMapTableField f t (Eval (f a))
55 HMapTableField :: HField t a -> HMapTableField f t (Eval (f a))
52
56
@@ -79,11 +83,17 @@ instance (HTable t, MapSpec f) => HTable (HMapTable f t) where
79 {-# INLINABLE hspecs #-}
83 {-# INLINABLE hspecs #-}
80
84
81
85
82−type MapSpec :: (Spec -> Exp Spec) -> Constraint
86+type MapSpec :: (Type -> Exp Type) -> Constraint
83class MapSpec f where
87class MapSpec f where
84− mapInfo :: SSpec x -> SSpec (Eval (f x))
88+ mapInfo :: Spec x -> Spec (Eval (f x))
85
89
86
90
87−type ComposeConstraint :: (a -> Exp b) -> (b -> Constraint) -> a -> Constraint
91+type ComposeConstraint :: (Type -> Exp Type) -> (Type -> Constraint) -> Type -> Constraint
88class c (Eval (f a)) => ComposeConstraint f c a
92class c (Eval (f a)) => ComposeConstraint f c a
89instance c (Eval (f a)) => ComposeConstraint f c a
93instance c (Eval (f a)) => ComposeConstraint f c a
94+
95+
96+hproject :: ()
97+ => (forall ctx. t ctx -> t' ctx)
98+ -> HMapTable f t context -> HMapTable f t' context
99+hproject f (HMapTable a) = HMapTable (f a)
src/Rel8/Schema/HTable/Maybe.hs+2−2
@@ -15,7 +15,7 @@ import Prelude
15
15
16-- rel8
16-- rel8
17import Rel8.Schema.HTable ( HTable )
17import Rel8.Schema.HTable ( HTable )
18−import Rel8.Schema.HTable.Identity ( HType )
18+import Rel8.Schema.HTable.Identity ( HIdentity )
19import Rel8.Schema.HTable.Label ( HLabel )
19import Rel8.Schema.HTable.Label ( HLabel )
20import Rel8.Schema.HTable.Nullify ( HNullify )
20import Rel8.Schema.HTable.Nullify ( HNullify )
21import qualified Rel8.Schema.Kind as K
21import qualified Rel8.Schema.Kind as K
@@ -24,7 +24,7 @@ import Rel8.Type.Tag ( MaybeTag )
24
24
25type HMaybeTable :: K.HTable -> K.HTable
25type HMaybeTable :: K.HTable -> K.HTable
26data HMaybeTable table context = HMaybeTable
26data HMaybeTable table context = HMaybeTable
27− { htag :: HLabel "isJust" (HType (Maybe MaybeTag)) context
27+ { htag :: HLabel "isJust" (HIdentity (Maybe MaybeTag)) context
28 , hjust :: HLabel "Just" (HNullify table) context
28 , hjust :: HLabel "Just" (HNullify table) context
29 }
29 }
30 deriving stock Generic
30 deriving stock Generic
src/Rel8/Schema/HTable/Nullify.hs+22−24
@@ -23,10 +23,12 @@ module Rel8.Schema.HTable.Nullify
23 , hnulls
23 , hnulls
24 , hnullify
24 , hnullify
25 , hunnullify
25 , hunnullify
26+ , hproject
26 )
27 )
27where
28where
28
29
29-- base
30-- base
31+import Data.Kind ( Type )
30import GHC.Generics ( Generic )
32import GHC.Generics ( Generic )
31import Prelude hiding ( null )
33import Prelude hiding ( null )
32
34
@@ -37,10 +39,11 @@ import Rel8.Schema.HTable.MapTable
37 ( HMapTable, HMapTableField( HMapTableField )
39 ( HMapTable, HMapTableField( HMapTableField )
38 , MapSpec, mapInfo
40 , MapSpec, mapInfo
39 )
41 )
42+import qualified Rel8.Schema.HTable.MapTable as HMapTable ( hproject )
40import qualified Rel8.Schema.Kind as K
43import qualified Rel8.Schema.Kind as K
41import Rel8.Schema.Null ( Nullity( Null, NotNull ) )
44import Rel8.Schema.Null ( Nullity( Null, NotNull ) )
42import qualified Rel8.Schema.Null as Type ( Nullify )
45import qualified Rel8.Schema.Null as Type ( Nullify )
43−import Rel8.Schema.Spec ( Spec( Spec ), SSpec(..) )
46+import Rel8.Schema.Spec ( Spec(..) )
44
47
45-- semigroupoids
48-- semigroupoids
46import Data.Functor.Apply ( Apply )
49import Data.Functor.Apply ( Apply )
@@ -52,17 +55,14 @@ newtype HNullify table context = HNullify (HMapTable Nullify table context)
52 deriving anyclass HTable
55 deriving anyclass HTable
53
56
54
57
55−-- | Transform a 'Spec' by allowing it to be @null@.
58+-- | Transform a 'Type' by allowing it to be @null@.
56−data Nullify :: Spec -> Exp Spec
59+data Nullify :: Type -> Exp Type
57−
58−
59−type instance Eval (Nullify ('Spec a)) =
60+type instance Eval (Nullify a) = Type.Nullify a
60− 'Spec (Type.Nullify a)
61
61
62
62
63instance MapSpec Nullify where
63instance MapSpec Nullify where
64 mapInfo = \case
64 mapInfo = \case
65− SSpec {nullity, ..} -> SSpec
65+ Spec {nullity, ..} -> Spec
66 { nullity = case nullity of
66 { nullity = case nullity of
67 Null -> Null
67 Null -> Null
68 NotNull -> Null
68 NotNull -> Null
@@ -71,49 +71,47 @@ instance MapSpec Nullify where
71
71
72
72
73hguard :: HTable t
73hguard :: HTable t
74− => (forall a. context ('Spec (Maybe a)) -> context ('Spec (Maybe a)))
74+ => (forall a. context (Maybe a) -> context (Maybe a))
75 -> HNullify t context -> HNullify t context
75 -> HNullify t context -> HNullify t context
76hguard guarder (HNullify as) = HNullify $ htabulate $ \(HMapTableField field) ->
76hguard guarder (HNullify as) = HNullify $ htabulate $ \(HMapTableField field) ->
77 case hfield hspecs field of
77 case hfield hspecs field of
78− SSpec {nullity} -> case hfield as (HMapTableField field) of
78+ Spec {nullity} -> case hfield as (HMapTableField field) of
79 a -> case nullity of
79 a -> case nullity of
80 Null -> guarder a
80 Null -> guarder a
81 NotNull -> guarder a
81 NotNull -> guarder a
82
82
83
83
84hnulls :: HTable t
84hnulls :: HTable t
85− => (forall a. ()
86− => SSpec ('Spec a)
87− -> context ('Spec (Type.Nullify a)))
85+ => (forall a. Spec a -> context (Type.Nullify a))
88 -> HNullify t context
86 -> HNullify t context
89hnulls null = HNullify $ htabulate $ \(HMapTableField field) ->
87hnulls null = HNullify $ htabulate $ \(HMapTableField field) ->
90 case hfield hspecs field of
88 case hfield hspecs field of
91− spec@SSpec {} -> null spec
89+ spec@Spec {} -> null spec
92{-# INLINABLE hnulls #-}
90{-# INLINABLE hnulls #-}
93
91
94
92
95hnullify :: HTable t
93hnullify :: HTable t
96− => (forall a. ()
97− => SSpec ('Spec a)
98− -> context ('Spec a)
99− -> context ('Spec (Type.Nullify a)))
94+ => (forall a. Spec a -> context a -> context (Type.Nullify a))
100 -> t context
95 -> t context
101 -> HNullify t context
96 -> HNullify t context
102hnullify nullifier a = HNullify $ htabulate $ \(HMapTableField field) ->
97hnullify nullifier a = HNullify $ htabulate $ \(HMapTableField field) ->
103 case hfield hspecs field of
98 case hfield hspecs field of
104− spec@SSpec {} -> nullifier spec (hfield a field)
99+ spec@Spec {} -> nullifier spec (hfield a field)
105{-# INLINABLE hnullify #-}
100{-# INLINABLE hnullify #-}
106
101
107
102
108hunnullify :: (HTable t, Apply m)
103hunnullify :: (HTable t, Apply m)
109− => (forall a. ()
110− => SSpec ('Spec a)
111− -> context ('Spec (Type.Nullify a))
104+ => (forall a. Spec a -> context (Type.Nullify a) -> m (context a))
112− -> m (context ('Spec a)))
113 -> HNullify t context
105 -> HNullify t context
114 -> m (t context)
106 -> m (t context)
115hunnullify unnullifier (HNullify as) =
107hunnullify unnullifier (HNullify as) =
116 htabulateA $ \field -> case hfield hspecs field of
108 htabulateA $ \field -> case hfield hspecs field of
117− spec@SSpec {} -> case hfield as (HMapTableField field) of
109+ spec@Spec {} -> case hfield as (HMapTableField field) of
118 a -> unnullifier spec a
110 a -> unnullifier spec a
119{-# INLINABLE hunnullify #-}
111{-# INLINABLE hunnullify #-}
112+
113+
114+hproject :: ()
115+ => (forall ctx. t ctx -> t' ctx)
116+ -> HNullify t context -> HNullify t' context
117+hproject f (HNullify a) = HNullify (HMapTable.hproject f a)
src/Rel8/Schema/HTable/These.hs+3−3
@@ -15,7 +15,7 @@ import Prelude
15
15
16-- rel8
16-- rel8
17import Rel8.Schema.HTable ( HTable )
17import Rel8.Schema.HTable ( HTable )
18−import Rel8.Schema.HTable.Identity ( HType )
18+import Rel8.Schema.HTable.Identity ( HIdentity )
19import Rel8.Schema.HTable.Label ( HLabel )
19import Rel8.Schema.HTable.Label ( HLabel )
20import Rel8.Schema.HTable.Nullify ( HNullify )
20import Rel8.Schema.HTable.Nullify ( HNullify )
21import qualified Rel8.Schema.Kind as K
21import qualified Rel8.Schema.Kind as K
@@ -24,9 +24,9 @@ import Rel8.Type.Tag ( MaybeTag )
24
24
25type HTheseTable :: K.HTable -> K.HTable -> K.HTable
25type HTheseTable :: K.HTable -> K.HTable -> K.HTable
26data HTheseTable here there context = HTheseTable
26data HTheseTable here there context = HTheseTable
27− { hhereTag :: HLabel "hereTag" (HType (Maybe MaybeTag)) context
27+ { hhereTag :: HLabel "hereTag" (HIdentity (Maybe MaybeTag)) context
28 , hhere :: HLabel "Here" (HNullify here) context
28 , hhere :: HLabel "Here" (HNullify here) context
29− , hthereTag :: HLabel "thereTag" (HType (Maybe MaybeTag)) context
29+ , hthereTag :: HLabel "thereTag" (HIdentity (Maybe MaybeTag)) context
30 , hthere :: HLabel "There" (HNullify there) context
30 , hthere :: HLabel "There" (HNullify there) context
31 }
31 }
32 deriving stock Generic
32 deriving stock Generic
src/Rel8/Schema/HTable/Vectorize.hs+39−40
@@ -9,7 +9,6 @@
9{-# language GADTs #-}
9{-# language GADTs #-}
10{-# language LambdaCase #-}
10{-# language LambdaCase #-}
11{-# language MultiParamTypeClasses #-}
11{-# language MultiParamTypeClasses #-}
12−{-# language NamedFieldPuns #-}
13{-# language RankNTypes #-}
12{-# language RankNTypes #-}
14{-# language RecordWildCards #-}
13{-# language RecordWildCards #-}
15{-# language ScopedTypeVariables #-}
14{-# language ScopedTypeVariables #-}
@@ -22,33 +21,39 @@ module Rel8.Schema.HTable.Vectorize
22 ( HVectorize
21 ( HVectorize
23 , hvectorize, hunvectorize
22 , hvectorize, hunvectorize
24 , happend, hempty
23 , happend, hempty
24+ , hproject
25+ , hcolumn
25 )
26 )
26where
27where
27
28
28-- base
29-- base
29−import Data.Kind ( Type )
30+import Data.Kind ( Constraint, Type )
30import Data.List.NonEmpty ( NonEmpty )
31import Data.List.NonEmpty ( NonEmpty )
32+import GHC.Generics (Generic)
31import Prelude
33import Prelude
32
34
33-- rel8
35-- rel8
36+import Rel8.FCF ( Eval, Exp )
34import Rel8.Schema.Dict ( Dict( Dict ) )
37import Rel8.Schema.Dict ( Dict( Dict ) )
35import qualified Rel8.Schema.Kind as K
38import qualified Rel8.Schema.Kind as K
36−import Rel8.Schema.HTable
37− ( HTable
38− , hfield, htabulate, htabulateA, hspecs
39+import Rel8.Schema.HTable ( HTable, hfield, htabulate, htabulateA, hspecs )
40+import Rel8.Schema.HTable.Identity ( HIdentity( HIdentity ) )
41+import Rel8.Schema.HTable.MapTable
42+ ( HMapTable( HMapTable ), HMapTableField( HMapTableField )
43+ , MapSpec, mapInfo
44+ , Precompose( Precompose )
39 )
45 )
46+import qualified Rel8.Schema.HTable.MapTable as HMapTable ( hproject )
40import Rel8.Schema.Null ( Unnullify, NotNull, Nullity( NotNull ) )
47import Rel8.Schema.Null ( Unnullify, NotNull, Nullity( NotNull ) )
41−import Rel8.Schema.Spec ( Spec( Spec ), SSpec(..) )
48+import Rel8.Schema.Spec ( Spec(..) )
42import Rel8.Type.Array ( listTypeInformation, nonEmptyTypeInformation )
49import Rel8.Type.Array ( listTypeInformation, nonEmptyTypeInformation )
43import Rel8.Type.Information ( TypeInformation )
50import Rel8.Type.Information ( TypeInformation )
44
51
45-- semialign
52-- semialign
46import Data.Zip ( Unzip, Zip, Zippy(..) )
53import Data.Zip ( Unzip, Zip, Zippy(..) )
47−import Rel8.FCF
48−import Rel8.Schema.HTable.MapTable
49−import GHC.Generics (Generic)
50
54
51
55
56+type Vector :: (Type -> Type) -> Constraint
52class Vector list where
57class Vector list where
53 listNotNull :: proxy a -> Dict NotNull (list a)
58 listNotNull :: proxy a -> Dict NotNull (list a)
54 vectorTypeInformation :: ()
59 vectorTypeInformation :: ()
@@ -73,16 +78,16 @@ newtype HVectorize list table context = HVectorize (HMapTable (Vectorize list) t
73 deriving anyclass HTable
78 deriving anyclass HTable
74
79
75
80
76−data Vectorize :: (Type -> Type) -> Spec -> Exp Spec
81+data Vectorize :: (Type -> Type) -> Type -> Exp Type
77
82
78
83
79−type instance Eval (Vectorize list ('Spec a)) = 'Spec (list a)
84+type instance Eval (Vectorize list a) = list a
80
85
81
86
82instance Vector list => MapSpec (Vectorize list) where
87instance Vector list => MapSpec (Vectorize list) where
83 mapInfo = \case
88 mapInfo = \case
84− SSpec {..} -> case listNotNull @list nullity of
89+ Spec {..} -> case listNotNull @list nullity of
85− Dict -> SSpec
90+ Dict -> Spec
86 { nullity = NotNull
91 { nullity = NotNull
87 , info = vectorTypeInformation nullity info
92 , info = vectorTypeInformation nullity info
88 , ..
93 , ..
@@ -90,55 +95,49 @@ instance Vector list => MapSpec (Vectorize list) where
90
95
91
96
92hvectorize :: (HTable t, Unzip f, Vector list)
97hvectorize :: (HTable t, Unzip f, Vector list)
93− => (forall a. ()
94− => SSpec ('Spec a)
95− -> f (context ('Spec a))
96− -> context' ('Spec (list a)))
98+ => (forall a. Spec a -> f (context a) -> context' (list a))
97 -> f (t context)
99 -> f (t context)
98 -> HVectorize list t context'
100 -> HVectorize list t context'
99hvectorize vectorizer as = HVectorize $ htabulate $ \(HMapTableField field) ->
101hvectorize vectorizer as = HVectorize $ htabulate $ \(HMapTableField field) ->
100 case hfield hspecs field of
102 case hfield hspecs field of
101− spec@SSpec {} -> vectorizer spec (fmap (`hfield` field) as)
103+ spec -> vectorizer spec (fmap (`hfield` field) as)
102{-# INLINABLE hvectorize #-}
104{-# INLINABLE hvectorize #-}
103
105
104
106
105hunvectorize :: (HTable t, Zip f, Vector list)
107hunvectorize :: (HTable t, Zip f, Vector list)
106− => (forall a. ()
107− => SSpec ('Spec a)
108− -> context ('Spec (list a))
108+ => (forall a. Spec a -> context (list a) -> f (context' a))
109− -> f (context' ('Spec a)))
110 -> HVectorize list t context
109 -> HVectorize list t context
111 -> f (t context')
110 -> f (t context')
112hunvectorize unvectorizer (HVectorize table) =
111hunvectorize unvectorizer (HVectorize table) =
113 getZippy $ htabulateA $ \field -> case hfield hspecs field of
112 getZippy $ htabulateA $ \field -> case hfield hspecs field of
114− spec@SSpec{} -> case hfield table (HMapTableField field) of
113+ spec -> case hfield table (HMapTableField field) of
115 a -> Zippy (unvectorizer spec a)
114 a -> Zippy (unvectorizer spec a)
116{-# INLINABLE hunvectorize #-}
115{-# INLINABLE hunvectorize #-}
117
116
118
117
119−happend :: (HTable t, Vector list) =>
118+happend :: (HTable t, Vector list)
120− ( forall a. ()
119+ => (forall a. Spec a -> context (list a) -> context (list a) -> context (list a))
121− => Nullity a
122− -> TypeInformation (Unnullify a)
123− -> context ('Spec (list a))
124− -> context ('Spec (list a))
125− -> context ('Spec (list a))
126− )
127 -> HVectorize list t context
120 -> HVectorize list t context
128 -> HVectorize list t context
121 -> HVectorize list t context
129 -> HVectorize list t context
122 -> HVectorize list t context
130happend append (HVectorize as) (HVectorize bs) = HVectorize $
123happend append (HVectorize as) (HVectorize bs) = HVectorize $
131 htabulate $ \field@(HMapTableField j) -> case (hfield as field, hfield bs field) of
124 htabulate $ \field@(HMapTableField j) -> case (hfield as field, hfield bs field) of
132 (a, b) -> case hfield hspecs j of
125 (a, b) -> case hfield hspecs j of
133− SSpec {nullity, info} -> append nullity info a b
126+ spec -> append spec a b
134
127
135
128
136−hempty :: HTable t =>
129+hempty :: HTable t
137− ( forall a. ()
130+ => (forall a. Spec a -> context [a])
138− => Nullity a
139− -> TypeInformation (Unnullify a)
140− -> context ('Spec [a])
141− )
142 -> HVectorize [] t context
131 -> HVectorize [] t context
143−hempty empty = HVectorize $ htabulate $ \(HMapTableField field) -> case hfield hspecs field of
132+hempty empty = HVectorize $ htabulate $ \(HMapTableField field) ->
144− SSpec {nullity, info} -> empty nullity info
133+ empty (hfield hspecs field)
134+
135+
136+hproject :: ()
137+ => (forall ctx. t ctx -> t' ctx)
138+ -> HVectorize list t context -> HVectorize list t' context
139+hproject f (HVectorize a) = HVectorize (HMapTable.hproject f a)
140+
141+
142+hcolumn :: HVectorize list (HIdentity a) context -> context (list a)
143+hcolumn (HVectorize (HMapTable (HIdentity (Precompose a)))) = a
src/Rel8/Schema/Kind.hs+7−5
@@ -1,17 +1,19 @@
1{-# language StandaloneKindSignatures #-}
1{-# language StandaloneKindSignatures #-}
2
2
3−module Rel8.Schema.Kind ( Rel8able, Context, HTable ) where
3+module Rel8.Schema.Kind
4+ ( Rel8able
5+ , Context
6+ , HTable
7+ )
8+where
4
9
5-- base
10-- base
6import Data.Kind ( Type )
11import Data.Kind ( Type )
7import Prelude ()
12import Prelude ()
8
13
9−-- rel8
10−import Rel8.Schema.Spec ( Spec )
11−
12
14
13type Context :: Type
15type Context :: Type
14−type Context = Spec -> Type
16+type Context = Type -> Type
15
17
16
18
17type HTable :: Type
19type HTable :: Type
src/Rel8/Schema/Name.hs+31−35
@@ -3,37 +3,44 @@
3{-# language FlexibleContexts #-}
3{-# language FlexibleContexts #-}
4{-# language FlexibleInstances #-}
4{-# language FlexibleInstances #-}
5{-# language GADTs #-}
5{-# language GADTs #-}
6+{-# language GeneralizedNewtypeDeriving #-}
6{-# language MultiParamTypeClasses #-}
7{-# language MultiParamTypeClasses #-}
7−{-# language PolyKinds #-}
8{-# language RankNTypes #-}
8{-# language RankNTypes #-}
9−{-# language StandaloneDeriving #-}
10{-# language StandaloneKindSignatures #-}
9{-# language StandaloneKindSignatures #-}
11{-# language TypeFamilies #-}
10{-# language TypeFamilies #-}
12{-# language UndecidableInstances #-}
11{-# language UndecidableInstances #-}
13−{-# language UndecidableSuperClasses #-}
14
12
15module Rel8.Schema.Name
13module Rel8.Schema.Name
16 ( Name(..)
14 ( Name(..)
17 , Selects
15 , Selects
16+ , ppColumn
18 )
17 )
19where
18where
20
19
21-- base
20-- base
21+import Data.Functor.Identity ( Identity( Identity ) )
22import Data.Kind ( Constraint, Type )
22import Data.Kind ( Constraint, Type )
23−import Data.String ( IsString, fromString )
23+import Data.String ( IsString )
24import Prelude
24import Prelude
25
25
26+-- opaleye
27+import qualified Opaleye.Internal.HaskellDB.Sql as Opaleye
28+import qualified Opaleye.Internal.HaskellDB.Sql.Print as Opaleye
29+
30+-- pretty
31+import Text.PrettyPrint ( Doc )
32+
26-- rel8
33-- rel8
27import Rel8.Expr ( Expr )
34import Rel8.Expr ( Expr )
35+import qualified Rel8.Schema.Kind as K
28−import Rel8.Schema.HTable.Identity ( HIdentity( HType ), HType )
36+import Rel8.Schema.HTable.Identity ( HIdentity( HIdentity ) )
29import Rel8.Schema.Null ( Sql )
37import Rel8.Schema.Null ( Sql )
30−import Rel8.Schema.Result ( Result( R ) )
31−import Rel8.Schema.Spec ( Spec( Spec ) )
32import Rel8.Table
38import Rel8.Table
33 ( Table, Columns, Context, fromColumns, toColumns
39 ( Table, Columns, Context, fromColumns, toColumns
34 , FromExprs, fromResult, toResult
40 , FromExprs, fromResult, toResult
41+ , Transpose
35 )
42 )
36−import Rel8.Table.Recontextualize ( Recontextualize )
43+import Rel8.Table.Transpose ( Transposes )
37import Rel8.Type ( DBType )
44import Rel8.Type ( DBType )
38
45
39
46
@@ -41,41 +48,30 @@ import Rel8.Type ( DBType )
41-- schema definition. You can construct names by using the @OverloadedStrings@
48-- schema definition. You can construct names by using the @OverloadedStrings@
42-- extension and writing string literals. This is typically done when providing
49-- extension and writing string literals. This is typically done when providing
43-- a 'TableSchema' value.
50-- a 'TableSchema' value.
44−type Name :: k -> Type
51+type Name :: K.Context
45−data Name a where
52+newtype Name a = Name String
46− Name :: forall (a :: Type). !String -> Name a
47− N :: { unN :: !(Name a) } -> Name ('Spec a)
48−
49−
50−deriving stock instance Show (Name a)
53+ deriving stock Show
51−
54+ deriving newtype IsString
52−
53−instance k ~ Type => IsString (Name (a :: k)) where
54− fromString = Name
55
55
56
56
57instance Sql DBType a => Table Name (Name a) where
57instance Sql DBType a => Table Name (Name a) where
58− type Columns (Name a) = HType a
58+ type Columns (Name a) = HIdentity a
59 type Context (Name a) = Name
59 type Context (Name a) = Name
60 type FromExprs (Name a) = a
60 type FromExprs (Name a) = a
61+ type Transpose to (Name a) = to a
61
62
62− toColumns a = HType (N a)
63+ toColumns a = HIdentity a
63− fromColumns (HType (N a)) = a
64+ fromColumns (HIdentity a) = a
64− toResult a = HType (R a)
65+ toResult a = HIdentity (Identity a)
65− fromResult (HType (R a)) = a
66+ fromResult (HIdentity (Identity a)) = a
66−
67−
68−instance Sql DBType a => Recontextualize Expr Name (Expr a) (Name a)
69−
70−
71−instance Sql DBType a => Recontextualize Name Expr (Name a) (Expr a)
72−
73−
74−instance Sql DBType a => Recontextualize Name Name (Name a) (Name a)
75
67
76
68
77-- | @Selects a b@ means that @a@ is a schema (i.e., a 'Table' of 'Name's) for
69-- | @Selects a b@ means that @a@ is a schema (i.e., a 'Table' of 'Name's) for
78-- the 'Expr' columns in @b@.
70-- the 'Expr' columns in @b@.
79type Selects :: Type -> Type -> Constraint
71type Selects :: Type -> Type -> Constraint
80−class Recontextualize Name Expr names exprs => Selects names exprs
72+class Transposes Name Expr names exprs => Selects names exprs
81−instance Recontextualize Name Expr names exprs => Selects names exprs
73+instance Transposes Name Expr names exprs => Selects names exprs
74+
75+
76+ppColumn :: String -> Doc
77+ppColumn = Opaleye.ppSqlExpr . Opaleye.ColumnSqlExpr . Opaleye.SqlColumn
src/Rel8/Schema/Result.hs+17−49
@@ -1,86 +1,54 @@
1{-# language DataKinds #-}
1{-# language DataKinds #-}
2−{-# language EmptyCase #-}
3{-# language GADTs #-}
2{-# language GADTs #-}
4−{-# language LambdaCase #-}
5{-# language NamedFieldPuns #-}
3{-# language NamedFieldPuns #-}
6−{-# language PolyKinds #-}
7{-# language StandaloneKindSignatures #-}
4{-# language StandaloneKindSignatures #-}
8{-# language TypeFamilies #-}
5{-# language TypeFamilies #-}
9
6
10module Rel8.Schema.Result
7module Rel8.Schema.Result
11− ( Result( R, unR )
8+ ( Result
12− , NotResult( NotResult ), absurd
13 , null, nullifier, unnullifier
9 , null, nullifier, unnullifier
14 , vectorizer, unvectorizer
10 , vectorizer, unvectorizer
15 )
11 )
16where
12where
17
13
18-- base
14-- base
19−import Data.Kind ( Type )
15+import Data.Functor.Identity ( Identity( Identity), runIdentity )
20import Prelude hiding ( null )
16import Prelude hiding ( null )
21
17
22-- rel8
18-- rel8
23import Rel8.Schema.Kind ( Context )
19import Rel8.Schema.Kind ( Context )
24import Rel8.Schema.Null ( Nullify, Nullity( Null, NotNull ) )
20import Rel8.Schema.Null ( Nullify, Nullity( Null, NotNull ) )
25−import Rel8.Schema.Spec ( Spec( Spec ), SSpec(..) )
21+import Rel8.Schema.Spec ( Spec(..) )
26
22
27
23
28-- | The @Result@ context is the context used for decoded query results.
24-- | The @Result@ context is the context used for decoded query results.
29--
25--
30-- When a query is executed against a PostgreSQL database, Rel8 parses the
26-- When a query is executed against a PostgreSQL database, Rel8 parses the
31-- returned rows, decoding each row into the @Result@ context.
27-- returned rows, decoding each row into the @Result@ context.
32−type Result :: k -> Type
28+type Result :: Context
33−data Result a where
29+type Result = Identity
34− R :: { unR :: !a } -> Result ('Spec a)
35
30
36
31
37−type IsResult :: Context -> Bool
32+null :: Result (Maybe a)
38−type family IsResult context where
33+null = Identity Nothing
39− IsResult Result = 'True
40− IsResult _ = 'False
41
34
42
35
43−type NotResult :: Context -> Type
44−data NotResult context where
45− NotResult :: IsResult context ~ 'False => NotResult context
46−
47−
48−absurd :: NotResult Result -> a
49−absurd = \case
50−
51−
52−null :: Result ('Spec (Maybe a))
53−null = R Nothing
54−
55−
56−nullifier :: ()
57− => SSpec ('Spec a)
58− -> Result ('Spec a)
59− -> Result ('Spec (Nullify a))
36+nullifier :: Spec a -> Result a -> Result (Nullify a)
60−nullifier SSpec {nullity} (R a) = R $ case nullity of
37+nullifier Spec {nullity} (Identity a) = Identity $ case nullity of
61 Null -> a
38 Null -> a
62 NotNull -> Just a
39 NotNull -> Just a
63
40
64
41
65−unnullifier :: ()
66− => SSpec ('Spec a)
67− -> Result ('Spec (Nullify a))
42+unnullifier :: Spec a -> Result (Nullify a) -> Maybe (Result a)
68− -> Maybe (Result ('Spec a))
69−unnullifier SSpec {nullity} (R a) =
43+unnullifier Spec {nullity} (Identity a) =
70 case nullity of
44 case nullity of
71− Null -> pure $ R a
45+ Null -> pure $ Identity a
72− NotNull -> R <$> a
46+ NotNull -> Identity <$> a
73
47
74
48
75−vectorizer :: Functor f
49+vectorizer :: Functor f => Spec a -> f (Result a) -> Result (f a)
76− => SSpec ('Spec a)
77− -> f (Result ('Spec a))
78− -> Result ('Spec (f a))
79−vectorizer _ = R . fmap unR
50+vectorizer _ = Identity . fmap runIdentity
80
51
81
52
82−unvectorizer :: Functor f
53+unvectorizer :: Functor f => Spec a -> Result (f a) -> f (Result a)
83− => SSpec ('Spec a)
84− -> Result ('Spec (f a))
85− -> f (Result ('Spec a))
86−unvectorizer _ (R results) = R <$> results
54+unvectorizer _ (Identity results) = Identity <$> results
src/Rel8/Schema/Spec.hs+16−30
@@ -1,18 +1,15 @@
1−{-# language DataKinds #-}
2{-# language FlexibleContexts #-}
1{-# language FlexibleContexts #-}
3−{-# language GADTs #-}
2+{-# language MonoLocalBinds #-}
4{-# language StandaloneKindSignatures #-}
3{-# language StandaloneKindSignatures #-}
5−{-# language UndecidableInstances #-}
6
4
7module Rel8.Schema.Spec
5module Rel8.Schema.Spec
8− ( Spec( Spec )
9− , SSpec( SSpec, labels, info, nullity )
6+ ( Spec( Spec, labels, info, nullity )
10− , KnownSpec( specSing )
7+ , specification
11 )
8 )
12where
9where
13
10
14-- base
11-- base
15−import Data.Kind ( Constraint, Type )
12+import Data.Kind ( Type )
16import Prelude
13import Prelude
17
14
18-- rel8
15-- rel8
@@ -21,28 +18,17 @@ import Rel8.Type ( DBType, typeInformation )
21import Rel8.Type.Information ( TypeInformation )
18import Rel8.Type.Information ( TypeInformation )
22
19
23
20
24−type Spec :: Type
21+type Spec :: Type -> Type
25−newtype Spec = Spec Type
22+data Spec a = Spec
23+ { labels :: [String]
24+ , info :: TypeInformation (Unnullify a)
25+ , nullity :: Nullity a
26+ }
26
27
27
28
28−type SSpec :: Spec -> Type
29−data SSpec spec where
30− SSpec ::
31− { labels :: [String]
32− , info :: TypeInformation (Unnullify a)
33− , nullity :: Nullity a
34− }
35− -> SSpec ('Spec a)
36−
37−
38−type KnownSpec :: Spec -> Constraint
39−class KnownSpec spec where
40− specSing :: SSpec spec
41−
42−
43−instance Sql DBType a => KnownSpec ('Spec a) where
29+specification :: Sql DBType a => Spec a
44− specSing = SSpec
30+specification = Spec
45− { labels = []
31+ { labels = []
46− , info = typeInformation
32+ , info = typeInformation
47− , nullity = nullable
33+ , nullity = nullable
48− }
34+ }
src/Rel8/Schema/Spec/Constrain.hsdeleted−32
@@ -1,32 +0,0 @@
1−{-# language ConstraintKinds #-}
2−{-# language DataKinds #-}
3−{-# language FlexibleInstances #-}
4−{-# language MultiParamTypeClasses #-}
5−{-# language StandaloneKindSignatures #-}
6−{-# language TypeFamilies #-}
7−{-# language UndecidableInstances #-}
8−{-# language UndecidableSuperClasses #-}
9−
10−module Rel8.Schema.Spec.Constrain
11− ( ConstrainSpec
12− )
13−where
14−
15−-- base
16−import Data.Kind ( Constraint, Type )
17−import Prelude ()
18−
19−-- rel8
20−import Rel8.Schema.Spec ( Spec( Spec ) )
21−
22−
23−type Unspec :: Spec -> Type
24−type family Unspec spec where
25− Unspec ('Spec a) = a
26−
27−
28−type ConstrainSpec :: (Type -> Constraint) -> Spec -> Constraint
29−class (spec ~ 'Spec (Unspec spec), constraint (Unspec spec)) =>
30− ConstrainSpec constraint spec
31−instance (spec ~ 'Spec (Unspec spec), constraint (Unspec spec)) =>
32− ConstrainSpec constraint spec
src/Rel8/Schema/Table.hs+20
@@ -1,14 +1,26 @@
1{-# language DeriveFunctor #-}
1{-# language DeriveFunctor #-}
2{-# language DerivingStrategies #-}
2{-# language DerivingStrategies #-}
3+{-# language DisambiguateRecordFields #-}
4+{-# language NamedFieldPuns #-}
5+{-# language StandaloneKindSignatures #-}
3
6
4module Rel8.Schema.Table
7module Rel8.Schema.Table
5 ( TableSchema(..)
8 ( TableSchema(..)
9+ , ppTable
6 )
10 )
7where
11where
8
12
9-- base
13-- base
14+import Data.Kind ( Type )
10import Prelude
15import Prelude
11
16
17+-- opaleye
18+import qualified Opaleye.Internal.HaskellDB.Sql as Opaleye
19+import qualified Opaleye.Internal.HaskellDB.Sql.Print as Opaleye
20+
21+-- pretty
22+import Text.PrettyPrint ( Doc )
23+
12
24
13-- | The schema for a table. This is used to specify the name and schema that a
25-- | The schema for a table. This is used to specify the name and schema that a
14-- table belongs to (the @FROM@ part of a SQL query), along with the schema of
26-- table belongs to (the @FROM@ part of a SQL query), along with the schema of
@@ -16,6 +28,7 @@ import Prelude
16--
28--
17-- For each selectable table in your database, you should provide a
29-- For each selectable table in your database, you should provide a
18-- @TableSchema@ in order to interact with the table via Rel8.
30-- @TableSchema@ in order to interact with the table via Rel8.
31+type TableSchema :: Type -> Type
19data TableSchema names = TableSchema
32data TableSchema names = TableSchema
20 { name :: String
33 { name :: String
21 -- ^ The name of the table.
34 -- ^ The name of the table.
@@ -27,3 +40,10 @@ data TableSchema names = TableSchema
27 -- data type here, parameterized by the 'Rel8.ColumnSchema.ColumnSchema' functor.
40 -- data type here, parameterized by the 'Rel8.ColumnSchema.ColumnSchema' functor.
28 }
41 }
29 deriving stock Functor
42 deriving stock Functor
43+
44+
45+ppTable :: TableSchema a -> Doc
46+ppTable TableSchema {name, schema} = Opaleye.ppTable Opaleye.SqlTable
47+ { sqlTableSchemaName = schema
48+ , sqlTableName = name
49+ }
src/Rel8/Statement/Delete.hs+35−48
@@ -1,40 +1,37 @@
1{-# language DuplicateRecordFields #-}
1{-# language DuplicateRecordFields #-}
2{-# language GADTs #-}
2{-# language GADTs #-}
3{-# language NamedFieldPuns #-}
3{-# language NamedFieldPuns #-}
4−{-# language ScopedTypeVariables #-}
4+{-# language RankNTypes #-}
5+{-# language RecordWildCards #-}
5{-# language StandaloneKindSignatures #-}
6{-# language StandaloneKindSignatures #-}
6−{-# language TypeApplications #-}
7+{-# language StrictData #-}
7
8
8module Rel8.Statement.Delete
9module Rel8.Statement.Delete
9 ( Delete(..)
10 ( Delete(..)
10 , delete
11 , delete
12+ , ppDelete
11 )
13 )
12where
14where
13
15
14-- base
16-- base
15−import Control.Exception ( throwIO )
16import Data.Kind ( Type )
17import Data.Kind ( Type )
17import Prelude
18import Prelude
18
19
19-- hasql
20-- hasql
20−import Hasql.Connection ( Connection )
21−import qualified Hasql.Decoders as Hasql
22import qualified Hasql.Encoders as Hasql
21import qualified Hasql.Encoders as Hasql
23−import qualified Hasql.Session as Hasql
24import qualified Hasql.Statement as Hasql
22import qualified Hasql.Statement as Hasql
25
23
26−-- opaleye
24+-- pretty
27−import qualified Opaleye.Internal.Manipulation as Opaleye
25+import Text.PrettyPrint ( Doc, (<+>), ($$), text )
28
26
29-- rel8
27-- rel8
30import Rel8.Expr ( Expr )
28import Rel8.Expr ( Expr )
31−import Rel8.Expr.Opaleye ( toColumn, toPrimExpr )
29+import Rel8.Query ( Query )
32import Rel8.Schema.Name ( Selects )
30import Rel8.Schema.Name ( Selects )
33−import Rel8.Schema.Table ( TableSchema )
31+import Rel8.Schema.Table ( TableSchema, ppTable )
34−import Rel8.Statement.Returning ( Returning( NumberOfRowsAffected, Projection ) )
32+import Rel8.Statement.Returning ( Returning, decodeReturning, ppReturning )
35−import Rel8.Table.Cols ( fromCols, toCols )
33+import Rel8.Statement.Using ( ppUsing )
36−import Rel8.Table.Opaleye ( castTable, table, unpackspec )
34+import Rel8.Statement.Where ( ppWhere )
37−import Rel8.Table.Serialize ( Serializable, parse )
38
35
39-- text
36-- text
40import qualified Data.Text as Text
37import qualified Data.Text as Text
@@ -47,7 +44,10 @@ data Delete a where
47 Delete :: Selects names exprs =>
44 Delete :: Selects names exprs =>
48 { from :: TableSchema names
45 { from :: TableSchema names
49 -- ^ Which table to delete from.
46 -- ^ Which table to delete from.
47+ , using :: Query using
48+ -- ^ @USING@ clause — this can be used to join against other tables,
49+ -- and its results can be referenced in the @WHERE@ clause
50− , deleteWhere :: exprs -> Expr Bool
50+ , deleteWhere :: using -> exprs -> Expr Bool
51 -- ^ Which rows should be selected for deletion.
51 -- ^ Which rows should be selected for deletion.
52 , returning :: Returning names a
52 , returning :: Returning names a
53 -- ^ What to return from the @DELETE@ statement.
53 -- ^ What to return from the @DELETE@ statement.
@@ -55,38 +55,25 @@ data Delete a where
55 -> Delete a
55 -> Delete a
56
56
57
57
58−-- | Run a @DELETE@ statement.
58+ppDelete :: Delete a -> Doc
59−delete :: Connection -> Delete a -> IO a
59+ppDelete Delete {..} = case ppUsing using of
60−delete c Delete {from, deleteWhere, returning} =
60+ Nothing ->
61− case returning of
61+ text "DELETE FROM" <+> ppTable from $$
62− NumberOfRowsAffected -> Hasql.run session c >>= either throwIO pure
62+ text "WHERE false"
63− where
63+ Just (usingDoc, i) ->
64− session = Hasql.statement () statement
64+ text "DELETE FROM" <+> ppTable from $$
65− statement = Hasql.Statement bytes params decode prepare
65+ usingDoc $$
66− bytes = encodeUtf8 $ Text.pack sql
66+ ppWhere from (deleteWhere i) $$
67− params = Hasql.noParams
67+ ppReturning from returning
68− decode = Hasql.rowsAffected
69− prepare = False
70− sql = Opaleye.arrangeDeleteSql from' where'
71− where
72− from' = table $ toCols <$> from
73− where' = toColumn . toPrimExpr . deleteWhere . fromCols
74
68
75− Projection project -> Hasql.run session c >>= either throwIO pure
69+
76− where
70+-- | Run a 'Delete' statement.
77− session = Hasql.statement () statement
71+delete :: Delete a -> Hasql.Statement () a
78− statement = Hasql.Statement bytes params decode prepare
72+delete d@Delete {returning} = Hasql.Statement bytes params decode prepare
79− bytes = encodeUtf8 $ Text.pack sql
80− params = Hasql.noParams
81− decode = decoder project
82− prepare = False
83− sql =
84− Opaleye.arrangeDeleteReturningSql unpackspec from' where' project'
85− where
86− from' = table $ toCols <$> from
87− where' = toColumn . toPrimExpr . deleteWhere . fromCols
88− project' = castTable . toCols . project . fromCols
89 where
73 where
90− decoder :: forall exprs projection a. Serializable projection a
74+ bytes = encodeUtf8 $ Text.pack sql
91− => (exprs -> projection) -> Hasql.Result [a]
75+ params = Hasql.noParams
92− decoder _ = Hasql.rowList (parse @projection @a)
76+ decode = decodeReturning returning
77+ prepare = False
78+ sql = show doc
79+ doc = ppDelete d
src/Rel8/Statement/Insert.hs+43−72
@@ -1,64 +1,59 @@
1{-# language DuplicateRecordFields #-}
1{-# language DuplicateRecordFields #-}
2+{-# language FlexibleContexts #-}
2{-# language GADTs #-}
3{-# language GADTs #-}
3{-# language NamedFieldPuns #-}
4{-# language NamedFieldPuns #-}
4−{-# language ScopedTypeVariables #-}
5+{-# language RecordWildCards #-}
5{-# language StandaloneKindSignatures #-}
6{-# language StandaloneKindSignatures #-}
6−{-# language TypeApplications #-}
7+{-# language StrictData #-}
7
8
8module Rel8.Statement.Insert
9module Rel8.Statement.Insert
9 ( Insert(..)
10 ( Insert(..)
10− , OnConflict(..)
11 , insert
11 , insert
12+ , ppInsert
13+ , ppInto
12 )
14 )
13where
15where
14
16
15-- base
17-- base
16−import Control.Exception ( throwIO )
18+import Data.Foldable ( toList )
17−import Data.List.NonEmpty ( NonEmpty( (:|) ) )
18import Data.Kind ( Type )
19import Data.Kind ( Type )
19import Prelude
20import Prelude
20
21
21-- hasql
22-- hasql
22−import Hasql.Connection ( Connection )
23−import qualified Hasql.Decoders as Hasql
24import qualified Hasql.Encoders as Hasql
23import qualified Hasql.Encoders as Hasql
25−import qualified Hasql.Session as Hasql
26import qualified Hasql.Statement as Hasql
24import qualified Hasql.Statement as Hasql
27
25
28-- opaleye
26-- opaleye
29−import qualified Opaleye.Internal.Manipulation as Opaleye
27+import qualified Opaleye.Internal.HaskellDB.Sql.Print as Opaleye
30−import qualified Opaleye.Manipulation as Opaleye
28+
29+-- pretty
30+import Text.PrettyPrint ( Doc, (<+>), ($$), parens, text )
31
31
32-- rel8
32-- rel8
33+import Rel8.Query ( Query )
33−import Rel8.Schema.Name ( Selects )
34+import Rel8.Schema.Name ( Name, Selects, ppColumn )
34−import Rel8.Schema.Table ( TableSchema )
35+import Rel8.Schema.Table ( TableSchema(..), ppTable )
35−import Rel8.Statement.Returning ( Returning( Projection, NumberOfRowsAffected ) )
36+import Rel8.Statement.OnConflict ( OnConflict, ppOnConflict )
36−import Rel8.Table.Cols ( fromCols, toCols )
37+import Rel8.Statement.Returning ( Returning, decodeReturning, ppReturning )
38+import Rel8.Statement.Select ( ppRows )
37−import Rel8.Table.Opaleye ( castTable, table, unpackspec )
39+import Rel8.Table ( Table )
38−import Rel8.Table.Serialize ( Serializable, parse )
40+import Rel8.Table.Name ( showNames )
39
41
40-- text
42-- text
41import qualified Data.Text as Text ( pack )
43import qualified Data.Text as Text ( pack )
42import Data.Text.Encoding ( encodeUtf8 )
44import Data.Text.Encoding ( encodeUtf8 )
43
45
44
46
45−-- | @OnConflict@ allows you to add an @ON CONFLICT@ clause to an @INSERT@
46−-- statement.
47−type OnConflict :: Type
48−data OnConflict
49− = Abort -- ^ @ON CONFLICT ABORT@
50− | DoNothing -- ^ @ON CONFLICT DO NOTHING@
51−
52−
53-- | The constituent parts of a SQL @INSERT@ statement.
47-- | The constituent parts of a SQL @INSERT@ statement.
54type Insert :: Type -> Type
48type Insert :: Type -> Type
55data Insert a where
49data Insert a where
56 Insert :: Selects names exprs =>
50 Insert :: Selects names exprs =>
57 { into :: TableSchema names
51 { into :: TableSchema names
58 -- ^ Which table to insert into.
52 -- ^ Which table to insert into.
59− , rows :: [exprs]
53+ , rows :: Query exprs
60− -- ^ The rows to insert.
54+ -- ^ The rows to insert. This can be an arbitrary query — use
55+ -- 'Rel8.values' insert a static list of rows.
61− , onConflict :: OnConflict
56+ , onConflict :: OnConflict names
62 -- ^ What to do if the inserted rows conflict with data already in the
57 -- ^ What to do if the inserted rows conflict with data already in the
63 -- table.
58 -- table.
64 , returning :: Returning names a
59 , returning :: Returning names a
@@ -67,52 +62,28 @@ data Insert a where
67 -> Insert a
62 -> Insert a
68
63
69
64
70−-- | Run an @INSERT@ statement
65+ppInsert :: Insert a -> Doc
71−insert :: Connection -> Insert a -> IO a
66+ppInsert Insert {..} =
72−insert c Insert {into, rows, onConflict, returning} =
67+ text "INSERT INTO" <+>
73− case (rows, returning) of
68+ ppInto into $$
74− ([], NumberOfRowsAffected) -> pure 0
69+ ppRows rows $$
75− ([], Projection _) -> pure []
70+ ppOnConflict into onConflict $$
71+ ppReturning into returning
76
72
77− (x:xs, NumberOfRowsAffected) -> Hasql.run session c >>= either throwIO pure
78− where
79− session = Hasql.statement () statement
80− statement = Hasql.Statement bytes params decode prepare
81− bytes = encodeUtf8 $ Text.pack sql
82− params = Hasql.noParams
83− decode = Hasql.rowsAffected
84− prepare = False
85− sql = Opaleye.arrangeInsertManySql into' rows' onConflict'
86− where
87− into' = table $ toCols <$> into
88− rows' = toCols <$> x :| xs
89
73
90− (x:xs, Projection project) -> Hasql.run session c >>= either throwIO pure
74+ppInto :: Table Name a => TableSchema a -> Doc
91− where
75+ppInto table@TableSchema {columns} =
92− session = Hasql.statement () statement
76+ ppTable table <+>
93− statement = Hasql.Statement bytes params decode prepare
77+ parens (Opaleye.commaV ppColumn (toList (showNames columns)))
94− bytes = encodeUtf8 $ Text.pack sql
95− params = Hasql.noParams
96− decode = decoder project
97− prepare = False
98− sql =
99− Opaleye.arrangeInsertManyReturningSql
100− unpackspec
101− into'
102− rows'
103− project'
104− onConflict'
105− where
106− into' = table $ toCols <$> into
107− rows' = toCols <$> x :| xs
108− project' = castTable . toCols . project . fromCols
109
78
110− where
111− onConflict' =
112− case onConflict of
113− DoNothing -> Just Opaleye.DoNothing
114− Abort -> Nothing
115
79
116− decoder :: forall exprs projection a. Serializable projection a
80+-- | Run an 'Insert' statement.
117− => (exprs -> projection) -> Hasql.Result [a]
81+insert :: Insert a -> Hasql.Statement () a
118− decoder _ = Hasql.rowList (parse @projection @a)
82+insert i@Insert {returning} = Hasql.Statement bytes params decode prepare
83+ where
84+ bytes = encodeUtf8 $ Text.pack sql
85+ params = Hasql.noParams
86+ decode = decodeReturning returning
87+ prepare = False
88+ sql = show doc
89+ doc = ppInsert i
src/Rel8/Statement/OnConflict.hsnew file+106
@@ -0,0 +1,106 @@
1+{-# language DuplicateRecordFields #-}
2+{-# language FlexibleContexts #-}
3+{-# language GADTs #-}
4+{-# language LambdaCase #-}
5+{-# language NamedFieldPuns #-}
6+{-# language RecordWildCards #-}
7+{-# language StandaloneKindSignatures #-}
8+{-# language StrictData #-}
9+
10+module Rel8.Statement.OnConflict
11+ ( OnConflict(..)
12+ , Upsert(..)
13+ , ppOnConflict
14+ )
15+where
16+
17+-- base
18+import Data.Foldable ( toList )
19+import Data.Kind ( Type )
20+import Prelude
21+
22+-- opaleye
23+import qualified Opaleye.Internal.HaskellDB.Sql.Print as Opaleye
24+
25+-- pretty
26+import Text.PrettyPrint ( Doc, (<+>), ($$), parens, text )
27+
28+-- rel8
29+import Rel8.Expr ( Expr )
30+import Rel8.Schema.Name ( Name, Selects, ppColumn )
31+import Rel8.Schema.Table ( TableSchema(..) )
32+import Rel8.Statement.Set ( ppSet )
33+import Rel8.Statement.Where ( ppWhere )
34+import Rel8.Table ( Table, toColumns )
35+import Rel8.Table.Cols ( Cols( Cols ) )
36+import Rel8.Table.Name ( showNames )
37+import Rel8.Table.Opaleye ( attributes )
38+import Rel8.Table.Projection ( Projecting, Projection, apply )
39+
40+
41+-- | 'OnConflict' represents the @ON CONFLICT@ clause of an @INSERT@
42+-- statement. This specifies what ought to happen when one or more of the
43+-- rows proposed for insertion conflict with an existing row in the table.
44+type OnConflict :: Type -> Type
45+data OnConflict names
46+ = Abort
47+ -- ^ Abort the transaction if there are conflicting rows (Postgres' default)
48+ | DoNothing
49+ -- ^ @ON CONFLICT DO NOTHING@
50+ | DoUpdate (Upsert names)
51+ -- ^ @ON CONFLICT DO UPDATE@
52+
53+
54+-- | The @ON CONFLICT (...) DO UPDATE@ clause of an @INSERT@ statement, also
55+-- known as \"upsert\".
56+--
57+-- When an existing row conflicts with a row proposed for insertion,
58+-- @ON CONFLICT DO UPDATE@ allows you to instead update this existing row. The
59+-- conflicting row proposed for insertion is then \"excluded\", but its values
60+-- can still be referenced from the @SET@ and @WHERE@ clauses of the @UPDATE@
61+-- statement.
62+--
63+-- Upsert in Postgres requires an explicit set of \"conflict targets\" — the
64+-- set of columns comprising the @UNIQUE@ index from conflicts with which we
65+-- would like to recover.
66+type Upsert :: Type -> Type
67+data Upsert names where
68+ Upsert :: (Selects names exprs, Projecting names index, excluded ~ exprs) =>
69+ { index :: Projection names index
70+ -- ^ The set of conflict targets, projected from the set of columns for
71+ -- the whole table
72+ , set :: excluded -> exprs -> exprs
73+ -- ^ How to update each selected row.
74+ , updateWhere :: excluded -> exprs -> Expr Bool
75+ -- ^ Which rows to select for update.
76+ }
77+ -> Upsert names
78+
79+
80+ppOnConflict :: TableSchema names -> OnConflict names -> Doc
81+ppOnConflict schema = \case
82+ Abort -> mempty
83+ DoNothing -> text "ON CONFLICT DO NOTHING"
84+ DoUpdate upsert -> ppUpsert schema upsert
85+
86+
87+ppUpsert :: TableSchema names -> Upsert names -> Doc
88+ppUpsert schema@TableSchema {columns} Upsert {..} =
89+ text "ON CONFLICT" <+>
90+ ppIndex schema index <+>
91+ text "DO UPDATE" $$
92+ ppSet schema (set excluded) $$
93+ ppWhere schema (updateWhere excluded)
94+ where
95+ excluded = attributes TableSchema
96+ { schema = Nothing
97+ , name = "excluded"
98+ , columns
99+ }
100+
101+
102+ppIndex :: (Table Name names, Projecting names index)
103+ => TableSchema names -> Projection names index -> Doc
104+ppIndex TableSchema {columns} index =
105+ parens $ Opaleye.commaV ppColumn $ toList $
106+ showNames $ Cols $ apply index $ toColumns columns
src/Rel8/Statement/Returning.hs+114−10
@@ -1,29 +1,133 @@
1{-# language GADTs #-}
1{-# language GADTs #-}
2+{-# language LambdaCase #-}
3+{-# language NamedFieldPuns #-}
4+{-# language RankNTypes #-}
5+{-# language ScopedTypeVariables #-}
2{-# language StandaloneKindSignatures #-}
6{-# language StandaloneKindSignatures #-}
7+{-# language StrictData #-}
8+{-# language TypeApplications #-}
3
9
4module Rel8.Statement.Returning
10module Rel8.Statement.Returning
5− ( Returning(..)
11+ ( Returning( NumberOfRowsAffected, Projection )
12+ , decodeReturning
13+ , ppReturning
6 )
14 )
7where
15where
8
16
9-- base
17-- base
18+import Control.Applicative ( liftA2 )
19+import Data.Foldable ( toList )
10import Data.Int ( Int64 )
20import Data.Int ( Int64 )
11import Data.Kind ( Type )
21import Data.Kind ( Type )
22+import Data.List.NonEmpty ( NonEmpty )
12−import Prelude ()
23+import Prelude
24+
25+-- hasql
26+import qualified Hasql.Decoders as Hasql
27+
28+-- opaleye
29+import qualified Opaleye.Internal.HaskellDB.PrimQuery as Opaleye
30+import qualified Opaleye.Internal.HaskellDB.Sql.Print as Opaleye
31+import qualified Opaleye.Internal.Sql as Opaleye
32+
33+-- pretty
34+import Text.PrettyPrint ( Doc, (<+>), text )
13
35
14-- rel8
36-- rel8
15import Rel8.Schema.Name ( Selects )
37import Rel8.Schema.Name ( Selects )
38+import Rel8.Schema.Table ( TableSchema(..) )
39+import Rel8.Table.Opaleye ( castTable, exprs, view )
16−import Rel8.Table.Serialize ( Serializable )
40+import Rel8.Table.Serialize ( Serializable, parse )
17
41
42+-- semigropuoids
43+import Data.Functor.Apply ( Apply, (<.>) )
18
44
45+
19−-- | @INSERT@, @UPDATE@ and @DELETE@ all support returning either the number of
46+-- | 'Rel8.Insert', 'Rel8.Update' and 'Rel8.Delete' all support returning either
20−-- rows affected, or the actual rows modified. 'Projection' allows you to
47+-- the number of rows affected, or the actual rows modified.
21−-- project out of these returned rows, which can be useful if you want to log
22−-- exactly which rows were deleted, or to view a generated id (for example, if
23−-- using a column with an autoincrementing counter as a default value).
24type Returning :: Type -> Type -> Type
48type Returning :: Type -> Type -> Type
25data Returning names a where
49data Returning names a where
50+ Pure :: a -> Returning names a
51+ Ap :: Returning names (a -> b) -> Returning names a -> Returning names b
52+
53+ -- | Return the number of rows affected.
26 NumberOfRowsAffected :: Returning names Int64
54 NumberOfRowsAffected :: Returning names Int64
55+
56+ -- | 'Projection' allows you to project out of the affected rows, which can
57+ -- be useful if you want to log exactly which rows were deleted, or to view
58+ -- a generated id (for example, if using a column with an autoincrementing
59+ -- counter via 'Rel8.nextval').
27− Projection :: (Selects names exprs, Serializable projection a)
60+ Projection :: (Selects names exprs, Serializable returning a)
28− => (exprs -> projection)
61+ => (exprs -> returning)
29 -> Returning names [a]
62 -> Returning names [a]
63+
64+
65+instance Functor (Returning names) where
66+ fmap f = \case
67+ Pure a -> Pure (f a)
68+ Ap g a -> Ap (fmap (f .) g) a
69+ m -> Ap (Pure f) m
70+
71+
72+instance Apply (Returning names) where
73+ (<.>) = Ap
74+
75+
76+instance Applicative (Returning names) where
77+ pure = Pure
78+ (<*>) = Ap
79+
80+
81+projections :: ()
82+ => TableSchema names -> Returning names a -> Maybe (NonEmpty Opaleye.PrimExpr)
83+projections schema@TableSchema {columns} = \case
84+ Pure _ -> Nothing
85+ Ap f a -> projections schema f <> projections schema a
86+ NumberOfRowsAffected -> Nothing
87+ Projection f -> Just (exprs (castTable (f (view columns))))
88+
89+
90+runReturning :: ()
91+ => ((Int64 -> a) -> r)
92+ -> (forall x. Hasql.Row x -> ([x] -> a) -> r)
93+ -> Returning names a
94+ -> r
95+runReturning rowCount rowList = \case
96+ Pure a -> rowCount (const a)
97+ Ap fs as ->
98+ runReturning
99+ (\withCount ->
100+ runReturning
101+ (\withCount' -> rowCount (withCount <*> withCount'))
102+ (\decoder -> rowList decoder . liftA2 withCount length64)
103+ as)
104+ (\decoder withRows ->
105+ runReturning
106+ (\withCount -> rowList decoder $ withRows <*> withCount . length64)
107+ (\decoder' withRows' ->
108+ rowList (liftA2 (,) decoder decoder') $
109+ withRows <$> fmap fst <*> withRows' . fmap snd)
110+ as)
111+ fs
112+ NumberOfRowsAffected -> rowCount id
113+ Projection (_ :: exprs -> returning) -> rowList decoder' id
114+ where
115+ decoder' = parse @returning
116+ where
117+ length64 :: Foldable f => f x -> Int64
118+ length64 = fromIntegral . length
119+
120+
121+decodeReturning :: Returning names a -> Hasql.Result a
122+decodeReturning = runReturning
123+ (<$> Hasql.rowsAffected)
124+ (\decoder withRows -> withRows <$> Hasql.rowList decoder)
125+
126+
127+ppReturning :: TableSchema names -> Returning names a -> Doc
128+ppReturning schema returning = case projections schema returning of
129+ Nothing -> mempty
130+ Just columns ->
131+ text "RETURNING" <+> Opaleye.commaV Opaleye.ppSqlExpr (toList sqlExprs)
132+ where
133+ sqlExprs = Opaleye.sqlExpr <$> columns
src/Rel8/Statement/SQL.hsnew file+29
@@ -0,0 +1,29 @@
1+module Rel8.Statement.SQL
2+ ( showDelete
3+ , showInsert
4+ , showUpdate
5+ )
6+where
7+
8+-- base
9+import Prelude
10+
11+-- rel8
12+import Rel8.Statement.Delete ( Delete, ppDelete )
13+import Rel8.Statement.Insert ( Insert, ppInsert )
14+import Rel8.Statement.Update ( Update, ppUpdate )
15+
16+
17+-- | Convert a 'Delete' to a 'String' containing a @DELETE@ statement.
18+showDelete :: Delete a -> String
19+showDelete = show . ppDelete
20+
21+
22+-- | Convert an 'Insert' to a 'String' containing an @INSERT@ statement.
23+showInsert :: Insert a -> String
24+showInsert = show . ppInsert
25+
26+
27+-- | Convert an 'Update' to a 'String' containing an @UPDATE@ statement.
28+showUpdate :: Update a -> String
29+showUpdate = show . ppUpdate
src/Rel8/Statement/Select.hs+120−35
@@ -1,62 +1,147 @@
1+{-# language DeriveTraversable #-}
2+{-# language DerivingStrategies #-}
3+{-# language FlexibleContexts #-}
1{-# language MonoLocalBinds #-}
4{-# language MonoLocalBinds #-}
2{-# language ScopedTypeVariables #-}
5{-# language ScopedTypeVariables #-}
6+{-# language StandaloneKindSignatures #-}
3{-# language TypeApplications #-}
7{-# language TypeApplications #-}
4
8
5module Rel8.Statement.Select
9module Rel8.Statement.Select
6 ( select
10 ( select
7− , selectWithNames
11+ , ppSelect
12+
13+ , Optimized(..)
14+ , ppPrimSelect
15+ , ppRows
8 )
16 )
9where
17where
10
18
11-- base
19-- base
12−import Control.Exception ( throwIO )
20+import Data.Foldable ( toList )
21+import Data.Kind ( Type )
22+import Data.Void ( Void )
13−import Prelude
23+import Prelude hiding ( undefined )
14
24
15-- hasql
25-- hasql
16−import Hasql.Connection ( Connection )
17import qualified Hasql.Decoders as Hasql
26import qualified Hasql.Decoders as Hasql
18import qualified Hasql.Encoders as Hasql
27import qualified Hasql.Encoders as Hasql
19−import qualified Hasql.Session as Hasql
20import qualified Hasql.Statement as Hasql
28import qualified Hasql.Statement as Hasql
21
29
30+-- opaleye
31+import qualified Opaleye.Internal.HaskellDB.PrimQuery as Opaleye
32+import qualified Opaleye.Internal.HaskellDB.Sql as Opaleye
33+import qualified Opaleye.Internal.HaskellDB.Sql.Print as Opaleye
34+import qualified Opaleye.Internal.PrimQuery as Opaleye
35+import qualified Opaleye.Internal.Print as Opaleye
36+import qualified Opaleye.Internal.Optimize as Opaleye
37+import qualified Opaleye.Internal.QueryArr as Opaleye hiding ( Select )
38+import qualified Opaleye.Internal.Sql as Opaleye hiding ( Values )
39+import qualified Opaleye.Internal.Tag as Opaleye
40+
41+-- pretty
42+import Text.PrettyPrint ( Doc )
43+
22-- rel8
44-- rel8
45+import Rel8.Expr ( Expr )
46+import Rel8.Expr.Bool ( false )
47+import Rel8.Expr.Opaleye ( toPrimExpr )
23import Rel8.Query ( Query )
48import Rel8.Query ( Query )
24−import Rel8.Query.SQL ( sqlForQuery, sqlForQueryWithNames )
49+import Rel8.Query.Opaleye ( toOpaleye )
25import Rel8.Schema.Name ( Selects )
50import Rel8.Schema.Name ( Selects )
51+import Rel8.Table ( Table )
52+import Rel8.Table.Cols ( toCols )
53+import Rel8.Table.Name ( namesFromLabels )
54+import Rel8.Table.Opaleye ( castTable, exprsWithNames )
55+import qualified Rel8.Table.Opaleye as T
26import Rel8.Table.Serialize ( Serializable, parse )
56import Rel8.Table.Serialize ( Serializable, parse )
57+import Rel8.Table.Undefined ( undefined )
27
58
28-- text
59-- text
29import qualified Data.Text as Text
60import qualified Data.Text as Text
30import Data.Text.Encoding ( encodeUtf8 )
61import Data.Text.Encoding ( encodeUtf8 )
31
62
32
63
33−-- | Run a @SELECT@ query, returning all rows.
64+-- | Run a @SELECT@ statement, returning all rows.
34select :: forall exprs a. Serializable exprs a
65select :: forall exprs a. Serializable exprs a
35− => Connection -> Query exprs -> IO [a]
66+ => Query exprs -> Hasql.Statement () [a]
36−select c query = case sqlForQuery query of
67+select query = Hasql.Statement bytes params decode prepare
37− Nothing -> pure []
68+ where
38− Just sql -> Hasql.run session c >>= either throwIO pure
69+ bytes = encodeUtf8 (Text.pack sql)
39− where
70+ params = Hasql.noParams
40− session = Hasql.statement () statement
71+ decode = Hasql.rowList (parse @exprs @a)
41− statement = Hasql.Statement bytes params decode prepare
72+ prepare = False
42− bytes = encodeUtf8 (Text.pack sql)
73+ sql = show doc
43− params = Hasql.noParams
74+ doc = ppSelect query
44− decode = Hasql.rowList (parse @exprs @a)
75+
45− prepare = False
76+
46−
77+ppSelect :: Table Expr a => Query a -> Doc
47−
78+ppSelect query =
48−selectWithNames :: forall exprs a names.
79+ Opaleye.ppSql $ primSelectWith names (toCols exprs') primQuery'
80+ where
81+ names = namesFromLabels
82+ (exprs, primQuery, _) =
83+ Opaleye.runSimpleQueryArrStart (toOpaleye query) ()
84+ (exprs', primQuery') = case optimize primQuery of
85+ Empty -> (undefined, Opaleye.Product (pure (pure Opaleye.Unit)) never)
86+ Unit -> (exprs, Opaleye.Unit)
87+ Optimized pq -> (exprs, pq)
88+ never = pure (toPrimExpr false)
89+
90+
91+ppRows :: Table Expr a => Query a -> Doc
92+ppRows query = case optimize primQuery of
93+ -- Special case VALUES because we can't use DEFAULT inside a SELECT
94+ Optimized (Opaleye.Values symbols rows)
95+ | eqSymbols symbols (toList (T.exprs a)) ->
96+ Opaleye.ppValues_ (map Opaleye.sqlExpr <$> toList rows)
97+ _ -> ppSelect query
98+ where
99+ (a, primQuery, _) = Opaleye.runSimpleQueryArrStart (toOpaleye query) ()
100+
101+ eqSymbols (symbol : symbols) (Opaleye.AttrExpr symbol' : exprs)
102+ | eqSymbol symbol symbol' = eqSymbols symbols exprs
103+ | otherwise = False
104+ eqSymbols [] [] = True
105+ eqSymbols _ _ = False
106+
107+ eqSymbol
108+ (Opaleye.Symbol name (Opaleye.UnsafeTag tag))
109+ (Opaleye.Symbol name' (Opaleye.UnsafeTag tag'))
110+ = name == name' && tag == tag'
111+
112+
113+ppPrimSelect :: Query a -> (Optimized Doc, a)
114+ppPrimSelect query =
115+ (Opaleye.ppSql . primSelect <$> optimize primQuery, a)
116+ where
117+ (a, primQuery, _) = Opaleye.runSimpleQueryArrStart (toOpaleye query) ()
118+
119+
120+type Optimized :: Type -> Type
121+data Optimized a = Empty | Unit | Optimized a
122+ deriving stock (Functor, Foldable, Traversable, Show)
123+
124+
125+optimize :: Opaleye.PrimQuery' a -> Optimized (Opaleye.PrimQuery' Void)
126+optimize query = case Opaleye.removeEmpty (Opaleye.optimize query) of
127+ Nothing -> Empty
128+ Just Opaleye.Unit -> Unit
129+ Just query' -> Optimized query'
130+
131+
132+primSelect :: Opaleye.PrimQuery' Void -> Opaleye.Select
133+primSelect = Opaleye.foldPrimQuery Opaleye.sqlQueryGenerator
134+
135+
49− ( Selects names exprs
136+primSelectWith :: Selects names exprs
50− , Serializable exprs a
137+ => names -> exprs -> Opaleye.PrimQuery' Void -> Opaleye.Select
51− )
138+primSelectWith names exprs query =
52− => Connection -> names -> Query exprs -> IO [a]
139+ Opaleye.SelectFrom $ Opaleye.newSelect
53−selectWithNames c names query = case sqlForQueryWithNames names query of
140+ { Opaleye.attrs = Opaleye.SelectAttrs attrs
54− Nothing -> pure []
141+ , Opaleye.tables = Opaleye.oneTable (primSelect query)
55− Just sql -> Hasql.run session c >>= either throwIO pure
142+ }
56− where
143+ where
57− session = Hasql.statement () statement
144+ attrs = makeAttr <$> exprsWithNames names (castTable exprs)
58− statement = Hasql.Statement bytes params decode prepare
145+ where
59− bytes = encodeUtf8 (Text.pack sql)
146+ makeAttr (label, expr) =
60− params = Hasql.noParams
147+ (Opaleye.sqlExpr expr, Just (Opaleye.SqlColumn label))
61− decode = Hasql.rowList (parse @exprs @a)
62− prepare = False
src/Rel8/Statement/Set.hsnew file+33
@@ -0,0 +1,33 @@
1+{-# language MonoLocalBinds #-}
2+{-# language NamedFieldPuns #-}
3+
4+module Rel8.Statement.Set
5+ ( ppSet
6+ )
7+where
8+
9+-- base
10+import Data.Foldable ( toList )
11+import Prelude ()
12+
13+-- opaleye
14+import qualified Opaleye.Internal.HaskellDB.Sql.Print as Opaleye
15+import qualified Opaleye.Internal.Sql as Opaleye
16+
17+-- pretty
18+import Text.PrettyPrint ( Doc, (<+>), equals, text )
19+
20+-- rel8
21+import Rel8.Schema.Name ( Selects, ppColumn )
22+import Rel8.Schema.Table ( TableSchema(..) )
23+import Rel8.Table.Opaleye ( attributes, exprsWithNames )
24+
25+
26+ppSet :: Selects names exprs
27+ => TableSchema names -> (exprs -> exprs) -> Doc
28+ppSet schema@TableSchema {columns} f =
29+ text "SET" <+> Opaleye.commaV ppAssign (toList assigns)
30+ where
31+ assigns = exprsWithNames columns (f (attributes schema))
32+ ppAssign (column, expr) =
33+ ppColumn column <+> equals <+> Opaleye.ppSqlExpr (Opaleye.sqlExpr expr)
src/Rel8/Statement/Update.hs+38−56
@@ -1,39 +1,37 @@
1+{-# language DuplicateRecordFields #-}
1{-# language GADTs #-}
2{-# language GADTs #-}
2{-# language NamedFieldPuns #-}
3{-# language NamedFieldPuns #-}
3−{-# language ScopedTypeVariables #-}
4+{-# language RecordWildCards #-}
4{-# language StandaloneKindSignatures #-}
5{-# language StandaloneKindSignatures #-}
5−{-# language TypeApplications #-}
6+{-# language StrictData #-}
6
7
7module Rel8.Statement.Update
8module Rel8.Statement.Update
8 ( Update(..)
9 ( Update(..)
9 , update
10 , update
11+ , ppUpdate
10 )
12 )
11where
13where
12
14
13-- base
15-- base
14−import Control.Exception ( throwIO )
15import Data.Kind ( Type )
16import Data.Kind ( Type )
16import Prelude
17import Prelude
17
18
18-- hasql
19-- hasql
19−import Hasql.Connection ( Connection )
20−import qualified Hasql.Decoders as Hasql
21import qualified Hasql.Encoders as Hasql
20import qualified Hasql.Encoders as Hasql
22−import qualified Hasql.Session as Hasql
23import qualified Hasql.Statement as Hasql
21import qualified Hasql.Statement as Hasql
24
22
25−-- opaleye
23+-- pretty
26−import qualified Opaleye.Internal.Manipulation as Opaleye
24+import Text.PrettyPrint ( Doc, (<+>), ($$), text )
27
25
28-- rel8
26-- rel8
29import Rel8.Expr ( Expr )
27import Rel8.Expr ( Expr )
30−import Rel8.Expr.Opaleye ( toColumn, toPrimExpr )
28+import Rel8.Query ( Query )
31import Rel8.Schema.Name ( Selects )
29import Rel8.Schema.Name ( Selects )
32−import Rel8.Schema.Table ( TableSchema )
30+import Rel8.Schema.Table ( TableSchema(..), ppTable )
33−import Rel8.Statement.Returning ( Returning( Projection, NumberOfRowsAffected ) )
31+import Rel8.Statement.Returning ( Returning, decodeReturning, ppReturning )
34−import Rel8.Table.Cols ( fromCols, toCols )
32+import Rel8.Statement.Set ( ppSet )
35−import Rel8.Table.Opaleye ( castTable, table, unpackspec )
33+import Rel8.Statement.Using ( ppFrom )
36−import Rel8.Table.Serialize ( Serializable, parse )
34+import Rel8.Statement.Where ( ppWhere )
37
35
38-- text
36-- text
39import qualified Data.Text as Text
37import qualified Data.Text as Text
@@ -46,9 +44,12 @@ data Update a where
46 Update :: Selects names exprs =>
44 Update :: Selects names exprs =>
47 { target :: TableSchema names
45 { target :: TableSchema names
48 -- ^ Which table to update.
46 -- ^ Which table to update.
47+ , from :: Query from
48+ -- ^ @FROM@ clause — this can be used to join against other tables,
49+ -- and its results can be referenced in the @SET@ and @WHERE@ clauses.
49− , set :: exprs -> exprs
50+ , set :: from -> exprs -> exprs
50 -- ^ How to update each selected row.
51 -- ^ How to update each selected row.
51− , updateWhere :: exprs -> Expr Bool
52+ , updateWhere :: from -> exprs -> Expr Bool
52 -- ^ Which rows to select for update.
53 -- ^ Which rows to select for update.
53 , returning :: Returning names a
54 , returning :: Returning names a
54 -- ^ What to return from the @UPDATE@ statement.
55 -- ^ What to return from the @UPDATE@ statement.
@@ -56,46 +57,27 @@ data Update a where
56 -> Update a
57 -> Update a
57
58
58
59
59−-- | Run an @UPDATE@ statement.
60+ppUpdate :: Update a -> Doc
60−update :: Connection -> Update a -> IO a
61+ppUpdate Update {..} = case ppFrom from of
61−update c Update {target, set, updateWhere, returning} =
62+ Nothing ->
62− case returning of
63+ text "UPDATE" <+> ppTable target $$
63− NumberOfRowsAffected -> Hasql.run session c >>= either throwIO pure
64+ ppSet target id $$
64− where
65+ text "WHERE false"
65− session = Hasql.statement () statement
66+ Just (fromDoc, i) ->
66− statement = Hasql.Statement bytes params decode prepare
67+ text "UPDATE" <+> ppTable target $$
67− bytes = encodeUtf8 $ Text.pack sql
68+ ppSet target (set i) $$
68− params = Hasql.noParams
69+ fromDoc $$
69− decode = Hasql.rowsAffected
70+ ppWhere target (updateWhere i) $$
70− prepare = False
71+ ppReturning target returning
71− sql = Opaleye.arrangeUpdateSql target' set' where'
72− where
73− target' = table $ toCols <$> target
74− set' = toCols . set . fromCols
75− where' = toColumn . toPrimExpr . updateWhere . fromCols
76
72
77− Projection project -> Hasql.run session c >>= either throwIO pure
78− where
79− session = Hasql.statement () statement
80− statement = Hasql.Statement bytes params decode prepare
81− bytes = encodeUtf8 $ Text.pack sql
82− params = Hasql.noParams
83− decode = decoder project
84− prepare = False
85− sql =
86− Opaleye.arrangeUpdateReturningSql
87− unpackspec
88− target'
89− set'
90− where'
91− project'
92− where
93− target' = table $ toCols <$> target
94− set' = toCols . set . fromCols
95− where' = toColumn . toPrimExpr . updateWhere . fromCols
96− project' = castTable . toCols . project . fromCols
97
73
74+-- | Run an @UPDATE@ statement.
75+update :: Update a -> Hasql.Statement () a
76+update u@Update {returning} = Hasql.Statement bytes params decode prepare
98 where
77 where
99− decoder :: forall exprs projection a. Serializable projection a
78+ bytes = encodeUtf8 $ Text.pack sql
100− => (exprs -> projection) -> Hasql.Result [a]
79+ params = Hasql.noParams
101− decoder _ = Hasql.rowList (parse @projection @a)
80+ decode = decodeReturning returning
81+ prepare = False
82+ sql = show doc
83+ doc = ppUpdate u
src/Rel8/Statement/Using.hsnew file+36
@@ -0,0 +1,36 @@
1+module Rel8.Statement.Using
2+ ( ppFrom
3+ , ppUsing
4+ )
5+where
6+
7+-- base
8+import Prelude
9+
10+-- pretty
11+import Text.PrettyPrint ( Doc, (<+>), parens, text )
12+
13+-- rel8
14+import Rel8.Query ( Query )
15+import Rel8.Schema.Table ( TableSchema(..), ppTable )
16+import Rel8.Statement.Select ( Optimized(..), ppPrimSelect )
17+
18+
19+ppFrom :: Query a -> Maybe (Doc, a)
20+ppFrom = ppJoin "FROM"
21+
22+
23+ppUsing :: Query a -> Maybe (Doc, a)
24+ppUsing = ppJoin "USING"
25+
26+
27+ppJoin :: String -> Query a -> Maybe (Doc, a)
28+ppJoin clause join = do
29+ doc <- case ofrom of
30+ Empty -> Nothing
31+ Unit -> Just mempty
32+ Optimized doc -> Just $ text clause <+> parens doc <+> ppTable alias
33+ pure (doc, a)
34+ where
35+ alias = TableSchema {name = "T1", schema = Nothing, columns = ()}
36+ (ofrom, a) = ppPrimSelect join
src/Rel8/Statement/View.hs+43−28
@@ -3,61 +3,76 @@
3
3
4module Rel8.Statement.View
4module Rel8.Statement.View
5 ( createView
5 ( createView
6+ , createOrReplaceView
6 )
7 )
7where
8where
8
9
9-- base
10-- base
10−import Control.Exception ( throwIO )
11−import Control.Monad ( (>=>) )
12−import Data.Foldable ( fold )
13−import Data.Maybe ( fromMaybe )
14import Prelude
11import Prelude
15
12
16-- hasql
13-- hasql
17−import Hasql.Connection ( Connection )
18import qualified Hasql.Decoders as Hasql
14import qualified Hasql.Decoders as Hasql
19import qualified Hasql.Encoders as Hasql
15import qualified Hasql.Encoders as Hasql
20−import qualified Hasql.Session as Hasql
21import qualified Hasql.Statement as Hasql
16import qualified Hasql.Statement as Hasql
22
17
23-- rel8
18-- rel8
24import Rel8.Query ( Query )
19import Rel8.Query ( Query )
25−import Rel8.Query.SQL ( sqlForQueryWithNames )
26import Rel8.Schema.Name ( Selects )
20import Rel8.Schema.Name ( Selects )
27−import Rel8.Schema.Table ( TableSchema( TableSchema ) )
21+import Rel8.Schema.Table ( TableSchema )
28−import Rel8.Table.Alternative ( emptyTable )
22+import Rel8.Statement.Insert ( ppInto )
23+import Rel8.Statement.Select ( ppSelect )
24+
25+-- pretty
26+import Text.PrettyPrint ( Doc, (<+>), ($$), text )
29
27
30-- text
28-- text
31import qualified Data.Text as Text
29import qualified Data.Text as Text
32import Data.Text.Encoding ( encodeUtf8 )
30import Data.Text.Encoding ( encodeUtf8 )
33
31
34
32
33+data CreateView = Create | CreateOrReplace
34+
35+
35-- | Given a 'TableSchema' and 'Query', @createView@ runs a @CREATE VIEW@
36-- | Given a 'TableSchema' and 'Query', @createView@ runs a @CREATE VIEW@
36-- statement that will save the given query as a view. This can be useful if
37-- statement that will save the given query as a view. This can be useful if
37-- you want to share Rel8 queries with other applications.
38-- you want to share Rel8 queries with other applications.
38createView :: Selects names exprs
39createView :: Selects names exprs
39− => TableSchema names -> Query exprs -> Connection -> IO ()
40+ => TableSchema names -> Query exprs -> Hasql.Statement () ()
40−createView (TableSchema name mschema names) query =
41+createView =
41− Hasql.run session >=> either throwIO pure
42+ createViewGeneric Create
43+
44+
45+-- | Given a 'TableSchema' and 'Query', @createOrReplaceView@ runs a
46+-- @CREATE OR REPLACE VIEW@ statement that will save the given query
47+-- as a view, replacing the current view definition if it exists and
48+-- adheres to the restrictions in place for replacing a view in
49+-- PostgreSQL.
50+createOrReplaceView :: Selects names exprs
51+ => TableSchema names -> Query exprs -> Hasql.Statement () ()
52+createOrReplaceView =
53+ createViewGeneric CreateOrReplace
54+
55+
56+createViewGeneric :: Selects names exprs
57+ => CreateView -> TableSchema names -> Query exprs -> Hasql.Statement () ()
58+createViewGeneric replace schema query =
59+ Hasql.Statement bytes params decode prepare
42 where
60 where
43− session = Hasql.statement () statement
44− statement = Hasql.Statement bytes params decode prepare
45 bytes = encodeUtf8 (Text.pack sql)
61 bytes = encodeUtf8 (Text.pack sql)
46 params = Hasql.noParams
62 params = Hasql.noParams
47 decode = Hasql.noResult
63 decode = Hasql.noResult
48 prepare = False
64 prepare = False
49− sql = "CREATE VIEW " <> title <> " AS " <> select
65+ sql = show doc
50− where
66+ doc = ppCreateView schema query replace
51− title = case mschema of
67+
52− Nothing -> quote name
68+
53− Just schema -> quote schema <> "." <> quote name
69+ppCreateView :: Selects names exprs
54− select = fromMaybe fallback $ sqlForQueryWithNames names query
70+ => TableSchema names -> Query exprs -> CreateView -> Doc
55− where
71+ppCreateView schema query replace =
56− fallback = fold $ sqlForQueryWithNames names emptyTable
72+ createOrReplace replace <+>
57−
73+ ppInto schema $$
58−
74+ text "AS" <+>
59−quote :: String -> String
75+ ppSelect query
60−quote string = "\"" <> concatMap go string <> "\""
61 where
76 where
62− go '"' = "\"\""
77+ createOrReplace Create = text "CREATE VIEW"
63− go c = [c]
78+ createOrReplace CreateOrReplace = text "CREATE OR REPLACE VIEW"
src/Rel8/Statement/Where.hsnew file+31
@@ -0,0 +1,31 @@
1+{-# language MonoLocalBinds #-}
2+
3+module Rel8.Statement.Where
4+ ( ppWhere
5+ )
6+where
7+
8+-- base
9+import Prelude
10+
11+-- opaleye
12+import qualified Opaleye.Internal.HaskellDB.Sql.Print as Opaleye
13+import qualified Opaleye.Internal.Sql as Opaleye
14+
15+-- pretty
16+import Text.PrettyPrint ( Doc, (<+>), text )
17+
18+-- rel8
19+import Rel8.Expr ( Expr )
20+import Rel8.Expr.Opaleye ( toPrimExpr )
21+import Rel8.Schema.Name ( Selects )
22+import Rel8.Schema.Table ( TableSchema )
23+import Rel8.Table.Opaleye ( attributes )
24+
25+
26+ppWhere :: Selects names exprs
27+ => TableSchema names -> (exprs -> Expr Bool) -> Doc
28+ppWhere schema where_ = text "WHERE" <+> ppExpr condition
29+ where
30+ ppExpr = Opaleye.ppSqlExpr . Opaleye.sqlExpr . toPrimExpr
31+ condition = where_ (attributes schema)
src/Rel8/Table.hs+50−52
@@ -14,30 +14,34 @@ module Rel8.Table
14 ( Table
14 ( Table
15 ( Columns, Context, fromColumns, toColumns
15 ( Columns, Context, fromColumns, toColumns
16 , FromExprs, fromResult, toResult
16 , FromExprs, fromResult, toResult
17+ , Transpose
17 )
18 )
18 , Congruent
19 , Congruent
19− , TTable, TColumns, TContext, TFromExprs
20+ , TTable, TColumns, TContext, TFromExprs, TTranspose
21+ , TSerialize
20 )
22 )
21where
23where
22
24
23-- base
25-- base
26+import Data.Functor.Identity ( Identity( Identity ) )
24import Data.Kind ( Constraint, Type )
27import Data.Kind ( Constraint, Type )
25import GHC.Generics ( Generic, Rep, from, to )
28import GHC.Generics ( Generic, Rep, from, to )
26import Prelude hiding ( null )
29import Prelude hiding ( null )
27
30
28-- rel8
31-- rel8
29import Rel8.FCF ( Eval, Exp )
32import Rel8.FCF ( Eval, Exp )
30−import Rel8.Generic.Map ( GMap )
33+import Rel8.Generic.Map ( Map )
31import Rel8.Generic.Table.Record
34import Rel8.Generic.Table.Record
32− ( GTable, GColumns, GContext
35+ ( GTable, GColumns, GContext, gfromColumns, gtoColumns
33− , gfromColumns, gtoColumns, gfromResult, gtoResult
36+ , GSerialize, gfromResult, gtoResult
34 )
37 )
35import Rel8.Generic.Record ( Record(..) )
38import Rel8.Generic.Record ( Record(..) )
36import Rel8.Schema.HTable ( HTable )
39import Rel8.Schema.HTable ( HTable )
37−import Rel8.Schema.HTable.Identity ( HIdentity(..) )
40+import Rel8.Schema.HTable.Identity ( HIdentity( HIdentity ) )
38import qualified Rel8.Schema.Kind as K
41import qualified Rel8.Schema.Kind as K
42+import Rel8.Schema.Null ( Sql )
39import Rel8.Schema.Result ( Result )
43import Rel8.Schema.Result ( Result )
40−import Rel8.Schema.Spec ( KnownSpec )
44+import Rel8.Type ( DBType )
41
45
42
46
43-- | @Table@s are one of the foundational elements of Rel8, and describe data
47-- | @Table@s are one of the foundational elements of Rel8, and describe data
@@ -52,7 +56,13 @@ import Rel8.Schema.Spec ( KnownSpec )
52-- yourself, as anything that's an instance of 'Rel8.Rel8able' is always a
56-- yourself, as anything that's an instance of 'Rel8.Rel8able' is always a
53-- 'Table'.
57-- 'Table'.
54type Table :: K.Context -> Type -> Constraint
58type Table :: K.Context -> Type -> Constraint
59+class
60+ ( HTable (Columns a)
61+ , context ~ Context a
62+ , a ~ Transpose context a
63+ )
55−class (HTable (Columns a), context ~ Context a) => Table context a | a -> context where
64+ => Table context a | a -> context
65+ where
56 -- | The 'HTable' functor that describes the schema of this table.
66 -- | The 'HTable' functor that describes the schema of this table.
57 type Columns a :: K.HTable
67 type Columns a :: K.HTable
58
68
@@ -63,6 +73,9 @@ class (HTable (Columns a), context ~ Context a) => Table context a | a -> contex
63 -- corresponding Haskell type.
73 -- corresponding Haskell type.
64 type FromExprs a :: Type
74 type FromExprs a :: Type
65
75
76+ type Transpose (context' :: K.Context) a :: Type
77+
78+
66 toColumns :: a -> Columns a context
79 toColumns :: a -> Columns a context
67 fromColumns :: Columns a context -> a
80 fromColumns :: Columns a context -> a
68
81
@@ -71,88 +84,74 @@ class (HTable (Columns a), context ~ Context a) => Table context a | a -> contex
71
84
72 type Columns a = GColumns TColumns (Rep (Record a))
85 type Columns a = GColumns TColumns (Rep (Record a))
73 type Context a = GContext TContext (Rep (Record a))
86 type Context a = GContext TContext (Rep (Record a))
74− type FromExprs a = DefaultFromExprs a
87+ type FromExprs a = Map TFromExprs a
88+ type Transpose context a = Map (TTranspose context) a
75
89
76 default toColumns ::
90 default toColumns ::
77 ( Generic (Record a)
91 ( Generic (Record a)
78− , GTable (TTable context) TColumns TFromExprs (Rep (Record a))
92+ , GTable (TTable context) TColumns (Rep (Record a))
79 , Columns a ~ GColumns TColumns (Rep (Record a))
93 , Columns a ~ GColumns TColumns (Rep (Record a))
80 )
94 )
81 => a -> Columns a context
95 => a -> Columns a context
82 toColumns =
96 toColumns =
83− gtoColumns
84− @(TTable context)
97+ gtoColumns @(TTable context) @TColumns toColumns .
85− @TColumns
86− @TFromExprs
87− toColumns .
88 from .
98 from .
89 Record
99 Record
90
100
91 default fromColumns ::
101 default fromColumns ::
92 ( Generic (Record a)
102 ( Generic (Record a)
93− , GTable (TTable context) TColumns TFromExprs (Rep (Record a))
103+ , GTable (TTable context) TColumns (Rep (Record a))
94 , Columns a ~ GColumns TColumns (Rep (Record a))
104 , Columns a ~ GColumns TColumns (Rep (Record a))
95 )
105 )
96 => Columns a context -> a
106 => Columns a context -> a
97 fromColumns =
107 fromColumns =
98 unrecord .
108 unrecord .
99 to .
109 to .
100− gfromColumns
101− @(TTable context)
110+ gfromColumns @(TTable context) @TColumns fromColumns
102− @TColumns
103− @TFromExprs
104− fromColumns
105
111
106 default toResult ::
112 default toResult ::
107 ( Generic (Record (FromExprs a))
113 ( Generic (Record (FromExprs a))
108− , GTable (TTable context) TColumns TFromExprs (Rep (Record a))
114+ , GSerialize TSerialize TColumns (Rep (Record a)) (Rep (Record (FromExprs a)))
109 , Columns a ~ GColumns TColumns (Rep (Record a))
115 , Columns a ~ GColumns TColumns (Rep (Record a))
110− , Rep (Record (FromExprs a)) ~ GMap TFromExprs (Rep (Record a))
111 )
116 )
112 => FromExprs a -> Columns a Result
117 => FromExprs a -> Columns a Result
113 toResult =
118 toResult =
114 gtoResult
119 gtoResult
115− @(TTable context)
120+ @TSerialize
116 @TColumns
121 @TColumns
117− @TFromExprs
118 @(Rep (Record a))
122 @(Rep (Record a))
123+ @(Rep (Record (FromExprs a)))
119 (\(_ :: proxy x) -> toResult @(Context x) @x) .
124 (\(_ :: proxy x) -> toResult @(Context x) @x) .
120 from .
125 from .
121 Record
126 Record
122
127
123 default fromResult ::
128 default fromResult ::
124 ( Generic (Record (FromExprs a))
129 ( Generic (Record (FromExprs a))
125− , GTable (TTable context) TColumns TFromExprs (Rep (Record a))
130+ , GSerialize TSerialize TColumns (Rep (Record a)) (Rep (Record (FromExprs a)))
126 , Columns a ~ GColumns TColumns (Rep (Record a))
131 , Columns a ~ GColumns TColumns (Rep (Record a))
127− , Rep (Record (FromExprs a)) ~ GMap TFromExprs (Rep (Record a))
128 )
132 )
129 => Columns a Result -> FromExprs a
133 => Columns a Result -> FromExprs a
130 fromResult =
134 fromResult =
131 unrecord .
135 unrecord .
132 to .
136 to .
133 gfromResult
137 gfromResult
134− @(TTable context)
138+ @TSerialize
135 @TColumns
139 @TColumns
136− @TFromExprs
137 @(Rep (Record a))
140 @(Rep (Record a))
141+ @(Rep (Record (FromExprs a)))
138 (\(_ :: proxy x) -> fromResult @(Context x) @x)
142 (\(_ :: proxy x) -> fromResult @(Context x) @x)
139
143
140
144
141−type DefaultFromExprs :: Type -> Type
145+instance Sql DBType a => Table Result (Identity a) where
142−type family DefaultFromExprs a where
146+ type Columns (Identity a) = HIdentity a
143− DefaultFromExprs (t a b c d e f g) =
147+ type Context (Identity a) = Result
144− t (FromExprs a) (FromExprs b) (FromExprs c) (FromExprs d) (FromExprs e)
145− (FromExprs f) (FromExprs g)
148+ type FromExprs (Identity a) = a
146− DefaultFromExprs (t a b c d e f) =
149+ type Transpose to (Identity a) = to a
147− t (FromExprs a) (FromExprs b) (FromExprs c) (FromExprs d) (FromExprs e)
150+
148− (FromExprs f)
151+ toColumns = HIdentity
149− DefaultFromExprs (t a b c d e) =
152+ fromColumns (HIdentity a) = a
150− t (FromExprs a) (FromExprs b) (FromExprs c) (FromExprs d) (FromExprs e)
153+ toResult a = HIdentity (Identity a)
151− DefaultFromExprs (t a b c d) =
154+ fromResult (HIdentity (Identity a)) = a
152− t (FromExprs a) (FromExprs b) (FromExprs c) (FromExprs d)
153− DefaultFromExprs (t a b c) = t (FromExprs a) (FromExprs b) (FromExprs c)
154− DefaultFromExprs (t a b) = t (FromExprs a) (FromExprs b)
155− DefaultFromExprs (t a) = t (FromExprs a)
156
155
157
156
158data TTable :: K.Context -> Type -> Exp Constraint
157data TTable :: K.Context -> Type -> Exp Constraint
@@ -171,16 +170,15 @@ data TFromExprs :: Type -> Exp Type
171type instance Eval (TFromExprs a) = FromExprs a
170type instance Eval (TFromExprs a) = FromExprs a
172
171
173
172
174−-- | Any context is trivially a table.
173+data TTranspose :: K.Context -> Type -> Exp Type
175−instance KnownSpec spec => Table context (context spec) where
174+type instance Eval (TTranspose context a) = Transpose context a
176− type Columns (context spec) = HIdentity spec
177− type Context (context spec) = context
178− type FromExprs (context spec) = Result spec
179
175
180− toColumns = HIdentity
176+
181− fromColumns = unHIdentity
177+data TSerialize :: Type -> Type -> Exp Constraint
182− toResult = HIdentity
178+type instance Eval (TSerialize expr a) =
183− fromResult = unHIdentity
179+ ( Table (Context expr) expr
180+ , a ~ FromExprs expr
181+ )
184
182
185
183
186instance (Table context a, Table context b) => Table context (a, b)
184instance (Table context a, Table context b) => Table context (a, b)
src/Rel8/Table/ADT.hs+13−25
@@ -7,7 +7,6 @@
7{-# language ScopedTypeVariables #-}
7{-# language ScopedTypeVariables #-}
8{-# language StandaloneKindSignatures #-}
8{-# language StandaloneKindSignatures #-}
9{-# language TypeApplications #-}
9{-# language TypeApplications #-}
10−{-# language TypeFamilies #-}
11{-# language TypeFamilyDependencies #-}
10{-# language TypeFamilyDependencies #-}
12{-# language UndecidableInstances #-}
11{-# language UndecidableInstances #-}
13{-# language UndecidableSuperClasses #-}
12{-# language UndecidableSuperClasses #-}
@@ -28,7 +27,7 @@ where
28
27
29-- base
28-- base
30import Data.Kind ( Constraint, Type )
29import Data.Kind ( Constraint, Type )
31−import GHC.Generics ( Generic, Rep, from, to )
30+import GHC.Generics ( Generic, from, to )
32import GHC.TypeLits ( Symbol )
31import GHC.TypeLits ( Symbol )
33import Prelude
32import Prelude
34
33
@@ -45,24 +44,20 @@ import Rel8.Generic.Construction
45 , GGName, ggname
44 , GGName, ggname
46 , GGAggregate, ggaggregate
45 , GGAggregate, ggaggregate
47 )
46 )
48−import Rel8.Generic.Map ( GMap )
49import Rel8.Generic.Record ( Record( Record ), unrecord )
47import Rel8.Generic.Record ( Record( Record ), unrecord )
50import Rel8.Generic.Rel8able
48import Rel8.Generic.Rel8able
51 ( Rel8able
49 ( Rel8able
52 , GRep, GColumns, gfromColumns, gtoColumns
50 , GRep, GColumns, gfromColumns, gtoColumns
53 , GFromExprs, gfromResult, gtoResult
51 , GFromExprs, gfromResult, gtoResult
52+ , TSerialize, deserialize, serialize
54 )
53 )
55import qualified Rel8.Generic.Table.ADT as G
54import qualified Rel8.Generic.Table.ADT as G
56import qualified Rel8.Kind.Algebra as K
55import qualified Rel8.Kind.Algebra as K
57−import Rel8.Schema.Context.Virtual
58import Rel8.Schema.HTable ( HTable )
56import Rel8.Schema.HTable ( HTable )
59import qualified Rel8.Schema.Kind as K
57import qualified Rel8.Schema.Kind as K
60import Rel8.Schema.Name ( Name )
58import Rel8.Schema.Name ( Name )
61import Rel8.Schema.Result ( Result )
59import Rel8.Schema.Result ( Result )
62−import Rel8.Table
60+import Rel8.Table ( Table, TColumns )
63− ( Table, fromResult, toResult
64− , TTable, TColumns, TFromExprs
65− )
66
61
67
62
68type ADT :: K.Rel8able -> K.Rel8able
63type ADT :: K.Rel8able -> K.Rel8able
@@ -73,31 +68,26 @@ instance ADTable t => Rel8able (ADT t) where
73 type GColumns (ADT t) = GColumnsADT t
68 type GColumns (ADT t) = GColumnsADT t
74 type GFromExprs (ADT t) = t Result
69 type GFromExprs (ADT t) = t Result
75
70
76− gfromColumns VAggregate = ADT
71+ gfromColumns _ = ADT
77− gfromColumns VExpr = ADT
78− gfromColumns VName = ADT
79−
80− gtoColumns VAggregate (ADT a) = a
81− gtoColumns VExpr (ADT a) = a
82− gtoColumns VName (ADT a) = a
72+ gtoColumns _ (ADT a) = a
83
73
84 gfromResult =
74 gfromResult =
85 unrecord .
75 unrecord .
86 to .
76 to .
87 G.gfromResultADT
77 G.gfromResultADT
88− @(TTable Expr)
78+ @TSerialize
89 @TColumns
79 @TColumns
90− @TFromExprs
91 @(Eval (ADTRep t Expr))
80 @(Eval (ADTRep t Expr))
81+ @(Eval (ADTRep t Result))
92− (\(_ :: proxy x) -> fromResult @_ @x)
82+ (\(_ :: proxy x) -> deserialize @_ @x)
93
83
94 gtoResult =
84 gtoResult =
95 G.gtoResultADT
85 G.gtoResultADT
96− @(TTable Expr)
86+ @TSerialize
97 @TColumns
87 @TColumns
98− @TFromExprs
99 @(Eval (ADTRep t Expr))
88 @(Eval (ADTRep t Expr))
89+ @(Eval (ADTRep t Result))
100− (\(_ :: proxy x) -> toResult @_ @x) .
90+ (\(_ :: proxy x) -> serialize @_ @x) .
101 from .
91 from .
102 Record
92 Record
103
93
@@ -106,15 +96,13 @@ type ADTable :: K.Rel8able -> Constraint
106class
96class
107 ( Generic (Record (t Result))
97 ( Generic (Record (t Result))
108 , HTable (GColumnsADT t)
98 , HTable (GColumnsADT t)
109− , G.GTableADT (TTable Expr) TColumns TFromExprs (Eval (ADTRep t Expr))
99+ , G.GSerializeADT TSerialize TColumns (Eval (ADTRep t Expr)) (Eval (ADTRep t Result))
110− , GMap TFromExprs (Rep (Record (t Expr))) ~ Rep (Record (t Result))
111 )
100 )
112 => ADTable t
101 => ADTable t
113instance
102instance
114 ( Generic (Record (t Result))
103 ( Generic (Record (t Result))
115 , HTable (GColumnsADT t)
104 , HTable (GColumnsADT t)
116− , G.GTableADT (TTable Expr) TColumns TFromExprs (Eval (ADTRep t Expr))
105+ , G.GSerializeADT TSerialize TColumns (Eval (ADTRep t Expr)) (Eval (ADTRep t Result))
117− , GMap TFromExprs (Rep (Record (t Expr))) ~ Rep (Record (t Result))
118 )
106 )
119 => ADTable t
107 => ADTable t
120
108
src/Rel8/Table/Aggregate.hs+19−9
@@ -16,8 +16,8 @@ import Data.Functor.Identity ( Identity( Identity ) )
16import Prelude
16import Prelude
17
17
18-- rel8
18-- rel8
19−import Rel8.Aggregate ( Aggregate( A ), Aggregates )
19+import Rel8.Aggregate ( Aggregate, Aggregates )
20−import Rel8.Expr ( Expr( E ) )
20+import Rel8.Expr ( Expr )
21import Rel8.Expr.Aggregate
21import Rel8.Expr.Aggregate
22 ( groupByExpr
22 ( groupByExpr
23 , slistAggExpr
23 , slistAggExpr
@@ -27,8 +27,7 @@ import Rel8.Schema.Dict ( Dict( Dict ) )
27import Rel8.Schema.HTable ( HTable, hfield, htabulate )
27import Rel8.Schema.HTable ( HTable, hfield, htabulate )
28import Rel8.Schema.HTable.Vectorize ( hvectorize )
28import Rel8.Schema.HTable.Vectorize ( hvectorize )
29import Rel8.Schema.Null ( Sql )
29import Rel8.Schema.Null ( Sql )
30−import Rel8.Schema.Spec ( SSpec( SSpec, info ) )
30+import Rel8.Schema.Spec ( Spec( Spec, info ) )
31−import Rel8.Schema.Spec.Constrain ( ConstrainSpec )
32import Rel8.Table ( toColumns, fromColumns )
31import Rel8.Table ( toColumns, fromColumns )
33import Rel8.Table.Eq ( EqTable, eqTable )
32import Rel8.Table.Eq ( EqTable, eqTable )
34import Rel8.Table.List ( ListTable )
33import Rel8.Table.List ( ListTable )
@@ -38,17 +37,28 @@ import Rel8.Type.Eq ( DBEq )
38
37
39-- | Group equal tables together. This works by aggregating each column in the
38-- | Group equal tables together. This works by aggregating each column in the
40-- given table with 'groupByExpr'.
39-- given table with 'groupByExpr'.
40+--
41+-- For example, if we have a table of items, we could group the items by the
42+-- order they belong to:
43+--
44+-- @
45+-- itemsByOrder :: Query (OrderId Expr, ListTable Expr (Item Expr))
46+-- itemsByOrder = aggregate $ do
47+-- item <- each itemSchema
48+-- let orderId = groupBy (itemOrderId item)
49+-- let orderItems = listAgg item
50+-- pure (orderId, orderItems)
51+-- @
41groupBy :: forall exprs aggregates. (EqTable exprs, Aggregates aggregates exprs)
52groupBy :: forall exprs aggregates. (EqTable exprs, Aggregates aggregates exprs)
42 => exprs -> aggregates
53 => exprs -> aggregates
43groupBy = fromColumns . hgroupBy (eqTable @exprs) . toColumns
54groupBy = fromColumns . hgroupBy (eqTable @exprs) . toColumns
44
55
45
56
46−hgroupBy :: HTable t
47− => t (Dict (ConstrainSpec (Sql DBEq))) -> t Expr -> t Aggregate
57+hgroupBy :: HTable t => t (Dict (Sql DBEq)) -> t Expr -> t Aggregate
48hgroupBy eqs exprs = htabulate $ \field ->
58hgroupBy eqs exprs = htabulate $ \field ->
49 case hfield eqs field of
59 case hfield eqs field of
50 Dict -> case hfield exprs field of
60 Dict -> case hfield exprs field of
51− E expr -> A $ groupByExpr expr
61+ expr -> groupByExpr expr
52
62
53
63
54-- | Aggregate rows into a single row containing an array of all aggregated
64-- | Aggregate rows into a single row containing an array of all aggregated
@@ -70,7 +80,7 @@ hgroupBy eqs exprs = htabulate $ \field ->
70listAgg :: Aggregates aggregates exprs => exprs -> ListTable Aggregate aggregates
80listAgg :: Aggregates aggregates exprs => exprs -> ListTable Aggregate aggregates
71listAgg (toColumns -> exprs) = fromColumns $
81listAgg (toColumns -> exprs) = fromColumns $
72 hvectorize
82 hvectorize
73− (\SSpec {info} (Identity (E a)) -> A $ slistAggExpr info a)
83+ (\Spec {info} (Identity a) -> slistAggExpr info a)
74 (pure exprs)
84 (pure exprs)
75
85
76
86
@@ -78,5 +88,5 @@ listAgg (toColumns -> exprs) = fromColumns $
78nonEmptyAgg :: Aggregates aggregates exprs => exprs -> NonEmptyTable Aggregate aggregates
88nonEmptyAgg :: Aggregates aggregates exprs => exprs -> NonEmptyTable Aggregate aggregates
79nonEmptyAgg (toColumns -> exprs) = fromColumns $
89nonEmptyAgg (toColumns -> exprs) = fromColumns $
80 hvectorize
90 hvectorize
81− (\SSpec {info} (Identity (E a)) -> A $ snonEmptyAggExpr info a)
91+ (\Spec {info} (Identity a) -> snonEmptyAggExpr info a)
82 (pure exprs)
92 (pure exprs)
src/Rel8/Table/Bool.hs+5−6
@@ -13,7 +13,7 @@ where
13import Prelude
13import Prelude
14
14
15-- rel8
15-- rel8
16−import Rel8.Expr ( Expr( E, unE ) )
16+import Rel8.Expr ( Expr )
17import Rel8.Expr.Bool ( boolExpr, caseExpr )
17import Rel8.Expr.Bool ( boolExpr, caseExpr )
18import Rel8.Expr.Null ( isNull, unsafeUnnullify )
18import Rel8.Expr.Null ( isNull, unsafeUnnullify )
19import Rel8.Schema.HTable ( htabulate, hfield )
19import Rel8.Schema.HTable ( htabulate, hfield )
@@ -28,8 +28,7 @@ bool :: Table Expr a => a -> a -> Expr Bool -> a
28bool (toColumns -> false) (toColumns -> true) condition =
28bool (toColumns -> false) (toColumns -> true) condition =
29 fromColumns $ htabulate $ \field ->
29 fromColumns $ htabulate $ \field ->
30 case (hfield false field, hfield true field) of
30 case (hfield false field, hfield true field) of
31− (E falseExpr, E trueExpr) ->
32− E (boolExpr falseExpr trueExpr condition)
31+ (falseExpr, trueExpr) -> boolExpr falseExpr trueExpr condition
33{-# INLINABLE bool #-}
32{-# INLINABLE bool #-}
34
33
35
34
@@ -39,9 +38,9 @@ bool (toColumns -> false) (toColumns -> true) condition =
39case_ :: Table Expr a => [(Expr Bool, a)] -> a -> a
38case_ :: Table Expr a => [(Expr Bool, a)] -> a -> a
40case_ (map (fmap toColumns) -> branches) (toColumns -> fallback) =
39case_ (map (fmap toColumns) -> branches) (toColumns -> fallback) =
41 fromColumns $ htabulate $ \field -> case hfield fallback field of
40 fromColumns $ htabulate $ \field -> case hfield fallback field of
42− E fallbackExpr ->
41+ fallbackExpr ->
43− case map (fmap (unE . (`hfield` field))) branches of
42+ case map (fmap (`hfield` field)) branches of
44− branchExprs -> E (caseExpr branchExprs fallbackExpr)
43+ branchExprs -> caseExpr branchExprs fallbackExpr
45
44
46
45
47-- | Like 'maybe', but to eliminate @null@.
46-- | Like 'maybe', but to eliminate @null@.
src/Rel8/Table/Cols.hs+1−4
@@ -21,7 +21,6 @@ import qualified Rel8.Schema.Kind as K
21import Rel8.Schema.HTable ( HTable )
21import Rel8.Schema.HTable ( HTable )
22import Rel8.Schema.Result ( Result )
22import Rel8.Schema.Result ( Result )
23import Rel8.Table ( Table(..) )
23import Rel8.Table ( Table(..) )
24−import Rel8.Table.Recontextualize ( Recontextualize )
25
24
26
25
27type Cols :: K.Context -> K.HTable -> Type
26type Cols :: K.Context -> K.HTable -> Type
@@ -34,6 +33,7 @@ instance (HTable columns, context ~ context') =>
34 type Columns (Cols context columns) = columns
33 type Columns (Cols context columns) = columns
35 type Context (Cols context columns) = context
34 type Context (Cols context columns) = context
36 type FromExprs (Cols context columns) = Cols Result columns
35 type FromExprs (Cols context columns) = Cols Result columns
36+ type Transpose to (Cols context columns) = Cols to columns
37
37
38 toColumns (Cols a) = a
38 toColumns (Cols a) = a
39 fromColumns = Cols
39 fromColumns = Cols
@@ -42,9 +42,6 @@ instance (HTable columns, context ~ context') =>
42 fromResult = Cols
42 fromResult = Cols
43
43
44
44
45−instance HTable t => Recontextualize from to (Cols from t) (Cols to t)
46−
47−
48fromCols :: Table context a => Cols context (Columns a) -> a
45fromCols :: Table context a => Cols context (Columns a) -> a
49fromCols (Cols a) = fromColumns a
46fromCols (Cols a) = fromColumns a
50
47
src/Rel8/Table/Either.hs+37−35
@@ -25,6 +25,7 @@ where
25
25
26-- base
26-- base
27import Data.Bifunctor ( Bifunctor, bimap )
27import Data.Bifunctor ( Bifunctor, bimap )
28+import Data.Functor.Identity ( Identity( Identity ) )
28import Data.Kind ( Type )
29import Data.Kind ( Type )
29import Prelude hiding ( undefined )
30import Prelude hiding ( undefined )
30
31
@@ -32,8 +33,8 @@ import Prelude hiding ( undefined )
32import Control.Comonad ( extract )
33import Control.Comonad ( extract )
33
34
34-- rel8
35-- rel8
35−import Rel8.Aggregate ( Aggregate( A ) )
36+import Rel8.Aggregate ( Aggregate )
36−import Rel8.Expr ( Expr( E ) )
37+import Rel8.Expr ( Expr )
37import Rel8.Expr.Aggregate ( groupByExpr )
38import Rel8.Expr.Aggregate ( groupByExpr )
38import Rel8.Expr.Serialize ( litExpr )
39import Rel8.Expr.Serialize ( litExpr )
39import Rel8.Kind.Context ( Reifiable )
40import Rel8.Kind.Context ( Reifiable )
@@ -43,18 +44,17 @@ import Rel8.Schema.HTable.Either ( HEitherTable(..) )
43import Rel8.Schema.HTable.Identity ( HIdentity(..) )
44import Rel8.Schema.HTable.Identity ( HIdentity(..) )
44import Rel8.Schema.HTable.Label ( hlabel, hunlabel )
45import Rel8.Schema.HTable.Label ( hlabel, hunlabel )
45import qualified Rel8.Schema.Kind as K
46import qualified Rel8.Schema.Kind as K
46−import Rel8.Schema.Name ( Name( N ) )
47+import Rel8.Schema.Name ( Name )
47−import Rel8.Schema.Result ( Result( R ) )
48−import Rel8.Schema.Spec ( Spec( Spec ) )
49import Rel8.Table
48import Rel8.Table
50 ( Table, Columns, Context, fromColumns, toColumns
49 ( Table, Columns, Context, fromColumns, toColumns
51 , FromExprs, fromResult, toResult
50 , FromExprs, fromResult, toResult
51+ , Transpose
52 )
52 )
53import Rel8.Table.Bool ( bool )
53import Rel8.Table.Bool ( bool )
54import Rel8.Table.Eq ( EqTable, eqTable )
54import Rel8.Table.Eq ( EqTable, eqTable )
55import Rel8.Table.Nullify ( Nullify, aggregateNullify, guard )
55import Rel8.Table.Nullify ( Nullify, aggregateNullify, guard )
56import Rel8.Table.Ord ( OrdTable, ordTable )
56import Rel8.Table.Ord ( OrdTable, ordTable )
57−import Rel8.Table.Recontextualize ( Recontextualize )
57+import Rel8.Table.Projection ( Biprojectable, Projectable, biproject, project )
58import Rel8.Table.Serialize ( ToExprs )
58import Rel8.Table.Serialize ( ToExprs )
59import Rel8.Table.Undefined ( undefined )
59import Rel8.Table.Undefined ( undefined )
60import Rel8.Type.Tag ( EitherTag( IsLeft, IsRight ), isLeft, isRight )
60import Rel8.Type.Tag ( EitherTag( IsLeft, IsRight ), isLeft, isRight )
@@ -72,20 +72,29 @@ import Data.Functor.Bind ( Bind, (>>-) )
72-- adapted to work with Rel8.
72-- adapted to work with Rel8.
73type EitherTable :: K.Context -> Type -> Type -> Type
73type EitherTable :: K.Context -> Type -> Type -> Type
74data EitherTable context a b = EitherTable
74data EitherTable context a b = EitherTable
75− { tag :: context ('Spec EitherTag)
75+ { tag :: context EitherTag
76 , left :: Nullify context a
76 , left :: Nullify context a
77 , right :: Nullify context b
77 , right :: Nullify context b
78 }
78 }
79 deriving stock Functor
79 deriving stock Functor
80
80
81
81
82+instance Biprojectable (EitherTable context) where
83+ biproject f g (EitherTable tag a b) =
84+ EitherTable tag (project f a) (project g b)
85+
86+
82instance Nullifiable context => Bifunctor (EitherTable context) where
87instance Nullifiable context => Bifunctor (EitherTable context) where
83 bimap f g (EitherTable tag a b) = EitherTable tag (fmap f a) (fmap g b)
88 bimap f g (EitherTable tag a b) = EitherTable tag (fmap f a) (fmap g b)
84
89
85
90
91+instance Projectable (EitherTable context a) where
92+ project f (EitherTable tag a b) = EitherTable tag a (project f b)
93+
94+
86instance (context ~ Expr, Table Expr a) => Apply (EitherTable context a) where
95instance (context ~ Expr, Table Expr a) => Apply (EitherTable context a) where
87− EitherTable (E tag) l1 f <.> EitherTable (E tag') l2 a =
96+ EitherTable tag l1 f <.> EitherTable tag' l2 a =
88− EitherTable (E (tag <> tag')) (bool l1 l2 (isLeft tag)) (f <.> a)
97+ EitherTable (tag <> tag') (bool l1 l2 (isLeft tag)) (f <.> a)
89
98
90
99
91instance (context ~ Expr, Table Expr a) => Applicative (EitherTable context a) where
100instance (context ~ Expr, Table Expr a) => Applicative (EitherTable context a) where
@@ -94,9 +103,9 @@ instance (context ~ Expr, Table Expr a) => Applicative (EitherTable context a) w
94
103
95
104
96instance (context ~ Expr, Table Expr a) => Bind (EitherTable context a) where
105instance (context ~ Expr, Table Expr a) => Bind (EitherTable context a) where
97− EitherTable (E tag) l1 a >>- f = case f (extract a) of
106+ EitherTable tag l1 a >>- f = case f (extract a) of
98− EitherTable (E tag') l2 b ->
107+ EitherTable tag' l2 b ->
99− EitherTable (E (tag <> tag')) (bool l1 l2 (isRight tag)) b
108+ EitherTable (tag <> tag') (bool l1 l2 (isRight tag)) b
100
109
101
110
102instance (context ~ Expr, Table Expr a) => Monad (EitherTable context a) where
111instance (context ~ Expr, Table Expr a) => Monad (EitherTable context a) where
@@ -118,9 +127,11 @@ instance
118 type Columns (EitherTable context a b) = HEitherTable (Columns a) (Columns b)
127 type Columns (EitherTable context a b) = HEitherTable (Columns a) (Columns b)
119 type Context (EitherTable context a b) = Context a
128 type Context (EitherTable context a b) = Context a
120 type FromExprs (EitherTable context a b) = Either (FromExprs a) (FromExprs b)
129 type FromExprs (EitherTable context a b) = Either (FromExprs a) (FromExprs b)
130+ type Transpose to (EitherTable context a b) =
131+ EitherTable to (Transpose to a) (Transpose to b)
121
132
122 toColumns EitherTable {tag, left, right} = HEitherTable
133 toColumns EitherTable {tag, left, right} = HEitherTable
123− { htag = hlabel $ HType tag
134+ { htag = hlabel $ HIdentity tag
124 , hleft = hlabel $ guard tag (== IsLeft) isLeft $ toColumns left
135 , hleft = hlabel $ guard tag (== IsLeft) isLeft $ toColumns left
125 , hright = hlabel $ guard tag (== IsRight) isRight $ toColumns right
136 , hright = hlabel $ guard tag (== IsRight) isRight $ toColumns right
126 }
137 }
@@ -133,38 +144,29 @@ instance
133
144
134 toResult = \case
145 toResult = \case
135 Left table -> HEitherTable
146 Left table -> HEitherTable
136− { htag = hlabel (HType (R IsLeft))
147+ { htag = hlabel (HIdentity (Identity IsLeft))
137 , hleft = hlabel (toResult @_ @(Nullify context a) (Just table))
148 , hleft = hlabel (toResult @_ @(Nullify context a) (Just table))
138 , hright = hlabel (toResult @_ @(Nullify context b) Nothing)
149 , hright = hlabel (toResult @_ @(Nullify context b) Nothing)
139 }
150 }
140 Right table -> HEitherTable
151 Right table -> HEitherTable
141− { htag = hlabel (HType (R IsRight))
152+ { htag = hlabel (HIdentity (Identity IsRight))
142 , hleft = hlabel (toResult @_ @(Nullify context a) Nothing)
153 , hleft = hlabel (toResult @_ @(Nullify context a) Nothing)
143 , hright = hlabel (toResult @_ @(Nullify context b) (Just table))
154 , hright = hlabel (toResult @_ @(Nullify context b) (Just table))
144 }
155 }
145
156
146 fromResult HEitherTable {htag, hleft, hright} = case hunlabel htag of
157 fromResult HEitherTable {htag, hleft, hright} = case hunlabel htag of
147− HType (R tag) -> case tag of
158+ HIdentity (Identity tag) -> case tag of
148 IsLeft -> maybe err Left $ fromResult @_ @(Nullify context a) (hunlabel hleft)
159 IsLeft -> maybe err Left $ fromResult @_ @(Nullify context a) (hunlabel hleft)
149 IsRight -> maybe err Right $ fromResult @_ @(Nullify context b) (hunlabel hright)
160 IsRight -> maybe err Right $ fromResult @_ @(Nullify context b) (hunlabel hright)
150 where
161 where
151 err = error "Either.fromColumns: mismatch between tag and data"
162 err = error "Either.fromColumns: mismatch between tag and data"
152
163
153
164
154−instance
155− ( Reifiable from, from ~ from'
156− , Reifiable to, to ~ to'
157− , Recontextualize from to a1 b1
158− , Recontextualize from to a2 b2
159− )
160− => Recontextualize from to (EitherTable from' a1 a2) (EitherTable to' b1 b2)
161−
162−
163instance (EqTable a, EqTable b, context ~ Expr) =>
165instance (EqTable a, EqTable b, context ~ Expr) =>
164 EqTable (EitherTable context a b)
166 EqTable (EitherTable context a b)
165 where
167 where
166 eqTable = HEitherTable
168 eqTable = HEitherTable
167− { htag = hlabel (HType Dict)
169+ { htag = hlabel (HIdentity Dict)
168 , hleft = hlabel (eqTable @(Nullify context a))
170 , hleft = hlabel (eqTable @(Nullify context a))
169 , hright = hlabel (eqTable @(Nullify context b))
171 , hright = hlabel (eqTable @(Nullify context b))
170 }
172 }
@@ -174,7 +176,7 @@ instance (OrdTable a, OrdTable b, context ~ Expr) =>
174 OrdTable (EitherTable context a b)
176 OrdTable (EitherTable context a b)
175 where
177 where
176 ordTable = HEitherTable
178 ordTable = HEitherTable
177− { htag = hlabel (HType Dict)
179+ { htag = hlabel (HIdentity Dict)
178 , hleft = hlabel (ordTable @(Nullify context a))
180 , hleft = hlabel (ordTable @(Nullify context a))
179 , hright = hlabel (ordTable @(Nullify context b))
181 , hright = hlabel (ordTable @(Nullify context b))
180 }
182 }
@@ -186,30 +188,30 @@ instance (ToExprs exprs1 a, ToExprs exprs2 b, x ~ EitherTable Expr exprs1 exprs2
186
188
187-- | Test if an 'EitherTable' is a 'leftTable'.
189-- | Test if an 'EitherTable' is a 'leftTable'.
188isLeftTable :: EitherTable Expr a b -> Expr Bool
190isLeftTable :: EitherTable Expr a b -> Expr Bool
189−isLeftTable EitherTable {tag = E tag} = isLeft tag
191+isLeftTable EitherTable {tag} = isLeft tag
190
192
191
193
192-- | Test if an 'EitherTable' is a 'rightTable'.
194-- | Test if an 'EitherTable' is a 'rightTable'.
193isRightTable :: EitherTable Expr a b -> Expr Bool
195isRightTable :: EitherTable Expr a b -> Expr Bool
194−isRightTable EitherTable {tag = E tag} = isRight tag
196+isRightTable EitherTable {tag} = isRight tag
195
197
196
198
197-- | Pattern match/eliminate an 'EitherTable', by providing mappings from a
199-- | Pattern match/eliminate an 'EitherTable', by providing mappings from a
198-- 'leftTable' and 'rightTable'.
200-- 'leftTable' and 'rightTable'.
199eitherTable :: Table Expr c
201eitherTable :: Table Expr c
200 => (a -> c) -> (b -> c) -> EitherTable Expr a b -> c
202 => (a -> c) -> (b -> c) -> EitherTable Expr a b -> c
201−eitherTable f g EitherTable {tag = E tag, left, right} =
203+eitherTable f g EitherTable {tag, left, right} =
202 bool (f (extract left)) (g (extract right)) (isRight tag)
204 bool (f (extract left)) (g (extract right)) (isRight tag)
203
205
204
206
205-- | Construct a left 'EitherTable'. Like 'Left'.
207-- | Construct a left 'EitherTable'. Like 'Left'.
206leftTable :: Table Expr b => a -> EitherTable Expr a b
208leftTable :: Table Expr b => a -> EitherTable Expr a b
207−leftTable a = EitherTable (E (litExpr IsLeft)) (pure a) undefined
209+leftTable a = EitherTable (litExpr IsLeft) (pure a) undefined
208
210
209
211
210-- | Construct a right 'EitherTable'. Like 'Right'.
212-- | Construct a right 'EitherTable'. Like 'Right'.
211rightTable :: Table Expr a => b -> EitherTable Expr a b
213rightTable :: Table Expr a => b -> EitherTable Expr a b
212−rightTable = EitherTable (E (litExpr IsRight)) undefined . pure
214+rightTable = EitherTable (litExpr IsRight) undefined . pure
213
215
214
216
215-- | Lift a pair of aggregating functions to operate on an 'EitherTable'.
217-- | Lift a pair of aggregating functions to operate on an 'EitherTable'.
@@ -219,8 +221,8 @@ aggregateEitherTable :: ()
219 -> (exprs' -> aggregates')
221 -> (exprs' -> aggregates')
220 -> EitherTable Expr exprs exprs'
222 -> EitherTable Expr exprs exprs'
221 -> EitherTable Aggregate aggregates aggregates'
223 -> EitherTable Aggregate aggregates aggregates'
222−aggregateEitherTable f g (EitherTable (E tag) a b) = EitherTable
224+aggregateEitherTable f g (EitherTable tag a b) = EitherTable
223− { tag = A (groupByExpr tag)
225+ { tag = groupByExpr tag
224 , left = aggregateNullify f a
226 , left = aggregateNullify f a
225 , right = aggregateNullify g b
227 , right = aggregateNullify g b
226 }
228 }
@@ -238,4 +240,4 @@ nameEitherTable
238 -> b
240 -> b
239 -- ^ Names of the columns in the @b@ table.
241 -- ^ Names of the columns in the @b@ table.
240 -> EitherTable Name a b
242 -> EitherTable Name a b
241−nameEitherTable tag left right = EitherTable (N tag) (pure left) (pure right)
243+nameEitherTable tag left right = EitherTable tag (pure left) (pure right)
src/Rel8/Table/Eq.hs+10−18
@@ -11,7 +11,6 @@
11{-# language TypeFamilies #-}
11{-# language TypeFamilies #-}
12{-# language TypeOperators #-}
12{-# language TypeOperators #-}
13{-# language UndecidableInstances #-}
13{-# language UndecidableInstances #-}
14−{-# language UndecidableSuperClasses #-}
15{-# language ViewPatterns #-}
14{-# language ViewPatterns #-}
16
15
17module Rel8.Table.Eq
16module Rel8.Table.Eq
@@ -28,7 +27,7 @@ import GHC.Generics ( Rep )
28import Prelude
27import Prelude
29
28
30-- rel8
29-- rel8
31−import Rel8.Expr ( Expr( E ) )
30+import Rel8.Expr ( Expr )
32import Rel8.Expr.Bool ( (||.), (&&.) )
31import Rel8.Expr.Bool ( (||.), (&&.) )
33import Rel8.Expr.Eq ( (==.), (/=.) )
32import Rel8.Expr.Eq ( (==.), (/=.) )
34import Rel8.FCF ( Eval, Exp )
33import Rel8.FCF ( Eval, Exp )
@@ -36,10 +35,9 @@ import Rel8.Generic.Record ( Record )
36import Rel8.Generic.Table.Record ( GTable, GColumns, gtable )
35import Rel8.Generic.Table.Record ( GTable, GColumns, gtable )
37import Rel8.Schema.Dict ( Dict( Dict ) )
36import Rel8.Schema.Dict ( Dict( Dict ) )
38import Rel8.Schema.HTable ( htabulateA, hfield )
37import Rel8.Schema.HTable ( htabulateA, hfield )
39−import Rel8.Schema.HTable.Identity ( HIdentity( HType ) )
38+import Rel8.Schema.HTable.Identity ( HIdentity( HIdentity ) )
40import Rel8.Schema.Null ( Sql )
39import Rel8.Schema.Null ( Sql )
41−import Rel8.Schema.Spec.Constrain ( ConstrainSpec )
42−import Rel8.Table ( Table, Columns, toColumns, TColumns, TFromExprs )
40+import Rel8.Table ( Table, Columns, toColumns, TColumns )
43import Rel8.Type.Eq ( DBEq )
41import Rel8.Type.Eq ( DBEq )
44
42
45
43
@@ -48,20 +46,14 @@ import Rel8.Type.Eq ( DBEq )
48-- means "all columns in a 'Table' have an instance of 'DBEq'".
46-- means "all columns in a 'Table' have an instance of 'DBEq'".
49type EqTable :: Type -> Constraint
47type EqTable :: Type -> Constraint
50class Table Expr a => EqTable a where
48class Table Expr a => EqTable a where
51− eqTable :: Columns a (Dict (ConstrainSpec (Sql DBEq)))
49+ eqTable :: Columns a (Dict (Sql DBEq))
52
50
53 default eqTable ::
51 default eqTable ::
54− ( GTable TEqTable TColumns TFromExprs (Rep (Record a))
52+ ( GTable TEqTable TColumns (Rep (Record a))
55 , Columns a ~ GColumns TColumns (Rep (Record a))
53 , Columns a ~ GColumns TColumns (Rep (Record a))
56 )
54 )
57− => Columns a (Dict (ConstrainSpec (Sql DBEq)))
55+ => Columns a (Dict (Sql DBEq))
58− eqTable =
56+ eqTable = gtable @TEqTable @TColumns @(Rep (Record a)) table
59− gtable
60− @TEqTable
61− @TColumns
62− @TFromExprs
63− @(Rep (Record a))
64− table
65 where
57 where
66 table (_ :: proxy x) = eqTable @x
58 table (_ :: proxy x) = eqTable @x
67
59
@@ -71,7 +63,7 @@ type instance Eval (TEqTable a) = EqTable a
71
63
72
64
73instance Sql DBEq a => EqTable (Expr a) where
65instance Sql DBEq a => EqTable (Expr a) where
74− eqTable = HType Dict
66+ eqTable = HIdentity Dict
75
67
76
68
77instance (EqTable a, EqTable b) => EqTable (a, b)
69instance (EqTable a, EqTable b) => EqTable (a, b)
@@ -105,7 +97,7 @@ instance
105(toColumns -> as) ==: (toColumns -> bs) =
97(toColumns -> as) ==: (toColumns -> bs) =
106 foldl1' (&&.) $ getConst $ htabulateA $ \field ->
98 foldl1' (&&.) $ getConst $ htabulateA $ \field ->
107 case (hfield as field, hfield bs field) of
99 case (hfield as field, hfield bs field) of
108− (E a, E b) -> case hfield (eqTable @a) field of
100+ (a, b) -> case hfield (eqTable @a) field of
109 Dict -> Const (pure (a ==. b))
101 Dict -> Const (pure (a ==. b))
110infix 4 ==:
102infix 4 ==:
111
103
@@ -117,7 +109,7 @@ infix 4 ==:
117(toColumns -> as) /=: (toColumns -> bs) =
109(toColumns -> as) /=: (toColumns -> bs) =
118 foldl1' (||.) $ getConst $ htabulateA $ \field ->
110 foldl1' (||.) $ getConst $ htabulateA $ \field ->
119 case (hfield as field, hfield bs field) of
111 case (hfield as field, hfield bs field) of
120− (E a, E b) -> case hfield (eqTable @a) field of
112+ (a, b) -> case hfield (eqTable @a) field of
121 Dict -> Const (pure (a /=. b))
113 Dict -> Const (pure (a /=. b))
122infix 4 /=:
114infix 4 /=:
123
115
src/Rel8/Table/HKD.hs+14−13
@@ -57,16 +57,18 @@ import Rel8.Generic.Rel8able
57 , GFromExprs, gfromResult, gtoResult
57 , GFromExprs, gfromResult, gtoResult
58 )
58 )
59import Rel8.Generic.Table
59import Rel8.Generic.Table
60− ( GGTable, GGColumns, GAlgebra, ggfromResult, ggtoResult
60+ ( GGSerialize, GGColumns, GAlgebra, ggfromResult, ggtoResult
61 )
61 )
62import Rel8.Generic.Table.Record ( GTable, GContext )
62import Rel8.Generic.Table.Record ( GTable, GContext )
63import qualified Rel8.Generic.Table.Record as G
63import qualified Rel8.Generic.Table.Record as G
64import qualified Rel8.Schema.Kind as K
64import qualified Rel8.Schema.Kind as K
65import Rel8.Schema.HTable ( HTable )
65import Rel8.Schema.HTable ( HTable )
66import Rel8.Schema.Name ( Name )
66import Rel8.Schema.Name ( Name )
67+import Rel8.Schema.Result ( Result )
67import Rel8.Table
68import Rel8.Table
68 ( Table, fromColumns, toColumns, fromResult, toResult
69 ( Table, fromColumns, toColumns, fromResult, toResult
69− , TTable, TColumns, TContext, TFromExprs
70+ , TTable, TColumns, TContext
71+ , TSerialize
70 )
72 )
71
73
72
74
@@ -91,26 +93,26 @@ instance HKDable a => Rel8able (HKD a) where
91 to .
93 to .
92 ggfromResult
94 ggfromResult
93 @(GAlgebra (Rep a))
95 @(GAlgebra (Rep a))
94− @(TTable Expr)
96+ @TSerialize
95 @TColumns
97 @TColumns
96− @TFromExprs
97 @(Eval (HKDRep a Expr))
98 @(Eval (HKDRep a Expr))
99+ @(Eval (HKDRep a Result))
98 (\(_ :: proxy x) -> fromResult @_ @x)
100 (\(_ :: proxy x) -> fromResult @_ @x)
99
101
100 gtoResult =
102 gtoResult =
101 ggtoResult
103 ggtoResult
102 @(GAlgebra (Rep a))
104 @(GAlgebra (Rep a))
103− @(TTable Expr)
105+ @TSerialize
104 @TColumns
106 @TColumns
105− @TFromExprs
106 @(Eval (HKDRep a Expr))
107 @(Eval (HKDRep a Expr))
108+ @(Eval (HKDRep a Result))
107 (\(_ :: proxy x) -> toResult @_ @x) .
109 (\(_ :: proxy x) -> toResult @_ @x) .
108 from .
110 from .
109 Record
111 Record
110
112
111
113
112instance
114instance
113− ( GTable (TTable f) TColumns TFromExprs (GRecord (GMap (TColumn f) (Rep a)))
115+ ( GTable (TTable f) TColumns (GRecord (GMap (TColumn f) (Rep a)))
114 , G.GColumns TColumns (GRecord (GMap (TColumn f) (Rep a))) ~ GColumnsHKD a
116 , G.GColumns TColumns (GRecord (GMap (TColumn f) (Rep a))) ~ GColumnsHKD a
115 , GContext TContext (GRecord (GMap (TColumn f) (Rep a))) ~ f
117 , GContext TContext (GRecord (GMap (TColumn f) (Rep a))) ~ f
116 , GRecordable (GMap (TColumn f) (Rep a))
118 , GRecordable (GMap (TColumn f) (Rep a))
@@ -124,7 +126,6 @@ instance
124 G.gfromColumns
126 G.gfromColumns
125 @(TTable f)
127 @(TTable f)
126 @TColumns
128 @TColumns
127− @TFromExprs
128 fromColumns .
129 fromColumns .
129 (\(HKD a) -> a)
130 (\(HKD a) -> a)
130
131
@@ -133,7 +134,6 @@ instance
133 G.gtoColumns
134 G.gtoColumns
134 @(TTable f)
135 @(TTable f)
135 @TColumns
136 @TColumns
136− @TFromExprs
137 toColumns .
137 toColumns .
138 grecord @(GMap (TColumn f) (Rep a))
138 grecord @(GMap (TColumn f) (Rep a))
139
139
@@ -143,20 +143,21 @@ class
143 ( Generic (Record a)
143 ( Generic (Record a)
144 , HTable (GColumns (HKD a))
144 , HTable (GColumns (HKD a))
145 , KnownAlgebra (GAlgebra (Rep a))
145 , KnownAlgebra (GAlgebra (Rep a))
146− , Eval (GGTable (GAlgebra (Rep a)) (TTable Expr) TColumns TFromExprs (Eval (HKDRep a Expr)))
146+ , Eval (GGSerialize (GAlgebra (Rep a)) TSerialize TColumns (Eval (HKDRep a Expr)) (Eval (HKDRep a Result)))
147− , GMap TFromExprs (GRecord (GMap (TColumn Expr) (Rep a))) ~ Rep (Record a)
147+ , GRecord (GMap (TColumn Result) (Rep a)) ~ Rep (Record a)
148 )
148 )
149 => HKDable a
149 => HKDable a
150instance
150instance
151 ( Generic (Record a)
151 ( Generic (Record a)
152 , HTable (GColumns (HKD a))
152 , HTable (GColumns (HKD a))
153 , KnownAlgebra (GAlgebra (Rep a))
153 , KnownAlgebra (GAlgebra (Rep a))
154− , Eval (GGTable (GAlgebra (Rep a)) (TTable Expr) TColumns TFromExprs (Eval (HKDRep a Expr)))
154+ , Eval (GGSerialize (GAlgebra (Rep a)) TSerialize TColumns (Eval (HKDRep a Expr)) (Eval (HKDRep a Result)))
155− , GMap TFromExprs (GRecord (GMap (TColumn Expr) (Rep a))) ~ Rep (Record a)
155+ , GRecord (GMap (TColumn Result) (Rep a)) ~ Rep (Record a)
156 )
156 )
157 => HKDable a
157 => HKDable a
158
158
159
159
160+type Top_ :: Constraint
160class Top_
161class Top_
161instance Top_
162instance Top_
162
163
src/Rel8/Table/List.hs+34−19
@@ -11,7 +11,9 @@
11
11
12module Rel8.Table.List
12module Rel8.Table.List
13 ( ListTable(..)
13 ( ListTable(..)
14+ , ($*)
15+ , listTable
14− , listTable, nameListTable
16+ , nameListTable
15 )
17 )
16where
18where
17
19
@@ -21,19 +23,24 @@ import Data.Kind ( Type )
21import Prelude
23import Prelude
22
24
23-- rel8
25-- rel8
24−import Rel8.Expr ( Expr( E, unE ) )
26+import Rel8.Expr ( Expr )
25import Rel8.Expr.Array ( sappend, sempty, slistOf )
27import Rel8.Expr.Array ( sappend, sempty, slistOf )
26import Rel8.Schema.Dict ( Dict( Dict ) )
28import Rel8.Schema.Dict ( Dict( Dict ) )
27import Rel8.Schema.HTable.List ( HListTable )
29import Rel8.Schema.HTable.List ( HListTable )
28−import Rel8.Schema.HTable.Vectorize ( happend, hempty, hvectorize, hunvectorize )
30+import Rel8.Schema.HTable.Vectorize
31+ ( hvectorize, hunvectorize
32+ , happend, hempty
33+ , hproject, hcolumn
34+ )
29import qualified Rel8.Schema.Kind as K
35import qualified Rel8.Schema.Kind as K
30−import Rel8.Schema.Name ( Name( N, Name ) )
36+import Rel8.Schema.Name ( Name( Name ) )
31import Rel8.Schema.Null ( Nullity( Null, NotNull ) )
37import Rel8.Schema.Null ( Nullity( Null, NotNull ) )
32import Rel8.Schema.Result ( vectorizer, unvectorizer )
38import Rel8.Schema.Result ( vectorizer, unvectorizer )
33−import Rel8.Schema.Spec ( SSpec(..) )
39+import Rel8.Schema.Spec ( Spec(..) )
34import Rel8.Table
40import Rel8.Table
35 ( Table, Context, Columns, fromColumns, toColumns
41 ( Table, Context, Columns, fromColumns, toColumns
36 , FromExprs, fromResult, toResult
42 , FromExprs, fromResult, toResult
43+ , Transpose
37 )
44 )
38import Rel8.Table.Alternative
45import Rel8.Table.Alternative
39 ( AltTable, (<|>:)
46 ( AltTable, (<|>:)
@@ -41,7 +48,9 @@ import Rel8.Table.Alternative
41 )
48 )
42import Rel8.Table.Eq ( EqTable, eqTable )
49import Rel8.Table.Eq ( EqTable, eqTable )
43import Rel8.Table.Ord ( OrdTable, ordTable )
50import Rel8.Table.Ord ( OrdTable, ordTable )
44−import Rel8.Table.Recontextualize ( Recontextualize )
51+import Rel8.Table.Projection
52+ ( Projectable, Projecting, Projection, project, apply
53+ )
45import Rel8.Table.Serialize ( ToExprs )
54import Rel8.Table.Serialize ( ToExprs )
46
55
47
56
@@ -52,12 +61,17 @@ newtype ListTable context a =
52 ListTable (HListTable (Columns a) (Context a))
61 ListTable (HListTable (Columns a) (Context a))
53
62
54
63
64+instance Projectable (ListTable context) where
65+ project f (ListTable a) = ListTable (hproject (apply f) a)
66+
67+
55instance (Table context a, context ~ context') =>
68instance (Table context a, context ~ context') =>
56 Table context' (ListTable context a)
69 Table context' (ListTable context a)
57 where
70 where
58 type Columns (ListTable context a) = HListTable (Columns a)
71 type Columns (ListTable context a) = HListTable (Columns a)
59 type Context (ListTable context a) = Context a
72 type Context (ListTable context a) = Context a
60 type FromExprs (ListTable context a) = [FromExprs a]
73 type FromExprs (ListTable context a) = [FromExprs a]
74+ type Transpose to (ListTable context a) = ListTable to (Transpose to a)
61
75
62 fromColumns = ListTable
76 fromColumns = ListTable
63 toColumns (ListTable a) = a
77 toColumns (ListTable a) = a
@@ -65,14 +79,10 @@ instance (Table context a, context ~ context') =>
65 toResult = hvectorize vectorizer . fmap (toResult @_ @a)
79 toResult = hvectorize vectorizer . fmap (toResult @_ @a)
66
80
67
81
68−instance (Recontextualize from to a b, from ~ from', to ~ to') =>
69− Recontextualize from to (ListTable from' a) (ListTable to' b)
70−
71−
72instance (EqTable a, context ~ Expr) => EqTable (ListTable context a) where
82instance (EqTable a, context ~ Expr) => EqTable (ListTable context a) where
73 eqTable =
83 eqTable =
74 hvectorize
84 hvectorize
75− (\SSpec {nullity} (Identity Dict) -> case nullity of
85+ (\Spec {nullity} (Identity Dict) -> case nullity of
76 Null -> Dict
86 Null -> Dict
77 NotNull -> Dict)
87 NotNull -> Dict)
78 (Identity (eqTable @a))
88 (Identity (eqTable @a))
@@ -81,7 +91,7 @@ instance (EqTable a, context ~ Expr) => EqTable (ListTable context a) where
81instance (OrdTable a, context ~ Expr) => OrdTable (ListTable context a) where
91instance (OrdTable a, context ~ Expr) => OrdTable (ListTable context a) where
82 ordTable =
92 ordTable =
83 hvectorize
93 hvectorize
84− (\SSpec {nullity} (Identity Dict) -> case nullity of
94+ (\Spec {nullity} (Identity Dict) -> case nullity of
85 Null -> Dict
95 Null -> Dict
86 NotNull -> Dict)
96 NotNull -> Dict)
87 (Identity (ordTable @a))
97 (Identity (ordTable @a))
@@ -99,24 +109,29 @@ instance context ~ Expr => AlternativeTable (ListTable context) where
99 emptyTable = mempty
109 emptyTable = mempty
100
110
101
111
102−instance (context ~ Expr, Table Expr a) =>
112+instance (context ~ Expr, Table Expr a) => Semigroup (ListTable context a)
103− Semigroup (ListTable context a)
104 where
113 where
105− ListTable as <> ListTable bs = ListTable $
114+ ListTable as <> ListTable bs = ListTable $ happend (const sappend) as bs
106− happend (\_ _ (E a) (E b) -> E (sappend a b)) as bs
107
115
108
116
109instance (context ~ Expr, Table Expr a) =>
117instance (context ~ Expr, Table Expr a) =>
110 Monoid (ListTable context a)
118 Monoid (ListTable context a)
111 where
119 where
112− mempty = ListTable $ hempty $ \_ -> E . sempty
120+ mempty = ListTable $ hempty $ \Spec {info} -> sempty info
121+
122+
123+-- | Project a single expression out of a 'ListTable'.
124+($*) :: Projecting a (Expr b)
125+ => Projection a (Expr b) -> ListTable Expr a -> Expr [b]
126+f $* ListTable a = hcolumn $ hproject (apply f) a
127+infixl 4 $*
113
128
114
129
115-- | Construct a @ListTable@ from a list of expressions.
130-- | Construct a @ListTable@ from a list of expressions.
116listTable :: Table Expr a => [a] -> ListTable Expr a
131listTable :: Table Expr a => [a] -> ListTable Expr a
117listTable =
132listTable =
118 ListTable .
133 ListTable .
119− hvectorize (\SSpec {info} -> E . slistOf info . fmap unE) .
134+ hvectorize (\Spec {info} -> slistOf info) .
120 fmap toColumns
135 fmap toColumns
121
136
122
137
@@ -129,6 +144,6 @@ nameListTable
129 -> ListTable Name a
144 -> ListTable Name a
130nameListTable =
145nameListTable =
131 ListTable .
146 ListTable .
132− hvectorize (\_ (Identity (N (Name a))) -> N (Name a)) .
147+ hvectorize (\_ (Identity (Name a)) -> Name a) .
133 pure .
148 pure .
134 toColumns
149 toColumns
src/Rel8/Table/Maybe.hs+32−30
@@ -15,6 +15,7 @@ module Rel8.Table.Maybe
15 ( MaybeTable(..)
15 ( MaybeTable(..)
16 , maybeTable, nothingTable, justTable
16 , maybeTable, nothingTable, justTable
17 , isNothingTable, isJustTable
17 , isNothingTable, isJustTable
18+ , fromMaybeTable
18 , ($?)
19 , ($?)
19 , aggregateMaybeTable
20 , aggregateMaybeTable
20 , nameMaybeTable
21 , nameMaybeTable
@@ -23,6 +24,7 @@ where
23
24
24-- base
25-- base
25import Data.Functor ( ($>) )
26import Data.Functor ( ($>) )
27+import Data.Functor.Identity ( Identity( Identity ) )
26import Data.Kind ( Type )
28import Data.Kind ( Type )
27import Data.Maybe ( fromMaybe, isJust )
29import Data.Maybe ( fromMaybe, isJust )
28import Prelude hiding ( null, undefined )
30import Prelude hiding ( null, undefined )
@@ -31,8 +33,8 @@ import Prelude hiding ( null, undefined )
31import Control.Comonad ( extract )
33import Control.Comonad ( extract )
32
34
33-- rel8
35-- rel8
34−import Rel8.Aggregate ( Aggregate( A ) )
36+import Rel8.Aggregate ( Aggregate )
35−import Rel8.Expr ( Expr(E ) )
37+import Rel8.Expr ( Expr )
36import Rel8.Expr.Aggregate ( groupByExpr )
38import Rel8.Expr.Aggregate ( groupByExpr )
37import Rel8.Expr.Bool ( boolExpr )
39import Rel8.Expr.Bool ( boolExpr )
38import Rel8.Expr.Null ( isNull, isNonNull, null, nullify )
40import Rel8.Expr.Null ( isNull, isNonNull, null, nullify )
@@ -42,14 +44,13 @@ import qualified Rel8.Schema.Kind as K
42import Rel8.Schema.HTable.Identity ( HIdentity(..) )
44import Rel8.Schema.HTable.Identity ( HIdentity(..) )
43import Rel8.Schema.HTable.Label ( hlabel, hunlabel )
45import Rel8.Schema.HTable.Label ( hlabel, hunlabel )
44import Rel8.Schema.HTable.Maybe ( HMaybeTable(..) )
46import Rel8.Schema.HTable.Maybe ( HMaybeTable(..) )
45−import Rel8.Schema.Name ( Name( N ) )
47+import Rel8.Schema.Name ( Name )
46import Rel8.Schema.Null ( Nullity( Null, NotNull ), Sql, nullable )
48import Rel8.Schema.Null ( Nullity( Null, NotNull ), Sql, nullable )
47import qualified Rel8.Schema.Null as N
49import qualified Rel8.Schema.Null as N
48−import Rel8.Schema.Result ( Result( R ) )
49−import Rel8.Schema.Spec ( Spec( Spec ) )
50import Rel8.Table
50import Rel8.Table
51 ( Table, Columns, Context, fromColumns, toColumns
51 ( Table, Columns, Context, fromColumns, toColumns
52 , FromExprs, fromResult, toResult
52 , FromExprs, fromResult, toResult
53+ , Transpose
53 )
54 )
54import Rel8.Table.Alternative
55import Rel8.Table.Alternative
55 ( AltTable, (<|>:)
56 ( AltTable, (<|>:)
@@ -58,8 +59,8 @@ import Rel8.Table.Alternative
58import Rel8.Table.Bool ( bool )
59import Rel8.Table.Bool ( bool )
59import Rel8.Table.Eq ( EqTable, eqTable )
60import Rel8.Table.Eq ( EqTable, eqTable )
60import Rel8.Table.Ord ( OrdTable, ordTable )
61import Rel8.Table.Ord ( OrdTable, ordTable )
62+import Rel8.Table.Projection ( Projectable, project )
61import Rel8.Table.Nullify ( Nullify, aggregateNullify, guard )
63import Rel8.Table.Nullify ( Nullify, aggregateNullify, guard )
62−import Rel8.Table.Recontextualize ( Recontextualize )
63import Rel8.Table.Serialize ( ToExprs )
64import Rel8.Table.Serialize ( ToExprs )
64import Rel8.Table.Undefined ( undefined )
65import Rel8.Table.Undefined ( undefined )
65import Rel8.Type ( DBType )
66import Rel8.Type ( DBType )
@@ -80,15 +81,18 @@ import Data.Functor.Bind ( Bind, (>>-) )
80-- a "nullTag" - to track whether or not the outer join produced any rows.
81-- a "nullTag" - to track whether or not the outer join produced any rows.
81type MaybeTable :: K.Context -> Type -> Type
82type MaybeTable :: K.Context -> Type -> Type
82data MaybeTable context a = MaybeTable
83data MaybeTable context a = MaybeTable
83− { tag :: context ('Spec (Maybe MaybeTag))
84+ { tag :: context (Maybe MaybeTag)
84 , just :: Nullify context a
85 , just :: Nullify context a
85 }
86 }
86 deriving stock Functor
87 deriving stock Functor
87
88
88
89
90+instance Projectable (MaybeTable context) where
91+ project f (MaybeTable tag a) = MaybeTable tag (project f a)
92+
93+
89instance context ~ Expr => Apply (MaybeTable context) where
94instance context ~ Expr => Apply (MaybeTable context) where
90− MaybeTable (E tag) f <.> MaybeTable (E tag') a =
95+ MaybeTable tag f <.> MaybeTable tag' a = MaybeTable (tag <> tag') (f <.> a)
91− MaybeTable (E (tag <> tag')) (f <.> a)
92
96
93
97
94-- | Has the same behavior as the @Applicative@ instance for @Maybe@. See also:
98-- | Has the same behavior as the @Applicative@ instance for @Maybe@. See also:
@@ -99,8 +103,8 @@ instance context ~ Expr => Applicative (MaybeTable context) where
99
103
100
104
101instance context ~ Expr => Bind (MaybeTable context) where
105instance context ~ Expr => Bind (MaybeTable context) where
102− MaybeTable (E tag) a >>- f = case f (extract a) of
106+ MaybeTable tag a >>- f = case f (extract a) of
103− MaybeTable (E tag') b -> MaybeTable (E (tag <> tag')) b
107+ MaybeTable tag' b -> MaybeTable (tag <> tag') b
104
108
105
109
106-- | Has the same behavior as the @Monad@ instance for @Maybe@.
110-- | Has the same behavior as the @Monad@ instance for @Maybe@.
@@ -134,6 +138,7 @@ instance (Table context a, Reifiable context, context ~ context') =>
134 type Columns (MaybeTable context a) = HMaybeTable (Columns a)
138 type Columns (MaybeTable context a) = HMaybeTable (Columns a)
135 type Context (MaybeTable context a) = Context a
139 type Context (MaybeTable context a) = Context a
136 type FromExprs (MaybeTable context a) = Maybe (FromExprs a)
140 type FromExprs (MaybeTable context a) = Maybe (FromExprs a)
141+ type Transpose to (MaybeTable context a) = MaybeTable to (Transpose to a)
137
142
138 toColumns MaybeTable {tag, just} = HMaybeTable
143 toColumns MaybeTable {tag, just} = HMaybeTable
139 { htag = hlabel $ HIdentity tag
144 { htag = hlabel $ HIdentity tag
@@ -146,35 +151,27 @@ instance (Table context a, Reifiable context, context ~ context') =>
146 }
151 }
147
152
148 toResult ma = HMaybeTable
153 toResult ma = HMaybeTable
149− { htag = hlabel (HIdentity (R (IsJust <$ ma)))
154+ { htag = hlabel (HIdentity (Identity (IsJust <$ ma)))
150 , hjust = hlabel (toResult @_ @(Nullify context a) ma)
155 , hjust = hlabel (toResult @_ @(Nullify context a) ma)
151 }
156 }
152
157
153 fromResult HMaybeTable {htag, hjust} = case hunlabel htag of
158 fromResult HMaybeTable {htag, hjust} = case hunlabel htag of
154− HType (R tag) -> tag $>
159+ HIdentity (Identity tag) -> tag $>
155 fromMaybe err (fromResult @_ @(Nullify context a) (hunlabel hjust))
160 fromMaybe err (fromResult @_ @(Nullify context a) (hunlabel hjust))
156 where
161 where
157 err = error "Maybe.fromColumns: mismatch between tag and data"
162 err = error "Maybe.fromColumns: mismatch between tag and data"
158
163
159
164
160−instance
161− ( Recontextualize from to a b
162− , Reifiable from, from ~ from'
163− , Reifiable to, to ~ to'
164− )
165− => Recontextualize from to (MaybeTable from' a) (MaybeTable to' b)
166−
167−
168instance (EqTable a, context ~ Expr) => EqTable (MaybeTable context a) where
165instance (EqTable a, context ~ Expr) => EqTable (MaybeTable context a) where
169 eqTable = HMaybeTable
166 eqTable = HMaybeTable
170− { htag = hlabel (HType Dict)
167+ { htag = hlabel (HIdentity Dict)
171 , hjust = hlabel (eqTable @(Nullify context a))
168 , hjust = hlabel (eqTable @(Nullify context a))
172 }
169 }
173
170
174
171
175instance (OrdTable a, context ~ Expr) => OrdTable (MaybeTable context a) where
172instance (OrdTable a, context ~ Expr) => OrdTable (MaybeTable context a) where
176 ordTable = HMaybeTable
173 ordTable = HMaybeTable
177− { htag = hlabel (HType Dict)
174+ { htag = hlabel (HIdentity Dict)
178 , hjust = hlabel (ordTable @(Nullify context a))
175 , hjust = hlabel (ordTable @(Nullify context a))
179 }
176 }
180
177
@@ -185,12 +182,12 @@ instance (ToExprs exprs a, context ~ Expr) =>
185
182
186-- | Check if a @MaybeTable@ is absent of any row. Like 'Data.Maybe.isNothing'.
183-- | Check if a @MaybeTable@ is absent of any row. Like 'Data.Maybe.isNothing'.
187isNothingTable :: MaybeTable Expr a -> Expr Bool
184isNothingTable :: MaybeTable Expr a -> Expr Bool
188−isNothingTable (MaybeTable (E tag) _) = isNull tag
185+isNothingTable (MaybeTable tag _) = isNull tag
189
186
190
187
191-- | Check if a @MaybeTable@ contains a row. Like 'Data.Maybe.isJust'.
188-- | Check if a @MaybeTable@ contains a row. Like 'Data.Maybe.isJust'.
192isJustTable :: MaybeTable Expr a -> Expr Bool
189isJustTable :: MaybeTable Expr a -> Expr Bool
193−isJustTable (MaybeTable (E tag) _) = isNonNull tag
190+isJustTable (MaybeTable tag _) = isNonNull tag
194
191
195
192
196-- | Perform case analysis on a 'MaybeTable'. Like 'maybe'.
193-- | Perform case analysis on a 'MaybeTable'. Like 'maybe'.
@@ -201,13 +198,18 @@ maybeTable b f ma@(MaybeTable _ a) = bool (f (extract a)) b (isNothingTable ma)
201
198
202-- | The null table. Like 'Nothing'.
199-- | The null table. Like 'Nothing'.
203nothingTable :: Table Expr a => MaybeTable Expr a
200nothingTable :: Table Expr a => MaybeTable Expr a
204−nothingTable = MaybeTable (E null) (pure undefined)
201+nothingTable = MaybeTable null (pure undefined)
205
202
206
203
207-- | Lift any table into 'MaybeTable'. Like 'Just'. Note you can also use
204-- | Lift any table into 'MaybeTable'. Like 'Just'. Note you can also use
208-- 'pure'.
205-- 'pure'.
209justTable :: a -> MaybeTable Expr a
206justTable :: a -> MaybeTable Expr a
210−justTable = MaybeTable (E mempty) . pure
207+justTable = MaybeTable mempty . pure
208+
209+
210+-- | 'Data.Maybe.fromMaybe' for 'MaybeTable's.
211+fromMaybeTable :: Table Expr a => a -> MaybeTable Expr a -> a
212+fromMaybeTable fallback = maybeTable fallback id
211
213
212
214
213-- | Project a single expression out of a 'MaybeTable'. You can think of this
215-- | Project a single expression out of a 'MaybeTable'. You can think of this
@@ -227,8 +229,8 @@ aggregateMaybeTable :: ()
227 => (exprs -> aggregates)
229 => (exprs -> aggregates)
228 -> MaybeTable Expr exprs
230 -> MaybeTable Expr exprs
229 -> MaybeTable Aggregate aggregates
231 -> MaybeTable Aggregate aggregates
230−aggregateMaybeTable f (MaybeTable (E tag) a) =
232+aggregateMaybeTable f (MaybeTable tag a) =
231− MaybeTable (A (groupByExpr tag)) (aggregateNullify f a)
233+ MaybeTable (groupByExpr tag) (aggregateNullify f a)
232
234
233
235
234-- | Construct a 'MaybeTable' in the 'Name' context. This can be useful if you
236-- | Construct a 'MaybeTable' in the 'Name' context. This can be useful if you
@@ -241,4 +243,4 @@ nameMaybeTable
241 -> a
243 -> a
242 -- ^ Names of the columns in @a@.
244 -- ^ Names of the columns in @a@.
243 -> MaybeTable Name a
245 -> MaybeTable Name a
244−nameMaybeTable tag = MaybeTable (N tag) . pure
246+nameMaybeTable tag = MaybeTable tag . pure
src/Rel8/Table/Name.hs+6−20
@@ -12,7 +12,6 @@
12module Rel8.Table.Name
12module Rel8.Table.Name
13 ( namesFromLabels
13 ( namesFromLabels
14 , namesFromLabelsWith
14 , namesFromLabelsWith
15− , showExprs
16 , showLabels
15 , showLabels
17 , showNames
16 , showNames
18 )
17 )
@@ -25,17 +24,11 @@ import Data.List.NonEmpty ( NonEmpty, intersperse, nonEmpty )
25import Data.Maybe ( fromMaybe )
24import Data.Maybe ( fromMaybe )
26import Prelude
25import Prelude
27
26
28−-- opaleye
29−import qualified Opaleye.Internal.HaskellDB.PrimQuery as Opaleye
30−
31-- rel8
27-- rel8
32−import Rel8.Expr ( Expr( E ) )
33−import Rel8.Expr.Opaleye ( toPrimExpr )
34import Rel8.Schema.HTable ( htabulate, htabulateA, hfield, hspecs )
28import Rel8.Schema.HTable ( htabulate, htabulateA, hfield, hspecs )
35−import Rel8.Schema.Name ( Name( N, Name ) )
29+import Rel8.Schema.Name ( Name( Name ) )
36−import Rel8.Schema.Spec ( SSpec(..) )
30+import Rel8.Schema.Spec ( Spec(..) )
37import Rel8.Table ( Table(..) )
31import Rel8.Table ( Table(..) )
38−import Rel8.Table.Cols ( Cols( Cols ) )
39
32
40
33
41-- | Construct a table in the 'Name' context containing the names of all
34-- | Construct a table in the 'Name' context containing the names of all
@@ -67,26 +60,19 @@ namesFromLabelsWith :: Table Name a
67 => (NonEmpty String -> String) -> a
60 => (NonEmpty String -> String) -> a
68namesFromLabelsWith f = fromColumns $ htabulate $ \field ->
61namesFromLabelsWith f = fromColumns $ htabulate $ \field ->
69 case hfield hspecs field of
62 case hfield hspecs field of
70− SSpec {labels} -> N (Name (f (renderLabels labels)))
63+ Spec {labels} -> Name (f (renderLabels labels))
71−
72−
73−showExprs :: Table Expr a => a -> [(String, Opaleye.PrimExpr)]
74−showExprs as = case (namesFromLabels, toColumns as) of
75− (Cols names, exprs) -> getConst $ htabulateA $ \field ->
76− case (hfield names field, hfield exprs field) of
77− (N (Name name), E expr) -> Const [(name, toPrimExpr expr)]
78
64
79
65
80showLabels :: forall a. Table (Context a) a => a -> [NonEmpty String]
66showLabels :: forall a. Table (Context a) a => a -> [NonEmpty String]
81showLabels _ = getConst $
67showLabels _ = getConst $
82 htabulateA @(Columns a) $ \field -> case hfield hspecs field of
68 htabulateA @(Columns a) $ \field -> case hfield hspecs field of
83− SSpec {labels} -> Const [renderLabels labels]
69+ Spec {labels} -> Const (pure (renderLabels labels))
84
70
85
71
86−showNames :: forall a. Table Name a => a -> [String]
72+showNames :: forall a. Table Name a => a -> NonEmpty String
87showNames (toColumns -> names) = getConst $
73showNames (toColumns -> names) = getConst $
88 htabulateA @(Columns a) $ \field -> case hfield names field of
74 htabulateA @(Columns a) $ \field -> case hfield names field of
89− N (Name name) -> Const [name]
75+ Name name -> Const (pure name)
90
76
91
77
92renderLabels :: [String] -> NonEmpty String
78renderLabels :: [String] -> NonEmpty String
src/Rel8/Table/NonEmpty.hs+34−17
@@ -11,7 +11,9 @@
11
11
12module Rel8.Table.NonEmpty
12module Rel8.Table.NonEmpty
13 ( NonEmptyTable(..)
13 ( NonEmptyTable(..)
14+ , ($+)
15+ , nonEmptyTable
14− , nonEmptyTable, nameNonEmptyTable
16+ , nameNonEmptyTable
15 )
17 )
16where
18where
17
19
@@ -22,24 +24,31 @@ import Data.List.NonEmpty ( NonEmpty )
22import Prelude hiding ( id )
24import Prelude hiding ( id )
23
25
24-- rel8
26-- rel8
25−import Rel8.Expr ( Expr( E, unE ) )
27+import Rel8.Expr ( Expr )
26import Rel8.Expr.Array ( sappend1, snonEmptyOf )
28import Rel8.Expr.Array ( sappend1, snonEmptyOf )
27import Rel8.Schema.Dict ( Dict( Dict ) )
29import Rel8.Schema.Dict ( Dict( Dict ) )
28import Rel8.Schema.HTable.NonEmpty ( HNonEmptyTable )
30import Rel8.Schema.HTable.NonEmpty ( HNonEmptyTable )
29−import Rel8.Schema.HTable.Vectorize ( happend, hvectorize, hunvectorize )
31+import Rel8.Schema.HTable.Vectorize
32+ ( hvectorize, hunvectorize
33+ , happend
34+ , hproject, hcolumn
35+ )
30import qualified Rel8.Schema.Kind as K
36import qualified Rel8.Schema.Kind as K
31−import Rel8.Schema.Name ( Name( N, Name ) )
37+import Rel8.Schema.Name ( Name( Name ) )
32import Rel8.Schema.Null ( Nullity( Null, NotNull ) )
38import Rel8.Schema.Null ( Nullity( Null, NotNull ) )
33import Rel8.Schema.Result ( vectorizer, unvectorizer )
39import Rel8.Schema.Result ( vectorizer, unvectorizer )
34−import Rel8.Schema.Spec ( SSpec(..) )
40+import Rel8.Schema.Spec ( Spec(..) )
35import Rel8.Table
41import Rel8.Table
36 ( Table, Context, Columns, fromColumns, toColumns
42 ( Table, Context, Columns, fromColumns, toColumns
37 , FromExprs, fromResult, toResult
43 , FromExprs, fromResult, toResult
44+ , Transpose
38 )
45 )
39import Rel8.Table.Alternative ( AltTable, (<|>:) )
46import Rel8.Table.Alternative ( AltTable, (<|>:) )
40import Rel8.Table.Eq ( EqTable, eqTable )
47import Rel8.Table.Eq ( EqTable, eqTable )
41import Rel8.Table.Ord ( OrdTable, ordTable )
48import Rel8.Table.Ord ( OrdTable, ordTable )
42−import Rel8.Table.Recontextualize ( Recontextualize )
49+import Rel8.Table.Projection
50+ ( Projectable, Projecting, Projection, project, apply
51+ )
43import Rel8.Table.Serialize ( ToExprs )
52import Rel8.Table.Serialize ( ToExprs )
44
53
45
54
@@ -50,12 +59,18 @@ newtype NonEmptyTable context a =
50 NonEmptyTable (HNonEmptyTable (Columns a) (Context a))
59 NonEmptyTable (HNonEmptyTable (Columns a) (Context a))
51
60
52
61
62+instance Projectable (NonEmptyTable context) where
63+ project f (NonEmptyTable a) = NonEmptyTable (hproject (apply f) a)
64+
65+
53instance (Table context a, context ~ context') =>
66instance (Table context a, context ~ context') =>
54 Table context' (NonEmptyTable context a)
67 Table context' (NonEmptyTable context a)
55 where
68 where
56 type Columns (NonEmptyTable context a) = HNonEmptyTable (Columns a)
69 type Columns (NonEmptyTable context a) = HNonEmptyTable (Columns a)
57 type Context (NonEmptyTable context a) = Context a
70 type Context (NonEmptyTable context a) = Context a
58 type FromExprs (NonEmptyTable context a) = NonEmpty (FromExprs a)
71 type FromExprs (NonEmptyTable context a) = NonEmpty (FromExprs a)
72+ type Transpose to (NonEmptyTable context a) =
73+ NonEmptyTable to (Transpose to a)
59
74
60 fromColumns = NonEmptyTable
75 fromColumns = NonEmptyTable
61 toColumns (NonEmptyTable a) = a
76 toColumns (NonEmptyTable a) = a
@@ -63,16 +78,12 @@ instance (Table context a, context ~ context') =>
63 toResult = hvectorize vectorizer . fmap (toResult @_ @a)
78 toResult = hvectorize vectorizer . fmap (toResult @_ @a)
64
79
65
80
66−instance (Recontextualize from to a b, from ~ from', to ~ to') =>
67− Recontextualize from to (NonEmptyTable from' a) (NonEmptyTable to' b)
68−
69−
70instance (EqTable a, context ~ Expr) =>
81instance (EqTable a, context ~ Expr) =>
71 EqTable (NonEmptyTable context a)
82 EqTable (NonEmptyTable context a)
72 where
83 where
73 eqTable =
84 eqTable =
74 hvectorize
85 hvectorize
75− (\SSpec {nullity} (Identity Dict) -> case nullity of
86+ (\Spec {nullity} (Identity Dict) -> case nullity of
76 Null -> Dict
87 Null -> Dict
77 NotNull -> Dict)
88 NotNull -> Dict)
78 (Identity (eqTable @a))
89 (Identity (eqTable @a))
@@ -83,7 +94,7 @@ instance (OrdTable a, context ~ Expr) =>
83 where
94 where
84 ordTable =
95 ordTable =
85 hvectorize
96 hvectorize
86− (\SSpec {nullity} (Identity Dict) -> case nullity of
97+ (\Spec {nullity} (Identity Dict) -> case nullity of
87 Null -> Dict
98 Null -> Dict
88 NotNull -> Dict)
99 NotNull -> Dict)
89 (Identity (ordTable @a))
100 (Identity (ordTable @a))
@@ -97,18 +108,24 @@ instance context ~ Expr => AltTable (NonEmptyTable context) where
97 (<|>:) = (<>)
108 (<|>:) = (<>)
98
109
99
110
100−instance (Table Expr a, context ~ Expr) =>
101− Semigroup (NonEmptyTable context a)
111+instance (Table Expr a, context ~ Expr) => Semigroup (NonEmptyTable context a)
102 where
112 where
103 NonEmptyTable as <> NonEmptyTable bs = NonEmptyTable $
113 NonEmptyTable as <> NonEmptyTable bs = NonEmptyTable $
104− happend (\_ _ (E a) (E b) -> E (sappend1 a b)) as bs
114+ happend (const sappend1) as bs
115+
116+
117+-- | Project a single expression out of a 'NonEmptyTable'.
118+($+) :: Projecting a (Expr b)
119+ => Projection a (Expr b) -> NonEmptyTable Expr a -> Expr (NonEmpty b)
120+f $+ NonEmptyTable a = hcolumn $ hproject (apply f) a
121+infixl 4 $+
105
122
106
123
107-- | Construct a @NonEmptyTable@ from a non-empty list of expressions.
124-- | Construct a @NonEmptyTable@ from a non-empty list of expressions.
108nonEmptyTable :: Table Expr a => NonEmpty a -> NonEmptyTable Expr a
125nonEmptyTable :: Table Expr a => NonEmpty a -> NonEmptyTable Expr a
109nonEmptyTable =
126nonEmptyTable =
110 NonEmptyTable .
127 NonEmptyTable .
111− hvectorize (\SSpec {info} -> E . snonEmptyOf info . fmap unE) .
128+ hvectorize (\Spec {info} -> snonEmptyOf info) .
112 fmap toColumns
129 fmap toColumns
113
130
114
131
@@ -121,6 +138,6 @@ nameNonEmptyTable
121 -> NonEmptyTable Name a
138 -> NonEmptyTable Name a
122nameNonEmptyTable =
139nameNonEmptyTable =
123 NonEmptyTable .
140 NonEmptyTable .
124− hvectorize (\_ (Identity (N (Name a))) -> N (Name a)) .
141+ hvectorize (\_ (Identity (Name a)) -> Name a) .
125 pure .
142 pure .
126 toColumns
143 toColumns
src/Rel8/Table/Null.hsnew file+147
@@ -0,0 +1,147 @@
1+{-# language DataKinds #-}
2+{-# language FlexibleContexts #-}
3+{-# language FlexibleInstances #-}
4+{-# language MultiParamTypeClasses #-}
5+{-# language ScopedTypeVariables #-}
6+{-# language StandaloneKindSignatures #-}
7+{-# language TypeApplications #-}
8+{-# language TypeFamilies #-}
9+{-# language UndecidableInstances #-}
10+
11+module Rel8.Table.Null
12+ ( NullTable(..)
13+ , nullableTable, nullTable, nullifyTable, unsafeUnnullifyTable
14+ , isNullTable, isNonNullTable
15+ , nameNullTable
16+ , toMaybeTable, toNullTable
17+ )
18+where
19+
20+-- base
21+import Data.Kind ( Type )
22+import Prelude hiding ( null, undefined )
23+
24+-- comonad
25+import Control.Comonad ( extract )
26+
27+-- rel8
28+import Rel8.Expr ( Expr )
29+import Rel8.Expr.Bool ( not_ )
30+import Rel8.Kind.Context ( Reifiable )
31+import qualified Rel8.Schema.Kind as K
32+import Rel8.Schema.Name ( Name )
33+import Rel8.Table
34+ ( Table, Columns, Context, fromColumns, toColumns
35+ , FromExprs, fromResult, toResult
36+ , Transpose
37+ )
38+import Rel8.Table.Alternative
39+ ( AltTable, (<|>:)
40+ , AlternativeTable, emptyTable
41+ )
42+import Rel8.Table.Bool ( bool )
43+import Rel8.Table.Eq ( EqTable, eqTable )
44+import Rel8.Table.Maybe ( MaybeTable, justTable, maybeTable, nothingTable )
45+import Rel8.Table.Nullify ( Nullify, isNull )
46+import Rel8.Table.Ord ( OrdTable, ordTable )
47+import Rel8.Table.Projection ( Projectable, project )
48+import Rel8.Table.Serialize ( ToExprs )
49+import Rel8.Table.Undefined ( undefined )
50+
51+
52+-- | @NullTable t@ is the table @t@, but where all the columns in @t@ have the
53+-- possibility of being 'Rel8.null'. This is very similar to
54+-- 'Rel8.MaybeTable', except that it does not use an extra tag field, so it
55+-- cannot distinguish between @Nothing@ and @Just Nothing@ if nested. In other
56+-- words, if all of the columns of the @t@ passed to @NullTable@ are already
57+-- nullable, then @NullTable@ has no effect.
58+type NullTable :: K.Context -> Type -> Type
59+newtype NullTable context a = NullTable (Nullify context a)
60+
61+
62+instance Projectable (NullTable context) where
63+ project f (NullTable a) = NullTable (project f a)
64+
65+
66+instance context ~ Expr => AltTable (NullTable context) where
67+ ma <|>: mb = bool ma mb (isNullTable ma)
68+
69+
70+instance context ~ Expr => AlternativeTable (NullTable context) where
71+ emptyTable = nullTable
72+
73+
74+instance (Table context a, Reifiable context, context ~ context') =>
75+ Table context' (NullTable context a)
76+ where
77+ type Columns (NullTable context a) = Columns (Nullify context a)
78+ type Context (NullTable context a) = Context (Nullify context a)
79+ type FromExprs (NullTable context a) = FromExprs (Nullify context a)
80+ type Transpose to (NullTable context a) = NullTable to (Transpose to a)
81+
82+ toColumns (NullTable a) = toColumns a
83+ fromColumns = NullTable . fromColumns
84+
85+ toResult = toResult @_ @(Nullify context a)
86+ fromResult = fromResult @_ @(Nullify context a)
87+
88+
89+instance (EqTable a, context ~ Expr) => EqTable (NullTable context a) where
90+ eqTable = eqTable @(Nullify context a)
91+
92+
93+instance (OrdTable a, context ~ Expr) => OrdTable (NullTable context a) where
94+ ordTable = ordTable @(Nullify context a)
95+
96+
97+instance (ToExprs exprs a, context ~ Expr) =>
98+ ToExprs (NullTable context exprs) (Maybe a)
99+
100+
101+-- | Check if any of the non-nullable fields of @a@ are 'Rel8.null' under the
102+-- 'NullTable'. Returns 'Rel8.false' if @a@ has no non-nullable fields.
103+isNullTable :: Table Expr a => NullTable Expr a -> Expr Bool
104+isNullTable (NullTable a) = isNull a
105+
106+
107+-- | The inverse of 'isNullTable'.
108+isNonNullTable :: Table Expr a => NullTable Expr a -> Expr Bool
109+isNonNullTable = not_ . isNullTable
110+
111+
112+-- | Like 'Rel8.nullable'.
113+nullableTable :: (Table Expr a, Table Expr b)
114+ => b -> (a -> b) -> NullTable Expr a -> b
115+nullableTable b f ma@(NullTable a) = bool (f (extract a)) b (isNullTable ma)
116+
117+
118+-- | The null table. Like 'Rel8.null'.
119+nullTable :: Table Expr a => NullTable Expr a
120+nullTable = NullTable (pure undefined)
121+
122+
123+-- | Lift any table into 'NullTable'. Like 'Rel8.nullify'.
124+nullifyTable :: a -> NullTable Expr a
125+nullifyTable = NullTable . pure
126+
127+
128+unsafeUnnullifyTable :: NullTable Expr a -> a
129+unsafeUnnullifyTable (NullTable a) = extract a
130+
131+
132+-- | Construct a 'NullTable' in the 'Name' context. This can be useful if you
133+-- have a 'NullTable' that you are storing in a table and need to construct a
134+-- 'TableSchema'.
135+nameNullTable :: a -> NullTable Name a
136+nameNullTable = NullTable . pure
137+
138+
139+-- | Convert a 'NullTable' to a 'MaybeTable'.
140+toMaybeTable :: Table Expr a => NullTable Expr a -> MaybeTable Expr a
141+toMaybeTable = nullableTable nothingTable justTable
142+
143+
144+-- | Convert a 'MaybeTable' to a 'NullTable'. Note that if the underlying @a@
145+-- has no non-nullable fields, this is a lossy conversion.
146+toNullTable :: Table Expr a => MaybeTable Expr a -> NullTable Expr a
147+toNullTable = maybeTable nullTable nullifyTable
src/Rel8/Table/Nullify.hs+42−12
@@ -1,7 +1,9 @@
1{-# language DataKinds #-}
1{-# language DataKinds #-}
2+{-# language FlexibleContexts #-}
2{-# language FlexibleInstances #-}
3{-# language FlexibleInstances #-}
3{-# language LambdaCase #-}
4{-# language LambdaCase #-}
4{-# language MultiParamTypeClasses #-}
5{-# language MultiParamTypeClasses #-}
6+{-# language NamedFieldPuns #-}
5{-# language ScopedTypeVariables #-}
7{-# language ScopedTypeVariables #-}
6{-# language StandaloneKindSignatures #-}
8{-# language StandaloneKindSignatures #-}
7{-# language TypeApplications #-}
9{-# language TypeApplications #-}
@@ -12,11 +14,13 @@ module Rel8.Table.Nullify
12 ( Nullify
14 ( Nullify
13 , aggregateNullify
15 , aggregateNullify
14 , guard
16 , guard
17+ , isNull
15 )
18 )
16where
19where
17
20
18-- base
21-- base
19import Control.Applicative ( liftA2 )
22import Control.Applicative ( liftA2 )
23+import Data.Functor.Const ( Const( Const ), getConst )
20import Data.Functor.Identity ( runIdentity )
24import Data.Functor.Identity ( runIdentity )
21import Data.Kind ( Type )
25import Data.Kind ( Type )
22import Prelude
26import Prelude
@@ -27,6 +31,8 @@ import Control.Comonad ( Comonad, duplicate, extract, ComonadApply, (<@>) )
27-- rel8
31-- rel8
28import Rel8.Aggregate ( Aggregate )
32import Rel8.Aggregate ( Aggregate )
29import Rel8.Expr ( Expr )
33import Rel8.Expr ( Expr )
34+import Rel8.Expr.Bool ( (||.), false )
35+import qualified Rel8.Expr.Null as Expr
30import Rel8.Kind.Context ( Reifiable, contextSing )
36import Rel8.Kind.Context ( Reifiable, contextSing )
31import Rel8.Schema.Context.Nullify
37import Rel8.Schema.Context.Nullify
32 ( Nullifiability( NAggregate, NExpr )
38 ( Nullifiability( NAggregate, NExpr )
@@ -39,17 +45,23 @@ import Rel8.Schema.Context.Nullify
39 )
45 )
40import Rel8.Schema.Dict ( Dict( Dict ) )
46import Rel8.Schema.Dict ( Dict( Dict ) )
41import Rel8.Schema.HTable ( HTable )
47import Rel8.Schema.HTable ( HTable )
48+import Rel8.Schema.HTable.Nullify
42−import Rel8.Schema.HTable.Nullify ( HNullify, hnulls, hnullify, hunnullify, hguard )
49+ ( HNullify, hnulls, hnullify, hunnullify
50+ , hguard
51+ , hproject
52+ )
43import qualified Rel8.Schema.Kind as K
53import qualified Rel8.Schema.Kind as K
54+import Rel8.Schema.Null ( Nullity( NotNull, Null ) )
44import qualified Rel8.Schema.Result as R
55import qualified Rel8.Schema.Result as R
45−import Rel8.Schema.Spec ( Spec( Spec ) )
46import Rel8.Table
56import Rel8.Table
47 ( Table, Columns, Context, toColumns, fromColumns
57 ( Table, Columns, Context, toColumns, fromColumns
48 , FromExprs, fromResult, toResult
58 , FromExprs, fromResult, toResult
59+ , Transpose
49 )
60 )
61+import Rel8.Schema.Spec ( Spec( Spec, nullity ) )
50import Rel8.Table.Eq ( EqTable, eqTable )
62import Rel8.Table.Eq ( EqTable, eqTable )
51import Rel8.Table.Ord ( OrdTable, ordTable )
63import Rel8.Table.Ord ( OrdTable, ordTable )
52−import Rel8.Table.Recontextualize ( Recontextualize )
64+import Rel8.Table.Projection ( Projectable, apply, project )
53
65
54-- semigroupoids
66-- semigroupoids
55import Data.Functor.Apply ( Apply, (<.>), liftF2 )
67import Data.Functor.Apply ( Apply, (<.>), liftF2 )
@@ -63,6 +75,12 @@ data Nullify context a
63 | Fields (NonNullifiability context) (HNullify (Columns a) (Context a))
75 | Fields (NonNullifiability context) (HNullify (Columns a) (Context a))
64
76
65
77
78+instance Projectable (Nullify context) where
79+ project f = \case
80+ Table nullifiable a -> Table nullifiable (fromColumns (apply f (toColumns a)))
81+ Fields nonNullifiable a -> Fields nonNullifiable (hproject (apply f) a)
82+
83+
66instance Nullifiable context => Functor (Nullify context) where
84instance Nullifiable context => Functor (Nullify context) where
67 fmap f = \case
85 fmap f = \case
68 Table nullifiable a -> Table nullifiable (f a)
86 Table nullifiable a -> Table nullifiable (f a)
@@ -126,6 +144,7 @@ instance (Table context a, Reifiable context, context ~ context') =>
126 type Columns (Nullify context a) = HNullify (Columns a)
144 type Columns (Nullify context a) = HNullify (Columns a)
127 type Context (Nullify context a) = Context a
145 type Context (Nullify context a) = Context a
128 type FromExprs (Nullify context a) = Maybe (FromExprs a)
146 type FromExprs (Nullify context a) = Maybe (FromExprs a)
147+ type Transpose to (Nullify context a) = Nullify to (Transpose to a)
129
148
130 fromColumns = case nullifiableOrNot contextSing of
149 fromColumns = case nullifiableOrNot contextSing of
131 Left notNullifiable -> Fields notNullifiable
150 Left notNullifiable -> Fields notNullifiable
@@ -146,14 +165,6 @@ instance (Table context a, Reifiable context, context ~ context') =>
146 fmap (toResult @_ @a)
165 fmap (toResult @_ @a)
147
166
148
167
149−instance
150− ( Recontextualize from to a b
151− , Reifiable from, from ~ from'
152− , Reifiable to, to ~ to'
153− )
154− => Recontextualize from' to' (Nullify from a) (Nullify to b)
155−
156−
157instance (EqTable a, context ~ Expr) => EqTable (Nullify context a) where
168instance (EqTable a, context ~ Expr) => EqTable (Nullify context a) where
158 eqTable = hnullify (\_ Dict -> Dict) (eqTable @a)
169 eqTable = hnullify (\_ Dict -> Dict) (eqTable @a)
159
170
@@ -172,10 +183,29 @@ aggregateNullify f = \case
172
183
173
184
174guard :: (Reifiable context, HTable t)
185guard :: (Reifiable context, HTable t)
175− => context ('Spec tag)
186+ => context tag
176 -> (tag -> Bool)
187 -> (tag -> Bool)
177 -> (Expr tag -> Expr Bool)
188 -> (Expr tag -> Expr Bool)
178 -> HNullify t context
189 -> HNullify t context
179 -> HNullify t context
190 -> HNullify t context
180guard tag isNonNull isNonNullExpr =
191guard tag isNonNull isNonNullExpr =
181 hguard (guarder contextSing tag isNonNull isNonNullExpr)
192 hguard (guarder contextSing tag isNonNull isNonNullExpr)
193+
194+
195+isNull :: forall a. Table Expr a => Nullify Expr a -> Expr Bool
196+isNull =
197+ maybe false getAny .
198+ getConst .
199+ hunnullify (\Spec {nullity} a -> Const $ case nullity of
200+ NotNull -> Just $ Any $ Expr.isNull a
201+ Null -> Nothing) .
202+ toColumns
203+
204+
205+newtype Any = Any
206+ { getAny :: Expr Bool
207+ }
208+
209+
210+instance Semigroup Any where
211+ Any a <> Any b = Any (a ||. b)
src/Rel8/Table/Opaleye.hs+75−63
@@ -2,92 +2,112 @@
2{-# language DataKinds #-}
2{-# language DataKinds #-}
3{-# language DisambiguateRecordFields #-}
3{-# language DisambiguateRecordFields #-}
4{-# language FlexibleContexts #-}
4{-# language FlexibleContexts #-}
5−{-# language LambdaCase #-}
6{-# language NamedFieldPuns #-}
5{-# language NamedFieldPuns #-}
7{-# language RankNTypes #-}
6{-# language RankNTypes #-}
8{-# language TypeFamilies #-}
7{-# language TypeFamilies #-}
9{-# language ViewPatterns #-}
8{-# language ViewPatterns #-}
10
9
10+{-# options_ghc -Wno-deprecations #-}
11+
11module Rel8.Table.Opaleye
12module Rel8.Table.Opaleye
12 ( aggregator
13 ( aggregator
14+ , attributes
13 , binaryspec
15 , binaryspec
14 , distinctspec
16 , distinctspec
17+ , exprs
18+ , exprsWithNames
15 , table
19 , table
16 , tableFields
20 , tableFields
17 , unpackspec
21 , unpackspec
18 , valuesspec
22 , valuesspec
23+ , view
19 , castTable
24 , castTable
20 )
25 )
21where
26where
22
27
23-- base
28-- base
24−import Prelude hiding ( undefined )
29+import Data.Functor.Const ( Const( Const ), getConst )
30+import Data.List.NonEmpty ( NonEmpty )
31+import Prelude
25
32
26-- opaleye
33-- opaleye
34+import qualified Opaleye.Adaptors as Opaleye
35+import qualified Opaleye.Field as Opaleye ( Field_ )
27import qualified Opaleye.Internal.Aggregate as Opaleye
36import qualified Opaleye.Internal.Aggregate as Opaleye
28−import qualified Opaleye.Internal.Binary as Opaleye
29−import qualified Opaleye.Internal.Distinct as Opaleye
30import qualified Opaleye.Internal.HaskellDB.PrimQuery as Opaleye
37import qualified Opaleye.Internal.HaskellDB.PrimQuery as Opaleye
31−import qualified Opaleye.Internal.PackMap as Opaleye
32−import qualified Opaleye.Internal.Unpackspec as Opaleye
33import qualified Opaleye.Internal.Values as Opaleye
38import qualified Opaleye.Internal.Values as Opaleye
34−import qualified Opaleye.Internal.Table as Opaleye
39+import qualified Opaleye.Table as Opaleye
35
40
36-- profunctors
41-- profunctors
37import Data.Profunctor ( dimap, lmap )
42import Data.Profunctor ( dimap, lmap )
38
43
39-- rel8
44-- rel8
40−import Rel8.Aggregate ( Aggregate( A, Aggregate ), Aggregates )
45+import Rel8.Aggregate ( Aggregate( Aggregate ), Aggregates )
41−import Rel8.Expr ( Expr(..) )
46+import Rel8.Expr ( Expr )
42import Rel8.Expr.Opaleye
47import Rel8.Expr.Opaleye
43 ( fromPrimExpr, toPrimExpr
48 ( fromPrimExpr, toPrimExpr
44− , traversePrimExpr
45− , fromColumn, toColumn
46− , scastExpr
49+ , scastExpr, traverseFieldP
47 )
50 )
48−import Rel8.Schema.HTable ( htabulateA, hfield, htraverse, hspecs, htabulate )
51+import Rel8.Schema.HTable ( htabulateA, hfield, hspecs, htabulate,
52+ htraverseP, htraversePWithField )
49−import Rel8.Schema.Name ( Name( N, Name ), Selects )
53+import Rel8.Schema.Name ( Name( Name ), Selects, ppColumn )
50−import Rel8.Schema.Spec ( Spec, SSpec(..) )
54+import Rel8.Schema.Spec ( Spec(..) )
51−import Rel8.Schema.Table ( TableSchema(..) )
55+import Rel8.Schema.Table ( TableSchema(..), ppTable )
52import Rel8.Table ( Table, fromColumns, toColumns )
56import Rel8.Table ( Table, fromColumns, toColumns )
53−import Rel8.Table.Undefined ( undefined )
57+import Rel8.Type.Information ( typeName )
54
58
55-- semigroupoids
59-- semigroupoids
56import Data.Functor.Apply ( WrappedApplicative(..) )
60import Data.Functor.Apply ( WrappedApplicative(..) )
61+import Data.Profunctor.Product ( ProductProfunctor )
57
62
58
63
59aggregator :: Aggregates aggregates exprs => Opaleye.Aggregator aggregates exprs
64aggregator :: Aggregates aggregates exprs => Opaleye.Aggregator aggregates exprs
60−aggregator = Opaleye.Aggregator $ Opaleye.PackMap $ \f aggregates ->
65+aggregator = dimap toColumns fromColumns $
61− fmap fromColumns $ unwrapApplicative $ htabulateA $ \field ->
66+ htraverseP $
67+ lmap (\(Aggregate a) -> (a, ())) Opaleye.aggregatorApply
68+
69+
70+attributes :: Selects names exprs => TableSchema names -> exprs
71+attributes schema@TableSchema {columns} = fromColumns $ htabulate $ \field ->
62− WrapApplicative $ case hfield (toColumns aggregates) field of
72+ case hfield (toColumns columns) field of
63− A (Aggregate (Opaleye.Aggregator (Opaleye.PackMap inner))) ->
73+ Name column -> fromPrimExpr $ Opaleye.ConstExpr $
64− E <$> inner f ()
74+ Opaleye.OtherLit $
75+ show (ppTable schema) <> "." <> show (ppColumn column)
76+
77+
78+fromOpaleyespec :: (ProductProfunctor p, Table Expr a)
79+ => p (Opaleye.Field_ n x) (Opaleye.Field_ n x)
80+ -> p a a
81+fromOpaleyespec x =
82+ dimap toColumns fromColumns (htraverseP (traverseFieldP x))
65
83
66
84
67binaryspec :: Table Expr a => Opaleye.Binaryspec a a
85binaryspec :: Table Expr a => Opaleye.Binaryspec a a
68−binaryspec = Opaleye.Binaryspec $ Opaleye.PackMap $ \f (as, bs) ->
86+binaryspec = fromOpaleyespec Opaleye.binaryspecField
69− fmap fromColumns $ unwrapApplicative $ htabulateA $ \field ->
70− WrapApplicative $
71− case (hfield (toColumns as) field, hfield (toColumns bs) field) of
72− (E a, E b) -> E . fromPrimExpr <$> f (toPrimExpr a, toPrimExpr b)
73
87
74
88
75distinctspec :: Table Expr a => Opaleye.Distinctspec a a
89distinctspec :: Table Expr a => Opaleye.Distinctspec a a
76−distinctspec =
90+distinctspec = fromOpaleyespec Opaleye.distinctspecField
77− Opaleye.Distinctspec $ Opaleye.Aggregator $ Opaleye.PackMap $ \f ->
91+
78− fmap fromColumns .
92+
79− unwrapApplicative .
93+exprs :: Table Expr a => a -> NonEmpty Opaleye.PrimExpr
80− htraverse
94+exprs (toColumns -> as) = getConst $ htabulateA $ \field ->
81− (\(E a) ->
95+ case hfield as field of
82− WrapApplicative $ E . fromPrimExpr <$> f (Nothing, toPrimExpr a)) .
96+ expr -> Const (pure (toPrimExpr expr))
83− toColumns
97+
98+
99+exprsWithNames :: Selects names exprs
100+ => names -> exprs -> NonEmpty (String, Opaleye.PrimExpr)
101+exprsWithNames names as = getConst $ htabulateA $ \field ->
102+ case (hfield (toColumns names) field, hfield (toColumns as) field) of
103+ (Name name, expr) -> Const (pure (name, toPrimExpr expr))
84
104
85
105
86−table ::Selects names exprs => TableSchema names -> Opaleye.Table exprs exprs
106+table :: Selects names exprs => TableSchema names -> Opaleye.Table exprs exprs
87table (TableSchema name schema columns) =
107table (TableSchema name schema columns) =
88 case schema of
108 case schema of
89− Nothing -> Opaleye.Table name (tableFields columns)
109+ Nothing -> Opaleye.table name (tableFields columns)
90− Just schemaName -> Opaleye.TableWithSchema schemaName name (tableFields columns)
110+ Just schemaName -> Opaleye.tableWithSchema schemaName name (tableFields columns)
91
111
92
112
93tableFields :: Selects names exprs
113tableFields :: Selects names exprs
@@ -97,42 +117,34 @@ tableFields (toColumns -> names) = dimap toColumns fromColumns $
97 case hfield names field of
117 case hfield names field of
98 name -> lmap (`hfield` field) (go name)
118 name -> lmap (`hfield` field) (go name)
99 where
119 where
100− go :: forall (spec :: Spec). Name spec -> Opaleye.TableFields (Expr spec) (Expr spec)
120+ go :: Name a -> Opaleye.TableFields (Expr a) (Expr a)
101− go (N (Name name)) =
121+ go (Name name) =
102− lmap (\(E a) -> toColumn $ toPrimExpr a) $
122+ traverseFieldP $
103− E . fromPrimExpr . fromColumn <$>
104− Opaleye.requiredTableField name
123+ Opaleye.requiredTableField name
105
124
106
125
107unpackspec :: Table Expr a => Opaleye.Unpackspec a a
126unpackspec :: Table Expr a => Opaleye.Unpackspec a a
108−unpackspec = Opaleye.Unpackspec $ Opaleye.PackMap $ \f ->
127+unpackspec = fromOpaleyespec Opaleye.unpackspecField
109− fmap fromColumns .
110− unwrapApplicative .
111− htraverse (\(E a) -> WrapApplicative $ E <$> traversePrimExpr f a) .
112− toColumns
113{-# INLINABLE unpackspec #-}
128{-# INLINABLE unpackspec #-}
114
129
115
130
116−valuesspec :: Table Expr a => Opaleye.ValuesspecSafe a a
131+valuesspec :: Table Expr a => Opaleye.Valuesspec a a
117−valuesspec = Opaleye.ValuesspecSafe (toPackMap undefined) unpackspec
132+valuesspec = dimap toColumns fromColumns $
133+ htraversePWithField (traverseFieldP . Opaleye.valuesspecFieldType . typeName)
134+ where typeName = Rel8.Type.Information.typeName . info . hfield hspecs
118
135
119
136
120−toPackMap :: Table Expr a
137+view :: Selects names exprs => names -> exprs
121− => a -> Opaleye.PackMap Opaleye.PrimExpr Opaleye.PrimExpr () a
122−toPackMap as = Opaleye.PackMap $ \f () ->
123− fmap fromColumns $
138+view columns = fromColumns $ htabulate $ \field ->
124− unwrapApplicative .
125− htraverse (\(E a) -> WrapApplicative $ E <$> traversePrimExpr f a) $
126− toColumns as
139+ case hfield (toColumns columns) field of
140+ Name column -> fromPrimExpr $ Opaleye.BaseTableAttrExpr column
127
141
128
142
129-- | Transform a table by adding 'CAST' to all columns. This is most useful for
143-- | Transform a table by adding 'CAST' to all columns. This is most useful for
130-- finalising a SELECT or RETURNING statement, guaranteed that the output
144-- finalising a SELECT or RETURNING statement, guaranteed that the output
131-- matches what is encoded in each columns TypeInformation.
145-- matches what is encoded in each columns TypeInformation.
132castTable :: Table Expr a => a -> a
146castTable :: Table Expr a => a -> a
133−castTable (toColumns -> as) = fromColumns $ htabulate \i ->
147+castTable (toColumns -> as) = fromColumns $ htabulate \field ->
134− case hfield hspecs i of
148+ case hfield hspecs field of
135− SSpec{info} ->
136− case hfield as i of
149+ Spec {info} -> case hfield as field of
137− E expr ->
138− E (scastExpr info expr)
150+ expr -> scastExpr info expr
src/Rel8/Table/Ord.hs+14−22
@@ -10,7 +10,6 @@
10{-# language TypeFamilies #-}
10{-# language TypeFamilies #-}
11{-# language TypeOperators #-}
11{-# language TypeOperators #-}
12{-# language UndecidableInstances #-}
12{-# language UndecidableInstances #-}
13−{-# language UndecidableSuperClasses #-}
14{-# language ViewPatterns #-}
13{-# language ViewPatterns #-}
15
14
16module Rel8.Table.Ord
15module Rel8.Table.Ord
@@ -25,7 +24,7 @@ import GHC.Generics ( Rep )
25import Prelude hiding ( seq )
24import Prelude hiding ( seq )
26
25
27-- rel8
26-- rel8
28−import Rel8.Expr ( Expr( E ) )
27+import Rel8.Expr ( Expr )
29import Rel8.Expr.Bool ( (||.), (&&.), false, true )
28import Rel8.Expr.Bool ( (||.), (&&.), false, true )
30import Rel8.Expr.Eq ( (==.) )
29import Rel8.Expr.Eq ( (==.) )
31import Rel8.Expr.Ord ( (<.), (>.) )
30import Rel8.Expr.Ord ( (<.), (>.) )
@@ -34,10 +33,9 @@ import Rel8.Generic.Record ( Record )
34import Rel8.Generic.Table.Record ( GTable, GColumns, gtable )
33import Rel8.Generic.Table.Record ( GTable, GColumns, gtable )
35import Rel8.Schema.Dict ( Dict( Dict ) )
34import Rel8.Schema.Dict ( Dict( Dict ) )
36import Rel8.Schema.HTable ( htabulateA, hfield )
35import Rel8.Schema.HTable ( htabulateA, hfield )
37−import Rel8.Schema.HTable.Identity ( HIdentity( HType ) )
36+import Rel8.Schema.HTable.Identity ( HIdentity( HIdentity ) )
38import Rel8.Schema.Null (Sql)
37import Rel8.Schema.Null (Sql)
39−import Rel8.Schema.Spec.Constrain ( ConstrainSpec )
40−import Rel8.Table ( Columns, toColumns, TColumns, TFromExprs )
38+import Rel8.Table ( Columns, toColumns, TColumns )
41import Rel8.Table.Bool ( bool )
39import Rel8.Table.Bool ( bool )
42import Rel8.Table.Eq ( EqTable )
40import Rel8.Table.Eq ( EqTable )
43import Rel8.Type.Ord ( DBOrd )
41import Rel8.Type.Ord ( DBOrd )
@@ -48,20 +46,14 @@ import Rel8.Type.Ord ( DBOrd )
48-- columns in a 'Table' have an instance of 'DBOrd'".
46-- columns in a 'Table' have an instance of 'DBOrd'".
49type OrdTable :: Type -> Constraint
47type OrdTable :: Type -> Constraint
50class EqTable a => OrdTable a where
48class EqTable a => OrdTable a where
51− ordTable :: Columns a (Dict (ConstrainSpec (Sql DBOrd)))
49+ ordTable :: Columns a (Dict (Sql DBOrd))
52
50
53 default ordTable ::
51 default ordTable ::
54− ( GTable TOrdTable TColumns TFromExprs (Rep (Record a))
52+ ( GTable TOrdTable TColumns (Rep (Record a))
55 , Columns a ~ GColumns TColumns (Rep (Record a))
53 , Columns a ~ GColumns TColumns (Rep (Record a))
56 )
54 )
57− => Columns a (Dict (ConstrainSpec (Sql DBOrd)))
55+ => Columns a (Dict (Sql DBOrd))
58− ordTable =
56+ ordTable = gtable @TOrdTable @TColumns @(Rep (Record a)) table
59− gtable
60− @TOrdTable
61− @TColumns
62− @TFromExprs
63− @(Rep (Record a))
64− table
65 where
57 where
66 table (_ :: proxy x) = ordTable @x
58 table (_ :: proxy x) = ordTable @x
67
59
@@ -71,7 +63,7 @@ type instance Eval (TOrdTable a) = OrdTable a
71
63
72
64
73instance Sql DBOrd a => OrdTable (Expr a) where
65instance Sql DBOrd a => OrdTable (Expr a) where
74− ordTable = HType Dict
66+ ordTable = HIdentity Dict
75
67
76
68
77instance (OrdTable a, OrdTable b) => OrdTable (a, b)
69instance (OrdTable a, OrdTable b) => OrdTable (a, b)
@@ -106,7 +98,7 @@ instance
106(toColumns -> as) <: (toColumns -> bs) =
98(toColumns -> as) <: (toColumns -> bs) =
107 foldr @[] go false $ getConst $ htabulateA $ \field ->
99 foldr @[] go false $ getConst $ htabulateA $ \field ->
108 case (hfield as field, hfield bs field) of
100 case (hfield as field, hfield bs field) of
109− (E a, E b) -> case hfield (ordTable @a) field of
101+ (a, b) -> case hfield (ordTable @a) field of
110 Dict -> Const [(a <. b, a ==. b)]
102 Dict -> Const [(a <. b, a ==. b)]
111 where
103 where
112 go (lt, eq) a = lt ||. (eq &&. a)
104 go (lt, eq) a = lt ||. (eq &&. a)
@@ -119,7 +111,7 @@ infix 4 <:
119(toColumns -> as) <=: (toColumns -> bs) =
111(toColumns -> as) <=: (toColumns -> bs) =
120 foldr @[] go true $ getConst $ htabulateA $ \field ->
112 foldr @[] go true $ getConst $ htabulateA $ \field ->
121 case (hfield as field, hfield bs field) of
113 case (hfield as field, hfield bs field) of
122− (E a, E b) -> case hfield (ordTable @a) field of
114+ (a, b) -> case hfield (ordTable @a) field of
123 Dict -> Const [(a <. b, a ==. b)]
115 Dict -> Const [(a <. b, a ==. b)]
124 where
116 where
125 go (lt, eq) a = lt ||. (eq &&. a)
117 go (lt, eq) a = lt ||. (eq &&. a)
@@ -132,7 +124,7 @@ infix 4 <=:
132(toColumns -> as) >: (toColumns -> bs) =
124(toColumns -> as) >: (toColumns -> bs) =
133 foldr @[] go false $ getConst $ htabulateA $ \field ->
125 foldr @[] go false $ getConst $ htabulateA $ \field ->
134 case (hfield as field, hfield bs field) of
126 case (hfield as field, hfield bs field) of
135− (E a, E b) -> case hfield (ordTable @a) field of
127+ (a, b) -> case hfield (ordTable @a) field of
136 Dict -> Const [(a >. b, a ==. b)]
128 Dict -> Const [(a >. b, a ==. b)]
137 where
129 where
138 go (gt, eq) a = gt ||. (eq &&. a)
130 go (gt, eq) a = gt ||. (eq &&. a)
@@ -145,7 +137,7 @@ infix 4 >:
145(toColumns -> as) >=: (toColumns -> bs) =
137(toColumns -> as) >=: (toColumns -> bs) =
146 foldr @[] go true $ getConst $ htabulateA $ \field ->
138 foldr @[] go true $ getConst $ htabulateA $ \field ->
147 case (hfield as field, hfield bs field) of
139 case (hfield as field, hfield bs field) of
148− (E a, E b) -> case hfield (ordTable @a) field of
140+ (a, b) -> case hfield (ordTable @a) field of
149 Dict -> Const [(a >. b, a ==. b)]
141 Dict -> Const [(a >. b, a ==. b)]
150 where
142 where
151 go (gt, eq) a = gt ||. (eq &&. a)
143 go (gt, eq) a = gt ||. (eq &&. a)
@@ -154,9 +146,9 @@ infix 4 >=:
154
146
155-- | Given two 'Table's, return the table that sorts before the other.
147-- | Given two 'Table's, return the table that sorts before the other.
156least :: OrdTable a => a -> a -> a
148least :: OrdTable a => a -> a -> a
157−least a b = bool a b (a <: b)
149+least a b = bool b a (a <: b)
158
150
159
151
160-- | Given two 'Table's, return the table that sorts after the other.
152-- | Given two 'Table's, return the table that sorts after the other.
161greatest :: OrdTable a => a -> a -> a
153greatest :: OrdTable a => a -> a -> a
162−greatest a b = bool a b (a >: b)
154+greatest a b = bool b a (a >: b)
src/Rel8/Table/Order.hs+5−6
@@ -16,13 +16,12 @@ import Data.Functor.Contravariant ( (>$<), contramap )
16import Prelude
16import Prelude
17
17
18-- rel8
18-- rel8
19−import Rel8.Expr ( unE )
20import Rel8.Expr.Order ( asc, desc, nullsFirst, nullsLast )
19import Rel8.Expr.Order ( asc, desc, nullsFirst, nullsLast )
21import Rel8.Order ( Order )
20import Rel8.Order ( Order )
22import Rel8.Schema.Dict ( Dict( Dict ) )
21import Rel8.Schema.Dict ( Dict( Dict ) )
23import Rel8.Schema.HTable (htabulateA, hfield, hspecs)
22import Rel8.Schema.HTable (htabulateA, hfield, hspecs)
24import Rel8.Schema.Null ( Nullity( Null, NotNull ) )
23import Rel8.Schema.Null ( Nullity( Null, NotNull ) )
25−import Rel8.Schema.Spec ( SSpec( SSpec, nullity ) )
24+import Rel8.Schema.Spec ( Spec( Spec, nullity ) )
26import Rel8.Table ( Columns, toColumns )
25import Rel8.Table ( Columns, toColumns )
27import Rel8.Table.Ord ( OrdTable, ordTable )
26import Rel8.Table.Ord ( OrdTable, ordTable )
28
27
@@ -32,8 +31,8 @@ import Rel8.Table.Ord ( OrdTable, ordTable )
32ascTable :: forall a. OrdTable a => Order a
31ascTable :: forall a. OrdTable a => Order a
33ascTable = contramap toColumns $ getConst $
32ascTable = contramap toColumns $ getConst $
34 htabulateA @(Columns a) $ \field -> case hfield hspecs field of
33 htabulateA @(Columns a) $ \field -> case hfield hspecs field of
35− SSpec {nullity} -> case hfield (ordTable @a) field of
34+ Spec {nullity} -> case hfield (ordTable @a) field of
36− Dict -> Const $ unE . (`hfield` field) >$<
35+ Dict -> Const $ (`hfield` field) >$<
37 case nullity of
36 case nullity of
38 Null -> nullsFirst asc
37 Null -> nullsFirst asc
39 NotNull -> asc
38 NotNull -> asc
@@ -44,8 +43,8 @@ ascTable = contramap toColumns $ getConst $
44descTable :: forall a. OrdTable a => Order a
43descTable :: forall a. OrdTable a => Order a
45descTable = contramap toColumns $ getConst $
44descTable = contramap toColumns $ getConst $
46 htabulateA @(Columns a) $ \field -> case hfield hspecs field of
45 htabulateA @(Columns a) $ \field -> case hfield hspecs field of
47− SSpec {nullity} -> case hfield (ordTable @a) field of
46+ Spec {nullity} -> case hfield (ordTable @a) field of
48− Dict -> Const $ unE . (`hfield` field) >$<
47+ Dict -> Const $ (`hfield` field) >$<
49 case nullity of
48 case nullity of
50 Null -> nullsLast desc
49 Null -> nullsLast desc
51 NotNull -> desc
50 NotNull -> desc
src/Rel8/Table/Projection.hsnew file+73
@@ -0,0 +1,73 @@
1+{-# language FlexibleContexts #-}
2+{-# language FlexibleInstances #-}
3+{-# language MonoLocalBinds #-}
4+{-# language MultiParamTypeClasses #-}
5+{-# language StandaloneKindSignatures #-}
6+{-# language UndecidableInstances #-}
7+
8+module Rel8.Table.Projection
9+ ( Projection
10+ , Projectable( project )
11+ , Biprojectable( biproject )
12+ , Projecting
13+ , apply
14+ )
15+where
16+
17+-- base
18+import Data.Kind ( Constraint, Type )
19+import Prelude
20+
21+-- rel8
22+import Rel8.Schema.Field ( Field( Field ), fields )
23+import Rel8.Schema.HTable ( hfield, htabulate )
24+import Rel8.Table ( Columns, Context, Transpose, toColumns )
25+import Rel8.Table.Transpose ( Transposes )
26+
27+
28+-- | The constraint @'Projecting' a b@ ensures that @'Projection' a b@ is a
29+-- usable 'Projection'.
30+type Projecting :: Type -> Type -> Constraint
31+class
32+ ( Transposes (Context a) (Field a) a (Transpose (Field a) a)
33+ , Transposes (Context a) (Field a) b (Transpose (Field a) b)
34+ )
35+ => Projecting a b
36+instance
37+ ( Transposes (Context a) (Field a) a (Transpose (Field a) a)
38+ , Transposes (Context a) (Field a) b (Transpose (Field a) b)
39+ )
40+ => Projecting a b
41+
42+
43+-- | A @'Projection' a b@s is a special type of function @a -> b@ whereby the
44+-- resulting @b@ is guaranteed to be composed only from columns contained in
45+-- @a@.
46+type Projection :: Type -> Type -> Type
47+type Projection a b = Transpose (Field a) a -> Transpose (Field a) b
48+
49+
50+-- | @'Projectable' f@ means that @f@ is a kind of functor on 'Rel8.Table's
51+-- that allows the mapping of a 'Projection' over its underlying columns.
52+type Projectable :: (Type -> Type) -> Constraint
53+class Projectable f where
54+ -- | Map a 'Projection' over @f@.
55+ project :: Projecting a b
56+ => Projection a b -> f a -> f b
57+
58+
59+-- | @'Biprojectable' p@ means that @p@ is a kind of bifunctor on
60+-- 'Rel8.Table's that allows the mapping of a pair of 'Projection's over its
61+-- underlying columns.
62+type Biprojectable :: (Type -> Type -> Type) -> Constraint
63+class Biprojectable p where
64+ -- | Map a pair of 'Projection's over @p@.
65+ biproject :: (Projecting a b, Projecting c d)
66+ => Projection a b -> Projection c d -> p a c -> p b d
67+
68+
69+apply :: Projecting a b
70+ => Projection a b -> Columns a context -> Columns b context
71+apply f a = case toColumns (f fields) of
72+ bs -> htabulate $ \field -> case hfield bs field of
73+ Field field' -> hfield a field'
src/Rel8/Table/Recontextualize.hsdeleted−99
@@ -1,99 +0,0 @@
1−{-# language DataKinds #-}
2−{-# language FlexibleInstances #-}
3−{-# language FunctionalDependencies #-}
4−{-# language StandaloneKindSignatures #-}
5−{-# language TypeFamilies #-}
6−{-# language UndecidableInstances #-}
7−{-# language UndecidableSuperClasses #-}
8−
9−module Rel8.Table.Recontextualize
10− ( Recontextualize
11− )
12−where
13−
14−-- base
15−import Data.Kind ( Constraint, Type )
16−import Prelude ()
17−
18−-- rel8
19−import qualified Rel8.Schema.Kind as K
20−import Rel8.Schema.Spec ( KnownSpec )
21−import Rel8.Table ( Table, Congruent )
22−
23−
24−-- | @Recontextualize from to a b@ is evidence that the types @a@ and @b@ are
25−-- related, and that @b@ is the same type as @a@, but after changing the
26−-- context from the initial context @from@, to the new context @to@.
27−type Recontextualize :: K.Context -> K.Context -> Type -> Type -> Constraint
28−class
29− ( Table from a
30− , Table to b
31− , Congruent a b
32− , Recontextualize from from a a
33− , Recontextualize to to b b
34− , Recontextualize to from b a
35− ) => Recontextualize from to a b
36− | a -> from
37− , b -> to
38− , a to -> b
39− , b from -> a
40−
41−
42−instance KnownSpec spec => Recontextualize from to (from spec) (to spec)
43−
44−
45−instance
46− ( Recontextualize from to a1 b1
47− , Recontextualize from to a2 b2
48− )
49− => Recontextualize from to (a1, a2) (b1, b2)
50−
51−
52−instance
53− ( Recontextualize from to a1 b1
54− , Recontextualize from to a2 b2
55− , Recontextualize from to a3 b3
56− )
57− => Recontextualize from to (a1, a2, a3) (b1, b2, b3)
58−
59−
60−instance
61− ( Recontextualize from to a1 b1
62− , Recontextualize from to a2 b2
63− , Recontextualize from to a3 b3
64− , Recontextualize from to a4 b4
65− )
66− => Recontextualize from to (a1, a2, a3, a4) (b1, b2, b3, b4)
67−
68−
69−instance
70− ( Recontextualize from to a1 b1
71− , Recontextualize from to a2 b2
72− , Recontextualize from to a3 b3
73− , Recontextualize from to a4 b4
74− , Recontextualize from to a5 b5
75− )
76− => Recontextualize from to (a1, a2, a3, a4, a5) (b1, b2, b3, b4, b5)
77−
78−
79−instance
80− ( Recontextualize from to a1 b1
81− , Recontextualize from to a2 b2
82− , Recontextualize from to a3 b3
83− , Recontextualize from to a4 b4
84− , Recontextualize from to a5 b5
85− , Recontextualize from to a6 b6
86− )
87− => Recontextualize from to (a1, a2, a3, a4, a5, a6) (b1, b2, b3, b4, b5, b6)
88−
89−
90−instance
91− ( Recontextualize from to a1 b1
92− , Recontextualize from to a2 b2
93− , Recontextualize from to a3 b3
94− , Recontextualize from to a4 b4
95− , Recontextualize from to a5 b5
96− , Recontextualize from to a6 b6
97− , Recontextualize from to a7 b7
98− )
99− => Recontextualize from to (a1, a2, a3, a4, a5, a6, a7) (b1, b2, b3, b4, b5, b6, b7)
src/Rel8/Table/Rel8able.hs+17−26
@@ -20,71 +20,62 @@ import Prelude ()
20-- rel8
20-- rel8
21import Rel8.Expr ( Expr )
21import Rel8.Expr ( Expr )
22import qualified Rel8.Kind.Algebra as K
22import qualified Rel8.Kind.Algebra as K
23+import Rel8.Kind.Context ( Reifiable, contextSing )
23import Rel8.Generic.Rel8able
24import Rel8.Generic.Rel8able
24 ( Rel8able, Algebra
25 ( Rel8able, Algebra
25 , GColumns, gfromColumns, gtoColumns
26 , GColumns, gfromColumns, gtoColumns
26 , GFromExprs, gfromResult, gtoResult
27 , GFromExprs, gfromResult, gtoResult
27 )
28 )
28−import Rel8.Schema.Context.Virtual ( Virtual, virtual )
29import qualified Rel8.Schema.Kind as K
29import qualified Rel8.Schema.Kind as K
30import Rel8.Schema.HTable ( HConstrainTable, hdicts )
30import Rel8.Schema.HTable ( HConstrainTable, hdicts )
31import Rel8.Schema.Null ( Sql )
31import Rel8.Schema.Null ( Sql )
32import Rel8.Schema.Result ( Result )
32import Rel8.Schema.Result ( Result )
33import Rel8.Table
33import Rel8.Table
34− ( Table, Columns, Context, Congruent, fromColumns, toColumns
34+ ( Table, Columns, Context, fromColumns, toColumns
35 , FromExprs, fromResult, toResult
35 , FromExprs, fromResult, toResult
36+ , Transpose
36 )
37 )
37−import Rel8.Schema.Spec.Constrain ( ConstrainSpec )
38import Rel8.Table.ADT ( ADT )
38import Rel8.Table.ADT ( ADT )
39import Rel8.Table.Eq ( EqTable, eqTable )
39import Rel8.Table.Eq ( EqTable, eqTable )
40import Rel8.Table.Ord ( OrdTable, ordTable )
40import Rel8.Table.Ord ( OrdTable, ordTable )
41−import Rel8.Table.Recontextualize ( Recontextualize )
42import Rel8.Table.Serialize ( ToExprs )
41import Rel8.Table.Serialize ( ToExprs )
43import Rel8.Type.Eq ( DBEq )
42import Rel8.Type.Eq ( DBEq )
44import Rel8.Type.Ord ( DBOrd )
43import Rel8.Type.Ord ( DBOrd )
45
44
46
45
47−instance (Rel8able t, Virtual f, f ~ g) => Table f (t g) where
46+instance (Rel8able t, Reifiable context, context ~ context') =>
47+ Table context' (t context)
48+ where
48− type Columns (t g) = GColumns t
49+ type Columns (t context) = GColumns t
49− type Context (t g) = g
50+ type Context (t context) = context
50− type FromExprs (t g) = GFromExprs t
51+ type FromExprs (t context) = GFromExprs t
52+ type Transpose to (t context) = t to
51
53
52− fromColumns = gfromColumns virtual
54+ fromColumns = gfromColumns contextSing
53− toColumns = gtoColumns virtual
55+ toColumns = gtoColumns contextSing
54 fromResult = gfromResult @t
56 fromResult = gfromResult @t
55 toResult = gtoResult @t
57 toResult = gtoResult @t
56
58
57
59
58−instance
59− ( Rel8able t
60− , Virtual from
61− , Virtual to
62− , Congruent (t from) (t to)
63− , from ~ from'
64− , to ~ to'
65− )
66− => Recontextualize from' to' (t from) (t to)
67−
68−
69instance
60instance
70 ( context ~ Expr
61 ( context ~ Expr
71 , Rel8able t
62 , Rel8able t
72− , HConstrainTable (Columns (t context)) (ConstrainSpec (Sql DBEq))
63+ , HConstrainTable (Columns (t context)) (Sql DBEq)
73 )
64 )
74 => EqTable (t context)
65 => EqTable (t context)
75 where
66 where
76− eqTable = hdicts @(Columns (t context)) @(ConstrainSpec (Sql DBEq))
67+ eqTable = hdicts @(Columns (t context)) @(Sql DBEq)
77
68
78
69
79instance
70instance
80 ( context ~ Expr
71 ( context ~ Expr
81 , Rel8able t
72 , Rel8able t
82− , HConstrainTable (Columns (t context)) (ConstrainSpec (Sql DBEq))
73+ , HConstrainTable (Columns (t context)) (Sql DBEq)
83− , HConstrainTable (Columns (t context)) (ConstrainSpec (Sql DBOrd))
74+ , HConstrainTable (Columns (t context)) (Sql DBOrd)
84 )
75 )
85 => OrdTable (t context)
76 => OrdTable (t context)
86 where
77 where
87− ordTable = hdicts @(Columns (t context)) @(ConstrainSpec (Sql DBOrd))
78+ ordTable = hdicts @(Columns (t context)) @(Sql DBOrd)
88
79
89
80
90instance
81instance
src/Rel8/Table/Serialize.hs+7−10
@@ -16,6 +16,7 @@ module Rel8.Table.Serialize
16where
16where
17
17
18-- base
18-- base
19+import Data.Functor.Identity ( Identity( Identity ) )
19import Data.Kind ( Constraint, Type )
20import Data.Kind ( Constraint, Type )
20import Data.List.NonEmpty ( NonEmpty )
21import Data.List.NonEmpty ( NonEmpty )
21import Prelude
22import Prelude
@@ -24,12 +25,12 @@ import Prelude
24import qualified Hasql.Decoders as Hasql
25import qualified Hasql.Decoders as Hasql
25
26
26-- rel8
27-- rel8
27−import Rel8.Expr ( Expr( E ) )
28+import Rel8.Expr ( Expr )
28import Rel8.Expr.Serialize ( slitExpr, sparseValue )
29import Rel8.Expr.Serialize ( slitExpr, sparseValue )
29import Rel8.Schema.HTable ( HTable, htabulate, htabulateA, hfield, hspecs )
30import Rel8.Schema.HTable ( HTable, htabulate, htabulateA, hfield, hspecs )
30import Rel8.Schema.Null ( NotNull, Sql )
31import Rel8.Schema.Null ( NotNull, Sql )
31−import Rel8.Schema.Result ( Result( R ) )
32+import Rel8.Schema.Result ( Result )
32−import Rel8.Schema.Spec ( SSpec(..), KnownSpec )
33+import Rel8.Schema.Spec ( Spec(..) )
33import Rel8.Table ( Table, fromColumns, FromExprs, fromResult, toResult )
34import Rel8.Table ( Table, fromColumns, FromExprs, fromResult, toResult )
34import Rel8.Type ( DBType )
35import Rel8.Type ( DBType )
35
36
@@ -115,10 +116,6 @@ instance
115 => ToExprs x (a, b, c, d, e, f, g)
116 => ToExprs x (a, b, c, d, e, f, g)
116
117
117
118
118−instance (KnownSpec spec, x ~ Expr spec) =>
119− ToExprs x (Result spec)
120−
121−
122-- | @Serializable@ witnesses the one-to-one correspondence between the type
119-- | @Serializable@ witnesses the one-to-one correspondence between the type
123-- @sql@, which contains SQL expressions, and the type @haskell@, which
120-- @sql@, which contains SQL expressions, and the type @haskell@, which
124-- contains the Haskell decoding of rows containing @sql@ SQL expressions.
121-- contains the Haskell decoding of rows containing @sql@ SQL expressions.
@@ -141,11 +138,11 @@ parse = fromResult @_ @exprs <$> parseHTable
141litHTable :: HTable t => t Result -> t Expr
138litHTable :: HTable t => t Result -> t Expr
142litHTable as = htabulate $ \field ->
139litHTable as = htabulate $ \field ->
143 case hfield hspecs field of
140 case hfield hspecs field of
144− SSpec {nullity, info} -> case hfield as field of
141+ Spec {nullity, info} -> case hfield as field of
145− R value -> E (slitExpr nullity info value)
142+ Identity value -> slitExpr nullity info value
146
143
147
144
148parseHTable :: HTable t => Hasql.Row (t Result)
145parseHTable :: HTable t => Hasql.Row (t Result)
149parseHTable = unwrapApplicative $ htabulateA $ \field ->
146parseHTable = unwrapApplicative $ htabulateA $ \field ->
150 WrapApplicative $ case hfield hspecs field of
147 WrapApplicative $ case hfield hspecs field of
151− SSpec {nullity, info} -> R <$> sparseValue nullity info
148+ Spec {nullity, info} -> Identity <$> sparseValue nullity info
src/Rel8/Table/These.hs+30−17
@@ -20,6 +20,7 @@ module Rel8.Table.These
20 , isThisTable, isThatTable, isThoseTable
20 , isThisTable, isThatTable, isThoseTable
21 , hasHereTable, hasThereTable
21 , hasHereTable, hasThereTable
22 , justHereTable, justThereTable
22 , justHereTable, justThereTable
23+ , alignMaybeTable
23 , aggregateTheseTable
24 , aggregateTheseTable
24 , nameTheseTable
25 , nameTheseTable
25 )
26 )
@@ -29,13 +30,13 @@ where
29import Data.Bifunctor ( Bifunctor, bimap )
30import Data.Bifunctor ( Bifunctor, bimap )
30import Data.Kind ( Type )
31import Data.Kind ( Type )
31import Data.Maybe ( isJust )
32import Data.Maybe ( isJust )
32−import Prelude hiding ( undefined )
33+import Prelude hiding ( null, undefined )
33
34
34-- rel8
35-- rel8
35import Rel8.Aggregate ( Aggregate )
36import Rel8.Aggregate ( Aggregate )
36import Rel8.Expr ( Expr )
37import Rel8.Expr ( Expr )
37−import Rel8.Expr.Bool ( (&&.), not_ )
38+import Rel8.Expr.Bool ( (&&.), (||.), boolExpr, not_ )
38−import Rel8.Expr.Null ( isNonNull )
39+import Rel8.Expr.Null ( null, isNonNull )
39import Rel8.Kind.Context ( Reifiable )
40import Rel8.Kind.Context ( Reifiable )
40import Rel8.Schema.Context.Nullify ( Nullifiable )
41import Rel8.Schema.Context.Nullify ( Nullifiable )
41import Rel8.Schema.Dict ( Dict( Dict ) )
42import Rel8.Schema.Dict ( Dict( Dict ) )
@@ -48,6 +49,7 @@ import Rel8.Schema.Name ( Name )
48import Rel8.Table
49import Rel8.Table
49 ( Table, Columns, Context, fromColumns, toColumns
50 ( Table, Columns, Context, fromColumns, toColumns
50 , FromExprs, fromResult, toResult
51 , FromExprs, fromResult, toResult
52+ , Transpose
51 )
53 )
52import Rel8.Table.Eq ( EqTable, eqTable )
54import Rel8.Table.Eq ( EqTable, eqTable )
53import Rel8.Table.Maybe
55import Rel8.Table.Maybe
@@ -59,7 +61,7 @@ import Rel8.Table.Maybe
59 )
61 )
60import Rel8.Table.Nullify ( Nullify, guard )
62import Rel8.Table.Nullify ( Nullify, guard )
61import Rel8.Table.Ord ( OrdTable, ordTable )
63import Rel8.Table.Ord ( OrdTable, ordTable )
62−import Rel8.Table.Recontextualize ( Recontextualize )
64+import Rel8.Table.Projection ( Biprojectable, Projectable, biproject, project )
63import Rel8.Table.Serialize ( ToExprs )
65import Rel8.Table.Serialize ( ToExprs )
64import Rel8.Table.Undefined ( undefined )
66import Rel8.Table.Undefined ( undefined )
65import Rel8.Type.Tag ( MaybeTag )
67import Rel8.Type.Tag ( MaybeTag )
@@ -88,10 +90,18 @@ data TheseTable context a b = TheseTable
88 deriving stock Functor
90 deriving stock Functor
89
91
90
92
93+instance Biprojectable (TheseTable context) where
94+ biproject f g (TheseTable a b) = TheseTable (project f a) (project g b)
95+
96+
91instance Nullifiable context => Bifunctor (TheseTable context) where
97instance Nullifiable context => Bifunctor (TheseTable context) where
92 bimap f g (TheseTable a b) = TheseTable (fmap f a) (fmap g b)
98 bimap f g (TheseTable a b) = TheseTable (fmap f a) (fmap g b)
93
99
94
100
101+instance Projectable (TheseTable context a) where
102+ project f (TheseTable a b) = TheseTable a (project f b)
103+
104+
95instance (context ~ Expr, Table Expr a, Semigroup a) =>
105instance (context ~ Expr, Table Expr a, Semigroup a) =>
96 Apply (TheseTable context a)
106 Apply (TheseTable context a)
97 where
107 where
@@ -146,6 +156,8 @@ instance
146 type Context (TheseTable context a b) = Context a
156 type Context (TheseTable context a b) = Context a
147 type FromExprs (TheseTable context a b) =
157 type FromExprs (TheseTable context a b) =
148 These (FromExprs a) (FromExprs b)
158 These (FromExprs a) (FromExprs b)
159+ type Transpose to (TheseTable context a b) =
160+ TheseTable to (Transpose to a) (Transpose to b)
149
161
150 toColumns TheseTable {here, there} = HTheseTable
162 toColumns TheseTable {here, there} = HTheseTable
151 { hhereTag = hlabel $ HIdentity $ tag here
163 { hhereTag = hlabel $ HIdentity $ tag here
@@ -202,22 +214,13 @@ instance
202 }
214 }
203
215
204
216
205−instance
206− ( Recontextualize from to a1 b1
207− , Recontextualize from to a2 b2
208− , Reifiable from, from ~ from'
209− , Reifiable to, to ~ to'
210− )
211− => Recontextualize from to (TheseTable from' a1 a2) (TheseTable to' b1 b2)
212−
213−
214instance (EqTable a, EqTable b, context ~ Expr) =>
217instance (EqTable a, EqTable b, context ~ Expr) =>
215 EqTable (TheseTable context a b)
218 EqTable (TheseTable context a b)
216 where
219 where
217 eqTable = HTheseTable
220 eqTable = HTheseTable
218− { hhereTag = hlabel (HType Dict)
221+ { hhereTag = hlabel (HIdentity Dict)
219 , hhere = hlabel (eqTable @(Nullify context a))
222 , hhere = hlabel (eqTable @(Nullify context a))
220− , hthereTag = hlabel (HType Dict)
223+ , hthereTag = hlabel (HIdentity Dict)
221 , hthere = hlabel (eqTable @(Nullify context b))
224 , hthere = hlabel (eqTable @(Nullify context b))
222 }
225 }
223
226
@@ -226,9 +229,9 @@ instance (OrdTable a, OrdTable b, context ~ Expr) =>
226 OrdTable (TheseTable context a b)
229 OrdTable (TheseTable context a b)
227 where
230 where
228 ordTable = HTheseTable
231 ordTable = HTheseTable
229− { hhereTag = hlabel (HType Dict)
232+ { hhereTag = hlabel (HIdentity Dict)
230 , hhere = hlabel (ordTable @(Nullify context a))
233 , hhere = hlabel (ordTable @(Nullify context a))
231− , hthereTag = hlabel (HType Dict)
234+ , hthereTag = hlabel (HIdentity Dict)
232 , hthere = hlabel (ordTable @(Nullify context b))
235 , hthere = hlabel (ordTable @(Nullify context b))
233 }
236 }
234
237
@@ -286,6 +289,16 @@ justThereTable :: TheseTable context a b -> MaybeTable context b
286justThereTable = there
289justThereTable = there
287
290
288
291
292+-- | Construct a @TheseTable@ from two 'MaybeTable's.
293+alignMaybeTable :: ()
294+ => MaybeTable Expr a
295+ -> MaybeTable Expr b
296+ -> MaybeTable Expr (TheseTable Expr a b)
297+alignMaybeTable a b = MaybeTable tag (pure (TheseTable a b))
298+ where
299+ tag = boolExpr null mempty (isJustTable a ||. isJustTable b)
300+
301+
289-- | Construct a @TheseTable@. Corresponds to 'This'.
302-- | Construct a @TheseTable@. Corresponds to 'This'.
290thisTable :: Table Expr b => a -> TheseTable Expr a b
303thisTable :: Table Expr b => a -> TheseTable Expr a b
291thisTable a = TheseTable (justTable a) nothingTable
304thisTable a = TheseTable (justTable a) nothingTable
src/Rel8/Table/Transpose.hsnew file+46
@@ -0,0 +1,46 @@
1+{-# language DataKinds #-}
2+{-# language FlexibleInstances #-}
3+{-# language FunctionalDependencies #-}
4+{-# language StandaloneKindSignatures #-}
5+{-# language TypeFamilies #-}
6+{-# language UndecidableInstances #-}
7+
8+module Rel8.Table.Transpose
9+ ( Transposes
10+ )
11+where
12+
13+-- base
14+import Data.Kind ( Constraint, Type )
15+import Prelude ()
16+
17+-- rel8
18+import qualified Rel8.Schema.Kind as K
19+import Rel8.Table ( Table, Transpose, Congruent )
20+
21+
22+-- | @'Transposes' from to a b@ means that @a@ and @b@ are 'Table's, in the
23+-- @from@ and @to@ contexts respectively, which share the same underlying
24+-- structure. In other words, @b@ is a version of @a@ transposed from the
25+-- @from@ context to the @to@ context (and vice versa).
26+type Transposes :: K.Context -> K.Context -> Type -> Type -> Constraint
27+class
28+ ( Table from a
29+ , Table to b
30+ , Congruent a b
31+ , b ~ Transpose to a
32+ , a ~ Transpose from b
33+ )
34+ => Transposes from to a b
35+ | a -> from
36+ , b -> to
37+ , a to -> b
38+ , b from -> a
39+instance
40+ ( Table from a
41+ , Table to b
42+ , Congruent a b
43+ , b ~ Transpose to a
44+ , a ~ Transpose from b
45+ )
46+ => Transposes from to a b
src/Rel8/Table/Undefined.hs+5−5
@@ -11,16 +11,16 @@ where
11import Prelude hiding ( undefined )
11import Prelude hiding ( undefined )
12
12
13-- rel8
13-- rel8
14−import Rel8.Expr ( Expr( E ) )
14+import Rel8.Expr ( Expr )
15import Rel8.Expr.Null ( snull, unsafeUnnullify )
15import Rel8.Expr.Null ( snull, unsafeUnnullify )
16import Rel8.Schema.HTable ( htabulate, hfield, hspecs )
16import Rel8.Schema.HTable ( htabulate, hfield, hspecs )
17import Rel8.Schema.Null ( Nullity( Null, NotNull ) )
17import Rel8.Schema.Null ( Nullity( Null, NotNull ) )
18−import Rel8.Schema.Spec ( SSpec(..) )
18+import Rel8.Schema.Spec ( Spec(..) )
19import Rel8.Table ( Table, fromColumns )
19import Rel8.Table ( Table, fromColumns )
20
20
21
21
22undefined :: Table Expr a => a
22undefined :: Table Expr a => a
23undefined = fromColumns $ htabulate $ \field -> case hfield hspecs field of
23undefined = fromColumns $ htabulate $ \field -> case hfield hspecs field of
24− SSpec {nullity, info} -> case nullity of
24+ Spec {nullity, info} -> case nullity of
25− Null -> E (snull info)
25+ Null -> snull info
26− NotNull -> E (unsafeUnnullify (snull info))
26+ NotNull -> unsafeUnnullify (snull info)
src/Rel8/Table/Window.hsnew file+43
@@ -0,0 +1,43 @@
1+{-# language MonoLocalBinds #-}
2+
3+module Rel8.Table.Window
4+ ( cumulative
5+ , cumulative_
6+ , currentRow
7+ )
8+where
9+
10+-- base
11+import Prelude
12+
13+-- opaleye
14+import qualified Opaleye.Window as Opaleye
15+
16+-- rel8
17+import Rel8.Aggregate ( Aggregates )
18+import qualified Rel8.Expr.Window as Expr
19+import Rel8.Schema.HTable ( hfield, htabulateA )
20+import Rel8.Table ( fromColumns, toColumns )
21+import Rel8.Window ( Window( Window ) )
22+
23+
24+-- | 'cumulative' allows the use of aggregation functions in 'Window'
25+-- expressions. In particular, @'cumulative' 'Rel8.sum'@
26+-- (when combined with 'Rel8.Window.orderPartitionBy') gives a running total,
27+-- also known as a \"cumulative sum\", hence the name @cumulative@.
28+cumulative :: Aggregates aggregates exprs => (a -> aggregates) -> Window a exprs
29+cumulative f =
30+ fmap fromColumns $
31+ htabulateA $ \field ->
32+ Expr.cumulative ((`hfield` field) . toColumns . f)
33+
34+
35+-- | A version of 'cumulative' for use with nullary aggregators like
36+-- 'Rel8.Expr.Aggregate.countStar'.
37+cumulative_ :: Aggregates aggregates exprs => aggregates -> Window a exprs
38+cumulative_ = cumulative . const
39+
40+
41+-- | Return every column of the current row of a window query.
42+currentRow :: Window a a
43+currentRow = Window $ Opaleye.over (Opaleye.noWindowFunction id) mempty mempty
src/Rel8/Tabulate.hsnew file+640
@@ -0,0 +1,640 @@
1+{-# language FlexibleContexts #-}
2+{-# language MonoLocalBinds #-}
3+{-# language ScopedTypeVariables #-}
4+{-# language StandaloneKindSignatures #-}
5+{-# language TypeApplications #-}
6+{-# language TupleSections #-}
7+{-# language UndecidableInstances #-}
8+
9+-- | "Rel8.Tabulate" provides an alternative API ('Tabulation') for writing
10+-- queries that complements the main "Rel8" API ('Query').
11+
12+module Rel8.Tabulate
13+ (
14+ Tabulation
15+
16+ -- * Interfacing with 'Query's
17+ , fromQuery
18+ , toQuery
19+ , liftQuery
20+ , through
21+ , lookup
22+
23+ -- * Aggregation and Ordering
24+ , aggregate
25+ , distinct
26+ , order
27+
28+ -- ** Magic 'Tabulation's
29+ -- $magic
30+ , count
31+ , optional
32+ , many
33+ , some
34+ , exists
35+ , present
36+ , absent
37+
38+ -- * Natural joins
39+ , align
40+ , alignWith
41+ , leftAlign
42+ , leftAlignWith
43+ , rightAlign
44+ , rightAlignWith
45+ , zip
46+ , zipWith
47+ , similarity
48+ , difference
49+ )
50+where
51+
52+-- base
53+import Control.Applicative ( (<|>), empty, liftA2 )
54+import Control.Monad ( liftM2 )
55+import Data.Bifunctor ( Bifunctor, bimap, first, second )
56+import Data.Foldable ( traverse_ )
57+import Data.Function ( on )
58+import Data.Functor.Contravariant ( Contravariant, (>$<), contramap )
59+import Data.Int ( Int64 )
60+import Data.Kind ( Type )
61+import Data.Maybe ( fromJust, fromMaybe )
62+import Prelude hiding ( lookup, zip, zipWith )
63+
64+-- bifunctors
65+import Data.Bifunctor.Clown ( Clown( Clown ), runClown )
66+
67+-- comonad
68+import Control.Comonad ( extract )
69+
70+-- opaleye
71+import qualified Opaleye.Aggregate as Opaleye
72+import qualified Opaleye.Order as Opaleye ( orderBy, distinctOnExplicit )
73+
74+-- profunctors
75+import Data.Profunctor ( dimap, lmap )
76+
77+-- product-profunctors
78+import Data.Profunctor.Product
79+ ( ProductProfunctor, (***!)
80+ , SumProfunctor, (+++!)
81+ )
82+import qualified Data.Profunctor.Product as PP
83+
84+-- rel8
85+import Rel8.Aggregate ( Aggregates )
86+import Rel8.Expr ( Expr )
87+import Rel8.Expr.Aggregate ( countStar )
88+import Rel8.Expr.Bool ( true )
89+import Rel8.Order ( Order( Order ) )
90+import Rel8.Query ( Query )
91+import qualified Rel8.Query.Exists as Q ( exists, present, absent )
92+import Rel8.Query.Filter ( where_ )
93+import Rel8.Query.List ( catNonEmptyTable )
94+import qualified Rel8.Query.Maybe as Q ( optional )
95+import Rel8.Query.Opaleye ( mapOpaleye, unsafePeekQuery )
96+import Rel8.Query.Rebind ( rebind )
97+import Rel8.Query.These ( alignBy )
98+import Rel8.Table ( Table, fromColumns, toColumns )
99+import Rel8.Table.Aggregate ( hgroupBy, listAgg, nonEmptyAgg )
100+import Rel8.Table.Alternative
101+ ( AltTable, (<|>:)
102+ , AlternativeTable, emptyTable
103+ )
104+import Rel8.Table.Cols ( fromCols, toCols )
105+import Rel8.Table.Eq ( EqTable, (==:), eqTable )
106+import Rel8.Table.List ( ListTable( ListTable ) )
107+import Rel8.Table.Maybe ( MaybeTable( MaybeTable ), maybeTable )
108+import Rel8.Table.NonEmpty ( NonEmptyTable( NonEmptyTable ) )
109+import Rel8.Table.Opaleye ( aggregator, unpackspec )
110+import Rel8.Table.Ord ( OrdTable )
111+import Rel8.Table.Order ( ascTable )
112+import Rel8.Table.Projection
113+ ( Biprojectable, biproject
114+ , Projectable, project
115+ , apply
116+ )
117+import Rel8.Table.These ( TheseTable( TheseTable ), theseTable )
118+
119+-- semigroupoids
120+import Data.Functor.Apply ( Apply, liftF2 )
121+import Data.Functor.Bind ( Bind, (>>-) )
122+
123+
124+type Key :: Type -> Type
125+type Key = Maybe
126+
127+
128+cat :: Table Expr k => Key k -> Query k
129+cat = maybe emptyTable pure
130+
131+
132+key :: (ProductProfunctor p, SumProfunctor p)
133+ => p a b -> p (Key a) (Key b)
134+key a = dimap from to (PP.empty +++! a)
135+ where
136+ from = maybe (Left ()) Right
137+ to = either (const Nothing) Just
138+
139+
140+keyed :: (ProductProfunctor p, SumProfunctor p)
141+ => p k l -> p a b -> p (Key k, a) (Key l, b)
142+keyed k a = key k ***! a
143+
144+
145+type Predicate :: Type -> Type
146+newtype Predicate a = Predicate (Maybe (a -> Expr Bool))
147+
148+
149+instance Contravariant Predicate where
150+ contramap f (Predicate a) = Predicate (lmap f <$> a)
151+
152+
153+instance Semigroup (Predicate k) where
154+ Predicate ma <> Predicate mb = Predicate $ ma <|> mb
155+
156+
157+instance Monoid (Predicate k) where
158+ mempty = Predicate Nothing
159+
160+
161+match :: EqTable k => Key k -> Predicate k
162+match = Predicate . fmap (==:)
163+
164+
165+ensure :: Predicate k -> Key k -> Query ()
166+ensure (Predicate mp) = traverse_ (\k -> traverse_ (\p -> where_ (p k)) mp)
167+
168+
169+-- | A @'Tabulation' k a@ is like a @'Query' a@, except that each row also
170+-- has a key @k@ in addition to the value @a@. 'Tabulation's can be composed
171+-- monadically just like 'Query's, but the resulting join is more like a
172+-- @NATURAL JOIN@ (based on the common key column(s) @k@) than the
173+-- @CROSS JOIN@ given by 'Query'.
174+--
175+-- Another way to think of @'Tabulation' k a@ is as analogous to @Map k a@ in
176+-- the same way @'Query' a@ is analogous to @[a]@. However, there's nothing
177+-- stopping a 'Tabulation' from containing multiple rows with the same key, so
178+-- technically @Map k (NonEmpty a)@ is more accurate.
179+--
180+-- 'Tabulation's can be created from 'Query's with 'fromQuery' and 'liftQuery'
181+-- and converted back to 'Query's with 'lookup' and 'toQuery' (though note the
182+-- caveats that come with the latter).
183+type Tabulation :: Type -> Type -> Type
184+newtype Tabulation k a = Tabulation (Predicate k -> Query (Key k, a))
185+
186+
187+instance Biprojectable Tabulation where
188+ biproject f g =
189+ bimap
190+ (fromColumns . apply f . toColumns)
191+ (fromColumns . apply g . toColumns)
192+
193+
194+instance Bifunctor Tabulation where
195+ bimap f g (Tabulation a) = Tabulation $ \p ->
196+ bimap (fmap f) g <$> a (f >$< p)
197+
198+
199+instance Functor (Tabulation k) where
200+ fmap = second
201+
202+
203+instance Projectable (Tabulation k) where
204+ project f = fmap (fromColumns . apply f . toColumns)
205+
206+
207+-- | If @'Tabulation' k a@ is @Map k (NonEmpty a)@, then @(<.>)@ is
208+-- @intersectionWith (liftA2 (<*>))@
209+instance EqTable k => Apply (Tabulation k) where
210+ liftF2 = liftA2
211+
212+
213+-- | @pure = 'liftQuery' . pure@
214+instance EqTable k => Applicative (Tabulation k) where
215+ pure = liftQuery . pure
216+ liftA2 = liftM2
217+
218+
219+instance EqTable k => Bind (Tabulation k) where
220+ Tabulation as >>- f = Tabulation $ \p -> do
221+ (k, a) <- as p
222+ case f a of
223+ Tabulation bs -> do
224+ let p' = match k
225+ (k', b) <- bs (p' <> p)
226+ ensure p' k'
227+ pure (k' <|> k, b)
228+
229+
230+instance EqTable k => Monad (Tabulation k) where
231+ (>>=) = (>>-)
232+
233+
234+-- | If @'Tabulation' k a@ is @Map k (NonEmpty a)@, then @(<|>:)@ is
235+-- @unionWith (<>)@.
236+instance EqTable k => AltTable (Tabulation k) where
237+ tas <|>: tbs = do
238+ eas <- peek tas
239+ ebs <- peek tbs
240+ case (eas, ebs) of
241+ (Left as, Left bs) -> liftQuery $ as <|>: bs
242+ (Right as, Right bs) -> fromQuery $ as <|>: bs
243+ _ -> catNonEmptyTable `through` ((<>) `on` some) tas tbs
244+
245+
246+instance EqTable k => AlternativeTable (Tabulation k) where
247+ emptyTable = Tabulation $ const $ fmap (empty,) emptyTable
248+
249+
250+-- | If @'Tabulation' k a@ is @Map k (NonEmpty a)@, then @(<>)@ is
251+-- @unionWith (liftA2 (<>))@.
252+instance (EqTable k, Table Expr a, Semigroup a) => Semigroup (Tabulation k a)
253+ where
254+ (<>) = alignWith (theseTable id id (<>))
255+
256+
257+instance (EqTable k, Table Expr a, Semigroup a) => Monoid (Tabulation k a)
258+ where
259+ mempty = emptyTable
260+
261+
262+-- | Any 'Query' of key-value pairs @(k, a)@ can be a @'Tabulation' k a@.
263+fromQuery :: Query (k, a) -> Tabulation k a
264+fromQuery = Tabulation . const . fmap (first pure)
265+
266+
267+-- | Convert a @'Tabulation' k a@ back into a 'Query' of key-value pairs.
268+--
269+-- Note that the result of a 'toQuery' is undefined (will always return zero
270+-- rows) on 'Tabulation's constructed with 'liftQuery' or 'pure'. So while
271+-- @toQuery . fromQuery@ is always @id@, @fromQuery . toQuery@ is not.
272+--
273+-- A safer, more predictable alternative to 'toQuery' is to use 'lookup' with
274+-- an explicit set of keys:
275+--
276+-- @
277+-- do
278+-- k <- keys
279+-- a <- lookup k tabulation
280+-- pure (k, a)
281+-- @
282+--
283+-- Having said that, in practice, most legitimate uses of 'Tabulation' will
284+-- have a well-defined 'toQuery'. It would be possible in theory to encode
285+-- the necessary invariants at the type level using an indexed monad, but we
286+-- would lose the ability to use @do@-notation, which is the main benefit
287+-- of having 'Tabulation' as a monad in the first place.
288+--
289+-- In particular, @'toQuery' t@ is well-defined for any 'Tabulation' @t@
290+-- defined as @t = fromQuery _@. @'toQuery' t@ is also well-defined for any
291+-- 'Tabulation' @t@ defined as @t = t' >>= _@ or @t = t' *> _@ where
292+-- @'toQuery' t'@ is well-defined. There are other valid permutations too.
293+-- Generally, anything that uses 'fromQuery' at some point, unless wrapped in
294+-- a top-level 'present' or 'absent', will have a well-defined 'toQuery'.
295+toQuery :: Table Expr k => Tabulation k a -> Query (k, a)
296+toQuery (Tabulation f) = do
297+ (mk, a) <- f mempty
298+ k <- cat mk
299+ pure (k, a)
300+
301+
302+-- | A @'Query' a@ can be treated as a @'Tabulation' k a@ where the given @a@
303+-- values exist at every possible key @k@.
304+liftQuery :: Query a -> Tabulation k a
305+liftQuery = Tabulation . const . fmap (empty,)
306+
307+
308+-- | Run a Kleisli arrow in the the 'Query' monad \"through\" a 'Tabulation'.
309+-- Useful for 'Rel8.filter'ing a 'Tabulation'.
310+--
311+-- @
312+-- 'Rel8.filter' ((>=. 30) . userAge) `'through'` usersById
313+-- @
314+through :: (a -> Query b) -> Tabulation k a -> Tabulation k b
315+through f (Tabulation as) = Tabulation $ \p -> do
316+ (k, a) <- as p
317+ b <- f a
318+ pure (k, b)
319+infixr 1 `through`
320+
321+
322+-- | @'lookup' k t@ returns the value(s) at the key @k@ in the tabulation @t@.
323+lookup :: EqTable k => k -> Tabulation k a -> Query a
324+lookup k (Tabulation f) = do
325+ (k', a) <- f p
326+ ensure p k'
327+ pure a
328+ where
329+ p = match (pure k)
330+
331+
332+-- | 'aggregate' aggregates the values within each key of a
333+-- 'Tabulation'. There is an implicit @GROUP BY@ on all the key columns.
334+aggregate :: forall k aggregates exprs.
335+ ( EqTable k
336+ , Aggregates aggregates exprs
337+ )
338+ => Tabulation k aggregates -> Tabulation k exprs
339+aggregate (Tabulation f) = Tabulation $
340+ mapOpaleye (Opaleye.aggregate (keyed haggregator aggregator)) .
341+ fmap (first (fmap (hgroupBy (eqTable @k) . toColumns))) .
342+ f
343+ where
344+ haggregator = dimap fromColumns fromCols aggregator
345+
346+
347+-- | 'distinct' ensures a 'Tabulation' has at most one value for
348+-- each key, i.e., it drops duplicates. In general it keeps only the
349+-- \"first\" value it encounters for each key, but note that \"first\" is
350+-- undefined unless you first call 'order'.
351+distinct :: EqTable k => Tabulation k a -> Tabulation k a
352+distinct (Tabulation f) = Tabulation $
353+ mapOpaleye (Opaleye.distinctOnExplicit (key unpackspec) fst) . f
354+
355+
356+-- | 'order' orders the /values/ of a 'Tabulation' within their
357+-- respective keys. This specifies a defined order for 'distinct'.
358+-- It also defines the order of the lists produced by 'many' and
359+-- 'some'.
360+order :: OrdTable k => Order a -> Tabulation k a -> Tabulation k a
361+order ordering (Tabulation f) =
362+ Tabulation $ mapOpaleye (Opaleye.orderBy ordering') . f
363+ where
364+ Order ordering' = runClown (keyed (Clown ascTable) (Clown ordering))
365+
366+
367+-- $magic
368+--
369+-- Some of the following combinators produce \"magic\" 'Tabulation's. Let's
370+-- use 'count' as an example to demonstrate this concept. Consider
371+-- the following:
372+--
373+-- @
374+-- count $ fromQuery $ values
375+-- [ (lit 'a', lit True)
376+-- , (lit 'a', lit False)
377+-- , (lit 'b', lit True)
378+-- ]
379+-- @
380+--
381+-- You might expect this to be equivalent to the following 'Tabulation':
382+--
383+-- @
384+-- fromQuery $ values
385+-- [ (lit 'a', 2)
386+-- , (lit 'b', 1)
387+-- ]
388+-- @
389+--
390+-- However, it isn't quite. While the resulting 'Tabulation' does effectively
391+-- contain the above entries, it also behaves as though it contained the value
392+-- @0@ at every other possible key.
393+--
394+-- This means you can do:
395+--
396+-- @
397+-- do
398+-- user <- usersById
399+-- orderCount <- count ordersByUserId
400+-- @
401+--
402+-- To see how many orders a user has (getting @0@ if they have no orders).
403+
404+
405+-- | 'count' returns a count of how many entries are in the given
406+-- 'Tabulation' at each key.
407+--
408+-- The resulting 'Tabulation' is \"magic\" in that the value @0@ exists at
409+-- every possible key that wasn't in the given 'Tabulation'.
410+count :: EqTable k => Tabulation k a -> Tabulation k (Expr Int64)
411+count =
412+ fmap (maybeTable 0 id) .
413+ optional .
414+ aggregate .
415+ fmap (const countStar)
416+
417+
418+-- | 'optional' produces a \"magic\" 'Tabulation' whereby each
419+-- entry in the given 'Tabulation' is wrapped in 'Rel8.justTable', and every
420+-- other possible key contains a single 'Rel8.nothingTable'.
421+--
422+-- This is used to implement 'leftAlignWith'.
423+optional :: Tabulation k a -> Tabulation k (MaybeTable Expr a)
424+optional (Tabulation f) = Tabulation $ \p -> case p of
425+ Predicate Nothing -> fmap pure <$> f p
426+ _ -> fmap (\m -> (empty, snd <$> m)) $ Q.optional $ do
427+ (k, a) <- f p
428+ ensure p k
429+ pure (k, a)
430+
431+
432+-- | 'many' aggregates each entry with a particular key into a
433+-- single entry with all of the values contained in a 'ListTable'.
434+--
435+-- 'order' can be used to give this 'ListTable' a defined order.
436+--
437+-- The resulting 'Tabulation' is \"magic\" in that the value
438+-- @'Rel8.listTable []'@ exists at every possible key that wasn't in the given
439+-- 'Tabulation'.
440+many :: (EqTable k, Table Expr a)
441+ => Tabulation k a -> Tabulation k (ListTable Expr a)
442+many =
443+ fmap (maybeTable mempty (\(ListTable a) -> ListTable a)) .
444+ optional .
445+ aggregate .
446+ fmap (listAgg . toCols)
447+
448+
449+-- | 'some' aggregates each entry with a particular key into a
450+-- single entry with all of the values contained in a 'NonEmptyTable'.
451+--
452+-- 'order' can be used to give this 'NonEmptyTable' a defined order.
453+some :: (EqTable k, Table Expr a)
454+ => Tabulation k a -> Tabulation k (NonEmptyTable Expr a)
455+some =
456+ fmap (\(NonEmptyTable a) -> NonEmptyTable a) .
457+ aggregate .
458+ fmap (nonEmptyAgg . toCols)
459+
460+
461+-- | 'exists' produces a \"magic\" 'Tabulation' which contains the
462+-- value 'Rel8.true' at each key in the given 'Tabulation', and the value
463+-- 'Rel8.false' at every other possible key.
464+exists :: Tabulation k a -> Tabulation k (Expr Bool)
465+exists (Tabulation f) = Tabulation $ \p -> case p of
466+ Predicate Nothing -> (true <$) <$> f p
467+ _ -> fmap (empty,) $ Q.exists $ do
468+ (k, _) <- f p
469+ ensure p k
470+
471+
472+-- | 'present' produces a 'Tabulation' where a single @()@ row
473+-- exists for every key that was present in the given 'Tabulation'.
474+--
475+-- This is used to implement 'similarity'.
476+present :: Tabulation k a -> Tabulation k ()
477+present (Tabulation f) = Tabulation $ \p -> do
478+ Q.present $ do
479+ (k, _) <- f p
480+ ensure p k
481+ pure (empty, ())
482+
483+
484+-- | 'absent' produces a 'Tabulation' where a single @()@ row exists
485+-- at every possible key that absent from the given 'Tabulation'.
486+--
487+-- This is used to implement 'difference'.
488+absent :: Tabulation k a -> Tabulation k ()
489+absent (Tabulation f) = Tabulation $ \p -> do
490+ Q.absent $ do
491+ (k, _) <- f p
492+ ensure p k
493+ pure (empty, ())
494+
495+
496+-- | Performs a @NATURAL FULL OUTER JOIN@ based on the common key columns.
497+--
498+-- Analogous to 'Data.Semialign.align'.
499+align :: EqTable k
500+ => Tabulation k a -> Tabulation k b -> Tabulation k (TheseTable Expr a b)
501+align = alignWith id
502+
503+
504+-- | Performs a @NATURAL FULL OUTER JOIN@ based on the common key columns.
505+--
506+-- Analogous to 'Data.Semialign.alignWith'.
507+alignWith :: EqTable k
508+ => (TheseTable Expr a b -> c)
509+ -> Tabulation k a -> Tabulation k b -> Tabulation k c
510+alignWith f (Tabulation as) (Tabulation bs) = Tabulation $ \p -> do
511+ tkab <- liftF2 (alignBy condition) as bs p
512+ k <- traverse (rebind "key") $ recover $ bimap fst fst tkab
513+ let
514+ tab = bimap snd snd tkab
515+ pure (k, f tab)
516+ where
517+ condition (k, _) (k', _) = fromMaybe true (liftA2 (==:) k k')
518+ recover (TheseTable mma@(MaybeTable _ ma) mmb@(MaybeTable _ mb)) =
519+ case extract ma of
520+ Nothing -> extract mb
521+ Just a -> case extract mb of
522+ Nothing -> extract ma
523+ Just b -> case a <$ mma <|>: b <$ mmb of
524+ MaybeTable _ c -> pure (extract c)
525+
526+
527+-- | Performs a @NATURAL LEFT OUTER JOIN@ based on the common key columns.
528+--
529+-- Analogous to 'Data.Semialign.rpadZip'.
530+--
531+-- Note that you can achieve the same effect with 'optional' and the
532+-- 'Applicative' instance for 'Tabulation', i.e., this is just
533+-- @\left right -> liftA2 (,) left (optional right). You can also
534+-- use @do@-notation.
535+leftAlign :: EqTable k
536+ => Tabulation k a -> Tabulation k b -> Tabulation k (a, MaybeTable Expr b)
537+leftAlign = leftAlignWith (,)
538+
539+
540+-- | Performs a @NATURAL LEFT OUTER JOIN@ based on the common key columns.
541+--
542+-- Analogous to 'Data.Semialign.rpadZipWith'.
543+--
544+-- Note that you can achieve the same effect with 'optional' and the
545+-- 'Applicative' instance for 'Tabulation', i.e., this is just
546+-- @\f left right -> liftA2 f left (optional right). You can also
547+-- use @do@-notation.
548+leftAlignWith :: EqTable k
549+ => (a -> MaybeTable Expr b -> c)
550+ -> Tabulation k a -> Tabulation k b -> Tabulation k c
551+leftAlignWith f left right = liftA2 f left (optional right)
552+
553+
554+-- | Performs a @NATURAL RIGHT OUTER JOIN@ based on the common key columns.
555+--
556+-- Analogous to 'Data.Semialign.lpadZip'.
557+--
558+-- Note that you can achieve the same effect with 'optional' and the
559+-- 'Applicative' instance for 'Tabulation', i.e., this is just
560+-- @\left right -> liftA2 (flip (,)) right (optional left). You can
561+-- also use @do@-notation.
562+rightAlign :: EqTable k
563+ => Tabulation k a -> Tabulation k b -> Tabulation k (MaybeTable Expr a, b)
564+rightAlign = rightAlignWith (,)
565+
566+
567+-- | Performs a @NATURAL RIGHT OUTER JOIN@ based on the common key columns.
568+--
569+-- Analogous to 'Data.Semialign.lpadZipWith'.
570+--
571+-- Note that you can achieve the same effect with 'optional' and the
572+-- 'Applicative' instance for 'Tabulation', i.e., this is just
573+-- @\f left right -> liftA2 (flip f) right (optional left). You can
574+-- also use @do@-notation.
575+rightAlignWith :: EqTable k
576+ => (MaybeTable Expr a -> b -> c)
577+ -> Tabulation k a -> Tabulation k b -> Tabulation k c
578+rightAlignWith f left right = liftA2 (flip f) right (optional left)
579+
580+
581+-- | Performs a @NATURAL INNER JOIN@ based on the common key columns.
582+--
583+-- Analagous to 'Data.Semialign.zip'.
584+--
585+-- Note that you can achieve the same effect with the 'Applicative' instance
586+-- of 'Tabulation', i.e., this is just @'liftA2 (,)'@. You can also use
587+-- @do@-notation.
588+zip :: EqTable k
589+ => Tabulation k a -> Tabulation k b -> Tabulation k (a, b)
590+zip = zipWith (,)
591+
592+
593+-- | Performs a @NATURAL INNER JOIN@ based on the common key columns.
594+--
595+-- Analagous to 'Data.Semialign.zipWith'.
596+--
597+-- Note that you can achieve the same effect with the 'Applicative' instance
598+-- of 'Tabulation', i.e., this is just @'liftA2'@. You can also use
599+-- @do@-notation.
600+zipWith :: EqTable k
601+ => (a -> b -> c) -> Tabulation k a -> Tabulation k b -> Tabulation k c
602+zipWith = liftA2
603+
604+
605+-- | Performs a [@NATURAL SEMI JOIN@](https://en.wikipedia.org/wiki/Relational_algebra#Semijoin_%28%E2%8B%89%29%28%E2%8B%8A%29)
606+-- based on the common key columns.
607+--
608+-- The result is a subset of the left tabulation where only entries which have
609+-- a corresponding entry in the right tabulation are kept.
610+--
611+-- Note that you can achieve a similar effect with 'present' and the
612+-- 'Applicative' instance of 'Tabulation', i.e., this is just
613+-- @\left right -> left <* present right@. You can also use
614+-- @do@-notation.
615+similarity :: EqTable k => Tabulation k a -> Tabulation k b -> Tabulation k a
616+similarity a b = a <* present b
617+
618+
619+-- | Performs a [@NATURAL ANTI JOIN@](https://en.wikipedia.org/wiki/Relational_algebra#Antijoin_%28%E2%96%B7%29)
620+-- based on the common key columns.
621+--
622+-- The result is a subset of the left tabulation where only entries which do
623+-- not have a corresponding entry in the right tabulation are kept.
624+--
625+-- Note that you can achieve a similar effect with 'absent' and the
626+-- 'Applicative' instance of 'Tabulation', i.e., this is just
627+-- @\left right -> left <* absent right@. You can also use
628+-- @do@-notation.
629+difference :: EqTable k => Tabulation k a -> Tabulation k b -> Tabulation k a
630+difference a b = a <* absent b
631+
632+
633+-- | 'Tabulation's can be produced with either 'fromQuery' or 'liftQuery', and
634+-- in some cases we might want to treat these differently. 'peek' uses
635+-- 'unsafePeekQuery' to determine which type of 'Tabulation' we have.
636+peek :: Tabulation k a -> Tabulation k (Either (Query a) (Query (k, a)))
637+peek (Tabulation f) = Tabulation $ \p ->
638+ pure $ (empty,) $ case unsafePeekQuery (f p) of
639+ (Nothing, _) -> Left $ fmap snd (f p)
640+ (Just _, _) -> Right $ fmap (first fromJust) (f p)
src/Rel8/Type.hs+9−8
@@ -1,3 +1,4 @@
1+{-# language FlexibleContexts #-}
1{-# language FlexibleInstances #-}
2{-# language FlexibleInstances #-}
2{-# language MonoLocalBinds #-}
3{-# language MonoLocalBinds #-}
3{-# language MultiWayIf #-}
4{-# language MultiWayIf #-}
@@ -127,10 +128,10 @@ instance DBType Int64 where
127instance DBType Float where
128instance DBType Float where
128 typeInformation = TypeInformation
129 typeInformation = TypeInformation
129 { encode = \x -> Opaleye.ConstExpr
130 { encode = \x -> Opaleye.ConstExpr
130− if | x == (1 /0) -> Opaleye.OtherLit "'Infinity'"
131+ if | x == (1 / 0) -> Opaleye.OtherLit "'Infinity'"
131− | isNaN x -> Opaleye.OtherLit "'NaN'"
132+ | isNaN x -> Opaleye.OtherLit "'NaN'"
132− | x == (-1/0) -> Opaleye.OtherLit "'-Infinity'"
133+ | x == (-1 / 0) -> Opaleye.OtherLit "'-Infinity'"
133− | otherwise -> Opaleye.NumericLit $ realToFrac x
134+ | otherwise -> Opaleye.NumericLit $ realToFrac x
134 , decode = Hasql.float4
135 , decode = Hasql.float4
135 , typeName = "float4"
136 , typeName = "float4"
136 }
137 }
@@ -140,10 +141,10 @@ instance DBType Float where
140instance DBType Double where
141instance DBType Double where
141 typeInformation = TypeInformation
142 typeInformation = TypeInformation
142 { encode = \x -> Opaleye.ConstExpr
143 { encode = \x -> Opaleye.ConstExpr
143− if | x == (1 /0) -> Opaleye.OtherLit "'Infinity'"
144+ if | x == (1 / 0) -> Opaleye.OtherLit "'Infinity'"
144− | isNaN x -> Opaleye.OtherLit "'NaN'"
145+ | isNaN x -> Opaleye.OtherLit "'NaN'"
145− | x == (-1/0) -> Opaleye.OtherLit "'-Infinity'"
146+ | x == (-1 / 0) -> Opaleye.OtherLit "'-Infinity'"
146− | otherwise -> Opaleye.NumericLit $ realToFrac x
147+ | otherwise -> Opaleye.NumericLit $ realToFrac x
147 , decode = Hasql.float8
148 , decode = Hasql.float8
148 , typeName = "float8"
149 , typeName = "float8"
149 }
150 }
src/Rel8/Type/Composite.hs+9−8
@@ -20,6 +20,7 @@ where
20
20
21-- base
21-- base
22import Data.Functor.Const ( Const( Const ), getConst )
22import Data.Functor.Const ( Const( Const ), getConst )
23+import Data.Functor.Identity ( Identity( Identity ) )
23import Data.Kind ( Constraint, Type )
24import Data.Kind ( Constraint, Type )
24import Prelude
25import Prelude
25
26
@@ -30,13 +31,13 @@ import qualified Hasql.Decoders as Hasql
30import qualified Opaleye.Internal.HaskellDB.PrimQuery as Opaleye
31import qualified Opaleye.Internal.HaskellDB.PrimQuery as Opaleye
31
32
32-- rel8
33-- rel8
33−import Rel8.Expr ( Expr( E ) )
34+import Rel8.Expr ( Expr )
34import Rel8.Expr.Opaleye ( castExpr, fromPrimExpr, toPrimExpr )
35import Rel8.Expr.Opaleye ( castExpr, fromPrimExpr, toPrimExpr )
35import Rel8.Schema.HTable ( HTable, hfield, hspecs, htabulate, htabulateA )
36import Rel8.Schema.HTable ( HTable, hfield, hspecs, htabulate, htabulateA )
36−import Rel8.Schema.Name ( Name( N, Name ) )
37+import Rel8.Schema.Name ( Name( Name ) )
37import Rel8.Schema.Null ( Nullity( Null, NotNull ) )
38import Rel8.Schema.Null ( Nullity( Null, NotNull ) )
38−import Rel8.Schema.Result ( Result( R ) )
39+import Rel8.Schema.Result ( Result )
39−import Rel8.Schema.Spec ( SSpec( SSpec, nullity, info ) )
40+import Rel8.Schema.Spec ( Spec( Spec, nullity, info ) )
40import Rel8.Table ( fromColumns, toColumns, fromResult, toResult )
41import Rel8.Table ( fromColumns, toColumns, fromResult, toResult )
41import Rel8.Table.Eq ( EqTable )
42import Rel8.Table.Eq ( EqTable )
42import Rel8.Table.HKD ( HKD, HKDable )
43import Rel8.Table.HKD ( HKD, HKDable )
@@ -112,8 +113,8 @@ compose = castExpr . fromPrimExpr . encoder . toColumns
112decompose :: forall a. DBComposite a => Expr a -> HKD a Expr
113decompose :: forall a. DBComposite a => Expr a -> HKD a Expr
113decompose (toPrimExpr -> a) = fromColumns $ htabulate \field ->
114decompose (toPrimExpr -> a) = fromColumns $ htabulate \field ->
114 case hfield names field of
115 case hfield names field of
115− N (Name name) -> case hfield hspecs field of
116+ Name name -> case hfield hspecs field of
116− SSpec {} -> E $ fromPrimExpr $ Opaleye.CompositeExpr a name
117+ Spec {} -> fromPrimExpr $ Opaleye.CompositeExpr a name
117 where
118 where
118 names = toColumns (compositeFields @a)
119 names = toColumns (compositeFields @a)
119
120
@@ -121,7 +122,7 @@ decompose (toPrimExpr -> a) = fromColumns $ htabulate \field ->
121decoder :: HTable t => Hasql.Composite (t Result)
122decoder :: HTable t => Hasql.Composite (t Result)
122decoder = unwrapApplicative $ htabulateA \field ->
123decoder = unwrapApplicative $ htabulateA \field ->
123 case hfield hspecs field of
124 case hfield hspecs field of
124− SSpec {nullity, info} -> WrapApplicative $ R <$>
125+ Spec {nullity, info} -> WrapApplicative $ Identity <$>
125 case nullity of
126 case nullity of
126 Null -> Hasql.field $ Hasql.nullable $ decode info
127 Null -> Hasql.field $ Hasql.nullable $ decode info
127 NotNull -> Hasql.field $ Hasql.nonNullable $ decode info
128 NotNull -> Hasql.field $ Hasql.nonNullable $ decode info
@@ -131,4 +132,4 @@ encoder :: HTable t => t Expr -> Opaleye.PrimExpr
131encoder a = Opaleye.FunExpr "ROW" exprs
132encoder a = Opaleye.FunExpr "ROW" exprs
132 where
133 where
133 exprs = getConst $ htabulateA \field -> case hfield a field of
134 exprs = getConst $ htabulateA \field -> case hfield a field of
134− E (toPrimExpr -> expr) -> Const [expr]
135+ expr -> Const [toPrimExpr expr]
src/Rel8/Type/Enum.hs+1
@@ -106,6 +106,7 @@ class (DBType a, Enumable a) => DBEnum a where
106
106
107-- | Types that are sum types, where each constructor is unary (that is, has no
107-- | Types that are sum types, where each constructor is unary (that is, has no
108-- fields).
108-- fields).
109+type Enumable :: Type -> Constraint
109class (Generic a, GEnumable (Rep a)) => Enumable a
110class (Generic a, GEnumable (Rep a)) => Enumable a
110instance (Generic a, GEnumable (Rep a)) => Enumable a
111instance (Generic a, GEnumable (Rep a)) => Enumable a
111
112
src/Rel8/Type/JSONBEncoded.hs+4
@@ -1,3 +1,5 @@
1+{-# language StandaloneKindSignatures #-}
2+
1module Rel8.Type.JSONBEncoded ( JSONBEncoded(..) ) where
3module Rel8.Type.JSONBEncoded ( JSONBEncoded(..) ) where
2
4
3-- aeson
5-- aeson
@@ -6,6 +8,7 @@ import Data.Aeson.Types ( parseEither )
6
8
7-- base
9-- base
8import Data.Bifunctor ( first )
10import Data.Bifunctor ( first )
11+import Data.Kind ( Type )
9import Prelude
12import Prelude
10
13
11-- hasql
14-- hasql
@@ -20,6 +23,7 @@ import Data.Text ( pack )
20
23
21
24
22-- | Like 'Rel8.JSONEncoded', but works for @jsonb@ columns.
25-- | Like 'Rel8.JSONEncoded', but works for @jsonb@ columns.
26+type JSONBEncoded :: Type -> Type
23newtype JSONBEncoded a = JSONBEncoded { fromJSONBEncoded :: a }
27newtype JSONBEncoded a = JSONBEncoded { fromJSONBEncoded :: a }
24
28
25
29
src/Rel8/Type/JSONEncoded.hs+4
@@ -1,3 +1,5 @@
1+{-# language StandaloneKindSignatures #-}
2+
1module Rel8.Type.JSONEncoded ( JSONEncoded(..) ) where
3module Rel8.Type.JSONEncoded ( JSONEncoded(..) ) where
2
4
3-- aeson
5-- aeson
@@ -5,6 +7,7 @@ import Data.Aeson ( FromJSON, ToJSON, parseJSON, toJSON )
5import Data.Aeson.Types ( parseEither )
7import Data.Aeson.Types ( parseEither )
6
8
7-- base
9-- base
10+import Data.Kind ( Type )
8import Prelude
11import Prelude
9
12
10-- rel8
13-- rel8
@@ -15,6 +18,7 @@ import Rel8.Type.Information ( parseTypeInformation )
15-- | A deriving-via helper type for column types that store a Haskell value
18-- | A deriving-via helper type for column types that store a Haskell value
16-- using a JSON encoding described by @aeson@'s 'ToJSON' and 'FromJSON' type
19-- using a JSON encoding described by @aeson@'s 'ToJSON' and 'FromJSON' type
17-- classes.
20-- classes.
21+type JSONEncoded :: Type -> Type
18newtype JSONEncoded a = JSONEncoded { fromJSONEncoded :: a }
22newtype JSONEncoded a = JSONEncoded { fromJSONEncoded :: a }
19
23
20
24
src/Rel8/Type/Num.hs+4−1
@@ -18,6 +18,7 @@ import Prelude
18
18
19-- rel8
19-- rel8
20import Rel8.Type ( DBType )
20import Rel8.Type ( DBType )
21+import Rel8.Type.Ord ( DBOrd )
21
22
22-- scientific
23-- scientific
23import Data.Scientific ( Scientific )
24import Data.Scientific ( Scientific )
@@ -39,13 +40,14 @@ instance DBNum Scientific
39-- expressions. This is a Rel8 concept, and allows us to provide
40-- expressions. This is a Rel8 concept, and allows us to provide
40-- 'fromIntegral'.
41-- 'fromIntegral'.
41type DBIntegral :: Type -> Constraint
42type DBIntegral :: Type -> Constraint
42−class DBNum a => DBIntegral a
43+class (DBNum a, DBOrd a) => DBIntegral a
43instance DBIntegral Int16
44instance DBIntegral Int16
44instance DBIntegral Int32
45instance DBIntegral Int32
45instance DBIntegral Int64
46instance DBIntegral Int64
46
47
47
48
48-- | The class of database types that support the @/@ operator.
49-- | The class of database types that support the @/@ operator.
50+type DBFractional :: Type -> Constraint
49class DBNum a => DBFractional a
51class DBNum a => DBFractional a
50instance DBFractional Float
52instance DBFractional Float
51instance DBFractional Double
53instance DBFractional Double
@@ -53,6 +55,7 @@ instance DBFractional Scientific
53
55
54
56
55-- | The class of database types that support the @/@ operator.
57-- | The class of database types that support the @/@ operator.
58+type DBFloating :: Type -> Constraint
56class DBFractional a => DBFloating a
59class DBFractional a => DBFloating a
57instance DBFloating Float
60instance DBFloating Float
58instance DBFloating Double
61instance DBFloating Double
src/Rel8/Type/Ord.hs−2
@@ -75,7 +75,6 @@ instance Sql DBOrd a => DBOrd (NonEmpty a)
75-- | The class of database types that support the @max@ aggregation function.
75-- | The class of database types that support the @max@ aggregation function.
76type DBMax :: Type -> Constraint
76type DBMax :: Type -> Constraint
77class DBOrd a => DBMax a
77class DBOrd a => DBMax a
78−instance DBMax Bool
79instance DBMax Char
78instance DBMax Char
80instance DBMax Int16
79instance DBMax Int16
81instance DBMax Int32
80instance DBMax Int32
@@ -101,7 +100,6 @@ instance Sql DBMax a => DBMax (NonEmpty a)
101-- | The class of database types that support the @min@ aggregation function.
100-- | The class of database types that support the @min@ aggregation function.
102type DBMin :: Type -> Constraint
101type DBMin :: Type -> Constraint
103class DBOrd a => DBMin a
102class DBOrd a => DBMin a
104−instance DBMin Bool
105instance DBMin Char
103instance DBMin Char
106instance DBMin Int16
104instance DBMin Int16
107instance DBMin Int32
105instance DBMin Int32
src/Rel8/Type/ReadShow.hs+3
@@ -1,10 +1,12 @@
1{-# language ScopedTypeVariables #-}
1{-# language ScopedTypeVariables #-}
2+{-# language StandaloneKindSignatures #-}
2{-# language TypeApplications #-}
3{-# language TypeApplications #-}
3{-# language ViewPatterns #-}
4{-# language ViewPatterns #-}
4
5
5module Rel8.Type.ReadShow ( ReadShow(..) ) where
6module Rel8.Type.ReadShow ( ReadShow(..) ) where
6
7
7-- base
8-- base
9+import Data.Kind ( Type )
8import Data.Proxy ( Proxy( Proxy ) )
10import Data.Proxy ( Proxy( Proxy ) )
9import Data.Typeable ( Typeable, typeRep )
11import Data.Typeable ( Typeable, typeRep )
10import Prelude
12import Prelude
@@ -20,6 +22,7 @@ import qualified Data.Text as Text
20
22
21-- | A deriving-via helper type for column types that store a Haskell value
23-- | A deriving-via helper type for column types that store a Haskell value
22-- using a Haskell's 'Read' and 'Show' type classes.
24-- using a Haskell's 'Read' and 'Show' type classes.
25+type ReadShow :: Type -> Type
23newtype ReadShow a = ReadShow { fromReadShow :: a }
26newtype ReadShow a = ReadShow { fromReadShow :: a }
24
27
25
28
src/Rel8/Type/Tag.hs+1
@@ -90,6 +90,7 @@ instance DBMonoid MaybeTag where
90 memptyExpr = litExpr mempty
90 memptyExpr = litExpr mempty
91
91
92
92
93+type Tag :: Type
93newtype Tag = Tag Text
94newtype Tag = Tag Text
94 deriving newtype
95 deriving newtype
95 ( Eq, Ord, Read, Show
96 ( Eq, Ord, Read, Show
src/Rel8/Window.hsnew file+97
@@ -0,0 +1,97 @@
1+{-# language DerivingVia #-}
2+{-# language FlexibleContexts #-}
3+{-# language GeneralizedNewtypeDeriving #-}
4+{-# language ScopedTypeVariables #-}
5+{-# language StandaloneKindSignatures #-}
6+{-# language TypeApplications #-}
7+
8+module Rel8.Window
9+ ( Window(..)
10+ , Partition
11+ , over
12+ , partitionBy
13+ , orderPartitionBy
14+ )
15+where
16+
17+-- base
18+import Data.Functor.Const ( Const( Const ), getConst )
19+import Data.Functor.Contravariant ( Contravariant, contramap )
20+import Data.Kind ( Type )
21+import Prelude
22+
23+-- opaleye
24+import qualified Opaleye.Internal.Window as Opaleye
25+import qualified Opaleye.Internal.PackMap as Opaleye
26+
27+-- profunctors
28+import Data.Profunctor ( Profunctor )
29+
30+-- product-profunctors
31+import Data.Profunctor.Product ( ProductProfunctor, (****), purePP )
32+
33+-- rel8
34+import Rel8.Expr.Opaleye ( toColumn, toPrimExpr )
35+import Rel8.Order( Order( Order ) )
36+import Rel8.Schema.HTable ( hfield, htabulateA )
37+import Rel8.Table ( Columns, toColumns )
38+import Rel8.Table.Eq ( EqTable )
39+
40+-- semigroupoids
41+import Data.Functor.Apply ( Apply, WrappedApplicative(..) )
42+
43+
44+-- | 'Window' is an applicative functor that represents expressions that
45+-- contain
46+-- [window functions](https://www.postgresql.org/docs/current/tutorial-window.html).
47+-- 'Rel8.Query.Window.window' can be used to
48+-- evaluate these expressions over a particular query.
49+type Window :: Type -> Type -> Type
50+newtype Window a b = Window (Opaleye.Windows a b)
51+ deriving newtype (Profunctor)
52+ deriving newtype (Functor, Applicative)
53+ deriving (Apply) via (WrappedApplicative (Window a))
54+
55+
56+instance ProductProfunctor Window where
57+ purePP = pure
58+ (****) = (<*>)
59+
60+
61+-- | In PostgreSQL, window functions must specify the \"window\" or
62+-- \"partition\" over which they operate. The syntax for this looks like:
63+-- @SUM(salary) OVER (PARTITION BY department)@. The Rel8 type 'Partition'
64+-- represents everything that comes after @OVER@.
65+--
66+-- 'Partition' is a 'Monoid', so 'Window's created with 'partitionBy' and
67+-- 'orderWindowBy' can be combined using '<>'.
68+type Partition :: Type -> Type
69+newtype Partition a = Partition (Opaleye.Window a)
70+ deriving newtype (Contravariant, Semigroup, Monoid)
71+
72+
73+-- | 'over' adds a 'Partition' to a 'Window' expression.
74+--
75+-- @@@
76+-- 'Rel8.Table.Window.cumulative' ('Rel8.Expr.Aggregate.sum' . salary) `over` 'partitionBy' department <> 'orderPartitionBy' (salary >$< 'Rel8.desc')
77+-- @@@
78+over :: Window a b -> Partition a -> Window a b
79+over (Window (Opaleye.Windows (Opaleye.PackMap w))) (Partition p) =
80+ Window $ Opaleye.Windows $ Opaleye.PackMap $ \f ->
81+ w (\(o, p') -> f (o, p' <> p))
82+infixl 1 `over`
83+
84+
85+-- | Restricts a window function to operate only the group of rows that share
86+-- the same value(s) for the given expression(s).
87+partitionBy :: forall b a. EqTable b => (a -> b) -> Partition a
88+partitionBy f =
89+ Partition $ contramap (toColumns . f) $ getConst $
90+ htabulateA @(Columns b) $ \field ->
91+ Const $ Opaleye.partitionBy (toColumn . toPrimExpr . (`hfield` field))
92+
93+
94+-- | Controls the order in which rows are processed by window functions. This
95+-- does not need to match the ordering of the overall query.
96+orderPartitionBy :: Order a -> Partition a
97+orderPartitionBy (Order ordering) = Partition $ Opaleye.orderPartitionBy ordering
tests/Main.hs+288−178
@@ -1,12 +1,11 @@
1+{-# language BangPatterns #-}
1{-# language BlockArguments #-}
2{-# language BlockArguments #-}
2−{-# language DataKinds #-}
3{-# language DeriveAnyClass #-}
3{-# language DeriveAnyClass #-}
4{-# language DeriveGeneric #-}
4{-# language DeriveGeneric #-}
5{-# language DerivingStrategies #-}
5{-# language DerivingStrategies #-}
6−{-# language DisambiguateRecordFields #-}
7{-# language FlexibleContexts #-}
6{-# language FlexibleContexts #-}
8{-# language FlexibleInstances #-}
7{-# language FlexibleInstances #-}
9−{-# language GADTs #-}
8+{-# language MonoLocalBinds #-}
10{-# language NamedFieldPuns #-}
9{-# language NamedFieldPuns #-}
11{-# language OverloadedStrings #-}
10{-# language OverloadedStrings #-}
12{-# language RecordWildCards #-}
11{-# language RecordWildCards #-}
@@ -14,17 +13,15 @@
14{-# language StandaloneDeriving #-}
13{-# language StandaloneDeriving #-}
15{-# language TypeApplications #-}
14{-# language TypeApplications #-}
16
15
17−{-# options_ghc -fno-warn-redundant-constraints #-}
18−
19module Main
16module Main
20 ( main
17 ( main
21 )
18 )
22where
19where
23
20
24-- base
21-- base
25−import Control.Applicative ( liftA2, liftA3 )
22+import Control.Applicative ( empty, liftA2, liftA3 )
26−import Control.Monad (void)
23+import Control.Exception ( bracket, throwIO )
27−import Control.Monad.IO.Class ( MonadIO, liftIO )
24+import Control.Monad ( (>=>), void )
28import Data.Bifunctor ( bimap )
25import Data.Bifunctor ( bimap )
29import Data.Foldable ( for_ )
26import Data.Foldable ( for_ )
30import Data.Int ( Int32, Int64 )
27import Data.Int ( Int32, Int64 )
@@ -38,25 +35,27 @@ import GHC.Generics ( Generic )
38import qualified Data.ByteString.Lazy
35import qualified Data.ByteString.Lazy
39
36
40-- case-insensitive
37-- case-insensitive
41−import Data.CaseInsensitive (mk)
38+import Data.CaseInsensitive ( mk )
42
39
43-- containers
40-- containers
41+import Data.Containers.ListUtils ( nubOrdOn )
44import qualified Data.Map.Strict as Map
42import qualified Data.Map.Strict as Map
45
43
46-- hasql
44-- hasql
47−import Hasql.Connection ( Connection, acquire, release )
45+import Hasql.Connection ( Connection, acquire, release )
48import Hasql.Session ( sql, run )
46import Hasql.Session ( sql, run )
49
47
48+-- hasql-transaction
49+import Hasql.Transaction ( Transaction, condemn, statement )
50+import qualified Hasql.Transaction.Sessions as Hasql
51+
50-- hedgehog
52-- hedgehog
51import Hedgehog ( property, (===), forAll, cover, diff, evalM, PropertyT, TestT, test, Gen )
53import Hedgehog ( property, (===), forAll, cover, diff, evalM, PropertyT, TestT, test, Gen )
52import qualified Hedgehog.Gen as Gen
54import qualified Hedgehog.Gen as Gen
53import qualified Hedgehog.Range as Range
55import qualified Hedgehog.Range as Range
54
56
55−-- lifted-base
57+-- mmorph
56−import Control.Exception.Lifted ( bracket, throwIO, bracket_ )
57−
58−-- monad-control
59−import Control.Monad.Trans.Control ( MonadBaseControl )
58+import Control.Monad.Morph ( hoist )
60
59
61-- rel8
60-- rel8
62import Rel8 ( Result )
61import Rel8 ( Result )
@@ -72,12 +71,16 @@ import Test.Tasty
72import Test.Tasty.Hedgehog ( testProperty )
71import Test.Tasty.Hedgehog ( testProperty )
73
72
74-- text
73-- text
75−import Data.Text (Text, pack)
74+import Data.Text ( Text, pack, unpack )
76import qualified Data.Text.Lazy
75import qualified Data.Text.Lazy
76+import Data.Text.Encoding ( decodeUtf8 )
77
77
78-- time
78-- time
79import Data.Time
79import Data.Time
80
80
81+-- transformers
82+import Control.Monad.Trans.Class ( lift )
83+
81-- tmp-postgres
84-- tmp-postgres
82import qualified Database.Postgres.Temp as TmpPostgres
85import qualified Database.Postgres.Temp as TmpPostgres
83
86
@@ -113,11 +116,13 @@ tests =
113 , testCatMaybeTable getTestDatabase
116 , testCatMaybeTable getTestDatabase
114 , testCatMaybe getTestDatabase
117 , testCatMaybe getTestDatabase
115 , testMaybeTable getTestDatabase
118 , testMaybeTable getTestDatabase
119+ , testAggregateMaybeTable getTestDatabase
116 , testNestedTables getTestDatabase
120 , testNestedTables getTestDatabase
117 , testMaybeTableApplicative getTestDatabase
121 , testMaybeTableApplicative getTestDatabase
118 , testLogicalFixities getTestDatabase
122 , testLogicalFixities getTestDatabase
119 , testUpdate getTestDatabase
123 , testUpdate getTestDatabase
120 , testDelete getTestDatabase
124 , testDelete getTestDatabase
125+ , testUpsert getTestDatabase
121 , testSelectNestedPairs getTestDatabase
126 , testSelectNestedPairs getTestDatabase
122 , testSelectArray getTestDatabase
127 , testSelectArray getTestDatabase
123 , testNestedMaybeTable getTestDatabase
128 , testNestedMaybeTable getTestDatabase
@@ -133,6 +138,7 @@ tests =
133 flip run conn do
138 flip run conn do
134 sql "CREATE EXTENSION citext"
139 sql "CREATE EXTENSION citext"
135 sql "CREATE TABLE test_table ( column1 text not null, column2 bool not null )"
140 sql "CREATE TABLE test_table ( column1 text not null, column2 bool not null )"
141+ sql "CREATE TABLE unique_table ( \"key\" text not null unique, \"value\" text not null )"
136 sql "CREATE SEQUENCE test_seq"
142 sql "CREATE SEQUENCE test_seq"
137
143
138 return db
144 return db
@@ -140,19 +146,21 @@ tests =
140 stopTestDatabase = TmpPostgres.stop
146 stopTestDatabase = TmpPostgres.stop
141
147
142
148
149+connect :: TmpPostgres.DB -> IO Connection
150+connect = acquire . TmpPostgres.toConnectionString >=> either (maybe empty (fail . unpack . decodeUtf8)) pure
151+
152+
143databasePropertyTest
153databasePropertyTest
144 :: TestName
154 :: TestName
145− -> (((Connection -> TestT IO ()) -> PropertyT IO ()) -> PropertyT IO ())
155+ -> ((TestT Transaction () -> PropertyT IO ()) -> PropertyT IO ())
146 -> IO TmpPostgres.DB -> TestTree
156 -> IO TmpPostgres.DB -> TestTree
147databasePropertyTest testName f getTestDatabase =
157databasePropertyTest testName f getTestDatabase =
148− withResource connect release $ \c ->
158+ withResource (connect =<< getTestDatabase) release $ \c ->
149 testProperty testName $ property do
159 testProperty testName $ property do
150− connection <- liftIO c
160+ connection <- lift c
151− f \g -> test $ rollingBack connection $ g connection
161+ f $ test . hoist \m -> do
152−
162+ e <- run (Hasql.transaction Hasql.Serializable Hasql.Write (m <* condemn)) connection
153− where
163+ either throwIO pure e
154−
155− connect = either (error . show) return =<< acquire . TmpPostgres.toConnectionString =<< getTestDatabase
156
164
157
165
158data TestTable f = TestTable
166data TestTable f = TestTable
@@ -184,18 +192,17 @@ testSelectTestTable :: IO TmpPostgres.DB -> TestTree
184testSelectTestTable = databasePropertyTest "Can SELECT TestTable" \transaction -> do
192testSelectTestTable = databasePropertyTest "Can SELECT TestTable" \transaction -> do
185 rows <- forAll $ Gen.list (Range.linear 0 10) genTestTable
193 rows <- forAll $ Gen.list (Range.linear 0 10) genTestTable
186
194
187− transaction \connection -> do
195+ transaction do
188− void do
196+ selected <- lift do
189− liftIO $ Rel8.insert connection
190− Rel8.Insert
197+ statement () $ Rel8.insert Rel8.Insert
191− { into = testTableSchema
198+ { into = testTableSchema
192− , rows = map Rel8.lit rows
199+ , rows = Rel8.values $ map Rel8.lit rows
193− , onConflict = Rel8.DoNothing
200+ , onConflict = Rel8.DoNothing
194− , returning = Rel8.NumberOfRowsAffected
201+ , returning = pure ()
195− }
202+ }
196
203
197− selected <- liftIO $ Rel8.select connection do
204+ statement () $ Rel8.select do
198− Rel8.each testTableSchema
205+ Rel8.each testTableSchema
199
206
200 sort selected === sort rows
207 sort selected === sort rows
201
208
@@ -212,11 +219,12 @@ testWhere_ = databasePropertyTest "WHERE (Rel8.where_)" \transaction -> do
212
219
213 let expected = filter (\t -> testTableColumn2 t == magicBool) rows
220 let expected = filter (\t -> testTableColumn2 t == magicBool) rows
214
221
215− transaction \connection -> do
222+ transaction do
223+ selected <- lift do
216− selected <- liftIO $ Rel8.select connection do
224+ statement () $ Rel8.select do
217− t <- Rel8.values $ Rel8.lit <$> rows
225+ t <- Rel8.values $ Rel8.lit <$> rows
218− Rel8.where_ $ testTableColumn2 t Rel8.==. Rel8.lit magicBool
226+ Rel8.where_ $ testTableColumn2 t Rel8.==. Rel8.lit magicBool
219− return t
227+ return t
220
228
221 sort selected === sort expected
229 sort selected === sort expected
222
230
@@ -229,11 +237,12 @@ testFilter :: IO TmpPostgres.DB -> TestTree
229testFilter = databasePropertyTest "filter" \transaction -> do
237testFilter = databasePropertyTest "filter" \transaction -> do
230 rows <- forAll $ Gen.list (Range.linear 1 10) genTestTable
238 rows <- forAll $ Gen.list (Range.linear 1 10) genTestTable
231
239
232− transaction \connection -> do
240+ transaction do
233 let expected = filter testTableColumn2 rows
241 let expected = filter testTableColumn2 rows
234
242
235− selected <- liftIO $ Rel8.select connection
243+ selected <- lift do
244+ statement () $ Rel8.select do
236− $ Rel8.filter testTableColumn2 =<< Rel8.values (Rel8.lit <$> rows)
245+ Rel8.filter testTableColumn2 =<< Rel8.values (Rel8.lit <$> rows)
237
246
238 sort selected === sort expected
247 sort selected === sort expected
239
248
@@ -248,9 +257,10 @@ testLimit = databasePropertyTest "LIMIT (Rel8.limit)" \transaction -> do
248
257
249 n <- forAll $ Gen.integral (Range.linear 0 10)
258 n <- forAll $ Gen.integral (Range.linear 0 10)
250
259
251− transaction \connection -> do
260+ transaction do
261+ selected <- lift do
252− selected <- liftIO $ Rel8.select connection do
262+ statement () $ Rel8.select do
253− Rel8.limit n $ Rel8.values (Rel8.lit <$> rows)
263+ Rel8.limit n $ Rel8.values (Rel8.lit <$> rows)
254
264
255 diff (length selected) (<=) (fromIntegral n)
265 diff (length selected) (<=) (fromIntegral n)
256
266
@@ -268,9 +278,10 @@ testUnion = databasePropertyTest "UNION (Rel8.union)" \transaction -> evalM do
268 left <- forAll $ Gen.list (Range.linear 0 10) genTestTable
278 left <- forAll $ Gen.list (Range.linear 0 10) genTestTable
269 right <- forAll $ Gen.list (Range.linear 0 10) genTestTable
279 right <- forAll $ Gen.list (Range.linear 0 10) genTestTable
270
280
271− transaction \connection -> do
281+ transaction do
282+ selected <- lift do
272− selected <- liftIO $ Rel8.select connection do
283+ statement () $ Rel8.select do
273− Rel8.values (Rel8.lit <$> nub left) `Rel8.union` Rel8.values (Rel8.lit <$> nub right)
284+ Rel8.values (Rel8.lit <$> nub left) `Rel8.union` Rel8.values (Rel8.lit <$> nub right)
274
285
275 sort selected === sort (nub (left ++ right))
286 sort selected === sort (nub (left ++ right))
276
287
@@ -279,9 +290,11 @@ testDistinct :: IO TmpPostgres.DB -> TestTree
279testDistinct = databasePropertyTest "DISTINCT (Rel8.distinct)" \transaction -> do
290testDistinct = databasePropertyTest "DISTINCT (Rel8.distinct)" \transaction -> do
280 rows <- forAll $ Gen.list (Range.linear 0 10) genTestTable
291 rows <- forAll $ Gen.list (Range.linear 0 10) genTestTable
281
292
282− transaction \connection -> do
293+ transaction do
294+ selected <- lift do
295+ statement () $ Rel8.select do
283− selected <- liftIO $ Rel8.select connection $ Rel8.distinct do
296+ Rel8.distinct do
284− Rel8.values (Rel8.lit <$> rows)
297+ Rel8.values (Rel8.lit <$> rows)
285
298
286 sort selected === nub (sort rows)
299 sort selected === nub (sort rows)
287
300
@@ -294,8 +307,10 @@ testExists :: IO TmpPostgres.DB -> TestTree
294testExists = databasePropertyTest "EXISTS (Rel8.exists)" \transaction -> do
307testExists = databasePropertyTest "EXISTS (Rel8.exists)" \transaction -> do
295 rows <- forAll $ Gen.list (Range.linear 0 10) genTestTable
308 rows <- forAll $ Gen.list (Range.linear 0 10) genTestTable
296
309
297− transaction \connection -> do
310+ transaction do
311+ exists <- lift do
312+ statement () $ Rel8.select do
298− exists <- liftIO $ Rel8.select connection $ Rel8.exists $ Rel8.values $ Rel8.lit <$> rows
313+ Rel8.exists $ Rel8.values $ Rel8.lit <$> rows
299
314
300 case rows of
315 case rows of
301 [] -> exists === [False]
316 [] -> exists === [False]
@@ -306,9 +321,10 @@ testOptional :: IO TmpPostgres.DB -> TestTree
306testOptional = databasePropertyTest "Rel8.optional" \transaction -> do
321testOptional = databasePropertyTest "Rel8.optional" \transaction -> do
307 rows <- forAll $ Gen.list (Range.linear 0 10) genTestTable
322 rows <- forAll $ Gen.list (Range.linear 0 10) genTestTable
308
323
309− transaction \connection -> do
324+ transaction do
325+ selected <- lift do
310− selected <- liftIO $ Rel8.select connection do
326+ statement () $ Rel8.select do
311− Rel8.optional $ Rel8.values (Rel8.lit <$> rows)
327+ Rel8.optional $ Rel8.values (Rel8.lit <$> rows)
312
328
313 case rows of
329 case rows of
314 [] -> selected === [Nothing]
330 [] -> selected === [Nothing]
@@ -319,9 +335,10 @@ testAnd :: IO TmpPostgres.DB -> TestTree
319testAnd = databasePropertyTest "AND (&&.)" \transaction -> do
335testAnd = databasePropertyTest "AND (&&.)" \transaction -> do
320 (x, y) <- forAll $ liftA2 (,) Gen.bool Gen.bool
336 (x, y) <- forAll $ liftA2 (,) Gen.bool Gen.bool
321
337
322− transaction \connection -> do
338+ transaction do
323− [result] <- liftIO $ Rel8.select connection $ pure $
339+ [result] <- lift do
340+ statement () $ Rel8.select do
324− Rel8.lit x Rel8.&&. Rel8.lit y
341+ pure $ Rel8.lit x Rel8.&&. Rel8.lit y
325
342
326 result === (x && y)
343 result === (x && y)
327
344
@@ -330,9 +347,10 @@ testOr :: IO TmpPostgres.DB -> TestTree
330testOr = databasePropertyTest "OR (||.)" \transaction -> do
347testOr = databasePropertyTest "OR (||.)" \transaction -> do
331 (x, y) <- forAll $ liftA2 (,) Gen.bool Gen.bool
348 (x, y) <- forAll $ liftA2 (,) Gen.bool Gen.bool
332
349
333− transaction \connection -> do
350+ transaction do
351+ [result] <- lift do
334− [result] <- liftIO $ Rel8.select connection $ pure $
352+ statement () $ Rel8.select $ pure $
335− Rel8.lit x Rel8.||. Rel8.lit y
353+ Rel8.lit x Rel8.||. Rel8.lit y
336
354
337 result === (x || y)
355 result === (x || y)
338
356
@@ -341,9 +359,10 @@ testLogicalFixities :: IO TmpPostgres.DB -> TestTree
341testLogicalFixities = databasePropertyTest "Logical operator fixities" \transaction -> do
359testLogicalFixities = databasePropertyTest "Logical operator fixities" \transaction -> do
342 (u, v, w, x) <- forAll $ (,,,) <$> Gen.bool <*> Gen.bool <*> Gen.bool <*> Gen.bool
360 (u, v, w, x) <- forAll $ (,,,) <$> Gen.bool <*> Gen.bool <*> Gen.bool <*> Gen.bool
343
361
344− transaction \connection -> do
362+ transaction do
345− [result] <- liftIO $ Rel8.select connection $ pure $
363+ [result] <- lift do
364+ statement () $ Rel8.select do
346− Rel8.lit u Rel8.||. Rel8.lit v Rel8.&&. Rel8.lit w Rel8.==. Rel8.lit x
365+ pure $ Rel8.lit u Rel8.||. Rel8.lit v Rel8.&&. Rel8.lit w Rel8.==. Rel8.lit x
347
366
348 result === (u || v && w == x)
367 result === (u || v && w == x)
349
368
@@ -352,9 +371,10 @@ testNot :: IO TmpPostgres.DB -> TestTree
352testNot = databasePropertyTest "NOT (not_)" \transaction -> do
371testNot = databasePropertyTest "NOT (not_)" \transaction -> do
353 x <- forAll Gen.bool
372 x <- forAll Gen.bool
354
373
355− transaction \connection -> do
374+ transaction do
356− [result] <- liftIO $ Rel8.select connection $ pure $
375+ [result] <- lift do
376+ statement () $ Rel8.select do
357− Rel8.not_ $ Rel8.lit x
377+ pure $ Rel8.not_ $ Rel8.lit x
358
378
359 result === not x
379 result === not x
360
380
@@ -363,9 +383,10 @@ testBool :: IO TmpPostgres.DB -> TestTree
363testBool = databasePropertyTest "ifThenElse_" \transaction -> do
383testBool = databasePropertyTest "ifThenElse_" \transaction -> do
364 (x, y, z) <- forAll $ liftA3 (,,) Gen.bool Gen.bool Gen.bool
384 (x, y, z) <- forAll $ liftA3 (,,) Gen.bool Gen.bool Gen.bool
365
385
366− transaction \connection -> do
386+ transaction do
367− [result] <- liftIO $ Rel8.select connection $ pure $
387+ [result] <- lift do
388+ statement () $ Rel8.select do
368− Rel8.bool (Rel8.lit z) (Rel8.lit y) (Rel8.lit x)
389+ pure $ Rel8.bool (Rel8.lit z) (Rel8.lit y) (Rel8.lit x)
369
390
370 result === if x then y else z
391 result === if x then y else z
371
392
@@ -377,9 +398,10 @@ testAp = databasePropertyTest "Cartesian product (<*>)" \transaction -> do
377 (Gen.list (Range.linear 1 10) genTestTable)
398 (Gen.list (Range.linear 1 10) genTestTable)
378 (Gen.list (Range.linear 1 10) genTestTable)
399 (Gen.list (Range.linear 1 10) genTestTable)
379
400
380− transaction \connection -> do
401+ transaction do
402+ result <- lift do
381− result <- liftIO $ Rel8.select connection $ do
403+ statement () $ Rel8.select do
382− liftA2 (,) (Rel8.values (Rel8.lit <$> rows1)) (Rel8.values (Rel8.lit <$> rows2))
404+ liftA2 (,) (Rel8.values (Rel8.lit <$> rows1)) (Rel8.values (Rel8.lit <$> rows2))
383
405
384 sort result === sort (liftA2 (,) rows1 rows2)
406 sort result === sort (liftA2 (,) rows1 rows2)
385
407
@@ -408,21 +430,22 @@ testDBType getTestDatabase = testGroup "DBType instances"
408 where
430 where
409 dbTypeTest :: (Eq a, Show a, Rel8.DBType a) => TestName -> Gen a -> TestTree
431 dbTypeTest :: (Eq a, Show a, Rel8.DBType a) => TestName -> Gen a -> TestTree
410 dbTypeTest name generator = testGroup name
432 dbTypeTest name generator = testGroup name
411− [ databasePropertyTest name (t (==) generator) getTestDatabase
433+ [ databasePropertyTest name (t generator) getTestDatabase
412− , databasePropertyTest ("Maybe " <> name) (t (==) (Gen.maybe generator)) getTestDatabase
434+ , databasePropertyTest ("Maybe " <> name) (t (Gen.maybe generator)) getTestDatabase
413 ]
435 ]
414
436
415− t :: forall a b. (Show a, Rel8.Sql Rel8.DBType a)
437+ t :: forall a b. (Eq a, Show a, Rel8.Sql Rel8.DBType a)
416− => (a -> a -> Bool)
417− -> Gen a
438+ => Gen a
418− -> ((Connection -> TestT IO ()) -> PropertyT IO b)
439+ -> (TestT Transaction () -> PropertyT IO b)
419 -> PropertyT IO b
440 -> PropertyT IO b
420− t eq generator transaction = do
441+ t generator transaction = do
421 x <- forAll generator
442 x <- forAll generator
422
443
423− transaction \connection -> do
444+ transaction do
445+ [res] <- lift do
446+ statement () $ Rel8.select do
424− [res] <- liftIO $ Rel8.select connection $ pure (Rel8.litExpr x)
447+ pure (Rel8.litExpr x)
425− diff res eq x
448+ diff res (==) x
426
449
427 genDay :: Gen Day
450 genDay :: Gen Day
428 genDay = do
451 genDay = do
@@ -464,13 +487,15 @@ testDBEq getTestDatabase = testGroup "DBEq instances"
464
487
465 t :: forall a. (Eq a, Show a, Rel8.Sql Rel8.DBEq a)
488 t :: forall a. (Eq a, Show a, Rel8.Sql Rel8.DBEq a)
466 => Gen a
489 => Gen a
467− -> ((Connection -> TestT IO ()) -> PropertyT IO ())
490+ -> (TestT Transaction () -> PropertyT IO ())
468 -> PropertyT IO ()
491 -> PropertyT IO ()
469 t generator transaction = do
492 t generator transaction = do
470 (x, y) <- forAll (liftA2 (,) generator generator)
493 (x, y) <- forAll (liftA2 (,) generator generator)
471
494
472− transaction \connection -> do
495+ transaction do
496+ [res] <- lift do
497+ statement () $ Rel8.select do
473− [res] <- liftIO $ Rel8.select connection $ pure $ Rel8.litExpr x Rel8.==. Rel8.litExpr y
498+ pure $ Rel8.litExpr x Rel8.==. Rel8.litExpr y
474 res === (x == y)
499 res === (x == y)
475
500
476
501
@@ -478,9 +503,10 @@ testTableEquality :: IO TmpPostgres.DB -> TestTree
478testTableEquality = databasePropertyTest "TestTable equality" \transaction -> do
503testTableEquality = databasePropertyTest "TestTable equality" \transaction -> do
479 (x, y) <- forAll $ liftA2 (,) genTestTable genTestTable
504 (x, y) <- forAll $ liftA2 (,) genTestTable genTestTable
480
505
481− transaction \connection -> do
506+ transaction do
507+ [eq] <- lift do
482− [eq] <- liftIO $ Rel8.select connection do
508+ statement () $ Rel8.select do
483− pure $ Rel8.lit x Rel8.==: Rel8.lit y
509+ pure $ Rel8.lit x Rel8.==: Rel8.lit y
484
510
485 eq === (x == y)
511 eq === (x == y)
486
512
@@ -489,8 +515,10 @@ testFromString :: IO TmpPostgres.DB -> TestTree
489testFromString = databasePropertyTest "FromString" \transaction -> do
515testFromString = databasePropertyTest "FromString" \transaction -> do
490 str <- forAll $ Gen.list (Range.linear 0 10) Gen.unicode
516 str <- forAll $ Gen.list (Range.linear 0 10) Gen.unicode
491
517
492− transaction \connection -> do
518+ transaction do
519+ [result] <- lift do
520+ statement () $ Rel8.select do
493− [result] <- liftIO $ Rel8.select connection $ pure $ fromString str
521+ pure $ fromString str
494 result === pack str
522 result === pack str
495
523
496
524
@@ -498,10 +526,11 @@ testCatMaybeTable :: IO TmpPostgres.DB -> TestTree
498testCatMaybeTable = databasePropertyTest "catMaybeTable" \transaction -> do
526testCatMaybeTable = databasePropertyTest "catMaybeTable" \transaction -> do
499 rows <- forAll $ Gen.list (Range.linear 0 10) genTestTable
527 rows <- forAll $ Gen.list (Range.linear 0 10) genTestTable
500
528
501− transaction \connection -> do
529+ transaction do
530+ selected <- lift do
502− selected <- liftIO $ Rel8.select connection do
531+ statement () $ Rel8.select do
503− testTable <- Rel8.values $ Rel8.lit <$> rows
532+ testTable <- Rel8.values $ Rel8.lit <$> rows
504− Rel8.catMaybeTable $ Rel8.bool Rel8.nothingTable (pure testTable) (testTableColumn2 testTable)
533+ Rel8.catMaybeTable $ Rel8.bool Rel8.nothingTable (pure testTable) (testTableColumn2 testTable)
505
534
506 sort selected === sort (filter testTableColumn2 rows)
535 sort selected === sort (filter testTableColumn2 rows)
507
536
@@ -510,9 +539,10 @@ testCatMaybe :: IO TmpPostgres.DB -> TestTree
510testCatMaybe = databasePropertyTest "catMaybe" \transaction -> evalM do
539testCatMaybe = databasePropertyTest "catMaybe" \transaction -> evalM do
511 rows <- forAll $ Gen.list (Range.linear 0 10) $ Gen.maybe Gen.bool
540 rows <- forAll $ Gen.list (Range.linear 0 10) $ Gen.maybe Gen.bool
512
541
513− transaction \connection -> do
542+ transaction do
514− selected <- evalM $ liftIO $ Rel8.select connection do
543+ selected <- lift do
544+ statement () $ Rel8.select do
515− Rel8.catNull =<< Rel8.values (map Rel8.lit rows)
545+ Rel8.catNull =<< Rel8.values (map Rel8.lit rows)
516
546
517 sort selected === sort (catMaybes rows)
547 sort selected === sort (catMaybes rows)
518
548
@@ -521,15 +551,38 @@ testMaybeTable :: IO TmpPostgres.DB -> TestTree
521testMaybeTable = databasePropertyTest "maybeTable" \transaction -> evalM do
551testMaybeTable = databasePropertyTest "maybeTable" \transaction -> evalM do
522 (rows, def) <- forAll $ liftA2 (,) (Gen.list (Range.linear 0 10) genTestTable) genTestTable
552 (rows, def) <- forAll $ liftA2 (,) (Gen.list (Range.linear 0 10) genTestTable) genTestTable
523
553
524− transaction \connection -> do
554+ transaction do
525− selected <- liftIO $ Rel8.select connection $
555+ selected <- lift do
556+ statement () $ Rel8.select do
526− Rel8.maybeTable (Rel8.lit def) id <$> Rel8.optional (Rel8.values (Rel8.lit <$> rows))
557+ Rel8.maybeTable (Rel8.lit def) id <$> Rel8.optional (Rel8.values (Rel8.lit <$> rows))
527
558
528 case rows of
559 case rows of
529 [] -> selected === [def]
560 [] -> selected === [def]
530 _ -> sort selected === sort rows
561 _ -> sort selected === sort rows
531
562
532
563
564+testAggregateMaybeTable :: IO TmpPostgres.DB -> TestTree
565+testAggregateMaybeTable = databasePropertyTest "aggregateMaybeTable" \transaction -> evalM do
566+ rows <- forAll $ Gen.list (Range.linear 0 10) (Gen.maybe (Gen.int64 (Range.linear 0 10)))
567+
568+ let
569+ aggregate = go 0 False False
570+ where
571+ go !n nothing _ (Just a : as) = go (n + a) nothing True as
572+ go n _ just (Nothing : as) = go n True just as
573+ go _ False False [] = []
574+ go _ True False [] = [Nothing]
575+ go n False True [] = [Just n]
576+ go n True True [] = [Nothing, Just n]
577+
578+ transaction do
579+ selected <- lift do
580+ statement () $ Rel8.select do
581+ Rel8.aggregate $ Rel8.aggregateMaybeTable Rel8.sum <$> Rel8.values (Rel8.lit <$> rows)
582+
583+ sort selected === aggregate rows
584+
585+
533data TwoTestTables f =
586data TwoTestTables f =
534 TwoTestTables
587 TwoTestTables
535 { testTable1 :: TestTable f
588 { testTable1 :: TestTable f
@@ -550,9 +603,10 @@ testNestedTables = databasePropertyTest "Nested TestTables" \transaction -> eval
550 Gen.list (Range.linear 0 10) $
603 Gen.list (Range.linear 0 10) $
551 liftA2 TwoTestTables genTestTable genTestTable
604 liftA2 TwoTestTables genTestTable genTestTable
552
605
553− transaction \connection -> do
606+ transaction do
607+ selected <- lift do
554− selected <- liftIO $ Rel8.select connection do
608+ statement () $ Rel8.select do
555− Rel8.values (Rel8.lit <$> rows)
609+ Rel8.values (Rel8.lit <$> rows)
556
610
557 sort selected === sort rows
611 sort selected === sort rows
558
612
@@ -562,11 +616,12 @@ testMaybeTableApplicative = databasePropertyTest "MaybeTable (<*>)" \transaction
562 rows1 <- genRows
616 rows1 <- genRows
563 rows2 <- genRows
617 rows2 <- genRows
564
618
565− transaction \connection -> do
619+ transaction do
620+ selected <- lift do
566− selected <- liftIO $ Rel8.select connection do
621+ statement () $ Rel8.select do
567− as <- Rel8.optional (Rel8.values (Rel8.lit <$> rows1))
622+ as <- Rel8.optional (Rel8.values (Rel8.lit <$> rows1))
568− bs <- Rel8.optional (Rel8.values (Rel8.lit <$> rows2))
623+ bs <- Rel8.optional (Rel8.values (Rel8.lit <$> rows2))
569− pure $ liftA2 (,) as bs
624+ pure $ liftA2 (,) as bs
570
625
571 case (rows1, rows2) of
626 case (rows1, rows2) of
572 ([], []) -> selected === [Nothing]
627 ([], []) -> selected === [Nothing]
@@ -578,14 +633,6 @@ testMaybeTableApplicative = databasePropertyTest "MaybeTable (<*>)" \transaction
578 genRows = forAll do
633 genRows = forAll do
579 Gen.list (Range.linear 0 10) $ liftA2 TestTable (Gen.text (Range.linear 0 10) Gen.unicode) (pure True)
634 Gen.list (Range.linear 0 10) $ liftA2 TestTable (Gen.text (Range.linear 0 10) Gen.unicode) (pure True)
580
635
581−rollingBack
582− :: (MonadBaseControl IO m, MonadIO m)
583− => Connection -> m a -> m a
584−rollingBack connection =
585− bracket_
586− (liftIO (run (sql "BEGIN") connection))
587− (liftIO (run (sql "ROLLBACK") connection))
588−
589
636
590genTestTable :: Gen (TestTable Result)
637genTestTable :: Gen (TestTable Result)
591genTestTable = do
638genTestTable = do
@@ -598,19 +645,19 @@ testUpdate :: IO TmpPostgres.DB -> TestTree
598testUpdate = databasePropertyTest "Can UPDATE TestTable" \transaction -> do
645testUpdate = databasePropertyTest "Can UPDATE TestTable" \transaction -> do
599 rows <- forAll $ Gen.map (Range.linear 0 5) $ liftA2 (,) genTestTable genTestTable
646 rows <- forAll $ Gen.map (Range.linear 0 5) $ liftA2 (,) genTestTable genTestTable
600
647
601− transaction \connection -> do
648+ transaction do
602− void $ liftIO $ Rel8.insert connection
649+ selected <- lift do
603− Rel8.Insert
650+ statement () $ Rel8.insert Rel8.Insert
604 { into = testTableSchema
651 { into = testTableSchema
605− , rows = map Rel8.lit $ Map.keys rows
652+ , rows = Rel8.values $ map Rel8.lit $ Map.keys rows
606 , onConflict = Rel8.DoNothing
653 , onConflict = Rel8.DoNothing
607− , returning = Rel8.NumberOfRowsAffected
654+ , returning = pure ()
608 }
655 }
609
656
610− void $ liftIO $ Rel8.update connection
611− Rel8.Update
657+ statement () $ Rel8.update Rel8.Update
612 { target = testTableSchema
658 { target = testTableSchema
659+ , from = pure ()
613− , set = \r ->
660+ , set = \_ r ->
614 let updates = map (bimap Rel8.lit Rel8.lit) $ Map.toList rows
661 let updates = map (bimap Rel8.lit Rel8.lit) $ Map.toList rows
615 in
662 in
616 foldl
663 foldl
@@ -624,12 +671,12 @@ testUpdate = databasePropertyTest "Can UPDATE TestTable" \transaction -> do
624 )
671 )
625 r
672 r
626 updates
673 updates
627− , updateWhere = \_ -> Rel8.lit True
674+ , updateWhere = \_ _ -> Rel8.lit True
628− , returning = Rel8.NumberOfRowsAffected
675+ , returning = pure ()
629 }
676 }
630
677
631− selected <- liftIO $ Rel8.select connection do
678+ statement () $ Rel8.select do
632− Rel8.each testTableSchema
679+ Rel8.each testTableSchema
633
680
634 sort selected === sort (Map.elems rows)
681 sort selected === sort (Map.elems rows)
635
682
@@ -642,29 +689,96 @@ testDelete :: IO TmpPostgres.DB -> TestTree
642testDelete = databasePropertyTest "Can DELETE TestTable" \transaction -> do
689testDelete = databasePropertyTest "Can DELETE TestTable" \transaction -> do
643 rows <- forAll $ Gen.list (Range.linear 0 5) genTestTable
690 rows <- forAll $ Gen.list (Range.linear 0 5) genTestTable
644
691
645− transaction \connection -> do
692+ transaction do
646− void $ liftIO $ Rel8.insert connection
693+ (deleted, selected) <- lift do
647− Rel8.Insert
694+ statement () $ Rel8.insert Rel8.Insert
648 { into = testTableSchema
695 { into = testTableSchema
649− , rows = map Rel8.lit rows
696+ , rows = Rel8.values $ map Rel8.lit rows
650 , onConflict = Rel8.DoNothing
697 , onConflict = Rel8.DoNothing
651− , returning = Rel8.NumberOfRowsAffected
698+ , returning = pure ()
652 }
699 }
653
700
654− deleted <-
655− liftIO $ Rel8.delete connection
656− Rel8.Delete
701+ deleted <- statement () $ Rel8.delete Rel8.Delete
657 { from = testTableSchema
702 { from = testTableSchema
703+ , using = pure ()
658− , deleteWhere = testTableColumn2
704+ , deleteWhere = const testTableColumn2
659 , returning = Rel8.Projection id
705 , returning = Rel8.Projection id
660 }
706 }
661
707
662− selected <- liftIO $ Rel8.select connection do
708+ selected <- statement () $ Rel8.select do
663− Rel8.each testTableSchema
709+ Rel8.each testTableSchema
710+
711+ pure (deleted, selected)
664
712
665 sort (deleted <> selected) === sort rows
713 sort (deleted <> selected) === sort rows
666
714
667
715
716+data UniqueTable f = UniqueTable
717+ { uniqueTableKey :: Rel8.Column f Text
718+ , uniqueTableValue :: Rel8.Column f Text
719+ }
720+ deriving stock Generic
721+ deriving anyclass Rel8.Rel8able
722+
723+
724+deriving stock instance Eq (UniqueTable Result)
725+deriving stock instance Ord (UniqueTable Result)
726+deriving stock instance Show (UniqueTable Result)
727+
728+
729+uniqueTableSchema :: Rel8.TableSchema (UniqueTable Rel8.Name)
730+uniqueTableSchema =
731+ Rel8.TableSchema
732+ { name = "unique_table"
733+ , schema = Nothing
734+ , columns = UniqueTable
735+ { uniqueTableKey = "key"
736+ , uniqueTableValue = "value"
737+ }
738+ }
739+
740+
741+genUniqueTable :: Gen (UniqueTable Result)
742+genUniqueTable = do
743+ uniqueTableKey <- Gen.text (Range.linear 0 5) Gen.alphaNum
744+ uniqueTableValue <- Gen.text (Range.linear 0 5) Gen.alphaNum
745+ pure UniqueTable {..}
746+
747+
748+testUpsert :: IO TmpPostgres.DB -> TestTree
749+testUpsert = databasePropertyTest "Can UPSERT UniqueTable" \transaction -> do
750+ as <- unique $ forAll $ Gen.list (Range.linear 0 20) genUniqueTable
751+ bs <- unique $ forAll $ Gen.list (Range.linear 0 20) genUniqueTable
752+
753+ transaction do
754+ selected <- lift do
755+ statement () $ Rel8.insert Rel8.Insert
756+ { into = uniqueTableSchema
757+ , rows = Rel8.values $ Rel8.lit <$> as
758+ , onConflict = Rel8.DoNothing
759+ , returning = pure ()
760+ }
761+
762+ statement () $ Rel8.insert Rel8.Insert
763+ { into = uniqueTableSchema
764+ , rows = Rel8.values $ Rel8.lit <$> bs
765+ , onConflict = Rel8.DoUpdate Rel8.Upsert
766+ { index = uniqueTableKey
767+ , set = \UniqueTable {uniqueTableValue} old -> old {uniqueTableValue}
768+ , updateWhere = \_ _ -> Rel8.true
769+ }
770+ , returning = pure ()
771+ }
772+
773+ statement () $ Rel8.select do
774+ Rel8.each uniqueTableSchema
775+
776+ fromUniqueTables selected === fromUniqueTables bs <> fromUniqueTables as
777+ where
778+ unique = fmap (nubOrdOn uniqueTableKey)
779+ fromUniqueTables = Map.fromList . map \(UniqueTable key value) -> (key, value)
780+
781+
668newtype HKNestedPair f = HKNestedPair { pairOne :: (TestTable f, TestTable f) }
782newtype HKNestedPair f = HKNestedPair { pairOne :: (TestTable f, TestTable f) }
669 deriving stock Generic
783 deriving stock Generic
670 deriving anyclass Rel8.Rel8able
784 deriving anyclass Rel8.Rel8able
@@ -678,9 +792,10 @@ testSelectNestedPairs :: IO TmpPostgres.DB -> TestTree
678testSelectNestedPairs = databasePropertyTest "Can SELECT nested pairs" \transaction -> do
792testSelectNestedPairs = databasePropertyTest "Can SELECT nested pairs" \transaction -> do
679 rows <- forAll $ Gen.list (Range.linear 0 10) $ HKNestedPair <$> liftA2 (,) genTestTable genTestTable
793 rows <- forAll $ Gen.list (Range.linear 0 10) $ HKNestedPair <$> liftA2 (,) genTestTable genTestTable
680
794
681− transaction \connection -> do
795+ transaction do
796+ selected <- lift do
682− selected <- liftIO $ Rel8.select connection do
797+ statement () $ Rel8.select do
683− Rel8.values $ map Rel8.lit rows
798+ Rel8.values $ map Rel8.lit rows
684
799
685 sort selected === sort rows
800 sort selected === sort rows
686
801
@@ -689,18 +804,20 @@ testSelectArray :: IO TmpPostgres.DB -> TestTree
689testSelectArray = databasePropertyTest "Can SELECT Arrays (with aggregation)" \transaction -> do
804testSelectArray = databasePropertyTest "Can SELECT Arrays (with aggregation)" \transaction -> do
690 rows <- forAll $ Gen.list (Range.linear 1 10) Gen.bool
805 rows <- forAll $ Gen.list (Range.linear 1 10) Gen.bool
691
806
692− transaction \connection -> do
807+ transaction do
808+ selected <- lift do
693− selected <- liftIO $ Rel8.select connection do
809+ statement () $ Rel8.select do
694− Rel8.many $ Rel8.values (map Rel8.lit rows)
810+ Rel8.many $ Rel8.values (map Rel8.lit rows)
695
811
696 selected === [foldMap pure rows]
812 selected === [foldMap pure rows]
697
813
814+ selected' <- lift do
698− selected' <- liftIO $ Rel8.select connection $ do
815+ statement () $ Rel8.select do
699− a <- Rel8.catListTable =<< do
816+ a <- Rel8.catListTable =<< do
700− Rel8.many $ Rel8.values (map Rel8.lit rows)
817+ Rel8.many $ Rel8.values (map Rel8.lit rows)
701− b <- Rel8.catListTable =<< do
818+ b <- Rel8.catListTable =<< do
702− Rel8.many $ Rel8.values (map Rel8.lit rows)
819+ Rel8.many $ Rel8.values (map Rel8.lit rows)
703− pure (a, b)
820+ pure (a, b)
704
821
705 selected' === liftA2 (,) rows rows
822 selected' === liftA2 (,) rows rows
706
823
@@ -722,10 +839,11 @@ testNestedMaybeTable :: IO TmpPostgres.DB -> TestTree
722testNestedMaybeTable = databasePropertyTest "Can nest MaybeTable within other tables" \transaction -> do
839testNestedMaybeTable = databasePropertyTest "Can nest MaybeTable within other tables" \transaction -> do
723 let example = NestedMaybeTable { nmt1 = True, nmt2 = Just (TestTable "Hi" True) }
840 let example = NestedMaybeTable { nmt1 = True, nmt2 = Just (TestTable "Hi" True) }
724
841
725− transaction \connection -> do
842+ transaction do
843+ selected <- lift do
726− selected <- liftIO $ Rel8.select connection do
844+ statement () $ Rel8.select do
727− x <- Rel8.values [Rel8.lit example]
845+ x <- Rel8.values [Rel8.lit example]
728− pure $ Rel8.maybeTable (Rel8.lit False) (\_ -> Rel8.lit True) (nmt2 x)
846+ pure $ Rel8.maybeTable (Rel8.lit False) (\_ -> Rel8.lit True) (nmt2 x)
729
847
730 selected === [True]
848 selected === [True]
731
849
@@ -733,11 +851,12 @@ testNestedMaybeTable = databasePropertyTest "Can nest MaybeTable within other ta
733testEvaluate :: IO TmpPostgres.DB -> TestTree
851testEvaluate :: IO TmpPostgres.DB -> TestTree
734testEvaluate = databasePropertyTest "evaluate has the evaluation order we expect" \transaction -> do
852testEvaluate = databasePropertyTest "evaluate has the evaluation order we expect" \transaction -> do
735
853
736− transaction \connection -> do
854+ transaction do
855+ selected <- lift do
737− selected <- liftIO $ Rel8.select connection do
856+ statement () $ Rel8.select do
738− x <- Rel8.values (Rel8.lit <$> ['a', 'b', 'c'])
857+ x <- Rel8.values (Rel8.lit <$> ['a', 'b', 'c'])
739− y <- Rel8.evaluate (Rel8.nextval "test_seq")
858+ y <- Rel8.evaluate (Rel8.nextval "test_seq")
740− pure (x, (y, y))
859+ pure (x, (y, y))
741
860
742 normalize selected ===
861 normalize selected ===
743 [ ('a', (0, 0))
862 [ ('a', (0, 0))
@@ -745,11 +864,12 @@ testEvaluate = databasePropertyTest "evaluate has the evaluation order we expect
745 , ('c', (2, 2))
864 , ('c', (2, 2))
746 ]
865 ]
747
866
867+ selected' <- lift do
748− selected' <- liftIO $ Rel8.select connection do
868+ statement () $ Rel8.select do
749− x <- Rel8.values (Rel8.lit <$> ['a', 'b', 'c'])
869+ x <- Rel8.values (Rel8.lit <$> ['a', 'b', 'c'])
750− y <- Rel8.values (Rel8.lit <$> ['d', 'e', 'f'])
870+ y <- Rel8.values (Rel8.lit <$> ['d', 'e', 'f'])
751− z <- Rel8.evaluate (Rel8.nextval "test_seq")
871+ z <- Rel8.evaluate (Rel8.nextval "test_seq")
752− pure ((x, y), (z, z))
872+ pure ((x, y), (z, z))
753
873
754 normalize selected' ===
874 normalize selected' ===
755 [ (('a', 'd'), (0, 0))
875 [ (('a', 'd'), (0, 0))
@@ -767,13 +887,3 @@ testEvaluate = databasePropertyTest "evaluate has the evaluation order we expect
767 normalize :: [(x, (Int64, Int64))] -> [(x, (Int64, Int64))]
887 normalize :: [(x, (Int64, Int64))] -> [(x, (Int64, Int64))]
768 normalize [] = []
888 normalize [] = []
769 normalize xs@((_, (i, _)) : _) = map (fmap (\(a, b) -> (a - i, b - i))) xs
889 normalize xs@((_, (i, _)) : _) = map (fmap (\(a, b) -> (a - i, b - i))) xs
770−
771−{-
772− selected <- liftIO $ Rel8.select connection do
773− x <- Rel8.values (Rel8.lit <$> ['a', 'b', 'c'])
774− x <- Rel8.values (Rel8.lit <$> ['d', 'e', 'f'])
775− y <- Rel8.evaluate (Rel8.nextval "test_seq")
776− pure (x, y, y)
777−
778− selected === [('a', 1, 1), ('b', 2, 2), ('c', 3, 3)]
779−-}
tests/Rel8/Generic/Rel8able/Test.hs+44−1
@@ -5,7 +5,9 @@
5{-# language DuplicateRecordFields #-}
5{-# language DuplicateRecordFields #-}
6{-# language FlexibleInstances #-}
6{-# language FlexibleInstances #-}
7{-# language MultiParamTypeClasses #-}
7{-# language MultiParamTypeClasses #-}
8+{-# language StandaloneKindSignatures #-}
8{-# language TypeFamilies #-}
9{-# language TypeFamilies #-}
10+{-# language UndecidableInstances #-}
9
11
10{-# options_ghc -O0 #-}
12{-# options_ghc -O0 #-}
11
13
@@ -136,10 +138,51 @@ data TableSum f
136 deriving stock Generic
138 deriving stock Generic
137
139
138
140
141+data BarbieSum f
142+ = BarbieSumA (f Bool) (f Text)
143+ | BarbieSumB
144+ | BarbieSumC (f Text)
145+ deriving stock Generic
146+
147+
139data TableProduct f = TableProduct
148data TableProduct f = TableProduct
140− { sum :: HADT f TableSum
149+ { sum :: HADT f BarbieSum
141 , list :: TableList f
150 , list :: TableList f
142 , foos :: HList f (HADT f TableSum, Lift f HKDSum, HKDTest f)
151 , foos :: HList f (HADT f TableSum, Lift f HKDSum, HKDTest f)
143 }
152 }
144 deriving stock Generic
153 deriving stock Generic
145 deriving anyclass Rel8able
154 deriving anyclass Rel8able
155+
156+
157+data TableTestB f = TableTestB
158+ { foo :: f Bool
159+ , bar :: f (Maybe Bool)
160+ }
161+ deriving stock Generic
162+ deriving anyclass Rel8able
163+
164+
165+data NestedTableTestB f = NestedTableTestB
166+ { foo :: f Bool
167+ , bar :: f (Maybe Bool)
168+ , baz :: Column f Char
169+ , nest :: TableTestB f
170+ }
171+ deriving stock Generic
172+ deriving anyclass Rel8able
173+
174+
175+newtype IdRecord a f = IdRecord { recordId :: Column f a }
176+ deriving stock Generic
177+
178+
179+instance DBType a => Rel8able (IdRecord a)
180+
181+
182+type Nest :: KRel8able -> KRel8able -> KRel8able
183+data Nest t u f = Nest
184+ { foo :: t f
185+ , bar :: u f
186+ }
187+ deriving stock Generic
188+ deriving anyclass Rel8able