@@ -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,12 @@ Squeal queries.
33module Squeal.PostgreSQL.Query
31module Squeal.PostgreSQL.Query
34 ( -- * Queries
32 ( -- * Queries
37 -- ** Select
34 -- ** Select
40 , selectDistinct
37 , selectDistinct
41 , selectDistinct_
38 , selectDistinct_
44 , Selection (..)
39 , Selection (..)
45 -- ** Values
40 -- ** Values
@@ -55,13 +50,31 @@ module Squeal.PostgreSQL.Query
55 -- ** With
50 -- ** With
56 , With (..)
51 , With (..)
57 , CommonTableExpression (..)
52 , CommonTableExpression (..)
58− , withRecursive
53+ , renderCommonTableExpression
54+ , renderCommonTableExpressions
63+ , jsonbPopulateRecord
64+ , jsonPopulateRecordSet
65+ , jsonbPopulateRecordSet
59 -- * Table Expressions
70 -- * Table Expressions
60 , TableExpression (..)
71 , TableExpression (..)
72+ , renderTableExpression
67 -- * From Clauses
80 -- * From Clauses
@@ -77,13 +90,42 @@ module Squeal.PostgreSQL.Query
77 , fullOuterJoin
90 , fullOuterJoin
78 -- * Grouping
91 -- * Grouping
80 , GroupByClause (..)
94 , GroupByClause (..)
81 , HavingClause (..)
95 , HavingClause (..)
97+ , SortExpression (..)
98+ -- * Subquery Expressions
84import Control.DeepSeq
127import Control.DeepSeq
85import Data.ByteString (ByteString)
128import Data.ByteString (ByteString)
86−import Data.Kind (Type)
87import Data.String
129import Data.String
88import Data.Word
130import Data.Word
89import Generics.SOP hiding (from)
131import Generics.SOP hiding (from)
@@ -91,67 +133,13 @@ import GHC.TypeLits
92import qualified GHC.Generics as GHC
134import qualified GHC.Generics as GHC
94−import Squeal.PostgreSQL.Alias
95import Squeal.PostgreSQL.Expression
136import 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
137import Squeal.PostgreSQL.Render
102import Squeal.PostgreSQL.Schema
138import 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
141+The process of retrieving or the command to retrieve data from a database
113−a database is called a `Query`.
142+is called a `Query`. Let's see some examples of queries.
115−The general `Query` type is parameterized by
117−* @outer :: FromType@ - outer scope for a correlated subquery,
118−* @commons :: FromType@ - scope for all `common` table expressions,
119−* @schemas :: SchemasType@ - scope for all `table`s and `view`s,
120−* @params :: [NullityType]@ - scope for all `Squeal.Expression.Parameter.parameter`s,
121−* @row :: RowType@ - return type of the `Query`.
125− (commons :: FromType)
126− (schemas :: SchemasType)
127− (params :: [NullityType])
129− = UnsafeQuery { renderQuery :: ByteString }
130− deriving (GHC.Generic,Show,Eq,Ord,NFData)
131−instance RenderSQL (Query outer commons schemas params row) where renderSQL = renderQuery
134−The top level `Query_` type is parameterized by a @schemas@ `SchemasType`,
135−against which the query is type-checked, an input @parameters@ Haskell `Type`,
136−and an ouput row Haskell `Type`.
138−A top-level query can be run
139−using `Squeal.PostgreSQL.PQ.runQueryParams`, or if @parameters = ()@
140−using `Squeal.PostgreSQL.PQ.runQuery`.
142−Generally, @parameters@ will be a Haskell tuple or record whose entries
143−may be referenced using positional
144−`Squeal.PostgreSQL.Expression.Parameter.parameter`s and @row@ will be a
145−Haskell record, whose entries will be targeted using overloaded labels.
147−Let's see some examples of queries.
149−>>> :set -XDeriveAnyClass -XDerivingStrategies
151−data Row a b = Row { col1 :: a, col2 :: b }
152− deriving stock (GHC.Generic)
153− deriving anyclass (SOP.Generic, SOP.HasDatatypeInfo)
156simple query:
144simple query:
@@ -159,7 +147,7 @@ simple query:
159>>> type Schema = '["tab" ::: 'Table ('[] :=> Columns)]
147>>> type Schema = '["tab" ::: 'Table ('[] :=> Columns)]
162− query :: Query_ (Public Schema) () (Row Int32 Int32)
150+ query :: Query (DBof (Public Schema)) '[] '["col1" ::: 'NotNull 'PGint4, "col2" ::: 'NotNull 'PGint4]
163 query = select Star (from (table #tab))
151 query = select Star (from (table #tab))
164in printSQL query
152in printSQL query
@@ -169,21 +157,21 @@ restricted query:
172− query :: Query_ (Public Schema) () (Row Int32 Int32)
160+ query :: Query (DBof (Public Schema)) '[] '["sum" ::: 'NotNull 'PGint4, "col1" ::: 'NotNull 'PGint4]
174− select_ ((#col1 + #col2) `as` #col1 :* #col1 `as` #col2)
162+ select_ ((#col1 + #col2) `as` #sum :* #col1)
175 ( from (table #tab)
163 ( from (table #tab)
176 & where_ (#col1 .> #col2)
164 & where_ (#col1 .> #col2)
177 & where_ (#col2 .> 0) )
165 & where_ (#col2 .> 0) )
178in printSQL query
166in printSQL query
180−SELECT ("col1" + "col2") AS "col1", "col1" AS "col2" FROM "tab" AS "tab" WHERE (("col1" > "col2") AND ("col2" > 0))
168+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)
174+ query :: Query (DBof (Public Schema)) '[] '["col1" ::: 'NotNull 'PGint4, "col2" ::: 'NotNull 'PGint4]
187 query = select Star (from (subquery (select Star (from (table #tab)) `as` #sub)))
175 query = select Star (from (subquery (select Star (from (table #tab)) `as` #sub)))
188in printSQL query
176in printSQL query
@@ -193,7 +181,7 @@ limits and offsets:
196− query :: Query_ (Public Schema) () (Row Int32 Int32)
184+ query :: Query (DBof (Public Schema)) '[] '["col1" ::: 'NotNull 'PGint4, "col2" ::: 'NotNull 'PGint4]
197 query = select Star (from (table #tab) & limit 100 & offset 2 & limit 50 & offset 2)
185 query = select Star (from (table #tab) & limit 100 & offset 2 & limit 50 & offset 2)
198in printSQL query
186in printSQL query
@@ -203,7 +191,7 @@ parameterized query:
206− query :: Query_ (Public Schema) (Only Int32) (Row Int32 Int32)
194+ query :: Query (DBof (Public Schema)) '[ 'NotNull 'PGint4] '["col1" ::: 'NotNull 'PGint4, "col2" ::: 'NotNull 'PGint4]
207 query = select Star (from (table #tab) & where_ (#col1 .> param @1))
195 query = select Star (from (table #tab) & where_ (#col1 .> param @1))
208in printSQL query
196in printSQL query
@@ -213,21 +201,21 @@ aggregation query:
216− query :: Query_ (Public Schema) () (Row Int64 Int32)
204+ query :: Query (DBof (Public Schema)) '[] '["sum" ::: 'NotNull 'PGint4, "col1" ::: 'NotNull 'PGint4 ]
218− select_ ((fromNull 0 (sum_ (All #col2))) `as` #col1 :* #col1 `as` #col2)
206+ select_ (sum_ #col2 `as` #sum :* #col1)
219 ( from (table (#tab `as` #table1))
207 ( from (table (#tab `as` #table1))
220 & groupBy #col1
208 & groupBy #col1
221− & having (sum_ (Distinct #col2) .> 1) )
209+ & having (#col1 + sum_ #col2 .> 1) )
222in printSQL query
210in 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)
212+SELECT sum("col2") AS "sum", "col1" AS "col1" FROM "tab" AS "table1" GROUP BY "col1" HAVING (("col1" + sum("col2")) > 1)
226sorted query:
214sorted query:
230− query :: Query_ (Public Schema) () (Row Int32 Int32)
218+ query :: Query (DBof (Public Schema)) '[] '["col1" ::: 'NotNull 'PGint4, "col2" ::: 'NotNull 'PGint4]
231 query = select Star (from (table #tab) & orderBy [#col1 & Asc])
219 query = select Star (from (table #tab) & orderBy [#col1 & Asc])
232in printSQL query
220in printSQL query
@@ -235,12 +223,14 @@ SELECT * FROM "tab" AS "tab" ORDER BY "col1" ASC
226+>>> :set -XFlexibleContexts
239type OrdersColumns =
228type OrdersColumns =
240 '[ "id" ::: 'NoDef :=> 'NotNull 'PGint4
229 '[ "id" ::: 'NoDef :=> 'NotNull 'PGint4
241− , "price" ::: 'NoDef :=> 'NotNull 'PGfloat4
230+ , "price" ::: 'NoDef :=> 'NotNull 'PGfloat4
242− , "customer_id" ::: 'NoDef :=> 'NotNull 'PGint4
231+ , "customer_id" ::: 'NoDef :=> 'NotNull 'PGint4
243− , "shipper_id" ::: 'NoDef :=> 'NotNull 'PGint4 ]
232+ , "shipper_id" ::: 'NoDef :=> 'NotNull 'PGint4
@@ -256,27 +246,22 @@ type OrdersConstraints =
257type OrdersSchema =
247type OrdersSchema =
258 '[ "orders" ::: 'Table (OrdersConstraints :=> OrdersColumns)
248 '[ "orders" ::: 'Table (OrdersConstraints :=> OrdersColumns)
259− , "customers" ::: 'Table (CustomersConstraints :=> NamesColumns)
249+ , "customers" ::: 'Table (CustomersConstraints :=> NamesColumns)
260− , "shippers" ::: 'Table (ShippersConstraints :=> NamesColumns) ]
250+ , "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
255+ query :: Query (DBof (Public OrdersSchema))
257+ '[ "order_price" ::: 'NotNull 'PGfloat4
258+ , "customer_name" ::: 'NotNull 'PGtext
259+ , "shipper_name" ::: 'NotNull 'PGtext
276 query = select_
261 query = select_
277− ( #o ! #price `as` #price :*
262+ ( #o ! #price `as` #order_price :*
278− #c ! #name `as` #customerName :*
263+ #c ! #name `as` #customer_name :*
279− #s ! #name `as` #shipperName )
264+ #s ! #name `as` #shipper_name )
280 ( from (table (#orders `as` #o)
265 ( from (table (#orders `as` #o)
281 & innerJoin (table (#customers `as` #c))
266 & innerJoin (table (#customers `as` #c))
282 (#o ! #customer_id .== #c ! #id)
267 (#o ! #customer_id .== #c ! #id)
@@ -284,16 +269,14 @@ let
284 (#o ! #shipper_id .== #s ! #id)) )
269 (#o ! #shipper_id .== #s ! #id)) )
285in printSQL query
270in 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")
272+SELECT "o"."price" AS "order_price", "c"."name" AS "customer_name", "s"."name" AS "shipper_name" FROM "orders" AS "o" INNER JOIN "customers" AS "c" ON ("o"."customer_id" = "c"."id") INNER JOIN "shippers" AS "s" ON ("o"."shipper_id" = "s"."id")
289self-join:
274self-join:
293− query :: Query_ (Public Schema) () (Row Int32 Int32)
278+ query :: Query (DBof (Public Schema)) '[] '["col1" ::: 'NotNull 'PGint4, "col2" ::: 'NotNull 'PGint4]
294− query = select
279+ query = select (#t1 & DotStar) (from (table (#tab `as` #t1) & crossJoin (table (#tab `as` #t2))))
296− (from (table (#tab `as` #t1) & crossJoin (table (#tab `as` #t2))))
297in printSQL query
280in printSQL query
299SELECT "t1".* FROM "tab" AS "t1" CROSS JOIN "tab" AS "t2"
282SELECT "t1".* FROM "tab" AS "t1" CROSS JOIN "tab" AS "t2"
@@ -302,19 +285,17 @@ value queries:
305− query :: Query_ schemas () (Row String Bool)
288+ query :: Query db '[] '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
306− query = values
289+ 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
290in printSQL query
311−SELECT * FROM (VALUES (E'true', TRUE), (E'false', FALSE)) AS t ("col1", "col2")
292+SELECT * FROM (VALUES (1, TRUE), (2, FALSE)) AS t ("foo", "bar")
313set operations:
294set operations:
317− query :: Query_ (Public Schema) () (Row Int32 Int32)
298+ query :: Query (DBof (Public Schema)) '[] '["col1" ::: 'NotNull 'PGint4, "col2" ::: 'NotNull 'PGint4]
318 query = select Star (from (table #tab)) `unionAll` select Star (from (table #tab))
299 query = select Star (from (table #tab)) `unionAll` select Star (from (table #tab))
319in printSQL query
300in printSQL query
@@ -324,7 +305,7 @@ with queries:
327− query :: Query_ (Public Schema) () (Row Int32 Int32)
308+ query :: Query (DBof (Public Schema)) '[] '["col1" ::: 'NotNull 'PGint4, "col2" ::: 'NotNull 'PGint4]
328 query = with (
309 query = with (
329 select Star (from (table #tab)) `as` #cte1 :>>
310 select Star (from (table #tab)) `as` #cte1 :>>
330 select Star (from (common #cte1)) `as` #cte2
311 select Star (from (common #cte1)) `as` #cte2
@@ -332,195 +313,133 @@ let
332in printSQL query
313in printSQL query
334WITH "cte1" AS (SELECT * FROM "tab" AS "tab"), "cte2" AS (SELECT * FROM "cte1" AS "cte1") SELECT * FROM "cte2" AS "cte2"
315WITH "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_
317+newtype Query
364− (schemas :: SchemasType)
318+ (db :: DBType)
365− (parameters :: Type)
319+ (params :: [NullityType])
366− (row :: Type) where
320+ (columns :: RowType)
367− Query_ schemas params row =
321+ = UnsafeQuery { renderQuery :: ByteString }
368− Query '[] '[] schemas (TuplePG params) (RowPG row)
322+ deriving (GHC.Generic,Show,Eq,Ord,NFData)
323+instance RenderSQL (Query db params columns) where renderSQL = renderQuery
370-- | The results of two queries can be combined using the set operation
325-- | The results of two queries can be combined using the set operation
371-- `union`. Duplicate rows are eliminated.
326-- `union`. Duplicate rows are eliminated.
373− :: Query outer commons schemas params columns
328+ :: Query db params columns
374− -> Query outer commons schemas params columns
329+ -> Query db params columns
375− -> Query outer commons schemas params columns
330+ -> Query db params columns
376q1 `union` q2 = UnsafeQuery $
331q1 `union` q2 = UnsafeQuery $
377− parenthesized (renderSQL q1)
332+ parenthesized (renderQuery q1)
378 <+> "UNION"
333 <+> "UNION"
379− <+> parenthesized (renderSQL q2)
334+ <+> parenthesized (renderQuery q2)
381-- | The results of two queries can be combined using the set operation
336-- | The results of two queries can be combined using the set operation
382-- `unionAll`, the disjoint union. Duplicate rows are retained.
337-- `unionAll`, the disjoint union. Duplicate rows are retained.
384− :: Query outer commons schemas params columns
339+ :: Query db params columns
385− -> Query outer commons schemas params columns
340+ -> Query db params columns
386− -> Query outer commons schemas params columns
341+ -> Query db params columns
387q1 `unionAll` q2 = UnsafeQuery $
342q1 `unionAll` q2 = UnsafeQuery $
388− parenthesized (renderSQL q1)
343+ parenthesized (renderQuery q1)
389 <+> "UNION" <+> "ALL"
344 <+> "UNION" <+> "ALL"
390− <+> parenthesized (renderSQL q2)
345+ <+> parenthesized (renderQuery q2)
392-- | The results of two queries can be combined using the set operation
347-- | The results of two queries can be combined using the set operation
393-- `intersect`, the intersection. Duplicate rows are eliminated.
348-- `intersect`, the intersection. Duplicate rows are eliminated.
395− :: Query outer commons schemas params columns
350+ :: Query db params columns
396− -> Query outer commons schemas params columns
351+ -> Query db params columns
397− -> Query outer commons schemas params columns
352+ -> Query db params columns
398q1 `intersect` q2 = UnsafeQuery $
353q1 `intersect` q2 = UnsafeQuery $
399− parenthesized (renderSQL q1)
354+ parenthesized (renderQuery q1)
400 <+> "INTERSECT"
355 <+> "INTERSECT"
401− <+> parenthesized (renderSQL q2)
356+ <+> parenthesized (renderQuery q2)
403-- | The results of two queries can be combined using the set operation
358-- | The results of two queries can be combined using the set operation
404-- `intersectAll`, the intersection. Duplicate rows are retained.
359-- `intersectAll`, the intersection. Duplicate rows are retained.
405intersectAll
360intersectAll
406− :: Query outer commons schemas params columns
361+ :: Query db params columns
407− -> Query outer commons schemas params columns
362+ -> Query db params columns
408− -> Query outer commons schemas params columns
363+ -> Query db params columns
409q1 `intersectAll` q2 = UnsafeQuery $
364q1 `intersectAll` q2 = UnsafeQuery $
410− parenthesized (renderSQL q1)
365+ parenthesized (renderQuery q1)
411 <+> "INTERSECT" <+> "ALL"
366 <+> "INTERSECT" <+> "ALL"
412− <+> parenthesized (renderSQL q2)
367+ <+> parenthesized (renderQuery q2)
414-- | The results of two queries can be combined using the set operation
369-- | The results of two queries can be combined using the set operation
415-- `except`, the set difference. Duplicate rows are eliminated.
370-- `except`, the set difference. Duplicate rows are eliminated.
417− :: Query outer commons schemas params columns
372+ :: Query db params columns
418− -> Query outer commons schemas params columns
373+ -> Query db params columns
419− -> Query outer commons schemas params columns
374+ -> Query db params columns
420q1 `except` q2 = UnsafeQuery $
375q1 `except` q2 = UnsafeQuery $
421− parenthesized (renderSQL q1)
376+ parenthesized (renderQuery q1)
422 <+> "EXCEPT"
377 <+> "EXCEPT"
423− <+> parenthesized (renderSQL q2)
378+ <+> parenthesized (renderQuery q2)
425-- | The results of two queries can be combined using the set operation
380-- | The results of two queries can be combined using the set operation
426-- `exceptAll`, the set difference. Duplicate rows are retained.
381-- `exceptAll`, the set difference. Duplicate rows are retained.
428− :: Query outer commons schemas params columns
383+ :: Query db params columns
429− -> Query outer commons schemas params columns
384+ -> Query db params columns
430− -> Query outer commons schemas params columns
385+ -> Query db params columns
431q1 `exceptAll` q2 = UnsafeQuery $
386q1 `exceptAll` q2 = UnsafeQuery $
432− parenthesized (renderSQL q1)
387+ parenthesized (renderQuery q1)
433 <+> "EXCEPT" <+> "ALL"
388 <+> "EXCEPT" <+> "ALL"
434− <+> parenthesized (renderSQL q2)
389+ <+> parenthesized (renderQuery q2)
436{-----------------------------------------
391{-----------------------------------------
437SELECT queries
392SELECT queries
438-----------------------------------------}
393-----------------------------------------}
440−{- | The simplest kinds of `Selection` are `Star` and `DotStar` which
395+data Selection db params grp from row where
441−emits all columns that a `TableExpression` produces. A select `List`
396+ List
442−is a list of `Expression`s. A `Selection` could be a list of
397+ :: SListI row
443−`WindowFunction`s `Over` `WindowDefinition`. `Additional` `Selection`s can
398+ => NP (Aliased (Expression db params grp from)) row
444−be selected with `Also`.
399+ -> Selection db params grp from row
446−data Selection outer commons grp schemas params from row where
448 :: HasUnique tab from row
401 :: HasUnique tab from row
449− => Selection outer commons 'Ungrouped schemas params from row
402+ => Selection db params 'Ungrouped from row
450− -- ^ `HasUnique` table in the `FromClause`
452 :: Has tab from row
404 :: Has tab from row
453 => Alias tab
405 => Alias tab
454− -- ^ `Has` table with `Alias`
406+ -> Selection db params 'Ungrouped from row
455− -> Selection outer commons 'Ungrouped schemas params from row
458− => NP (Aliased (Expression outer commons grp schemas params from)) row
459− -- ^ `NP` list of `Aliased` `Expression`s
460− -> Selection outer commons grp schemas params from row
463− => NP (Aliased (WindowFunction outer commons grp schemas params from)) row
464− -- ^ `NP` list of `Aliased` `WindowFunction`s
465− -> WindowDefinition outer commons grp schemas params from
466− -> Selection outer commons grp schemas params from row
468− :: Selection outer commons grp schemas params from right
408+ :: Selection db params grp from right
469− -- ^ `Additional` `Selection`
409+ -> Selection db params grp from left
470− -> Selection outer commons grp schemas params from left
410+ -> Selection db params grp from (Join left right)
471− -> Selection outer commons grp schemas params from (Join left right)
472−instance Additional (Selection outer commons grp schemas params from) where
474instance (KnownSymbol col, row ~ '[col ::: ty])
411instance (KnownSymbol col, row ~ '[col ::: ty])
475 => Aliasable col
412 => Aliasable col
476− (Expression outer commons grp schemas params from ty)
413+ (Expression db params grp from ty)
477− (Selection outer commons grp schemas params from row) where
414+ (Selection db params grp from row) where
478 expr `as` col = List (expr `as` col)
415 expr `as` col = List (expr `as` col)
479−instance (Has tab (Join outer from) row0, Has col row0 ty, row1 ~ '[col ::: ty])
416+instance (Has tab from row0, Has col row0 ty, row1 ~ '[col ::: ty])
480− => IsQualified tab col
417+ => IsQualified tab col (Selection db params 'Ungrouped from row1) where
481− (Selection outer commons 'Ungrouped schemas params from row1) where
418+ tab ! col = tab ! col `as` col
482− tab ! col = tab ! col `as` col
484− ( Has tab (Join outer from) row0
420+ ( Has tab from row0
485 , Has col row0 ty
421 , Has col row0 ty
486 , row1 ~ '[col ::: ty]
422 , row1 ~ '[col ::: ty]
487 , GroupedBy tab col bys )
423 , GroupedBy tab col bys )
488− => IsQualified tab col
424+ => IsQualified tab col (Selection db params ('Grouped bys) from row1) where
489− (Selection outer commons ('Grouped bys) schemas params from row1) where
425+ tab ! col = tab ! col `as` col
490− tab ! col = tab ! col `as` col
426+instance (HasUnique tab from row0, Has col row0 ty, row1 ~ '[col ::: ty])
491−instance (HasUnique tab (Join outer from) row0, Has col row0 ty, row1 ~ '[col ::: ty])
427+ => IsLabel col (Selection db params 'Ungrouped from row1) where
492− => IsLabel col
428+ fromLabel = fromLabel @col `as` Alias
493− (Selection outer commons 'Ungrouped schemas params from row1) where
494− fromLabel = fromLabel @col `as` Alias
496− ( HasUnique tab (Join outer from) row0
430+ ( HasUnique tab from row0
497 , Has col row0 ty
431 , Has col row0 ty
498 , row1 ~ '[col ::: ty]
432 , row1 ~ '[col ::: ty]
499 , GroupedBy tab col bys )
433 , GroupedBy tab col bys )
500− => IsLabel col
434+ => IsLabel col (Selection db params ('Grouped bys) from row1) where
501− (Selection outer commons ('Grouped bys) schemas params from row1) where
435+ fromLabel = fromLabel @col `as` Alias
502− fromLabel = fromLabel @col `as` Alias
504−instance RenderSQL (Selection outer commons grp schemas params from row) where
437+instance RenderSQL (Selection db params grp from row) where
505 renderSQL = \case
438 renderSQL = \case
506 List list -> renderCommaSeparated (renderAliased renderSQL) list
439 List list -> renderCommaSeparated (renderAliased renderSQL) list
507 Star -> "*"
440 Star -> "*"
508 DotStar tab -> renderSQL tab <> ".*"
441 DotStar tab -> renderSQL tab <> ".*"
509 Also right left -> renderSQL left <> ", " <> renderSQL right
442 Also right left -> renderSQL left <> ", " <> renderSQL right
510− Over winFns winDef ->
513− :: Aliased (WindowFunction outer commons grp schemas params from) field
515− renderOver (winFn `As` col) = renderSQL winFn
516− <+> "OVER" <+> parenthesized (renderSQL winDef)
517− <+> "AS" <+> renderSQL col
519− 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
444-- | the `TableExpression` in the `select` command constructs an intermediate
526-- virtual table by possibly combining tables, views, eliminating rows,
445-- virtual table by possibly combining tables, views, eliminating rows,
@@ -529,100 +448,45 @@ instance IsString
529-- the intermediate table are actually output.
448-- the intermediate table are actually output.
531 :: (SListI row, row ~ (x ': xs))
450 :: (SListI row, row ~ (x ': xs))
532− => Selection outer commons grp schemas params from row
451+ => Selection db params grp from row
533− -- ^ selection
452+ -- ^ select list
534− -> TableExpression outer commons grp schemas params from
453+ -> TableExpression db params grp from
535 -- ^ intermediate virtual table
454 -- ^ intermediate virtual table
536− -> Query outer commons schemas params row
455+ -> Query db params row
537select selection tabexpr = UnsafeQuery $
456select selection tabexpr = UnsafeQuery $
539 <+> renderSQL selection
458 <+> renderSQL selection
540− <+> renderSQL tabexpr
459+ <+> renderTableExpression tabexpr
542−-- | Like `select` but takes an `NP` list of `Expression`s instead
543−-- of a general `Selection`.
545 :: (SListI row, row ~ (x ': xs))
462 :: (SListI row, row ~ (x ': xs))
546− => NP (Aliased (Expression outer commons grp schemas params from)) row
463+ => NP (Aliased (Expression db params grp from)) row
547− -- ^ select list
464+ -> TableExpression db params grp from
548− -> TableExpression outer commons grp schemas params from
465+ -> Query db params row
549− -- ^ intermediate virtual table
466+select_ list = select (List list)
550− -> Query outer commons schemas params row
551−select_ = select . List
553-- | After the select list has been processed, the result table can
468-- | After the select list has been processed, the result table can
554-- be subject to the elimination of duplicate rows using `selectDistinct`.
469-- be subject to the elimination of duplicate rows using `selectDistinct`.
555selectDistinct
470selectDistinct
556 :: (SListI columns, columns ~ (col ': cols))
471 :: (SListI columns, columns ~ (col ': cols))
557− => Selection outer commons grp schemas params from columns
472+ => Selection db params 'Ungrouped from columns
558− -- ^ selection
473+ -- ^ select list
559− -> TableExpression outer commons grp schemas params from
474+ -> TableExpression db params 'Ungrouped from
560 -- ^ intermediate virtual table
475 -- ^ intermediate virtual table
561− -> Query outer commons schemas params columns
476+ -> Query db params columns
562selectDistinct selection tabexpr = UnsafeQuery $
477selectDistinct selection tabexpr = UnsafeQuery $
563 "SELECT DISTINCT"
478 "SELECT DISTINCT"
564 <+> renderSQL selection
479 <+> renderSQL selection
565− <+> renderSQL tabexpr
480+ <+> renderTableExpression tabexpr
567−-- | Like `selectDistinct` but takes an `NP` list of `Expression`s instead
568−-- of a general `Selection`.
569selectDistinct_
482selectDistinct_
570 :: (SListI columns, columns ~ (col ': cols))
483 :: (SListI columns, columns ~ (col ': cols))
571− => NP (Aliased (Expression outer commons grp schemas params from)) columns
484+ => NP (Aliased (Expression db params 'Ungrouped from)) columns
572 -- ^ select list
485 -- ^ select list
573− -> TableExpression outer commons grp schemas params from
486+ -> TableExpression db params 'Ungrouped from
574 -- ^ intermediate virtual table
487 -- ^ intermediate virtual table
575− -> Query outer commons schemas params columns
488+ -> Query db params columns
576−selectDistinct_ = selectDistinct . List
489+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
491-- | `values` computes a row value or set of row values
628-- specified by value expressions. It is most commonly used
492-- specified by value expressions. It is most commonly used
@@ -630,16 +494,16 @@ selectDistinctOn_ distincts = selectDistinctOn distincts . List
630-- but it can be used on its own.
494-- but it can be used on its own.
632-- >>> type Row = '["a" ::: 'NotNull 'PGint4, "b" ::: 'NotNull 'PGtext]
496-- >>> type Row = '["a" ::: 'NotNull 'PGint4, "b" ::: 'NotNull 'PGtext]
633−-- >>> let query = values (1 `as` #a :* "one" `as` #b) [] :: Query outer commons schemas '[] Row
497+-- >>> let query = values (1 `as` #a :* "one" `as` #b) [] :: Query db '[] Row
634-- >>> printSQL query
498-- >>> printSQL query
635-- SELECT * FROM (VALUES (1, E'one')) AS t ("a", "b")
499-- SELECT * FROM (VALUES (1, E'one')) AS t ("a", "b")
637 :: SListI cols
501 :: SListI cols
638− => NP (Aliased (Expression outer commons 'Ungrouped schemas params '[] )) cols
502+ => NP (Aliased (Expression db params 'Ungrouped '[] )) cols
639− -> [NP (Aliased (Expression outer commons 'Ungrouped schemas params '[] )) cols]
503+ -> [NP (Aliased (Expression db params 'Ungrouped '[] )) cols]
640 -- ^ When more than one row is specified, all the rows must
504 -- ^ When more than one row is specified, all the rows must
641 -- must have the same number of elements
505 -- must have the same number of elements
642− -> Query outer commons schemas params cols
506+ -> Query db params cols
643values rw rws = UnsafeQuery $ "SELECT * FROM"
507values rw rws = UnsafeQuery $ "SELECT * FROM"
644 <+> parenthesized (
508 <+> parenthesized (
@@ -647,20 +511,20 @@ values rw rws = UnsafeQuery $ "SELECT * FROM"
647 ( parenthesized
511 ( parenthesized
648 . renderCommaSeparated renderValuePart <$> rw:rws )
512 . renderCommaSeparated renderValuePart <$> rw:rws )
649 ) <+> "AS t"
513 ) <+> "AS t"
650− <+> parenthesized (renderCommaSeparated renderAliasPart rw)
514+ <+> parenthesized (renderCommaSeparated renderSQLPart rw)
652− renderAliasPart, renderValuePart
516+ renderSQLPart, renderValuePart
653− :: Aliased (Expression outer commons 'Ungrouped schemas params '[] ) ty -> ByteString
517+ :: Aliased (Expression db params 'Ungrouped '[] ) ty -> ByteString
654− renderAliasPart (_ `As` name) = renderSQL name
518+ renderSQLPart (_ `As` name) = renderSQL name
655 renderValuePart (value `As` _) = renderSQL value
519 renderValuePart (value `As` _) = renderSQL value
657-- | `values_` computes a row value or set of row values
521-- | `values_` computes a row value or set of row values
658-- specified by value expressions.
522-- specified by value expressions.
660 :: SListI cols
524 :: SListI cols
661− => NP (Aliased (Expression outer commons 'Ungrouped schemas params '[] )) cols
525+ => NP (Aliased (Expression db params 'Ungrouped '[] )) cols
662 -- ^ one row of values
526 -- ^ one row of values
663− -> Query outer commons schemas params cols
527+ -> Query db params cols
664values_ rw = values rw []
528values_ rw = values rw []
666{-----------------------------------------
530{-----------------------------------------
@@ -674,17 +538,15 @@ Table Expressions
674-- to a table on disk, a so-called base table, but more complex expressions
538-- 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.
539-- can be used to modify or combine base tables in various ways.
676data TableExpression
540data TableExpression
677− (outer :: FromType)
541+ (db :: DBType)
678− (commons :: FromType)
680− (schemas :: SchemasType)
681 (params :: [NullityType])
542 (params :: [NullityType])
682 (from :: FromType)
544 (from :: FromType)
683 = TableExpression
545 = TableExpression
684− { fromClause :: FromClause outer commons schemas params from
546+ { fromClause :: FromClause db params from
685 -- ^ A table reference that can be a table name, or a derived table such
547 -- ^ 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.
548 -- as a subquery, a @JOIN@ construct, or complex combinations of these.
687− , whereClause :: [Condition outer commons 'Ungrouped schemas params from]
549+ , whereClause :: [Condition db params 'Ungrouped from]
688 -- ^ optional search coditions, combined with `.&&`. After the processing
550 -- ^ optional search coditions, combined with `.&&`. After the processing
689 -- of the `fromClause` is done, each row of the derived virtual table
551 -- of the `fromClause` is done, each row of the derived virtual table
690 -- is checked against the search condition. If the result of the
552 -- is checked against the search condition. If the result of the
@@ -700,13 +562,13 @@ data TableExpression
700 -- set of rows having common values into one group row that represents all
562 -- 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
563 -- rows in the group. This is done to eliminate redundancy in the output
702 -- and/or compute aggregates that apply to these groups.
564 -- and/or compute aggregates that apply to these groups.
703− , havingClause :: HavingClause outer commons grp schemas params from
565+ , havingClause :: HavingClause db params grp from
704 -- ^ If a table has been grouped using `groupBy`, but only certain groups
566 -- ^ If a table has been grouped using `groupBy`, but only certain groups
705 -- are of interest, the `havingClause` can be used, much like a
567 -- are of interest, the `havingClause` can be used, much like a
706 -- `whereClause`, to eliminate groups from the result. Expressions in the
568 -- `whereClause`, to eliminate groups from the result. Expressions in the
707 -- `havingClause` can refer both to grouped expressions and to ungrouped
569 -- `havingClause` can refer both to grouped expressions and to ungrouped
708 -- expressions (which necessarily involve an aggregate function).
570 -- expressions (which necessarily involve an aggregate function).
709− , orderByClause :: [SortExpression outer commons grp schemas params from]
571+ , orderByClause :: [SortExpression db params grp from]
710 -- ^ The `orderByClause` is for optional sorting. When more than one
572 -- ^ The `orderByClause` is for optional sorting. When more than one
711 -- `SortExpression` is specified, the later (right) values are used to sort
573 -- `SortExpression` is specified, the later (right) values are used to sort
712 -- rows that are equal according to the earlier (left) values.
574 -- rows that are equal according to the earlier (left) values.
@@ -716,69 +578,72 @@ data TableExpression
716 -- will be returned (but possibly fewer, if the query itself yields
578 -- will be returned (but possibly fewer, if the query itself yields
717 -- fewer rows).
579 -- fewer rows).
718 , offsetClause :: [Word64]
580 , offsetClause :: [Word64]
719− -- ^ The `offsetClause` is combined with `Prelude.+` to give an offset count
581+ -- ^ The `offsetClause` is combined with `+` to give an offset count
720 -- if nonempty. The offset count says to skip that many rows before
582 -- 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
583 -- beginning to return rows. The rows are skipped before the limit count
722 -- is applied.
584 -- is applied.
723− } deriving (GHC.Generic)
585+ }
725-- | Render a `TableExpression`
587-- | Render a `TableExpression`
726−instance RenderSQL (TableExpression outer commons grp schemas params from) where
588+renderTableExpression
727− renderSQL
589+ :: TableExpression db params grp from
728− (TableExpression frm' whs' grps' hvs' srts' lims' offs') = mconcat
590+ -> ByteString
729− [ "FROM ", renderSQL frm'
591+renderTableExpression
730− , renderWheres whs'
592+ (TableExpression frm' whs' grps' hvs' srts' lims' offs') = mconcat
731− , renderSQL grps'
593+ [ "FROM ", renderFromClause frm'
732− , renderSQL hvs'
594+ , renderWheres whs'
733− , renderOrderByClause srts'
595+ , renderSQL grps'
734− , renderLimits lims'
596+ , renderSQL hvs'
735− , renderOffsets offs' ]
597+ , renderOrderByClause srts'
736− where
598+ , renderLimits lims'
737− renderWheres = \case
599+ , renderOffsets offs'
739− wh:[] -> " WHERE" <+> renderSQL wh
601+ where
740− wh:whs -> " WHERE" <+> renderSQL (foldr (.&&) wh whs)
602+ renderWheres = \case
741− renderOrderByClause = \case
603+ [] -> ""
742− [] -> ""
604+ wh:[] -> " WHERE" <+> renderSQL wh
743− srts -> " ORDER BY"
605+ wh:whs -> " WHERE" <+> renderSQL (foldr (.&&) wh whs)
744− <+> commaSeparated (renderSQL <$> srts)
606+ renderOrderByClause = \case
745− renderLimits = \case
607+ [] -> ""
746− [] -> ""
608+ srts -> " ORDER BY"
747− lims -> " LIMIT" <+> fromString (show (minimum lims))
609+ <+> commaSeparated (renderSQL <$> srts)
748− renderOffsets = \case
610+ renderLimits = \case
749− [] -> ""
611+ [] -> ""
750− offs -> " OFFSET" <+> fromString (show (sum offs))
612+ lims -> " LIMIT" <+> fromString (show (minimum lims))
613+ renderOffsets = \case
615+ offs -> " OFFSET" <+> fromString (show (sum offs))
752-- | A `from` generates a `TableExpression` from a table reference that can be
617-- | 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,
618-- 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_`,
619-- or complex combinations of these. A `from` may be transformed by `where_`,
755−-- `groupBy`, `having`, `orderBy`, `limit` and `offset`, using the `&` operator
620+-- `group`, `having`, `orderBy`, `limit` and `offset`, using the `&` operator
756-- to match the left-to-right sequencing of their placement in SQL.
621-- to match the left-to-right sequencing of their placement in SQL.
758− :: FromClause outer commons schemas params from -- ^ table reference
623+ :: FromClause db params from -- ^ table reference
759− -> TableExpression outer commons 'Ungrouped schemas params from
624+ -> TableExpression db params 'Ungrouped from
760−from tab = TableExpression tab [] noGroups NoHaving [] [] []
625+from rels = TableExpression rels [] NoGroups NoHaving [] [] []
762-- | A `where_` is an endomorphism of `TableExpression`s which adds a
627-- | A `where_` is an endomorphism of `TableExpression`s which adds a
763-- search condition to the `whereClause`.
628-- search condition to the `whereClause`.
765− :: Condition outer commons 'Ungrouped schemas params from -- ^ filtering condition
630+ :: Condition db params 'Ungrouped from -- ^ filtering condition
766− -> TableExpression outer commons grp schemas params from
631+ -> TableExpression db params grp from
767− -> TableExpression outer commons grp schemas params from
632+ -> TableExpression db params grp from
768where_ wh rels = rels {whereClause = wh : whereClause rels}
633where_ wh rels = rels {whereClause = wh : whereClause rels}
770-- | A `groupBy` is a transformation of `TableExpression`s which switches
635-- | A `groupBy` is a transformation of `TableExpression`s which switches
771−-- its `Grouping` from `Ungrouped` to `Grouped`. Use @groupBy Nil@ to perform
636+-- its `Grouping` from `Ungrouped` to `Grouped`. Use @group Nil@ to perform
772-- a "grand total" aggregation query.
637-- a "grand total" aggregation query.
774 :: SListI bys
639 :: SListI bys
775 => NP (By from) bys -- ^ grouped columns
640 => NP (By from) bys -- ^ grouped columns
776− -> TableExpression outer commons 'Ungrouped schemas params from
641+ -> TableExpression db params 'Ungrouped from
777− -> TableExpression outer commons ('Grouped bys) schemas params from
642+ -> TableExpression db params ('Grouped bys) from
778groupBy bys rels = TableExpression
643groupBy bys rels = TableExpression
779 { fromClause = fromClause rels
644 { fromClause = fromClause rels
780 , whereClause = whereClause rels
645 , whereClause = whereClause rels
781− , groupByClause = group bys
646+ , groupByClause = Group bys
782 , havingClause = Having []
647 , havingClause = Having []
783 , orderByClause = []
648 , orderByClause = []
784 , limitClause = limitClause rels
649 , limitClause = limitClause rels
@@ -788,31 +653,177 @@ groupBy bys rels = TableExpression
788-- | A `having` is an endomorphism of `TableExpression`s which adds a
653-- | A `having` is an endomorphism of `TableExpression`s which adds a
789-- search condition to the `havingClause`.
654-- search condition to the `havingClause`.
791− :: Condition outer commons ('Grouped bys) schemas params from -- ^ having condition
656+ :: Condition db params ('Grouped bys) from -- ^ having condition
792− -> TableExpression outer commons ('Grouped bys) schemas params from
657+ -> TableExpression db params ('Grouped bys) from
793− -> TableExpression outer commons ('Grouped bys) schemas params from
658+ -> TableExpression db params ('Grouped bys) from
794having hv rels = rels
659having hv rels = rels
795 { havingClause = case havingClause rels of Having hvs -> Having (hv:hvs) }
660 { havingClause = case havingClause rels of Having hvs -> Having (hv:hvs) }
797−instance OrderBy TableExpression where
662+-- | An `orderBy` is an endomorphism of `TableExpression`s which appends an
798− orderBy srts rels = rels {orderByClause = orderByClause rels ++ srts}
663+-- ordering to the right of the `orderByClause`.
665+ :: [SortExpression db params grp from] -- ^ sort expressions
666+ -> TableExpression db params grp from
667+ -> TableExpression db params grp from
668+orderBy srts rels = rels {orderByClause = orderByClause rels ++ srts}
800-- | A `limit` is an endomorphism of `TableExpression`s which adds to the
670-- | A `limit` is an endomorphism of `TableExpression`s which adds to the
801-- `limitClause`.
671-- `limitClause`.
803 :: Word64 -- ^ limit parameter
673 :: Word64 -- ^ limit parameter
804− -> TableExpression outer commons grp schemas params from
674+ -> TableExpression db params grp from
805− -> TableExpression outer commons grp schemas params from
675+ -> TableExpression db params grp from
806limit lim rels = rels {limitClause = lim : limitClause rels}
676limit lim rels = rels {limitClause = lim : limitClause rels}
808-- | An `offset` is an endomorphism of `TableExpression`s which adds to the
678-- | An `offset` is an endomorphism of `TableExpression`s which adds to the
809-- `offsetClause`.
679-- `offsetClause`.
811 :: Word64 -- ^ offset parameter
681 :: Word64 -- ^ offset parameter
812− -> TableExpression outer commons grp schemas params from
682+ -> TableExpression db params grp from
813− -> TableExpression outer commons grp schemas params from
683+ -> TableExpression db params grp from
814offset off rels = rels {offsetClause = off : offsetClause rels}
684offset off rels = rels {offsetClause = off : offsetClause rels}
686+{-----------------------------------------
688+-----------------------------------------}
692+ -> Expression db params 'Ungrouped '[] ty
693+ -> Query db params row
694+unsafeSetOfFunction fun expr = UnsafeQuery $
695+ "SELECT * FROM " <> fun <> "(" <> renderSQL expr <> ")"
697+-- | Expands the outermost JSON object into a set of key/value pairs.
699+ :: Expression db params 'Ungrouped '[] (nullity 'PGjson) -- ^ json object
701+ '["key" ::: 'NotNull 'PGtext, "value" ::: 'NotNull 'PGjson]
702+jsonEach = unsafeSetOfFunction "json_each"
704+-- | Expands the outermost binary JSON object into a set of key/value pairs.
706+ :: Expression db params 'Ungrouped '[] (nullity 'PGjsonb) -- ^ jsonb object
708+ '["key" ::: 'NotNull 'PGtext, "value" ::: 'NotNull 'PGjsonb]
709+jsonbEach = unsafeSetOfFunction "jsonb_each"
711+-- | Expands the outermost JSON object into a set of key/value pairs.
713+ :: Expression db params 'Ungrouped '[] (nullity 'PGjson) -- ^ json object
715+ '["key" ::: 'NotNull 'PGtext, "value" ::: 'NotNull 'PGtext]
716+jsonEachAsText = unsafeSetOfFunction "json_each_text"
718+-- | Expands the outermost binary JSON object into a set of key/value pairs.
720+ :: Expression db params 'Ungrouped '[] (nullity 'PGjsonb) -- ^ jsonb object
722+ '["key" ::: 'NotNull 'PGtext, "value" ::: 'NotNull 'PGtext]
723+jsonbEachAsText = unsafeSetOfFunction "jsonb_each_text"
725+-- | Returns set of keys in the outermost JSON object.
727+ :: Expression db params 'Ungrouped '[] (nullity 'PGjson) -- ^ json object
728+ -> Query db params '["json_object_keys" ::: 'NotNull 'PGtext]
729+jsonObjectKeys = unsafeSetOfFunction "json_object_keys"
731+-- | Returns set of keys in the outermost JSON object.
733+ :: Expression db params 'Ungrouped '[] (nullity 'PGjsonb) -- ^ jsonb object
734+ -> Query db params '["jsonb_object_keys" ::: 'NotNull 'PGtext]
735+jsonbObjectKeys = unsafeSetOfFunction "jsonb_object_keys"
737+unsafePopulateFunction
739+ -> TypeExpression schemas (nullity ('PGcomposite row))
740+ -> Expression (commons :=> schemas) params 'Ungrouped '[] ty
741+ -> Query (commons :=> schemas) params row
742+unsafePopulateFunction fun ty expr = UnsafeQuery $
743+ "SELECT * FROM " <> fun <> "("
744+ <> "null::" <> renderSQL ty <> ", "
745+ <> renderSQL expr <> ")"
747+-- | Expands the JSON expression to a row whose columns match the record
748+-- type defined by the given table.
750+ :: TypeExpression schemas (nullity ('PGcomposite row)) -- ^ row type
751+ -> Expression (commons :=> schemas) params 'Ungrouped '[] (nullity 'PGjson) -- ^ json object
752+ -> Query (commons :=> schemas) params row
753+jsonPopulateRecord = unsafePopulateFunction "json_populate_record"
755+-- | Expands the binary JSON expression to a row whose columns match the record
756+-- type defined by the given table.
758+ :: TypeExpression schemas (nullity ('PGcomposite row)) -- ^ row type
759+ -> Expression (commons :=> schemas) params 'Ungrouped '[] (nullity 'PGjsonb) -- ^ jsonb object
760+ -> Query (commons :=> schemas) params row
761+jsonbPopulateRecord = unsafePopulateFunction "jsonb_populate_record"
763+-- | Expands the outermost array of objects in the given JSON expression to a
764+-- set of rows whose columns match the record type defined by the given table.
765+jsonPopulateRecordSet
766+ :: TypeExpression schemas (nullity ('PGcomposite row)) -- ^ row type
767+ -> Expression (commons :=> schemas) params 'Ungrouped '[] (nullity 'PGjson) -- ^ json array
768+ -> Query (commons :=> schemas) params row
769+jsonPopulateRecordSet = unsafePopulateFunction "json_populate_record_set"
771+-- | Expands the outermost array of objects in the given binary JSON expression
772+-- to a set of rows whose columns match the record type defined by the given
774+jsonbPopulateRecordSet
775+ :: TypeExpression schemas (nullity ('PGcomposite row)) -- ^ row type
776+ -> Expression (commons :=> schemas) params 'Ungrouped '[] (nullity 'PGjsonb) -- ^ jsonb array
777+ -> Query (commons :=> schemas) params row
778+jsonbPopulateRecordSet = unsafePopulateFunction "jsonb_populate_record_set"
781+ :: (SListI record, json `In` PGJsonType)
783+ -> Expression (commons :=> schemas) params 'Ungrouped '[] (nullity json)
784+ -> NP (Aliased (TypeExpression schemas)) record
785+ -> Query (commons :=> schemas) params record
786+unsafeRecordFunction fun expr types = UnsafeQuery $
787+ "SELECT * FROM " <> fun <> "("
788+ <> renderSQL expr <> ")"
789+ <+> "AS" <+> "x" <> parenthesized (renderCommaSeparated renderTy types)
791+ renderTy :: Aliased (TypeExpression db) ty -> ByteString
792+ renderTy (ty `As` alias) =
793+ renderSQL alias <+> renderSQL ty
795+-- | Builds an arbitrary record from a JSON object.
798+ => Expression (commons :=> schemas) params 'Ungrouped '[] (nullity 'PGjson) -- ^ json object
799+ -> NP (Aliased (TypeExpression schemas)) record -- ^ record types
800+ -> Query (commons :=> schemas) params record
801+jsonToRecord = unsafeRecordFunction "json_to_record"
803+-- | Builds an arbitrary record from a binary JSON object.
806+ => Expression (commons :=> schemas) params 'Ungrouped '[] (nullity 'PGjsonb) -- ^ jsonb object
807+ -> NP (Aliased (TypeExpression schemas)) record -- ^ record types
808+ -> Query (commons :=> schemas) params record
809+jsonbToRecord = unsafeRecordFunction "jsonb_to_record"
811+-- | Builds an arbitrary set of records from a JSON array of objects.
814+ => Expression (commons :=> schemas) params 'Ungrouped '[] (nullity 'PGjson) -- ^ json array
815+ -> NP (Aliased (TypeExpression schemas)) record -- ^ record types
816+ -> Query (commons :=> schemas) params record
817+jsonToRecordSet = unsafeRecordFunction "json_to_record_set"
819+-- | Builds an arbitrary set of records from a binary JSON array of objects.
822+ => Expression (commons :=> schemas) params 'Ungrouped '[] (nullity 'PGjsonb) -- ^ jsonb array
823+ -> NP (Aliased (TypeExpression schemas)) record -- ^ record types
824+ -> Query (commons :=> schemas) params record
825+jsonbToRecordSet = unsafeRecordFunction "jsonb_to_record_set"
816{-----------------------------------------
827{-----------------------------------------
817FROM clauses
828FROM clauses
818-----------------------------------------}
829-----------------------------------------}
@@ -821,75 +832,67 @@ FROM clauses
821A `FromClause` can be a table name, or a derived table such
832A `FromClause` can be a table name, or a derived table such
822as a subquery, a @JOIN@ construct, or complex combinations of these.
833as a subquery, a @JOIN@ construct, or complex combinations of these.
824−newtype FromClause outer commons schemas params from
835+newtype FromClause db params from
825 = UnsafeFromClause { renderFromClause :: ByteString }
836 = UnsafeFromClause { renderFromClause :: ByteString }
826 deriving (GHC.Generic,Show,Eq,Ord,NFData)
837 deriving (GHC.Generic,Show,Eq,Ord,NFData)
827−instance RenderSQL (FromClause outer commons schemas params from) where
828− renderSQL = renderFromClause
830-- | A real `table` is a table from the database.
839-- | A real `table` is a table from the database.
832 :: (Has sch schemas schema, Has tab schema ('Table table))
841 :: (Has sch schemas schema, Has tab schema ('Table table))
833 => Aliased (QualifiedAlias sch) (alias ::: tab)
842 => Aliased (QualifiedAlias sch) (alias ::: tab)
834− -> FromClause outer commons schemas params '[alias ::: TableToRow table]
843+ -> FromClause (commons :=> schemas) params '[alias ::: TableToRow table]
835table (tab `As` alias) = UnsafeFromClause $
844table (tab `As` alias) = UnsafeFromClause $
836 renderSQL tab <+> "AS" <+> renderSQL alias
845 renderSQL tab <+> "AS" <+> renderSQL alias
838-- | `subquery` derives a table from a `Query`.
847-- | `subquery` derives a table from a `Query`.
840− :: Aliased (Query outer commons schemas params) query
849+ :: Aliased (Query db params) query
841− -> FromClause outer commons schemas params '[query]
850+ -> FromClause db params '[query]
842−subquery = UnsafeFromClause . renderAliased (parenthesized . renderSQL)
851+subquery = UnsafeFromClause . renderAliased (parenthesized . renderQuery)
844-- | `view` derives a table from a `View`.
853-- | `view` derives a table from a `View`.
846 :: (Has sch schemas schema, Has vw schema ('View view))
855 :: (Has sch schemas schema, Has vw schema ('View view))
847 => Aliased (QualifiedAlias sch) (alias ::: vw)
856 => Aliased (QualifiedAlias sch) (alias ::: vw)
848− -> FromClause outer commons schemas params '[alias ::: view]
857+ -> FromClause (commons :=> schemas) params '[alias ::: view]
849view (vw `As` alias) = UnsafeFromClause $
858view (vw `As` alias) = UnsafeFromClause $
850 renderSQL vw <+> "AS" <+> renderSQL alias
859 renderSQL vw <+> "AS" <+> renderSQL alias
852−-- | `common` derives a table from a common table expression.
854 :: Has cte commons common
862 :: Has cte commons common
855 => Aliased Alias (alias ::: cte)
863 => Aliased Alias (alias ::: cte)
856− -> FromClause outer commons schemas params '[alias ::: common]
864+ -> FromClause (commons :=> schemas) params '[alias ::: common]
857common (cte `As` alias) = UnsafeFromClause $
865common (cte `As` alias) = UnsafeFromClause $
858 renderSQL cte <+> "AS" <+> renderSQL alias
866 renderSQL cte <+> "AS" <+> renderSQL alias
860−instance Additional (FromClause outer commons schemas params) where
868+{- | @left & crossJoin right@. For every possible combination of rows from
861− also right left = UnsafeFromClause $
869+ @left@ and @right@ (i.e., a Cartesian product), the joined table will contain
862− renderSQL left <> ", " <> renderSQL right
870+ a row consisting of all columns in @left@ followed by all columns in @right@.
863−
871+ If the tables have @n@ and @m@ rows respectively, the joined table will
864−{- |
872+ have @n * m@ rows.
865−@left & crossJoin right@. For every possible combination of rows from
866−@left@ and @right@ (i.e., a Cartesian product), the joined table will contain
867−a row consisting of all columns in @left@ followed by all columns in @right@.
868−If the tables have @n@ and @m@ rows respectively, the joined table will
872− :: FromClause outer commons schemas params right
875+ :: FromClause db params right
873 -- ^ right
876 -- ^ right
874− -> FromClause outer commons schemas params left
877+ -> FromClause db params left
875 -- ^ left
878 -- ^ left
876− -> FromClause outer commons schemas params (Join left right)
879+ -> FromClause db params (Join left right)
877crossJoin right left = UnsafeFromClause $
880crossJoin right left = UnsafeFromClause $
878− renderSQL left <+> "CROSS JOIN" <+> renderSQL right
881+ renderFromClause left <+> "CROSS JOIN" <+> renderFromClause right
880{- | @left & innerJoin right on@. The joined table is filtered by
883{- | @left & innerJoin right on@. The joined table is filtered by
881the @on@ condition.
884the @on@ condition.
884− :: FromClause outer commons schemas params right
887+ :: FromClause db params right
885 -- ^ right
888 -- ^ right
886− -> Condition outer commons 'Ungrouped schemas params (Join left right)
889+ -> Condition db params 'Ungrouped (Join left right)
887 -- ^ @on@ condition
890 -- ^ @on@ condition
888− -> FromClause outer commons schemas params left
891+ -> FromClause db params left
889 -- ^ left
892 -- ^ left
890− -> FromClause outer commons schemas params (Join left right)
893+ -> FromClause db params (Join left right)
891innerJoin right on left = UnsafeFromClause $
894innerJoin right on left = UnsafeFromClause $
892− renderSQL left <+> "INNER JOIN" <+> renderSQL right
895+ renderFromClause left <+> "INNER JOIN" <+> renderFromClause right
893 <+> "ON" <+> renderSQL on
896 <+> "ON" <+> renderSQL on
895{- | @left & leftOuterJoin right on@. First, an inner join is performed.
898{- | @left & leftOuterJoin right on@. First, an inner join is performed.
@@ -898,15 +901,15 @@ innerJoin right on left = UnsafeFromClause $
898 Thus, the joined table always has at least one row for each row in @left@.
901 Thus, the joined table always has at least one row for each row in @left@.
900leftOuterJoin
903leftOuterJoin
901− :: FromClause outer commons schemas params right
904+ :: FromClause db params right
902 -- ^ right
905 -- ^ right
903− -> Condition outer commons 'Ungrouped schemas params (Join left right)
906+ -> Condition db params 'Ungrouped (Join left right)
904 -- ^ @on@ condition
907 -- ^ @on@ condition
905− -> FromClause outer commons schemas params left
908+ -> FromClause db params left
906 -- ^ left
909 -- ^ left
907− -> FromClause outer commons schemas params (Join left (NullifyFrom right))
910+ -> FromClause db params (Join left (NullifyFrom right))
908leftOuterJoin right on left = UnsafeFromClause $
911leftOuterJoin right on left = UnsafeFromClause $
909− renderSQL left <+> "LEFT OUTER JOIN" <+> renderSQL right
912+ renderFromClause left <+> "LEFT OUTER JOIN" <+> renderFromClause right
910 <+> "ON" <+> renderSQL on
913 <+> "ON" <+> renderSQL on
912{- | @left & rightOuterJoin right on@. First, an inner join is performed.
915{- | @left & rightOuterJoin right on@. First, an inner join is performed.
@@ -916,15 +919,15 @@ leftOuterJoin right on left = UnsafeFromClause $
916 have a row for each row in @right@.
919 have a row for each row in @right@.
918rightOuterJoin
921rightOuterJoin
919− :: FromClause outer commons schemas params right
922+ :: FromClause db params right
920 -- ^ right
923 -- ^ right
921− -> Condition outer commons 'Ungrouped schemas params (Join left right)
924+ -> Condition db params 'Ungrouped (Join left right)
922 -- ^ @on@ condition
925 -- ^ @on@ condition
923− -> FromClause outer commons schemas params left
926+ -> FromClause db params left
924 -- ^ left
927 -- ^ left
925− -> FromClause outer commons schemas params (Join (NullifyFrom left) right)
928+ -> FromClause db params (Join (NullifyFrom left) right)
926rightOuterJoin right on left = UnsafeFromClause $
929rightOuterJoin right on left = UnsafeFromClause $
927− renderSQL left <+> "RIGHT OUTER JOIN" <+> renderSQL right
930+ renderFromClause left <+> "RIGHT OUTER JOIN" <+> renderFromClause right
928 <+> "ON" <+> renderSQL on
931 <+> "ON" <+> renderSQL on
930{- | @left & fullOuterJoin right on@. First, an inner join is performed.
933{- | @left & fullOuterJoin right on@. First, an inner join is performed.
@@ -935,23 +938,23 @@ rightOuterJoin right on left = UnsafeFromClause $
935 is added.
938 is added.
937fullOuterJoin
940fullOuterJoin
938− :: FromClause outer commons schemas params right
941+ :: FromClause db params right
939 -- ^ right
942 -- ^ right
940− -> Condition outer commons 'Ungrouped schemas params (Join left right)
943+ -> Condition db params 'Ungrouped (Join left right)
941 -- ^ @on@ condition
944 -- ^ @on@ condition
942− -> FromClause outer commons schemas params left
945+ -> FromClause db params left
943 -- ^ left
946 -- ^ left
944− -> FromClause outer commons schemas params
947+ -> FromClause db params
945 (Join (NullifyFrom left) (NullifyFrom right))
948 (Join (NullifyFrom left) (NullifyFrom right))
946fullOuterJoin right on left = UnsafeFromClause $
949fullOuterJoin right on left = UnsafeFromClause $
947− renderSQL left <+> "FULL OUTER JOIN" <+> renderSQL right
950+ renderFromClause left <+> "FULL OUTER JOIN" <+> renderFromClause right
948 <+> "ON" <+> renderSQL on
951 <+> "ON" <+> renderSQL on
950{-----------------------------------------
953{-----------------------------------------
952-----------------------------------------}
955-----------------------------------------}
954−-- | `By`s are used in `groupBy` to reference a list of columns which are then
957+-- | `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
958-- 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
959-- in all the columns listed. @By \#col@ will reference an unambiguous
957-- column @col@; otherwise @By2 (\#tab \! \#col)@ will reference a table
960-- column @col@; otherwise @By2 (\#tab \! \#col)@ will reference a table
@@ -971,10 +974,6 @@ data By
971deriving instance Show (By from by)
974deriving instance Show (By from by)
972deriving instance Eq (By from by)
975deriving instance Eq (By from by)
973deriving instance Ord (By from by)
976deriving instance Ord (By from by)
974−instance RenderSQL (By from by) where
976− By1 column -> renderSQL column
977− By2 rel column -> renderSQL rel <> "." <> renderSQL column
979instance (HasUnique rel rels cols, Has col cols ty, by ~ '(rel, col))
978instance (HasUnique rel rels cols, Has col cols ty, by ~ '(rel, col))
980 => IsLabel col (By rels by) where fromLabel = By1 fromLabel
979 => IsLabel col (By rels by) where fromLabel = By1 fromLabel
@@ -986,113 +985,424 @@ instance (Has rel rels cols, Has col cols ty, bys ~ '[ '(rel, col)])
986 => IsQualified rel col (NP (By rels) bys) where
985 => IsQualified rel col (NP (By rels) bys) where
987 rel ! col = By2 rel col :* Nil
986 rel ! col = By2 rel col :* Nil
989+renderBy :: By from by -> ByteString
991+ By1 column -> renderSQL column
992+ By2 rel column -> renderSQL rel <> "." <> renderSQL column
989-- | A `GroupByClause` indicates the `Grouping` of a `TableExpression`.
994-- | A `GroupByClause` indicates the `Grouping` of a `TableExpression`.
990-- A `NoGroups` indicates `Ungrouped` while a `Group` indicates `Grouped`.
995-- A `NoGroups` indicates `Ungrouped` while a `Group` indicates `Grouped`.
991-- @NoGroups@ is distinguised from @Group Nil@ since no aggregation can be
996-- @NoGroups@ is distinguised from @Group Nil@ since no aggregation can be
992-- done on @NoGroups@ while all output `Expression`s must be aggregated
997-- done on @NoGroups@ while all output `Expression`s must be aggregated
993-- in @Group Nil@. In general, all output `Expression`s in the
998-- in @Group Nil@. In general, all output `Expression`s in the
994-- complement of @bys@ must be aggregated in @Group bys@.
999-- complement of @bys@ must be aggregated in @Group bys@.
995−newtype GroupByClause grp from = UnsafeGroupByClause
1000+data GroupByClause grp from where
996− { renderGroupByClause :: ByteString }
1001+ NoGroups :: GroupByClause 'Ungrouped from
997− deriving (GHC.Generic,Show,Eq,Ord,NFData)
1002+ Group
1004+ => NP (By from) bys
1005+ -> GroupByClause ('Grouped bys) from
1007+-- | Renders a `GroupByClause`.
998instance RenderSQL (GroupByClause grp from) where
1008instance RenderSQL (GroupByClause grp from) where
999− renderSQL = renderGroupByClause
1009+ renderSQL = \case
1000−noGroups :: GroupByClause 'Ungrouped from
1010+ NoGroups -> ""
1001−noGroups = UnsafeGroupByClause ""
1011+ Group Nil -> ""
1002−group
1012+ Group bys -> " GROUP BY" <+> renderCommaSeparated renderBy bys
1004− => NP (By from) bys
1005− -> GroupByClause ('Grouped bys) from
1006−group bys = UnsafeGroupByClause $ case bys of
1008− bys' -> " GROUP BY" <+> renderCommaSeparated renderSQL bys'
1010-- | A `HavingClause` is used to eliminate groups that are not of interest.
1014-- | A `HavingClause` is used to eliminate groups that are not of interest.
1011-- An `Ungrouped` `TableExpression` may only use `NoHaving` while a `Grouped`
1015-- An `Ungrouped` `TableExpression` may only use `NoHaving` while a `Grouped`
1012-- `TableExpression` must use `Having` whose conditions are combined with
1016-- `TableExpression` must use `Having` whose conditions are combined with
1013-- `.&&`.
1017-- `.&&`.
1014−data HavingClause outer commons grp schemas params from where
1018+data HavingClause db params grp from where
1015− NoHaving :: HavingClause outer commons 'Ungrouped schemas params from
1019+ NoHaving :: HavingClause db params 'Ungrouped from
1017− :: [Condition outer commons ('Grouped bys) schemas params from]
1021+ :: [Condition db params ('Grouped bys) from]
1018− -> HavingClause outer commons ('Grouped bys) schemas params from
1022+ -> HavingClause db params ('Grouped bys) from
1019−deriving instance Show (HavingClause outer commons grp schemas params from)
1023+deriving instance Show (HavingClause db params grp from)
1020−deriving instance Eq (HavingClause outer commons grp schemas params from)
1024+deriving instance Eq (HavingClause db params grp from)
1021−deriving instance Ord (HavingClause outer commons grp schemas params from)
1025+deriving instance Ord (HavingClause db params grp from)
1023-- | Render a `HavingClause`.
1027-- | Render a `HavingClause`.
1024−instance RenderSQL (HavingClause outer commons grp schemas params from) where
1028+instance RenderSQL (HavingClause db params grp from) where
1025 renderSQL = \case
1029 renderSQL = \case
1026 NoHaving -> ""
1030 NoHaving -> ""
1027 Having [] -> ""
1031 Having [] -> ""
1028 Having conditions ->
1032 Having conditions ->
1029 " HAVING" <+> commaSeparated (renderSQL <$> conditions)
1033 " HAVING" <+> commaSeparated (renderSQL <$> conditions)
1035+{-----------------------------------------
1037+-----------------------------------------}
1039+-- | `SortExpression`s are used by `sortBy` to optionally sort the results
1040+-- of a `Query`. `Asc` or `Desc` set the sort direction of a `NotNull` result
1041+-- column to ascending or descending. Ascending order puts smaller values
1042+-- first, where "smaller" is defined in terms of the `.<` operator. Similarly,
1043+-- descending order is determined with the `.>` operator. `AscNullsFirst`,
1044+-- `AscNullsLast`, `DescNullsFirst` and `DescNullsLast` options are used to
1045+-- determine whether nulls appear before or after non-null values in the sort
1046+-- ordering of a `Null` result column.
1047+data SortExpression db params grp from where
1049+ :: Expression db params grp from ('NotNull ty)
1050+ -> SortExpression db params grp from
1052+ :: Expression db params grp from ('NotNull ty)
1053+ -> SortExpression db params grp from
1055+ :: Expression db params grp from ('Null ty)
1056+ -> SortExpression db params grp from
1058+ :: Expression db params grp from ('Null ty)
1059+ -> SortExpression db params grp from
1061+ :: Expression db params grp from ('Null ty)
1062+ -> SortExpression db params grp from
1064+ :: Expression db params grp from ('Null ty)
1065+ -> SortExpression db params grp from
1066+deriving instance Show (SortExpression db params grp from)
1068+-- | Render a `SortExpression`.
1069+instance RenderSQL (SortExpression db params grp from) where
1071+ Asc expression -> renderSQL expression <+> "ASC"
1072+ Desc expression -> renderSQL expression <+> "DESC"
1073+ AscNullsFirst expression -> renderSQL expression
1074+ <+> "ASC NULLS FIRST"
1075+ DescNullsFirst expression -> renderSQL expression
1076+ <+> "DESC NULLS FIRST"
1077+ AscNullsLast expression -> renderSQL expression <+> "ASC NULLS LAST"
1078+ DescNullsLast expression -> renderSQL expression <+> "DESC NULLS LAST"
1080+unsafeSubqueryExpression
1082+ -> Expression db params grp from ty
1083+ -> Query db params '[alias ::: ty]
1084+ -> Expression db params grp from (nullity 'PGbool)
1085+unsafeSubqueryExpression op x q = UnsafeExpression $
1086+ renderSQL x <+> op <+> parenthesized (renderQuery q)
1088+unsafeRowSubqueryExpression
1091+ -> NP (Aliased (Expression db params grp from)) row
1092+ -> Query db params row
1093+ -> Expression db params grp from (nullity 'PGbool)
1094+unsafeRowSubqueryExpression op xs q = UnsafeExpression $
1095+ renderSQL (row xs) <+> op <+> parenthesized (renderQuery q)
1097+-- | The right-hand side is a sub`Query`, which must return exactly one column.
1098+-- The left-hand expression is evaluated and compared to each row of the
1099+-- sub`Query` result. The result of `in_` is `true` if any equal subquery row is found.
1100+-- The result is `false` if no equal row is found
1101+-- (including the case where the subquery returns no rows).
1103+-- >>> printSQL $ true `in_` values_ (true `as` #foo)
1104+-- TRUE IN (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1106+ :: Expression db params grp from ty -- ^ expression
1107+ -> Query db params '[alias ::: ty] -- ^ subquery
1108+ -> Expression db params grp from (nullity 'PGbool)
1109+in_ = unsafeSubqueryExpression "IN"
1111+{- | The left-hand side of this form of `rowIn` is a row constructor.
1112+The right-hand side is a sub`Query`,
1113+which must return exactly as many columns as
1114+there are expressions in the left-hand row.
1115+The left-hand expressions are evaluated and compared row-wise to each row
1116+of the subquery result. The result of `rowIn`
1117+is `true` if any equal subquery row is found.
1118+The result is `false` if no equal row is found
1119+(including the case where the subquery returns no rows).
1121+>>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db params grp from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1122+>>> printSQL $ myRow `rowIn` values_ myRow
1123+ROW(1, FALSE) IN (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1127+ => NP (Aliased (Expression db params grp from)) row -- ^ row constructor
1128+ -> Query db params row -- ^ subquery
1129+ -> Expression db params grp from (nullity 'PGbool)
1130+rowIn = unsafeRowSubqueryExpression "IN"
1132+-- | >>> printSQL $ true `eqAll` values_ (true `as` #foo)
1133+-- TRUE = ALL (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1135+ :: Expression db params grp from ty -- ^ expression
1136+ -> Query db params '[alias ::: ty] -- ^ subquery
1137+ -> Expression db params grp from (nullity 'PGbool)
1138+eqAll = unsafeSubqueryExpression "= ALL"
1140+-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db params grp from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1141+-- >>> printSQL $ myRow `rowEqAll` values_ myRow
1142+-- ROW(1, FALSE) = ALL (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1145+ => NP (Aliased (Expression db params grp from)) row -- ^ row constructor
1146+ -> Query db params row -- ^ subquery
1147+ -> Expression db params grp from (nullity 'PGbool)
1148+rowEqAll = unsafeRowSubqueryExpression "= ALL"
1150+-- | >>> printSQL $ true `eqAny` values_ (true `as` #foo)
1151+-- TRUE = ANY (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1153+ :: Expression db params grp from ty -- ^ expression
1154+ -> Query db params '[alias ::: ty] -- ^ subquery
1155+ -> Expression db params grp from (nullity 'PGbool)
1156+eqAny = unsafeSubqueryExpression "= ANY"
1158+-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db params grp from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1159+-- >>> printSQL $ myRow `rowEqAny` values_ myRow
1160+-- ROW(1, FALSE) = ANY (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1163+ => NP (Aliased (Expression db params grp from)) row -- ^ row constructor
1164+ -> Query db params row -- ^ subquery
1165+ -> Expression db params grp from (nullity 'PGbool)
1166+rowEqAny = unsafeRowSubqueryExpression "= ANY"
1168+-- | >>> printSQL $ true `neqAll` values_ (true `as` #foo)
1169+-- TRUE <> ALL (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1171+ :: Expression db params grp from ty -- ^ expression
1172+ -> Query db params '[alias ::: ty] -- ^ subquery
1173+ -> Expression db params grp from (nullity 'PGbool)
1174+neqAll = unsafeSubqueryExpression "<> ALL"
1176+-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db params grp from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1177+-- >>> printSQL $ myRow `rowNeqAll` values_ myRow
1178+-- ROW(1, FALSE) <> ALL (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1181+ => NP (Aliased (Expression db params grp from)) row -- ^ row constructor
1182+ -> Query db params row -- ^ subquery
1183+ -> Expression db params grp from (nullity 'PGbool)
1184+rowNeqAll = unsafeRowSubqueryExpression "<> ALL"
1186+-- | >>> printSQL $ true `neqAny` values_ (true `as` #foo)
1187+-- TRUE <> ANY (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1189+ :: Expression db params grp from ty -- ^ expression
1190+ -> Query db params '[alias ::: ty] -- ^ subquery
1191+ -> Expression db params grp from (nullity 'PGbool)
1192+neqAny = unsafeSubqueryExpression "<> ANY"
1194+-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db params grp from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1195+-- >>> printSQL $ myRow `rowNeqAny` values_ myRow
1196+-- ROW(1, FALSE) <> ANY (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1199+ => NP (Aliased (Expression db params grp from)) row -- ^ row constructor
1200+ -> Query db params row -- ^ subquery
1201+ -> Expression db params grp from (nullity 'PGbool)
1202+rowNeqAny = unsafeRowSubqueryExpression "<> ANY"
1204+-- | >>> printSQL $ true `allLt` values_ (true `as` #foo)
1205+-- TRUE ALL < (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1207+ :: Expression db params grp from ty -- ^ expression
1208+ -> Query db params '[alias ::: ty] -- ^ subquery
1209+ -> Expression db params grp from (nullity 'PGbool)
1210+allLt = unsafeSubqueryExpression "ALL <"
1212+-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db params grp from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1213+-- >>> printSQL $ myRow `rowLtAll` values_ myRow
1214+-- ROW(1, FALSE) ALL < (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1217+ => NP (Aliased (Expression db params grp from)) row -- ^ row constructor
1218+ -> Query db params row -- ^ subquery
1219+ -> Expression db params grp from (nullity 'PGbool)
1220+rowLtAll = unsafeRowSubqueryExpression "ALL <"
1222+-- | >>> printSQL $ true `ltAny` values_ (true `as` #foo)
1223+-- TRUE ANY < (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1225+ :: Expression db params grp from ty -- ^ expression
1226+ -> Query db params '[alias ::: ty] -- ^ subquery
1227+ -> Expression db params grp from (nullity 'PGbool)
1228+ltAny = unsafeSubqueryExpression "ANY <"
1230+-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db params grp from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1231+-- >>> printSQL $ myRow `rowLtAll` values_ myRow
1232+-- ROW(1, FALSE) ALL < (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1235+ => NP (Aliased (Expression db params grp from)) row -- ^ row constructor
1236+ -> Query db params row -- ^ subquery
1237+ -> Expression db params grp from (nullity 'PGbool)
1238+rowLtAny = unsafeRowSubqueryExpression "ANY <"
1240+-- | >>> printSQL $ true `lteAll` values_ (true `as` #foo)
1241+-- TRUE <= ALL (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1243+ :: Expression db params grp from ty -- ^ expression
1244+ -> Query db params '[alias ::: ty] -- ^ subquery
1245+ -> Expression db params grp from (nullity 'PGbool)
1246+lteAll = unsafeSubqueryExpression "<= ALL"
1248+-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db params grp from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1249+-- >>> printSQL $ myRow `rowLteAll` values_ myRow
1250+-- ROW(1, FALSE) <= ALL (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1253+ => NP (Aliased (Expression db params grp from)) row -- ^ row constructor
1254+ -> Query db params row -- ^ subquery
1255+ -> Expression db params grp from (nullity 'PGbool)
1256+rowLteAll = unsafeRowSubqueryExpression "<= ALL"
1258+-- | >>> printSQL $ true `lteAny` values_ (true `as` #foo)
1259+-- TRUE <= ANY (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1261+ :: Expression db params grp from ty -- ^ expression
1262+ -> Query db params '[alias ::: ty] -- ^ subquery
1263+ -> Expression db params grp from (nullity 'PGbool)
1264+lteAny = unsafeSubqueryExpression "<= ANY"
1266+-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db params grp from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1267+-- >>> printSQL $ myRow `rowLteAny` values_ myRow
1268+-- ROW(1, FALSE) <= ANY (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1271+ => NP (Aliased (Expression db params grp from)) row -- ^ row constructor
1272+ -> Query db params row -- ^ subquery
1273+ -> Expression db params grp from (nullity 'PGbool)
1274+rowLteAny = unsafeRowSubqueryExpression "<= ANY"
1276+-- | >>> printSQL $ true `gtAll` values_ (true `as` #foo)
1277+-- TRUE > ALL (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1279+ :: Expression db params grp from ty -- ^ expression
1280+ -> Query db params '[alias ::: ty] -- ^ subquery
1281+ -> Expression db params grp from (nullity 'PGbool)
1282+gtAll = unsafeSubqueryExpression "> ALL"
1284+-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db params grp from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1285+-- >>> printSQL $ myRow `rowGtAll` values_ myRow
1286+-- ROW(1, FALSE) > ALL (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1289+ => NP (Aliased (Expression db params grp from)) row -- ^ row constructor
1290+ -> Query db params row -- ^ subquery
1291+ -> Expression db params grp from (nullity 'PGbool)
1292+rowGtAll = unsafeRowSubqueryExpression "> ALL"
1294+-- | >>> printSQL $ true `gtAny` values_ (true `as` #foo)
1295+-- TRUE > ANY (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1297+ :: Expression db params grp from ty -- ^ expression
1298+ -> Query db params '[alias ::: ty] -- ^ subquery
1299+ -> Expression db params grp from (nullity 'PGbool)
1300+gtAny = unsafeSubqueryExpression "> ANY"
1302+-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db params grp from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1303+-- >>> printSQL $ myRow `rowGtAny` values_ myRow
1304+-- ROW(1, FALSE) > ANY (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1307+ => NP (Aliased (Expression db params grp from)) row -- ^ row constructor
1308+ -> Query db params row -- ^ subquery
1309+ -> Expression db params grp from (nullity 'PGbool)
1310+rowGtAny = unsafeRowSubqueryExpression "> ANY"
1312+-- | >>> printSQL $ true `gteAll` values_ (true `as` #foo)
1313+-- TRUE >= ALL (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1315+ :: Expression db params grp from ty -- ^ expression
1316+ -> Query db params '[alias ::: ty] -- ^ subquery
1317+ -> Expression db params grp from (nullity 'PGbool)
1318+gteAll = unsafeSubqueryExpression ">= ALL"
1320+-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db params grp from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1321+-- >>> printSQL $ myRow `rowGteAll` values_ myRow
1322+-- ROW(1, FALSE) >= ALL (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1325+ => NP (Aliased (Expression db params grp from)) row -- ^ row constructor
1326+ -> Query db params row -- ^ subquery
1327+ -> Expression db params grp from (nullity 'PGbool)
1328+rowGteAll = unsafeRowSubqueryExpression ">= ALL"
1330+-- | >>> printSQL $ true `gteAny` values_ (true `as` #foo)
1331+-- TRUE >= ANY (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1333+ :: Expression db params grp from ty -- ^ expression
1334+ -> Query db params '[alias ::: ty] -- ^ subquery
1335+ -> Expression db params grp from (nullity 'PGbool)
1336+gteAny = unsafeSubqueryExpression ">= ANY"
1338+-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db params grp from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1339+-- >>> printSQL $ myRow `rowGteAny` values_ myRow
1340+-- ROW(1, FALSE) >= ANY (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1343+ => NP (Aliased (Expression db params grp from)) row -- ^ row constructor
1344+ -> Query db params row -- ^ subquery
1345+ -> Expression db params grp from (nullity 'PGbool)
1346+rowGteAny = unsafeRowSubqueryExpression ">= ANY"
1031-- | A `CommonTableExpression` is an auxiliary statement in a `with` clause.
1348-- | A `CommonTableExpression` is an auxiliary statement in a `with` clause.
1032data CommonTableExpression statement
1349data CommonTableExpression statement
1033− (schemas :: SchemasType)
1034 (params :: [NullityType])
1350 (params :: [NullityType])
1035− (commons0 :: FromType)
1351+ (db0 :: DBType)
1036− (commons1 :: FromType) where
1352+ (db1 :: DBType) where
1037 CommonTableExpression
1353 CommonTableExpression
1038− :: Aliased (statement commons schemas params) (cte ::: common)
1354+ :: Aliased (statement (commons :=> schemas) params) (cte ::: common)
1039− -> CommonTableExpression statement schemas params commons (cte ::: common ': commons)
1355+ -> CommonTableExpression statement params
1356+ (commons :=> schemas) ((cte ::: common ': commons) :=> schemas)
1041 ( KnownSymbol cte
1358 ( KnownSymbol cte
1042− , commons1 ~ (cte ::: common ': commons)
1359+ , db0 ~ (commons :=> schemas)
1360+ , db1 ~ ((cte ::: common ': commons) :=> schemas)
1043 ) => Aliasable cte
1361 ) => Aliasable cte
1044− (statement commons schemas params common)
1362+ (statement db0 params common)
1045− (CommonTableExpression statement schemas params commons commons1) where
1363+ (CommonTableExpression statement params db0 db1) where
1046 statement `as` cte = CommonTableExpression (statement `as` cte)
1364 statement `as` cte = CommonTableExpression (statement `as` cte)
1048 ( KnownSymbol cte
1366 ( KnownSymbol cte
1049− , commons1 ~ (cte ::: common ': commons)
1367+ , db0 ~ (commons :=> schemas)
1368+ , db1 ~ ((cte ::: common ': commons) :=> schemas)
1050 ) => Aliasable cte
1369 ) => Aliasable cte
1051− (statement commons schemas params common)
1370+ (statement db0 params common)
1052− (Path (CommonTableExpression statement schemas params) commons commons1) where
1371+ (AlignedList (CommonTableExpression statement params) db0 db1) where
1053− statement `as` cte = csingleton (statement `as` cte)
1372+ statement `as` cte = single (statement `as` cte)
1055−instance (forall c s p r. RenderSQL (statement c s p r)) => RenderSQL
1374+-- | render a `CommonTableExpression`.
1056− (CommonTableExpression statement schemas params commons0 commons1) where
1375+renderCommonTableExpression
1057− renderSQL (CommonTableExpression (statement `As` cte)) =
1376+ :: (forall db ps row. statement db ps row -> ByteString) -- ^ render statement
1058− renderSQL cte <+> "AS" <+> parenthesized (renderSQL statement)
1377+ -> CommonTableExpression statement params db0 db1 -> ByteString
1378+renderCommonTableExpression renderStatement
1379+ (CommonTableExpression (statement `As` alias)) =
1380+ renderSQL alias <+> "AS" <+> parenthesized (renderStatement statement)
1382+-- | render a non-empty `AlignedList` of `CommonTableExpression`s.
1383+renderCommonTableExpressions
1384+ :: (forall db ps row. statement db ps row -> ByteString) -- ^ render statement
1385+ -> CommonTableExpression statement params db0 db1
1386+ -> AlignedList (CommonTableExpression statement params) db1 db2
1388+renderCommonTableExpressions renderStatement cte ctes =
1389+ renderCommonTableExpression renderStatement cte <> case ctes of
1391+ cte' :>> ctes' -> "," <+>
1392+ renderCommonTableExpressions renderStatement cte' ctes'
1060-- | `with` provides a way to write auxiliary statements for use in a larger query.
1394-- | `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
1395-- These statements, referred to as `CommonTableExpression`s, can be thought of as
1062-- defining temporary tables that exist just for one query.
1396-- defining temporary tables that exist just for one query.
1063class With statement where
1397class With statement where
1065− :: Path (CommonTableExpression statement schemas params) commons0 commons1
1399+ :: AlignedList (CommonTableExpression statement params) db0 db1
1066 -- ^ common table expressions
1400 -- ^ common table expressions
1067− -> statement commons1 schemas params row
1401+ -> statement db1 params row
1068 -- ^ larger query
1402 -- ^ larger query
1069− -> statement commons0 schemas params row
1403+ -> statement db0 params row
1070−instance With (Query outer) where
1404+instance With Query where
1071 with Done query = query
1405 with Done query = query
1072− with ctes query = UnsafeQuery $
1406+ with (cte :>> ctes) query = UnsafeQuery $
1073− "WITH" <+> commaSeparated (ctoList renderSQL ctes) <+> renderSQL query
1407+ "WITH" <+> renderCommonTableExpressions renderQuery cte ctes
1074−
1408+ <+> renderQuery 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
1097− <+> "AS" <+> parenthesized (renderSQL recursive)
1098− <+> renderSQL query