@@ -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,7 +449,7 @@ 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 `As` col) = renderSQL winFn
516 <+> "OVER" <+> parenthesized (renderSQL winDef)
455 <+> "OVER" <+> parenthesized (renderSQL winDef)
@@ -518,10 +457,6 @@ instance RenderSQL (Selection outer commons grp schemas params from row) where
519 renderCommaSeparated renderOver winFns
458 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
460-- | the `TableExpression` in the `select` command constructs an intermediate
526-- virtual table by possibly combining tables, views, eliminating rows,
461-- virtual table by possibly combining tables, views, eliminating rows,
527-- grouping, etc. This table is finally passed on to processing by
462-- grouping, etc. This table is finally passed on to processing by
@@ -529,100 +464,45 @@ instance IsString
529-- the intermediate table are actually output.
464-- the intermediate table are actually output.
531 :: (SListI row, row ~ (x ': xs))
466 :: (SListI row, row ~ (x ': xs))
532− => Selection outer commons grp schemas params from row
467+ => Selection commons schemas params grp from row
533− -- ^ selection
468+ -- ^ select list
534− -> TableExpression outer commons grp schemas params from
469+ -> TableExpression commons schemas params grp from
535 -- ^ intermediate virtual table
470 -- ^ intermediate virtual table
536− -> Query outer commons schemas params row
471+ -> Query commons schemas params row
537select selection tabexpr = UnsafeQuery $
472select selection tabexpr = UnsafeQuery $
539 <+> renderSQL selection
474 <+> renderSQL selection
540 <+> renderSQL tabexpr
475 <+> 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))
478 :: (SListI row, row ~ (x ': xs))
546− => NP (Aliased (Expression outer commons grp schemas params from)) row
479+ => NP (Aliased (Expression commons schemas params grp from)) row
548− -> TableExpression outer commons grp schemas params from
480+ -> TableExpression commons schemas params grp from
549− -- ^ intermediate virtual table
550− -> Query outer commons schemas params row
481+ -> Query commons schemas params row
551−select_ = select . List
482+select_ list = select (List list)
553-- | After the select list has been processed, the result table can
484-- | After the select list has been processed, the result table can
554-- be subject to the elimination of duplicate rows using `selectDistinct`.
485-- be subject to the elimination of duplicate rows using `selectDistinct`.
555selectDistinct
486selectDistinct
556 :: (SListI columns, columns ~ (col ': cols))
487 :: (SListI columns, columns ~ (col ': cols))
557− => Selection outer commons grp schemas params from columns
488+ => Selection commons schemas params 'Ungrouped from columns
558− -- ^ selection
489+ -- ^ select list
559− -> TableExpression outer commons grp schemas params from
490+ -> TableExpression commons schemas params 'Ungrouped from
560 -- ^ intermediate virtual table
491 -- ^ intermediate virtual table
561− -> Query outer commons schemas params columns
492+ -> Query commons schemas params columns
562selectDistinct selection tabexpr = UnsafeQuery $
493selectDistinct selection tabexpr = UnsafeQuery $
563 "SELECT DISTINCT"
494 "SELECT DISTINCT"
564 <+> renderSQL selection
495 <+> renderSQL selection
565 <+> renderSQL tabexpr
496 <+> renderSQL tabexpr
567−-- | Like `selectDistinct` but takes an `NP` list of `Expression`s instead
568−-- of a general `Selection`.
569selectDistinct_
498selectDistinct_
570 :: (SListI columns, columns ~ (col ': cols))
499 :: (SListI columns, columns ~ (col ': cols))
571− => NP (Aliased (Expression outer commons grp schemas params from)) columns
500+ => NP (Aliased (Expression commons schemas params 'Ungrouped from)) columns
572 -- ^ select list
501 -- ^ select list
573− -> TableExpression outer commons grp schemas params from
502+ -> TableExpression commons schemas params 'Ungrouped from
574 -- ^ intermediate virtual table
503 -- ^ intermediate virtual table
575− -> Query outer commons schemas params columns
504+ -> Query commons schemas params columns
576−selectDistinct_ = selectDistinct . List
505+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
507-- | `values` computes a row value or set of row values
628-- specified by value expressions. It is most commonly used
508-- specified by value expressions. It is most commonly used
@@ -630,16 +510,16 @@ selectDistinctOn_ distincts = selectDistinctOn distincts . List
630-- but it can be used on its own.
510-- but it can be used on its own.
632-- >>> type Row = '["a" ::: 'NotNull 'PGint4, "b" ::: 'NotNull 'PGtext]
512-- >>> type Row = '["a" ::: 'NotNull 'PGint4, "b" ::: 'NotNull 'PGtext]
633−-- >>> let query = values (1 `as` #a :* "one" `as` #b) [] :: Query outer commons schemas '[] Row
513+-- >>> let query = values (1 `as` #a :* "one" `as` #b) [] :: Query commons schemas '[] Row
634-- >>> printSQL query
514-- >>> printSQL query
635-- SELECT * FROM (VALUES (1, E'one')) AS t ("a", "b")
515-- SELECT * FROM (VALUES (1, E'one')) AS t ("a", "b")
637 :: SListI cols
517 :: SListI cols
638− => NP (Aliased (Expression outer commons 'Ungrouped schemas params '[] )) cols
518+ => NP (Aliased (Expression commons schemas params 'Ungrouped '[] )) cols
639− -> [NP (Aliased (Expression outer commons 'Ungrouped schemas params '[] )) cols]
519+ -> [NP (Aliased (Expression commons schemas params 'Ungrouped '[] )) cols]
640 -- ^ When more than one row is specified, all the rows must
520 -- ^ When more than one row is specified, all the rows must
641 -- must have the same number of elements
521 -- must have the same number of elements
642− -> Query outer commons schemas params cols
522+ -> Query commons schemas params cols
643values rw rws = UnsafeQuery $ "SELECT * FROM"
523values rw rws = UnsafeQuery $ "SELECT * FROM"
644 <+> parenthesized (
524 <+> parenthesized (
@@ -650,7 +530,7 @@ values rw rws = UnsafeQuery $ "SELECT * FROM"
650 <+> parenthesized (renderCommaSeparated renderAliasPart rw)
530 <+> parenthesized (renderCommaSeparated renderAliasPart rw)
652 renderAliasPart, renderValuePart
532 renderAliasPart, renderValuePart
653− :: Aliased (Expression outer commons 'Ungrouped schemas params '[] ) ty -> ByteString
533+ :: Aliased (Expression commons schemas params 'Ungrouped '[] ) ty -> ByteString
654 renderAliasPart (_ `As` name) = renderSQL name
534 renderAliasPart (_ `As` name) = renderSQL name
655 renderValuePart (value `As` _) = renderSQL value
535 renderValuePart (value `As` _) = renderSQL value
@@ -658,9 +538,9 @@ values rw rws = UnsafeQuery $ "SELECT * FROM"
658-- specified by value expressions.
538-- specified by value expressions.
660 :: SListI cols
540 :: SListI cols
661− => NP (Aliased (Expression outer commons 'Ungrouped schemas params '[] )) cols
541+ => NP (Aliased (Expression commons schemas params 'Ungrouped '[] )) cols
662 -- ^ one row of values
542 -- ^ one row of values
663− -> Query outer commons schemas params cols
543+ -> Query commons schemas params cols
664values_ rw = values rw []
544values_ rw = values rw []
666{-----------------------------------------
546{-----------------------------------------
@@ -674,17 +554,16 @@ Table Expressions
674-- to a table on disk, a so-called base table, but more complex expressions
554-- 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.
555-- can be used to modify or combine base tables in various ways.
676data TableExpression
556data TableExpression
678 (commons :: FromType)
557 (commons :: FromType)
680 (schemas :: SchemasType)
558 (schemas :: SchemasType)
681 (params :: [NullityType])
559 (params :: [NullityType])
682 (from :: FromType)
561 (from :: FromType)
683 = TableExpression
562 = TableExpression
684− { fromClause :: FromClause outer commons schemas params from
563+ { fromClause :: FromClause commons schemas params from
685 -- ^ A table reference that can be a table name, or a derived table such
564 -- ^ 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.
565 -- as a subquery, a @JOIN@ construct, or complex combinations of these.
687− , whereClause :: [Condition outer commons 'Ungrouped schemas params from]
566+ , whereClause :: [Condition commons schemas params 'Ungrouped from]
688 -- ^ optional search coditions, combined with `.&&`. After the processing
567 -- ^ optional search coditions, combined with `.&&`. After the processing
689 -- of the `fromClause` is done, each row of the derived virtual table
568 -- of the `fromClause` is done, each row of the derived virtual table
690 -- is checked against the search condition. If the result of the
569 -- is checked against the search condition. If the result of the
@@ -700,13 +579,13 @@ data TableExpression
700 -- set of rows having common values into one group row that represents all
579 -- 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
580 -- rows in the group. This is done to eliminate redundancy in the output
702 -- and/or compute aggregates that apply to these groups.
581 -- and/or compute aggregates that apply to these groups.
703− , havingClause :: HavingClause outer commons grp schemas params from
582+ , havingClause :: HavingClause commons schemas params grp from
704 -- ^ If a table has been grouped using `groupBy`, but only certain groups
583 -- ^ If a table has been grouped using `groupBy`, but only certain groups
705 -- are of interest, the `havingClause` can be used, much like a
584 -- are of interest, the `havingClause` can be used, much like a
706 -- `whereClause`, to eliminate groups from the result. Expressions in the
585 -- `whereClause`, to eliminate groups from the result. Expressions in the
707 -- `havingClause` can refer both to grouped expressions and to ungrouped
586 -- `havingClause` can refer both to grouped expressions and to ungrouped
708 -- expressions (which necessarily involve an aggregate function).
587 -- expressions (which necessarily involve an aggregate function).
709− , orderByClause :: [SortExpression outer commons grp schemas params from]
588+ , orderByClause :: [SortExpression commons schemas params grp from]
710 -- ^ The `orderByClause` is for optional sorting. When more than one
589 -- ^ The `orderByClause` is for optional sorting. When more than one
711 -- `SortExpression` is specified, the later (right) values are used to sort
590 -- `SortExpression` is specified, the later (right) values are used to sort
712 -- rows that are equal according to the earlier (left) values.
591 -- rows that are equal according to the earlier (left) values.
@@ -716,14 +595,14 @@ data TableExpression
716 -- will be returned (but possibly fewer, if the query itself yields
595 -- will be returned (but possibly fewer, if the query itself yields
717 -- fewer rows).
596 -- fewer rows).
718 , offsetClause :: [Word64]
597 , offsetClause :: [Word64]
719− -- ^ The `offsetClause` is combined with `Prelude.+` to give an offset count
598+ -- ^ The `offsetClause` is combined with `+` to give an offset count
720 -- if nonempty. The offset count says to skip that many rows before
599 -- 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
600 -- beginning to return rows. The rows are skipped before the limit count
722 -- is applied.
601 -- is applied.
723− } deriving (GHC.Generic)
602+ }
725-- | Render a `TableExpression`
604-- | Render a `TableExpression`
726−instance RenderSQL (TableExpression outer commons grp schemas params from) where
605+instance RenderSQL (TableExpression commons schemas params grp from) where
727 renderSQL
606 renderSQL
728 (TableExpression frm' whs' grps' hvs' srts' lims' offs') = mconcat
607 (TableExpression frm' whs' grps' hvs' srts' lims' offs') = mconcat
729 [ "FROM ", renderSQL frm'
608 [ "FROM ", renderSQL frm'
@@ -732,7 +611,8 @@ instance RenderSQL (TableExpression outer commons grp schemas params from) where
732 , renderSQL hvs'
611 , renderSQL hvs'
733 , renderOrderByClause srts'
612 , renderOrderByClause srts'
734 , renderLimits lims'
613 , renderLimits lims'
735− , renderOffsets offs' ]
614+ , renderOffsets offs'
737 renderWheres = \case
617 renderWheres = \case
@@ -752,33 +632,33 @@ instance RenderSQL (TableExpression outer commons grp schemas params from) where
752-- | A `from` generates a `TableExpression` from a table reference that can be
632-- | 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,
633-- 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_`,
634-- or complex combinations of these. A `from` may be transformed by `where_`,
755−-- `groupBy`, `having`, `orderBy`, `limit` and `offset`, using the `&` operator
635+-- `group`, `having`, `orderBy`, `limit` and `offset`, using the `&` operator
756-- to match the left-to-right sequencing of their placement in SQL.
636-- to match the left-to-right sequencing of their placement in SQL.
758− :: FromClause outer commons schemas params from -- ^ table reference
638+ :: FromClause commons schemas params from -- ^ table reference
759− -> TableExpression outer commons 'Ungrouped schemas params from
639+ -> TableExpression commons schemas params 'Ungrouped from
760−from tab = TableExpression tab [] noGroups NoHaving [] [] []
640+from rels = TableExpression rels [] NoGroups NoHaving [] [] []
762-- | A `where_` is an endomorphism of `TableExpression`s which adds a
642-- | A `where_` is an endomorphism of `TableExpression`s which adds a
763-- search condition to the `whereClause`.
643-- search condition to the `whereClause`.
765− :: Condition outer commons 'Ungrouped schemas params from -- ^ filtering condition
645+ :: Condition commons schemas params 'Ungrouped from -- ^ filtering condition
766− -> TableExpression outer commons grp schemas params from
646+ -> TableExpression commons schemas params grp from
767− -> TableExpression outer commons grp schemas params from
647+ -> TableExpression commons schemas params grp from
768where_ wh rels = rels {whereClause = wh : whereClause rels}
648where_ wh rels = rels {whereClause = wh : whereClause rels}
770-- | A `groupBy` is a transformation of `TableExpression`s which switches
650-- | A `groupBy` is a transformation of `TableExpression`s which switches
771−-- its `Grouping` from `Ungrouped` to `Grouped`. Use @groupBy Nil@ to perform
651+-- its `Grouping` from `Ungrouped` to `Grouped`. Use @group Nil@ to perform
772-- a "grand total" aggregation query.
652-- a "grand total" aggregation query.
774 :: SListI bys
654 :: SListI bys
775 => NP (By from) bys -- ^ grouped columns
655 => NP (By from) bys -- ^ grouped columns
776− -> TableExpression outer commons 'Ungrouped schemas params from
656+ -> TableExpression commons schemas params 'Ungrouped from
777− -> TableExpression outer commons ('Grouped bys) schemas params from
657+ -> TableExpression commons schemas params ('Grouped bys) from
778groupBy bys rels = TableExpression
658groupBy bys rels = TableExpression
779 { fromClause = fromClause rels
659 { fromClause = fromClause rels
780 , whereClause = whereClause rels
660 , whereClause = whereClause rels
781− , groupByClause = group bys
661+ , groupByClause = Group bys
782 , havingClause = Having []
662 , havingClause = Having []
783 , orderByClause = []
663 , orderByClause = []
784 , limitClause = limitClause rels
664 , limitClause = limitClause rels
@@ -788,9 +668,9 @@ groupBy bys rels = TableExpression
788-- | A `having` is an endomorphism of `TableExpression`s which adds a
668-- | A `having` is an endomorphism of `TableExpression`s which adds a
789-- search condition to the `havingClause`.
669-- search condition to the `havingClause`.
791− :: Condition outer commons ('Grouped bys) schemas params from -- ^ having condition
671+ :: Condition commons schemas params ('Grouped bys) from -- ^ having condition
792− -> TableExpression outer commons ('Grouped bys) schemas params from
672+ -> TableExpression commons schemas params ('Grouped bys) from
793− -> TableExpression outer commons ('Grouped bys) schemas params from
673+ -> TableExpression commons schemas params ('Grouped bys) from
794having hv rels = rels
674having hv rels = rels
795 { havingClause = case havingClause rels of Having hvs -> Having (hv:hvs) }
675 { havingClause = case havingClause rels of Having hvs -> Having (hv:hvs) }
@@ -801,18 +681,159 @@ instance OrderBy TableExpression where
801-- `limitClause`.
681-- `limitClause`.
803 :: Word64 -- ^ limit parameter
683 :: Word64 -- ^ limit parameter
804− -> TableExpression outer commons grp schemas params from
684+ -> TableExpression commons schemas params grp from
805− -> TableExpression outer commons grp schemas params from
685+ -> TableExpression commons schemas params grp from
806limit lim rels = rels {limitClause = lim : limitClause rels}
686limit lim rels = rels {limitClause = lim : limitClause rels}
808-- | An `offset` is an endomorphism of `TableExpression`s which adds to the
688-- | An `offset` is an endomorphism of `TableExpression`s which adds to the
809-- `offsetClause`.
689-- `offsetClause`.
811 :: Word64 -- ^ offset parameter
691 :: Word64 -- ^ offset parameter
812− -> TableExpression outer commons grp schemas params from
692+ -> TableExpression commons schemas params grp from
813− -> TableExpression outer commons grp schemas params from
693+ -> TableExpression commons schemas params grp from
814offset off rels = rels {offsetClause = off : offsetClause rels}
694offset off rels = rels {offsetClause = off : offsetClause rels}
696+{-----------------------------------------
698+-----------------------------------------}
702+ -> Expression commons schemas params 'Ungrouped '[] ty
703+ -> Query commons schemas params row
704+unsafeSetOfFunction fun expr = UnsafeQuery $
705+ "SELECT * FROM " <> fun <> "(" <> renderSQL expr <> ")"
707+-- | Expands the outermost JSON object into a set of key/value pairs.
709+ :: Expression commons schemas params 'Ungrouped '[] (nullity 'PGjson) -- ^ json object
710+ -> Query commons schemas params
711+ '["key" ::: 'NotNull 'PGtext, "value" ::: 'NotNull 'PGjson]
712+jsonEach = unsafeSetOfFunction "json_each"
714+-- | Expands the outermost binary JSON object into a set of key/value pairs.
716+ :: Expression commons schemas params 'Ungrouped '[] (nullity 'PGjsonb) -- ^ jsonb object
717+ -> Query commons schemas params
718+ '["key" ::: 'NotNull 'PGtext, "value" ::: 'NotNull 'PGjsonb]
719+jsonbEach = unsafeSetOfFunction "jsonb_each"
721+-- | Expands the outermost JSON object into a set of key/value pairs.
723+ :: Expression commons schemas params 'Ungrouped '[] (nullity 'PGjson) -- ^ json object
724+ -> Query commons schemas params
725+ '["key" ::: 'NotNull 'PGtext, "value" ::: 'NotNull 'PGtext]
726+jsonEachAsText = unsafeSetOfFunction "json_each_text"
728+-- | Expands the outermost binary JSON object into a set of key/value pairs.
730+ :: Expression commons schemas params 'Ungrouped '[] (nullity 'PGjsonb) -- ^ jsonb object
731+ -> Query commons schemas params
732+ '["key" ::: 'NotNull 'PGtext, "value" ::: 'NotNull 'PGtext]
733+jsonbEachAsText = unsafeSetOfFunction "jsonb_each_text"
735+-- | Returns set of keys in the outermost JSON object.
737+ :: Expression commons schemas params 'Ungrouped '[] (nullity 'PGjson) -- ^ json object
738+ -> Query commons schemas params '["json_object_keys" ::: 'NotNull 'PGtext]
739+jsonObjectKeys = unsafeSetOfFunction "json_object_keys"
741+-- | Returns set of keys in the outermost JSON object.
743+ :: Expression commons schemas params 'Ungrouped '[] (nullity 'PGjsonb) -- ^ jsonb object
744+ -> Query commons schemas params '["jsonb_object_keys" ::: 'NotNull 'PGtext]
745+jsonbObjectKeys = unsafeSetOfFunction "jsonb_object_keys"
747+unsafePopulateFunction
749+ -> TypeExpression schemas (nullity ('PGcomposite row))
750+ -> Expression commons schemas params 'Ungrouped '[] ty
751+ -> Query commons schemas params row
752+unsafePopulateFunction fun ty expr = UnsafeQuery $
753+ "SELECT * FROM " <> fun <> "("
754+ <> "null::" <> renderSQL ty <> ", "
755+ <> renderSQL expr <> ")"
757+-- | Expands the JSON expression to a row whose columns match the record
758+-- type defined by the given table.
760+ :: TypeExpression schemas (nullity ('PGcomposite row)) -- ^ row type
761+ -> Expression commons schemas params 'Ungrouped '[] (nullity 'PGjson) -- ^ json object
762+ -> Query commons schemas params row
763+jsonPopulateRecord = unsafePopulateFunction "json_populate_record"
765+-- | Expands the binary JSON expression to a row whose columns match the record
766+-- type defined by the given table.
768+ :: TypeExpression schemas (nullity ('PGcomposite row)) -- ^ row type
769+ -> Expression commons schemas params 'Ungrouped '[] (nullity 'PGjsonb) -- ^ jsonb object
770+ -> Query commons schemas params row
771+jsonbPopulateRecord = unsafePopulateFunction "jsonb_populate_record"
773+-- | Expands the outermost array of objects in the given JSON expression to a
774+-- set of rows whose columns match the record type defined by the given table.
775+jsonPopulateRecordSet
776+ :: TypeExpression schemas (nullity ('PGcomposite row)) -- ^ row type
777+ -> Expression commons schemas params 'Ungrouped '[] (nullity 'PGjson) -- ^ json array
778+ -> Query commons schemas params row
779+jsonPopulateRecordSet = unsafePopulateFunction "json_populate_record_set"
781+-- | Expands the outermost array of objects in the given binary JSON expression
782+-- to a set of rows whose columns match the record type defined by the given
784+jsonbPopulateRecordSet
785+ :: TypeExpression schemas (nullity ('PGcomposite row)) -- ^ row type
786+ -> Expression commons schemas params 'Ungrouped '[] (nullity 'PGjsonb) -- ^ jsonb array
787+ -> Query commons schemas params row
788+jsonbPopulateRecordSet = unsafePopulateFunction "jsonb_populate_record_set"
791+ :: (SListI record, json `In` PGJsonType)
793+ -> Expression commons schemas params 'Ungrouped '[] (nullity json)
794+ -> NP (Aliased (TypeExpression schemas)) record
795+ -> Query commons schemas params record
796+unsafeRecordFunction fun expr types = UnsafeQuery $
797+ "SELECT * FROM " <> fun <> "("
798+ <> renderSQL expr <> ")"
799+ <+> "AS" <+> "x" <> parenthesized (renderCommaSeparated renderTy types)
801+ renderTy :: Aliased (TypeExpression schemas) ty -> ByteString
802+ renderTy (ty `As` alias) =
803+ renderSQL alias <+> renderSQL ty
805+-- | Builds an arbitrary record from a JSON object.
808+ => Expression commons schemas params 'Ungrouped '[] (nullity 'PGjson) -- ^ json object
809+ -> NP (Aliased (TypeExpression schemas)) record -- ^ record types
810+ -> Query commons schemas params record
811+jsonToRecord = unsafeRecordFunction "json_to_record"
813+-- | Builds an arbitrary record from a binary JSON object.
816+ => Expression commons schemas params 'Ungrouped '[] (nullity 'PGjsonb) -- ^ jsonb object
817+ -> NP (Aliased (TypeExpression schemas)) record -- ^ record types
818+ -> Query commons schemas params record
819+jsonbToRecord = unsafeRecordFunction "jsonb_to_record"
821+-- | Builds an arbitrary set of records from a JSON array of objects.
824+ => Expression commons schemas params 'Ungrouped '[] (nullity 'PGjson) -- ^ json array
825+ -> NP (Aliased (TypeExpression schemas)) record -- ^ record types
826+ -> Query commons schemas params record
827+jsonToRecordSet = unsafeRecordFunction "json_to_record_set"
829+-- | Builds an arbitrary set of records from a binary JSON array of objects.
832+ => Expression commons schemas params 'Ungrouped '[] (nullity 'PGjsonb) -- ^ jsonb array
833+ -> NP (Aliased (TypeExpression schemas)) record -- ^ record types
834+ -> Query commons schemas params record
835+jsonbToRecordSet = unsafeRecordFunction "jsonb_to_record_set"
816{-----------------------------------------
837{-----------------------------------------
817FROM clauses
838FROM clauses
818-----------------------------------------}
839-----------------------------------------}
@@ -821,59 +842,53 @@ FROM clauses
821A `FromClause` can be a table name, or a derived table such
842A `FromClause` can be a table name, or a derived table such
822as a subquery, a @JOIN@ construct, or complex combinations of these.
843as a subquery, a @JOIN@ construct, or complex combinations of these.
824−newtype FromClause outer commons schemas params from
845+newtype FromClause commons schemas params from
825 = UnsafeFromClause { renderFromClause :: ByteString }
846 = UnsafeFromClause { renderFromClause :: ByteString }
826 deriving (GHC.Generic,Show,Eq,Ord,NFData)
847 deriving (GHC.Generic,Show,Eq,Ord,NFData)
827−instance RenderSQL (FromClause outer commons schemas params from) where
848+instance RenderSQL (FromClause commons schemas params from) where
828 renderSQL = renderFromClause
849 renderSQL = renderFromClause
830-- | A real `table` is a table from the database.
851-- | A real `table` is a table from the database.
832 :: (Has sch schemas schema, Has tab schema ('Table table))
853 :: (Has sch schemas schema, Has tab schema ('Table table))
833 => Aliased (QualifiedAlias sch) (alias ::: tab)
854 => Aliased (QualifiedAlias sch) (alias ::: tab)
834− -> FromClause outer commons schemas params '[alias ::: TableToRow table]
855+ -> FromClause commons schemas params '[alias ::: TableToRow table]
835table (tab `As` alias) = UnsafeFromClause $
856table (tab `As` alias) = UnsafeFromClause $
836 renderSQL tab <+> "AS" <+> renderSQL alias
857 renderSQL tab <+> "AS" <+> renderSQL alias
838-- | `subquery` derives a table from a `Query`.
859-- | `subquery` derives a table from a `Query`.
840− :: Aliased (Query outer commons schemas params) query
861+ :: Aliased (Query commons schemas params) query
841− -> FromClause outer commons schemas params '[query]
862+ -> FromClause commons schemas params '[query]
842−subquery = UnsafeFromClause . renderAliased (parenthesized . renderSQL)
863+subquery = UnsafeFromClause . renderAliased (parenthesized . renderQuery)
844-- | `view` derives a table from a `View`.
865-- | `view` derives a table from a `View`.
846 :: (Has sch schemas schema, Has vw schema ('View view))
867 :: (Has sch schemas schema, Has vw schema ('View view))
847 => Aliased (QualifiedAlias sch) (alias ::: vw)
868 => Aliased (QualifiedAlias sch) (alias ::: vw)
848− -> FromClause outer commons schemas params '[alias ::: view]
869+ -> FromClause commons schemas params '[alias ::: view]
849view (vw `As` alias) = UnsafeFromClause $
870view (vw `As` alias) = UnsafeFromClause $
850 renderSQL vw <+> "AS" <+> renderSQL alias
871 renderSQL vw <+> "AS" <+> renderSQL alias
852−-- | `common` derives a table from a common table expression.
854 :: Has cte commons common
874 :: Has cte commons common
855 => Aliased Alias (alias ::: cte)
875 => Aliased Alias (alias ::: cte)
856− -> FromClause outer commons schemas params '[alias ::: common]
876+ -> FromClause commons schemas params '[alias ::: common]
857common (cte `As` alias) = UnsafeFromClause $
877common (cte `As` alias) = UnsafeFromClause $
858 renderSQL cte <+> "AS" <+> renderSQL alias
878 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
880+{- | @left & crossJoin right@. For every possible combination of rows from
866−@left@ and @right@ (i.e., a Cartesian product), the joined table will contain
881+ @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@.
882+ 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
883+ If the tables have @n@ and @m@ rows respectively, the joined table will
869−have @n * m@ rows.
884+ have @n * m@ rows.
872− :: FromClause outer commons schemas params right
887+ :: FromClause commons schemas params right
873 -- ^ right
888 -- ^ right
874− -> FromClause outer commons schemas params left
889+ -> FromClause commons schemas params left
875 -- ^ left
890 -- ^ left
876− -> FromClause outer commons schemas params (Join left right)
891+ -> FromClause commons schemas params (Join left right)
877crossJoin right left = UnsafeFromClause $
892crossJoin right left = UnsafeFromClause $
878 renderSQL left <+> "CROSS JOIN" <+> renderSQL right
893 renderSQL left <+> "CROSS JOIN" <+> renderSQL right
@@ -881,13 +896,13 @@ crossJoin right left = UnsafeFromClause $
881the @on@ condition.
896the @on@ condition.
884− :: FromClause outer commons schemas params right
899+ :: FromClause commons schemas params right
885 -- ^ right
900 -- ^ right
886− -> Condition outer commons 'Ungrouped schemas params (Join left right)
901+ -> Condition commons schemas params 'Ungrouped (Join left right)
887 -- ^ @on@ condition
902 -- ^ @on@ condition
888− -> FromClause outer commons schemas params left
903+ -> FromClause commons schemas params left
889 -- ^ left
904 -- ^ left
890− -> FromClause outer commons schemas params (Join left right)
905+ -> FromClause commons schemas params (Join left right)
891innerJoin right on left = UnsafeFromClause $
906innerJoin right on left = UnsafeFromClause $
892 renderSQL left <+> "INNER JOIN" <+> renderSQL right
907 renderSQL left <+> "INNER JOIN" <+> renderSQL right
893 <+> "ON" <+> renderSQL on
908 <+> "ON" <+> renderSQL on
@@ -898,13 +913,13 @@ innerJoin right on left = UnsafeFromClause $
898 Thus, the joined table always has at least one row for each row in @left@.
913 Thus, the joined table always has at least one row for each row in @left@.
900leftOuterJoin
915leftOuterJoin
901− :: FromClause outer commons schemas params right
916+ :: FromClause commons schemas params right
902 -- ^ right
917 -- ^ right
903− -> Condition outer commons 'Ungrouped schemas params (Join left right)
918+ -> Condition commons schemas params 'Ungrouped (Join left right)
904 -- ^ @on@ condition
919 -- ^ @on@ condition
905− -> FromClause outer commons schemas params left
920+ -> FromClause commons schemas params left
906 -- ^ left
921 -- ^ left
907− -> FromClause outer commons schemas params (Join left (NullifyFrom right))
922+ -> FromClause commons schemas params (Join left (NullifyFrom right))
908leftOuterJoin right on left = UnsafeFromClause $
923leftOuterJoin right on left = UnsafeFromClause $
909 renderSQL left <+> "LEFT OUTER JOIN" <+> renderSQL right
924 renderSQL left <+> "LEFT OUTER JOIN" <+> renderSQL right
910 <+> "ON" <+> renderSQL on
925 <+> "ON" <+> renderSQL on
@@ -916,13 +931,13 @@ leftOuterJoin right on left = UnsafeFromClause $
916 have a row for each row in @right@.
931 have a row for each row in @right@.
918rightOuterJoin
933rightOuterJoin
919− :: FromClause outer commons schemas params right
934+ :: FromClause commons schemas params right
920 -- ^ right
935 -- ^ right
921− -> Condition outer commons 'Ungrouped schemas params (Join left right)
936+ -> Condition commons schemas params 'Ungrouped (Join left right)
922 -- ^ @on@ condition
937 -- ^ @on@ condition
923− -> FromClause outer commons schemas params left
938+ -> FromClause commons schemas params left
924 -- ^ left
939 -- ^ left
925− -> FromClause outer commons schemas params (Join (NullifyFrom left) right)
940+ -> FromClause commons schemas params (Join (NullifyFrom left) right)
926rightOuterJoin right on left = UnsafeFromClause $
941rightOuterJoin right on left = UnsafeFromClause $
927 renderSQL left <+> "RIGHT OUTER JOIN" <+> renderSQL right
942 renderSQL left <+> "RIGHT OUTER JOIN" <+> renderSQL right
928 <+> "ON" <+> renderSQL on
943 <+> "ON" <+> renderSQL on
@@ -935,13 +950,13 @@ rightOuterJoin right on left = UnsafeFromClause $
935 is added.
950 is added.
937fullOuterJoin
952fullOuterJoin
938− :: FromClause outer commons schemas params right
953+ :: FromClause commons schemas params right
939 -- ^ right
954 -- ^ right
940− -> Condition outer commons 'Ungrouped schemas params (Join left right)
955+ -> Condition commons schemas params 'Ungrouped (Join left right)
941 -- ^ @on@ condition
956 -- ^ @on@ condition
942− -> FromClause outer commons schemas params left
957+ -> FromClause commons schemas params left
943 -- ^ left
958 -- ^ left
944− -> FromClause outer commons schemas params
959+ -> FromClause commons schemas params
945 (Join (NullifyFrom left) (NullifyFrom right))
960 (Join (NullifyFrom left) (NullifyFrom right))
946fullOuterJoin right on left = UnsafeFromClause $
961fullOuterJoin right on left = UnsafeFromClause $
947 renderSQL left <+> "FULL OUTER JOIN" <+> renderSQL right
962 renderSQL left <+> "FULL OUTER JOIN" <+> renderSQL right
@@ -951,7 +966,7 @@ fullOuterJoin right on left = UnsafeFromClause $
952-----------------------------------------}
967-----------------------------------------}
954−-- | `By`s are used in `groupBy` to reference a list of columns which are then
969+-- | `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
970-- 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
971-- in all the columns listed. @By \#col@ will reference an unambiguous
957-- column @col@; otherwise @By2 (\#tab \! \#col)@ will reference a table
972-- column @col@; otherwise @By2 (\#tab \! \#col)@ will reference a table
@@ -992,42 +1007,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
1007-- done on @NoGroups@ while all output `Expression`s must be aggregated
993-- in @Group Nil@. In general, all output `Expression`s in the
1008-- in @Group Nil@. In general, all output `Expression`s in the
994-- complement of @bys@ must be aggregated in @Group bys@.
1009-- complement of @bys@ must be aggregated in @Group bys@.
995−newtype GroupByClause grp from = UnsafeGroupByClause
1010+data GroupByClause grp from where
996− { renderGroupByClause :: ByteString }
1011+ NoGroups :: GroupByClause 'Ungrouped from
997− deriving (GHC.Generic,Show,Eq,Ord,NFData)
1012+ Group
1014+ => NP (By from) bys
1015+ -> GroupByClause ('Grouped bys) from
1017+-- | Renders a `GroupByClause`.
998instance RenderSQL (GroupByClause grp from) where
1018instance RenderSQL (GroupByClause grp from) where
999− renderSQL = renderGroupByClause
1019+ renderSQL = \case
1000−noGroups :: GroupByClause 'Ungrouped from
1020+ NoGroups -> ""
1001−noGroups = UnsafeGroupByClause ""
1004− => NP (By from) bys
1005− -> GroupByClause ('Grouped bys) from
1006−group bys = UnsafeGroupByClause $ case bys of
1007− Nil -> ""
1021+ Group Nil -> ""
1008− bys' -> " GROUP BY" <+> renderCommaSeparated renderSQL bys'
1022+ Group bys -> " GROUP BY" <+> renderCommaSeparated renderSQL bys
1010-- | A `HavingClause` is used to eliminate groups that are not of interest.
1024-- | A `HavingClause` is used to eliminate groups that are not of interest.
1011-- An `Ungrouped` `TableExpression` may only use `NoHaving` while a `Grouped`
1025-- An `Ungrouped` `TableExpression` may only use `NoHaving` while a `Grouped`
1012-- `TableExpression` must use `Having` whose conditions are combined with
1026-- `TableExpression` must use `Having` whose conditions are combined with
1013-- `.&&`.
1027-- `.&&`.
1014−data HavingClause outer commons grp schemas params from where
1028+data HavingClause commons schemas params grp from where
1015− NoHaving :: HavingClause outer commons 'Ungrouped schemas params from
1029+ NoHaving :: HavingClause commons schemas params 'Ungrouped from
1017− :: [Condition outer commons ('Grouped bys) schemas params from]
1031+ :: [Condition commons schemas params ('Grouped bys) from]
1018− -> HavingClause outer commons ('Grouped bys) schemas params from
1032+ -> HavingClause commons schemas params ('Grouped bys) from
1019−deriving instance Show (HavingClause outer commons grp schemas params from)
1033+deriving instance Show (HavingClause commons schemas params grp from)
1020−deriving instance Eq (HavingClause outer commons grp schemas params from)
1034+deriving instance Eq (HavingClause commons schemas params grp from)
1021−deriving instance Ord (HavingClause outer commons grp schemas params from)
1035+deriving instance Ord (HavingClause commons schemas params grp from)
1023-- | Render a `HavingClause`.
1037-- | Render a `HavingClause`.
1024−instance RenderSQL (HavingClause outer commons grp schemas params from) where
1038+instance RenderSQL (HavingClause commons schemas params grp from) where
1025 renderSQL = \case
1039 renderSQL = \case
1026 NoHaving -> ""
1040 NoHaving -> ""
1027 Having [] -> ""
1041 Having [] -> ""
1028 Having conditions ->
1042 Having conditions ->
1029 " HAVING" <+> commaSeparated (renderSQL <$> conditions)
1043 " HAVING" <+> commaSeparated (renderSQL <$> conditions)
1045+unsafeSubqueryExpression
1047+ -> Expression commons schemas params grp from ty
1048+ -> Query commons schemas params '[alias ::: ty]
1049+ -> Expression commons schemas params grp from (nullity 'PGbool)
1050+unsafeSubqueryExpression op x q = UnsafeExpression $
1051+ renderSQL x <+> op <+> parenthesized (renderSQL q)
1053+unsafeRowSubqueryExpression
1056+ -> NP (Aliased (Expression commons schemas params grp from)) row
1057+ -> Query commons schemas params row
1058+ -> Expression commons schemas params grp from (nullity 'PGbool)
1059+unsafeRowSubqueryExpression op xs q = UnsafeExpression $
1060+ renderSQL (row xs) <+> op <+> parenthesized (renderSQL q)
1062+-- | The right-hand side is a sub`Query`, which must return exactly one column.
1063+-- The left-hand expression is evaluated and compared to each row of the
1064+-- sub`Query` result. The result of `in_` is `true` if any equal subquery row is found.
1065+-- The result is `false` if no equal row is found
1066+-- (including the case where the subquery returns no rows).
1068+-- >>> printSQL $ true `in_` values_ (true `as` #foo)
1069+-- TRUE IN (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1071+ :: Expression commons schemas params grp from ty -- ^ expression
1072+ -> Query commons schemas params '[alias ::: ty] -- ^ subquery
1073+ -> Expression commons schemas params grp from (nullity 'PGbool)
1074+in_ = unsafeSubqueryExpression "IN"
1076+{- | The left-hand side of this form of `rowIn` is a row constructor.
1077+The right-hand side is a sub`Query`,
1078+which must return exactly as many columns as
1079+there are expressions in the left-hand row.
1080+The left-hand expressions are evaluated and compared row-wise to each row
1081+of the subquery result. The result of `rowIn`
1082+is `true` if any equal subquery row is found.
1083+The result is `false` if no equal row is found
1084+(including the case where the subquery returns no rows).
1086+>>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression commons schemas params grp from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1087+>>> printSQL $ myRow `rowIn` values_ myRow
1088+ROW(1, FALSE) IN (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1092+ => NP (Aliased (Expression commons schemas params grp from)) row -- ^ row constructor
1093+ -> Query commons schemas params row -- ^ subquery
1094+ -> Expression commons schemas params grp from (nullity 'PGbool)
1095+rowIn = unsafeRowSubqueryExpression "IN"
1097+-- | >>> printSQL $ true `eqAll` values_ (true `as` #foo)
1098+-- TRUE = ALL (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1100+ :: Expression commons schemas params grp from ty -- ^ expression
1101+ -> Query commons schemas params '[alias ::: ty] -- ^ subquery
1102+ -> Expression commons schemas params grp from (nullity 'PGbool)
1103+eqAll = unsafeSubqueryExpression "= ALL"
1105+-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression commons schemas params grp from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1106+-- >>> printSQL $ myRow `rowEqAll` values_ myRow
1107+-- ROW(1, FALSE) = ALL (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1110+ => NP (Aliased (Expression commons schemas params grp from)) row -- ^ row constructor
1111+ -> Query commons schemas params row -- ^ subquery
1112+ -> Expression commons schemas params grp from (nullity 'PGbool)
1113+rowEqAll = unsafeRowSubqueryExpression "= ALL"
1115+-- | >>> printSQL $ true `eqAny` values_ (true `as` #foo)
1116+-- TRUE = ANY (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1118+ :: Expression commons schemas params grp from ty -- ^ expression
1119+ -> Query commons schemas params '[alias ::: ty] -- ^ subquery
1120+ -> Expression commons schemas params grp from (nullity 'PGbool)
1121+eqAny = unsafeSubqueryExpression "= ANY"
1123+-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression commons schemas params grp from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1124+-- >>> printSQL $ myRow `rowEqAny` values_ myRow
1125+-- ROW(1, FALSE) = ANY (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1128+ => NP (Aliased (Expression commons schemas params grp from)) row -- ^ row constructor
1129+ -> Query commons schemas params row -- ^ subquery
1130+ -> Expression commons schemas params grp from (nullity 'PGbool)
1131+rowEqAny = unsafeRowSubqueryExpression "= ANY"
1133+-- | >>> printSQL $ true `neqAll` values_ (true `as` #foo)
1134+-- TRUE <> ALL (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1136+ :: Expression commons schemas params grp from ty -- ^ expression
1137+ -> Query commons schemas params '[alias ::: ty] -- ^ subquery
1138+ -> Expression commons schemas params grp from (nullity 'PGbool)
1139+neqAll = unsafeSubqueryExpression "<> ALL"
1141+-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression commons schemas params grp from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1142+-- >>> printSQL $ myRow `rowNeqAll` values_ myRow
1143+-- ROW(1, FALSE) <> ALL (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1146+ => NP (Aliased (Expression commons schemas params grp from)) row -- ^ row constructor
1147+ -> Query commons schemas params row -- ^ subquery
1148+ -> Expression commons schemas params grp from (nullity 'PGbool)
1149+rowNeqAll = unsafeRowSubqueryExpression "<> ALL"
1151+-- | >>> printSQL $ true `neqAny` values_ (true `as` #foo)
1152+-- TRUE <> ANY (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1154+ :: Expression commons schemas params grp from ty -- ^ expression
1155+ -> Query commons schemas params '[alias ::: ty] -- ^ subquery
1156+ -> Expression commons schemas params grp from (nullity 'PGbool)
1157+neqAny = unsafeSubqueryExpression "<> ANY"
1159+-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression commons schemas params grp from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1160+-- >>> printSQL $ myRow `rowNeqAny` values_ myRow
1161+-- ROW(1, FALSE) <> ANY (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1164+ => NP (Aliased (Expression commons schemas params grp from)) row -- ^ row constructor
1165+ -> Query commons schemas params row -- ^ subquery
1166+ -> Expression commons schemas params grp from (nullity 'PGbool)
1167+rowNeqAny = unsafeRowSubqueryExpression "<> ANY"
1169+-- | >>> printSQL $ true `allLt` values_ (true `as` #foo)
1170+-- TRUE ALL < (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1172+ :: Expression commons schemas params grp from ty -- ^ expression
1173+ -> Query commons schemas params '[alias ::: ty] -- ^ subquery
1174+ -> Expression commons schemas params grp from (nullity 'PGbool)
1175+allLt = unsafeSubqueryExpression "ALL <"
1177+-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression commons schemas params grp from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1178+-- >>> printSQL $ myRow `rowLtAll` values_ myRow
1179+-- ROW(1, FALSE) ALL < (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1182+ => NP (Aliased (Expression commons schemas params grp from)) row -- ^ row constructor
1183+ -> Query commons schemas params row -- ^ subquery
1184+ -> Expression commons schemas params grp from (nullity 'PGbool)
1185+rowLtAll = unsafeRowSubqueryExpression "ALL <"
1187+-- | >>> printSQL $ true `ltAny` values_ (true `as` #foo)
1188+-- TRUE ANY < (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1190+ :: Expression commons schemas params grp from ty -- ^ expression
1191+ -> Query commons schemas params '[alias ::: ty] -- ^ subquery
1192+ -> Expression commons schemas params grp from (nullity 'PGbool)
1193+ltAny = unsafeSubqueryExpression "ANY <"
1195+-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression commons schemas params grp from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1196+-- >>> printSQL $ myRow `rowLtAll` values_ myRow
1197+-- ROW(1, FALSE) ALL < (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1200+ => NP (Aliased (Expression commons schemas params grp from)) row -- ^ row constructor
1201+ -> Query commons schemas params row -- ^ subquery
1202+ -> Expression commons schemas params grp from (nullity 'PGbool)
1203+rowLtAny = unsafeRowSubqueryExpression "ANY <"
1205+-- | >>> printSQL $ true `lteAll` values_ (true `as` #foo)
1206+-- TRUE <= ALL (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1208+ :: Expression commons schemas params grp from ty -- ^ expression
1209+ -> Query commons schemas params '[alias ::: ty] -- ^ subquery
1210+ -> Expression commons schemas params grp from (nullity 'PGbool)
1211+lteAll = unsafeSubqueryExpression "<= ALL"
1213+-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression commons schemas params grp from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1214+-- >>> printSQL $ myRow `rowLteAll` values_ myRow
1215+-- ROW(1, FALSE) <= ALL (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1218+ => NP (Aliased (Expression commons schemas params grp from)) row -- ^ row constructor
1219+ -> Query commons schemas params row -- ^ subquery
1220+ -> Expression commons schemas params grp from (nullity 'PGbool)
1221+rowLteAll = unsafeRowSubqueryExpression "<= ALL"
1223+-- | >>> printSQL $ true `lteAny` values_ (true `as` #foo)
1224+-- TRUE <= ANY (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1226+ :: Expression commons schemas params grp from ty -- ^ expression
1227+ -> Query commons schemas params '[alias ::: ty] -- ^ subquery
1228+ -> Expression commons schemas params grp from (nullity 'PGbool)
1229+lteAny = unsafeSubqueryExpression "<= ANY"
1231+-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression commons schemas params grp from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1232+-- >>> printSQL $ myRow `rowLteAny` values_ myRow
1233+-- ROW(1, FALSE) <= ANY (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1236+ => NP (Aliased (Expression commons schemas params grp from)) row -- ^ row constructor
1237+ -> Query commons schemas params row -- ^ subquery
1238+ -> Expression commons schemas params grp from (nullity 'PGbool)
1239+rowLteAny = unsafeRowSubqueryExpression "<= ANY"
1241+-- | >>> printSQL $ true `gtAll` values_ (true `as` #foo)
1242+-- TRUE > ALL (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1244+ :: Expression commons schemas params grp from ty -- ^ expression
1245+ -> Query commons schemas params '[alias ::: ty] -- ^ subquery
1246+ -> Expression commons schemas params grp from (nullity 'PGbool)
1247+gtAll = unsafeSubqueryExpression "> ALL"
1249+-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression commons schemas params grp from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1250+-- >>> printSQL $ myRow `rowGtAll` values_ myRow
1251+-- ROW(1, FALSE) > ALL (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1254+ => NP (Aliased (Expression commons schemas params grp from)) row -- ^ row constructor
1255+ -> Query commons schemas params row -- ^ subquery
1256+ -> Expression commons schemas params grp from (nullity 'PGbool)
1257+rowGtAll = unsafeRowSubqueryExpression "> ALL"
1259+-- | >>> printSQL $ true `gtAny` values_ (true `as` #foo)
1260+-- TRUE > ANY (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1262+ :: Expression commons schemas params grp from ty -- ^ expression
1263+ -> Query commons schemas params '[alias ::: ty] -- ^ subquery
1264+ -> Expression commons schemas params grp from (nullity 'PGbool)
1265+gtAny = unsafeSubqueryExpression "> ANY"
1267+-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression commons schemas params grp from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1268+-- >>> printSQL $ myRow `rowGtAny` values_ myRow
1269+-- ROW(1, FALSE) > ANY (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1272+ => NP (Aliased (Expression commons schemas params grp from)) row -- ^ row constructor
1273+ -> Query commons schemas params row -- ^ subquery
1274+ -> Expression commons schemas params grp from (nullity 'PGbool)
1275+rowGtAny = unsafeRowSubqueryExpression "> ANY"
1277+-- | >>> printSQL $ true `gteAll` values_ (true `as` #foo)
1278+-- TRUE >= ALL (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1280+ :: Expression commons schemas params grp from ty -- ^ expression
1281+ -> Query commons schemas params '[alias ::: ty] -- ^ subquery
1282+ -> Expression commons schemas params grp from (nullity 'PGbool)
1283+gteAll = unsafeSubqueryExpression ">= ALL"
1285+-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression commons schemas params grp from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1286+-- >>> printSQL $ myRow `rowGteAll` values_ myRow
1287+-- ROW(1, FALSE) >= ALL (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1290+ => NP (Aliased (Expression commons schemas params grp from)) row -- ^ row constructor
1291+ -> Query commons schemas params row -- ^ subquery
1292+ -> Expression commons schemas params grp from (nullity 'PGbool)
1293+rowGteAll = unsafeRowSubqueryExpression ">= ALL"
1295+-- | >>> printSQL $ true `gteAny` values_ (true `as` #foo)
1296+-- TRUE >= ANY (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1298+ :: Expression commons schemas params grp from ty -- ^ expression
1299+ -> Query commons schemas params '[alias ::: ty] -- ^ subquery
1300+ -> Expression commons schemas params grp from (nullity 'PGbool)
1301+gteAny = unsafeSubqueryExpression ">= ANY"
1303+-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression commons schemas params grp from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1304+-- >>> printSQL $ myRow `rowGteAny` values_ myRow
1305+-- ROW(1, FALSE) >= ANY (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1308+ => NP (Aliased (Expression commons schemas params grp from)) row -- ^ row constructor
1309+ -> Query commons schemas params row -- ^ subquery
1310+ -> Expression commons schemas params grp from (nullity 'PGbool)
1311+rowGteAny = unsafeRowSubqueryExpression ">= ANY"
1031-- | A `CommonTableExpression` is an auxiliary statement in a `with` clause.
1313-- | A `CommonTableExpression` is an auxiliary statement in a `with` clause.
1032data CommonTableExpression statement
1314data CommonTableExpression statement
1033 (schemas :: SchemasType)
1315 (schemas :: SchemasType)
@@ -1049,50 +1331,41 @@ instance
1049 , commons1 ~ (cte ::: common ': commons)
1331 , commons1 ~ (cte ::: common ': commons)
1050 ) => Aliasable cte
1332 ) => Aliasable cte
1051 (statement commons schemas params common)
1333 (statement commons schemas params common)
1052− (Path (CommonTableExpression statement schemas params) commons commons1) where
1334+ (AlignedList (CommonTableExpression statement schemas params) commons commons1) where
1053− statement `as` cte = csingleton (statement `as` cte)
1335+ statement `as` cte = single (statement `as` cte)
1055−instance (forall c s p r. RenderSQL (statement c s p r)) => RenderSQL
1337+-- | render a `CommonTableExpression`.
1338+renderCommonTableExpression
1339+ :: (forall cs ss ps row. statement cs ss ps row -> ByteString) -- ^ render statement
1056− (CommonTableExpression statement schemas params commons0 commons1) where
1340+ -> CommonTableExpression statement schemas params commons0 commons1 -> ByteString
1341+renderCommonTableExpression renderStatement
1057− renderSQL (CommonTableExpression (statement `As` cte)) =
1342+ (CommonTableExpression (statement `As` alias)) =
1058− renderSQL cte <+> "AS" <+> parenthesized (renderSQL statement)
1343+ renderSQL alias <+> "AS" <+> parenthesized (renderStatement statement)
1345+-- | render a non-empty `AlignedList` of `CommonTableExpression`s.
1346+renderCommonTableExpressions
1347+ :: (forall cs ss ps row. statement cs ss ps row -> ByteString) -- ^ render statement
1348+ -> CommonTableExpression statement schemas params commons0 commons1
1349+ -> AlignedList (CommonTableExpression statement schemas params) commons1 commons2
1351+renderCommonTableExpressions renderStatement cte ctes =
1352+ renderCommonTableExpression renderStatement cte <> case ctes of
1354+ cte' :>> ctes' -> "," <+>
1355+ renderCommonTableExpressions renderStatement cte' ctes'
1060-- | `with` provides a way to write auxiliary statements for use in a larger query.
1357-- | `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
1358-- These statements, referred to as `CommonTableExpression`s, can be thought of as
1062-- defining temporary tables that exist just for one query.
1359-- defining temporary tables that exist just for one query.
1063class With statement where
1360class With statement where
1065− :: Path (CommonTableExpression statement schemas params) commons0 commons1
1362+ :: AlignedList (CommonTableExpression statement schemas params) commons0 commons1
1066 -- ^ common table expressions
1363 -- ^ common table expressions
1067 -> statement commons1 schemas params row
1364 -> statement commons1 schemas params row
1068 -- ^ larger query
1365 -- ^ larger query
1069 -> statement commons0 schemas params row
1366 -> statement commons0 schemas params row
1070−instance With (Query outer) where
1367+instance With Query where
1071 with Done query = query
1368 with Done query = query
1072− with ctes query = UnsafeQuery $
1369+ 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
1370+ "WITH" <+> renderCommonTableExpressions renderSQL cte ctes
1097− <+> "AS" <+> parenthesized (renderSQL recursive)
1098− <+> renderSQL query
1371+ <+> renderSQL query