@@ -1,7 +1,7 @@
11{-|
22Module: Squeal.PostgreSQL.Query
33Description: Squeal queries
4−Copyright: (c) Eitan Chatav, 2019
4+Copyright: (c) Eitan Chatav, 2017
55Maintainer: eitan@morphism.tech
66Stability: experimental
77
@@ -17,9 +17,7 @@ Squeal queries.
1717 , GeneralizedNewtypeDeriving
1818 , LambdaCase
1919 , MultiParamTypeClasses
20− , OverloadedLabels
2120 , OverloadedStrings
22− , QuantifiedConstraints
2321 , ScopedTypeVariables
2422 , StandaloneDeriving
2523 , TypeApplications
@@ -32,15 +30,12 @@ Squeal queries.
3230
3331module Squeal.PostgreSQL.Query
3432 ( -- * Queries
35− Query_
36− , Query (..)
33+ Query (UnsafeQuery, renderQuery)
3734 -- ** Select
3835 , select
3936 , select_
4037 , selectDistinct
4138 , selectDistinct_
42− , selectDistinctOn
43− , selectDistinctOn_
4439 , Selection (..)
4540 -- ** Values
4641 , values
@@ -53,15 +48,33 @@ module Squeal.PostgreSQL.Query
5348 , except
5449 , exceptAll
5550 -- ** With
56− , With (..)
51+ , With (with)
5752 , CommonTableExpression (..)
58− , withRecursive
53+ , renderCommonTableExpression
54+ , renderCommonTableExpressions
55+ -- ** Json
56+ , jsonEach
57+ , jsonbEach
58+ , jsonEachAsText
59+ , jsonbEachAsText
60+ , jsonObjectKeys
61+ , jsonbObjectKeys
62+ , jsonPopulateRecord
63+ , jsonbPopulateRecord
64+ , jsonPopulateRecordSet
65+ , jsonbPopulateRecordSet
66+ , jsonToRecord
67+ , jsonbToRecord
68+ , jsonToRecordSet
69+ , jsonbToRecordSet
5970 -- * Table Expressions
6071 , TableExpression (..)
72+ , renderTableExpression
6173 , from
6274 , where_
6375 , groupBy
6476 , having
77+ , orderBy
6578 , limit
6679 , offset
6780 -- * From Clauses
@@ -76,14 +89,45 @@ module Squeal.PostgreSQL.Query
7689 , rightOuterJoin
7790 , fullOuterJoin
7891 -- * Grouping
79− , By (..)
80− , GroupByClause (..)
81− , HavingClause (..)
92+ , By (By1, By2)
93+ , renderBy
94+ , GroupByClause (NoGroups, Group)
95+ , renderGroupByClause
96+ , HavingClause (NoHaving, Having)
97+ , renderHavingClause
98+ -- * Sorting
99+ , SortExpression (..)
100+ -- * Subquery Expressions
101+ , in_
102+ , rowIn
103+ , eqAll
104+ , rowEqAll
105+ , eqAny
106+ , rowEqAny
107+ , neqAll
108+ , rowNeqAll
109+ , neqAny
110+ , rowNeqAny
111+ , allLt
112+ , rowLtAll
113+ , ltAny
114+ , rowLtAny
115+ , lteAll
116+ , rowLteAll
117+ , lteAny
118+ , rowLteAny
119+ , gtAll
120+ , rowGtAll
121+ , gtAny
122+ , rowGtAny
123+ , gteAll
124+ , rowGteAll
125+ , gteAny
126+ , rowGteAny
82127 ) where
83128
84129import Control.DeepSeq
85130import Data.ByteString (ByteString)
86−import Data.Kind (Type)
87131import Data.String
88132import Data.Word
89133import Generics.SOP hiding (from)
@@ -91,67 +135,13 @@ import GHC.TypeLits
91135
92136import qualified GHC.Generics as GHC
93137
94−import Squeal.PostgreSQL.Alias
95138import 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
101139import Squeal.PostgreSQL.Render
102140import Squeal.PostgreSQL.Schema
103141
104−-- $setup
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
110−
111142{- |
112−The process of retrieving or the command to retrieve data from
113−a database is called a `Query`.
114−
115−The general `Query` type is parameterized by
116−
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`.
122−-}
123−newtype Query
124− (outer :: FromType)
125− (commons :: FromType)
126− (schemas :: SchemasType)
127− (params :: [NullityType])
128− (row :: RowType)
129− = UnsafeQuery { renderQuery :: ByteString }
130− deriving (GHC.Generic,Show,Eq,Ord,NFData)
131−instance RenderSQL (Query outer commons schemas params row) where renderSQL = renderQuery
132−
133−{- |
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`.
137−
138−A top-level query can be run
139−using `Squeal.PostgreSQL.PQ.runQueryParams`, or if @parameters = ()@
140−using `Squeal.PostgreSQL.PQ.runQuery`.
141−
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.
146−
147−Let's see some examples of queries.
148−
149−>>> :set -XDeriveAnyClass -XDerivingStrategies
150−>>> :{
151−data Row a b = Row { col1 :: a, col2 :: b }
152− deriving stock (GHC.Generic)
153− deriving anyclass (SOP.Generic, SOP.HasDatatypeInfo)
154−:}
143+The process of retrieving or the command to retrieve data from a database
144+is called a `Query`. Let's see some examples of queries.
155145
156146simple query:
157147
@@ -159,7 +149,7 @@ simple query:
159149>>> type Schema = '["tab" ::: 'Table ('[] :=> Columns)]
160150>>> :{
161151let
162− query :: Query_ (Public Schema) () (Row Int32 Int32)
152+ query :: Query (DBof (Public Schema)) '[] '["col1" ::: 'NotNull 'PGint4, "col2" ::: 'NotNull 'PGint4]
163153 query = select Star (from (table #tab))
164154in printSQL query
165155:}
@@ -169,21 +159,21 @@ restricted query:
169159
170160>>> :{
171161let
172− query :: Query_ (Public Schema) () (Row Int32 Int32)
162+ query :: Query (DBof (Public Schema)) '[] '["sum" ::: 'NotNull 'PGint4, "col1" ::: 'NotNull 'PGint4]
173163 query =
174− select_ ((#col1 + #col2) `as` #col1 :* #col1 `as` #col2)
164+ select_ ((#col1 + #col2) `as` #sum :* #col1)
175165 ( from (table #tab)
176166 & where_ (#col1 .> #col2)
177167 & where_ (#col2 .> 0) )
178168in printSQL query
179169:}
180−SELECT ("col1" + "col2") AS "col1", "col1" AS "col2" FROM "tab" AS "tab" WHERE (("col1" > "col2") AND ("col2" > 0))
170+SELECT ("col1" + "col2") AS "sum", "col1" AS "col1" FROM "tab" AS "tab" WHERE (("col1" > "col2") AND ("col2" > 0))
181171
182172subquery:
183173
184174>>> :{
185175let
186− query :: Query_ (Public Schema) () (Row Int32 Int32)
176+ query :: Query (DBof (Public Schema)) '[] '["col1" ::: 'NotNull 'PGint4, "col2" ::: 'NotNull 'PGint4]
187177 query = select Star (from (subquery (select Star (from (table #tab)) `as` #sub)))
188178in printSQL query
189179:}
@@ -193,7 +183,7 @@ limits and offsets:
193183
194184>>> :{
195185let
196− query :: Query_ (Public Schema) () (Row Int32 Int32)
186+ query :: Query (DBof (Public Schema)) '[] '["col1" ::: 'NotNull 'PGint4, "col2" ::: 'NotNull 'PGint4]
197187 query = select Star (from (table #tab) & limit 100 & offset 2 & limit 50 & offset 2)
198188in printSQL query
199189:}
@@ -203,7 +193,7 @@ parameterized query:
203193
204194>>> :{
205195let
206− query :: Query_ (Public Schema) (Only Int32) (Row Int32 Int32)
196+ query :: Query (DBof (Public Schema)) '[ 'NotNull 'PGint4] '["col1" ::: 'NotNull 'PGint4, "col2" ::: 'NotNull 'PGint4]
207197 query = select Star (from (table #tab) & where_ (#col1 .> param @1))
208198in printSQL query
209199:}
@@ -213,21 +203,21 @@ aggregation query:
213203
214204>>> :{
215205let
216− query :: Query_ (Public Schema) () (Row Int64 Int32)
206+ query :: Query (DBof (Public Schema)) '[] '["sum" ::: 'NotNull 'PGint4, "col1" ::: 'NotNull 'PGint4 ]
217207 query =
218− select_ ((fromNull 0 (sum_ (All #col2))) `as` #col1 :* #col1 `as` #col2)
208+ select_ (sum_ #col2 `as` #sum :* #col1)
219209 ( from (table (#tab `as` #table1))
220210 & groupBy #col1
221− & having (sum_ (Distinct #col2) .> 1) )
211+ & having (#col1 + sum_ #col2 .> 1) )
222212in printSQL query
223213:}
224−SELECT COALESCE(sum(ALL "col2"), 0) AS "col1", "col1" AS "col2" FROM "tab" AS "table1" GROUP BY "col1" HAVING (sum(DISTINCT "col2") > 1)
214+SELECT sum("col2") AS "sum", "col1" AS "col1" FROM "tab" AS "table1" GROUP BY "col1" HAVING (("col1" + sum("col2")) > 1)
225215
226216sorted query:
227217
228218>>> :{
229219let
230− query :: Query_ (Public Schema) () (Row Int32 Int32)
220+ query :: Query (DBof (Public Schema)) '[] '["col1" ::: 'NotNull 'PGint4, "col2" ::: 'NotNull 'PGint4]
231221 query = select Star (from (table #tab) & orderBy [#col1 & Asc])
232222in printSQL query
233223:}
@@ -235,12 +225,14 @@ SELECT * FROM "tab" AS "tab" ORDER BY "col1" ASC
235225
236226joins:
237227
228+>>> :set -XFlexibleContexts
238229>>> :{
239230type OrdersColumns =
240231 '[ "id" ::: 'NoDef :=> 'NotNull 'PGint4
241− , "price" ::: 'NoDef :=> 'NotNull 'PGfloat4
242− , "customer_id" ::: 'NoDef :=> 'NotNull 'PGint4
243− , "shipper_id" ::: 'NoDef :=> 'NotNull 'PGint4 ]
232+ , "price" ::: 'NoDef :=> 'NotNull 'PGfloat4
233+ , "customer_id" ::: 'NoDef :=> 'NotNull 'PGint4
234+ , "shipper_id" ::: 'NoDef :=> 'NotNull 'PGint4
235+ ]
244236:}
245237
246238>>> :{
@@ -256,27 +248,22 @@ type OrdersConstraints =
256248>>> :{
257249type OrdersSchema =
258250 '[ "orders" ::: 'Table (OrdersConstraints :=> OrdersColumns)
259− , "customers" ::: 'Table (CustomersConstraints :=> NamesColumns)
260− , "shippers" ::: 'Table (ShippersConstraints :=> NamesColumns) ]
261−:}
262−
263−>>> :{
264−data Order = Order
265− { price :: Float
266− , customerName :: Text
267− , shipperName :: Text
268− } deriving GHC.Generic
269−instance SOP.Generic Order
270−instance SOP.HasDatatypeInfo Order
251+ , "customers" ::: 'Table (CustomersConstraints :=> NamesColumns)
252+ , "shippers" ::: 'Table (ShippersConstraints :=> NamesColumns) ]
271253:}
272254
273255>>> :{
274256let
275− query :: Query_ (Public OrdersSchema) () Order
257+ query :: Query (DBof (Public OrdersSchema))
258+ '[]
259+ '[ "order_price" ::: 'NotNull 'PGfloat4
260+ , "customer_name" ::: 'NotNull 'PGtext
261+ , "shipper_name" ::: 'NotNull 'PGtext
262+ ]
276263 query = select_
277− ( #o ! #price `as` #price :*
278− #c ! #name `as` #customerName :*
279− #s ! #name `as` #shipperName )
264+ ( #o ! #price `as` #order_price :*
265+ #c ! #name `as` #customer_name :*
266+ #s ! #name `as` #shipper_name )
280267 ( from (table (#orders `as` #o)
281268 & innerJoin (table (#customers `as` #c))
282269 (#o ! #customer_id .== #c ! #id)
@@ -284,16 +271,14 @@ let
284271 (#o ! #shipper_id .== #s ! #id)) )
285272in printSQL query
286273:}
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")
274+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")
288275
289276self-join:
290277
291278>>> :{
292279let
293− query :: Query_ (Public Schema) () (Row Int32 Int32)
294− query = select
295− (#t1 & DotStar)
296− (from (table (#tab `as` #t1) & crossJoin (table (#tab `as` #t2))))
280+ query :: Query (DBof (Public Schema)) '[] '["col1" ::: 'NotNull 'PGint4, "col2" ::: 'NotNull 'PGint4]
281+ query = select (#t1 & DotStar) (from (table (#tab `as` #t1) & crossJoin (table (#tab `as` #t2))))
297282in printSQL query
298283:}
299284SELECT "t1".* FROM "tab" AS "t1" CROSS JOIN "tab" AS "t2"
@@ -302,19 +287,17 @@ value queries:
302287
303288>>> :{
304289let
305− query :: Query_ schemas () (Row String Bool)
306− query = values
307− ("true" `as` #col1 :* true `as` #col2)
308− ["false" `as` #col1 :* false `as` #col2]
290+ query :: Query db '[] '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
291+ query = values (1 `as` #foo :* true `as` #bar) [2 `as` #foo :* false `as` #bar]
309292in printSQL query
310293:}
311−SELECT * FROM (VALUES (E'true', TRUE), (E'false', FALSE)) AS t ("col1", "col2")
294+SELECT * FROM (VALUES (1, TRUE), (2, FALSE)) AS t ("foo", "bar")
312295
313296set operations:
314297
315298>>> :{
316299let
317− query :: Query_ (Public Schema) () (Row Int32 Int32)
300+ query :: Query (DBof (Public Schema)) '[] '["col1" ::: 'NotNull 'PGint4, "col2" ::: 'NotNull 'PGint4]
318301 query = select Star (from (table #tab)) `unionAll` select Star (from (table #tab))
319302in printSQL query
320303:}
@@ -324,7 +307,7 @@ with queries:
324307
325308>>> :{
326309let
327− query :: Query_ (Public Schema) () (Row Int32 Int32)
310+ query :: Query (DBof (Public Schema)) '[] '["col1" ::: 'NotNull 'PGint4, "col2" ::: 'NotNull 'PGint4]
328311 query = with (
329312 select Star (from (table #tab)) `as` #cte1 :>>
330313 select Star (from (common #cte1)) `as` #cte2
@@ -332,195 +315,133 @@ let
332315in printSQL query
333316:}
334317WITH "cte1" AS (SELECT * FROM "tab" AS "tab"), "cte2" AS (SELECT * FROM "cte1" AS "cte1") SELECT * FROM "cte2" AS "cte2"
335−
336−window function queries
337−
338−>>> :{
339−let
340− query :: Query_ (Public Schema) () (Row Int32 Int64)
341− query = select
342− (#col1 & Also (rank `as` #col2 `Over` (partitionBy #col1 & orderBy [#col2 & Asc])))
343− (from (table #tab))
344−in printSQL query
345−:}
346−SELECT "col1" AS "col1", rank() OVER (PARTITION BY "col1" ORDER BY "col2" ASC) AS "col2" FROM "tab" AS "tab"
347−
348−correlated subqueries
349−
350−>>> :{
351−let
352− query :: Query_ (Public Schema) () (Only Int32)
353− query =
354− select (#col1 `as` #fromOnly) (from (table (#tab `as` #t1))
355− & where_ (exists (
356− select Star (from (table (#tab `as` #t2))
357− & where_ (#t2 ! #col2 .== #t1 ! #col1)))))
358−in printSQL query
359−:}
360−SELECT "col1" AS "fromOnly" FROM "tab" AS "t1" WHERE EXISTS (SELECT * FROM "tab" AS "t2" WHERE ("t2"."col2" = "t1"."col1"))
361−
362318-}
363−type family Query_
364− (schemas :: SchemasType)
365− (parameters :: Type)
366− (row :: Type) where
367− Query_ schemas params row =
368− Query '[] '[] schemas (TuplePG params) (RowPG row)
319+newtype Query
320+ (db :: DBType)
321+ (params :: [NullityType])
322+ (columns :: RowType)
323+ = UnsafeQuery { renderQuery :: ByteString }
324+ deriving (GHC.Generic,Show,Eq,Ord,NFData)
325+instance RenderSQL (Query db params columns) where renderSQL = renderQuery
369326
370327-- | The results of two queries can be combined using the set operation
371328-- `union`. Duplicate rows are eliminated.
372329union
373− :: Query outer commons schemas params columns
374− -> Query outer commons schemas params columns
375− -> Query outer commons schemas params columns
330+ :: Query db params columns
331+ -> Query db params columns
332+ -> Query db params columns
376333q1 `union` q2 = UnsafeQuery $
377− parenthesized (renderSQL q1)
334+ parenthesized (renderQuery q1)
378335 <+> "UNION"
379− <+> parenthesized (renderSQL q2)
336+ <+> parenthesized (renderQuery q2)
380337
381338-- | The results of two queries can be combined using the set operation
382339-- `unionAll`, the disjoint union. Duplicate rows are retained.
383340unionAll
384− :: Query outer commons schemas params columns
385− -> Query outer commons schemas params columns
386− -> Query outer commons schemas params columns
341+ :: Query db params columns
342+ -> Query db params columns
343+ -> Query db params columns
387344q1 `unionAll` q2 = UnsafeQuery $
388− parenthesized (renderSQL q1)
345+ parenthesized (renderQuery q1)
389346 <+> "UNION" <+> "ALL"
390− <+> parenthesized (renderSQL q2)
347+ <+> parenthesized (renderQuery q2)
391348
392349-- | The results of two queries can be combined using the set operation
393350-- `intersect`, the intersection. Duplicate rows are eliminated.
394351intersect
395− :: Query outer commons schemas params columns
396− -> Query outer commons schemas params columns
397− -> Query outer commons schemas params columns
352+ :: Query db params columns
353+ -> Query db params columns
354+ -> Query db params columns
398355q1 `intersect` q2 = UnsafeQuery $
399− parenthesized (renderSQL q1)
356+ parenthesized (renderQuery q1)
400357 <+> "INTERSECT"
401− <+> parenthesized (renderSQL q2)
358+ <+> parenthesized (renderQuery q2)
402359
403360-- | The results of two queries can be combined using the set operation
404361-- `intersectAll`, the intersection. Duplicate rows are retained.
405362intersectAll
406− :: Query outer commons schemas params columns
407− -> Query outer commons schemas params columns
408− -> Query outer commons schemas params columns
363+ :: Query db params columns
364+ -> Query db params columns
365+ -> Query db params columns
409366q1 `intersectAll` q2 = UnsafeQuery $
410− parenthesized (renderSQL q1)
367+ parenthesized (renderQuery q1)
411368 <+> "INTERSECT" <+> "ALL"
412− <+> parenthesized (renderSQL q2)
369+ <+> parenthesized (renderQuery q2)
413370
414371-- | The results of two queries can be combined using the set operation
415372-- `except`, the set difference. Duplicate rows are eliminated.
416373except
417− :: Query outer commons schemas params columns
418− -> Query outer commons schemas params columns
419− -> Query outer commons schemas params columns
374+ :: Query db params columns
375+ -> Query db params columns
376+ -> Query db params columns
420377q1 `except` q2 = UnsafeQuery $
421− parenthesized (renderSQL q1)
378+ parenthesized (renderQuery q1)
422379 <+> "EXCEPT"
423− <+> parenthesized (renderSQL q2)
380+ <+> parenthesized (renderQuery q2)
424381
425382-- | The results of two queries can be combined using the set operation
426383-- `exceptAll`, the set difference. Duplicate rows are retained.
427384exceptAll
428− :: Query outer commons schemas params columns
429− -> Query outer commons schemas params columns
430− -> Query outer commons schemas params columns
385+ :: Query db params columns
386+ -> Query db params columns
387+ -> Query db params columns
431388q1 `exceptAll` q2 = UnsafeQuery $
432− parenthesized (renderSQL q1)
389+ parenthesized (renderQuery q1)
433390 <+> "EXCEPT" <+> "ALL"
434− <+> parenthesized (renderSQL q2)
391+ <+> parenthesized (renderQuery q2)
435392
436393{-----------------------------------------
437394SELECT queries
438395-----------------------------------------}
439396
440−{- | The simplest kinds of `Selection` are `Star` and `DotStar` which
441−emits all columns that a `TableExpression` produces. A select `List`
442−is a list of `Expression`s. A `Selection` could be a list of
443−`WindowFunction`s `Over` `WindowDefinition`. `Additional` `Selection`s can
444−be selected with `Also`.
445−-}
446−data Selection outer commons grp schemas params from row where
397+data Selection db params grp from row where
398+ List
399+ :: SListI row
400+ => NP (Aliased (Expression db params grp from)) row
401+ -> Selection db params grp from row
447402 Star
448403 :: HasUnique tab from row
449− => Selection outer commons 'Ungrouped schemas params from row
450− -- ^ `HasUnique` table in the `FromClause`
404+ => Selection db params 'Ungrouped from row
451405 DotStar
452406 :: Has tab from row
453407 => Alias tab
454− -- ^ `Has` table with `Alias`
455− -> Selection outer commons 'Ungrouped schemas params from row
456− List
457− :: SListI 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
461− Over
462− :: SListI 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
408+ -> Selection db params 'Ungrouped from row
467409 Also
468− :: Selection outer commons grp schemas params from right
469− -- ^ `Additional` `Selection`
470− -> Selection outer commons grp schemas params from left
471− -> Selection outer commons grp schemas params from (Join left right)
472−instance Additional (Selection outer commons grp schemas params from) where
473− also = Also
410+ :: Selection db params grp from right
411+ -> Selection db params grp from left
412+ -> Selection db params grp from (Join left right)
474413instance (KnownSymbol col, row ~ '[col ::: ty])
475414 => Aliasable col
476− (Expression outer commons grp schemas params from ty)
477− (Selection outer commons grp schemas params from row) where
415+ (Expression db params grp from ty)
416+ (Selection db params grp from row) where
478417 expr `as` col = List (expr `as` col)
479−instance (Has tab (Join outer from) row0, Has col row0 ty, row1 ~ '[col ::: ty])
480− => IsQualified tab col
481− (Selection outer commons 'Ungrouped schemas params from row1) where
482− tab ! col = tab ! col `as` col
418+instance (Has tab from row0, Has col row0 ty, row1 ~ '[col ::: ty])
419+ => IsQualified tab col (Selection db params 'Ungrouped from row1) where
420+ tab ! col = tab ! col `as` col
483421instance
484− ( Has tab (Join outer from) row0
422+ ( Has tab from row0
485423 , Has col row0 ty
486424 , row1 ~ '[col ::: ty]
487425 , GroupedBy tab col bys )
488− => IsQualified tab col
489− (Selection outer commons ('Grouped bys) schemas params from row1) where
490− tab ! col = tab ! col `as` col
491−instance (HasUnique tab (Join outer from) row0, Has col row0 ty, row1 ~ '[col ::: ty])
492− => IsLabel col
493− (Selection outer commons 'Ungrouped schemas params from row1) where
494− fromLabel = fromLabel @col `as` Alias
426+ => IsQualified tab col (Selection db params ('Grouped bys) from row1) where
427+ tab ! col = tab ! col `as` col
428+instance (HasUnique tab from row0, Has col row0 ty, row1 ~ '[col ::: ty])
429+ => IsLabel col (Selection db params 'Ungrouped from row1) where
430+ fromLabel = fromLabel @col `as` Alias
495431instance
496− ( HasUnique tab (Join outer from) row0
432+ ( HasUnique tab from row0
497433 , Has col row0 ty
498434 , row1 ~ '[col ::: ty]
499435 , GroupedBy tab col bys )
500− => IsLabel col
501− (Selection outer commons ('Grouped bys) schemas params from row1) where
502− fromLabel = fromLabel @col `as` Alias
436+ => IsLabel col (Selection db params ('Grouped bys) from row1) where
437+ fromLabel = fromLabel @col `as` Alias
503438
504−instance RenderSQL (Selection outer commons grp schemas params from row) where
439+instance RenderSQL (Selection db params grp from row) where
505440 renderSQL = \case
506441 List list -> renderCommaSeparated (renderAliased renderSQL) list
507442 Star -> "*"
508443 DotStar tab -> renderSQL tab <> ".*"
509444 Also right left -> renderSQL left <> ", " <> renderSQL right
510− Over winFns winDef ->
511− let
512− renderOver
513− :: Aliased (WindowFunction outer commons grp schemas params from) field
514− -> ByteString
515− renderOver (winFn `As` col) = renderSQL winFn
516− <+> "OVER" <+> parenthesized (renderSQL winDef)
517− <+> "AS" <+> renderSQL col
518− in
519− renderCommaSeparated renderOver winFns
520−
521−instance IsString
522− (Selection outer commons grp schemas params from '["fromOnly" ::: 'NotNull 'PGtext]) where
523− fromString str = fromString str `as` Alias
524445
525446-- | the `TableExpression` in the `select` command constructs an intermediate
526447-- virtual table by possibly combining tables, views, eliminating rows,
@@ -529,100 +450,45 @@ instance IsString
529450-- the intermediate table are actually output.
530451select
531452 :: (SListI row, row ~ (x ': xs))
532− => Selection outer commons grp schemas params from row
533− -- ^ selection
534− -> TableExpression outer commons grp schemas params from
453+ => Selection db params grp from row
454+ -- ^ select list
455+ -> TableExpression db params grp from
535456 -- ^ intermediate virtual table
536− -> Query outer commons schemas params row
457+ -> Query db params row
537458select selection tabexpr = UnsafeQuery $
538459 "SELECT"
539460 <+> renderSQL selection
540− <+> renderSQL tabexpr
461+ <+> renderTableExpression tabexpr
541462
542−-- | Like `select` but takes an `NP` list of `Expression`s instead
543−-- of a general `Selection`.
544463select_
545464 :: (SListI row, row ~ (x ': xs))
546− => NP (Aliased (Expression outer commons grp schemas params from)) row
547− -- ^ select list
548− -> TableExpression outer commons grp schemas params from
549− -- ^ intermediate virtual table
550− -> Query outer commons schemas params row
551−select_ = select . List
465+ => NP (Aliased (Expression db params grp from)) row
466+ -> TableExpression db params grp from
467+ -> Query db params row
468+select_ list = select (List list)
552469
553470-- | After the select list has been processed, the result table can
554471-- be subject to the elimination of duplicate rows using `selectDistinct`.
555472selectDistinct
556473 :: (SListI columns, columns ~ (col ': cols))
557− => Selection outer commons grp schemas params from columns
558− -- ^ selection
559− -> TableExpression outer commons grp schemas params from
474+ => Selection db params 'Ungrouped from columns
475+ -- ^ select list
476+ -> TableExpression db params 'Ungrouped from
560477 -- ^ intermediate virtual table
561− -> Query outer commons schemas params columns
478+ -> Query db params columns
562479selectDistinct selection tabexpr = UnsafeQuery $
563480 "SELECT DISTINCT"
564481 <+> renderSQL selection
565− <+> renderSQL tabexpr
482+ <+> renderTableExpression tabexpr
566483
567−-- | Like `selectDistinct` but takes an `NP` list of `Expression`s instead
568−-- of a general `Selection`.
569484selectDistinct_
570485 :: (SListI columns, columns ~ (col ': cols))
571− => NP (Aliased (Expression outer commons grp schemas params from)) columns
486+ => NP (Aliased (Expression db params 'Ungrouped from)) columns
572487 -- ^ select list
573− -> TableExpression outer commons grp schemas params from
488+ -> TableExpression db params 'Ungrouped from
574489 -- ^ intermediate virtual table
575− -> Query outer commons schemas params columns
576−selectDistinct_ = selectDistinct . List
577−
578−{-|
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.
583−
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.
587−
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.
590−-}
591−selectDistinctOn
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
596− -- ^ selection
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})
605− where
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
613−
614−-- | Like `selectDistinctOn` but takes an `NP` list of `Expression`s instead
615−-- of a general `Selection`.
616−selectDistinctOn_
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
621− -- ^ selection
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
490+ -> Query db params columns
491+selectDistinct_ list = select (List list)
626492
627493-- | `values` computes a row value or set of row values
628494-- specified by value expressions. It is most commonly used
@@ -630,16 +496,16 @@ selectDistinctOn_ distincts = selectDistinctOn distincts . List
630496-- but it can be used on its own.
631497--
632498-- >>> type Row = '["a" ::: 'NotNull 'PGint4, "b" ::: 'NotNull 'PGtext]
633−-- >>> let query = values (1 `as` #a :* "one" `as` #b) [] :: Query outer commons schemas '[] Row
499+-- >>> let query = values (1 `as` #a :* "one" `as` #b) [] :: Query db '[] Row
634500-- >>> printSQL query
635501-- SELECT * FROM (VALUES (1, E'one')) AS t ("a", "b")
636502values
637503 :: SListI cols
638− => NP (Aliased (Expression outer commons 'Ungrouped schemas params '[] )) cols
639− -> [NP (Aliased (Expression outer commons 'Ungrouped schemas params '[] )) cols]
504+ => NP (Aliased (Expression db params 'Ungrouped '[] )) cols
505+ -> [NP (Aliased (Expression db params 'Ungrouped '[] )) cols]
640506 -- ^ When more than one row is specified, all the rows must
641507 -- must have the same number of elements
642− -> Query outer commons schemas params cols
508+ -> Query db params cols
643509values rw rws = UnsafeQuery $ "SELECT * FROM"
644510 <+> parenthesized (
645511 "VALUES"
@@ -647,20 +513,20 @@ values rw rws = UnsafeQuery $ "SELECT * FROM"
647513 ( parenthesized
648514 . renderCommaSeparated renderValuePart <$> rw:rws )
649515 ) <+> "AS t"
650− <+> parenthesized (renderCommaSeparated renderAliasPart rw)
516+ <+> parenthesized (renderCommaSeparated renderSQLPart rw)
651517 where
652− renderAliasPart, renderValuePart
653− :: Aliased (Expression outer commons 'Ungrouped schemas params '[] ) ty -> ByteString
654− renderAliasPart (_ `As` name) = renderSQL name
518+ renderSQLPart, renderValuePart
519+ :: Aliased (Expression db params 'Ungrouped '[] ) ty -> ByteString
520+ renderSQLPart (_ `As` name) = renderSQL name
655521 renderValuePart (value `As` _) = renderSQL value
656522
657523-- | `values_` computes a row value or set of row values
658524-- specified by value expressions.
659525values_
660526 :: SListI cols
661− => NP (Aliased (Expression outer commons 'Ungrouped schemas params '[] )) cols
527+ => NP (Aliased (Expression db params 'Ungrouped '[] )) cols
662528 -- ^ one row of values
663− -> Query outer commons schemas params cols
529+ -> Query db params cols
664530values_ rw = values rw []
665531
666532{-----------------------------------------
@@ -674,17 +540,15 @@ Table Expressions
674540-- to a table on disk, a so-called base table, but more complex expressions
675541-- can be used to modify or combine base tables in various ways.
676542data TableExpression
677− (outer :: FromType)
678− (commons :: FromType)
679− (grp :: Grouping)
680− (schemas :: SchemasType)
543+ (db :: DBType)
681544 (params :: [NullityType])
545+ (grp :: Grouping)
682546 (from :: FromType)
683547 = TableExpression
684− { fromClause :: FromClause outer commons schemas params from
548+ { fromClause :: FromClause db params from
685549 -- ^ A table reference that can be a table name, or a derived table such
686550 -- as a subquery, a @JOIN@ construct, or complex combinations of these.
687− , whereClause :: [Condition outer commons 'Ungrouped schemas params from]
551+ , whereClause :: [Condition db params 'Ungrouped from]
688552 -- ^ optional search coditions, combined with `.&&`. After the processing
689553 -- of the `fromClause` is done, each row of the derived virtual table
690554 -- is checked against the search condition. If the result of the
@@ -700,13 +564,13 @@ data TableExpression
700564 -- set of rows having common values into one group row that represents all
701565 -- rows in the group. This is done to eliminate redundancy in the output
702566 -- and/or compute aggregates that apply to these groups.
703− , havingClause :: HavingClause outer commons grp schemas params from
567+ , havingClause :: HavingClause db params grp from
704568 -- ^ If a table has been grouped using `groupBy`, but only certain groups
705569 -- are of interest, the `havingClause` can be used, much like a
706570 -- `whereClause`, to eliminate groups from the result. Expressions in the
707571 -- `havingClause` can refer both to grouped expressions and to ungrouped
708572 -- expressions (which necessarily involve an aggregate function).
709− , orderByClause :: [SortExpression outer commons grp schemas params from]
573+ , orderByClause :: [SortExpression db params grp from]
710574 -- ^ The `orderByClause` is for optional sorting. When more than one
711575 -- `SortExpression` is specified, the later (right) values are used to sort
712576 -- rows that are equal according to the earlier (left) values.
@@ -716,69 +580,72 @@ data TableExpression
716580 -- will be returned (but possibly fewer, if the query itself yields
717581 -- fewer rows).
718582 , offsetClause :: [Word64]
719− -- ^ The `offsetClause` is combined with `Prelude.+` to give an offset count
583+ -- ^ The `offsetClause` is combined with `+` to give an offset count
720584 -- if nonempty. The offset count says to skip that many rows before
721585 -- beginning to return rows. The rows are skipped before the limit count
722586 -- is applied.
723− } deriving (GHC.Generic)
587+ }
724588
725589-- | Render a `TableExpression`
726−instance RenderSQL (TableExpression outer commons grp schemas params from) where
727− renderSQL
728− (TableExpression frm' whs' grps' hvs' srts' lims' offs') = mconcat
729− [ "FROM ", renderSQL frm'
730− , renderWheres whs'
731− , renderSQL grps'
732− , renderSQL hvs'
733− , renderOrderByClause srts'
734− , renderLimits lims'
735− , renderOffsets offs' ]
736− where
737− renderWheres = \case
738− [] -> ""
739− wh:[] -> " WHERE" <+> renderSQL wh
740− wh:whs -> " WHERE" <+> renderSQL (foldr (.&&) wh whs)
741− renderOrderByClause = \case
742− [] -> ""
743− srts -> " ORDER BY"
744− <+> commaSeparated (renderSQL <$> srts)
745− renderLimits = \case
746− [] -> ""
747− lims -> " LIMIT" <+> fromString (show (minimum lims))
748− renderOffsets = \case
749− [] -> ""
750− offs -> " OFFSET" <+> fromString (show (sum offs))
590+renderTableExpression
591+ :: TableExpression db params grp from
592+ -> ByteString
593+renderTableExpression
594+ (TableExpression frm' whs' grps' hvs' srts' lims' offs') = mconcat
595+ [ "FROM ", renderFromClause frm'
596+ , renderWheres whs'
597+ , renderGroupByClause grps'
598+ , renderHavingClause hvs'
599+ , renderOrderByClause srts'
600+ , renderLimits lims'
601+ , renderOffsets offs'
602+ ]
603+ where
604+ renderWheres = \case
605+ [] -> ""
606+ wh:[] -> " WHERE" <+> renderSQL wh
607+ wh:whs -> " WHERE" <+> renderSQL (foldr (.&&) wh whs)
608+ renderOrderByClause = \case
609+ [] -> ""
610+ srts -> " ORDER BY"
611+ <+> commaSeparated (renderSQL <$> srts)
612+ renderLimits = \case
613+ [] -> ""
614+ lims -> " LIMIT" <+> fromString (show (minimum lims))
615+ renderOffsets = \case
616+ [] -> ""
617+ offs -> " OFFSET" <+> fromString (show (sum offs))
751618
752619-- | A `from` generates a `TableExpression` from a table reference that can be
753620-- a table name, or a derived table such as a subquery, a JOIN construct,
754621-- or complex combinations of these. A `from` may be transformed by `where_`,
755−-- `groupBy`, `having`, `orderBy`, `limit` and `offset`, using the `&` operator
622+-- `group`, `having`, `orderBy`, `limit` and `offset`, using the `&` operator
756623-- to match the left-to-right sequencing of their placement in SQL.
757624from
758− :: FromClause outer commons schemas params from -- ^ table reference
759− -> TableExpression outer commons 'Ungrouped schemas params from
760−from tab = TableExpression tab [] noGroups NoHaving [] [] []
625+ :: FromClause db params from -- ^ table reference
626+ -> TableExpression db params 'Ungrouped from
627+from rels = TableExpression rels [] NoGroups NoHaving [] [] []
761628
762629-- | A `where_` is an endomorphism of `TableExpression`s which adds a
763630-- search condition to the `whereClause`.
764631where_
765− :: Condition outer commons 'Ungrouped schemas params from -- ^ filtering condition
766− -> TableExpression outer commons grp schemas params from
767− -> TableExpression outer commons grp schemas params from
632+ :: Condition db params 'Ungrouped from -- ^ filtering condition
633+ -> TableExpression db params grp from
634+ -> TableExpression db params grp from
768635where_ wh rels = rels {whereClause = wh : whereClause rels}
769636
770637-- | A `groupBy` is a transformation of `TableExpression`s which switches
771−-- its `Grouping` from `Ungrouped` to `Grouped`. Use @groupBy Nil@ to perform
638+-- its `Grouping` from `Ungrouped` to `Grouped`. Use @group Nil@ to perform
772639-- a "grand total" aggregation query.
773640groupBy
774641 :: SListI bys
775642 => NP (By from) bys -- ^ grouped columns
776− -> TableExpression outer commons 'Ungrouped schemas params from
777− -> TableExpression outer commons ('Grouped bys) schemas params from
643+ -> TableExpression db params 'Ungrouped from
644+ -> TableExpression db params ('Grouped bys) from
778645groupBy bys rels = TableExpression
779646 { fromClause = fromClause rels
780647 , whereClause = whereClause rels
781− , groupByClause = group bys
648+ , groupByClause = Group bys
782649 , havingClause = Having []
783650 , orderByClause = []
784651 , limitClause = limitClause rels
@@ -788,31 +655,177 @@ groupBy bys rels = TableExpression
788655-- | A `having` is an endomorphism of `TableExpression`s which adds a
789656-- search condition to the `havingClause`.
790657having
791− :: Condition outer commons ('Grouped bys) schemas params from -- ^ having condition
792− -> TableExpression outer commons ('Grouped bys) schemas params from
793− -> TableExpression outer commons ('Grouped bys) schemas params from
658+ :: Condition db params ('Grouped bys) from -- ^ having condition
659+ -> TableExpression db params ('Grouped bys) from
660+ -> TableExpression db params ('Grouped bys) from
794661having hv rels = rels
795662 { havingClause = case havingClause rels of Having hvs -> Having (hv:hvs) }
796663
797−instance OrderBy TableExpression where
798− orderBy srts rels = rels {orderByClause = orderByClause rels ++ srts}
664+-- | An `orderBy` is an endomorphism of `TableExpression`s which appends an
665+-- ordering to the right of the `orderByClause`.
666+orderBy
667+ :: [SortExpression db params grp from] -- ^ sort expressions
668+ -> TableExpression db params grp from
669+ -> TableExpression db params grp from
670+orderBy srts rels = rels {orderByClause = orderByClause rels ++ srts}
799671
800672-- | A `limit` is an endomorphism of `TableExpression`s which adds to the
801673-- `limitClause`.
802674limit
803675 :: Word64 -- ^ limit parameter
804− -> TableExpression outer commons grp schemas params from
805− -> TableExpression outer commons grp schemas params from
676+ -> TableExpression db params grp from
677+ -> TableExpression db params grp from
806678limit lim rels = rels {limitClause = lim : limitClause rels}
807679
808680-- | An `offset` is an endomorphism of `TableExpression`s which adds to the
809681-- `offsetClause`.
810682offset
811683 :: Word64 -- ^ offset parameter
812− -> TableExpression outer commons grp schemas params from
813− -> TableExpression outer commons grp schemas params from
684+ -> TableExpression db params grp from
685+ -> TableExpression db params grp from
814686offset off rels = rels {offsetClause = off : offsetClause rels}
815687
688+{-----------------------------------------
689+JSON stuff
690+-----------------------------------------}
691+
692+unsafeSetOfFunction
693+ :: ByteString
694+ -> Expression db params 'Ungrouped '[] ty
695+ -> Query db params row
696+unsafeSetOfFunction fun expr = UnsafeQuery $
697+ "SELECT * FROM " <> fun <> "(" <> renderSQL expr <> ")"
698+
699+-- | Expands the outermost JSON object into a set of key/value pairs.
700+jsonEach
701+ :: Expression db params 'Ungrouped '[] (nullity 'PGjson) -- ^ json object
702+ -> Query db params
703+ '["key" ::: 'NotNull 'PGtext, "value" ::: 'NotNull 'PGjson]
704+jsonEach = unsafeSetOfFunction "json_each"
705+
706+-- | Expands the outermost binary JSON object into a set of key/value pairs.
707+jsonbEach
708+ :: Expression db params 'Ungrouped '[] (nullity 'PGjsonb) -- ^ jsonb object
709+ -> Query db params
710+ '["key" ::: 'NotNull 'PGtext, "value" ::: 'NotNull 'PGjsonb]
711+jsonbEach = unsafeSetOfFunction "jsonb_each"
712+
713+-- | Expands the outermost JSON object into a set of key/value pairs.
714+jsonEachAsText
715+ :: Expression db params 'Ungrouped '[] (nullity 'PGjson) -- ^ json object
716+ -> Query db params
717+ '["key" ::: 'NotNull 'PGtext, "value" ::: 'NotNull 'PGtext]
718+jsonEachAsText = unsafeSetOfFunction "json_each_text"
719+
720+-- | Expands the outermost binary JSON object into a set of key/value pairs.
721+jsonbEachAsText
722+ :: Expression db params 'Ungrouped '[] (nullity 'PGjsonb) -- ^ jsonb object
723+ -> Query db params
724+ '["key" ::: 'NotNull 'PGtext, "value" ::: 'NotNull 'PGtext]
725+jsonbEachAsText = unsafeSetOfFunction "jsonb_each_text"
726+
727+-- | Returns set of keys in the outermost JSON object.
728+jsonObjectKeys
729+ :: Expression db params 'Ungrouped '[] (nullity 'PGjson) -- ^ json object
730+ -> Query db params '["json_object_keys" ::: 'NotNull 'PGtext]
731+jsonObjectKeys = unsafeSetOfFunction "json_object_keys"
732+
733+-- | Returns set of keys in the outermost JSON object.
734+jsonbObjectKeys
735+ :: Expression db params 'Ungrouped '[] (nullity 'PGjsonb) -- ^ jsonb object
736+ -> Query db params '["jsonb_object_keys" ::: 'NotNull 'PGtext]
737+jsonbObjectKeys = unsafeSetOfFunction "jsonb_object_keys"
738+
739+unsafePopulateFunction
740+ :: ByteString
741+ -> TypeExpression schemas (nullity ('PGcomposite row))
742+ -> Expression (commons :=> schemas) params 'Ungrouped '[] ty
743+ -> Query (commons :=> schemas) params row
744+unsafePopulateFunction fun ty expr = UnsafeQuery $
745+ "SELECT * FROM " <> fun <> "("
746+ <> "null::" <> renderSQL ty <> ", "
747+ <> renderSQL expr <> ")"
748+
749+-- | Expands the JSON expression to a row whose columns match the record
750+-- type defined by the given table.
751+jsonPopulateRecord
752+ :: TypeExpression schemas (nullity ('PGcomposite row)) -- ^ row type
753+ -> Expression (commons :=> schemas) params 'Ungrouped '[] (nullity 'PGjson) -- ^ json object
754+ -> Query (commons :=> schemas) params row
755+jsonPopulateRecord = unsafePopulateFunction "json_populate_record"
756+
757+-- | Expands the binary JSON expression to a row whose columns match the record
758+-- type defined by the given table.
759+jsonbPopulateRecord
760+ :: TypeExpression schemas (nullity ('PGcomposite row)) -- ^ row type
761+ -> Expression (commons :=> schemas) params 'Ungrouped '[] (nullity 'PGjsonb) -- ^ jsonb object
762+ -> Query (commons :=> schemas) params row
763+jsonbPopulateRecord = unsafePopulateFunction "jsonb_populate_record"
764+
765+-- | Expands the outermost array of objects in the given JSON expression to a
766+-- set of rows whose columns match the record type defined by the given table.
767+jsonPopulateRecordSet
768+ :: TypeExpression schemas (nullity ('PGcomposite row)) -- ^ row type
769+ -> Expression (commons :=> schemas) params 'Ungrouped '[] (nullity 'PGjson) -- ^ json array
770+ -> Query (commons :=> schemas) params row
771+jsonPopulateRecordSet = unsafePopulateFunction "json_populate_record_set"
772+
773+-- | Expands the outermost array of objects in the given binary JSON expression
774+-- to a set of rows whose columns match the record type defined by the given
775+-- table.
776+jsonbPopulateRecordSet
777+ :: TypeExpression schemas (nullity ('PGcomposite row)) -- ^ row type
778+ -> Expression (commons :=> schemas) params 'Ungrouped '[] (nullity 'PGjsonb) -- ^ jsonb array
779+ -> Query (commons :=> schemas) params row
780+jsonbPopulateRecordSet = unsafePopulateFunction "jsonb_populate_record_set"
781+
782+unsafeRecordFunction
783+ :: (SListI record, json `In` PGJsonType)
784+ => ByteString
785+ -> Expression (commons :=> schemas) params 'Ungrouped '[] (nullity json)
786+ -> NP (Aliased (TypeExpression schemas)) record
787+ -> Query (commons :=> schemas) params record
788+unsafeRecordFunction fun expr types = UnsafeQuery $
789+ "SELECT * FROM " <> fun <> "("
790+ <> renderSQL expr <> ")"
791+ <+> "AS" <+> "x" <> parenthesized (renderCommaSeparated renderTy types)
792+ where
793+ renderTy :: Aliased (TypeExpression db) ty -> ByteString
794+ renderTy (ty `As` alias) =
795+ renderSQL alias <+> renderSQL ty
796+
797+-- | Builds an arbitrary record from a JSON object.
798+jsonToRecord
799+ :: SListI record
800+ => Expression (commons :=> schemas) params 'Ungrouped '[] (nullity 'PGjson) -- ^ json object
801+ -> NP (Aliased (TypeExpression schemas)) record -- ^ record types
802+ -> Query (commons :=> schemas) params record
803+jsonToRecord = unsafeRecordFunction "json_to_record"
804+
805+-- | Builds an arbitrary record from a binary JSON object.
806+jsonbToRecord
807+ :: SListI record
808+ => Expression (commons :=> schemas) params 'Ungrouped '[] (nullity 'PGjsonb) -- ^ jsonb object
809+ -> NP (Aliased (TypeExpression schemas)) record -- ^ record types
810+ -> Query (commons :=> schemas) params record
811+jsonbToRecord = unsafeRecordFunction "jsonb_to_record"
812+
813+-- | Builds an arbitrary set of records from a JSON array of objects.
814+jsonToRecordSet
815+ :: SListI record
816+ => Expression (commons :=> schemas) params 'Ungrouped '[] (nullity 'PGjson) -- ^ json array
817+ -> NP (Aliased (TypeExpression schemas)) record -- ^ record types
818+ -> Query (commons :=> schemas) params record
819+jsonToRecordSet = unsafeRecordFunction "json_to_record_set"
820+
821+-- | Builds an arbitrary set of records from a binary JSON array of objects.
822+jsonbToRecordSet
823+ :: SListI record
824+ => Expression (commons :=> schemas) params 'Ungrouped '[] (nullity 'PGjsonb) -- ^ jsonb array
825+ -> NP (Aliased (TypeExpression schemas)) record -- ^ record types
826+ -> Query (commons :=> schemas) params record
827+jsonbToRecordSet = unsafeRecordFunction "jsonb_to_record_set"
828+
816829{-----------------------------------------
817830FROM clauses
818831-----------------------------------------}
@@ -821,75 +834,67 @@ FROM clauses
821834A `FromClause` can be a table name, or a derived table such
822835as a subquery, a @JOIN@ construct, or complex combinations of these.
823836-}
824−newtype FromClause outer commons schemas params from
837+newtype FromClause db params from
825838 = UnsafeFromClause { renderFromClause :: ByteString }
826839 deriving (GHC.Generic,Show,Eq,Ord,NFData)
827−instance RenderSQL (FromClause outer commons schemas params from) where
828− renderSQL = renderFromClause
829840
830841-- | A real `table` is a table from the database.
831842table
832843 :: (Has sch schemas schema, Has tab schema ('Table table))
833844 => Aliased (QualifiedAlias sch) (alias ::: tab)
834− -> FromClause outer commons schemas params '[alias ::: TableToRow table]
845+ -> FromClause (commons :=> schemas) params '[alias ::: TableToRow table]
835846table (tab `As` alias) = UnsafeFromClause $
836847 renderSQL tab <+> "AS" <+> renderSQL alias
837848
838849-- | `subquery` derives a table from a `Query`.
839850subquery
840− :: Aliased (Query outer commons schemas params) query
841− -> FromClause outer commons schemas params '[query]
842−subquery = UnsafeFromClause . renderAliased (parenthesized . renderSQL)
851+ :: Aliased (Query db params) query
852+ -> FromClause db params '[query]
853+subquery = UnsafeFromClause . renderAliased (parenthesized . renderQuery)
843854
844855-- | `view` derives a table from a `View`.
845856view
846857 :: (Has sch schemas schema, Has vw schema ('View view))
847858 => Aliased (QualifiedAlias sch) (alias ::: vw)
848− -> FromClause outer commons schemas params '[alias ::: view]
859+ -> FromClause (commons :=> schemas) params '[alias ::: view]
849860view (vw `As` alias) = UnsafeFromClause $
850861 renderSQL vw <+> "AS" <+> renderSQL alias
851862
852−-- | `common` derives a table from a common table expression.
853863common
854864 :: Has cte commons common
855865 => Aliased Alias (alias ::: cte)
856− -> FromClause outer commons schemas params '[alias ::: common]
866+ -> FromClause (commons :=> schemas) params '[alias ::: common]
857867common (cte `As` alias) = UnsafeFromClause $
858868 renderSQL cte <+> "AS" <+> renderSQL alias
859869
860−instance Additional (FromClause outer commons schemas params) where
861− also right left = UnsafeFromClause $
862− renderSQL left <> ", " <> renderSQL right
863−
864−{- |
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
869−have @n * m@ rows.
870+{- | @left & crossJoin right@. For every possible combination of rows from
871+ @left@ and @right@ (i.e., a Cartesian product), the joined table will contain
872+ a row consisting of all columns in @left@ followed by all columns in @right@.
873+ If the tables have @n@ and @m@ rows respectively, the joined table will
874+ have @n * m@ rows.
870875-}
871876crossJoin
872− :: FromClause outer commons schemas params right
877+ :: FromClause db params right
873878 -- ^ right
874− -> FromClause outer commons schemas params left
879+ -> FromClause db params left
875880 -- ^ left
876− -> FromClause outer commons schemas params (Join left right)
881+ -> FromClause db params (Join left right)
877882crossJoin right left = UnsafeFromClause $
878− renderSQL left <+> "CROSS JOIN" <+> renderSQL right
883+ renderFromClause left <+> "CROSS JOIN" <+> renderFromClause right
879884
880885{- | @left & innerJoin right on@. The joined table is filtered by
881886the @on@ condition.
882887-}
883888innerJoin
884− :: FromClause outer commons schemas params right
889+ :: FromClause db params right
885890 -- ^ right
886− -> Condition outer commons 'Ungrouped schemas params (Join left right)
891+ -> Condition db params 'Ungrouped (Join left right)
887892 -- ^ @on@ condition
888− -> FromClause outer commons schemas params left
893+ -> FromClause db params left
889894 -- ^ left
890− -> FromClause outer commons schemas params (Join left right)
895+ -> FromClause db params (Join left right)
891896innerJoin right on left = UnsafeFromClause $
892− renderSQL left <+> "INNER JOIN" <+> renderSQL right
897+ renderFromClause left <+> "INNER JOIN" <+> renderFromClause right
893898 <+> "ON" <+> renderSQL on
894899
895900{- | @left & leftOuterJoin right on@. First, an inner join is performed.
@@ -898,15 +903,15 @@ innerJoin right on left = UnsafeFromClause $
898903 Thus, the joined table always has at least one row for each row in @left@.
899904-}
900905leftOuterJoin
901− :: FromClause outer commons schemas params right
906+ :: FromClause db params right
902907 -- ^ right
903− -> Condition outer commons 'Ungrouped schemas params (Join left right)
908+ -> Condition db params 'Ungrouped (Join left right)
904909 -- ^ @on@ condition
905− -> FromClause outer commons schemas params left
910+ -> FromClause db params left
906911 -- ^ left
907− -> FromClause outer commons schemas params (Join left (NullifyFrom right))
912+ -> FromClause db params (Join left (NullifyFrom right))
908913leftOuterJoin right on left = UnsafeFromClause $
909− renderSQL left <+> "LEFT OUTER JOIN" <+> renderSQL right
914+ renderFromClause left <+> "LEFT OUTER JOIN" <+> renderFromClause right
910915 <+> "ON" <+> renderSQL on
911916
912917{- | @left & rightOuterJoin right on@. First, an inner join is performed.
@@ -916,15 +921,15 @@ leftOuterJoin right on left = UnsafeFromClause $
916921 have a row for each row in @right@.
917922-}
918923rightOuterJoin
919− :: FromClause outer commons schemas params right
924+ :: FromClause db params right
920925 -- ^ right
921− -> Condition outer commons 'Ungrouped schemas params (Join left right)
926+ -> Condition db params 'Ungrouped (Join left right)
922927 -- ^ @on@ condition
923− -> FromClause outer commons schemas params left
928+ -> FromClause db params left
924929 -- ^ left
925− -> FromClause outer commons schemas params (Join (NullifyFrom left) right)
930+ -> FromClause db params (Join (NullifyFrom left) right)
926931rightOuterJoin right on left = UnsafeFromClause $
927− renderSQL left <+> "RIGHT OUTER JOIN" <+> renderSQL right
932+ renderFromClause left <+> "RIGHT OUTER JOIN" <+> renderFromClause right
928933 <+> "ON" <+> renderSQL on
929934
930935{- | @left & fullOuterJoin right on@. First, an inner join is performed.
@@ -935,23 +940,23 @@ rightOuterJoin right on left = UnsafeFromClause $
935940 is added.
936941-}
937942fullOuterJoin
938− :: FromClause outer commons schemas params right
943+ :: FromClause db params right
939944 -- ^ right
940− -> Condition outer commons 'Ungrouped schemas params (Join left right)
945+ -> Condition db params 'Ungrouped (Join left right)
941946 -- ^ @on@ condition
942− -> FromClause outer commons schemas params left
947+ -> FromClause db params left
943948 -- ^ left
944− -> FromClause outer commons schemas params
949+ -> FromClause db params
945950 (Join (NullifyFrom left) (NullifyFrom right))
946951fullOuterJoin right on left = UnsafeFromClause $
947− renderSQL left <+> "FULL OUTER JOIN" <+> renderSQL right
952+ renderFromClause left <+> "FULL OUTER JOIN" <+> renderFromClause right
948953 <+> "ON" <+> renderSQL on
949954
950955{-----------------------------------------
951956Grouping
952957-----------------------------------------}
953958
954−-- | `By`s are used in `groupBy` to reference a list of columns which are then
959+-- | `By`s are used in `group` to reference a list of columns which are then
955960-- used to group together those rows in a table that have the same values
956961-- in all the columns listed. @By \#col@ will reference an unambiguous
957962-- column @col@; otherwise @By2 (\#tab \! \#col)@ will reference a table
@@ -971,10 +976,6 @@ data By
971976deriving instance Show (By from by)
972977deriving instance Eq (By from by)
973978deriving instance Ord (By from by)
974−instance RenderSQL (By from by) where
975− renderSQL = \case
976− By1 column -> renderSQL column
977− By2 rel column -> renderSQL rel <> "." <> renderSQL column
978979
979980instance (HasUnique rel rels cols, Has col cols ty, by ~ '(rel, col))
980981 => IsLabel col (By rels by) where fromLabel = By1 fromLabel
@@ -986,113 +987,424 @@ instance (Has rel rels cols, Has col cols ty, bys ~ '[ '(rel, col)])
986987 => IsQualified rel col (NP (By rels) bys) where
987988 rel ! col = By2 rel col :* Nil
988989
990+-- | Renders a `By`.
991+renderBy :: By from by -> ByteString
992+renderBy = \case
993+ By1 column -> renderSQL column
994+ By2 rel column -> renderSQL rel <> "." <> renderSQL column
995+
989996-- | A `GroupByClause` indicates the `Grouping` of a `TableExpression`.
990997-- A `NoGroups` indicates `Ungrouped` while a `Group` indicates `Grouped`.
991998-- @NoGroups@ is distinguised from @Group Nil@ since no aggregation can be
992999-- done on @NoGroups@ while all output `Expression`s must be aggregated
9931000-- in @Group Nil@. In general, all output `Expression`s in the
9941001-- complement of @bys@ must be aggregated in @Group bys@.
995−newtype GroupByClause grp from = UnsafeGroupByClause
996− { renderGroupByClause :: ByteString }
997− deriving (GHC.Generic,Show,Eq,Ord,NFData)
998−instance RenderSQL (GroupByClause grp from) where
999− renderSQL = renderGroupByClause
1000−noGroups :: GroupByClause 'Ungrouped from
1001−noGroups = UnsafeGroupByClause ""
1002−group
1003− :: SListI bys
1004− => NP (By from) bys
1005− -> GroupByClause ('Grouped bys) from
1006−group bys = UnsafeGroupByClause $ case bys of
1007− Nil -> ""
1008− bys' -> " GROUP BY" <+> renderCommaSeparated renderSQL bys'
1002+data GroupByClause grp from where
1003+ NoGroups :: GroupByClause 'Ungrouped from
1004+ Group
1005+ :: SListI bys
1006+ => NP (By from) bys
1007+ -> GroupByClause ('Grouped bys) from
1008+
1009+-- | Renders a `GroupByClause`.
1010+renderGroupByClause :: GroupByClause grp from -> ByteString
1011+renderGroupByClause = \case
1012+ NoGroups -> ""
1013+ Group Nil -> ""
1014+ Group bys -> " GROUP BY" <+> renderCommaSeparated renderBy bys
10091015
10101016-- | A `HavingClause` is used to eliminate groups that are not of interest.
10111017-- An `Ungrouped` `TableExpression` may only use `NoHaving` while a `Grouped`
10121018-- `TableExpression` must use `Having` whose conditions are combined with
10131019-- `.&&`.
1014−data HavingClause outer commons grp schemas params from where
1015− NoHaving :: HavingClause outer commons 'Ungrouped schemas params from
1020+data HavingClause db params grp from where
1021+ NoHaving :: HavingClause db params 'Ungrouped from
10161022 Having
1017− :: [Condition outer commons ('Grouped bys) schemas params from]
1018− -> HavingClause outer commons ('Grouped bys) schemas params from
1019−deriving instance Show (HavingClause outer commons grp schemas params from)
1020−deriving instance Eq (HavingClause outer commons grp schemas params from)
1021−deriving instance Ord (HavingClause outer commons grp schemas params from)
1023+ :: [Condition db params ('Grouped bys) from]
1024+ -> HavingClause db params ('Grouped bys) from
1025+deriving instance Show (HavingClause db params grp from)
1026+deriving instance Eq (HavingClause db params grp from)
1027+deriving instance Ord (HavingClause db params grp from)
10221028
10231029-- | Render a `HavingClause`.
1024−instance RenderSQL (HavingClause outer commons grp schemas params from) where
1030+renderHavingClause :: HavingClause db params grp from -> ByteString
1031+renderHavingClause = \case
1032+ NoHaving -> ""
1033+ Having [] -> ""
1034+ Having conditions ->
1035+ " HAVING" <+> commaSeparated (renderSQL <$> conditions)
1036+
1037+{-----------------------------------------
1038+Sorting
1039+-----------------------------------------}
1040+
1041+-- | `SortExpression`s are used by `sortBy` to optionally sort the results
1042+-- of a `Query`. `Asc` or `Desc` set the sort direction of a `NotNull` result
1043+-- column to ascending or descending. Ascending order puts smaller values
1044+-- first, where "smaller" is defined in terms of the `.<` operator. Similarly,
1045+-- descending order is determined with the `.>` operator. `AscNullsFirst`,
1046+-- `AscNullsLast`, `DescNullsFirst` and `DescNullsLast` options are used to
1047+-- determine whether nulls appear before or after non-null values in the sort
1048+-- ordering of a `Null` result column.
1049+data SortExpression db params grp from where
1050+ Asc
1051+ :: Expression db params grp from ('NotNull ty)
1052+ -> SortExpression db params grp from
1053+ Desc
1054+ :: Expression db params grp from ('NotNull ty)
1055+ -> SortExpression db params grp from
1056+ AscNullsFirst
1057+ :: Expression db params grp from ('Null ty)
1058+ -> SortExpression db params grp from
1059+ AscNullsLast
1060+ :: Expression db params grp from ('Null ty)
1061+ -> SortExpression db params grp from
1062+ DescNullsFirst
1063+ :: Expression db params grp from ('Null ty)
1064+ -> SortExpression db params grp from
1065+ DescNullsLast
1066+ :: Expression db params grp from ('Null ty)
1067+ -> SortExpression db params grp from
1068+deriving instance Show (SortExpression db params grp from)
1069+
1070+-- | Render a `SortExpression`.
1071+instance RenderSQL (SortExpression db params grp from) where
10251072 renderSQL = \case
1026− NoHaving -> ""
1027− Having [] -> ""
1028− Having conditions ->
1029− " HAVING" <+> commaSeparated (renderSQL <$> conditions)
1073+ Asc expression -> renderSQL expression <+> "ASC"
1074+ Desc expression -> renderSQL expression <+> "DESC"
1075+ AscNullsFirst expression -> renderSQL expression
1076+ <+> "ASC NULLS FIRST"
1077+ DescNullsFirst expression -> renderSQL expression
1078+ <+> "DESC NULLS FIRST"
1079+ AscNullsLast expression -> renderSQL expression <+> "ASC NULLS LAST"
1080+ DescNullsLast expression -> renderSQL expression <+> "DESC NULLS LAST"
1081+
1082+unsafeSubqueryExpression
1083+ :: ByteString
1084+ -> Expression db params grp from ty
1085+ -> Query db params '[alias ::: ty]
1086+ -> Expression db params grp from (nullity 'PGbool)
1087+unsafeSubqueryExpression op x q = UnsafeExpression $
1088+ renderSQL x <+> op <+> parenthesized (renderQuery q)
1089+
1090+unsafeRowSubqueryExpression
1091+ :: SListI row
1092+ => ByteString
1093+ -> NP (Aliased (Expression db params grp from)) row
1094+ -> Query db params row
1095+ -> Expression db params grp from (nullity 'PGbool)
1096+unsafeRowSubqueryExpression op xs q = UnsafeExpression $
1097+ renderSQL (row xs) <+> op <+> parenthesized (renderQuery q)
1098+
1099+-- | The right-hand side is a sub`Query`, which must return exactly one column.
1100+-- The left-hand expression is evaluated and compared to each row of the
1101+-- sub`Query` result. The result of `in_` is `true` if any equal subquery row is found.
1102+-- The result is `false` if no equal row is found
1103+-- (including the case where the subquery returns no rows).
1104+--
1105+-- >>> printSQL $ true `in_` values_ (true `as` #foo)
1106+-- TRUE IN (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1107+in_
1108+ :: Expression db params grp from ty -- ^ expression
1109+ -> Query db params '[alias ::: ty] -- ^ subquery
1110+ -> Expression db params grp from (nullity 'PGbool)
1111+in_ = unsafeSubqueryExpression "IN"
1112+
1113+{- | The left-hand side of this form of `rowIn` is a row constructor.
1114+The right-hand side is a sub`Query`,
1115+which must return exactly as many columns as
1116+there are expressions in the left-hand row.
1117+The left-hand expressions are evaluated and compared row-wise to each row
1118+of the subquery result. The result of `rowIn`
1119+is `true` if any equal subquery row is found.
1120+The result is `false` if no equal row is found
1121+(including the case where the subquery returns no rows).
1122+
1123+>>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db params grp from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1124+>>> printSQL $ myRow `rowIn` values_ myRow
1125+ROW(1, FALSE) IN (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1126+-}
1127+rowIn
1128+ :: SListI row
1129+ => NP (Aliased (Expression db params grp from)) row -- ^ row constructor
1130+ -> Query db params row -- ^ subquery
1131+ -> Expression db params grp from (nullity 'PGbool)
1132+rowIn = unsafeRowSubqueryExpression "IN"
1133+
1134+-- | >>> printSQL $ true `eqAll` values_ (true `as` #foo)
1135+-- TRUE = ALL (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1136+eqAll
1137+ :: Expression db params grp from ty -- ^ expression
1138+ -> Query db params '[alias ::: ty] -- ^ subquery
1139+ -> Expression db params grp from (nullity 'PGbool)
1140+eqAll = unsafeSubqueryExpression "= ALL"
1141+
1142+-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db params grp from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1143+-- >>> printSQL $ myRow `rowEqAll` values_ myRow
1144+-- ROW(1, FALSE) = ALL (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1145+rowEqAll
1146+ :: SListI row
1147+ => NP (Aliased (Expression db params grp from)) row -- ^ row constructor
1148+ -> Query db params row -- ^ subquery
1149+ -> Expression db params grp from (nullity 'PGbool)
1150+rowEqAll = unsafeRowSubqueryExpression "= ALL"
1151+
1152+-- | >>> printSQL $ true `eqAny` values_ (true `as` #foo)
1153+-- TRUE = ANY (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1154+eqAny
1155+ :: Expression db params grp from ty -- ^ expression
1156+ -> Query db params '[alias ::: ty] -- ^ subquery
1157+ -> Expression db params grp from (nullity 'PGbool)
1158+eqAny = unsafeSubqueryExpression "= ANY"
1159+
1160+-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db params grp from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1161+-- >>> printSQL $ myRow `rowEqAny` values_ myRow
1162+-- ROW(1, FALSE) = ANY (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1163+rowEqAny
1164+ :: SListI row
1165+ => NP (Aliased (Expression db params grp from)) row -- ^ row constructor
1166+ -> Query db params row -- ^ subquery
1167+ -> Expression db params grp from (nullity 'PGbool)
1168+rowEqAny = unsafeRowSubqueryExpression "= ANY"
1169+
1170+-- | >>> printSQL $ true `neqAll` values_ (true `as` #foo)
1171+-- TRUE <> ALL (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1172+neqAll
1173+ :: Expression db params grp from ty -- ^ expression
1174+ -> Query db params '[alias ::: ty] -- ^ subquery
1175+ -> Expression db params grp from (nullity 'PGbool)
1176+neqAll = unsafeSubqueryExpression "<> ALL"
1177+
1178+-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db params grp from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1179+-- >>> printSQL $ myRow `rowNeqAll` values_ myRow
1180+-- ROW(1, FALSE) <> ALL (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1181+rowNeqAll
1182+ :: SListI row
1183+ => NP (Aliased (Expression db params grp from)) row -- ^ row constructor
1184+ -> Query db params row -- ^ subquery
1185+ -> Expression db params grp from (nullity 'PGbool)
1186+rowNeqAll = unsafeRowSubqueryExpression "<> ALL"
1187+
1188+-- | >>> printSQL $ true `neqAny` values_ (true `as` #foo)
1189+-- TRUE <> ANY (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1190+neqAny
1191+ :: Expression db params grp from ty -- ^ expression
1192+ -> Query db params '[alias ::: ty] -- ^ subquery
1193+ -> Expression db params grp from (nullity 'PGbool)
1194+neqAny = unsafeSubqueryExpression "<> ANY"
1195+
1196+-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db params grp from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1197+-- >>> printSQL $ myRow `rowNeqAny` values_ myRow
1198+-- ROW(1, FALSE) <> ANY (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1199+rowNeqAny
1200+ :: SListI row
1201+ => NP (Aliased (Expression db params grp from)) row -- ^ row constructor
1202+ -> Query db params row -- ^ subquery
1203+ -> Expression db params grp from (nullity 'PGbool)
1204+rowNeqAny = unsafeRowSubqueryExpression "<> ANY"
1205+
1206+-- | >>> printSQL $ true `allLt` values_ (true `as` #foo)
1207+-- TRUE ALL < (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1208+allLt
1209+ :: Expression db params grp from ty -- ^ expression
1210+ -> Query db params '[alias ::: ty] -- ^ subquery
1211+ -> Expression db params grp from (nullity 'PGbool)
1212+allLt = unsafeSubqueryExpression "ALL <"
1213+
1214+-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db params grp from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1215+-- >>> printSQL $ myRow `rowLtAll` values_ myRow
1216+-- ROW(1, FALSE) ALL < (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1217+rowLtAll
1218+ :: SListI row
1219+ => NP (Aliased (Expression db params grp from)) row -- ^ row constructor
1220+ -> Query db params row -- ^ subquery
1221+ -> Expression db params grp from (nullity 'PGbool)
1222+rowLtAll = unsafeRowSubqueryExpression "ALL <"
1223+
1224+-- | >>> printSQL $ true `ltAny` values_ (true `as` #foo)
1225+-- TRUE ANY < (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1226+ltAny
1227+ :: Expression db params grp from ty -- ^ expression
1228+ -> Query db params '[alias ::: ty] -- ^ subquery
1229+ -> Expression db params grp from (nullity 'PGbool)
1230+ltAny = unsafeSubqueryExpression "ANY <"
1231+
1232+-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db params grp from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1233+-- >>> printSQL $ myRow `rowLtAll` values_ myRow
1234+-- ROW(1, FALSE) ALL < (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1235+rowLtAny
1236+ :: SListI row
1237+ => NP (Aliased (Expression db params grp from)) row -- ^ row constructor
1238+ -> Query db params row -- ^ subquery
1239+ -> Expression db params grp from (nullity 'PGbool)
1240+rowLtAny = unsafeRowSubqueryExpression "ANY <"
1241+
1242+-- | >>> printSQL $ true `lteAll` values_ (true `as` #foo)
1243+-- TRUE <= ALL (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1244+lteAll
1245+ :: Expression db params grp from ty -- ^ expression
1246+ -> Query db params '[alias ::: ty] -- ^ subquery
1247+ -> Expression db params grp from (nullity 'PGbool)
1248+lteAll = unsafeSubqueryExpression "<= ALL"
1249+
1250+-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db params grp from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1251+-- >>> printSQL $ myRow `rowLteAll` values_ myRow
1252+-- ROW(1, FALSE) <= ALL (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1253+rowLteAll
1254+ :: SListI row
1255+ => NP (Aliased (Expression db params grp from)) row -- ^ row constructor
1256+ -> Query db params row -- ^ subquery
1257+ -> Expression db params grp from (nullity 'PGbool)
1258+rowLteAll = unsafeRowSubqueryExpression "<= ALL"
1259+
1260+-- | >>> printSQL $ true `lteAny` values_ (true `as` #foo)
1261+-- TRUE <= ANY (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1262+lteAny
1263+ :: Expression db params grp from ty -- ^ expression
1264+ -> Query db params '[alias ::: ty] -- ^ subquery
1265+ -> Expression db params grp from (nullity 'PGbool)
1266+lteAny = unsafeSubqueryExpression "<= ANY"
1267+
1268+-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db params grp from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1269+-- >>> printSQL $ myRow `rowLteAny` values_ myRow
1270+-- ROW(1, FALSE) <= ANY (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1271+rowLteAny
1272+ :: SListI row
1273+ => NP (Aliased (Expression db params grp from)) row -- ^ row constructor
1274+ -> Query db params row -- ^ subquery
1275+ -> Expression db params grp from (nullity 'PGbool)
1276+rowLteAny = unsafeRowSubqueryExpression "<= ANY"
1277+
1278+-- | >>> printSQL $ true `gtAll` values_ (true `as` #foo)
1279+-- TRUE > ALL (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1280+gtAll
1281+ :: Expression db params grp from ty -- ^ expression
1282+ -> Query db params '[alias ::: ty] -- ^ subquery
1283+ -> Expression db params grp from (nullity 'PGbool)
1284+gtAll = unsafeSubqueryExpression "> ALL"
1285+
1286+-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db params grp from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1287+-- >>> printSQL $ myRow `rowGtAll` values_ myRow
1288+-- ROW(1, FALSE) > ALL (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1289+rowGtAll
1290+ :: SListI row
1291+ => NP (Aliased (Expression db params grp from)) row -- ^ row constructor
1292+ -> Query db params row -- ^ subquery
1293+ -> Expression db params grp from (nullity 'PGbool)
1294+rowGtAll = unsafeRowSubqueryExpression "> ALL"
1295+
1296+-- | >>> printSQL $ true `gtAny` values_ (true `as` #foo)
1297+-- TRUE > ANY (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1298+gtAny
1299+ :: Expression db params grp from ty -- ^ expression
1300+ -> Query db params '[alias ::: ty] -- ^ subquery
1301+ -> Expression db params grp from (nullity 'PGbool)
1302+gtAny = unsafeSubqueryExpression "> ANY"
1303+
1304+-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db params grp from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1305+-- >>> printSQL $ myRow `rowGtAny` values_ myRow
1306+-- ROW(1, FALSE) > ANY (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1307+rowGtAny
1308+ :: SListI row
1309+ => NP (Aliased (Expression db params grp from)) row -- ^ row constructor
1310+ -> Query db params row -- ^ subquery
1311+ -> Expression db params grp from (nullity 'PGbool)
1312+rowGtAny = unsafeRowSubqueryExpression "> ANY"
1313+
1314+-- | >>> printSQL $ true `gteAll` values_ (true `as` #foo)
1315+-- TRUE >= ALL (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1316+gteAll
1317+ :: Expression db params grp from ty -- ^ expression
1318+ -> Query db params '[alias ::: ty] -- ^ subquery
1319+ -> Expression db params grp from (nullity 'PGbool)
1320+gteAll = unsafeSubqueryExpression ">= ALL"
1321+
1322+-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db params grp from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1323+-- >>> printSQL $ myRow `rowGteAll` values_ myRow
1324+-- ROW(1, FALSE) >= ALL (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1325+rowGteAll
1326+ :: SListI row
1327+ => NP (Aliased (Expression db params grp from)) row -- ^ row constructor
1328+ -> Query db params row -- ^ subquery
1329+ -> Expression db params grp from (nullity 'PGbool)
1330+rowGteAll = unsafeRowSubqueryExpression ">= ALL"
1331+
1332+-- | >>> printSQL $ true `gteAny` values_ (true `as` #foo)
1333+-- TRUE >= ANY (SELECT * FROM (VALUES (TRUE)) AS t ("foo"))
1334+gteAny
1335+ :: Expression db params grp from ty -- ^ expression
1336+ -> Query db params '[alias ::: ty] -- ^ subquery
1337+ -> Expression db params grp from (nullity 'PGbool)
1338+gteAny = unsafeSubqueryExpression ">= ANY"
1339+
1340+-- | >>> let myRow = 1 `as` #foo :* false `as` #bar :: NP (Aliased (Expression db params grp from)) '["foo" ::: 'NotNull 'PGint2, "bar" ::: 'NotNull 'PGbool]
1341+-- >>> printSQL $ myRow `rowGteAny` values_ myRow
1342+-- ROW(1, FALSE) >= ANY (SELECT * FROM (VALUES (1, FALSE)) AS t ("foo", "bar"))
1343+rowGteAny
1344+ :: SListI row
1345+ => NP (Aliased (Expression db params grp from)) row -- ^ row constructor
1346+ -> Query db params row -- ^ subquery
1347+ -> Expression db params grp from (nullity 'PGbool)
1348+rowGteAny = unsafeRowSubqueryExpression ">= ANY"
10301349
10311350-- | A `CommonTableExpression` is an auxiliary statement in a `with` clause.
10321351data CommonTableExpression statement
1033− (schemas :: SchemasType)
10341352 (params :: [NullityType])
1035− (commons0 :: FromType)
1036− (commons1 :: FromType) where
1353+ (db0 :: DBType)
1354+ (db1 :: DBType) where
10371355 CommonTableExpression
1038− :: Aliased (statement commons schemas params) (cte ::: common)
1039− -> CommonTableExpression statement schemas params commons (cte ::: common ': commons)
1356+ :: Aliased (statement (commons :=> schemas) params) (cte ::: common)
1357+ -> CommonTableExpression statement params
1358+ (commons :=> schemas) ((cte ::: common ': commons) :=> schemas)
10401359instance
10411360 ( KnownSymbol cte
1042− , commons1 ~ (cte ::: common ': commons)
1361+ , db0 ~ (commons :=> schemas)
1362+ , db1 ~ ((cte ::: common ': commons) :=> schemas)
10431363 ) => Aliasable cte
1044− (statement commons schemas params common)
1045− (CommonTableExpression statement schemas params commons commons1) where
1364+ (statement db0 params common)
1365+ (CommonTableExpression statement params db0 db1) where
10461366 statement `as` cte = CommonTableExpression (statement `as` cte)
10471367instance
10481368 ( KnownSymbol cte
1049− , commons1 ~ (cte ::: common ': commons)
1369+ , db0 ~ (commons :=> schemas)
1370+ , db1 ~ ((cte ::: common ': commons) :=> schemas)
10501371 ) => Aliasable cte
1051− (statement commons schemas params common)
1052− (Path (CommonTableExpression statement schemas params) commons commons1) where
1053− statement `as` cte = csingleton (statement `as` cte)
1054−
1055−instance (forall c s p r. RenderSQL (statement c s p r)) => RenderSQL
1056− (CommonTableExpression statement schemas params commons0 commons1) where
1057− renderSQL (CommonTableExpression (statement `As` cte)) =
1058− renderSQL cte <+> "AS" <+> parenthesized (renderSQL statement)
1372+ (statement db0 params common)
1373+ (AlignedList (CommonTableExpression statement params) db0 db1) where
1374+ statement `as` cte = single (statement `as` cte)
1375+
1376+-- | render a `CommonTableExpression`.
1377+renderCommonTableExpression
1378+ :: (forall db ps row. statement db ps row -> ByteString) -- ^ render statement
1379+ -> CommonTableExpression statement params db0 db1 -> ByteString
1380+renderCommonTableExpression renderStatement
1381+ (CommonTableExpression (statement `As` alias)) =
1382+ renderSQL alias <+> "AS" <+> parenthesized (renderStatement statement)
1383+
1384+-- | render a non-empty `AlignedList` of `CommonTableExpression`s.
1385+renderCommonTableExpressions
1386+ :: (forall db ps row. statement db ps row -> ByteString) -- ^ render statement
1387+ -> CommonTableExpression statement params db0 db1
1388+ -> AlignedList (CommonTableExpression statement params) db1 db2
1389+ -> ByteString
1390+renderCommonTableExpressions renderStatement cte ctes =
1391+ renderCommonTableExpression renderStatement cte <> case ctes of
1392+ Done -> ""
1393+ cte' :>> ctes' -> "," <+>
1394+ renderCommonTableExpressions renderStatement cte' ctes'
10591395
10601396-- | `with` provides a way to write auxiliary statements for use in a larger query.
10611397-- These statements, referred to as `CommonTableExpression`s, can be thought of as
10621398-- defining temporary tables that exist just for one query.
10631399class With statement where
10641400 with
1065− :: Path (CommonTableExpression statement schemas params) commons0 commons1
1401+ :: AlignedList (CommonTableExpression statement params) db0 db1
10661402 -- ^ common table expressions
1067− -> statement commons1 schemas params row
1403+ -> statement db1 params row
10681404 -- ^ larger query
1069− -> statement commons0 schemas params row
1070−instance With (Query outer) where
1405+ -> statement db0 params row
1406+instance With Query where
10711407 with Done query = query
1072− with ctes query = UnsafeQuery $
1073− "WITH" <+> commaSeparated (ctoList renderSQL ctes) <+> renderSQL query
1074−
1075−{- |
1076−>>> import Data.Monoid (Sum (..))
1077−>>> import Data.Int (Int64)
1078−>>> :{
1079− let
1080− query :: Query_ schema () (Sum Int64)
1081− query = withRecursive
1082− ( values_ ((1 & astype int) `as` #n)
1083− `unionAll`
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))
1087− in printSQL query
1088−:}
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"
1090−-}
1091−withRecursive
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
1408+ with (cte :>> ctes) query = UnsafeQuery $
1409+ "WITH" <+> renderCommonTableExpressions renderQuery cte ctes
1410+ <+> renderQuery query