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