@@ -1,7 +1,7 @@
2Module: Squeal.PostgreSQL.Query
2Module: Squeal.PostgreSQL.Query
3Description: Squeal queries
3Description: Squeal queries
4−Copyright: (c) Eitan Chatav, 2017
4+Copyright: (c) Eitan Chatav, 2019
5Maintainer: eitan@morphism.tech
5Maintainer: eitan@morphism.tech
6Stability: experimental
6Stability: experimental
@@ -17,7 +17,9 @@ Squeal queries.
17 , GeneralizedNewtypeDeriving
17 , GeneralizedNewtypeDeriving
18 , LambdaCase
18 , LambdaCase
19 , MultiParamTypeClasses
19 , MultiParamTypeClasses
20 , OverloadedStrings
21 , OverloadedStrings
22+ , QuantifiedConstraints
21 , ScopedTypeVariables
23 , ScopedTypeVariables
22 , StandaloneDeriving
24 , StandaloneDeriving
23 , TypeApplications
25 , TypeApplications
@@ -30,13 +32,15 @@ Squeal queries.
31module Squeal.PostgreSQL.Query
33module Squeal.PostgreSQL.Query
32 ( -- * Queries
34 ( -- * Queries
34− , Query_
36+ , Query (..)
35 -- ** Select
37 -- ** Select
38 , selectDistinct
40 , selectDistinct
39 , selectDistinct_
41 , selectDistinct_
40 , Selection (..)
44 , Selection (..)
41 -- ** Values
45 -- ** Values
@@ -51,23 +55,7 @@ module Squeal.PostgreSQL.Query
51 -- ** With
55 -- ** With
52 , With (..)
56 , With (..)
53 , CommonTableExpression (..)
57 , CommonTableExpression (..)
54− , renderCommonTableExpression
58+ , withRecursive
55− , renderCommonTableExpressions
64− , jsonbPopulateRecord
65− , jsonPopulateRecordSet
66− , jsonbPopulateRecordSet
71 -- * Table Expressions
59 -- * Table Expressions
72 , TableExpression (..)
60 , TableExpression (..)
@@ -91,33 +79,6 @@ module Squeal.PostgreSQL.Query
92 , GroupByClause (..)
80 , GroupByClause (..)
93 , HavingClause (..)
81 , HavingClause (..)
94− -- * Subquery Expressions
123import Control.DeepSeq
84import Control.DeepSeq
@@ -130,13 +91,67 @@ import GHC.TypeLits
131import qualified GHC.Generics as GHC
92import qualified GHC.Generics as GHC
94+import Squeal.PostgreSQL.Alias
133import Squeal.PostgreSQL.Expression
95import 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
134import Squeal.PostgreSQL.Render
101import Squeal.PostgreSQL.Render
135import Squeal.PostgreSQL.Schema
102import Squeal.PostgreSQL.Schema
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
138−The process of retrieving or the command to retrieve data from a database
112+The process of retrieving or the command to retrieve data from
139−is called a `Query`. Let's see some examples of queries.
113+a database is called a `Query`.
115+The general `Query` type is parameterized by
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`.
125+ (commons :: FromType)
126+ (schemas :: SchemasType)
127+ (params :: [NullityType])
129+ = UnsafeQuery { renderQuery :: ByteString }
130+ deriving (GHC.Generic,Show,Eq,Ord,NFData)
131+instance RenderSQL (Query outer commons schemas params row) where renderSQL = renderQuery
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`.
138+A top-level query can be run
139+using `Squeal.PostgreSQL.PQ.runQueryParams`, or if @parameters = ()@
140+using `Squeal.PostgreSQL.PQ.runQuery`.
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.
147+Let's see some examples of queries.
149+>>> :set -XDeriveAnyClass -XDerivingStrategies
151+data Row a b = Row { col1 :: a, col2 :: b }
152+ deriving stock (GHC.Generic)
153+ deriving anyclass (SOP.Generic, SOP.HasDatatypeInfo)
141simple query:
156simple query:
@@ -144,7 +159,7 @@ simple query:
144>>> type Schema = '["tab" ::: 'Table ('[] :=> Columns)]
159>>> type Schema = '["tab" ::: 'Table ('[] :=> Columns)]
147− query :: Query '[] (Public Schema) '[] '["col1" ::: 'NotNull 'PGint4, "col2" ::: 'NotNull 'PGint4]
162+ query :: Query_ (Public Schema) () (Row Int32 Int32)
148 query = select Star (from (table #tab))
163 query = select Star (from (table #tab))
149in printSQL query
164in printSQL query
@@ -154,21 +169,21 @@ restricted query:
157− query :: Query '[] (Public Schema) '[] '["sum" ::: 'NotNull 'PGint4, "col1" ::: 'NotNull 'PGint4]
172+ query :: Query_ (Public Schema) () (Row Int32 Int32)
159− select_ ((#col1 + #col2) `as` #sum :* #col1)
174+ select_ ((#col1 + #col2) `as` #col1 :* #col1 `as` #col2)
160 ( from (table #tab)
175 ( from (table #tab)
161 & where_ (#col1 .> #col2)
176 & where_ (#col1 .> #col2)
162 & where_ (#col2 .> 0) )
177 & where_ (#col2 .> 0) )
163in printSQL query
178in printSQL query
165−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))
171− query :: Query '[] (Public Schema) '[] '["col1" ::: 'NotNull 'PGint4, "col2" ::: 'NotNull 'PGint4]
186+ query :: Query_ (Public Schema) () (Row Int32 Int32)
172 query = select Star (from (subquery (select Star (from (table #tab)) `as` #sub)))
187 query = select Star (from (subquery (select Star (from (table #tab)) `as` #sub)))
173in printSQL query
188in printSQL query
@@ -178,7 +193,7 @@ limits and offsets:
181− query :: Query '[] (Public Schema) '[] '["col1" ::: 'NotNull 'PGint4, "col2" ::: 'NotNull 'PGint4]
196+ query :: Query_ (Public Schema) () (Row Int32 Int32)
182 query = select Star (from (table #tab) & limit 100 & offset 2 & limit 50 & offset 2)
197 query = select Star (from (table #tab) & limit 100 & offset 2 & limit 50 & offset 2)
183in printSQL query
198in printSQL query
@@ -188,7 +203,7 @@ parameterized query:
191− query :: Query '[] (Public Schema) '[ 'NotNull 'PGint4] '["col1" ::: 'NotNull 'PGint4, "col2" ::: 'NotNull 'PGint4]
206+ query :: Query_ (Public Schema) (Only Int32) (Row Int32 Int32)
192 query = select Star (from (table #tab) & where_ (#col1 .> param @1))
207 query = select Star (from (table #tab) & where_ (#col1 .> param @1))
193in printSQL query
208in printSQL query
@@ -198,21 +213,21 @@ aggregation query:
201− query :: Query '[] (Public Schema) '[] '["sum" ::: 'NotNull 'PGint4, "col1" ::: 'NotNull 'PGint4 ]
216+ query :: Query_ (Public Schema) () (Row Int64 Int32)
203− select_ (sum_ (All #col2) `as` #sum :* #col1)
218+ select_ ((fromNull 0 (sum_ (All #col2))) `as` #col1 :* #col1 `as` #col2)
204 ( from (table (#tab `as` #table1))
219 ( from (table (#tab `as` #table1))
205 & groupBy #col1
220 & groupBy #col1
206− & having (#col1 + sum_ (Distinct #col2) .> 1) )
221+ & having (sum_ (Distinct #col2) .> 1) )
207in printSQL query
222in printSQL query
209−SELECT sum(ALL "col2") AS "sum", "col1" AS "col1" FROM "tab" AS "table1" GROUP BY "col1" HAVING (("col1" + sum(DISTINCT "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)
211sorted query:
226sorted query:
215− query :: Query '[] (Public Schema) '[] '["col1" ::: 'NotNull 'PGint4, "col2" ::: 'NotNull 'PGint4]
230+ query :: Query_ (Public Schema) () (Row Int32 Int32)
216 query = select Star (from (table #tab) & orderBy [#col1 & Asc])
231 query = select Star (from (table #tab) & orderBy [#col1 & Asc])
217in printSQL query
232in printSQL query
@@ -220,14 +235,12 @@ SELECT * FROM "tab" AS "tab" ORDER BY "col1" ASC
223−>>> :set -XFlexibleContexts
225type OrdersColumns =
239type OrdersColumns =
226 '[ "id" ::: 'NoDef :=> 'NotNull 'PGint4
240 '[ "id" ::: 'NoDef :=> 'NotNull 'PGint4
227− , "price" ::: 'NoDef :=> 'NotNull 'PGfloat4
241+ , "price" ::: 'NoDef :=> 'NotNull 'PGfloat4
228− , "customer_id" ::: 'NoDef :=> 'NotNull 'PGint4
242+ , "customer_id" ::: 'NoDef :=> 'NotNull 'PGint4
229− , "shipper_id" ::: 'NoDef :=> 'NotNull 'PGint4
243+ , "shipper_id" ::: 'NoDef :=> 'NotNull 'PGint4 ]
@@ -243,22 +256,27 @@ type OrdersConstraints =
244type OrdersSchema =
257type OrdersSchema =
245 '[ "orders" ::: 'Table (OrdersConstraints :=> OrdersColumns)
258 '[ "orders" ::: 'Table (OrdersConstraints :=> OrdersColumns)
246− , "customers" ::: 'Table (CustomersConstraints :=> NamesColumns)
259+ , "customers" ::: 'Table (CustomersConstraints :=> NamesColumns)
247− , "shippers" ::: 'Table (ShippersConstraints :=> NamesColumns) ]
260+ , "shippers" ::: 'Table (ShippersConstraints :=> NamesColumns) ]
266+ , customerName :: Text
267+ , shipperName :: Text
268+ } deriving GHC.Generic
269+instance SOP.Generic Order
270+instance SOP.HasDatatypeInfo Order
252− query :: Query '[] (Public OrdersSchema)
275+ query :: Query_ (Public OrdersSchema) () Order
254− '[ "order_price" ::: 'NotNull 'PGfloat4
255− , "customer_name" ::: 'NotNull 'PGtext
256− , "shipper_name" ::: 'NotNull 'PGtext
258 query = select_
276 query = select_
259− ( #o ! #price `as` #order_price :*
277+ ( #o ! #price `as` #price :*
260− #c ! #name `as` #customer_name :*
278+ #c ! #name `as` #customerName :*
261− #s ! #name `as` #shipper_name )
279+ #s ! #name `as` #shipperName )
262 ( from (table (#orders `as` #o)
280 ( from (table (#orders `as` #o)
263 & innerJoin (table (#customers `as` #c))
281 & innerJoin (table (#customers `as` #c))
264 (#o ! #customer_id .== #c ! #id)
282 (#o ! #customer_id .== #c ! #id)
@@ -266,14 +284,16 @@ let
266 (#o ! #shipper_id .== #s ! #id)) )
284 (#o ! #shipper_id .== #s ! #id)) )
267in printSQL query
285in printSQL query
269−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")
271self-join:
289self-join:
275− query :: Query '[] (Public Schema) '[] '["col1" ::: 'NotNull 'PGint4, "col2" ::: 'NotNull 'PGint4]
293+ query :: Query_ (Public Schema) () (Row Int32 Int32)
276− query = select (#t1 & DotStar) (from (table (#tab `as` #t1) & crossJoin (table (#tab `as` #t2))))
294+ query = select
296+ (from (table (#tab `as` #t1) & crossJoin (table (#tab `as` #t2))))
277in printSQL query
297in printSQL query
279SELECT "t1".* FROM "tab" AS "t1" CROSS JOIN "tab" AS "t2"
299SELECT "t1".* FROM "tab" AS "t1" CROSS JOIN "tab" AS "t2"
@@ -282,17 +302,19 @@ value queries:
285− query :: Query commons schemas '[] '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
305+ query :: Query_ schemas () (Row String Bool)
286− query = values (1 `as` #foo :* true `as` #bar) [2 `as` #foo :* false `as` #bar]
306+ query = values
307+ ("true" `as` #col1 :* true `as` #col2)
308+ ["false" `as` #col1 :* false `as` #col2]
287in printSQL query
309in printSQL query
289−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")
291set operations:
313set operations:
295− query :: Query '[] (Public Schema) '[] '["col1" ::: 'NotNull 'PGint4, "col2" ::: 'NotNull 'PGint4]
317+ query :: Query_ (Public Schema) () (Row Int32 Int32)
296 query = select Star (from (table #tab)) `unionAll` select Star (from (table #tab))
318 query = select Star (from (table #tab)) `unionAll` select Star (from (table #tab))
297in printSQL query
319in printSQL query
@@ -302,7 +324,7 @@ with queries:
305− query :: Query '[] (Public Schema) '[] '["col1" ::: 'NotNull 'PGint4, "col2" ::: 'NotNull 'PGint4]
327+ query :: Query_ (Public Schema) () (Row Int32 Int32)
306 query = with (
328 query = with (
307 select Star (from (table #tab)) `as` #cte1 :>>
329 select Star (from (table #tab)) `as` #cte1 :>>
308 select Star (from (common #cte1)) `as` #cte2
330 select Star (from (common #cte1)) `as` #cte2
@@ -315,32 +337,42 @@ window function queries
318− query :: Query '[] (Public Schema) '[] ["col1" ::: 'NotNull 'PGint4, "rank" ::: 'NotNull 'PGint8]
340+ query :: Query_ (Public Schema) () (Row Int32 Int64)
319 query = select
341 query = select
320− (List #col1 & Also ((rank `as` #rank) `Over` (partitionBy (#col1 :* Nil) & orderBy [#col2 & Asc])))
342+ (#col1 & Also (rank `as` #col2 `Over` (partitionBy #col1 & orderBy [#col2 & Asc])))
321 (from (table #tab))
343 (from (table #tab))
322in printSQL query
344in printSQL query
324−SELECT "col1" AS "col1", rank() OVER (PARTITION BY "col1" ORDER BY "col2" ASC) AS "rank" FROM "tab" AS "tab"
346+SELECT "col1" AS "col1", rank() OVER (PARTITION BY "col1" ORDER BY "col2" ASC) AS "col2" FROM "tab" AS "tab"
348+correlated subqueries
352+ query :: Query_ (Public Schema) () (Only Int32)
354+ select (#col1 `as` #fromOnly) (from (table (#tab `as` #t1))
356+ select Star (from (table (#tab `as` #t2))
357+ & where_ (#t2 ! #col2 .== #t1 ! #col1)))))
360+SELECT "col1" AS "fromOnly" FROM "tab" AS "t1" WHERE EXISTS (SELECT * FROM "tab" AS "t2" WHERE ("t2"."col2" = "t1"."col1"))
326−newtype Query
363+type family Query_
327− (commons :: FromType)
328 (schemas :: SchemasType)
364 (schemas :: SchemasType)
329− (params :: [NullityType])
365+ (parameters :: Type)
330− (row :: RowType)
366+ (row :: Type) where
331− = UnsafeQuery { renderQuery :: ByteString }
367+ Query_ schemas params row =
332− deriving (GHC.Generic,Show,Eq,Ord,NFData)
368+ Query '[] '[] schemas (TuplePG params) (RowPG row)
333−instance RenderSQL (Query commons schemas params row) where renderSQL = renderQuery
335−type family Query_ (schemas :: SchemasType) (params :: Type) (row :: Type) where
336− Query_ schemas params row = Query '[] schemas (TuplePG params) (RowPG row)
338-- | The results of two queries can be combined using the set operation
370-- | The results of two queries can be combined using the set operation
339-- `union`. Duplicate rows are eliminated.
371-- `union`. Duplicate rows are eliminated.
341− :: Query commons schemas params columns
373+ :: Query outer commons schemas params columns
342− -> Query commons schemas params columns
374+ -> Query outer commons schemas params columns
343− -> Query commons schemas params columns
375+ -> Query outer commons schemas params columns
344q1 `union` q2 = UnsafeQuery $
376q1 `union` q2 = UnsafeQuery $
345 parenthesized (renderSQL q1)
377 parenthesized (renderSQL q1)
346 <+> "UNION"
378 <+> "UNION"
@@ -349,9 +381,9 @@ q1 `union` q2 = UnsafeQuery $
349-- | The results of two queries can be combined using the set operation
381-- | The results of two queries can be combined using the set operation
350-- `unionAll`, the disjoint union. Duplicate rows are retained.
382-- `unionAll`, the disjoint union. Duplicate rows are retained.
352− :: Query commons schemas params columns
384+ :: Query outer commons schemas params columns
353− -> Query commons schemas params columns
385+ -> Query outer commons schemas params columns
354− -> Query commons schemas params columns
386+ -> Query outer commons schemas params columns
355q1 `unionAll` q2 = UnsafeQuery $
387q1 `unionAll` q2 = UnsafeQuery $
356 parenthesized (renderSQL q1)
388 parenthesized (renderSQL q1)
357 <+> "UNION" <+> "ALL"
389 <+> "UNION" <+> "ALL"
@@ -360,9 +392,9 @@ q1 `unionAll` q2 = UnsafeQuery $
360-- | The results of two queries can be combined using the set operation
392-- | The results of two queries can be combined using the set operation
361-- `intersect`, the intersection. Duplicate rows are eliminated.
393-- `intersect`, the intersection. Duplicate rows are eliminated.
363− :: Query commons schemas params columns
395+ :: Query outer commons schemas params columns
364− -> Query commons schemas params columns
396+ -> Query outer commons schemas params columns
365− -> Query commons schemas params columns
397+ -> Query outer commons schemas params columns
366q1 `intersect` q2 = UnsafeQuery $
398q1 `intersect` q2 = UnsafeQuery $
367 parenthesized (renderSQL q1)
399 parenthesized (renderSQL q1)
368 <+> "INTERSECT"
400 <+> "INTERSECT"
@@ -371,9 +403,9 @@ q1 `intersect` q2 = UnsafeQuery $
371-- | The results of two queries can be combined using the set operation
403-- | The results of two queries can be combined using the set operation
372-- `intersectAll`, the intersection. Duplicate rows are retained.
404-- `intersectAll`, the intersection. Duplicate rows are retained.
373intersectAll
405intersectAll
374− :: Query commons schemas params columns
406+ :: Query outer commons schemas params columns
375− -> Query commons schemas params columns
407+ -> Query outer commons schemas params columns
376− -> Query commons schemas params columns
408+ -> Query outer commons schemas params columns
377q1 `intersectAll` q2 = UnsafeQuery $
409q1 `intersectAll` q2 = UnsafeQuery $
378 parenthesized (renderSQL q1)
410 parenthesized (renderSQL q1)
379 <+> "INTERSECT" <+> "ALL"
411 <+> "INTERSECT" <+> "ALL"
@@ -382,9 +414,9 @@ q1 `intersectAll` q2 = UnsafeQuery $
382-- | The results of two queries can be combined using the set operation
414-- | The results of two queries can be combined using the set operation
383-- `except`, the set difference. Duplicate rows are eliminated.
415-- `except`, the set difference. Duplicate rows are eliminated.
385− :: Query commons schemas params columns
417+ :: Query outer commons schemas params columns
386− -> Query commons schemas params columns
418+ -> Query outer commons schemas params columns
387− -> Query commons schemas params columns
419+ -> Query outer commons schemas params columns
388q1 `except` q2 = UnsafeQuery $
420q1 `except` q2 = UnsafeQuery $
389 parenthesized (renderSQL q1)
421 parenthesized (renderSQL q1)
390 <+> "EXCEPT"
422 <+> "EXCEPT"
@@ -393,9 +425,9 @@ q1 `except` q2 = UnsafeQuery $
393-- | The results of two queries can be combined using the set operation
425-- | The results of two queries can be combined using the set operation
394-- `exceptAll`, the set difference. Duplicate rows are retained.
426-- `exceptAll`, the set difference. Duplicate rows are retained.
396− :: Query commons schemas params columns
428+ :: Query outer commons schemas params columns
397− -> Query commons schemas params columns
429+ -> Query outer commons schemas params columns
398− -> Query commons schemas params columns
430+ -> Query outer commons schemas params columns
399q1 `exceptAll` q2 = UnsafeQuery $
431q1 `exceptAll` q2 = UnsafeQuery $
400 parenthesized (renderSQL q1)
432 parenthesized (renderSQL q1)
401 <+> "EXCEPT" <+> "ALL"
433 <+> "EXCEPT" <+> "ALL"
@@ -405,54 +437,71 @@ q1 `exceptAll` q2 = UnsafeQuery $
405SELECT queries
437SELECT queries
406-----------------------------------------}
438-----------------------------------------}
408−data Selection grp commons schemas params from row where
440+{- | The simplest kinds of `Selection` are `Star` and `DotStar` which
409− List
441+emits all columns that a `TableExpression` produces. A select `List`
410− :: SListI row
442+is a list of `Expression`s. A `Selection` could be a list of
411− => NP (Aliased (Expression grp commons schemas params from)) row
443+`WindowFunction`s `Over` `WindowDefinition`. `Additional` `Selection`s can
412− -> Selection grp commons schemas params from row
444+be selected with `Also`.
446+data Selection outer commons grp schemas params from row where
414 :: HasUnique tab from row
448 :: HasUnique tab from row
415− => Selection 'Ungrouped commons schemas params from row
449+ => Selection outer commons 'Ungrouped schemas params from row
450+ -- ^ `HasUnique` table in the `FromClause`
417 :: Has tab from row
452 :: Has tab from row
418 => Alias tab
453 => Alias tab
419− -> Selection 'Ungrouped commons schemas params from row
454+ -- ^ `Has` table with `Alias`
420− Also
455+ -> Selection outer commons 'Ungrouped schemas params from row
421− :: Selection grp commons schemas params from right
456+ List
422− -> Selection grp commons schemas params from left
457+ :: SListI row
423− -> Selection grp commons schemas params from (Join left right)
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
425 :: SListI row
462 :: SListI row
426− => NP (Aliased (WindowFunction grp commons schemas params from)) row
463+ => NP (Aliased (WindowFunction outer commons grp schemas params from)) row
427− -> WindowDefinition grp commons schemas params from
464+ -- ^ `NP` list of `Aliased` `WindowFunction`s
428− -> Selection grp commons schemas params from row
465+ -> WindowDefinition outer commons grp schemas params from
466+ -> Selection outer commons grp schemas params from row
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
429instance (KnownSymbol col, row ~ '[col ::: ty])
474instance (KnownSymbol col, row ~ '[col ::: ty])
430 => Aliasable col
475 => Aliasable col
431− (Expression grp commons schemas params from ty)
476+ (Expression outer commons grp schemas params from ty)
432− (Selection grp commons schemas params from row) where
477+ (Selection outer commons grp schemas params from row) where
433 expr `as` col = List (expr `as` col)
478 expr `as` col = List (expr `as` col)
434−instance (Has tab from row0, Has col row0 ty, row1 ~ '[col ::: ty])
479+instance (Has tab (Join outer from) row0, Has col row0 ty, row1 ~ '[col ::: ty])
435− => IsQualified tab col (Selection 'Ungrouped commons schemas params from row1) where
480+ => IsQualified tab col
436− tab ! col = tab ! col `as` col
481+ (Selection outer commons 'Ungrouped schemas params from row1) where
482+ tab ! col = tab ! col `as` col
438− ( Has tab from row0
484+ ( Has tab (Join outer from) row0
439 , Has col row0 ty
485 , Has col row0 ty
440 , row1 ~ '[col ::: ty]
486 , row1 ~ '[col ::: ty]
441 , GroupedBy tab col bys )
487 , GroupedBy tab col bys )
442− => IsQualified tab col (Selection ('Grouped bys) commons schemas params from row1) where
488+ => IsQualified tab col
443− tab ! col = tab ! col `as` col
489+ (Selection outer commons ('Grouped bys) schemas params from row1) where
444−instance (HasUnique tab from row0, Has col row0 ty, row1 ~ '[col ::: ty])
490+ tab ! col = tab ! col `as` col
445− => IsLabel col (Selection 'Ungrouped commons schemas params from row1) where
491+instance (HasUnique tab (Join outer from) row0, Has col row0 ty, row1 ~ '[col ::: ty])
446− fromLabel = fromLabel @col `as` Alias
492+ => IsLabel col
493+ (Selection outer commons 'Ungrouped schemas params from row1) where
494+ fromLabel = fromLabel @col `as` Alias
448− ( HasUnique tab from row0
496+ ( HasUnique tab (Join outer from) row0
449 , Has col row0 ty
497 , Has col row0 ty
450 , row1 ~ '[col ::: ty]
498 , row1 ~ '[col ::: ty]
451 , GroupedBy tab col bys )
499 , GroupedBy tab col bys )
452− => IsLabel col (Selection ('Grouped bys) commons schemas params from row1) where
500+ => IsLabel col
453− fromLabel = fromLabel @col `as` Alias
501+ (Selection outer commons ('Grouped bys) schemas params from row1) where
502+ fromLabel = fromLabel @col `as` Alias
455−instance RenderSQL (Selection grp commons schemas params from row) where
504+instance RenderSQL (Selection outer commons grp schemas params from row) where
456 renderSQL = \case
505 renderSQL = \case
457 List list -> renderCommaSeparated (renderAliased renderSQL) list
506 List list -> renderCommaSeparated (renderAliased renderSQL) list
458 Star -> "*"
507 Star -> "*"
@@ -461,7 +510,7 @@ instance RenderSQL (Selection grp commons schemas params from row) where
461 Over winFns winDef ->
510 Over winFns winDef ->
463 renderOver
512 renderOver
464− :: Aliased (WindowFunction grp commons schemas params from) field
513+ :: Aliased (WindowFunction outer commons grp schemas params from) field
465 -> ByteString
514 -> ByteString
466 renderOver (winFn `As` col) = renderSQL winFn
515 renderOver (winFn `As` col) = renderSQL winFn
467 <+> "OVER" <+> parenthesized (renderSQL winDef)
516 <+> "OVER" <+> parenthesized (renderSQL winDef)
@@ -469,6 +518,10 @@ instance RenderSQL (Selection grp commons schemas params from row) where
470 renderCommaSeparated renderOver winFns
519 renderCommaSeparated renderOver winFns
522+ (Selection outer commons grp schemas params from '["fromOnly" ::: 'NotNull 'PGtext]) where
523+ fromString str = fromString str `as` Alias
472-- | the `TableExpression` in the `select` command constructs an intermediate
525-- | the `TableExpression` in the `select` command constructs an intermediate
473-- virtual table by possibly combining tables, views, eliminating rows,
526-- virtual table by possibly combining tables, views, eliminating rows,
474-- grouping, etc. This table is finally passed on to processing by
527-- grouping, etc. This table is finally passed on to processing by
@@ -476,45 +529,100 @@ instance RenderSQL (Selection grp commons schemas params from row) where
476-- the intermediate table are actually output.
529-- the intermediate table are actually output.
478 :: (SListI row, row ~ (x ': xs))
531 :: (SListI row, row ~ (x ': xs))
479− => Selection grp commons schemas params from row
532+ => Selection outer commons grp schemas params from row
480− -- ^ select list
533+ -- ^ selection
481− -> TableExpression grp commons schemas params from
534+ -> TableExpression outer commons grp schemas params from
482 -- ^ intermediate virtual table
535 -- ^ intermediate virtual table
483− -> Query commons schemas params row
536+ -> Query outer commons schemas params row
484select selection tabexpr = UnsafeQuery $
537select selection tabexpr = UnsafeQuery $
486 <+> renderSQL selection
539 <+> renderSQL selection
487 <+> renderSQL tabexpr
540 <+> renderSQL tabexpr
542+-- | Like `select` but takes an `NP` list of `Expression`s instead
543+-- of a general `Selection`.
490 :: (SListI row, row ~ (x ': xs))
545 :: (SListI row, row ~ (x ': xs))
491− => NP (Aliased (Expression grp commons schemas params from)) row
546+ => NP (Aliased (Expression outer commons grp schemas params from)) row
492− -> TableExpression grp commons schemas params from
547+ -- ^ select list
493− -> Query commons schemas params row
548+ -> TableExpression outer commons grp schemas params from
494−select_ list = select (List list)
549+ -- ^ intermediate virtual table
550+ -> Query outer commons schemas params row
551+select_ = select . List
496-- | After the select list has been processed, the result table can
553-- | After the select list has been processed, the result table can
497-- be subject to the elimination of duplicate rows using `selectDistinct`.
554-- be subject to the elimination of duplicate rows using `selectDistinct`.
498selectDistinct
555selectDistinct
499 :: (SListI columns, columns ~ (col ': cols))
556 :: (SListI columns, columns ~ (col ': cols))
500− => Selection 'Ungrouped commons schemas params from columns
557+ => Selection outer commons grp schemas params from columns
501− -- ^ select list
558+ -- ^ selection
502− -> TableExpression 'Ungrouped commons schemas params from
559+ -> TableExpression outer commons grp schemas params from
503 -- ^ intermediate virtual table
560 -- ^ intermediate virtual table
504− -> Query commons schemas params columns
561+ -> Query outer commons schemas params columns
505selectDistinct selection tabexpr = UnsafeQuery $
562selectDistinct selection tabexpr = UnsafeQuery $
506 "SELECT DISTINCT"
563 "SELECT DISTINCT"
507 <+> renderSQL selection
564 <+> renderSQL selection
508 <+> renderSQL tabexpr
565 <+> renderSQL tabexpr
567+-- | Like `selectDistinct` but takes an `NP` list of `Expression`s instead
568+-- of a general `Selection`.
510selectDistinct_
569selectDistinct_
511 :: (SListI columns, columns ~ (col ': cols))
570 :: (SListI columns, columns ~ (col ': cols))
512− => NP (Aliased (Expression 'Ungrouped commons schemas params from)) columns
571+ => NP (Aliased (Expression outer commons grp schemas params from)) columns
513 -- ^ select list
572 -- ^ select list
514− -> TableExpression 'Ungrouped commons schemas params from
573+ -> TableExpression outer commons grp schemas params from
574+ -- ^ intermediate virtual table
575+ -> Query outer commons schemas params columns
576+selectDistinct_ = selectDistinct . List
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.
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.
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.
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
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})
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
614+-- | Like `selectDistinctOn` but takes an `NP` list of `Expression`s instead
615+-- of a general `Selection`.
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
622+ -> TableExpression outer commons grp schemas params from
515 -- ^ intermediate virtual table
623 -- ^ intermediate virtual table
516− -> Query commons schemas params columns
624+ -> Query outer commons schemas params columns
517−selectDistinct_ list = select (List list)
625+selectDistinctOn_ distincts = selectDistinctOn distincts . List
519-- | `values` computes a row value or set of row values
627-- | `values` computes a row value or set of row values
520-- specified by value expressions. It is most commonly used
628-- specified by value expressions. It is most commonly used
@@ -522,16 +630,16 @@ selectDistinct_ list = select (List list)
522-- but it can be used on its own.
630-- but it can be used on its own.
524-- >>> type Row = '["a" ::: 'NotNull 'PGint4, "b" ::: 'NotNull 'PGtext]
632-- >>> type Row = '["a" ::: 'NotNull 'PGint4, "b" ::: 'NotNull 'PGtext]
525−-- >>> let query = values (1 `as` #a :* "one" `as` #b) [] :: Query commons schemas '[] Row
633+-- >>> let query = values (1 `as` #a :* "one" `as` #b) [] :: Query outer commons schemas '[] Row
526-- >>> printSQL query
634-- >>> printSQL query
527-- SELECT * FROM (VALUES (1, E'one')) AS t ("a", "b")
635-- SELECT * FROM (VALUES (1, E'one')) AS t ("a", "b")
529 :: SListI cols
637 :: SListI cols
530− => NP (Aliased (Expression 'Ungrouped commons schemas params '[] )) cols
638+ => NP (Aliased (Expression outer commons 'Ungrouped schemas params '[] )) cols
531− -> [NP (Aliased (Expression 'Ungrouped commons schemas params '[] )) cols]
639+ -> [NP (Aliased (Expression outer commons 'Ungrouped schemas params '[] )) cols]
532 -- ^ When more than one row is specified, all the rows must
640 -- ^ When more than one row is specified, all the rows must
533 -- must have the same number of elements
641 -- must have the same number of elements
534− -> Query commons schemas params cols
642+ -> Query outer commons schemas params cols
535values rw rws = UnsafeQuery $ "SELECT * FROM"
643values rw rws = UnsafeQuery $ "SELECT * FROM"
536 <+> parenthesized (
644 <+> parenthesized (
@@ -542,7 +650,7 @@ values rw rws = UnsafeQuery $ "SELECT * FROM"
542 <+> parenthesized (renderCommaSeparated renderAliasPart rw)
650 <+> parenthesized (renderCommaSeparated renderAliasPart rw)
544 renderAliasPart, renderValuePart
652 renderAliasPart, renderValuePart
545− :: Aliased (Expression 'Ungrouped commons schemas params '[] ) ty -> ByteString
653+ :: Aliased (Expression outer commons 'Ungrouped schemas params '[] ) ty -> ByteString
546 renderAliasPart (_ `As` name) = renderSQL name
654 renderAliasPart (_ `As` name) = renderSQL name
547 renderValuePart (value `As` _) = renderSQL value
655 renderValuePart (value `As` _) = renderSQL value
@@ -550,9 +658,9 @@ values rw rws = UnsafeQuery $ "SELECT * FROM"
550-- specified by value expressions.
658-- specified by value expressions.
552 :: SListI cols
660 :: SListI cols
553− => NP (Aliased (Expression 'Ungrouped commons schemas params '[] )) cols
661+ => NP (Aliased (Expression outer commons 'Ungrouped schemas params '[] )) cols
554 -- ^ one row of values
662 -- ^ one row of values
555− -> Query commons schemas params cols
663+ -> Query outer commons schemas params cols
556values_ rw = values rw []
664values_ rw = values rw []
558{-----------------------------------------
666{-----------------------------------------
@@ -566,16 +674,17 @@ Table Expressions
566-- to a table on disk, a so-called base table, but more complex expressions
674-- to a table on disk, a so-called base table, but more complex expressions
567-- can be used to modify or combine base tables in various ways.
675-- can be used to modify or combine base tables in various ways.
568data TableExpression
676data TableExpression
569− (grp :: Grouping)
677+ (outer :: FromType)
570 (commons :: FromType)
678 (commons :: FromType)
571 (schemas :: SchemasType)
680 (schemas :: SchemasType)
572 (params :: [NullityType])
681 (params :: [NullityType])
573 (from :: FromType)
682 (from :: FromType)
574 = TableExpression
683 = TableExpression
575− { fromClause :: FromClause commons schemas params from
684+ { fromClause :: FromClause outer commons schemas params from
576 -- ^ A table reference that can be a table name, or a derived table such
685 -- ^ A table reference that can be a table name, or a derived table such
577 -- as a subquery, a @JOIN@ construct, or complex combinations of these.
686 -- as a subquery, a @JOIN@ construct, or complex combinations of these.
578− , whereClause :: [Condition 'Ungrouped commons schemas params from]
687+ , whereClause :: [Condition outer commons 'Ungrouped schemas params from]
579 -- ^ optional search coditions, combined with `.&&`. After the processing
688 -- ^ optional search coditions, combined with `.&&`. After the processing
580 -- of the `fromClause` is done, each row of the derived virtual table
689 -- of the `fromClause` is done, each row of the derived virtual table
581 -- is checked against the search condition. If the result of the
690 -- is checked against the search condition. If the result of the
@@ -591,13 +700,13 @@ data TableExpression
591 -- set of rows having common values into one group row that represents all
700 -- set of rows having common values into one group row that represents all
592 -- rows in the group. This is done to eliminate redundancy in the output
701 -- rows in the group. This is done to eliminate redundancy in the output
593 -- and/or compute aggregates that apply to these groups.
702 -- and/or compute aggregates that apply to these groups.
594− , havingClause :: HavingClause grp commons schemas params from
703+ , havingClause :: HavingClause outer commons grp schemas params from
595 -- ^ If a table has been grouped using `groupBy`, but only certain groups
704 -- ^ If a table has been grouped using `groupBy`, but only certain groups
596 -- are of interest, the `havingClause` can be used, much like a
705 -- are of interest, the `havingClause` can be used, much like a
597 -- `whereClause`, to eliminate groups from the result. Expressions in the
706 -- `whereClause`, to eliminate groups from the result. Expressions in the
598 -- `havingClause` can refer both to grouped expressions and to ungrouped
707 -- `havingClause` can refer both to grouped expressions and to ungrouped
599 -- expressions (which necessarily involve an aggregate function).
708 -- expressions (which necessarily involve an aggregate function).
600− , orderByClause :: [SortExpression grp commons schemas params from]
709+ , orderByClause :: [SortExpression outer commons grp schemas params from]
601 -- ^ The `orderByClause` is for optional sorting. When more than one
710 -- ^ The `orderByClause` is for optional sorting. When more than one
602 -- `SortExpression` is specified, the later (right) values are used to sort
711 -- `SortExpression` is specified, the later (right) values are used to sort
603 -- rows that are equal according to the earlier (left) values.
712 -- rows that are equal according to the earlier (left) values.
@@ -607,14 +716,14 @@ data TableExpression
607 -- will be returned (but possibly fewer, if the query itself yields
716 -- will be returned (but possibly fewer, if the query itself yields
608 -- fewer rows).
717 -- fewer rows).
609 , offsetClause :: [Word64]
718 , offsetClause :: [Word64]
610− -- ^ The `offsetClause` is combined with `+` to give an offset count
719+ -- ^ The `offsetClause` is combined with `Prelude.+` to give an offset count
611 -- if nonempty. The offset count says to skip that many rows before
720 -- if nonempty. The offset count says to skip that many rows before
612 -- beginning to return rows. The rows are skipped before the limit count
721 -- beginning to return rows. The rows are skipped before the limit count
613 -- is applied.
722 -- is applied.
614− }
723+ } deriving (GHC.Generic)
616-- | Render a `TableExpression`
725-- | Render a `TableExpression`
617−instance RenderSQL (TableExpression grp commons schemas params from) where
726+instance RenderSQL (TableExpression outer commons grp schemas params from) where
618 renderSQL
727 renderSQL
619 (TableExpression frm' whs' grps' hvs' srts' lims' offs') = mconcat
728 (TableExpression frm' whs' grps' hvs' srts' lims' offs') = mconcat
620 [ "FROM ", renderSQL frm'
729 [ "FROM ", renderSQL frm'
@@ -623,8 +732,7 @@ instance RenderSQL (TableExpression grp commons schemas params from) where
623 , renderSQL hvs'
732 , renderSQL hvs'
624 , renderOrderByClause srts'
733 , renderOrderByClause srts'
625 , renderLimits lims'
734 , renderLimits lims'
626− , renderOffsets offs'
735+ , renderOffsets offs' ]
629 renderWheres = \case
737 renderWheres = \case
@@ -644,33 +752,33 @@ instance RenderSQL (TableExpression grp commons schemas params from) where
644-- | A `from` generates a `TableExpression` from a table reference that can be
752-- | A `from` generates a `TableExpression` from a table reference that can be
645-- a table name, or a derived table such as a subquery, a JOIN construct,
753-- a table name, or a derived table such as a subquery, a JOIN construct,
646-- or complex combinations of these. A `from` may be transformed by `where_`,
754-- or complex combinations of these. A `from` may be transformed by `where_`,
647−-- `group`, `having`, `orderBy`, `limit` and `offset`, using the `&` operator
755+-- `groupBy`, `having`, `orderBy`, `limit` and `offset`, using the `&` operator
648-- to match the left-to-right sequencing of their placement in SQL.
756-- to match the left-to-right sequencing of their placement in SQL.
650− :: FromClause commons schemas params from -- ^ table reference
758+ :: FromClause outer commons schemas params from -- ^ table reference
651− -> TableExpression 'Ungrouped commons schemas params from
759+ -> TableExpression outer commons 'Ungrouped schemas params from
652−from rels = TableExpression rels [] NoGroups NoHaving [] [] []
760+from tab = TableExpression tab [] noGroups NoHaving [] [] []
654-- | A `where_` is an endomorphism of `TableExpression`s which adds a
762-- | A `where_` is an endomorphism of `TableExpression`s which adds a
655-- search condition to the `whereClause`.
763-- search condition to the `whereClause`.
657− :: Condition 'Ungrouped commons schemas params from -- ^ filtering condition
765+ :: Condition outer commons 'Ungrouped schemas params from -- ^ filtering condition
658− -> TableExpression grp commons schemas params from
766+ -> TableExpression outer commons grp schemas params from
659− -> TableExpression grp commons schemas params from
767+ -> TableExpression outer commons grp schemas params from
660where_ wh rels = rels {whereClause = wh : whereClause rels}
768where_ wh rels = rels {whereClause = wh : whereClause rels}
662-- | A `groupBy` is a transformation of `TableExpression`s which switches
770-- | A `groupBy` is a transformation of `TableExpression`s which switches
663−-- its `Grouping` from `Ungrouped` to `Grouped`. Use @group Nil@ to perform
771+-- its `Grouping` from `Ungrouped` to `Grouped`. Use @groupBy Nil@ to perform
664-- a "grand total" aggregation query.
772-- a "grand total" aggregation query.
666 :: SListI bys
774 :: SListI bys
667 => NP (By from) bys -- ^ grouped columns
775 => NP (By from) bys -- ^ grouped columns
668− -> TableExpression 'Ungrouped commons schemas params from
776+ -> TableExpression outer commons 'Ungrouped schemas params from
669− -> TableExpression ('Grouped bys) commons schemas params from
777+ -> TableExpression outer commons ('Grouped bys) schemas params from
670groupBy bys rels = TableExpression
778groupBy bys rels = TableExpression
671 { fromClause = fromClause rels
779 { fromClause = fromClause rels
672 , whereClause = whereClause rels
780 , whereClause = whereClause rels
673− , groupByClause = Group bys
781+ , groupByClause = group bys
674 , havingClause = Having []
782 , havingClause = Having []
675 , orderByClause = []
783 , orderByClause = []
676 , limitClause = limitClause rels
784 , limitClause = limitClause rels
@@ -680,9 +788,9 @@ groupBy bys rels = TableExpression
680-- | A `having` is an endomorphism of `TableExpression`s which adds a
788-- | A `having` is an endomorphism of `TableExpression`s which adds a
681-- search condition to the `havingClause`.
789-- search condition to the `havingClause`.
683− :: Condition ('Grouped bys) commons schemas params from -- ^ having condition
791+ :: Condition outer commons ('Grouped bys) schemas params from -- ^ having condition
684− -> TableExpression ('Grouped bys) commons schemas params from
792+ -> TableExpression outer commons ('Grouped bys) schemas params from
685− -> TableExpression ('Grouped bys) commons schemas params from
793+ -> TableExpression outer commons ('Grouped bys) schemas params from
686having hv rels = rels
794having hv rels = rels
687 { havingClause = case havingClause rels of Having hvs -> Having (hv:hvs) }
795 { havingClause = case havingClause rels of Having hvs -> Having (hv:hvs) }
@@ -693,159 +801,18 @@ instance OrderBy TableExpression where
693-- `limitClause`.
801-- `limitClause`.
695 :: Word64 -- ^ limit parameter
803 :: Word64 -- ^ limit parameter
696− -> TableExpression grp commons schemas params from
804+ -> TableExpression outer commons grp schemas params from
697− -> TableExpression grp commons schemas params from
805+ -> TableExpression outer commons grp schemas params from
698limit lim rels = rels {limitClause = lim : limitClause rels}
806limit lim rels = rels {limitClause = lim : limitClause rels}
700-- | An `offset` is an endomorphism of `TableExpression`s which adds to the
808-- | An `offset` is an endomorphism of `TableExpression`s which adds to the
701-- `offsetClause`.
809-- `offsetClause`.
703 :: Word64 -- ^ offset parameter
811 :: Word64 -- ^ offset parameter
704− -> TableExpression grp commons schemas params from
812+ -> TableExpression outer commons grp schemas params from
705− -> TableExpression grp commons schemas params from
813+ -> TableExpression outer commons grp schemas params from
706offset off rels = rels {offsetClause = off : offsetClause rels}
814offset off rels = rels {offsetClause = off : offsetClause rels}
708−{-----------------------------------------
710−-----------------------------------------}
714− -> Expression 'Ungrouped commons schemas params '[] ty
715− -> Query commons schemas params row
716−unsafeSetOfFunction fun expr = UnsafeQuery $
717− "SELECT * FROM " <> fun <> "(" <> renderSQL expr <> ")"
719−-- | Expands the outermost JSON object into a set of key/value pairs.
721− :: Expression 'Ungrouped commons schemas params '[] (nullity 'PGjson) -- ^ json object
722− -> Query commons schemas params
723− '["key" ::: 'NotNull 'PGtext, "value" ::: 'NotNull 'PGjson]
724−jsonEach = unsafeSetOfFunction "json_each"
726−-- | Expands the outermost binary JSON object into a set of key/value pairs.
728− :: Expression 'Ungrouped commons schemas params '[] (nullity 'PGjsonb) -- ^ jsonb object
729− -> Query commons schemas params
730− '["key" ::: 'NotNull 'PGtext, "value" ::: 'NotNull 'PGjsonb]
731−jsonbEach = unsafeSetOfFunction "jsonb_each"
733−-- | Expands the outermost JSON object into a set of key/value pairs.
735− :: Expression 'Ungrouped commons schemas params '[] (nullity 'PGjson) -- ^ json object
736− -> Query commons schemas params
737− '["key" ::: 'NotNull 'PGtext, "value" ::: 'NotNull 'PGtext]
738−jsonEachAsText = unsafeSetOfFunction "json_each_text"
740−-- | Expands the outermost binary JSON object into a set of key/value pairs.
742− :: Expression 'Ungrouped commons schemas params '[] (nullity 'PGjsonb) -- ^ jsonb object
743− -> Query commons schemas params
744− '["key" ::: 'NotNull 'PGtext, "value" ::: 'NotNull 'PGtext]
745−jsonbEachAsText = unsafeSetOfFunction "jsonb_each_text"
747−-- | Returns set of keys in the outermost JSON object.
749− :: Expression 'Ungrouped commons schemas params '[] (nullity 'PGjson) -- ^ json object
750− -> Query commons schemas params '["json_object_keys" ::: 'NotNull 'PGtext]
751−jsonObjectKeys = unsafeSetOfFunction "json_object_keys"
753−-- | Returns set of keys in the outermost JSON object.
755− :: Expression 'Ungrouped commons schemas params '[] (nullity 'PGjsonb) -- ^ jsonb object
756− -> Query commons schemas params '["jsonb_object_keys" ::: 'NotNull 'PGtext]
757−jsonbObjectKeys = unsafeSetOfFunction "jsonb_object_keys"
759−unsafePopulateFunction
761− -> TypeExpression schemas (nullity ('PGcomposite row))
762− -> Expression 'Ungrouped commons schemas params '[] ty
763− -> Query commons schemas params row
764−unsafePopulateFunction fun ty expr = UnsafeQuery $
765− "SELECT * FROM " <> fun <> "("
766− <> "null::" <> renderSQL ty <> ", "
767− <> renderSQL expr <> ")"
769−-- | Expands the JSON expression to a row whose columns match the record
770−-- type defined by the given table.
772− :: TypeExpression schemas (nullity ('PGcomposite row)) -- ^ row type
773− -> Expression 'Ungrouped commons schemas params '[] (nullity 'PGjson) -- ^ json object
774− -> Query commons schemas params row
775−jsonPopulateRecord = unsafePopulateFunction "json_populate_record"
777−-- | Expands the binary JSON expression to a row whose columns match the record
778−-- type defined by the given table.
780− :: TypeExpression schemas (nullity ('PGcomposite row)) -- ^ row type
781− -> Expression 'Ungrouped commons schemas params '[] (nullity 'PGjsonb) -- ^ jsonb object
782− -> Query commons schemas params row
783−jsonbPopulateRecord = unsafePopulateFunction "jsonb_populate_record"
785−-- | Expands the outermost array of objects in the given JSON expression to a
786−-- set of rows whose columns match the record type defined by the given table.
787−jsonPopulateRecordSet
788− :: TypeExpression schemas (nullity ('PGcomposite row)) -- ^ row type
789− -> Expression 'Ungrouped commons schemas params '[] (nullity 'PGjson) -- ^ json array
790− -> Query commons schemas params row
791−jsonPopulateRecordSet = unsafePopulateFunction "json_populate_record_set"
793−-- | Expands the outermost array of objects in the given binary JSON expression
794−-- to a set of rows whose columns match the record type defined by the given
796−jsonbPopulateRecordSet
797− :: TypeExpression schemas (nullity ('PGcomposite row)) -- ^ row type
798− -> Expression 'Ungrouped commons schemas params '[] (nullity 'PGjsonb) -- ^ jsonb array
799− -> Query commons schemas params row
800−jsonbPopulateRecordSet = unsafePopulateFunction "jsonb_populate_record_set"
803− :: (SListI record, json `In` PGJsonType)
805− -> Expression 'Ungrouped commons schemas params '[] (nullity json)
806− -> NP (Aliased (TypeExpression schemas)) record
807− -> Query commons schemas params record
808−unsafeRecordFunction fun expr types = UnsafeQuery $
809− "SELECT * FROM " <> fun <> "("
810− <> renderSQL expr <> ")"
811− <+> "AS" <+> "x" <> parenthesized (renderCommaSeparated renderTy types)
813− renderTy :: Aliased (TypeExpression schemas) ty -> ByteString
814− renderTy (ty `As` alias) =
815− renderSQL alias <+> renderSQL ty
817−-- | Builds an arbitrary record from a JSON object.
820− => Expression 'Ungrouped commons schemas params '[] (nullity 'PGjson) -- ^ json object
821− -> NP (Aliased (TypeExpression schemas)) record -- ^ record types
822− -> Query commons schemas params record
823−jsonToRecord = unsafeRecordFunction "json_to_record"
825−-- | Builds an arbitrary record from a binary JSON object.
828− => Expression 'Ungrouped commons schemas params '[] (nullity 'PGjsonb) -- ^ jsonb object
829− -> NP (Aliased (TypeExpression schemas)) record -- ^ record types
830− -> Query commons schemas params record
831−jsonbToRecord = unsafeRecordFunction "jsonb_to_record"
833−-- | Builds an arbitrary set of records from a JSON array of objects.
836− => Expression 'Ungrouped commons schemas params '[] (nullity 'PGjson) -- ^ json array
837− -> NP (Aliased (TypeExpression schemas)) record -- ^ record types
838− -> Query commons schemas params record
839−jsonToRecordSet = unsafeRecordFunction "json_to_record_set"
841−-- | Builds an arbitrary set of records from a binary JSON array of objects.
844− => Expression 'Ungrouped commons schemas params '[] (nullity 'PGjsonb) -- ^ jsonb array
845− -> NP (Aliased (TypeExpression schemas)) record -- ^ record types
846− -> Query commons schemas params record
847−jsonbToRecordSet = unsafeRecordFunction "jsonb_to_record_set"
849{-----------------------------------------
816{-----------------------------------------
850FROM clauses
817FROM clauses
851-----------------------------------------}
818-----------------------------------------}
@@ -854,53 +821,59 @@ FROM clauses
854A `FromClause` can be a table name, or a derived table such
821A `FromClause` can be a table name, or a derived table such
855as a subquery, a @JOIN@ construct, or complex combinations of these.
822as a subquery, a @JOIN@ construct, or complex combinations of these.
857−newtype FromClause commons schemas params from
824+newtype FromClause outer commons schemas params from
858 = UnsafeFromClause { renderFromClause :: ByteString }
825 = UnsafeFromClause { renderFromClause :: ByteString }
859 deriving (GHC.Generic,Show,Eq,Ord,NFData)
826 deriving (GHC.Generic,Show,Eq,Ord,NFData)
860−instance RenderSQL (FromClause commons schemas params from) where
827+instance RenderSQL (FromClause outer commons schemas params from) where
861 renderSQL = renderFromClause
828 renderSQL = renderFromClause
863-- | A real `table` is a table from the database.
830-- | A real `table` is a table from the database.
865 :: (Has sch schemas schema, Has tab schema ('Table table))
832 :: (Has sch schemas schema, Has tab schema ('Table table))
866 => Aliased (QualifiedAlias sch) (alias ::: tab)
833 => Aliased (QualifiedAlias sch) (alias ::: tab)
867− -> FromClause commons schemas params '[alias ::: TableToRow table]
834+ -> FromClause outer commons schemas params '[alias ::: TableToRow table]
868table (tab `As` alias) = UnsafeFromClause $
835table (tab `As` alias) = UnsafeFromClause $
869 renderSQL tab <+> "AS" <+> renderSQL alias
836 renderSQL tab <+> "AS" <+> renderSQL alias
871-- | `subquery` derives a table from a `Query`.
838-- | `subquery` derives a table from a `Query`.
873− :: Aliased (Query commons schemas params) query
840+ :: Aliased (Query outer commons schemas params) query
874− -> FromClause commons schemas params '[query]
841+ -> FromClause outer commons schemas params '[query]
875−subquery = UnsafeFromClause . renderAliased (parenthesized . renderQuery)
842+subquery = UnsafeFromClause . renderAliased (parenthesized . renderSQL)
877-- | `view` derives a table from a `View`.
844-- | `view` derives a table from a `View`.
879 :: (Has sch schemas schema, Has vw schema ('View view))
846 :: (Has sch schemas schema, Has vw schema ('View view))
880 => Aliased (QualifiedAlias sch) (alias ::: vw)
847 => Aliased (QualifiedAlias sch) (alias ::: vw)
881− -> FromClause commons schemas params '[alias ::: view]
848+ -> FromClause outer commons schemas params '[alias ::: view]
882view (vw `As` alias) = UnsafeFromClause $
849view (vw `As` alias) = UnsafeFromClause $
883 renderSQL vw <+> "AS" <+> renderSQL alias
850 renderSQL vw <+> "AS" <+> renderSQL alias
852+-- | `common` derives a table from a common table expression.
886 :: Has cte commons common
854 :: Has cte commons common
887 => Aliased Alias (alias ::: cte)
855 => Aliased Alias (alias ::: cte)
888− -> FromClause commons schemas params '[alias ::: common]
856+ -> FromClause outer commons schemas params '[alias ::: common]
889common (cte `As` alias) = UnsafeFromClause $
857common (cte `As` alias) = UnsafeFromClause $
890 renderSQL cte <+> "AS" <+> renderSQL alias
858 renderSQL cte <+> "AS" <+> renderSQL alias
892−{- | @left & crossJoin right@. For every possible combination of rows from
860+instance Additional (FromClause outer commons schemas params) where
893− @left@ and @right@ (i.e., a Cartesian product), the joined table will contain
861+ also right left = UnsafeFromClause $
894− a row consisting of all columns in @left@ followed by all columns in @right@.
862+ renderSQL left <> ", " <> renderSQL right
895− If the tables have @n@ and @m@ rows respectively, the joined table will
863+
896− have @n * m@ rows.
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
899− :: FromClause commons schemas params right
872+ :: FromClause outer commons schemas params right
900 -- ^ right
873 -- ^ right
901− -> FromClause commons schemas params left
874+ -> FromClause outer commons schemas params left
902 -- ^ left
875 -- ^ left
903− -> FromClause commons schemas params (Join left right)
876+ -> FromClause outer commons schemas params (Join left right)
904crossJoin right left = UnsafeFromClause $
877crossJoin right left = UnsafeFromClause $
905 renderSQL left <+> "CROSS JOIN" <+> renderSQL right
878 renderSQL left <+> "CROSS JOIN" <+> renderSQL right
@@ -908,13 +881,13 @@ crossJoin right left = UnsafeFromClause $
908the @on@ condition.
881the @on@ condition.
911− :: FromClause commons schemas params right
884+ :: FromClause outer commons schemas params right
912 -- ^ right
885 -- ^ right
913− -> Condition 'Ungrouped commons schemas params (Join left right)
886+ -> Condition outer commons 'Ungrouped schemas params (Join left right)
914 -- ^ @on@ condition
887 -- ^ @on@ condition
915− -> FromClause commons schemas params left
888+ -> FromClause outer commons schemas params left
916 -- ^ left
889 -- ^ left
917− -> FromClause commons schemas params (Join left right)
890+ -> FromClause outer commons schemas params (Join left right)
918innerJoin right on left = UnsafeFromClause $
891innerJoin right on left = UnsafeFromClause $
919 renderSQL left <+> "INNER JOIN" <+> renderSQL right
892 renderSQL left <+> "INNER JOIN" <+> renderSQL right
920 <+> "ON" <+> renderSQL on
893 <+> "ON" <+> renderSQL on
@@ -925,13 +898,13 @@ innerJoin right on left = UnsafeFromClause $
925 Thus, the joined table always has at least one row for each row in @left@.
898 Thus, the joined table always has at least one row for each row in @left@.
927leftOuterJoin
900leftOuterJoin
928− :: FromClause commons schemas params right
901+ :: FromClause outer commons schemas params right
929 -- ^ right
902 -- ^ right
930− -> Condition 'Ungrouped commons schemas params (Join left right)
903+ -> Condition outer commons 'Ungrouped schemas params (Join left right)
931 -- ^ @on@ condition
904 -- ^ @on@ condition
932− -> FromClause commons schemas params left
905+ -> FromClause outer commons schemas params left
933 -- ^ left
906 -- ^ left
934− -> FromClause commons schemas params (Join left (NullifyFrom right))
907+ -> FromClause outer commons schemas params (Join left (NullifyFrom right))
935leftOuterJoin right on left = UnsafeFromClause $
908leftOuterJoin right on left = UnsafeFromClause $
936 renderSQL left <+> "LEFT OUTER JOIN" <+> renderSQL right
909 renderSQL left <+> "LEFT OUTER JOIN" <+> renderSQL right
937 <+> "ON" <+> renderSQL on
910 <+> "ON" <+> renderSQL on
@@ -943,13 +916,13 @@ leftOuterJoin right on left = UnsafeFromClause $
943 have a row for each row in @right@.
916 have a row for each row in @right@.
945rightOuterJoin
918rightOuterJoin
946− :: FromClause commons schemas params right
919+ :: FromClause outer commons schemas params right
947 -- ^ right
920 -- ^ right
948− -> Condition 'Ungrouped commons schemas params (Join left right)
921+ -> Condition outer commons 'Ungrouped schemas params (Join left right)
949 -- ^ @on@ condition
922 -- ^ @on@ condition
950− -> FromClause commons schemas params left
923+ -> FromClause outer commons schemas params left
951 -- ^ left
924 -- ^ left
952− -> FromClause commons schemas params (Join (NullifyFrom left) right)
925+ -> FromClause outer commons schemas params (Join (NullifyFrom left) right)
953rightOuterJoin right on left = UnsafeFromClause $
926rightOuterJoin right on left = UnsafeFromClause $
954 renderSQL left <+> "RIGHT OUTER JOIN" <+> renderSQL right
927 renderSQL left <+> "RIGHT OUTER JOIN" <+> renderSQL right
955 <+> "ON" <+> renderSQL on
928 <+> "ON" <+> renderSQL on
@@ -962,13 +935,13 @@ rightOuterJoin right on left = UnsafeFromClause $
962 is added.
935 is added.
964fullOuterJoin
937fullOuterJoin
965− :: FromClause commons schemas params right
938+ :: FromClause outer commons schemas params right
966 -- ^ right
939 -- ^ right
967− -> Condition 'Ungrouped commons schemas params (Join left right)
940+ -> Condition outer commons 'Ungrouped schemas params (Join left right)
968 -- ^ @on@ condition
941 -- ^ @on@ condition
969− -> FromClause commons schemas params left
942+ -> FromClause outer commons schemas params left
970 -- ^ left
943 -- ^ left
971− -> FromClause commons schemas params
944+ -> FromClause outer commons schemas params
972 (Join (NullifyFrom left) (NullifyFrom right))
945 (Join (NullifyFrom left) (NullifyFrom right))
973fullOuterJoin right on left = UnsafeFromClause $
946fullOuterJoin right on left = UnsafeFromClause $
974 renderSQL left <+> "FULL OUTER JOIN" <+> renderSQL right
947 renderSQL left <+> "FULL OUTER JOIN" <+> renderSQL right
@@ -978,7 +951,7 @@ fullOuterJoin right on left = UnsafeFromClause $
979-----------------------------------------}
952-----------------------------------------}
981−-- | `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
982-- used to group together those rows in a table that have the same values
955-- used to group together those rows in a table that have the same values
983-- in all the columns listed. @By \#col@ will reference an unambiguous
956-- in all the columns listed. @By \#col@ will reference an unambiguous
984-- column @col@; otherwise @By2 (\#tab \! \#col)@ will reference a table
957-- column @col@; otherwise @By2 (\#tab \! \#col)@ will reference a table
@@ -1019,309 +992,42 @@ instance (Has rel rels cols, Has col cols ty, bys ~ '[ '(rel, col)])
1019-- done on @NoGroups@ while all output `Expression`s must be aggregated
992-- done on @NoGroups@ while all output `Expression`s must be aggregated
1020-- in @Group Nil@. In general, all output `Expression`s in the
993-- in @Group Nil@. In general, all output `Expression`s in the
1021-- complement of @bys@ must be aggregated in @Group bys@.
994-- complement of @bys@ must be aggregated in @Group bys@.
1022−data GroupByClause grp from where
995+newtype GroupByClause grp from = UnsafeGroupByClause
1023− NoGroups :: GroupByClause 'Ungrouped from
996+ { renderGroupByClause :: ByteString }
1024− Group
997+ deriving (GHC.Generic,Show,Eq,Ord,NFData)
1026− => NP (By from) bys
1027− -> GroupByClause ('Grouped bys) from
1029−-- | Renders a `GroupByClause`.
1030instance RenderSQL (GroupByClause grp from) where
998instance RenderSQL (GroupByClause grp from) where
1031− renderSQL = \case
999+ renderSQL = renderGroupByClause
1032− NoGroups -> ""
1000+noGroups :: GroupByClause 'Ungrouped from
1033− Group Nil -> ""
1001+noGroups = UnsafeGroupByClause ""
1034− Group bys -> " GROUP BY" <+> renderCommaSeparated renderSQL bys
1002+group
1004+ => NP (By from) bys
1005+ -> GroupByClause ('Grouped bys) from
1006+group bys = UnsafeGroupByClause $ case bys of
1008+ bys' -> " GROUP BY" <+> renderCommaSeparated renderSQL bys'
1036-- | A `HavingClause` is used to eliminate groups that are not of interest.
1010-- | A `HavingClause` is used to eliminate groups that are not of interest.
1037-- An `Ungrouped` `TableExpression` may only use `NoHaving` while a `Grouped`
1011-- An `Ungrouped` `TableExpression` may only use `NoHaving` while a `Grouped`
1038-- `TableExpression` must use `Having` whose conditions are combined with
1012-- `TableExpression` must use `Having` whose conditions are combined with
1039-- `.&&`.
1013-- `.&&`.
1040−data HavingClause grp commons schemas params from where
1014+data HavingClause outer commons grp schemas params from where
1041− NoHaving :: HavingClause 'Ungrouped commons schemas params from
1015+ NoHaving :: HavingClause outer commons 'Ungrouped schemas params from
1043− :: [Condition ('Grouped bys) commons schemas params from]
1017+ :: [Condition outer commons ('Grouped bys) schemas params from]
1044− -> HavingClause ('Grouped bys) commons schemas params from
1018+ -> HavingClause outer commons ('Grouped bys) schemas params from
1045−deriving instance Show (HavingClause grp commons schemas params from)
1019+deriving instance Show (HavingClause outer commons grp schemas params from)
1046−deriving instance Eq (HavingClause grp commons schemas params from)
1020+deriving instance Eq (HavingClause outer commons grp schemas params from)
1047−deriving instance Ord (HavingClause grp commons schemas params from)
1021+deriving instance Ord (HavingClause outer commons grp schemas params from)
1049-- | Render a `HavingClause`.
1023-- | Render a `HavingClause`.
1050−instance RenderSQL (HavingClause grp commons schemas params from) where
1024+instance RenderSQL (HavingClause outer commons grp schemas params from) where
1051 renderSQL = \case
1025 renderSQL = \case
1052 NoHaving -> ""
1026 NoHaving -> ""
1053 Having [] -> ""
1027 Having [] -> ""
1054 Having conditions ->
1028 Having conditions ->
1055 " HAVING" <+> commaSeparated (renderSQL <$> conditions)
1029 " HAVING" <+> commaSeparated (renderSQL <$> conditions)
1057−unsafeSubqueryExpression
1059− -> Expression grp commons schemas params from ty
1060− -> Query commons schemas params '[alias ::: ty]
1061− -> Expression grp commons schemas params from (nullity 'PGbool)
1062−unsafeSubqueryExpression op x q = UnsafeExpression $
1063− renderSQL x <+> op <+> parenthesized (renderSQL q)
1065−unsafeRowSubqueryExpression
1068− -> NP (Aliased (Expression grp commons schemas params from)) row
1069− -> Query commons schemas params row
1070− -> Expression grp commons schemas params from (nullity 'PGbool)
1071−unsafeRowSubqueryExpression op xs q = UnsafeExpression $
1072− renderSQL (row xs) <+> op <+> parenthesized (renderSQL q)
1074−-- | The right-hand side is a sub`Query`, which must return exactly one column.
1075−-- The left-hand expression is evaluated and compared to each row of the
1076−-- sub`Query` result. The result of `in_` is `true` if any equal subquery row is found.
1077−-- The result is `false` if no equal row is found
1078−-- (including the case where the subquery returns no rows).
1080−-- >>> printSQL $ true `in_` values_ (true `as` #foo)
1081−-- TRUE IN (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1083− :: Expression grp commons schemas params from ty -- ^ expression
1084− -> Query commons schemas params '[alias ::: ty] -- ^ subquery
1085− -> Expression grp commons schemas params from (nullity 'PGbool)
1086−in_ = unsafeSubqueryExpression "IN"
1088−{- | The left-hand side of this form of `rowIn` is a row constructor.
1089−The right-hand side is a sub`Query`,
1090−which must return exactly as many columns as
1091−there are expressions in the left-hand row.
1092−The left-hand expressions are evaluated and compared row-wise to each row
1093−of the subquery result. The result of `rowIn`
1094−is `true` if any equal subquery row is found.
1095−The result is `false` if no equal row is found
1096−(including the case where the subquery returns no rows).
1098−>>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression grp commons schemas params from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1099−>>> printSQL $ myRow `rowIn` values_ myRow
1100−ROW(1, FALSE) IN (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1104− => NP (Aliased (Expression grp commons schemas params from)) row -- ^ row constructor
1105− -> Query commons schemas params row -- ^ subquery
1106− -> Expression grp commons schemas params from (nullity 'PGbool)
1107−rowIn = unsafeRowSubqueryExpression "IN"
1109−-- | >>> printSQL $ true `eqAll` values_ (true `as` #foo)
1110−-- TRUE = ALL (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1112− :: Expression grp commons schemas params from ty -- ^ expression
1113− -> Query commons schemas params '[alias ::: ty] -- ^ subquery
1114− -> Expression grp commons schemas params from (nullity 'PGbool)
1115−eqAll = unsafeSubqueryExpression "= ALL"
1117−-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression grp commons schemas params from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1118−-- >>> printSQL $ myRow `rowEqAll` values_ myRow
1119−-- ROW(1, FALSE) = ALL (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1122− => NP (Aliased (Expression grp commons schemas params from)) row -- ^ row constructor
1123− -> Query commons schemas params row -- ^ subquery
1124− -> Expression grp commons schemas params from (nullity 'PGbool)
1125−rowEqAll = unsafeRowSubqueryExpression "= ALL"
1127−-- | >>> printSQL $ true `eqAny` values_ (true `as` #foo)
1128−-- TRUE = ANY (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1130− :: Expression grp commons schemas params from ty -- ^ expression
1131− -> Query commons schemas params '[alias ::: ty] -- ^ subquery
1132− -> Expression grp commons schemas params from (nullity 'PGbool)
1133−eqAny = unsafeSubqueryExpression "= ANY"
1135−-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression grp commons schemas params from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1136−-- >>> printSQL $ myRow `rowEqAny` values_ myRow
1137−-- ROW(1, FALSE) = ANY (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1140− => NP (Aliased (Expression grp commons schemas params from)) row -- ^ row constructor
1141− -> Query commons schemas params row -- ^ subquery
1142− -> Expression grp commons schemas params from (nullity 'PGbool)
1143−rowEqAny = unsafeRowSubqueryExpression "= ANY"
1145−-- | >>> printSQL $ true `neqAll` values_ (true `as` #foo)
1146−-- TRUE <> ALL (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1148− :: Expression grp commons schemas params from ty -- ^ expression
1149− -> Query commons schemas params '[alias ::: ty] -- ^ subquery
1150− -> Expression grp commons schemas params from (nullity 'PGbool)
1151−neqAll = unsafeSubqueryExpression "<> ALL"
1153−-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression grp commons schemas params from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1154−-- >>> printSQL $ myRow `rowNeqAll` values_ myRow
1155−-- ROW(1, FALSE) <> ALL (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1158− => NP (Aliased (Expression grp commons schemas params from)) row -- ^ row constructor
1159− -> Query commons schemas params row -- ^ subquery
1160− -> Expression grp commons schemas params from (nullity 'PGbool)
1161−rowNeqAll = unsafeRowSubqueryExpression "<> ALL"
1163−-- | >>> printSQL $ true `neqAny` values_ (true `as` #foo)
1164−-- TRUE <> ANY (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1166− :: Expression grp commons schemas params from ty -- ^ expression
1167− -> Query commons schemas params '[alias ::: ty] -- ^ subquery
1168− -> Expression grp commons schemas params from (nullity 'PGbool)
1169−neqAny = unsafeSubqueryExpression "<> ANY"
1171−-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression grp commons schemas params from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1172−-- >>> printSQL $ myRow `rowNeqAny` values_ myRow
1173−-- ROW(1, FALSE) <> ANY (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1176− => NP (Aliased (Expression grp commons schemas params from)) row -- ^ row constructor
1177− -> Query commons schemas params row -- ^ subquery
1178− -> Expression grp commons schemas params from (nullity 'PGbool)
1179−rowNeqAny = unsafeRowSubqueryExpression "<> ANY"
1181−-- | >>> printSQL $ true `allLt` values_ (true `as` #foo)
1182−-- TRUE ALL < (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1184− :: Expression grp commons schemas params from ty -- ^ expression
1185− -> Query commons schemas params '[alias ::: ty] -- ^ subquery
1186− -> Expression grp commons schemas params from (nullity 'PGbool)
1187−allLt = unsafeSubqueryExpression "ALL <"
1189−-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression grp commons schemas params from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1190−-- >>> printSQL $ myRow `rowLtAll` values_ myRow
1191−-- ROW(1, FALSE) ALL < (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1194− => NP (Aliased (Expression grp commons schemas params from)) row -- ^ row constructor
1195− -> Query commons schemas params row -- ^ subquery
1196− -> Expression grp commons schemas params from (nullity 'PGbool)
1197−rowLtAll = unsafeRowSubqueryExpression "ALL <"
1199−-- | >>> printSQL $ true `ltAny` values_ (true `as` #foo)
1200−-- TRUE ANY < (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1202− :: Expression grp commons schemas params from ty -- ^ expression
1203− -> Query commons schemas params '[alias ::: ty] -- ^ subquery
1204− -> Expression grp commons schemas params from (nullity 'PGbool)
1205−ltAny = unsafeSubqueryExpression "ANY <"
1207−-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression grp commons schemas params from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1208−-- >>> printSQL $ myRow `rowLtAll` values_ myRow
1209−-- ROW(1, FALSE) ALL < (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1212− => NP (Aliased (Expression grp commons schemas params from)) row -- ^ row constructor
1213− -> Query commons schemas params row -- ^ subquery
1214− -> Expression grp commons schemas params from (nullity 'PGbool)
1215−rowLtAny = unsafeRowSubqueryExpression "ANY <"
1217−-- | >>> printSQL $ true `lteAll` values_ (true `as` #foo)
1218−-- TRUE <= ALL (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1220− :: Expression grp commons schemas params from ty -- ^ expression
1221− -> Query commons schemas params '[alias ::: ty] -- ^ subquery
1222− -> Expression grp commons schemas params from (nullity 'PGbool)
1223−lteAll = unsafeSubqueryExpression "<= ALL"
1225−-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression grp commons schemas params from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1226−-- >>> printSQL $ myRow `rowLteAll` values_ myRow
1227−-- ROW(1, FALSE) <= ALL (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1230− => NP (Aliased (Expression grp commons schemas params from)) row -- ^ row constructor
1231− -> Query commons schemas params row -- ^ subquery
1232− -> Expression grp commons schemas params from (nullity 'PGbool)
1233−rowLteAll = unsafeRowSubqueryExpression "<= ALL"
1235−-- | >>> printSQL $ true `lteAny` values_ (true `as` #foo)
1236−-- TRUE <= ANY (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1238− :: Expression grp commons schemas params from ty -- ^ expression
1239− -> Query commons schemas params '[alias ::: ty] -- ^ subquery
1240− -> Expression grp commons schemas params from (nullity 'PGbool)
1241−lteAny = unsafeSubqueryExpression "<= ANY"
1243−-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression grp commons schemas params from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1244−-- >>> printSQL $ myRow `rowLteAny` values_ myRow
1245−-- ROW(1, FALSE) <= ANY (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1248− => NP (Aliased (Expression grp commons schemas params from)) row -- ^ row constructor
1249− -> Query commons schemas params row -- ^ subquery
1250− -> Expression grp commons schemas params from (nullity 'PGbool)
1251−rowLteAny = unsafeRowSubqueryExpression "<= ANY"
1253−-- | >>> printSQL $ true `gtAll` values_ (true `as` #foo)
1254−-- TRUE > ALL (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1256− :: Expression grp commons schemas params from ty -- ^ expression
1257− -> Query commons schemas params '[alias ::: ty] -- ^ subquery
1258− -> Expression grp commons schemas params from (nullity 'PGbool)
1259−gtAll = unsafeSubqueryExpression "> ALL"
1261−-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression grp commons schemas params from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1262−-- >>> printSQL $ myRow `rowGtAll` values_ myRow
1263−-- ROW(1, FALSE) > ALL (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1266− => NP (Aliased (Expression grp commons schemas params from)) row -- ^ row constructor
1267− -> Query commons schemas params row -- ^ subquery
1268− -> Expression grp commons schemas params from (nullity 'PGbool)
1269−rowGtAll = unsafeRowSubqueryExpression "> ALL"
1271−-- | >>> printSQL $ true `gtAny` values_ (true `as` #foo)
1272−-- TRUE > ANY (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1274− :: Expression grp commons schemas params from ty -- ^ expression
1275− -> Query commons schemas params '[alias ::: ty] -- ^ subquery
1276− -> Expression grp commons schemas params from (nullity 'PGbool)
1277−gtAny = unsafeSubqueryExpression "> ANY"
1279−-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression grp commons schemas params from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1280−-- >>> printSQL $ myRow `rowGtAny` values_ myRow
1281−-- ROW(1, FALSE) > ANY (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1284− => NP (Aliased (Expression grp commons schemas params from)) row -- ^ row constructor
1285− -> Query commons schemas params row -- ^ subquery
1286− -> Expression grp commons schemas params from (nullity 'PGbool)
1287−rowGtAny = unsafeRowSubqueryExpression "> ANY"
1289−-- | >>> printSQL $ true `gteAll` values_ (true `as` #foo)
1290−-- TRUE >= ALL (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1292− :: Expression grp commons schemas params from ty -- ^ expression
1293− -> Query commons schemas params '[alias ::: ty] -- ^ subquery
1294− -> Expression grp commons schemas params from (nullity 'PGbool)
1295−gteAll = unsafeSubqueryExpression ">= ALL"
1297−-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression grp commons schemas params from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1298−-- >>> printSQL $ myRow `rowGteAll` values_ myRow
1299−-- ROW(1, FALSE) >= ALL (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1302− => NP (Aliased (Expression grp commons schemas params from)) row -- ^ row constructor
1303− -> Query commons schemas params row -- ^ subquery
1304− -> Expression grp commons schemas params from (nullity 'PGbool)
1305−rowGteAll = unsafeRowSubqueryExpression ">= ALL"
1307−-- | >>> printSQL $ true `gteAny` values_ (true `as` #foo)
1308−-- TRUE >= ANY (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1310− :: Expression grp commons schemas params from ty -- ^ expression
1311− -> Query commons schemas params '[alias ::: ty] -- ^ subquery
1312− -> Expression grp commons schemas params from (nullity 'PGbool)
1313−gteAny = unsafeSubqueryExpression ">= ANY"
1315−-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression grp commons schemas params from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1316−-- >>> printSQL $ myRow `rowGteAny` values_ myRow
1317−-- ROW(1, FALSE) >= ANY (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1320− => NP (Aliased (Expression grp commons schemas params from)) row -- ^ row constructor
1321− -> Query commons schemas params row -- ^ subquery
1322− -> Expression grp commons schemas params from (nullity 'PGbool)
1323−rowGteAny = unsafeRowSubqueryExpression ">= ANY"
1325-- | A `CommonTableExpression` is an auxiliary statement in a `with` clause.
1031-- | A `CommonTableExpression` is an auxiliary statement in a `with` clause.
1326data CommonTableExpression statement
1032data CommonTableExpression statement
1327 (schemas :: SchemasType)
1033 (schemas :: SchemasType)
@@ -1343,41 +1049,50 @@ instance
1343 , commons1 ~ (cte ::: common ': commons)
1049 , commons1 ~ (cte ::: common ': commons)
1344 ) => Aliasable cte
1050 ) => Aliasable cte
1345 (statement commons schemas params common)
1051 (statement commons schemas params common)
1346− (AlignedList (CommonTableExpression statement schemas params) commons commons1) where
1052+ (Path (CommonTableExpression statement schemas params) commons commons1) where
1347− statement `as` cte = single (statement `as` cte)
1053+ statement `as` cte = csingleton (statement `as` cte)
1349−-- | render a `CommonTableExpression`.
1055+instance (forall c s p r. RenderSQL (statement c s p r)) => RenderSQL
1350−renderCommonTableExpression
1056+ (CommonTableExpression statement schemas params commons0 commons1) where
1351− :: (forall cs ss ps row. statement cs ss ps row -> ByteString) -- ^ render statement
1057+ renderSQL (CommonTableExpression (statement `As` cte)) =
1352− -> CommonTableExpression statement schemas params commons0 commons1 -> ByteString
1058+ renderSQL cte <+> "AS" <+> parenthesized (renderSQL statement)
1353−renderCommonTableExpression renderStatement
1354− (CommonTableExpression (statement `As` alias)) =
1355− renderSQL alias <+> "AS" <+> parenthesized (renderStatement statement)
1357−-- | render a non-empty `AlignedList` of `CommonTableExpression`s.
1358−renderCommonTableExpressions
1359− :: (forall cs ss ps row. statement cs ss ps row -> ByteString) -- ^ render statement
1360− -> CommonTableExpression statement schemas params commons0 commons1
1361− -> AlignedList (CommonTableExpression statement schemas params) commons1 commons2
1363−renderCommonTableExpressions renderStatement cte ctes =
1364− renderCommonTableExpression renderStatement cte <> case ctes of
1366− cte' :>> ctes' -> "," <+>
1367− renderCommonTableExpressions renderStatement cte' ctes'
1369-- | `with` provides a way to write auxiliary statements for use in a larger query.
1060-- | `with` provides a way to write auxiliary statements for use in a larger query.
1370-- These statements, referred to as `CommonTableExpression`s, can be thought of as
1061-- These statements, referred to as `CommonTableExpression`s, can be thought of as
1371-- defining temporary tables that exist just for one query.
1062-- defining temporary tables that exist just for one query.
1372class With statement where
1063class With statement where
1374− :: AlignedList (CommonTableExpression statement schemas params) commons0 commons1
1065+ :: Path (CommonTableExpression statement schemas params) commons0 commons1
1375 -- ^ common table expressions
1066 -- ^ common table expressions
1376 -> statement commons1 schemas params row
1067 -> statement commons1 schemas params row
1377 -- ^ larger query
1068 -- ^ larger query
1378 -> statement commons0 schemas params row
1069 -> statement commons0 schemas params row
1379−instance With Query where
1070+instance With (Query outer) where
1380 with Done query = query
1071 with Done query = query
1381− with (cte :>> ctes) query = UnsafeQuery $
1072+ with ctes query = UnsafeQuery $
1382− "WITH" <+> renderCommonTableExpressions renderSQL cte ctes
1073+ "WITH" <+> commaSeparated (ctoList renderSQL ctes) <+> renderSQL query
1383− <+> renderSQL query
1074+
1076+>>> import Data.Monoid (Sum (..))
1077+>>> import Data.Int (Int64)
1080+ query :: Query_ schema () (Sum Int64)
1081+ query = withRecursive
1082+ ( values_ ((1 & astype int) `as` #n)
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))
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"
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