@@ -1,7 +1,7 @@
11{-|
22Module: Squeal.PostgreSQL.Query
33Description: Squeal queries
4−Copyright: (c) Eitan Chatav, 2017
4+Copyright: (c) Eitan Chatav, 2019
55Maintainer: eitan@morphism.tech
66Stability: experimental
77
@@ -17,7 +17,9 @@ Squeal queries.
1717 , GeneralizedNewtypeDeriving
1818 , LambdaCase
1919 , MultiParamTypeClasses
20+ , OverloadedLabels
2021 , OverloadedStrings
22+ , QuantifiedConstraints
2123 , ScopedTypeVariables
2224 , StandaloneDeriving
2325 , TypeApplications
@@ -30,12 +32,15 @@ Squeal queries.
3032
3133module Squeal.PostgreSQL.Query
3234 ( -- * Queries
33− Query (..)
35+ Query_
36+ , Query (..)
3437 -- ** Select
3538 , select
3639 , select_
3740 , selectDistinct
3841 , selectDistinct_
42+ , selectDistinctOn
43+ , selectDistinctOn_
3944 , Selection (..)
4045 -- ** Values
4146 , values
@@ -50,31 +55,13 @@ module Squeal.PostgreSQL.Query
5055 -- ** With
5156 , With (..)
5257 , CommonTableExpression (..)
53− , renderCommonTableExpression
54− , renderCommonTableExpressions
55− -- ** Json
56− , jsonEach
57− , jsonbEach
58− , jsonEachAsText
59− , jsonbEachAsText
60− , jsonObjectKeys
61− , jsonbObjectKeys
62− , jsonPopulateRecord
63− , jsonbPopulateRecord
64− , jsonPopulateRecordSet
65− , jsonbPopulateRecordSet
66− , jsonToRecord
67− , jsonbToRecord
68− , jsonToRecordSet
69− , jsonbToRecordSet
58+ , withRecursive
7059 -- * Table Expressions
7160 , TableExpression (..)
72− , renderTableExpression
7361 , from
7462 , where_
7563 , groupBy
7664 , having
77− , orderBy
7865 , limit
7966 , offset
8067 -- * From Clauses
@@ -90,42 +77,13 @@ module Squeal.PostgreSQL.Query
9077 , fullOuterJoin
9178 -- * Grouping
9279 , By (..)
93− , renderBy
9480 , GroupByClause (..)
9581 , HavingClause (..)
96− -- * Sorting
97− , SortExpression (..)
98− -- * Subquery Expressions
99− , in_
100− , rowIn
101− , eqAll
102− , rowEqAll
103− , eqAny
104− , rowEqAny
105− , neqAll
106− , rowNeqAll
107− , neqAny
108− , rowNeqAny
109− , allLt
110− , rowLtAll
111− , ltAny
112− , rowLtAny
113− , lteAll
114− , rowLteAll
115− , lteAny
116− , rowLteAny
117− , gtAll
118− , rowGtAll
119− , gtAny
120− , rowGtAny
121− , gteAll
122− , rowGteAll
123− , gteAny
124− , rowGteAny
12582 ) where
12683
12784import Control.DeepSeq
12885import Data.ByteString (ByteString)
86+import Data.Kind (Type)
12987import Data.String
13088import Data.Word
13189import Generics.SOP hiding (from)
@@ -133,13 +91,67 @@ import GHC.TypeLits
13391
13492import qualified GHC.Generics as GHC
13593
94+import Squeal.PostgreSQL.Alias
13695import Squeal.PostgreSQL.Expression
96+import Squeal.PostgreSQL.Expression.Logic
97+import Squeal.PostgreSQL.Expression.Sort
98+import Squeal.PostgreSQL.Expression.Window
99+import Squeal.PostgreSQL.List
100+import Squeal.PostgreSQL.PG
137101import Squeal.PostgreSQL.Render
138102import Squeal.PostgreSQL.Schema
139103
104+-- $setup
105+-- >>> import Squeal.PostgreSQL
106+-- >>> import Data.Int (Int32, Int64)
107+-- >>> import Data.Monoid (Sum (..))
108+-- >>> import Data.Text (Text)
109+-- >>> import qualified Generics.SOP as SOP
110+
140111{- |
141−The process of retrieving or the command to retrieve data from a database
142−is called a `Query`. Let's see some examples of queries.
112+The process of retrieving or the command to retrieve data from
113+a database is called a `Query`.
114+
115+The general `Query` type is parameterized by
116+
117+* @outer :: FromType@ - outer scope for a correlated subquery,
118+* @commons :: FromType@ - scope for all `common` table expressions,
119+* @schemas :: SchemasType@ - scope for all `table`s and `view`s,
120+* @params :: [NullityType]@ - scope for all `Squeal.Expression.Parameter.parameter`s,
121+* @row :: RowType@ - return type of the `Query`.
122+-}
123+newtype Query
124+ (outer :: FromType)
125+ (commons :: FromType)
126+ (schemas :: SchemasType)
127+ (params :: [NullityType])
128+ (row :: RowType)
129+ = UnsafeQuery { renderQuery :: ByteString }
130+ deriving (GHC.Generic,Show,Eq,Ord,NFData)
131+instance RenderSQL (Query outer commons schemas params row) where renderSQL = renderQuery
132+
133+{- |
134+The top level `Query_` type is parameterized by a @schemas@ `SchemasType`,
135+against which the query is type-checked, an input @parameters@ Haskell `Type`,
136+and an ouput row Haskell `Type`.
137+
138+A top-level query can be run
139+using `Squeal.PostgreSQL.PQ.runQueryParams`, or if @parameters = ()@
140+using `Squeal.PostgreSQL.PQ.runQuery`.
141+
142+Generally, @parameters@ will be a Haskell tuple or record whose entries
143+may be referenced using positional
144+`Squeal.PostgreSQL.Expression.Parameter.parameter`s and @row@ will be a
145+Haskell record, whose entries will be targeted using overloaded labels.
146+
147+Let's see some examples of queries.
148+
149+>>> :set -XDeriveAnyClass -XDerivingStrategies
150+>>> :{
151+data Row a b = Row { col1 :: a, col2 :: b }
152+ deriving stock (GHC.Generic)
153+ deriving anyclass (SOP.Generic, SOP.HasDatatypeInfo)
154+:}
143155
144156simple query:
145157
@@ -147,7 +159,7 @@ simple query:
147159>>> type Schema = '["tab" ::: 'Table ('[] :=> Columns)]
148160>>> :{
149161let
150− query :: Query (DBof (Public Schema)) '[] '["col1" ::: 'NotNull 'PGint4, "col2" ::: 'NotNull 'PGint4]
162+ query :: Query_ (Public Schema) () (Row Int32 Int32)
151163 query = select Star (from (table #tab))
152164in printSQL query
153165:}
@@ -157,21 +169,21 @@ restricted query:
157169
158170>>> :{
159171let
160− query :: Query (DBof (Public Schema)) '[] '["sum" ::: 'NotNull 'PGint4, "col1" ::: 'NotNull 'PGint4]
172+ query :: Query_ (Public Schema) () (Row Int32 Int32)
161173 query =
162− select_ ((#col1 + #col2) `as` #sum :* #col1)
174+ select_ ((#col1 + #col2) `as` #col1 :* #col1 `as` #col2)
163175 ( from (table #tab)
164176 & where_ (#col1 .> #col2)
165177 & where_ (#col2 .> 0) )
166178in printSQL query
167179:}
168−SELECT ("col1" + "col2") AS "sum", "col1" AS "col1" FROM "tab" AS "tab" WHERE (("col1" > "col2") AND ("col2" > 0))
180+SELECT ("col1" + "col2") AS "col1", "col1" AS "col2" FROM "tab" AS "tab" WHERE (("col1" > "col2") AND ("col2" > 0))
169181
170182subquery:
171183
172184>>> :{
173185let
174− query :: Query (DBof (Public Schema)) '[] '["col1" ::: 'NotNull 'PGint4, "col2" ::: 'NotNull 'PGint4]
186+ query :: Query_ (Public Schema) () (Row Int32 Int32)
175187 query = select Star (from (subquery (select Star (from (table #tab)) `as` #sub)))
176188in printSQL query
177189:}
@@ -181,7 +193,7 @@ limits and offsets:
181193
182194>>> :{
183195let
184− query :: Query (DBof (Public Schema)) '[] '["col1" ::: 'NotNull 'PGint4, "col2" ::: 'NotNull 'PGint4]
196+ query :: Query_ (Public Schema) () (Row Int32 Int32)
185197 query = select Star (from (table #tab) & limit 100 & offset 2 & limit 50 & offset 2)
186198in printSQL query
187199:}
@@ -191,7 +203,7 @@ parameterized query:
191203
192204>>> :{
193205let
194− query :: Query (DBof (Public Schema)) '[ 'NotNull 'PGint4] '["col1" ::: 'NotNull 'PGint4, "col2" ::: 'NotNull 'PGint4]
206+ query :: Query_ (Public Schema) (Only Int32) (Row Int32 Int32)
195207 query = select Star (from (table #tab) & where_ (#col1 .> param @1))
196208in printSQL query
197209:}
@@ -201,21 +213,21 @@ aggregation query:
201213
202214>>> :{
203215let
204− query :: Query (DBof (Public Schema)) '[] '["sum" ::: 'NotNull 'PGint4, "col1" ::: 'NotNull 'PGint4 ]
216+ query :: Query_ (Public Schema) () (Row Int64 Int32)
205217 query =
206− select_ (sum_ #col2 `as` #sum :* #col1)
218+ select_ ((fromNull 0 (sum_ (All #col2))) `as` #col1 :* #col1 `as` #col2)
207219 ( from (table (#tab `as` #table1))
208220 & groupBy #col1
209− & having (#col1 + sum_ #col2 .> 1) )
221+ & having (sum_ (Distinct #col2) .> 1) )
210222in printSQL query
211223:}
212−SELECT sum("col2") AS "sum", "col1" AS "col1" FROM "tab" AS "table1" GROUP BY "col1" HAVING (("col1" + sum("col2")) > 1)
224+SELECT COALESCE(sum(ALL "col2"), 0) AS "col1", "col1" AS "col2" FROM "tab" AS "table1" GROUP BY "col1" HAVING (sum(DISTINCT "col2") > 1)
213225
214226sorted query:
215227
216228>>> :{
217229let
218− query :: Query (DBof (Public Schema)) '[] '["col1" ::: 'NotNull 'PGint4, "col2" ::: 'NotNull 'PGint4]
230+ query :: Query_ (Public Schema) () (Row Int32 Int32)
219231 query = select Star (from (table #tab) & orderBy [#col1 & Asc])
220232in printSQL query
221233:}
@@ -223,14 +235,12 @@ SELECT * FROM "tab" AS "tab" ORDER BY "col1" ASC
223235
224236joins:
225237
226−>>> :set -XFlexibleContexts
227238>>> :{
228239type OrdersColumns =
229240 '[ "id" ::: 'NoDef :=> 'NotNull 'PGint4
230− , "price" ::: 'NoDef :=> 'NotNull 'PGfloat4
231− , "customer_id" ::: 'NoDef :=> 'NotNull 'PGint4
232− , "shipper_id" ::: 'NoDef :=> 'NotNull 'PGint4
233− ]
241+ , "price" ::: 'NoDef :=> 'NotNull 'PGfloat4
242+ , "customer_id" ::: 'NoDef :=> 'NotNull 'PGint4
243+ , "shipper_id" ::: 'NoDef :=> 'NotNull 'PGint4 ]
234244:}
235245
236246>>> :{
@@ -246,22 +256,27 @@ type OrdersConstraints =
246256>>> :{
247257type OrdersSchema =
248258 '[ "orders" ::: 'Table (OrdersConstraints :=> OrdersColumns)
249− , "customers" ::: 'Table (CustomersConstraints :=> NamesColumns)
250− , "shippers" ::: 'Table (ShippersConstraints :=> NamesColumns) ]
259+ , "customers" ::: 'Table (CustomersConstraints :=> NamesColumns)
260+ , "shippers" ::: 'Table (ShippersConstraints :=> NamesColumns) ]
261+:}
262+
263+>>> :{
264+data Order = Order
265+ { price :: Float
266+ , customerName :: Text
267+ , shipperName :: Text
268+ } deriving GHC.Generic
269+instance SOP.Generic Order
270+instance SOP.HasDatatypeInfo Order
251271:}
252272
253273>>> :{
254274let
255− query :: Query (DBof (Public OrdersSchema))
256− '[]
257− '[ "order_price" ::: 'NotNull 'PGfloat4
258− , "customer_name" ::: 'NotNull 'PGtext
259− , "shipper_name" ::: 'NotNull 'PGtext
260− ]
275+ query :: Query_ (Public OrdersSchema) () Order
261276 query = select_
262− ( #o ! #price `as` #order_price :*
263− #c ! #name `as` #customer_name :*
264− #s ! #name `as` #shipper_name )
277+ ( #o ! #price `as` #price :*
278+ #c ! #name `as` #customerName :*
279+ #s ! #name `as` #shipperName )
265280 ( from (table (#orders `as` #o)
266281 & innerJoin (table (#customers `as` #c))
267282 (#o ! #customer_id .== #c ! #id)
@@ -269,14 +284,16 @@ let
269284 (#o ! #shipper_id .== #s ! #id)) )
270285in printSQL query
271286:}
272−SELECT "o"."price" AS "order_price", "c"."name" AS "customer_name", "s"."name" AS "shipper_name" FROM "orders" AS "o" INNER JOIN "customers" AS "c" ON ("o"."customer_id" = "c"."id") INNER JOIN "shippers" AS "s" ON ("o"."shipper_id" = "s"."id")
287+SELECT "o"."price" AS "price", "c"."name" AS "customerName", "s"."name" AS "shipperName" FROM "orders" AS "o" INNER JOIN "customers" AS "c" ON ("o"."customer_id" = "c"."id") INNER JOIN "shippers" AS "s" ON ("o"."shipper_id" = "s"."id")
273288
274289self-join:
275290
276291>>> :{
277292let
278− query :: Query (DBof (Public Schema)) '[] '["col1" ::: 'NotNull 'PGint4, "col2" ::: 'NotNull 'PGint4]
279− query = select (#t1 & DotStar) (from (table (#tab `as` #t1) & crossJoin (table (#tab `as` #t2))))
293+ query :: Query_ (Public Schema) () (Row Int32 Int32)
294+ query = select
295+ (#t1 & DotStar)
296+ (from (table (#tab `as` #t1) & crossJoin (table (#tab `as` #t2))))
280297in printSQL query
281298:}
282299SELECT "t1".* FROM "tab" AS "t1" CROSS JOIN "tab" AS "t2"
@@ -285,17 +302,19 @@ value queries:
285302
286303>>> :{
287304let
288− query :: Query db '[] '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
289− query = values (1 `as` #foo :* true `as` #bar) [2 `as` #foo :* false `as` #bar]
305+ query :: Query_ schemas () (Row String Bool)
306+ query = values
307+ ("true" `as` #col1 :* true `as` #col2)
308+ ["false" `as` #col1 :* false `as` #col2]
290309in printSQL query
291310:}
292−SELECT * FROM (VALUES (1, TRUE), (2, FALSE)) AS t ("foo", "bar")
311+SELECT * FROM (VALUES (E'true', TRUE), (E'false', FALSE)) AS t ("col1", "col2")
293312
294313set operations:
295314
296315>>> :{
297316let
298− query :: Query (DBof (Public Schema)) '[] '["col1" ::: 'NotNull 'PGint4, "col2" ::: 'NotNull 'PGint4]
317+ query :: Query_ (Public Schema) () (Row Int32 Int32)
299318 query = select Star (from (table #tab)) `unionAll` select Star (from (table #tab))
300319in printSQL query
301320:}
@@ -305,7 +324,7 @@ with queries:
305324
306325>>> :{
307326let
308− query :: Query (DBof (Public Schema)) '[] '["col1" ::: 'NotNull 'PGint4, "col2" ::: 'NotNull 'PGint4]
327+ query :: Query_ (Public Schema) () (Row Int32 Int32)
309328 query = with (
310329 select Star (from (table #tab)) `as` #cte1 :>>
311330 select Star (from (common #cte1)) `as` #cte2
@@ -313,133 +332,195 @@ let
313332in printSQL query
314333:}
315334WITH "cte1" AS (SELECT * FROM "tab" AS "tab"), "cte2" AS (SELECT * FROM "cte1" AS "cte1") SELECT * FROM "cte2" AS "cte2"
335+
336+window function queries
337+
338+>>> :{
339+let
340+ query :: Query_ (Public Schema) () (Row Int32 Int64)
341+ query = select
342+ (#col1 & Also (rank `as` #col2 `Over` (partitionBy #col1 & orderBy [#col2 & Asc])))
343+ (from (table #tab))
344+in printSQL query
345+:}
346+SELECT "col1" AS "col1", rank() OVER (PARTITION BY "col1" ORDER BY "col2" ASC) AS "col2" FROM "tab" AS "tab"
347+
348+correlated subqueries
349+
350+>>> :{
351+let
352+ query :: Query_ (Public Schema) () (Only Int32)
353+ query =
354+ select (#col1 `as` #fromOnly) (from (table (#tab `as` #t1))
355+ & where_ (exists (
356+ select Star (from (table (#tab `as` #t2))
357+ & where_ (#t2 ! #col2 .== #t1 ! #col1)))))
358+in printSQL query
359+:}
360+SELECT "col1" AS "fromOnly" FROM "tab" AS "t1" WHERE EXISTS (SELECT * FROM "tab" AS "t2" WHERE ("t2"."col2" = "t1"."col1"))
361+
316362-}
317−newtype Query
318− (db :: DBType)
319− (params :: [NullityType])
320− (columns :: RowType)
321− = UnsafeQuery { renderQuery :: ByteString }
322− deriving (GHC.Generic,Show,Eq,Ord,NFData)
323−instance RenderSQL (Query db params columns) where renderSQL = renderQuery
363+type family Query_
364+ (schemas :: SchemasType)
365+ (parameters :: Type)
366+ (row :: Type) where
367+ Query_ schemas params row =
368+ Query '[] '[] schemas (TuplePG params) (RowPG row)
324369
325370-- | The results of two queries can be combined using the set operation
326371-- `union`. Duplicate rows are eliminated.
327372union
328− :: Query db params columns
329− -> Query db params columns
330− -> Query db params columns
373+ :: Query outer commons schemas params columns
374+ -> Query outer commons schemas params columns
375+ -> Query outer commons schemas params columns
331376q1 `union` q2 = UnsafeQuery $
332− parenthesized (renderQuery q1)
377+ parenthesized (renderSQL q1)
333378 <+> "UNION"
334− <+> parenthesized (renderQuery q2)
379+ <+> parenthesized (renderSQL q2)
335380
336381-- | The results of two queries can be combined using the set operation
337382-- `unionAll`, the disjoint union. Duplicate rows are retained.
338383unionAll
339− :: Query db params columns
340− -> Query db params columns
341− -> Query db params columns
384+ :: Query outer commons schemas params columns
385+ -> Query outer commons schemas params columns
386+ -> Query outer commons schemas params columns
342387q1 `unionAll` q2 = UnsafeQuery $
343− parenthesized (renderQuery q1)
388+ parenthesized (renderSQL q1)
344389 <+> "UNION" <+> "ALL"
345− <+> parenthesized (renderQuery q2)
390+ <+> parenthesized (renderSQL q2)
346391
347392-- | The results of two queries can be combined using the set operation
348393-- `intersect`, the intersection. Duplicate rows are eliminated.
349394intersect
350− :: Query db params columns
351− -> Query db params columns
352− -> Query db params columns
395+ :: Query outer commons schemas params columns
396+ -> Query outer commons schemas params columns
397+ -> Query outer commons schemas params columns
353398q1 `intersect` q2 = UnsafeQuery $
354− parenthesized (renderQuery q1)
399+ parenthesized (renderSQL q1)
355400 <+> "INTERSECT"
356− <+> parenthesized (renderQuery q2)
401+ <+> parenthesized (renderSQL q2)
357402
358403-- | The results of two queries can be combined using the set operation
359404-- `intersectAll`, the intersection. Duplicate rows are retained.
360405intersectAll
361− :: Query db params columns
362− -> Query db params columns
363− -> Query db params columns
406+ :: Query outer commons schemas params columns
407+ -> Query outer commons schemas params columns
408+ -> Query outer commons schemas params columns
364409q1 `intersectAll` q2 = UnsafeQuery $
365− parenthesized (renderQuery q1)
410+ parenthesized (renderSQL q1)
366411 <+> "INTERSECT" <+> "ALL"
367− <+> parenthesized (renderQuery q2)
412+ <+> parenthesized (renderSQL q2)
368413
369414-- | The results of two queries can be combined using the set operation
370415-- `except`, the set difference. Duplicate rows are eliminated.
371416except
372− :: Query db params columns
373− -> Query db params columns
374− -> Query db params columns
417+ :: Query outer commons schemas params columns
418+ -> Query outer commons schemas params columns
419+ -> Query outer commons schemas params columns
375420q1 `except` q2 = UnsafeQuery $
376− parenthesized (renderQuery q1)
421+ parenthesized (renderSQL q1)
377422 <+> "EXCEPT"
378− <+> parenthesized (renderQuery q2)
423+ <+> parenthesized (renderSQL q2)
379424
380425-- | The results of two queries can be combined using the set operation
381426-- `exceptAll`, the set difference. Duplicate rows are retained.
382427exceptAll
383− :: Query db params columns
384− -> Query db params columns
385− -> Query db params columns
428+ :: Query outer commons schemas params columns
429+ -> Query outer commons schemas params columns
430+ -> Query outer commons schemas params columns
386431q1 `exceptAll` q2 = UnsafeQuery $
387− parenthesized (renderQuery q1)
432+ parenthesized (renderSQL q1)
388433 <+> "EXCEPT" <+> "ALL"
389− <+> parenthesized (renderQuery q2)
434+ <+> parenthesized (renderSQL q2)
390435
391436{-----------------------------------------
392437SELECT queries
393438-----------------------------------------}
394439
395−data Selection db params grp from row where
396− List
397− :: SListI row
398− => NP (Aliased (Expression db params grp from)) row
399− -> Selection db params grp from row
440+{- | The simplest kinds of `Selection` are `Star` and `DotStar` which
441+emits all columns that a `TableExpression` produces. A select `List`
442+is a list of `Expression`s. A `Selection` could be a list of
443+`WindowFunction`s `Over` `WindowDefinition`. `Additional` `Selection`s can
444+be selected with `Also`.
445+-}
446+data Selection outer commons grp schemas params from row where
400447 Star
401448 :: HasUnique tab from row
402− => Selection db params 'Ungrouped from row
449+ => Selection outer commons 'Ungrouped schemas params from row
450+ -- ^ `HasUnique` table in the `FromClause`
403451 DotStar
404452 :: Has tab from row
405453 => Alias tab
406− -> Selection db params 'Ungrouped from row
454+ -- ^ `Has` table with `Alias`
455+ -> Selection outer commons 'Ungrouped schemas params from row
456+ List
457+ :: SListI row
458+ => NP (Aliased (Expression outer commons grp schemas params from)) row
459+ -- ^ `NP` list of `Aliased` `Expression`s
460+ -> Selection outer commons grp schemas params from row
461+ Over
462+ :: SListI row
463+ => NP (Aliased (WindowFunction outer commons grp schemas params from)) row
464+ -- ^ `NP` list of `Aliased` `WindowFunction`s
465+ -> WindowDefinition outer commons grp schemas params from
466+ -> Selection outer commons grp schemas params from row
407467 Also
408− :: Selection db params grp from right
409− -> Selection db params grp from left
410− -> Selection db params grp from (Join left right)
468+ :: Selection outer commons grp schemas params from right
469+ -- ^ `Additional` `Selection`
470+ -> Selection outer commons grp schemas params from left
471+ -> Selection outer commons grp schemas params from (Join left right)
472+instance Additional (Selection outer commons grp schemas params from) where
473+ also = Also
411474instance (KnownSymbol col, row ~ '[col ::: ty])
412475 => Aliasable col
413− (Expression db params grp from ty)
414− (Selection db params grp from row) where
476+ (Expression outer commons grp schemas params from ty)
477+ (Selection outer commons grp schemas params from row) where
415478 expr `as` col = List (expr `as` col)
416−instance (Has tab from row0, Has col row0 ty, row1 ~ '[col ::: ty])
417− => IsQualified tab col (Selection db params 'Ungrouped from row1) where
418− tab ! col = tab ! col `as` col
479+instance (Has tab (Join outer from) row0, Has col row0 ty, row1 ~ '[col ::: ty])
480+ => IsQualified tab col
481+ (Selection outer commons 'Ungrouped schemas params from row1) where
482+ tab ! col = tab ! col `as` col
419483instance
420− ( Has tab from row0
484+ ( Has tab (Join outer from) row0
421485 , Has col row0 ty
422486 , row1 ~ '[col ::: ty]
423487 , GroupedBy tab col bys )
424− => IsQualified tab col (Selection db params ('Grouped bys) from row1) where
425− tab ! col = tab ! col `as` col
426−instance (HasUnique tab from row0, Has col row0 ty, row1 ~ '[col ::: ty])
427− => IsLabel col (Selection db params 'Ungrouped from row1) where
428− fromLabel = fromLabel @col `as` Alias
488+ => IsQualified tab col
489+ (Selection outer commons ('Grouped bys) schemas params from row1) where
490+ tab ! col = tab ! col `as` col
491+instance (HasUnique tab (Join outer from) row0, Has col row0 ty, row1 ~ '[col ::: ty])
492+ => IsLabel col
493+ (Selection outer commons 'Ungrouped schemas params from row1) where
494+ fromLabel = fromLabel @col `as` Alias
429495instance
430− ( HasUnique tab from row0
496+ ( HasUnique tab (Join outer from) row0
431497 , Has col row0 ty
432498 , row1 ~ '[col ::: ty]
433499 , GroupedBy tab col bys )
434− => IsLabel col (Selection db params ('Grouped bys) from row1) where
435− fromLabel = fromLabel @col `as` Alias
500+ => IsLabel col
501+ (Selection outer commons ('Grouped bys) schemas params from row1) where
502+ fromLabel = fromLabel @col `as` Alias
436503
437−instance RenderSQL (Selection db params grp from row) where
504+instance RenderSQL (Selection outer commons grp schemas params from row) where
438505 renderSQL = \case
439506 List list -> renderCommaSeparated (renderAliased renderSQL) list
440507 Star -> "*"
441508 DotStar tab -> renderSQL tab <> ".*"
442509 Also right left -> renderSQL left <> ", " <> renderSQL right
510+ Over winFns winDef ->
511+ let
512+ renderOver
513+ :: Aliased (WindowFunction outer commons grp schemas params from) field
514+ -> ByteString
515+ renderOver (winFn `As` col) = renderSQL winFn
516+ <+> "OVER" <+> parenthesized (renderSQL winDef)
517+ <+> "AS" <+> renderSQL col
518+ in
519+ renderCommaSeparated renderOver winFns
520+
521+instance IsString
522+ (Selection outer commons grp schemas params from '["fromOnly" ::: 'NotNull 'PGtext]) where
523+ fromString str = fromString str `as` Alias
443524
444525-- | the `TableExpression` in the `select` command constructs an intermediate
445526-- virtual table by possibly combining tables, views, eliminating rows,
@@ -448,45 +529,100 @@ instance RenderSQL (Selection db params grp from row) where
448529-- the intermediate table are actually output.
449530select
450531 :: (SListI row, row ~ (x ': xs))
451− => Selection db params grp from row
452− -- ^ select list
453− -> TableExpression db params grp from
532+ => Selection outer commons grp schemas params from row
533+ -- ^ selection
534+ -> TableExpression outer commons grp schemas params from
454535 -- ^ intermediate virtual table
455− -> Query db params row
536+ -> Query outer commons schemas params row
456537select selection tabexpr = UnsafeQuery $
457538 "SELECT"
458539 <+> renderSQL selection
459− <+> renderTableExpression tabexpr
540+ <+> renderSQL tabexpr
460541
542+-- | Like `select` but takes an `NP` list of `Expression`s instead
543+-- of a general `Selection`.
461544select_
462545 :: (SListI row, row ~ (x ': xs))
463− => NP (Aliased (Expression db params grp from)) row
464− -> TableExpression db params grp from
465− -> Query db params row
466−select_ list = select (List list)
546+ => NP (Aliased (Expression outer commons grp schemas params from)) row
547+ -- ^ select list
548+ -> TableExpression outer commons grp schemas params from
549+ -- ^ intermediate virtual table
550+ -> Query outer commons schemas params row
551+select_ = select . List
467552
468553-- | After the select list has been processed, the result table can
469554-- be subject to the elimination of duplicate rows using `selectDistinct`.
470555selectDistinct
471556 :: (SListI columns, columns ~ (col ': cols))
472− => Selection db params 'Ungrouped from columns
473− -- ^ select list
474− -> TableExpression db params 'Ungrouped from
557+ => Selection outer commons grp schemas params from columns
558+ -- ^ selection
559+ -> TableExpression outer commons grp schemas params from
475560 -- ^ intermediate virtual table
476− -> Query db params columns
561+ -> Query outer commons schemas params columns
477562selectDistinct selection tabexpr = UnsafeQuery $
478563 "SELECT DISTINCT"
479564 <+> renderSQL selection
480− <+> renderTableExpression tabexpr
565+ <+> renderSQL tabexpr
481566
567+-- | Like `selectDistinct` but takes an `NP` list of `Expression`s instead
568+-- of a general `Selection`.
482569selectDistinct_
483570 :: (SListI columns, columns ~ (col ': cols))
484− => NP (Aliased (Expression db params 'Ungrouped from)) columns
571+ => NP (Aliased (Expression outer commons grp schemas params from)) columns
485572 -- ^ select list
486− -> TableExpression db params 'Ungrouped from
573+ -> TableExpression outer commons grp schemas params from
487574 -- ^ intermediate virtual table
488− -> Query db params columns
489−selectDistinct_ list = select (List list)
575+ -> Query outer commons schemas params columns
576+selectDistinct_ = selectDistinct . List
577+
578+{-|
579+`selectDistinctOn` keeps only the first row of each set of rows where
580+the given expressions evaluate to equal. The DISTINCT ON expressions are
581+interpreted using the same rules as for ORDER BY. ORDER BY is used to
582+ensure that the desired row appears first.
583+
584+The DISTINCT ON expression(s) must match the leftmost ORDER BY expression(s).
585+The ORDER BY clause will normally contain additional expression(s) that
586+determine the desired precedence of rows within each DISTINCT ON group.
587+
588+In order to guarantee they match and reduce redundancy, this function
589+will prepend the The DISTINCT ON expressions to the ORDER BY clause.
590+-}
591+selectDistinctOn
592+ :: (SListI columns, columns ~ (col ': cols))
593+ => [SortExpression outer commons grp schemas params from]
594+ -- ^ DISTINCT ON expression(s) and prepended to ORDER BY clause
595+ -> Selection outer commons grp schemas params from columns
596+ -- ^ selection
597+ -> TableExpression outer commons grp schemas params from
598+ -- ^ intermediate virtual table
599+ -> Query outer commons schemas params columns
600+selectDistinctOn distincts selection tab = UnsafeQuery $
601+ "SELECT DISTINCT ON"
602+ <+> parenthesized (commaSeparated (renderDistinctOn <$> distincts))
603+ <+> renderSQL selection
604+ <+> renderSQL (tab {orderByClause = distincts <> orderByClause tab})
605+ where
606+ renderDistinctOn = \case
607+ Asc expression -> renderSQL expression
608+ Desc expression -> renderSQL expression
609+ AscNullsFirst expression -> renderSQL expression
610+ DescNullsFirst expression -> renderSQL expression
611+ AscNullsLast expression -> renderSQL expression
612+ DescNullsLast expression -> renderSQL expression
613+
614+-- | Like `selectDistinctOn` but takes an `NP` list of `Expression`s instead
615+-- of a general `Selection`.
616+selectDistinctOn_
617+ :: (SListI columns, columns ~ (col ': cols))
618+ => [SortExpression outer commons grp schemas params from]
619+ -- ^ distinct on and return the first row in ordering
620+ -> NP (Aliased (Expression outer commons grp schemas params from)) columns
621+ -- ^ selection
622+ -> TableExpression outer commons grp schemas params from
623+ -- ^ intermediate virtual table
624+ -> Query outer commons schemas params columns
625+selectDistinctOn_ distincts = selectDistinctOn distincts . List
490626
491627-- | `values` computes a row value or set of row values
492628-- specified by value expressions. It is most commonly used
@@ -494,16 +630,16 @@ selectDistinct_ list = select (List list)
494630-- but it can be used on its own.
495631--
496632-- >>> type Row = '["a" ::: 'NotNull 'PGint4, "b" ::: 'NotNull 'PGtext]
497−-- >>> let query = values (1 `as` #a :* "one" `as` #b) [] :: Query db '[] Row
633+-- >>> let query = values (1 `as` #a :* "one" `as` #b) [] :: Query outer commons schemas '[] Row
498634-- >>> printSQL query
499635-- SELECT * FROM (VALUES (1, E'one')) AS t ("a", "b")
500636values
501637 :: SListI cols
502− => NP (Aliased (Expression db params 'Ungrouped '[] )) cols
503− -> [NP (Aliased (Expression db params 'Ungrouped '[] )) cols]
638+ => NP (Aliased (Expression outer commons 'Ungrouped schemas params '[] )) cols
639+ -> [NP (Aliased (Expression outer commons 'Ungrouped schemas params '[] )) cols]
504640 -- ^ When more than one row is specified, all the rows must
505641 -- must have the same number of elements
506− -> Query db params cols
642+ -> Query outer commons schemas params cols
507643values rw rws = UnsafeQuery $ "SELECT * FROM"
508644 <+> parenthesized (
509645 "VALUES"
@@ -511,20 +647,20 @@ values rw rws = UnsafeQuery $ "SELECT * FROM"
511647 ( parenthesized
512648 . renderCommaSeparated renderValuePart <$> rw:rws )
513649 ) <+> "AS t"
514− <+> parenthesized (renderCommaSeparated renderSQLPart rw)
650+ <+> parenthesized (renderCommaSeparated renderAliasPart rw)
515651 where
516− renderSQLPart, renderValuePart
517− :: Aliased (Expression db params 'Ungrouped '[] ) ty -> ByteString
518− renderSQLPart (_ `As` name) = renderSQL name
652+ renderAliasPart, renderValuePart
653+ :: Aliased (Expression outer commons 'Ungrouped schemas params '[] ) ty -> ByteString
654+ renderAliasPart (_ `As` name) = renderSQL name
519655 renderValuePart (value `As` _) = renderSQL value
520656
521657-- | `values_` computes a row value or set of row values
522658-- specified by value expressions.
523659values_
524660 :: SListI cols
525− => NP (Aliased (Expression db params 'Ungrouped '[] )) cols
661+ => NP (Aliased (Expression outer commons 'Ungrouped schemas params '[] )) cols
526662 -- ^ one row of values
527− -> Query db params cols
663+ -> Query outer commons schemas params cols
528664values_ rw = values rw []
529665
530666{-----------------------------------------
@@ -538,15 +674,17 @@ Table Expressions
538674-- to a table on disk, a so-called base table, but more complex expressions
539675-- can be used to modify or combine base tables in various ways.
540676data TableExpression
541− (db :: DBType)
542− (params :: [NullityType])
677+ (outer :: FromType)
678+ (commons :: FromType)
543679 (grp :: Grouping)
680+ (schemas :: SchemasType)
681+ (params :: [NullityType])
544682 (from :: FromType)
545683 = TableExpression
546− { fromClause :: FromClause db params from
684+ { fromClause :: FromClause outer commons schemas params from
547685 -- ^ A table reference that can be a table name, or a derived table such
548686 -- as a subquery, a @JOIN@ construct, or complex combinations of these.
549− , whereClause :: [Condition db params 'Ungrouped from]
687+ , whereClause :: [Condition outer commons 'Ungrouped schemas params from]
550688 -- ^ optional search coditions, combined with `.&&`. After the processing
551689 -- of the `fromClause` is done, each row of the derived virtual table
552690 -- is checked against the search condition. If the result of the
@@ -562,13 +700,13 @@ data TableExpression
562700 -- set of rows having common values into one group row that represents all
563701 -- rows in the group. This is done to eliminate redundancy in the output
564702 -- and/or compute aggregates that apply to these groups.
565− , havingClause :: HavingClause db params grp from
703+ , havingClause :: HavingClause outer commons grp schemas params from
566704 -- ^ If a table has been grouped using `groupBy`, but only certain groups
567705 -- are of interest, the `havingClause` can be used, much like a
568706 -- `whereClause`, to eliminate groups from the result. Expressions in the
569707 -- `havingClause` can refer both to grouped expressions and to ungrouped
570708 -- expressions (which necessarily involve an aggregate function).
571− , orderByClause :: [SortExpression db params grp from]
709+ , orderByClause :: [SortExpression outer commons grp schemas params from]
572710 -- ^ The `orderByClause` is for optional sorting. When more than one
573711 -- `SortExpression` is specified, the later (right) values are used to sort
574712 -- rows that are equal according to the earlier (left) values.
@@ -578,72 +716,69 @@ data TableExpression
578716 -- will be returned (but possibly fewer, if the query itself yields
579717 -- fewer rows).
580718 , offsetClause :: [Word64]
581− -- ^ The `offsetClause` is combined with `+` to give an offset count
719+ -- ^ The `offsetClause` is combined with `Prelude.+` to give an offset count
582720 -- if nonempty. The offset count says to skip that many rows before
583721 -- beginning to return rows. The rows are skipped before the limit count
584722 -- is applied.
585− }
723+ } deriving (GHC.Generic)
586724
587725-- | Render a `TableExpression`
588−renderTableExpression
589− :: TableExpression db params grp from
590− -> ByteString
591−renderTableExpression
592− (TableExpression frm' whs' grps' hvs' srts' lims' offs') = mconcat
593− [ "FROM ", renderFromClause frm'
594− , renderWheres whs'
595− , renderSQL grps'
596− , renderSQL hvs'
597− , renderOrderByClause srts'
598− , renderLimits lims'
599− , renderOffsets offs'
600− ]
601− where
602− renderWheres = \case
603− [] -> ""
604− wh:[] -> " WHERE" <+> renderSQL wh
605− wh:whs -> " WHERE" <+> renderSQL (foldr (.&&) wh whs)
606− renderOrderByClause = \case
607− [] -> ""
608− srts -> " ORDER BY"
609− <+> commaSeparated (renderSQL <$> srts)
610− renderLimits = \case
611− [] -> ""
612− lims -> " LIMIT" <+> fromString (show (minimum lims))
613− renderOffsets = \case
614− [] -> ""
615− offs -> " OFFSET" <+> fromString (show (sum offs))
726+instance RenderSQL (TableExpression outer commons grp schemas params from) where
727+ renderSQL
728+ (TableExpression frm' whs' grps' hvs' srts' lims' offs') = mconcat
729+ [ "FROM ", renderSQL frm'
730+ , renderWheres whs'
731+ , renderSQL grps'
732+ , renderSQL hvs'
733+ , renderOrderByClause srts'
734+ , renderLimits lims'
735+ , renderOffsets offs' ]
736+ where
737+ renderWheres = \case
738+ [] -> ""
739+ wh:[] -> " WHERE" <+> renderSQL wh
740+ wh:whs -> " WHERE" <+> renderSQL (foldr (.&&) wh whs)
741+ renderOrderByClause = \case
742+ [] -> ""
743+ srts -> " ORDER BY"
744+ <+> commaSeparated (renderSQL <$> srts)
745+ renderLimits = \case
746+ [] -> ""
747+ lims -> " LIMIT" <+> fromString (show (minimum lims))
748+ renderOffsets = \case
749+ [] -> ""
750+ offs -> " OFFSET" <+> fromString (show (sum offs))
616751
617752-- | A `from` generates a `TableExpression` from a table reference that can be
618753-- a table name, or a derived table such as a subquery, a JOIN construct,
619754-- or complex combinations of these. A `from` may be transformed by `where_`,
620−-- `group`, `having`, `orderBy`, `limit` and `offset`, using the `&` operator
755+-- `groupBy`, `having`, `orderBy`, `limit` and `offset`, using the `&` operator
621756-- to match the left-to-right sequencing of their placement in SQL.
622757from
623− :: FromClause db params from -- ^ table reference
624− -> TableExpression db params 'Ungrouped from
625−from rels = TableExpression rels [] NoGroups NoHaving [] [] []
758+ :: FromClause outer commons schemas params from -- ^ table reference
759+ -> TableExpression outer commons 'Ungrouped schemas params from
760+from tab = TableExpression tab [] noGroups NoHaving [] [] []
626761
627762-- | A `where_` is an endomorphism of `TableExpression`s which adds a
628763-- search condition to the `whereClause`.
629764where_
630− :: Condition db params 'Ungrouped from -- ^ filtering condition
631− -> TableExpression db params grp from
632− -> TableExpression db params grp from
765+ :: Condition outer commons 'Ungrouped schemas params from -- ^ filtering condition
766+ -> TableExpression outer commons grp schemas params from
767+ -> TableExpression outer commons grp schemas params from
633768where_ wh rels = rels {whereClause = wh : whereClause rels}
634769
635770-- | A `groupBy` is a transformation of `TableExpression`s which switches
636−-- its `Grouping` from `Ungrouped` to `Grouped`. Use @group Nil@ to perform
771+-- its `Grouping` from `Ungrouped` to `Grouped`. Use @groupBy Nil@ to perform
637772-- a "grand total" aggregation query.
638773groupBy
639774 :: SListI bys
640775 => NP (By from) bys -- ^ grouped columns
641− -> TableExpression db params 'Ungrouped from
642− -> TableExpression db params ('Grouped bys) from
776+ -> TableExpression outer commons 'Ungrouped schemas params from
777+ -> TableExpression outer commons ('Grouped bys) schemas params from
643778groupBy bys rels = TableExpression
644779 { fromClause = fromClause rels
645780 , whereClause = whereClause rels
646− , groupByClause = Group bys
781+ , groupByClause = group bys
647782 , havingClause = Having []
648783 , orderByClause = []
649784 , limitClause = limitClause rels
@@ -653,177 +788,31 @@ groupBy bys rels = TableExpression
653788-- | A `having` is an endomorphism of `TableExpression`s which adds a
654789-- search condition to the `havingClause`.
655790having
656− :: Condition db params ('Grouped bys) from -- ^ having condition
657− -> TableExpression db params ('Grouped bys) from
658− -> TableExpression db params ('Grouped bys) from
791+ :: Condition outer commons ('Grouped bys) schemas params from -- ^ having condition
792+ -> TableExpression outer commons ('Grouped bys) schemas params from
793+ -> TableExpression outer commons ('Grouped bys) schemas params from
659794having hv rels = rels
660795 { havingClause = case havingClause rels of Having hvs -> Having (hv:hvs) }
661796
662−-- | An `orderBy` is an endomorphism of `TableExpression`s which appends an
663−-- ordering to the right of the `orderByClause`.
664−orderBy
665− :: [SortExpression db params grp from] -- ^ sort expressions
666− -> TableExpression db params grp from
667− -> TableExpression db params grp from
668−orderBy srts rels = rels {orderByClause = orderByClause rels ++ srts}
797+instance OrderBy TableExpression where
798+ orderBy srts rels = rels {orderByClause = orderByClause rels ++ srts}
669799
670800-- | A `limit` is an endomorphism of `TableExpression`s which adds to the
671801-- `limitClause`.
672802limit
673803 :: Word64 -- ^ limit parameter
674− -> TableExpression db params grp from
675− -> TableExpression db params grp from
804+ -> TableExpression outer commons grp schemas params from
805+ -> TableExpression outer commons grp schemas params from
676806limit lim rels = rels {limitClause = lim : limitClause rels}
677807
678808-- | An `offset` is an endomorphism of `TableExpression`s which adds to the
679809-- `offsetClause`.
680810offset
681811 :: Word64 -- ^ offset parameter
682− -> TableExpression db params grp from
683− -> TableExpression db params grp from
812+ -> TableExpression outer commons grp schemas params from
813+ -> TableExpression outer commons grp schemas params from
684814offset off rels = rels {offsetClause = off : offsetClause rels}
685815
686−{-----------------------------------------
687−JSON stuff
688−-----------------------------------------}
689−
690−unsafeSetOfFunction
691− :: ByteString
692− -> Expression db params 'Ungrouped '[] ty
693− -> Query db params row
694−unsafeSetOfFunction fun expr = UnsafeQuery $
695− "SELECT * FROM " <> fun <> "(" <> renderSQL expr <> ")"
696−
697−-- | Expands the outermost JSON object into a set of key/value pairs.
698−jsonEach
699− :: Expression db params 'Ungrouped '[] (nullity 'PGjson) -- ^ json object
700− -> Query db params
701− '["key" ::: 'NotNull 'PGtext, "value" ::: 'NotNull 'PGjson]
702−jsonEach = unsafeSetOfFunction "json_each"
703−
704−-- | Expands the outermost binary JSON object into a set of key/value pairs.
705−jsonbEach
706− :: Expression db params 'Ungrouped '[] (nullity 'PGjsonb) -- ^ jsonb object
707− -> Query db params
708− '["key" ::: 'NotNull 'PGtext, "value" ::: 'NotNull 'PGjsonb]
709−jsonbEach = unsafeSetOfFunction "jsonb_each"
710−
711−-- | Expands the outermost JSON object into a set of key/value pairs.
712−jsonEachAsText
713− :: Expression db params 'Ungrouped '[] (nullity 'PGjson) -- ^ json object
714− -> Query db params
715− '["key" ::: 'NotNull 'PGtext, "value" ::: 'NotNull 'PGtext]
716−jsonEachAsText = unsafeSetOfFunction "json_each_text"
717−
718−-- | Expands the outermost binary JSON object into a set of key/value pairs.
719−jsonbEachAsText
720− :: Expression db params 'Ungrouped '[] (nullity 'PGjsonb) -- ^ jsonb object
721− -> Query db params
722− '["key" ::: 'NotNull 'PGtext, "value" ::: 'NotNull 'PGtext]
723−jsonbEachAsText = unsafeSetOfFunction "jsonb_each_text"
724−
725−-- | Returns set of keys in the outermost JSON object.
726−jsonObjectKeys
727− :: Expression db params 'Ungrouped '[] (nullity 'PGjson) -- ^ json object
728− -> Query db params '["json_object_keys" ::: 'NotNull 'PGtext]
729−jsonObjectKeys = unsafeSetOfFunction "json_object_keys"
730−
731−-- | Returns set of keys in the outermost JSON object.
732−jsonbObjectKeys
733− :: Expression db params 'Ungrouped '[] (nullity 'PGjsonb) -- ^ jsonb object
734− -> Query db params '["jsonb_object_keys" ::: 'NotNull 'PGtext]
735−jsonbObjectKeys = unsafeSetOfFunction "jsonb_object_keys"
736−
737−unsafePopulateFunction
738− :: ByteString
739− -> TypeExpression schemas (nullity ('PGcomposite row))
740− -> Expression (commons :=> schemas) params 'Ungrouped '[] ty
741− -> Query (commons :=> schemas) params row
742−unsafePopulateFunction fun ty expr = UnsafeQuery $
743− "SELECT * FROM " <> fun <> "("
744− <> "null::" <> renderSQL ty <> ", "
745− <> renderSQL expr <> ")"
746−
747−-- | Expands the JSON expression to a row whose columns match the record
748−-- type defined by the given table.
749−jsonPopulateRecord
750− :: TypeExpression schemas (nullity ('PGcomposite row)) -- ^ row type
751− -> Expression (commons :=> schemas) params 'Ungrouped '[] (nullity 'PGjson) -- ^ json object
752− -> Query (commons :=> schemas) params row
753−jsonPopulateRecord = unsafePopulateFunction "json_populate_record"
754−
755−-- | Expands the binary JSON expression to a row whose columns match the record
756−-- type defined by the given table.
757−jsonbPopulateRecord
758− :: TypeExpression schemas (nullity ('PGcomposite row)) -- ^ row type
759− -> Expression (commons :=> schemas) params 'Ungrouped '[] (nullity 'PGjsonb) -- ^ jsonb object
760− -> Query (commons :=> schemas) params row
761−jsonbPopulateRecord = unsafePopulateFunction "jsonb_populate_record"
762−
763−-- | Expands the outermost array of objects in the given JSON expression to a
764−-- set of rows whose columns match the record type defined by the given table.
765−jsonPopulateRecordSet
766− :: TypeExpression schemas (nullity ('PGcomposite row)) -- ^ row type
767− -> Expression (commons :=> schemas) params 'Ungrouped '[] (nullity 'PGjson) -- ^ json array
768− -> Query (commons :=> schemas) params row
769−jsonPopulateRecordSet = unsafePopulateFunction "json_populate_record_set"
770−
771−-- | Expands the outermost array of objects in the given binary JSON expression
772−-- to a set of rows whose columns match the record type defined by the given
773−-- table.
774−jsonbPopulateRecordSet
775− :: TypeExpression schemas (nullity ('PGcomposite row)) -- ^ row type
776− -> Expression (commons :=> schemas) params 'Ungrouped '[] (nullity 'PGjsonb) -- ^ jsonb array
777− -> Query (commons :=> schemas) params row
778−jsonbPopulateRecordSet = unsafePopulateFunction "jsonb_populate_record_set"
779−
780−unsafeRecordFunction
781− :: (SListI record, json `In` PGJsonType)
782− => ByteString
783− -> Expression (commons :=> schemas) params 'Ungrouped '[] (nullity json)
784− -> NP (Aliased (TypeExpression schemas)) record
785− -> Query (commons :=> schemas) params record
786−unsafeRecordFunction fun expr types = UnsafeQuery $
787− "SELECT * FROM " <> fun <> "("
788− <> renderSQL expr <> ")"
789− <+> "AS" <+> "x" <> parenthesized (renderCommaSeparated renderTy types)
790− where
791− renderTy :: Aliased (TypeExpression db) ty -> ByteString
792− renderTy (ty `As` alias) =
793− renderSQL alias <+> renderSQL ty
794−
795−-- | Builds an arbitrary record from a JSON object.
796−jsonToRecord
797− :: SListI record
798− => Expression (commons :=> schemas) params 'Ungrouped '[] (nullity 'PGjson) -- ^ json object
799− -> NP (Aliased (TypeExpression schemas)) record -- ^ record types
800− -> Query (commons :=> schemas) params record
801−jsonToRecord = unsafeRecordFunction "json_to_record"
802−
803−-- | Builds an arbitrary record from a binary JSON object.
804−jsonbToRecord
805− :: SListI record
806− => Expression (commons :=> schemas) params 'Ungrouped '[] (nullity 'PGjsonb) -- ^ jsonb object
807− -> NP (Aliased (TypeExpression schemas)) record -- ^ record types
808− -> Query (commons :=> schemas) params record
809−jsonbToRecord = unsafeRecordFunction "jsonb_to_record"
810−
811−-- | Builds an arbitrary set of records from a JSON array of objects.
812−jsonToRecordSet
813− :: SListI record
814− => Expression (commons :=> schemas) params 'Ungrouped '[] (nullity 'PGjson) -- ^ json array
815− -> NP (Aliased (TypeExpression schemas)) record -- ^ record types
816− -> Query (commons :=> schemas) params record
817−jsonToRecordSet = unsafeRecordFunction "json_to_record_set"
818−
819−-- | Builds an arbitrary set of records from a binary JSON array of objects.
820−jsonbToRecordSet
821− :: SListI record
822− => Expression (commons :=> schemas) params 'Ungrouped '[] (nullity 'PGjsonb) -- ^ jsonb array
823− -> NP (Aliased (TypeExpression schemas)) record -- ^ record types
824− -> Query (commons :=> schemas) params record
825−jsonbToRecordSet = unsafeRecordFunction "jsonb_to_record_set"
826−
827816{-----------------------------------------
828817FROM clauses
829818-----------------------------------------}
@@ -832,67 +821,75 @@ FROM clauses
832821A `FromClause` can be a table name, or a derived table such
833822as a subquery, a @JOIN@ construct, or complex combinations of these.
834823-}
835−newtype FromClause db params from
824+newtype FromClause outer commons schemas params from
836825 = UnsafeFromClause { renderFromClause :: ByteString }
837826 deriving (GHC.Generic,Show,Eq,Ord,NFData)
827+instance RenderSQL (FromClause outer commons schemas params from) where
828+ renderSQL = renderFromClause
838829
839830-- | A real `table` is a table from the database.
840831table
841832 :: (Has sch schemas schema, Has tab schema ('Table table))
842833 => Aliased (QualifiedAlias sch) (alias ::: tab)
843− -> FromClause (commons :=> schemas) params '[alias ::: TableToRow table]
834+ -> FromClause outer commons schemas params '[alias ::: TableToRow table]
844835table (tab `As` alias) = UnsafeFromClause $
845836 renderSQL tab <+> "AS" <+> renderSQL alias
846837
847838-- | `subquery` derives a table from a `Query`.
848839subquery
849− :: Aliased (Query db params) query
850− -> FromClause db params '[query]
851−subquery = UnsafeFromClause . renderAliased (parenthesized . renderQuery)
840+ :: Aliased (Query outer commons schemas params) query
841+ -> FromClause outer commons schemas params '[query]
842+subquery = UnsafeFromClause . renderAliased (parenthesized . renderSQL)
852843
853844-- | `view` derives a table from a `View`.
854845view
855846 :: (Has sch schemas schema, Has vw schema ('View view))
856847 => Aliased (QualifiedAlias sch) (alias ::: vw)
857− -> FromClause (commons :=> schemas) params '[alias ::: view]
848+ -> FromClause outer commons schemas params '[alias ::: view]
858849view (vw `As` alias) = UnsafeFromClause $
859850 renderSQL vw <+> "AS" <+> renderSQL alias
860851
852+-- | `common` derives a table from a common table expression.
861853common
862854 :: Has cte commons common
863855 => Aliased Alias (alias ::: cte)
864− -> FromClause (commons :=> schemas) params '[alias ::: common]
856+ -> FromClause outer commons schemas params '[alias ::: common]
865857common (cte `As` alias) = UnsafeFromClause $
866858 renderSQL cte <+> "AS" <+> renderSQL alias
867859
868−{- | @left & crossJoin right@. For every possible combination of rows from
869− @left@ and @right@ (i.e., a Cartesian product), the joined table will contain
870− a row consisting of all columns in @left@ followed by all columns in @right@.
871− If the tables have @n@ and @m@ rows respectively, the joined table will
872− have @n * m@ rows.
860+instance Additional (FromClause outer commons schemas params) where
861+ also right left = UnsafeFromClause $
862+ renderSQL left <> ", " <> renderSQL right
863+
864+{- |
865+@left & crossJoin right@. For every possible combination of rows from
866+@left@ and @right@ (i.e., a Cartesian product), the joined table will contain
867+a row consisting of all columns in @left@ followed by all columns in @right@.
868+If the tables have @n@ and @m@ rows respectively, the joined table will
869+have @n * m@ rows.
873870-}
874871crossJoin
875− :: FromClause db params right
872+ :: FromClause outer commons schemas params right
876873 -- ^ right
877− -> FromClause db params left
874+ -> FromClause outer commons schemas params left
878875 -- ^ left
879− -> FromClause db params (Join left right)
876+ -> FromClause outer commons schemas params (Join left right)
880877crossJoin right left = UnsafeFromClause $
881− renderFromClause left <+> "CROSS JOIN" <+> renderFromClause right
878+ renderSQL left <+> "CROSS JOIN" <+> renderSQL right
882879
883880{- | @left & innerJoin right on@. The joined table is filtered by
884881the @on@ condition.
885882-}
886883innerJoin
887− :: FromClause db params right
884+ :: FromClause outer commons schemas params right
888885 -- ^ right
889− -> Condition db params 'Ungrouped (Join left right)
886+ -> Condition outer commons 'Ungrouped schemas params (Join left right)
890887 -- ^ @on@ condition
891− -> FromClause db params left
888+ -> FromClause outer commons schemas params left
892889 -- ^ left
893− -> FromClause db params (Join left right)
890+ -> FromClause outer commons schemas params (Join left right)
894891innerJoin right on left = UnsafeFromClause $
895− renderFromClause left <+> "INNER JOIN" <+> renderFromClause right
892+ renderSQL left <+> "INNER JOIN" <+> renderSQL right
896893 <+> "ON" <+> renderSQL on
897894
898895{- | @left & leftOuterJoin right on@. First, an inner join is performed.
@@ -901,15 +898,15 @@ innerJoin right on left = UnsafeFromClause $
901898 Thus, the joined table always has at least one row for each row in @left@.
902899-}
903900leftOuterJoin
904− :: FromClause db params right
901+ :: FromClause outer commons schemas params right
905902 -- ^ right
906− -> Condition db params 'Ungrouped (Join left right)
903+ -> Condition outer commons 'Ungrouped schemas params (Join left right)
907904 -- ^ @on@ condition
908− -> FromClause db params left
905+ -> FromClause outer commons schemas params left
909906 -- ^ left
910− -> FromClause db params (Join left (NullifyFrom right))
907+ -> FromClause outer commons schemas params (Join left (NullifyFrom right))
911908leftOuterJoin right on left = UnsafeFromClause $
912− renderFromClause left <+> "LEFT OUTER JOIN" <+> renderFromClause right
909+ renderSQL left <+> "LEFT OUTER JOIN" <+> renderSQL right
913910 <+> "ON" <+> renderSQL on
914911
915912{- | @left & rightOuterJoin right on@. First, an inner join is performed.
@@ -919,15 +916,15 @@ leftOuterJoin right on left = UnsafeFromClause $
919916 have a row for each row in @right@.
920917-}
921918rightOuterJoin
922− :: FromClause db params right
919+ :: FromClause outer commons schemas params right
923920 -- ^ right
924− -> Condition db params 'Ungrouped (Join left right)
921+ -> Condition outer commons 'Ungrouped schemas params (Join left right)
925922 -- ^ @on@ condition
926− -> FromClause db params left
923+ -> FromClause outer commons schemas params left
927924 -- ^ left
928− -> FromClause db params (Join (NullifyFrom left) right)
925+ -> FromClause outer commons schemas params (Join (NullifyFrom left) right)
929926rightOuterJoin right on left = UnsafeFromClause $
930− renderFromClause left <+> "RIGHT OUTER JOIN" <+> renderFromClause right
927+ renderSQL left <+> "RIGHT OUTER JOIN" <+> renderSQL right
931928 <+> "ON" <+> renderSQL on
932929
933930{- | @left & fullOuterJoin right on@. First, an inner join is performed.
@@ -938,23 +935,23 @@ rightOuterJoin right on left = UnsafeFromClause $
938935 is added.
939936-}
940937fullOuterJoin
941− :: FromClause db params right
938+ :: FromClause outer commons schemas params right
942939 -- ^ right
943− -> Condition db params 'Ungrouped (Join left right)
940+ -> Condition outer commons 'Ungrouped schemas params (Join left right)
944941 -- ^ @on@ condition
945− -> FromClause db params left
942+ -> FromClause outer commons schemas params left
946943 -- ^ left
947− -> FromClause db params
944+ -> FromClause outer commons schemas params
948945 (Join (NullifyFrom left) (NullifyFrom right))
949946fullOuterJoin right on left = UnsafeFromClause $
950− renderFromClause left <+> "FULL OUTER JOIN" <+> renderFromClause right
947+ renderSQL left <+> "FULL OUTER JOIN" <+> renderSQL right
951948 <+> "ON" <+> renderSQL on
952949
953950{-----------------------------------------
954951Grouping
955952-----------------------------------------}
956953
957−-- | `By`s are used in `group` to reference a list of columns which are then
954+-- | `By`s are used in `groupBy` to reference a list of columns which are then
958955-- used to group together those rows in a table that have the same values
959956-- in all the columns listed. @By \#col@ will reference an unambiguous
960957-- column @col@; otherwise @By2 (\#tab \! \#col)@ will reference a table
@@ -974,6 +971,10 @@ data By
974971deriving instance Show (By from by)
975972deriving instance Eq (By from by)
976973deriving instance Ord (By from by)
974+instance RenderSQL (By from by) where
975+ renderSQL = \case
976+ By1 column -> renderSQL column
977+ By2 rel column -> renderSQL rel <> "." <> renderSQL column
977978
978979instance (HasUnique rel rels cols, Has col cols ty, by ~ '(rel, col))
979980 => IsLabel col (By rels by) where fromLabel = By1 fromLabel
@@ -985,424 +986,113 @@ instance (Has rel rels cols, Has col cols ty, bys ~ '[ '(rel, col)])
985986 => IsQualified rel col (NP (By rels) bys) where
986987 rel ! col = By2 rel col :* Nil
987988
988−-- | Renders a `By`.
989−renderBy :: By from by -> ByteString
990−renderBy = \case
991− By1 column -> renderSQL column
992− By2 rel column -> renderSQL rel <> "." <> renderSQL column
993−
994989-- | A `GroupByClause` indicates the `Grouping` of a `TableExpression`.
995990-- A `NoGroups` indicates `Ungrouped` while a `Group` indicates `Grouped`.
996991-- @NoGroups@ is distinguised from @Group Nil@ since no aggregation can be
997992-- done on @NoGroups@ while all output `Expression`s must be aggregated
998993-- in @Group Nil@. In general, all output `Expression`s in the
999994-- complement of @bys@ must be aggregated in @Group bys@.
1000−data GroupByClause grp from where
1001− NoGroups :: GroupByClause 'Ungrouped from
1002− Group
1003− :: SListI bys
1004− => NP (By from) bys
1005− -> GroupByClause ('Grouped bys) from
1006−
1007−-- | Renders a `GroupByClause`.
995+newtype GroupByClause grp from = UnsafeGroupByClause
996+ { renderGroupByClause :: ByteString }
997+ deriving (GHC.Generic,Show,Eq,Ord,NFData)
1008998instance RenderSQL (GroupByClause grp from) where
1009− renderSQL = \case
1010− NoGroups -> ""
1011− Group Nil -> ""
1012− Group bys -> " GROUP BY" <+> renderCommaSeparated renderBy bys
999+ renderSQL = renderGroupByClause
1000+noGroups :: GroupByClause 'Ungrouped from
1001+noGroups = UnsafeGroupByClause ""
1002+group
1003+ :: SListI bys
1004+ => NP (By from) bys
1005+ -> GroupByClause ('Grouped bys) from
1006+group bys = UnsafeGroupByClause $ case bys of
1007+ Nil -> ""
1008+ bys' -> " GROUP BY" <+> renderCommaSeparated renderSQL bys'
10131009
10141010-- | A `HavingClause` is used to eliminate groups that are not of interest.
10151011-- An `Ungrouped` `TableExpression` may only use `NoHaving` while a `Grouped`
10161012-- `TableExpression` must use `Having` whose conditions are combined with
10171013-- `.&&`.
1018−data HavingClause db params grp from where
1019− NoHaving :: HavingClause db params 'Ungrouped from
1014+data HavingClause outer commons grp schemas params from where
1015+ NoHaving :: HavingClause outer commons 'Ungrouped schemas params from
10201016 Having
1021− :: [Condition db params ('Grouped bys) from]
1022− -> HavingClause db params ('Grouped bys) from
1023−deriving instance Show (HavingClause db params grp from)
1024−deriving instance Eq (HavingClause db params grp from)
1025−deriving instance Ord (HavingClause db params grp from)
1017+ :: [Condition outer commons ('Grouped bys) schemas params from]
1018+ -> HavingClause outer commons ('Grouped bys) schemas params from
1019+deriving instance Show (HavingClause outer commons grp schemas params from)
1020+deriving instance Eq (HavingClause outer commons grp schemas params from)
1021+deriving instance Ord (HavingClause outer commons grp schemas params from)
10261022
10271023-- | Render a `HavingClause`.
1028−instance RenderSQL (HavingClause db params grp from) where
1024+instance RenderSQL (HavingClause outer commons grp schemas params from) where
10291025 renderSQL = \case
10301026 NoHaving -> ""
10311027 Having [] -> ""
10321028 Having conditions ->
10331029 " HAVING" <+> commaSeparated (renderSQL <$> conditions)
10341030
1035−{-----------------------------------------
1036−Sorting
1037−-----------------------------------------}
1038−
1039−-- | `SortExpression`s are used by `sortBy` to optionally sort the results
1040−-- of a `Query`. `Asc` or `Desc` set the sort direction of a `NotNull` result
1041−-- column to ascending or descending. Ascending order puts smaller values
1042−-- first, where "smaller" is defined in terms of the `.<` operator. Similarly,
1043−-- descending order is determined with the `.>` operator. `AscNullsFirst`,
1044−-- `AscNullsLast`, `DescNullsFirst` and `DescNullsLast` options are used to
1045−-- determine whether nulls appear before or after non-null values in the sort
1046−-- ordering of a `Null` result column.
1047−data SortExpression db params grp from where
1048− Asc
1049− :: Expression db params grp from ('NotNull ty)
1050− -> SortExpression db params grp from
1051− Desc
1052− :: Expression db params grp from ('NotNull ty)
1053− -> SortExpression db params grp from
1054− AscNullsFirst
1055− :: Expression db params grp from ('Null ty)
1056− -> SortExpression db params grp from
1057− AscNullsLast
1058− :: Expression db params grp from ('Null ty)
1059− -> SortExpression db params grp from
1060− DescNullsFirst
1061− :: Expression db params grp from ('Null ty)
1062− -> SortExpression db params grp from
1063− DescNullsLast
1064− :: Expression db params grp from ('Null ty)
1065− -> SortExpression db params grp from
1066−deriving instance Show (SortExpression db params grp from)
1067−
1068−-- | Render a `SortExpression`.
1069−instance RenderSQL (SortExpression db params grp from) where
1070− renderSQL = \case
1071− Asc expression -> renderSQL expression <+> "ASC"
1072− Desc expression -> renderSQL expression <+> "DESC"
1073− AscNullsFirst expression -> renderSQL expression
1074− <+> "ASC NULLS FIRST"
1075− DescNullsFirst expression -> renderSQL expression
1076− <+> "DESC NULLS FIRST"
1077− AscNullsLast expression -> renderSQL expression <+> "ASC NULLS LAST"
1078− DescNullsLast expression -> renderSQL expression <+> "DESC NULLS LAST"
1079−
1080−unsafeSubqueryExpression
1081− :: ByteString
1082− -> Expression db params grp from ty
1083− -> Query db params '[alias ::: ty]
1084− -> Expression db params grp from (nullity 'PGbool)
1085−unsafeSubqueryExpression op x q = UnsafeExpression $
1086− renderSQL x <+> op <+> parenthesized (renderQuery q)
1087−
1088−unsafeRowSubqueryExpression
1089− :: SListI row
1090− => ByteString
1091− -> NP (Aliased (Expression db params grp from)) row
1092− -> Query db params row
1093− -> Expression db params grp from (nullity 'PGbool)
1094−unsafeRowSubqueryExpression op xs q = UnsafeExpression $
1095− renderSQL (row xs) <+> op <+> parenthesized (renderQuery q)
1096−
1097−-- | The right-hand side is a sub`Query`, which must return exactly one column.
1098−-- The left-hand expression is evaluated and compared to each row of the
1099−-- sub`Query` result. The result of `in_` is `true` if any equal subquery row is found.
1100−-- The result is `false` if no equal row is found
1101−-- (including the case where the subquery returns no rows).
1102−--
1103−-- >>> printSQL $ true `in_` values_ (true `as` #foo)
1104−-- TRUE IN (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1105−in_
1106− :: Expression db params grp from ty -- ^ expression
1107− -> Query db params '[alias ::: ty] -- ^ subquery
1108− -> Expression db params grp from (nullity 'PGbool)
1109−in_ = unsafeSubqueryExpression "IN"
1110−
1111−{- | The left-hand side of this form of `rowIn` is a row constructor.
1112−The right-hand side is a sub`Query`,
1113−which must return exactly as many columns as
1114−there are expressions in the left-hand row.
1115−The left-hand expressions are evaluated and compared row-wise to each row
1116−of the subquery result. The result of `rowIn`
1117−is `true` if any equal subquery row is found.
1118−The result is `false` if no equal row is found
1119−(including the case where the subquery returns no rows).
1120−
1121−>>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db params grp from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1122−>>> printSQL $ myRow `rowIn` values_ myRow
1123−ROW(1, FALSE) IN (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1124−-}
1125−rowIn
1126− :: SListI row
1127− => NP (Aliased (Expression db params grp from)) row -- ^ row constructor
1128− -> Query db params row -- ^ subquery
1129− -> Expression db params grp from (nullity 'PGbool)
1130−rowIn = unsafeRowSubqueryExpression "IN"
1131−
1132−-- | >>> printSQL $ true `eqAll` values_ (true `as` #foo)
1133−-- TRUE = ALL (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1134−eqAll
1135− :: Expression db params grp from ty -- ^ expression
1136− -> Query db params '[alias ::: ty] -- ^ subquery
1137− -> Expression db params grp from (nullity 'PGbool)
1138−eqAll = unsafeSubqueryExpression "= ALL"
1139−
1140−-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db params grp from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1141−-- >>> printSQL $ myRow `rowEqAll` values_ myRow
1142−-- ROW(1, FALSE) = ALL (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1143−rowEqAll
1144− :: SListI row
1145− => NP (Aliased (Expression db params grp from)) row -- ^ row constructor
1146− -> Query db params row -- ^ subquery
1147− -> Expression db params grp from (nullity 'PGbool)
1148−rowEqAll = unsafeRowSubqueryExpression "= ALL"
1149−
1150−-- | >>> printSQL $ true `eqAny` values_ (true `as` #foo)
1151−-- TRUE = ANY (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1152−eqAny
1153− :: Expression db params grp from ty -- ^ expression
1154− -> Query db params '[alias ::: ty] -- ^ subquery
1155− -> Expression db params grp from (nullity 'PGbool)
1156−eqAny = unsafeSubqueryExpression "= ANY"
1157−
1158−-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db params grp from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1159−-- >>> printSQL $ myRow `rowEqAny` values_ myRow
1160−-- ROW(1, FALSE) = ANY (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1161−rowEqAny
1162− :: SListI row
1163− => NP (Aliased (Expression db params grp from)) row -- ^ row constructor
1164− -> Query db params row -- ^ subquery
1165− -> Expression db params grp from (nullity 'PGbool)
1166−rowEqAny = unsafeRowSubqueryExpression "= ANY"
1167−
1168−-- | >>> printSQL $ true `neqAll` values_ (true `as` #foo)
1169−-- TRUE <> ALL (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1170−neqAll
1171− :: Expression db params grp from ty -- ^ expression
1172− -> Query db params '[alias ::: ty] -- ^ subquery
1173− -> Expression db params grp from (nullity 'PGbool)
1174−neqAll = unsafeSubqueryExpression "<> ALL"
1175−
1176−-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db params grp from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1177−-- >>> printSQL $ myRow `rowNeqAll` values_ myRow
1178−-- ROW(1, FALSE) <> ALL (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1179−rowNeqAll
1180− :: SListI row
1181− => NP (Aliased (Expression db params grp from)) row -- ^ row constructor
1182− -> Query db params row -- ^ subquery
1183− -> Expression db params grp from (nullity 'PGbool)
1184−rowNeqAll = unsafeRowSubqueryExpression "<> ALL"
1185−
1186−-- | >>> printSQL $ true `neqAny` values_ (true `as` #foo)
1187−-- TRUE <> ANY (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1188−neqAny
1189− :: Expression db params grp from ty -- ^ expression
1190− -> Query db params '[alias ::: ty] -- ^ subquery
1191− -> Expression db params grp from (nullity 'PGbool)
1192−neqAny = unsafeSubqueryExpression "<> ANY"
1193−
1194−-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db params grp from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1195−-- >>> printSQL $ myRow `rowNeqAny` values_ myRow
1196−-- ROW(1, FALSE) <> ANY (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1197−rowNeqAny
1198− :: SListI row
1199− => NP (Aliased (Expression db params grp from)) row -- ^ row constructor
1200− -> Query db params row -- ^ subquery
1201− -> Expression db params grp from (nullity 'PGbool)
1202−rowNeqAny = unsafeRowSubqueryExpression "<> ANY"
1203−
1204−-- | >>> printSQL $ true `allLt` values_ (true `as` #foo)
1205−-- TRUE ALL < (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1206−allLt
1207− :: Expression db params grp from ty -- ^ expression
1208− -> Query db params '[alias ::: ty] -- ^ subquery
1209− -> Expression db params grp from (nullity 'PGbool)
1210−allLt = unsafeSubqueryExpression "ALL <"
1211−
1212−-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db params grp from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1213−-- >>> printSQL $ myRow `rowLtAll` values_ myRow
1214−-- ROW(1, FALSE) ALL < (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1215−rowLtAll
1216− :: SListI row
1217− => NP (Aliased (Expression db params grp from)) row -- ^ row constructor
1218− -> Query db params row -- ^ subquery
1219− -> Expression db params grp from (nullity 'PGbool)
1220−rowLtAll = unsafeRowSubqueryExpression "ALL <"
1221−
1222−-- | >>> printSQL $ true `ltAny` values_ (true `as` #foo)
1223−-- TRUE ANY < (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1224−ltAny
1225− :: Expression db params grp from ty -- ^ expression
1226− -> Query db params '[alias ::: ty] -- ^ subquery
1227− -> Expression db params grp from (nullity 'PGbool)
1228−ltAny = unsafeSubqueryExpression "ANY <"
1229−
1230−-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db params grp from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1231−-- >>> printSQL $ myRow `rowLtAll` values_ myRow
1232−-- ROW(1, FALSE) ALL < (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1233−rowLtAny
1234− :: SListI row
1235− => NP (Aliased (Expression db params grp from)) row -- ^ row constructor
1236− -> Query db params row -- ^ subquery
1237− -> Expression db params grp from (nullity 'PGbool)
1238−rowLtAny = unsafeRowSubqueryExpression "ANY <"
1239−
1240−-- | >>> printSQL $ true `lteAll` values_ (true `as` #foo)
1241−-- TRUE <= ALL (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1242−lteAll
1243− :: Expression db params grp from ty -- ^ expression
1244− -> Query db params '[alias ::: ty] -- ^ subquery
1245− -> Expression db params grp from (nullity 'PGbool)
1246−lteAll = unsafeSubqueryExpression "<= ALL"
1247−
1248−-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db params grp from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1249−-- >>> printSQL $ myRow `rowLteAll` values_ myRow
1250−-- ROW(1, FALSE) <= ALL (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1251−rowLteAll
1252− :: SListI row
1253− => NP (Aliased (Expression db params grp from)) row -- ^ row constructor
1254− -> Query db params row -- ^ subquery
1255− -> Expression db params grp from (nullity 'PGbool)
1256−rowLteAll = unsafeRowSubqueryExpression "<= ALL"
1257−
1258−-- | >>> printSQL $ true `lteAny` values_ (true `as` #foo)
1259−-- TRUE <= ANY (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1260−lteAny
1261− :: Expression db params grp from ty -- ^ expression
1262− -> Query db params '[alias ::: ty] -- ^ subquery
1263− -> Expression db params grp from (nullity 'PGbool)
1264−lteAny = unsafeSubqueryExpression "<= ANY"
1265−
1266−-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db params grp from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1267−-- >>> printSQL $ myRow `rowLteAny` values_ myRow
1268−-- ROW(1, FALSE) <= ANY (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1269−rowLteAny
1270− :: SListI row
1271− => NP (Aliased (Expression db params grp from)) row -- ^ row constructor
1272− -> Query db params row -- ^ subquery
1273− -> Expression db params grp from (nullity 'PGbool)
1274−rowLteAny = unsafeRowSubqueryExpression "<= ANY"
1275−
1276−-- | >>> printSQL $ true `gtAll` values_ (true `as` #foo)
1277−-- TRUE > ALL (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1278−gtAll
1279− :: Expression db params grp from ty -- ^ expression
1280− -> Query db params '[alias ::: ty] -- ^ subquery
1281− -> Expression db params grp from (nullity 'PGbool)
1282−gtAll = unsafeSubqueryExpression "> ALL"
1283−
1284−-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db params grp from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1285−-- >>> printSQL $ myRow `rowGtAll` values_ myRow
1286−-- ROW(1, FALSE) > ALL (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1287−rowGtAll
1288− :: SListI row
1289− => NP (Aliased (Expression db params grp from)) row -- ^ row constructor
1290− -> Query db params row -- ^ subquery
1291− -> Expression db params grp from (nullity 'PGbool)
1292−rowGtAll = unsafeRowSubqueryExpression "> ALL"
1293−
1294−-- | >>> printSQL $ true `gtAny` values_ (true `as` #foo)
1295−-- TRUE > ANY (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1296−gtAny
1297− :: Expression db params grp from ty -- ^ expression
1298− -> Query db params '[alias ::: ty] -- ^ subquery
1299− -> Expression db params grp from (nullity 'PGbool)
1300−gtAny = unsafeSubqueryExpression "> ANY"
1301−
1302−-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db params grp from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1303−-- >>> printSQL $ myRow `rowGtAny` values_ myRow
1304−-- ROW(1, FALSE) > ANY (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1305−rowGtAny
1306− :: SListI row
1307− => NP (Aliased (Expression db params grp from)) row -- ^ row constructor
1308− -> Query db params row -- ^ subquery
1309− -> Expression db params grp from (nullity 'PGbool)
1310−rowGtAny = unsafeRowSubqueryExpression "> ANY"
1311−
1312−-- | >>> printSQL $ true `gteAll` values_ (true `as` #foo)
1313−-- TRUE >= ALL (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1314−gteAll
1315− :: Expression db params grp from ty -- ^ expression
1316− -> Query db params '[alias ::: ty] -- ^ subquery
1317− -> Expression db params grp from (nullity 'PGbool)
1318−gteAll = unsafeSubqueryExpression ">= ALL"
1319−
1320−-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db params grp from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1321−-- >>> printSQL $ myRow `rowGteAll` values_ myRow
1322−-- ROW(1, FALSE) >= ALL (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1323−rowGteAll
1324− :: SListI row
1325− => NP (Aliased (Expression db params grp from)) row -- ^ row constructor
1326− -> Query db params row -- ^ subquery
1327− -> Expression db params grp from (nullity 'PGbool)
1328−rowGteAll = unsafeRowSubqueryExpression ">= ALL"
1329−
1330−-- | >>> printSQL $ true `gteAny` values_ (true `as` #foo)
1331−-- TRUE >= ANY (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1332−gteAny
1333− :: Expression db params grp from ty -- ^ expression
1334− -> Query db params '[alias ::: ty] -- ^ subquery
1335− -> Expression db params grp from (nullity 'PGbool)
1336−gteAny = unsafeSubqueryExpression ">= ANY"
1337−
1338−-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db params grp from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1339−-- >>> printSQL $ myRow `rowGteAny` values_ myRow
1340−-- ROW(1, FALSE) >= ANY (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1341−rowGteAny
1342− :: SListI row
1343− => NP (Aliased (Expression db params grp from)) row -- ^ row constructor
1344− -> Query db params row -- ^ subquery
1345− -> Expression db params grp from (nullity 'PGbool)
1346−rowGteAny = unsafeRowSubqueryExpression ">= ANY"
1347−
13481031-- | A `CommonTableExpression` is an auxiliary statement in a `with` clause.
13491032data CommonTableExpression statement
1033+ (schemas :: SchemasType)
13501034 (params :: [NullityType])
1351− (db0 :: DBType)
1352− (db1 :: DBType) where
1035+ (commons0 :: FromType)
1036+ (commons1 :: FromType) where
13531037 CommonTableExpression
1354− :: Aliased (statement (commons :=> schemas) params) (cte ::: common)
1355− -> CommonTableExpression statement params
1356− (commons :=> schemas) ((cte ::: common ': commons) :=> schemas)
1038+ :: Aliased (statement commons schemas params) (cte ::: common)
1039+ -> CommonTableExpression statement schemas params commons (cte ::: common ': commons)
13571040instance
13581041 ( KnownSymbol cte
1359− , db0 ~ (commons :=> schemas)
1360− , db1 ~ ((cte ::: common ': commons) :=> schemas)
1042+ , commons1 ~ (cte ::: common ': commons)
13611043 ) => Aliasable cte
1362− (statement db0 params common)
1363− (CommonTableExpression statement params db0 db1) where
1044+ (statement commons schemas params common)
1045+ (CommonTableExpression statement schemas params commons commons1) where
13641046 statement `as` cte = CommonTableExpression (statement `as` cte)
13651047instance
13661048 ( KnownSymbol cte
1367− , db0 ~ (commons :=> schemas)
1368− , db1 ~ ((cte ::: common ': commons) :=> schemas)
1049+ , commons1 ~ (cte ::: common ': commons)
13691050 ) => Aliasable cte
1370− (statement db0 params common)
1371− (AlignedList (CommonTableExpression statement params) db0 db1) where
1372− statement `as` cte = single (statement `as` cte)
1373−
1374−-- | render a `CommonTableExpression`.
1375−renderCommonTableExpression
1376− :: (forall db ps row. statement db ps row -> ByteString) -- ^ render statement
1377− -> CommonTableExpression statement params db0 db1 -> ByteString
1378−renderCommonTableExpression renderStatement
1379− (CommonTableExpression (statement `As` alias)) =
1380− renderSQL alias <+> "AS" <+> parenthesized (renderStatement statement)
1381−
1382−-- | render a non-empty `AlignedList` of `CommonTableExpression`s.
1383−renderCommonTableExpressions
1384− :: (forall db ps row. statement db ps row -> ByteString) -- ^ render statement
1385− -> CommonTableExpression statement params db0 db1
1386− -> AlignedList (CommonTableExpression statement params) db1 db2
1387− -> ByteString
1388−renderCommonTableExpressions renderStatement cte ctes =
1389− renderCommonTableExpression renderStatement cte <> case ctes of
1390− Done -> ""
1391− cte' :>> ctes' -> "," <+>
1392− renderCommonTableExpressions renderStatement cte' ctes'
1051+ (statement commons schemas params common)
1052+ (Path (CommonTableExpression statement schemas params) commons commons1) where
1053+ statement `as` cte = csingleton (statement `as` cte)
1054+
1055+instance (forall c s p r. RenderSQL (statement c s p r)) => RenderSQL
1056+ (CommonTableExpression statement schemas params commons0 commons1) where
1057+ renderSQL (CommonTableExpression (statement `As` cte)) =
1058+ renderSQL cte <+> "AS" <+> parenthesized (renderSQL statement)
13931059
13941060-- | `with` provides a way to write auxiliary statements for use in a larger query.
13951061-- These statements, referred to as `CommonTableExpression`s, can be thought of as
13961062-- defining temporary tables that exist just for one query.
13971063class With statement where
13981064 with
1399− :: AlignedList (CommonTableExpression statement params) db0 db1
1065+ :: Path (CommonTableExpression statement schemas params) commons0 commons1
14001066 -- ^ common table expressions
1401− -> statement db1 params row
1067+ -> statement commons1 schemas params row
14021068 -- ^ larger query
1403− -> statement db0 params row
1404−instance With Query where
1069+ -> statement commons0 schemas params row
1070+instance With (Query outer) where
14051071 with Done query = query
1406− with (cte :>> ctes) query = UnsafeQuery $
1407− "WITH" <+> renderCommonTableExpressions renderQuery cte ctes
1408− <+> renderQuery query
1072+ with ctes query = UnsafeQuery $
1073+ "WITH" <+> commaSeparated (ctoList renderSQL ctes) <+> renderSQL query
1074+
1075+{- |
1076+>>> import Data.Monoid (Sum (..))
1077+>>> import Data.Int (Int64)
1078+>>> :{
1079+ let
1080+ query :: Query_ schema () (Sum Int64)
1081+ query = withRecursive
1082+ ( values_ ((1 & astype int) `as` #n)
1083+ `unionAll`
1084+ select_ ((#n + 1) `as` #n)
1085+ (from (common #t) & where_ (#n .< 100)) `as` #t )
1086+ ( select_ (fromNull 0 (sum_ (All #n)) `as` #getSum) (from (common #t) & groupBy Nil))
1087+ in printSQL query
1088+:}
1089+WITH RECURSIVE "t" AS ((SELECT * FROM (VALUES ((1 :: int))) AS t ("n")) UNION ALL (SELECT ("n" + 1) AS "n" FROM "t" AS "t" WHERE ("n" < 100))) SELECT COALESCE(sum(ALL "n"), 0) AS "getSum" FROM "t" AS "t"
1090+-}
1091+withRecursive
1092+ :: Aliased (Query outer (recursive ': commons) schemas params) recursive
1093+ -> Query outer (recursive ': commons) schemas params row
1094+ -> Query outer commons schemas params row
1095+withRecursive (recursive `As` cte) query = UnsafeQuery $
1096+ "WITH RECURSIVE" <+> renderSQL cte
1097+ <+> "AS" <+> parenthesized (renderSQL recursive)
1098+ <+> renderSQL query