@@ -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
36− , Query (..)
33+ Query (..)
37 -- ** Select
34 -- ** Select
40 , selectDistinct
37 , selectDistinct
41 , selectDistinct_
38 , selectDistinct_
44 , Selection (..)
39 , Selection (..)
45 -- ** Values
40 -- ** Values
@@ -55,13 +50,30 @@ 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 (..)
67 -- * From Clauses
79 -- * From Clauses
@@ -79,11 +91,39 @@ module Squeal.PostgreSQL.Query
80 , GroupByClause (..)
92 , GroupByClause (..)
81 , HavingClause (..)
93 , HavingClause (..)
95+ , SortExpression (..)
96+ -- * Subquery Expressions
84import Control.DeepSeq
125import Control.DeepSeq
85import Data.ByteString (ByteString)
126import Data.ByteString (ByteString)
86−import Data.Kind (Type)
87import Data.String
127import Data.String
88import Data.Word
128import Data.Word
89import Generics.SOP hiding (from)
129import Generics.SOP hiding (from)
@@ -91,67 +131,13 @@ import GHC.TypeLits
92import qualified GHC.Generics as GHC
132import qualified GHC.Generics as GHC
94−import Squeal.PostgreSQL.Alias
95import Squeal.PostgreSQL.Expression
134import 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
135import Squeal.PostgreSQL.Render
102import Squeal.PostgreSQL.Schema
136import 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
139+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.
140+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:
142simple query:
@@ -159,7 +145,7 @@ simple query:
159>>> type Schema = '["tab" ::: 'Table ('[] :=> Columns)]
145>>> type Schema = '["tab" ::: 'Table ('[] :=> Columns)]
162− query :: Query_ (Public Schema) () (Row Int32 Int32)
148+ query :: Query (DBof (Public Schema)) '[] '["col1" ::: 'NotNull 'PGint4, "col2" ::: 'NotNull 'PGint4]
163 query = select Star (from (table #tab))
149 query = select Star (from (table #tab))
164in printSQL query
150in printSQL query
@@ -169,21 +155,21 @@ restricted query:
172− query :: Query_ (Public Schema) () (Row Int32 Int32)
158+ query :: Query (DBof (Public Schema)) '[] '["sum" ::: 'NotNull 'PGint4, "col1" ::: 'NotNull 'PGint4]
174− select_ ((#col1 + #col2) `as` #col1 :* #col1 `as` #col2)
160+ select_ ((#col1 + #col2) `as` #sum :* #col1)
175 ( from (table #tab)
161 ( from (table #tab)
176 & where_ (#col1 .> #col2)
162 & where_ (#col1 .> #col2)
177 & where_ (#col2 .> 0) )
163 & where_ (#col2 .> 0) )
178in printSQL query
164in printSQL query
180−SELECT ("col1" + "col2") AS "col1", "col1" AS "col2" FROM "tab" AS "tab" WHERE (("col1" > "col2") AND ("col2" > 0))
166+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)
172+ query :: Query (DBof (Public Schema)) '[] '["col1" ::: 'NotNull 'PGint4, "col2" ::: 'NotNull 'PGint4]
187 query = select Star (from (subquery (select Star (from (table #tab)) `as` #sub)))
173 query = select Star (from (subquery (select Star (from (table #tab)) `as` #sub)))
188in printSQL query
174in printSQL query
@@ -193,7 +179,7 @@ limits and offsets:
196− query :: Query_ (Public Schema) () (Row Int32 Int32)
182+ 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)
183 query = select Star (from (table #tab) & limit 100 & offset 2 & limit 50 & offset 2)
198in printSQL query
184in printSQL query
@@ -203,7 +189,7 @@ parameterized query:
206− query :: Query_ (Public Schema) (Only Int32) (Row Int32 Int32)
192+ query :: Query (DBof (Public Schema)) '[ 'NotNull 'PGint4] '["col1" ::: 'NotNull 'PGint4, "col2" ::: 'NotNull 'PGint4]
207 query = select Star (from (table #tab) & where_ (#col1 .> param @1))
193 query = select Star (from (table #tab) & where_ (#col1 .> param @1))
208in printSQL query
194in printSQL query
@@ -213,21 +199,21 @@ aggregation query:
216− query :: Query_ (Public Schema) () (Row Int64 Int32)
202+ query :: Query (DBof (Public Schema)) '[] '["sum" ::: 'NotNull 'PGint4, "col1" ::: 'NotNull 'PGint4 ]
218− select_ ((fromNull 0 (sum_ (All #col2))) `as` #col1 :* #col1 `as` #col2)
204+ select_ (sum_ #col2 `as` #sum :* #col1)
219 ( from (table (#tab `as` #table1))
205 ( from (table (#tab `as` #table1))
220 & groupBy #col1
206 & groupBy #col1
221− & having (sum_ (Distinct #col2) .> 1) )
207+ & having (#col1 + sum_ #col2 .> 1) )
222in printSQL query
208in 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)
210+SELECT sum("col2") AS "sum", "col1" AS "col1" FROM "tab" AS "table1" GROUP BY "col1" HAVING (("col1" + sum("col2")) > 1)
226sorted query:
212sorted query:
230− query :: Query_ (Public Schema) () (Row Int32 Int32)
216+ query :: Query (DBof (Public Schema)) '[] '["col1" ::: 'NotNull 'PGint4, "col2" ::: 'NotNull 'PGint4]
231 query = select Star (from (table #tab) & orderBy [#col1 & Asc])
217 query = select Star (from (table #tab) & orderBy [#col1 & Asc])
232in printSQL query
218in printSQL query
@@ -235,12 +221,14 @@ SELECT * FROM "tab" AS "tab" ORDER BY "col1" ASC
224+>>> :set -XFlexibleContexts
239type OrdersColumns =
226type OrdersColumns =
240 '[ "id" ::: 'NoDef :=> 'NotNull 'PGint4
227 '[ "id" ::: 'NoDef :=> 'NotNull 'PGint4
241− , "price" ::: 'NoDef :=> 'NotNull 'PGfloat4
228+ , "price" ::: 'NoDef :=> 'NotNull 'PGfloat4
242− , "customer_id" ::: 'NoDef :=> 'NotNull 'PGint4
229+ , "customer_id" ::: 'NoDef :=> 'NotNull 'PGint4
243− , "shipper_id" ::: 'NoDef :=> 'NotNull 'PGint4 ]
230+ , "shipper_id" ::: 'NoDef :=> 'NotNull 'PGint4
@@ -256,27 +244,22 @@ type OrdersConstraints =
257type OrdersSchema =
245type OrdersSchema =
258 '[ "orders" ::: 'Table (OrdersConstraints :=> OrdersColumns)
246 '[ "orders" ::: 'Table (OrdersConstraints :=> OrdersColumns)
259− , "customers" ::: 'Table (CustomersConstraints :=> NamesColumns)
247+ , "customers" ::: 'Table (CustomersConstraints :=> NamesColumns)
260− , "shippers" ::: 'Table (ShippersConstraints :=> NamesColumns) ]
248+ , "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
253+ query :: Query (DBof (Public OrdersSchema))
255+ '[ "order_price" ::: 'NotNull 'PGfloat4
256+ , "customer_name" ::: 'NotNull 'PGtext
257+ , "shipper_name" ::: 'NotNull 'PGtext
276 query = select_
259 query = select_
277− ( #o ! #price `as` #price :*
260+ ( #o ! #price `as` #order_price :*
278− #c ! #name `as` #customerName :*
261+ #c ! #name `as` #customer_name :*
279− #s ! #name `as` #shipperName )
262+ #s ! #name `as` #shipper_name )
280 ( from (table (#orders `as` #o)
263 ( from (table (#orders `as` #o)
281 & innerJoin (table (#customers `as` #c))
264 & innerJoin (table (#customers `as` #c))
282 (#o ! #customer_id .== #c ! #id)
265 (#o ! #customer_id .== #c ! #id)
@@ -284,16 +267,14 @@ let
284 (#o ! #shipper_id .== #s ! #id)) )
267 (#o ! #shipper_id .== #s ! #id)) )
285in printSQL query
268in 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")
270+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:
272self-join:
293− query :: Query_ (Public Schema) () (Row Int32 Int32)
276+ query :: Query (DBof (Public Schema)) '[] '["col1" ::: 'NotNull 'PGint4, "col2" ::: 'NotNull 'PGint4]
296− (from (table (#tab `as` #t1) & crossJoin (table (#tab `as` #t2))))
277+ query = select (#t1 & DotStar) (from (table (#tab `as` #t1) & crossJoin (table (#tab `as` #t2))))
297in printSQL query
278in printSQL query
299SELECT "t1".* FROM "tab" AS "t1" CROSS JOIN "tab" AS "t2"
280SELECT "t1".* FROM "tab" AS "t1" CROSS JOIN "tab" AS "t2"
@@ -302,19 +283,17 @@ value queries:
305− query :: Query_ schemas () (Row String Bool)
286+ query :: Query db '[] '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
306− query = values
287+ 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
288in printSQL query
311−SELECT * FROM (VALUES (E'true', TRUE), (E'false', FALSE)) AS t ("col1", "col2")
290+SELECT * FROM (VALUES (1, TRUE), (2, FALSE)) AS t ("foo", "bar")
313set operations:
292set operations:
317− query :: Query_ (Public Schema) () (Row Int32 Int32)
296+ query :: Query (DBof (Public Schema)) '[] '["col1" ::: 'NotNull 'PGint4, "col2" ::: 'NotNull 'PGint4]
318 query = select Star (from (table #tab)) `unionAll` select Star (from (table #tab))
297 query = select Star (from (table #tab)) `unionAll` select Star (from (table #tab))
319in printSQL query
298in printSQL query
@@ -324,7 +303,7 @@ with queries:
327− query :: Query_ (Public Schema) () (Row Int32 Int32)
306+ query :: Query (DBof (Public Schema)) '[] '["col1" ::: 'NotNull 'PGint4, "col2" ::: 'NotNull 'PGint4]
328 query = with (
307 query = with (
329 select Star (from (table #tab)) `as` #cte1 :>>
308 select Star (from (table #tab)) `as` #cte1 :>>
330 select Star (from (common #cte1)) `as` #cte2
309 select Star (from (common #cte1)) `as` #cte2
@@ -332,47 +311,21 @@ let
332in printSQL query
311in printSQL query
334WITH "cte1" AS (SELECT * FROM "tab" AS "tab"), "cte2" AS (SELECT * FROM "cte1" AS "cte1") SELECT * FROM "cte2" AS "cte2"
313WITH "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_
315+newtype Query
364− (schemas :: SchemasType)
316+ (db :: DBType)
365− (parameters :: Type)
317+ (params :: [NullityType])
366− (row :: Type) where
318+ (columns :: RowType)
367− Query_ schemas params row =
319+ = UnsafeQuery { renderQuery :: ByteString }
368− Query '[] '[] schemas (TuplePG params) (RowPG row)
320+ deriving (GHC.Generic,Show,Eq,Ord,NFData)
321+instance RenderSQL (Query db params columns) where renderSQL = renderQuery
370-- | The results of two queries can be combined using the set operation
323-- | The results of two queries can be combined using the set operation
371-- `union`. Duplicate rows are eliminated.
324-- `union`. Duplicate rows are eliminated.
373− :: Query outer commons schemas params columns
326+ :: Query db params columns
374− -> Query outer commons schemas params columns
327+ -> Query db params columns
375− -> Query outer commons schemas params columns
328+ -> Query db params columns
376q1 `union` q2 = UnsafeQuery $
329q1 `union` q2 = UnsafeQuery $
377 parenthesized (renderSQL q1)
330 parenthesized (renderSQL q1)
378 <+> "UNION"
331 <+> "UNION"
@@ -381,9 +334,9 @@ q1 `union` q2 = UnsafeQuery $
381-- | The results of two queries can be combined using the set operation
334-- | The results of two queries can be combined using the set operation
382-- `unionAll`, the disjoint union. Duplicate rows are retained.
335-- `unionAll`, the disjoint union. Duplicate rows are retained.
384− :: Query outer commons schemas params columns
337+ :: Query db params columns
385− -> Query outer commons schemas params columns
338+ -> Query db params columns
386− -> Query outer commons schemas params columns
339+ -> Query db params columns
387q1 `unionAll` q2 = UnsafeQuery $
340q1 `unionAll` q2 = UnsafeQuery $
388 parenthesized (renderSQL q1)
341 parenthesized (renderSQL q1)
389 <+> "UNION" <+> "ALL"
342 <+> "UNION" <+> "ALL"
@@ -392,9 +345,9 @@ q1 `unionAll` q2 = UnsafeQuery $
392-- | The results of two queries can be combined using the set operation
345-- | The results of two queries can be combined using the set operation
393-- `intersect`, the intersection. Duplicate rows are eliminated.
346-- `intersect`, the intersection. Duplicate rows are eliminated.
395− :: Query outer commons schemas params columns
348+ :: Query db params columns
396− -> Query outer commons schemas params columns
349+ -> Query db params columns
397− -> Query outer commons schemas params columns
350+ -> Query db params columns
398q1 `intersect` q2 = UnsafeQuery $
351q1 `intersect` q2 = UnsafeQuery $
399 parenthesized (renderSQL q1)
352 parenthesized (renderSQL q1)
400 <+> "INTERSECT"
353 <+> "INTERSECT"
@@ -403,9 +356,9 @@ q1 `intersect` q2 = UnsafeQuery $
403-- | The results of two queries can be combined using the set operation
356-- | The results of two queries can be combined using the set operation
404-- `intersectAll`, the intersection. Duplicate rows are retained.
357-- `intersectAll`, the intersection. Duplicate rows are retained.
405intersectAll
358intersectAll
406− :: Query outer commons schemas params columns
359+ :: Query db params columns
407− -> Query outer commons schemas params columns
360+ -> Query db params columns
408− -> Query outer commons schemas params columns
361+ -> Query db params columns
409q1 `intersectAll` q2 = UnsafeQuery $
362q1 `intersectAll` q2 = UnsafeQuery $
410 parenthesized (renderSQL q1)
363 parenthesized (renderSQL q1)
411 <+> "INTERSECT" <+> "ALL"
364 <+> "INTERSECT" <+> "ALL"
@@ -414,9 +367,9 @@ q1 `intersectAll` q2 = UnsafeQuery $
414-- | The results of two queries can be combined using the set operation
367-- | The results of two queries can be combined using the set operation
415-- `except`, the set difference. Duplicate rows are eliminated.
368-- `except`, the set difference. Duplicate rows are eliminated.
417− :: Query outer commons schemas params columns
370+ :: Query db params columns
418− -> Query outer commons schemas params columns
371+ -> Query db params columns
419− -> Query outer commons schemas params columns
372+ -> Query db params columns
420q1 `except` q2 = UnsafeQuery $
373q1 `except` q2 = UnsafeQuery $
421 parenthesized (renderSQL q1)
374 parenthesized (renderSQL q1)
422 <+> "EXCEPT"
375 <+> "EXCEPT"
@@ -425,9 +378,9 @@ q1 `except` q2 = UnsafeQuery $
425-- | The results of two queries can be combined using the set operation
378-- | The results of two queries can be combined using the set operation
426-- `exceptAll`, the set difference. Duplicate rows are retained.
379-- `exceptAll`, the set difference. Duplicate rows are retained.
428− :: Query outer commons schemas params columns
381+ :: Query db params columns
429− -> Query outer commons schemas params columns
382+ -> Query db params columns
430− -> Query outer commons schemas params columns
383+ -> Query db params columns
431q1 `exceptAll` q2 = UnsafeQuery $
384q1 `exceptAll` q2 = UnsafeQuery $
432 parenthesized (renderSQL q1)
385 parenthesized (renderSQL q1)
433 <+> "EXCEPT" <+> "ALL"
386 <+> "EXCEPT" <+> "ALL"
@@ -437,90 +390,54 @@ q1 `exceptAll` q2 = UnsafeQuery $
437SELECT queries
390SELECT queries
438-----------------------------------------}
391-----------------------------------------}
440−{- | The simplest kinds of `Selection` are `Star` and `DotStar` which
393+data Selection db params grp from row where
441−emits all columns that a `TableExpression` produces. A select `List`
394+ List
442−is a list of `Expression`s. A `Selection` could be a list of
395+ :: SListI row
443−`WindowFunction`s `Over` `WindowDefinition`. `Additional` `Selection`s can
396+ => NP (Aliased (Expression db params grp from)) row
444−be selected with `Also`.
446−data Selection outer commons grp schemas params from row where
397+ -> Selection db params grp from row
448 :: HasUnique tab from row
399 :: HasUnique tab from row
449− => Selection outer commons 'Ungrouped schemas params from row
400+ => Selection db params 'Ungrouped from row
450− -- ^ `HasUnique` table in the `FromClause`
452 :: Has tab from row
402 :: Has tab from row
453 => Alias tab
403 => Alias tab
454− -- ^ `Has` table with `Alias`
455− -> Selection outer commons 'Ungrouped schemas params from row
404+ -> Selection db params 'Ungrouped 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
406+ :: Selection db params grp from right
469− -- ^ `Additional` `Selection`
470− -> Selection outer commons grp schemas params from left
407+ -> Selection db params grp from left
471− -> Selection outer commons grp schemas params from (Join left right)
408+ -> Selection db params grp from (Join left right)
472−instance Additional (Selection outer commons grp schemas params from) where
474instance (KnownSymbol col, row ~ '[col ::: ty])
409instance (KnownSymbol col, row ~ '[col ::: ty])
475 => Aliasable col
410 => Aliasable col
476− (Expression outer commons grp schemas params from ty)
411+ (Expression db params grp from ty)
477− (Selection outer commons grp schemas params from row) where
412+ (Selection db params grp from row) where
478 expr `as` col = List (expr `as` col)
413 expr `as` col = List (expr `as` col)
479−instance (Has tab (Join outer from) row0, Has col row0 ty, row1 ~ '[col ::: ty])
414+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
415+ => IsQualified tab col (Selection db params 'Ungrouped from row1) where
482− tab ! col = tab ! col `as` col
416+ tab ! col = tab ! col `as` col
484− ( Has tab (Join outer from) row0
418+ ( Has tab from row0
485 , Has col row0 ty
419 , Has col row0 ty
486 , row1 ~ '[col ::: ty]
420 , row1 ~ '[col ::: ty]
487 , GroupedBy tab col bys )
421 , GroupedBy tab col bys )
488− => IsQualified tab col
489− (Selection outer commons ('Grouped bys) schemas params from row1) where
422+ => IsQualified tab col (Selection db params ('Grouped bys) from row1) where
490− tab ! col = tab ! col `as` col
423+ tab ! col = tab ! col `as` col
491−instance (HasUnique tab (Join outer from) row0, Has col row0 ty, row1 ~ '[col ::: ty])
424+instance (HasUnique tab from row0, Has col row0 ty, row1 ~ '[col ::: ty])
493− (Selection outer commons 'Ungrouped schemas params from row1) where
425+ => IsLabel col (Selection db params 'Ungrouped from row1) where
494− fromLabel = fromLabel @col `as` Alias
426+ fromLabel = fromLabel @col `as` Alias
496− ( HasUnique tab (Join outer from) row0
428+ ( HasUnique tab from row0
497 , Has col row0 ty
429 , Has col row0 ty
498 , row1 ~ '[col ::: ty]
430 , row1 ~ '[col ::: ty]
499 , GroupedBy tab col bys )
431 , GroupedBy tab col bys )
501− (Selection outer commons ('Grouped bys) schemas params from row1) where
432+ => IsLabel col (Selection db params ('Grouped bys) from row1) where
502− fromLabel = fromLabel @col `as` Alias
433+ fromLabel = fromLabel @col `as` Alias
504−instance RenderSQL (Selection outer commons grp schemas params from row) where
435+instance RenderSQL (Selection db params grp from row) where
505 renderSQL = \case
436 renderSQL = \case
506 List list -> renderCommaSeparated (renderAliased renderSQL) list
437 List list -> renderCommaSeparated (renderAliased renderSQL) list
507 Star -> "*"
438 Star -> "*"
508 DotStar tab -> renderSQL tab <> ".*"
439 DotStar tab -> renderSQL tab <> ".*"
509 Also right left -> renderSQL left <> ", " <> renderSQL right
440 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
442-- | the `TableExpression` in the `select` command constructs an intermediate
526-- virtual table by possibly combining tables, views, eliminating rows,
443-- virtual table by possibly combining tables, views, eliminating rows,
@@ -529,100 +446,45 @@ instance IsString
529-- the intermediate table are actually output.
446-- the intermediate table are actually output.
531 :: (SListI row, row ~ (x ': xs))
448 :: (SListI row, row ~ (x ': xs))
532− => Selection outer commons grp schemas params from row
449+ => Selection db params grp from row
533− -- ^ selection
450+ -- ^ select list
534− -> TableExpression outer commons grp schemas params from
451+ -> TableExpression db params grp from
535 -- ^ intermediate virtual table
452 -- ^ intermediate virtual table
536− -> Query outer commons schemas params row
453+ -> Query db params row
537select selection tabexpr = UnsafeQuery $
454select selection tabexpr = UnsafeQuery $
539 <+> renderSQL selection
456 <+> renderSQL selection
540 <+> renderSQL tabexpr
457 <+> 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))
460 :: (SListI row, row ~ (x ': xs))
546− => NP (Aliased (Expression outer commons grp schemas params from)) row
461+ => NP (Aliased (Expression db params grp from)) row
548− -> TableExpression outer commons grp schemas params from
462+ -> TableExpression db params grp from
549− -- ^ intermediate virtual table
550− -> Query outer commons schemas params row
463+ -> Query db params row
551−select_ = select . List
464+select_ list = select (List list)
553-- | After the select list has been processed, the result table can
466-- | After the select list has been processed, the result table can
554-- be subject to the elimination of duplicate rows using `selectDistinct`.
467-- be subject to the elimination of duplicate rows using `selectDistinct`.
555selectDistinct
468selectDistinct
556 :: (SListI columns, columns ~ (col ': cols))
469 :: (SListI columns, columns ~ (col ': cols))
557− => Selection outer commons grp schemas params from columns
470+ => Selection db params 'Ungrouped from columns
558− -- ^ selection
471+ -- ^ select list
559− -> TableExpression outer commons grp schemas params from
472+ -> TableExpression db params 'Ungrouped from
560 -- ^ intermediate virtual table
473 -- ^ intermediate virtual table
561− -> Query outer commons schemas params columns
474+ -> Query db params columns
562selectDistinct selection tabexpr = UnsafeQuery $
475selectDistinct selection tabexpr = UnsafeQuery $
563 "SELECT DISTINCT"
476 "SELECT DISTINCT"
564 <+> renderSQL selection
477 <+> renderSQL selection
565 <+> renderSQL tabexpr
478 <+> renderSQL tabexpr
567−-- | Like `selectDistinct` but takes an `NP` list of `Expression`s instead
568−-- of a general `Selection`.
569selectDistinct_
480selectDistinct_
570 :: (SListI columns, columns ~ (col ': cols))
481 :: (SListI columns, columns ~ (col ': cols))
571− => NP (Aliased (Expression outer commons grp schemas params from)) columns
482+ => NP (Aliased (Expression db params 'Ungrouped from)) columns
572 -- ^ select list
483 -- ^ select list
573− -> TableExpression outer commons grp schemas params from
484+ -> TableExpression db params 'Ungrouped from
574 -- ^ intermediate virtual table
485 -- ^ intermediate virtual table
575− -> Query outer commons schemas params columns
486+ -> Query db params columns
576−selectDistinct_ = selectDistinct . List
487+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
489-- | `values` computes a row value or set of row values
628-- specified by value expressions. It is most commonly used
490-- specified by value expressions. It is most commonly used
@@ -630,16 +492,16 @@ selectDistinctOn_ distincts = selectDistinctOn distincts . List
630-- but it can be used on its own.
492-- but it can be used on its own.
632-- >>> type Row = '["a" ::: 'NotNull 'PGint4, "b" ::: 'NotNull 'PGtext]
494-- >>> type Row = '["a" ::: 'NotNull 'PGint4, "b" ::: 'NotNull 'PGtext]
633−-- >>> let query = values (1 `as` #a :* "one" `as` #b) [] :: Query outer commons schemas '[] Row
495+-- >>> let query = values (1 `as` #a :* "one" `as` #b) [] :: Query db '[] Row
634-- >>> printSQL query
496-- >>> printSQL query
635-- SELECT * FROM (VALUES (1, E'one')) AS t ("a", "b")
497-- SELECT * FROM (VALUES (1, E'one')) AS t ("a", "b")
637 :: SListI cols
499 :: SListI cols
638− => NP (Aliased (Expression outer commons 'Ungrouped schemas params '[] )) cols
500+ => NP (Aliased (Expression db params 'Ungrouped '[] )) cols
639− -> [NP (Aliased (Expression outer commons 'Ungrouped schemas params '[] )) cols]
501+ -> [NP (Aliased (Expression db params 'Ungrouped '[] )) cols]
640 -- ^ When more than one row is specified, all the rows must
502 -- ^ When more than one row is specified, all the rows must
641 -- must have the same number of elements
503 -- must have the same number of elements
642− -> Query outer commons schemas params cols
504+ -> Query db params cols
643values rw rws = UnsafeQuery $ "SELECT * FROM"
505values rw rws = UnsafeQuery $ "SELECT * FROM"
644 <+> parenthesized (
506 <+> parenthesized (
@@ -650,7 +512,7 @@ values rw rws = UnsafeQuery $ "SELECT * FROM"
650 <+> parenthesized (renderCommaSeparated renderAliasPart rw)
512 <+> parenthesized (renderCommaSeparated renderAliasPart rw)
652 renderAliasPart, renderValuePart
514 renderAliasPart, renderValuePart
653− :: Aliased (Expression outer commons 'Ungrouped schemas params '[] ) ty -> ByteString
515+ :: Aliased (Expression db params 'Ungrouped '[] ) ty -> ByteString
654 renderAliasPart (_ `As` name) = renderSQL name
516 renderAliasPart (_ `As` name) = renderSQL name
655 renderValuePart (value `As` _) = renderSQL value
517 renderValuePart (value `As` _) = renderSQL value
@@ -658,9 +520,9 @@ values rw rws = UnsafeQuery $ "SELECT * FROM"
658-- specified by value expressions.
520-- specified by value expressions.
660 :: SListI cols
522 :: SListI cols
661− => NP (Aliased (Expression outer commons 'Ungrouped schemas params '[] )) cols
523+ => NP (Aliased (Expression db params 'Ungrouped '[] )) cols
662 -- ^ one row of values
524 -- ^ one row of values
663− -> Query outer commons schemas params cols
525+ -> Query db params cols
664values_ rw = values rw []
526values_ rw = values rw []
666{-----------------------------------------
528{-----------------------------------------
@@ -674,17 +536,15 @@ Table Expressions
674-- to a table on disk, a so-called base table, but more complex expressions
536-- 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.
537-- can be used to modify or combine base tables in various ways.
676data TableExpression
538data TableExpression
677− (outer :: FromType)
539+ (db :: DBType)
678− (commons :: FromType)
680− (schemas :: SchemasType)
681 (params :: [NullityType])
540 (params :: [NullityType])
682 (from :: FromType)
542 (from :: FromType)
683 = TableExpression
543 = TableExpression
684− { fromClause :: FromClause outer commons schemas params from
544+ { fromClause :: FromClause db params from
685 -- ^ A table reference that can be a table name, or a derived table such
545 -- ^ 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.
546 -- as a subquery, a @JOIN@ construct, or complex combinations of these.
687− , whereClause :: [Condition outer commons 'Ungrouped schemas params from]
547+ , whereClause :: [Condition db params 'Ungrouped from]
688 -- ^ optional search coditions, combined with `.&&`. After the processing
548 -- ^ optional search coditions, combined with `.&&`. After the processing
689 -- of the `fromClause` is done, each row of the derived virtual table
549 -- of the `fromClause` is done, each row of the derived virtual table
690 -- is checked against the search condition. If the result of the
550 -- is checked against the search condition. If the result of the
@@ -700,13 +560,13 @@ data TableExpression
700 -- set of rows having common values into one group row that represents all
560 -- 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
561 -- rows in the group. This is done to eliminate redundancy in the output
702 -- and/or compute aggregates that apply to these groups.
562 -- and/or compute aggregates that apply to these groups.
703− , havingClause :: HavingClause outer commons grp schemas params from
563+ , havingClause :: HavingClause db params grp from
704 -- ^ If a table has been grouped using `groupBy`, but only certain groups
564 -- ^ If a table has been grouped using `groupBy`, but only certain groups
705 -- are of interest, the `havingClause` can be used, much like a
565 -- are of interest, the `havingClause` can be used, much like a
706 -- `whereClause`, to eliminate groups from the result. Expressions in the
566 -- `whereClause`, to eliminate groups from the result. Expressions in the
707 -- `havingClause` can refer both to grouped expressions and to ungrouped
567 -- `havingClause` can refer both to grouped expressions and to ungrouped
708 -- expressions (which necessarily involve an aggregate function).
568 -- expressions (which necessarily involve an aggregate function).
709− , orderByClause :: [SortExpression outer commons grp schemas params from]
569+ , orderByClause :: [SortExpression db params grp from]
710 -- ^ The `orderByClause` is for optional sorting. When more than one
570 -- ^ The `orderByClause` is for optional sorting. When more than one
711 -- `SortExpression` is specified, the later (right) values are used to sort
571 -- `SortExpression` is specified, the later (right) values are used to sort
712 -- rows that are equal according to the earlier (left) values.
572 -- rows that are equal according to the earlier (left) values.
@@ -716,14 +576,14 @@ data TableExpression
716 -- will be returned (but possibly fewer, if the query itself yields
576 -- will be returned (but possibly fewer, if the query itself yields
717 -- fewer rows).
577 -- fewer rows).
718 , offsetClause :: [Word64]
578 , offsetClause :: [Word64]
719− -- ^ The `offsetClause` is combined with `Prelude.+` to give an offset count
579+ -- ^ The `offsetClause` is combined with `+` to give an offset count
720 -- if nonempty. The offset count says to skip that many rows before
580 -- 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
581 -- beginning to return rows. The rows are skipped before the limit count
722 -- is applied.
582 -- is applied.
723− } deriving (GHC.Generic)
583+ }
725-- | Render a `TableExpression`
585-- | Render a `TableExpression`
726−instance RenderSQL (TableExpression outer commons grp schemas params from) where
586+instance RenderSQL (TableExpression db params grp from) where
727 renderSQL
587 renderSQL
728 (TableExpression frm' whs' grps' hvs' srts' lims' offs') = mconcat
588 (TableExpression frm' whs' grps' hvs' srts' lims' offs') = mconcat
729 [ "FROM ", renderSQL frm'
589 [ "FROM ", renderSQL frm'
@@ -732,7 +592,8 @@ instance RenderSQL (TableExpression outer commons grp schemas params from) where
732 , renderSQL hvs'
592 , renderSQL hvs'
733 , renderOrderByClause srts'
593 , renderOrderByClause srts'
734 , renderLimits lims'
594 , renderLimits lims'
735− , renderOffsets offs' ]
595+ , renderOffsets offs'
737 renderWheres = \case
598 renderWheres = \case
@@ -752,33 +613,33 @@ instance RenderSQL (TableExpression outer commons grp schemas params from) where
752-- | A `from` generates a `TableExpression` from a table reference that can be
613-- | 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,
614-- 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_`,
615-- or complex combinations of these. A `from` may be transformed by `where_`,
755−-- `groupBy`, `having`, `orderBy`, `limit` and `offset`, using the `&` operator
616+-- `group`, `having`, `orderBy`, `limit` and `offset`, using the `&` operator
756-- to match the left-to-right sequencing of their placement in SQL.
617-- to match the left-to-right sequencing of their placement in SQL.
758− :: FromClause outer commons schemas params from -- ^ table reference
619+ :: FromClause db params from -- ^ table reference
759− -> TableExpression outer commons 'Ungrouped schemas params from
620+ -> TableExpression db params 'Ungrouped from
760−from tab = TableExpression tab [] noGroups NoHaving [] [] []
621+from rels = TableExpression rels [] NoGroups NoHaving [] [] []
762-- | A `where_` is an endomorphism of `TableExpression`s which adds a
623-- | A `where_` is an endomorphism of `TableExpression`s which adds a
763-- search condition to the `whereClause`.
624-- search condition to the `whereClause`.
765− :: Condition outer commons 'Ungrouped schemas params from -- ^ filtering condition
626+ :: Condition db params 'Ungrouped from -- ^ filtering condition
766− -> TableExpression outer commons grp schemas params from
627+ -> TableExpression db params grp from
767− -> TableExpression outer commons grp schemas params from
628+ -> TableExpression db params grp from
768where_ wh rels = rels {whereClause = wh : whereClause rels}
629where_ wh rels = rels {whereClause = wh : whereClause rels}
770-- | A `groupBy` is a transformation of `TableExpression`s which switches
631-- | A `groupBy` is a transformation of `TableExpression`s which switches
771−-- its `Grouping` from `Ungrouped` to `Grouped`. Use @groupBy Nil@ to perform
632+-- its `Grouping` from `Ungrouped` to `Grouped`. Use @group Nil@ to perform
772-- a "grand total" aggregation query.
633-- a "grand total" aggregation query.
774 :: SListI bys
635 :: SListI bys
775 => NP (By from) bys -- ^ grouped columns
636 => NP (By from) bys -- ^ grouped columns
776− -> TableExpression outer commons 'Ungrouped schemas params from
637+ -> TableExpression db params 'Ungrouped from
777− -> TableExpression outer commons ('Grouped bys) schemas params from
638+ -> TableExpression db params ('Grouped bys) from
778groupBy bys rels = TableExpression
639groupBy bys rels = TableExpression
779 { fromClause = fromClause rels
640 { fromClause = fromClause rels
780 , whereClause = whereClause rels
641 , whereClause = whereClause rels
781− , groupByClause = group bys
642+ , groupByClause = Group bys
782 , havingClause = Having []
643 , havingClause = Having []
783 , orderByClause = []
644 , orderByClause = []
784 , limitClause = limitClause rels
645 , limitClause = limitClause rels
@@ -788,31 +649,177 @@ groupBy bys rels = TableExpression
788-- | A `having` is an endomorphism of `TableExpression`s which adds a
649-- | A `having` is an endomorphism of `TableExpression`s which adds a
789-- search condition to the `havingClause`.
650-- search condition to the `havingClause`.
791− :: Condition outer commons ('Grouped bys) schemas params from -- ^ having condition
652+ :: Condition db params ('Grouped bys) from -- ^ having condition
792− -> TableExpression outer commons ('Grouped bys) schemas params from
653+ -> TableExpression db params ('Grouped bys) from
793− -> TableExpression outer commons ('Grouped bys) schemas params from
654+ -> TableExpression db params ('Grouped bys) from
794having hv rels = rels
655having hv rels = rels
795 { havingClause = case havingClause rels of Having hvs -> Having (hv:hvs) }
656 { havingClause = case havingClause rels of Having hvs -> Having (hv:hvs) }
658+-- | An `orderBy` is an endomorphism of `TableExpression`s which appends an
659+-- ordering to the right of the `orderByClause`.
661+ :: [SortExpression db params grp from] -- ^ sort expressions
797−instance OrderBy TableExpression where
662+ -> TableExpression db params grp from
663+ -> TableExpression db params grp from
798− orderBy srts rels = rels {orderByClause = orderByClause rels ++ srts}
664+orderBy srts rels = rels {orderByClause = orderByClause rels ++ srts}
800-- | A `limit` is an endomorphism of `TableExpression`s which adds to the
666-- | A `limit` is an endomorphism of `TableExpression`s which adds to the
801-- `limitClause`.
667-- `limitClause`.
803 :: Word64 -- ^ limit parameter
669 :: Word64 -- ^ limit parameter
804− -> TableExpression outer commons grp schemas params from
670+ -> TableExpression db params grp from
805− -> TableExpression outer commons grp schemas params from
671+ -> TableExpression db params grp from
806limit lim rels = rels {limitClause = lim : limitClause rels}
672limit lim rels = rels {limitClause = lim : limitClause rels}
808-- | An `offset` is an endomorphism of `TableExpression`s which adds to the
674-- | An `offset` is an endomorphism of `TableExpression`s which adds to the
809-- `offsetClause`.
675-- `offsetClause`.
811 :: Word64 -- ^ offset parameter
677 :: Word64 -- ^ offset parameter
812− -> TableExpression outer commons grp schemas params from
678+ -> TableExpression db params grp from
813− -> TableExpression outer commons grp schemas params from
679+ -> TableExpression db params grp from
814offset off rels = rels {offsetClause = off : offsetClause rels}
680offset off rels = rels {offsetClause = off : offsetClause rels}
682+{-----------------------------------------
684+-----------------------------------------}
688+ -> Expression db params 'Ungrouped '[] ty
689+ -> Query db params row
690+unsafeSetOfFunction fun expr = UnsafeQuery $
691+ "SELECT * FROM " <> fun <> "(" <> renderSQL expr <> ")"
693+-- | Expands the outermost JSON object into a set of key/value pairs.
695+ :: Expression db params 'Ungrouped '[] (nullity 'PGjson) -- ^ json object
697+ '["key" ::: 'NotNull 'PGtext, "value" ::: 'NotNull 'PGjson]
698+jsonEach = unsafeSetOfFunction "json_each"
700+-- | Expands the outermost binary JSON object into a set of key/value pairs.
702+ :: Expression db params 'Ungrouped '[] (nullity 'PGjsonb) -- ^ jsonb object
704+ '["key" ::: 'NotNull 'PGtext, "value" ::: 'NotNull 'PGjsonb]
705+jsonbEach = unsafeSetOfFunction "jsonb_each"
707+-- | Expands the outermost JSON object into a set of key/value pairs.
709+ :: Expression db params 'Ungrouped '[] (nullity 'PGjson) -- ^ json object
711+ '["key" ::: 'NotNull 'PGtext, "value" ::: 'NotNull 'PGtext]
712+jsonEachAsText = unsafeSetOfFunction "json_each_text"
714+-- | Expands the outermost binary JSON object into a set of key/value pairs.
716+ :: Expression db params 'Ungrouped '[] (nullity 'PGjsonb) -- ^ jsonb object
718+ '["key" ::: 'NotNull 'PGtext, "value" ::: 'NotNull 'PGtext]
719+jsonbEachAsText = unsafeSetOfFunction "jsonb_each_text"
721+-- | Returns set of keys in the outermost JSON object.
723+ :: Expression db params 'Ungrouped '[] (nullity 'PGjson) -- ^ json object
724+ -> Query db params '["json_object_keys" ::: 'NotNull 'PGtext]
725+jsonObjectKeys = unsafeSetOfFunction "json_object_keys"
727+-- | Returns set of keys in the outermost JSON object.
729+ :: Expression db params 'Ungrouped '[] (nullity 'PGjsonb) -- ^ jsonb object
730+ -> Query db params '["jsonb_object_keys" ::: 'NotNull 'PGtext]
731+jsonbObjectKeys = unsafeSetOfFunction "jsonb_object_keys"
733+unsafePopulateFunction
735+ -> TypeExpression schemas (nullity ('PGcomposite row))
736+ -> Expression (commons :=> schemas) params 'Ungrouped '[] ty
737+ -> Query (commons :=> schemas) params row
738+unsafePopulateFunction fun ty expr = UnsafeQuery $
739+ "SELECT * FROM " <> fun <> "("
740+ <> "null::" <> renderSQL ty <> ", "
741+ <> renderSQL expr <> ")"
743+-- | Expands the JSON expression to a row whose columns match the record
744+-- type defined by the given table.
746+ :: TypeExpression schemas (nullity ('PGcomposite row)) -- ^ row type
747+ -> Expression (commons :=> schemas) params 'Ungrouped '[] (nullity 'PGjson) -- ^ json object
748+ -> Query (commons :=> schemas) params row
749+jsonPopulateRecord = unsafePopulateFunction "json_populate_record"
751+-- | Expands the binary JSON expression to a row whose columns match the record
752+-- type defined by the given table.
754+ :: TypeExpression schemas (nullity ('PGcomposite row)) -- ^ row type
755+ -> Expression (commons :=> schemas) params 'Ungrouped '[] (nullity 'PGjsonb) -- ^ jsonb object
756+ -> Query (commons :=> schemas) params row
757+jsonbPopulateRecord = unsafePopulateFunction "jsonb_populate_record"
759+-- | Expands the outermost array of objects in the given JSON expression to a
760+-- set of rows whose columns match the record type defined by the given table.
761+jsonPopulateRecordSet
762+ :: TypeExpression schemas (nullity ('PGcomposite row)) -- ^ row type
763+ -> Expression (commons :=> schemas) params 'Ungrouped '[] (nullity 'PGjson) -- ^ json array
764+ -> Query (commons :=> schemas) params row
765+jsonPopulateRecordSet = unsafePopulateFunction "json_populate_record_set"
767+-- | Expands the outermost array of objects in the given binary JSON expression
768+-- to a set of rows whose columns match the record type defined by the given
770+jsonbPopulateRecordSet
771+ :: TypeExpression schemas (nullity ('PGcomposite row)) -- ^ row type
772+ -> Expression (commons :=> schemas) params 'Ungrouped '[] (nullity 'PGjsonb) -- ^ jsonb array
773+ -> Query (commons :=> schemas) params row
774+jsonbPopulateRecordSet = unsafePopulateFunction "jsonb_populate_record_set"
777+ :: (SListI record, json `In` PGJsonType)
779+ -> Expression (commons :=> schemas) params 'Ungrouped '[] (nullity json)
780+ -> NP (Aliased (TypeExpression schemas)) record
781+ -> Query (commons :=> schemas) params record
782+unsafeRecordFunction fun expr types = UnsafeQuery $
783+ "SELECT * FROM " <> fun <> "("
784+ <> renderSQL expr <> ")"
785+ <+> "AS" <+> "x" <> parenthesized (renderCommaSeparated renderTy types)
787+ renderTy :: Aliased (TypeExpression db) ty -> ByteString
788+ renderTy (ty `As` alias) =
789+ renderSQL alias <+> renderSQL ty
791+-- | Builds an arbitrary record from a JSON object.
794+ => Expression (commons :=> schemas) params 'Ungrouped '[] (nullity 'PGjson) -- ^ json object
795+ -> NP (Aliased (TypeExpression schemas)) record -- ^ record types
796+ -> Query (commons :=> schemas) params record
797+jsonToRecord = unsafeRecordFunction "json_to_record"
799+-- | Builds an arbitrary record from a binary JSON object.
802+ => Expression (commons :=> schemas) params 'Ungrouped '[] (nullity 'PGjsonb) -- ^ jsonb object
803+ -> NP (Aliased (TypeExpression schemas)) record -- ^ record types
804+ -> Query (commons :=> schemas) params record
805+jsonbToRecord = unsafeRecordFunction "jsonb_to_record"
807+-- | Builds an arbitrary set of records from a JSON array of objects.
810+ => Expression (commons :=> schemas) params 'Ungrouped '[] (nullity 'PGjson) -- ^ json array
811+ -> NP (Aliased (TypeExpression schemas)) record -- ^ record types
812+ -> Query (commons :=> schemas) params record
813+jsonToRecordSet = unsafeRecordFunction "json_to_record_set"
815+-- | Builds an arbitrary set of records from a binary JSON array of objects.
818+ => Expression (commons :=> schemas) params 'Ungrouped '[] (nullity 'PGjsonb) -- ^ jsonb array
819+ -> NP (Aliased (TypeExpression schemas)) record -- ^ record types
820+ -> Query (commons :=> schemas) params record
821+jsonbToRecordSet = unsafeRecordFunction "jsonb_to_record_set"
816{-----------------------------------------
823{-----------------------------------------
817FROM clauses
824FROM clauses
818-----------------------------------------}
825-----------------------------------------}
@@ -821,59 +828,53 @@ FROM clauses
821A `FromClause` can be a table name, or a derived table such
828A `FromClause` can be a table name, or a derived table such
822as a subquery, a @JOIN@ construct, or complex combinations of these.
829as a subquery, a @JOIN@ construct, or complex combinations of these.
824−newtype FromClause outer commons schemas params from
831+newtype FromClause db params from
825 = UnsafeFromClause { renderFromClause :: ByteString }
832 = UnsafeFromClause { renderFromClause :: ByteString }
826 deriving (GHC.Generic,Show,Eq,Ord,NFData)
833 deriving (GHC.Generic,Show,Eq,Ord,NFData)
827−instance RenderSQL (FromClause outer commons schemas params from) where
834+instance RenderSQL (FromClause db params from) where
828 renderSQL = renderFromClause
835 renderSQL = renderFromClause
830-- | A real `table` is a table from the database.
837-- | A real `table` is a table from the database.
832 :: (Has sch schemas schema, Has tab schema ('Table table))
839 :: (Has sch schemas schema, Has tab schema ('Table table))
833 => Aliased (QualifiedAlias sch) (alias ::: tab)
840 => Aliased (QualifiedAlias sch) (alias ::: tab)
834− -> FromClause outer commons schemas params '[alias ::: TableToRow table]
841+ -> FromClause (commons :=> schemas) params '[alias ::: TableToRow table]
835table (tab `As` alias) = UnsafeFromClause $
842table (tab `As` alias) = UnsafeFromClause $
836 renderSQL tab <+> "AS" <+> renderSQL alias
843 renderSQL tab <+> "AS" <+> renderSQL alias
838-- | `subquery` derives a table from a `Query`.
845-- | `subquery` derives a table from a `Query`.
840− :: Aliased (Query outer commons schemas params) query
847+ :: Aliased (Query db params) query
841− -> FromClause outer commons schemas params '[query]
848+ -> FromClause db params '[query]
842−subquery = UnsafeFromClause . renderAliased (parenthesized . renderSQL)
849+subquery = UnsafeFromClause . renderAliased (parenthesized . renderQuery)
844-- | `view` derives a table from a `View`.
851-- | `view` derives a table from a `View`.
846 :: (Has sch schemas schema, Has vw schema ('View view))
853 :: (Has sch schemas schema, Has vw schema ('View view))
847 => Aliased (QualifiedAlias sch) (alias ::: vw)
854 => Aliased (QualifiedAlias sch) (alias ::: vw)
848− -> FromClause outer commons schemas params '[alias ::: view]
855+ -> FromClause (commons :=> schemas) params '[alias ::: view]
849view (vw `As` alias) = UnsafeFromClause $
856view (vw `As` alias) = UnsafeFromClause $
850 renderSQL vw <+> "AS" <+> renderSQL alias
857 renderSQL vw <+> "AS" <+> renderSQL alias
852−-- | `common` derives a table from a common table expression.
854 :: Has cte commons common
860 :: Has cte commons common
855 => Aliased Alias (alias ::: cte)
861 => Aliased Alias (alias ::: cte)
856− -> FromClause outer commons schemas params '[alias ::: common]
862+ -> FromClause (commons :=> schemas) params '[alias ::: common]
857common (cte `As` alias) = UnsafeFromClause $
863common (cte `As` alias) = UnsafeFromClause $
858 renderSQL cte <+> "AS" <+> renderSQL alias
864 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
866+{- | @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+ @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+ 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
869+ If the tables have @n@ and @m@ rows respectively, the joined table will
869−have @n * m@ rows.
870+ have @n * m@ rows.
872− :: FromClause outer commons schemas params right
873+ :: FromClause db params right
873 -- ^ right
874 -- ^ right
874− -> FromClause outer commons schemas params left
875+ -> FromClause db params left
875 -- ^ left
876 -- ^ left
876− -> FromClause outer commons schemas params (Join left right)
877+ -> FromClause db params (Join left right)
877crossJoin right left = UnsafeFromClause $
878crossJoin right left = UnsafeFromClause $
878 renderSQL left <+> "CROSS JOIN" <+> renderSQL right
879 renderSQL left <+> "CROSS JOIN" <+> renderSQL right
@@ -881,13 +882,13 @@ crossJoin right left = UnsafeFromClause $
881the @on@ condition.
882the @on@ condition.
884− :: FromClause outer commons schemas params right
885+ :: FromClause db params right
885 -- ^ right
886 -- ^ right
886− -> Condition outer commons 'Ungrouped schemas params (Join left right)
887+ -> Condition db params 'Ungrouped (Join left right)
887 -- ^ @on@ condition
888 -- ^ @on@ condition
888− -> FromClause outer commons schemas params left
889+ -> FromClause db params left
889 -- ^ left
890 -- ^ left
890− -> FromClause outer commons schemas params (Join left right)
891+ -> FromClause db params (Join left right)
891innerJoin right on left = UnsafeFromClause $
892innerJoin right on left = UnsafeFromClause $
892 renderSQL left <+> "INNER JOIN" <+> renderSQL right
893 renderSQL left <+> "INNER JOIN" <+> renderSQL right
893 <+> "ON" <+> renderSQL on
894 <+> "ON" <+> renderSQL on
@@ -898,13 +899,13 @@ innerJoin right on left = UnsafeFromClause $
898 Thus, the joined table always has at least one row for each row in @left@.
899 Thus, the joined table always has at least one row for each row in @left@.
900leftOuterJoin
901leftOuterJoin
901− :: FromClause outer commons schemas params right
902+ :: FromClause db params right
902 -- ^ right
903 -- ^ right
903− -> Condition outer commons 'Ungrouped schemas params (Join left right)
904+ -> Condition db params 'Ungrouped (Join left right)
904 -- ^ @on@ condition
905 -- ^ @on@ condition
905− -> FromClause outer commons schemas params left
906+ -> FromClause db params left
906 -- ^ left
907 -- ^ left
907− -> FromClause outer commons schemas params (Join left (NullifyFrom right))
908+ -> FromClause db params (Join left (NullifyFrom right))
908leftOuterJoin right on left = UnsafeFromClause $
909leftOuterJoin right on left = UnsafeFromClause $
909 renderSQL left <+> "LEFT OUTER JOIN" <+> renderSQL right
910 renderSQL left <+> "LEFT OUTER JOIN" <+> renderSQL right
910 <+> "ON" <+> renderSQL on
911 <+> "ON" <+> renderSQL on
@@ -916,13 +917,13 @@ leftOuterJoin right on left = UnsafeFromClause $
916 have a row for each row in @right@.
917 have a row for each row in @right@.
918rightOuterJoin
919rightOuterJoin
919− :: FromClause outer commons schemas params right
920+ :: FromClause db params right
920 -- ^ right
921 -- ^ right
921− -> Condition outer commons 'Ungrouped schemas params (Join left right)
922+ -> Condition db params 'Ungrouped (Join left right)
922 -- ^ @on@ condition
923 -- ^ @on@ condition
923− -> FromClause outer commons schemas params left
924+ -> FromClause db params left
924 -- ^ left
925 -- ^ left
925− -> FromClause outer commons schemas params (Join (NullifyFrom left) right)
926+ -> FromClause db params (Join (NullifyFrom left) right)
926rightOuterJoin right on left = UnsafeFromClause $
927rightOuterJoin right on left = UnsafeFromClause $
927 renderSQL left <+> "RIGHT OUTER JOIN" <+> renderSQL right
928 renderSQL left <+> "RIGHT OUTER JOIN" <+> renderSQL right
928 <+> "ON" <+> renderSQL on
929 <+> "ON" <+> renderSQL on
@@ -935,13 +936,13 @@ rightOuterJoin right on left = UnsafeFromClause $
935 is added.
936 is added.
937fullOuterJoin
938fullOuterJoin
938− :: FromClause outer commons schemas params right
939+ :: FromClause db params right
939 -- ^ right
940 -- ^ right
940− -> Condition outer commons 'Ungrouped schemas params (Join left right)
941+ -> Condition db params 'Ungrouped (Join left right)
941 -- ^ @on@ condition
942 -- ^ @on@ condition
942− -> FromClause outer commons schemas params left
943+ -> FromClause db params left
943 -- ^ left
944 -- ^ left
944− -> FromClause outer commons schemas params
945+ -> FromClause db params
945 (Join (NullifyFrom left) (NullifyFrom right))
946 (Join (NullifyFrom left) (NullifyFrom right))
946fullOuterJoin right on left = UnsafeFromClause $
947fullOuterJoin right on left = UnsafeFromClause $
947 renderSQL left <+> "FULL OUTER JOIN" <+> renderSQL right
948 renderSQL left <+> "FULL OUTER JOIN" <+> renderSQL right
@@ -951,7 +952,7 @@ fullOuterJoin right on left = UnsafeFromClause $
952-----------------------------------------}
953-----------------------------------------}
954−-- | `By`s are used in `groupBy` to reference a list of columns which are then
955+-- | `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
956-- 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
957-- in all the columns listed. @By \#col@ will reference an unambiguous
957-- column @col@; otherwise @By2 (\#tab \! \#col)@ will reference a table
958-- column @col@; otherwise @By2 (\#tab \! \#col)@ will reference a table
@@ -992,107 +993,412 @@ instance (Has rel rels cols, Has col cols ty, bys ~ '[ '(rel, col)])
992-- done on @NoGroups@ while all output `Expression`s must be aggregated
993-- done on @NoGroups@ while all output `Expression`s must be aggregated
993-- in @Group Nil@. In general, all output `Expression`s in the
994-- in @Group Nil@. In general, all output `Expression`s in the
994-- complement of @bys@ must be aggregated in @Group bys@.
995-- complement of @bys@ must be aggregated in @Group bys@.
995−newtype GroupByClause grp from = UnsafeGroupByClause
996+data GroupByClause grp from where
996− { renderGroupByClause :: ByteString }
997+ NoGroups :: GroupByClause 'Ungrouped from
997− deriving (GHC.Generic,Show,Eq,Ord,NFData)
998+ Group
1000+ => NP (By from) bys
1001+ -> GroupByClause ('Grouped bys) from
1003+-- | Renders a `GroupByClause`.
998instance RenderSQL (GroupByClause grp from) where
1004instance RenderSQL (GroupByClause grp from) where
999− renderSQL = renderGroupByClause
1005+ renderSQL = \case
1000−noGroups :: GroupByClause 'Ungrouped from
1006+ NoGroups -> ""
1001−noGroups = UnsafeGroupByClause ""
1004− => NP (By from) bys
1005− -> GroupByClause ('Grouped bys) from
1006−group bys = UnsafeGroupByClause $ case bys of
1007− Nil -> ""
1007+ Group Nil -> ""
1008− bys' -> " GROUP BY" <+> renderCommaSeparated renderSQL bys'
1008+ Group bys -> " GROUP BY" <+> renderCommaSeparated renderSQL bys
1010-- | A `HavingClause` is used to eliminate groups that are not of interest.
1010-- | A `HavingClause` is used to eliminate groups that are not of interest.
1011-- An `Ungrouped` `TableExpression` may only use `NoHaving` while a `Grouped`
1011-- An `Ungrouped` `TableExpression` may only use `NoHaving` while a `Grouped`
1012-- `TableExpression` must use `Having` whose conditions are combined with
1012-- `TableExpression` must use `Having` whose conditions are combined with
1013-- `.&&`.
1013-- `.&&`.
1014−data HavingClause outer commons grp schemas params from where
1014+data HavingClause db params grp from where
1015− NoHaving :: HavingClause outer commons 'Ungrouped schemas params from
1015+ NoHaving :: HavingClause db params 'Ungrouped from
1017− :: [Condition outer commons ('Grouped bys) schemas params from]
1017+ :: [Condition db params ('Grouped bys) from]
1018− -> HavingClause outer commons ('Grouped bys) schemas params from
1018+ -> HavingClause db params ('Grouped bys) from
1019−deriving instance Show (HavingClause outer commons grp schemas params from)
1019+deriving instance Show (HavingClause db params grp from)
1020−deriving instance Eq (HavingClause outer commons grp schemas params from)
1020+deriving instance Eq (HavingClause db params grp from)
1021−deriving instance Ord (HavingClause outer commons grp schemas params from)
1021+deriving instance Ord (HavingClause db params grp from)
1023-- | Render a `HavingClause`.
1023-- | Render a `HavingClause`.
1024−instance RenderSQL (HavingClause outer commons grp schemas params from) where
1024+instance RenderSQL (HavingClause db params grp from) where
1025 renderSQL = \case
1025 renderSQL = \case
1026 NoHaving -> ""
1026 NoHaving -> ""
1027 Having [] -> ""
1027 Having [] -> ""
1028 Having conditions ->
1028 Having conditions ->
1029 " HAVING" <+> commaSeparated (renderSQL <$> conditions)
1029 " HAVING" <+> commaSeparated (renderSQL <$> conditions)
1031+{-----------------------------------------
1033+-----------------------------------------}
1035+-- | `SortExpression`s are used by `sortBy` to optionally sort the results
1036+-- of a `Query`. `Asc` or `Desc` set the sort direction of a `NotNull` result
1037+-- column to ascending or descending. Ascending order puts smaller values
1038+-- first, where "smaller" is defined in terms of the `.<` operator. Similarly,
1039+-- descending order is determined with the `.>` operator. `AscNullsFirst`,
1040+-- `AscNullsLast`, `DescNullsFirst` and `DescNullsLast` options are used to
1041+-- determine whether nulls appear before or after non-null values in the sort
1042+-- ordering of a `Null` result column.
1043+data SortExpression db params grp from where
1045+ :: Expression db params grp from ('NotNull ty)
1046+ -> SortExpression db params grp from
1048+ :: Expression db params grp from ('NotNull ty)
1049+ -> SortExpression db params grp from
1051+ :: Expression db params grp from ('Null ty)
1052+ -> SortExpression db params grp from
1054+ :: Expression db params grp from ('Null ty)
1055+ -> SortExpression db params grp from
1057+ :: Expression db params grp from ('Null ty)
1058+ -> SortExpression db params grp from
1060+ :: Expression db params grp from ('Null ty)
1061+ -> SortExpression db params grp from
1062+deriving instance Show (SortExpression db params grp from)
1064+-- | Render a `SortExpression`.
1065+instance RenderSQL (SortExpression db params grp from) where
1067+ Asc expression -> renderSQL expression <+> "ASC"
1068+ Desc expression -> renderSQL expression <+> "DESC"
1069+ AscNullsFirst expression -> renderSQL expression
1070+ <+> "ASC NULLS FIRST"
1071+ DescNullsFirst expression -> renderSQL expression
1072+ <+> "DESC NULLS FIRST"
1073+ AscNullsLast expression -> renderSQL expression <+> "ASC NULLS LAST"
1074+ DescNullsLast expression -> renderSQL expression <+> "DESC NULLS LAST"
1076+unsafeSubqueryExpression
1078+ -> Expression db params grp from ty
1079+ -> Query db params '[alias ::: ty]
1080+ -> Expression db params grp from (nullity 'PGbool)
1081+unsafeSubqueryExpression op x q = UnsafeExpression $
1082+ renderSQL x <+> op <+> parenthesized (renderSQL q)
1084+unsafeRowSubqueryExpression
1087+ -> NP (Aliased (Expression db params grp from)) row
1088+ -> Query db params row
1089+ -> Expression db params grp from (nullity 'PGbool)
1090+unsafeRowSubqueryExpression op xs q = UnsafeExpression $
1091+ renderSQL (row xs) <+> op <+> parenthesized (renderSQL q)
1093+-- | The right-hand side is a sub`Query`, which must return exactly one column.
1094+-- The left-hand expression is evaluated and compared to each row of the
1095+-- sub`Query` result. The result of `in_` is `true` if any equal subquery row is found.
1096+-- The result is `false` if no equal row is found
1097+-- (including the case where the subquery returns no rows).
1099+-- >>> printSQL $ true `in_` values_ (true `as` #foo)
1100+-- TRUE IN (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1102+ :: Expression db params grp from ty -- ^ expression
1103+ -> Query db params '[alias ::: ty] -- ^ subquery
1104+ -> Expression db params grp from (nullity 'PGbool)
1105+in_ = unsafeSubqueryExpression "IN"
1107+{- | The left-hand side of this form of `rowIn` is a row constructor.
1108+The right-hand side is a sub`Query`,
1109+which must return exactly as many columns as
1110+there are expressions in the left-hand row.
1111+The left-hand expressions are evaluated and compared row-wise to each row
1112+of the subquery result. The result of `rowIn`
1113+is `true` if any equal subquery row is found.
1114+The result is `false` if no equal row is found
1115+(including the case where the subquery returns no rows).
1117+>>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db params grp from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1118+>>> printSQL $ myRow `rowIn` values_ myRow
1119+ROW(1, FALSE) IN (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1123+ => NP (Aliased (Expression db params grp from)) row -- ^ row constructor
1124+ -> Query db params row -- ^ subquery
1125+ -> Expression db params grp from (nullity 'PGbool)
1126+rowIn = unsafeRowSubqueryExpression "IN"
1128+-- | >>> printSQL $ true `eqAll` values_ (true `as` #foo)
1129+-- TRUE = ALL (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1131+ :: Expression db params grp from ty -- ^ expression
1132+ -> Query db params '[alias ::: ty] -- ^ subquery
1133+ -> Expression db params grp from (nullity 'PGbool)
1134+eqAll = unsafeSubqueryExpression "= ALL"
1136+-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db params grp from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1137+-- >>> printSQL $ myRow `rowEqAll` values_ myRow
1138+-- ROW(1, FALSE) = ALL (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1141+ => NP (Aliased (Expression db params grp from)) row -- ^ row constructor
1142+ -> Query db params row -- ^ subquery
1143+ -> Expression db params grp from (nullity 'PGbool)
1144+rowEqAll = unsafeRowSubqueryExpression "= ALL"
1146+-- | >>> printSQL $ true `eqAny` values_ (true `as` #foo)
1147+-- TRUE = ANY (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1149+ :: Expression db params grp from ty -- ^ expression
1150+ -> Query db params '[alias ::: ty] -- ^ subquery
1151+ -> Expression db params grp from (nullity 'PGbool)
1152+eqAny = unsafeSubqueryExpression "= ANY"
1154+-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db params grp from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1155+-- >>> printSQL $ myRow `rowEqAny` values_ myRow
1156+-- ROW(1, FALSE) = ANY (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1159+ => NP (Aliased (Expression db params grp from)) row -- ^ row constructor
1160+ -> Query db params row -- ^ subquery
1161+ -> Expression db params grp from (nullity 'PGbool)
1162+rowEqAny = unsafeRowSubqueryExpression "= ANY"
1164+-- | >>> printSQL $ true `neqAll` values_ (true `as` #foo)
1165+-- TRUE <> ALL (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1167+ :: Expression db params grp from ty -- ^ expression
1168+ -> Query db params '[alias ::: ty] -- ^ subquery
1169+ -> Expression db params grp from (nullity 'PGbool)
1170+neqAll = unsafeSubqueryExpression "<> ALL"
1172+-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db params grp from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1173+-- >>> printSQL $ myRow `rowNeqAll` values_ myRow
1174+-- ROW(1, FALSE) <> ALL (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1177+ => NP (Aliased (Expression db params grp from)) row -- ^ row constructor
1178+ -> Query db params row -- ^ subquery
1179+ -> Expression db params grp from (nullity 'PGbool)
1180+rowNeqAll = unsafeRowSubqueryExpression "<> ALL"
1182+-- | >>> printSQL $ true `neqAny` values_ (true `as` #foo)
1183+-- TRUE <> ANY (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1185+ :: Expression db params grp from ty -- ^ expression
1186+ -> Query db params '[alias ::: ty] -- ^ subquery
1187+ -> Expression db params grp from (nullity 'PGbool)
1188+neqAny = unsafeSubqueryExpression "<> ANY"
1190+-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db params grp from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1191+-- >>> printSQL $ myRow `rowNeqAny` values_ myRow
1192+-- ROW(1, FALSE) <> ANY (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1195+ => NP (Aliased (Expression db params grp from)) row -- ^ row constructor
1196+ -> Query db params row -- ^ subquery
1197+ -> Expression db params grp from (nullity 'PGbool)
1198+rowNeqAny = unsafeRowSubqueryExpression "<> ANY"
1200+-- | >>> printSQL $ true `allLt` values_ (true `as` #foo)
1201+-- TRUE ALL < (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1203+ :: Expression db params grp from ty -- ^ expression
1204+ -> Query db params '[alias ::: ty] -- ^ subquery
1205+ -> Expression db params grp from (nullity 'PGbool)
1206+allLt = unsafeSubqueryExpression "ALL <"
1208+-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db params grp from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1209+-- >>> printSQL $ myRow `rowLtAll` values_ myRow
1210+-- ROW(1, FALSE) ALL < (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1213+ => NP (Aliased (Expression db params grp from)) row -- ^ row constructor
1214+ -> Query db params row -- ^ subquery
1215+ -> Expression db params grp from (nullity 'PGbool)
1216+rowLtAll = unsafeRowSubqueryExpression "ALL <"
1218+-- | >>> printSQL $ true `ltAny` values_ (true `as` #foo)
1219+-- TRUE ANY < (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1221+ :: Expression db params grp from ty -- ^ expression
1222+ -> Query db params '[alias ::: ty] -- ^ subquery
1223+ -> Expression db params grp from (nullity 'PGbool)
1224+ltAny = unsafeSubqueryExpression "ANY <"
1226+-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db params grp from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1227+-- >>> printSQL $ myRow `rowLtAll` values_ myRow
1228+-- ROW(1, FALSE) ALL < (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1231+ => NP (Aliased (Expression db params grp from)) row -- ^ row constructor
1232+ -> Query db params row -- ^ subquery
1233+ -> Expression db params grp from (nullity 'PGbool)
1234+rowLtAny = unsafeRowSubqueryExpression "ANY <"
1236+-- | >>> printSQL $ true `lteAll` values_ (true `as` #foo)
1237+-- TRUE <= ALL (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1239+ :: Expression db params grp from ty -- ^ expression
1240+ -> Query db params '[alias ::: ty] -- ^ subquery
1241+ -> Expression db params grp from (nullity 'PGbool)
1242+lteAll = unsafeSubqueryExpression "<= ALL"
1244+-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db params grp from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1245+-- >>> printSQL $ myRow `rowLteAll` values_ myRow
1246+-- ROW(1, FALSE) <= ALL (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1249+ => NP (Aliased (Expression db params grp from)) row -- ^ row constructor
1250+ -> Query db params row -- ^ subquery
1251+ -> Expression db params grp from (nullity 'PGbool)
1252+rowLteAll = unsafeRowSubqueryExpression "<= ALL"
1254+-- | >>> printSQL $ true `lteAny` values_ (true `as` #foo)
1255+-- TRUE <= ANY (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1257+ :: Expression db params grp from ty -- ^ expression
1258+ -> Query db params '[alias ::: ty] -- ^ subquery
1259+ -> Expression db params grp from (nullity 'PGbool)
1260+lteAny = unsafeSubqueryExpression "<= ANY"
1262+-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db params grp from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1263+-- >>> printSQL $ myRow `rowLteAny` values_ myRow
1264+-- ROW(1, FALSE) <= ANY (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1267+ => NP (Aliased (Expression db params grp from)) row -- ^ row constructor
1268+ -> Query db params row -- ^ subquery
1269+ -> Expression db params grp from (nullity 'PGbool)
1270+rowLteAny = unsafeRowSubqueryExpression "<= ANY"
1272+-- | >>> printSQL $ true `gtAll` values_ (true `as` #foo)
1273+-- TRUE > ALL (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1275+ :: Expression db params grp from ty -- ^ expression
1276+ -> Query db params '[alias ::: ty] -- ^ subquery
1277+ -> Expression db params grp from (nullity 'PGbool)
1278+gtAll = unsafeSubqueryExpression "> ALL"
1280+-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db params grp from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1281+-- >>> printSQL $ myRow `rowGtAll` values_ myRow
1282+-- ROW(1, FALSE) > ALL (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1285+ => NP (Aliased (Expression db params grp from)) row -- ^ row constructor
1286+ -> Query db params row -- ^ subquery
1287+ -> Expression db params grp from (nullity 'PGbool)
1288+rowGtAll = unsafeRowSubqueryExpression "> ALL"
1290+-- | >>> printSQL $ true `gtAny` values_ (true `as` #foo)
1291+-- TRUE > ANY (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1293+ :: Expression db params grp from ty -- ^ expression
1294+ -> Query db params '[alias ::: ty] -- ^ subquery
1295+ -> Expression db params grp from (nullity 'PGbool)
1296+gtAny = unsafeSubqueryExpression "> ANY"
1298+-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db params grp from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1299+-- >>> printSQL $ myRow `rowGtAny` values_ myRow
1300+-- ROW(1, FALSE) > ANY (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1303+ => NP (Aliased (Expression db params grp from)) row -- ^ row constructor
1304+ -> Query db params row -- ^ subquery
1305+ -> Expression db params grp from (nullity 'PGbool)
1306+rowGtAny = unsafeRowSubqueryExpression "> ANY"
1308+-- | >>> printSQL $ true `gteAll` values_ (true `as` #foo)
1309+-- TRUE >= ALL (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1311+ :: Expression db params grp from ty -- ^ expression
1312+ -> Query db params '[alias ::: ty] -- ^ subquery
1313+ -> Expression db params grp from (nullity 'PGbool)
1314+gteAll = unsafeSubqueryExpression ">= ALL"
1316+-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db params grp from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1317+-- >>> printSQL $ myRow `rowGteAll` values_ myRow
1318+-- ROW(1, FALSE) >= ALL (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1321+ => NP (Aliased (Expression db params grp from)) row -- ^ row constructor
1322+ -> Query db params row -- ^ subquery
1323+ -> Expression db params grp from (nullity 'PGbool)
1324+rowGteAll = unsafeRowSubqueryExpression ">= ALL"
1326+-- | >>> printSQL $ true `gteAny` values_ (true `as` #foo)
1327+-- TRUE >= ANY (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1329+ :: Expression db params grp from ty -- ^ expression
1330+ -> Query db params '[alias ::: ty] -- ^ subquery
1331+ -> Expression db params grp from (nullity 'PGbool)
1332+gteAny = unsafeSubqueryExpression ">= ANY"
1334+-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db params grp from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1335+-- >>> printSQL $ myRow `rowGteAny` values_ myRow
1336+-- ROW(1, FALSE) >= ANY (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1339+ => NP (Aliased (Expression db params grp from)) row -- ^ row constructor
1340+ -> Query db params row -- ^ subquery
1341+ -> Expression db params grp from (nullity 'PGbool)
1342+rowGteAny = unsafeRowSubqueryExpression ">= ANY"
1031-- | A `CommonTableExpression` is an auxiliary statement in a `with` clause.
1344-- | A `CommonTableExpression` is an auxiliary statement in a `with` clause.
1032data CommonTableExpression statement
1345data CommonTableExpression statement
1033− (schemas :: SchemasType)
1034 (params :: [NullityType])
1346 (params :: [NullityType])
1035− (commons0 :: FromType)
1347+ (db0 :: DBType)
1036− (commons1 :: FromType) where
1348+ (db1 :: DBType) where
1037 CommonTableExpression
1349 CommonTableExpression
1038− :: Aliased (statement commons schemas params) (cte ::: common)
1350+ :: Aliased (statement (commons :=> schemas) params) (cte ::: common)
1039− -> CommonTableExpression statement schemas params commons (cte ::: common ': commons)
1351+ -> CommonTableExpression statement params
1352+ (commons :=> schemas) ((cte ::: common ': commons) :=> schemas)
1041 ( KnownSymbol cte
1354 ( KnownSymbol cte
1355+ , db0 ~ (commons :=> schemas)
1042− , commons1 ~ (cte ::: common ': commons)
1356+ , db1 ~ ((cte ::: common ': commons) :=> schemas)
1043 ) => Aliasable cte
1357 ) => Aliasable cte
1044− (statement commons schemas params common)
1358+ (statement db0 params common)
1045− (CommonTableExpression statement schemas params commons commons1) where
1359+ (CommonTableExpression statement params db0 db1) where
1046 statement `as` cte = CommonTableExpression (statement `as` cte)
1360 statement `as` cte = CommonTableExpression (statement `as` cte)
1048 ( KnownSymbol cte
1362 ( KnownSymbol cte
1363+ , db0 ~ (commons :=> schemas)
1049− , commons1 ~ (cte ::: common ': commons)
1364+ , db1 ~ ((cte ::: common ': commons) :=> schemas)
1050 ) => Aliasable cte
1365 ) => Aliasable cte
1051− (statement commons schemas params common)
1366+ (statement db0 params common)
1052− (Path (CommonTableExpression statement schemas params) commons commons1) where
1367+ (AlignedList (CommonTableExpression statement params) db0 db1) where
1053− statement `as` cte = csingleton (statement `as` cte)
1368+ statement `as` cte = single (statement `as` cte)
1055−instance (forall c s p r. RenderSQL (statement c s p r)) => RenderSQL
1370+-- | render a `CommonTableExpression`.
1371+renderCommonTableExpression
1372+ :: (forall db ps row. statement db ps row -> ByteString) -- ^ render statement
1056− (CommonTableExpression statement schemas params commons0 commons1) where
1373+ -> CommonTableExpression statement params db0 db1 -> ByteString
1374+renderCommonTableExpression renderStatement
1057− renderSQL (CommonTableExpression (statement `As` cte)) =
1375+ (CommonTableExpression (statement `As` alias)) =
1058− renderSQL cte <+> "AS" <+> parenthesized (renderSQL statement)
1376+ renderSQL alias <+> "AS" <+> parenthesized (renderStatement statement)
1378+-- | render a non-empty `AlignedList` of `CommonTableExpression`s.
1379+renderCommonTableExpressions
1380+ :: (forall db ps row. statement db ps row -> ByteString) -- ^ render statement
1381+ -> CommonTableExpression statement params db0 db1
1382+ -> AlignedList (CommonTableExpression statement params) db1 db2
1384+renderCommonTableExpressions renderStatement cte ctes =
1385+ renderCommonTableExpression renderStatement cte <> case ctes of
1387+ cte' :>> ctes' -> "," <+>
1388+ renderCommonTableExpressions renderStatement cte' ctes'
1060-- | `with` provides a way to write auxiliary statements for use in a larger query.
1390-- | `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
1391-- These statements, referred to as `CommonTableExpression`s, can be thought of as
1062-- defining temporary tables that exist just for one query.
1392-- defining temporary tables that exist just for one query.
1063class With statement where
1393class With statement where
1065− :: Path (CommonTableExpression statement schemas params) commons0 commons1
1395+ :: AlignedList (CommonTableExpression statement params) db0 db1
1066 -- ^ common table expressions
1396 -- ^ common table expressions
1067− -> statement commons1 schemas params row
1397+ -> statement db1 params row
1068 -- ^ larger query
1398 -- ^ larger query
1069− -> statement commons0 schemas params row
1399+ -> statement db0 params row
1070−instance With (Query outer) where
1400+instance With Query where
1071 with Done query = query
1401 with Done query = query
1072− with ctes query = UnsafeQuery $
1402+ 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
1403+ "WITH" <+> renderCommonTableExpressions renderSQL cte ctes
1097− <+> "AS" <+> parenthesized (renderSQL recursive)
1098− <+> renderSQL query
1404+ <+> renderSQL query