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