@@ -1,7 +1,7 @@
11{-|
22Module: Squeal.PostgreSQL.Query
33Description: Squeal queries
4−Copyright: (c) Eitan Chatav, 2017
4+Copyright: (c) Eitan Chatav, 2019
55Maintainer: eitan@morphism.tech
66Stability: experimental
77
@@ -9,74 +9,81 @@ Squeal queries.
99-}
1010
1111{-# LANGUAGE
12− DeriveGeneric
12+ ConstraintKinds
13+ , DeriveGeneric
1314 , FlexibleContexts
1415 , FlexibleInstances
1516 , GADTs
1617 , GeneralizedNewtypeDeriving
1718 , LambdaCase
1819 , MultiParamTypeClasses
20+ , OverloadedLabels
1921 , OverloadedStrings
22+ , QuantifiedConstraints
23+ , ScopedTypeVariables
2024 , StandaloneDeriving
25+ , TypeApplications
2126 , TypeFamilies
2227 , TypeInType
2328 , TypeOperators
29+ , RankNTypes
2430 , UndecidableInstances
25−#-}
31+ #-}
2632
2733module Squeal.PostgreSQL.Query
2834 ( -- * Queries
29− Query (UnsafeQuery, renderQuery)
35+ Query_
36+ , Query (..)
37+ -- ** Select
38+ , select
39+ , select_
40+ , selectDistinct
41+ , selectDistinct_
42+ , selectDistinctOn
43+ , selectDistinctOn_
44+ , Selection (..)
45+ -- ** Values
46+ , values
47+ , values_
48+ -- ** Set Operations
3049 , union
3150 , unionAll
3251 , intersect
3352 , intersectAll
3453 , except
3554 , exceptAll
36− -- * Select
37− , select
38− , selectDistinct
39− , selectStar
40− , selectDistinctStar
41− , selectDotStar
42− , selectDistinctDotStar
43− , values
44− , values_
55+ -- ** With
56+ , With (..)
57+ , CommonTableExpression (..)
58+ , withRecursive
4559 -- * Table Expressions
4660 , TableExpression (..)
47− , renderTableExpression
4861 , from
4962 , where_
5063 , groupBy
5164 , having
52− , orderBy
5365 , limit
5466 , offset
55− -- * From
67+ -- * From Clauses
5668 , FromClause (..)
5769 , table
5870 , subquery
5971 , view
72+ , common
6073 , crossJoin
6174 , innerJoin
6275 , leftOuterJoin
6376 , rightOuterJoin
6477 , fullOuterJoin
6578 -- * Grouping
66− , By (By1, By2)
67− , renderBy
68− , GroupByClause (NoGroups, Group)
69− , renderGroupByClause
70− , HavingClause (NoHaving, Having)
71− , renderHavingClause
72− -- * Sorting
73− , SortExpression (..)
74− , renderSortExpression
79+ , By (..)
80+ , GroupByClause (..)
81+ , HavingClause (..)
7582 ) where
7683
7784import Control.DeepSeq
7885import Data.ByteString (ByteString)
79−import Data.Monoid hiding (All)
86+import Data.Kind (Type)
8087import Data.String
8188import Data.Word
8289import Generics.SOP hiding (from)
@@ -84,25 +91,76 @@ import GHC.TypeLits
8491
8592import qualified GHC.Generics as GHC
8693
94+import Squeal.PostgreSQL.Alias
8795import 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
88101import Squeal.PostgreSQL.Render
89102import Squeal.PostgreSQL.Schema
90103
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+
91111{- |
92−The process of retrieving or the command to retrieve data from a database
93−is called a `Query`. The `select`, `selectStar`, `selectDotStar`,
94−`selectDistinct`, `selectDistinctStar` and `selectDistinctDotStar` commands
95−are used to specify queries.
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+:}
96155
97156simple query:
98157
158+>>> type Columns = '["col1" ::: 'NoDef :=> 'NotNull 'PGint4, "col2" ::: 'NoDef :=> 'NotNull 'PGint4]
159+>>> type Schema = '["tab" ::: 'Table ('[] :=> Columns)]
99160>>> :{
100161let
101− query :: Query
102− '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'Null 'PGint4])]
103− '[]
104− '["col" ::: 'Null 'PGint4]
105− query = selectStar (from (table #tab))
162+ query :: Query_ (Public Schema) () (Row Int32 Int32)
163+ query = select Star (from (table #tab))
106164in printSQL query
107165:}
108166SELECT * FROM "tab" AS "tab"
@@ -111,34 +169,22 @@ restricted query:
111169
112170>>> :{
113171let
114− query :: Query
115− '[ "tab" ::: 'Table ('[] :=>
116− '[ "col1" ::: 'NoDef :=> 'NotNull 'PGint4
117− , "col2" ::: 'NoDef :=> 'NotNull 'PGint4 ])]
118− '[]
119− '[ "sum" ::: 'NotNull 'PGint4
120− , "col1" ::: 'NotNull 'PGint4 ]
172+ query :: Query_ (Public Schema) () (Row Int32 Int32)
121173 query =
122− select
123− ((#col1 + #col2) `as` #sum :* #col1)
174+ select_ ((#col1 + #col2) `as` #col1 :* #col1 `as` #col2)
124175 ( from (table #tab)
125176 & where_ (#col1 .> #col2)
126177 & where_ (#col2 .> 0) )
127178in printSQL query
128179:}
129−SELECT ("col1" + "col2") AS "sum", "col1" AS "col1" FROM "tab" AS "tab" WHERE (("col1" > "col2") AND ("col2" > 0))
180+SELECT ("col1" + "col2") AS "col1", "col1" AS "col2" FROM "tab" AS "tab" WHERE (("col1" > "col2") AND ("col2" > 0))
130181
131182subquery:
132183
133184>>> :{
134185let
135− query :: Query
136− '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'Null 'PGint4])]
137− '[]
138− '["col" ::: 'Null 'PGint4]
139− query =
140− selectStar
141− (from (subquery (selectStar (from (table #tab)) `as` #sub)))
186+ query :: Query_ (Public Schema) () (Row Int32 Int32)
187+ query = select Star (from (subquery (select Star (from (table #tab)) `as` #sub)))
142188in printSQL query
143189:}
144190SELECT * FROM (SELECT * FROM "tab" AS "tab") AS "sub"
@@ -147,12 +193,8 @@ limits and offsets:
147193
148194>>> :{
149195let
150− query :: Query
151− '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'Null 'PGint4])]
152− '[]
153− '["col" ::: 'Null 'PGint4]
154− query = selectStar
155− (from (table #tab) & limit 100 & offset 2 & limit 50 & offset 2)
196+ query :: Query_ (Public Schema) () (Row Int32 Int32)
197+ query = select Star (from (table #tab) & limit 100 & offset 2 & limit 50 & offset 2)
156198in printSQL query
157199:}
158200SELECT * FROM "tab" AS "tab" LIMIT 50 OFFSET 4
@@ -161,85 +203,80 @@ parameterized query:
161203
162204>>> :{
163205let
164− query :: Query
165− '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'NotNull 'PGfloat8])]
166− '[ 'NotNull 'PGfloat8]
167− '["col" ::: 'NotNull 'PGfloat8]
168− query = selectStar
169− (from (table #tab) & where_ (#col .> param @1))
206+ query :: Query_ (Public Schema) (Only Int32) (Row Int32 Int32)
207+ query = select Star (from (table #tab) & where_ (#col1 .> param @1))
170208in printSQL query
171209:}
172−SELECT * FROM "tab" AS "tab" WHERE ("col" > ($1 :: float8))
210+SELECT * FROM "tab" AS "tab" WHERE ("col1" > ($1 :: int4))
173211
174212aggregation query:
175213
176214>>> :{
177215let
178− query :: Query
179− '[ "tab" ::: 'Table ('[] :=>
180− '[ "col1" ::: 'NoDef :=> 'NotNull 'PGint4
181− , "col2" ::: 'NoDef :=> 'NotNull 'PGint4 ])]
182− '[]
183− '[ "sum" ::: 'NotNull 'PGint4
184− , "col1" ::: 'NotNull 'PGint4 ]
216+ query :: Query_ (Public Schema) () (Row Int64 Int32)
185217 query =
186− select (sum_ #col2 `as` #sum :* #col1)
218+ select_ ((fromNull 0 (sum_ (All #col2))) `as` #col1 :* #col1 `as` #col2)
187219 ( from (table (#tab `as` #table1))
188220 & groupBy #col1
189− & having (#col1 + sum_ #col2 .> 1) )
221+ & having (sum_ (Distinct #col2) .> 1) )
190222in printSQL query
191223:}
192−SELECT sum("col2") AS "sum", "col1" AS "col1" FROM "tab" AS "table1" GROUP BY "col1" HAVING (("col1" + sum("col2")) > 1)
224+SELECT COALESCE(sum(ALL "col2"), 0) AS "col1", "col1" AS "col2" FROM "tab" AS "table1" GROUP BY "col1" HAVING (sum(DISTINCT "col2") > 1)
193225
194226sorted query:
195227
196228>>> :{
197229let
198− query :: Query
199− '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'Null 'PGint4])]
200− '[]
201− '["col" ::: 'Null 'PGint4]
202− query = selectStar
203− (from (table #tab) & orderBy [#col & AscNullsFirst])
230+ query :: Query_ (Public Schema) () (Row Int32 Int32)
231+ query = select Star (from (table #tab) & orderBy [#col1 & Asc])
204232in printSQL query
205233:}
206−SELECT * FROM "tab" AS "tab" ORDER BY "col" ASC NULLS FIRST
234+SELECT * FROM "tab" AS "tab" ORDER BY "col1" ASC
207235
208236joins:
209237
210−>>> :set -XFlexibleContexts
238+>>> :{
239+type OrdersColumns =
240+ '[ "id" ::: 'NoDef :=> 'NotNull 'PGint4
241+ , "price" ::: 'NoDef :=> 'NotNull 'PGfloat4
242+ , "customer_id" ::: 'NoDef :=> 'NotNull 'PGint4
243+ , "shipper_id" ::: 'NoDef :=> 'NotNull 'PGint4 ]
244+:}
245+
246+>>> :{
247+type OrdersConstraints =
248+ '["pk_orders" ::: PrimaryKey '["id"]
249+ ,"fk_customers" ::: ForeignKey '["customer_id"] "customers" '["id"]
250+ ,"fk_shippers" ::: ForeignKey '["shipper_id"] "shippers" '["id"] ]
251+:}
252+
253+>>> type NamesColumns = '["id" ::: 'NoDef :=> 'NotNull 'PGint4, "name" ::: 'NoDef :=> 'NotNull 'PGtext]
254+>>> type CustomersConstraints = '["pk_customers" ::: PrimaryKey '["id"]]
255+>>> type ShippersConstraints = '["pk_shippers" ::: PrimaryKey '["id"]]
256+>>> :{
257+type OrdersSchema =
258+ '[ "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
271+:}
272+
211273>>> :{
212274let
213− query :: Query
214− '[ "orders" ::: 'Table (
215− '["pk_orders" ::: PrimaryKey '["id"]
216− ,"fk_customers" ::: ForeignKey '["customer_id"] "customers" '["id"]
217− ,"fk_shippers" ::: ForeignKey '["shipper_id"] "shippers" '["id"]] :=>
218− '[ "id" ::: 'NoDef :=> 'NotNull 'PGint4
219− , "price" ::: 'NoDef :=> 'NotNull 'PGfloat4
220− , "customer_id" ::: 'NoDef :=> 'NotNull 'PGint4
221− , "shipper_id" ::: 'NoDef :=> 'NotNull 'PGint4
222− ])
223− , "customers" ::: 'Table (
224− '["pk_customers" ::: PrimaryKey '["id"]] :=>
225− '[ "id" ::: 'NoDef :=> 'NotNull 'PGint4
226− , "name" ::: 'NoDef :=> 'NotNull 'PGtext
227− ])
228− , "shippers" ::: 'Table (
229− '["pk_shippers" ::: PrimaryKey '["id"]] :=>
230− '[ "id" ::: 'NoDef :=> 'NotNull 'PGint4
231− , "name" ::: 'NoDef :=> 'NotNull 'PGtext
232− ])
233− ]
234− '[]
235− '[ "order_price" ::: 'NotNull 'PGfloat4
236− , "customer_name" ::: 'NotNull 'PGtext
237− , "shipper_name" ::: 'NotNull 'PGtext
238− ]
239− query = select
240− ( #o ! #price `as` #order_price :*
241− #c ! #name `as` #customer_name :*
242− #s ! #name `as` #shipper_name )
275+ query :: Query_ (Public OrdersSchema) () Order
276+ query = select_
277+ ( #o ! #price `as` #price :*
278+ #c ! #name `as` #customerName :*
279+ #s ! #name `as` #shipperName )
243280 ( from (table (#orders `as` #o)
244281 & innerJoin (table (#customers `as` #c))
245282 (#o ! #customer_id .== #c ! #id)
@@ -247,190 +284,345 @@ let
247284 (#o ! #shipper_id .== #s ! #id)) )
248285in printSQL query
249286:}
250−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")
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")
251288
252289self-join:
253290
254291>>> :{
255292let
256− query :: Query
257− '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'Null 'PGint4])]
258− '[]
259− '["col" ::: 'Null 'PGint4]
260− query = selectDotStar #t1
293+ query :: Query_ (Public Schema) () (Row Int32 Int32)
294+ query = select
295+ (#t1 & DotStar)
261296 (from (table (#tab `as` #t1) & crossJoin (table (#tab `as` #t2))))
262297in printSQL query
263298:}
264299SELECT "t1".* FROM "tab" AS "t1" CROSS JOIN "tab" AS "t2"
265300
301+value queries:
302+
303+>>> :{
304+let
305+ query :: Query_ schemas () (Row String Bool)
306+ query = values
307+ ("true" `as` #col1 :* true `as` #col2)
308+ ["false" `as` #col1 :* false `as` #col2]
309+in printSQL query
310+:}
311+SELECT * FROM (VALUES (E'true', TRUE), (E'false', FALSE)) AS t ("col1", "col2")
312+
266313set operations:
267314
268315>>> :{
269316let
270− query :: Query
271− '["tab" ::: 'Table ('[] :=> '["col" ::: 'NoDef :=> 'Null 'PGint4])]
272− '[]
273− '["col" ::: 'Null 'PGint4]
274− query =
275− selectStar (from (table #tab))
276− `unionAll`
277− selectStar (from (table #tab))
317+ query :: Query_ (Public Schema) () (Row Int32 Int32)
318+ query = select Star (from (table #tab)) `unionAll` select Star (from (table #tab))
278319in printSQL query
279320:}
280321(SELECT * FROM "tab" AS "tab") UNION ALL (SELECT * FROM "tab" AS "tab")
322+
323+with queries:
324+
325+>>> :{
326+let
327+ query :: Query_ (Public Schema) () (Row Int32 Int32)
328+ query = with (
329+ select Star (from (table #tab)) `as` #cte1 :>>
330+ select Star (from (common #cte1)) `as` #cte2
331+ ) (select Star (from (common #cte2)))
332+in printSQL query
333+:}
334+WITH "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+
281362-}
282−newtype Query
283− (schema :: SchemaType)
284− (params :: [NullityType])
285− (columns :: RelationType)
286− = UnsafeQuery { renderQuery :: ByteString }
287− deriving (GHC.Generic,Show,Eq,Ord,NFData)
288−instance RenderSQL (Query schema params columns) where renderSQL = renderQuery
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)
289369
290370-- | The results of two queries can be combined using the set operation
291371-- `union`. Duplicate rows are eliminated.
292372union
293− :: Query schema params columns
294− -> Query schema params columns
295− -> Query schema params columns
373+ :: Query outer commons schemas params columns
374+ -> Query outer commons schemas params columns
375+ -> Query outer commons schemas params columns
296376q1 `union` q2 = UnsafeQuery $
297− parenthesized (renderQuery q1)
377+ parenthesized (renderSQL q1)
298378 <+> "UNION"
299− <+> parenthesized (renderQuery q2)
379+ <+> parenthesized (renderSQL q2)
300380
301381-- | The results of two queries can be combined using the set operation
302382-- `unionAll`, the disjoint union. Duplicate rows are retained.
303383unionAll
304− :: Query schema params columns
305− -> Query schema params columns
306− -> Query schema params columns
384+ :: Query outer commons schemas params columns
385+ -> Query outer commons schemas params columns
386+ -> Query outer commons schemas params columns
307387q1 `unionAll` q2 = UnsafeQuery $
308− parenthesized (renderQuery q1)
388+ parenthesized (renderSQL q1)
309389 <+> "UNION" <+> "ALL"
310− <+> parenthesized (renderQuery q2)
390+ <+> parenthesized (renderSQL q2)
311391
312392-- | The results of two queries can be combined using the set operation
313393-- `intersect`, the intersection. Duplicate rows are eliminated.
314394intersect
315− :: Query schema params columns
316− -> Query schema params columns
317− -> Query schema params columns
395+ :: Query outer commons schemas params columns
396+ -> Query outer commons schemas params columns
397+ -> Query outer commons schemas params columns
318398q1 `intersect` q2 = UnsafeQuery $
319− parenthesized (renderQuery q1)
399+ parenthesized (renderSQL q1)
320400 <+> "INTERSECT"
321− <+> parenthesized (renderQuery q2)
401+ <+> parenthesized (renderSQL q2)
322402
323403-- | The results of two queries can be combined using the set operation
324404-- `intersectAll`, the intersection. Duplicate rows are retained.
325405intersectAll
326− :: Query schema params columns
327− -> Query schema params columns
328− -> Query schema params columns
406+ :: Query outer commons schemas params columns
407+ -> Query outer commons schemas params columns
408+ -> Query outer commons schemas params columns
329409q1 `intersectAll` q2 = UnsafeQuery $
330− parenthesized (renderQuery q1)
410+ parenthesized (renderSQL q1)
331411 <+> "INTERSECT" <+> "ALL"
332− <+> parenthesized (renderQuery q2)
412+ <+> parenthesized (renderSQL q2)
333413
334414-- | The results of two queries can be combined using the set operation
335415-- `except`, the set difference. Duplicate rows are eliminated.
336416except
337− :: Query schema params columns
338− -> Query schema params columns
339− -> Query schema params columns
417+ :: Query outer commons schemas params columns
418+ -> Query outer commons schemas params columns
419+ -> Query outer commons schemas params columns
340420q1 `except` q2 = UnsafeQuery $
341− parenthesized (renderQuery q1)
421+ parenthesized (renderSQL q1)
342422 <+> "EXCEPT"
343− <+> parenthesized (renderQuery q2)
423+ <+> parenthesized (renderSQL q2)
344424
345425-- | The results of two queries can be combined using the set operation
346426-- `exceptAll`, the set difference. Duplicate rows are retained.
347427exceptAll
348− :: Query schema params columns
349− -> Query schema params columns
350− -> Query schema params columns
428+ :: Query outer commons schemas params columns
429+ -> Query outer commons schemas params columns
430+ -> Query outer commons schemas params columns
351431q1 `exceptAll` q2 = UnsafeQuery $
352− parenthesized (renderQuery q1)
432+ parenthesized (renderSQL q1)
353433 <+> "EXCEPT" <+> "ALL"
354− <+> parenthesized (renderQuery q2)
434+ <+> parenthesized (renderSQL q2)
355435
356436{-----------------------------------------
357437SELECT queries
358438-----------------------------------------}
359439
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
447+ Star
448+ :: HasUnique tab from row
449+ => Selection outer commons 'Ungrouped schemas params from row
450+ -- ^ `HasUnique` table in the `FromClause`
451+ DotStar
452+ :: Has tab from row
453+ => 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
467+ 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
474+instance (KnownSymbol col, row ~ '[col ::: ty])
475+ => Aliasable col
476+ (Expression outer commons grp schemas params from ty)
477+ (Selection outer commons grp schemas params from row) where
478+ 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
483+instance
484+ ( Has tab (Join outer from) row0
485+ , Has col row0 ty
486+ , row1 ~ '[col ::: ty]
487+ , 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
495+instance
496+ ( HasUnique tab (Join outer from) row0
497+ , Has col row0 ty
498+ , row1 ~ '[col ::: ty]
499+ , GroupedBy tab col bys )
500+ => IsLabel col
501+ (Selection outer commons ('Grouped bys) schemas params from row1) where
502+ fromLabel = fromLabel @col `as` Alias
503+
504+instance RenderSQL (Selection outer commons grp schemas params from row) where
505+ renderSQL = \case
506+ List list -> renderCommaSeparated (renderAliased renderSQL) list
507+ Star -> "*"
508+ DotStar tab -> renderSQL tab <> ".*"
509+ 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
524+
360525-- | the `TableExpression` in the `select` command constructs an intermediate
361526-- virtual table by possibly combining tables, views, eliminating rows,
362527-- grouping, etc. This table is finally passed on to processing by
363−-- the select list. The select list determines which columns of
528+-- the select list. The `Selection` determines which columns of
364529-- the intermediate table are actually output.
365530select
366− :: SListI columns
367− => NP (Aliased (Expression schema relations grouping params)) (column ': columns)
368− -- ^ select list
369− -> TableExpression schema params relations grouping
531+ :: (SListI row, row ~ (x ': xs))
532+ => Selection outer commons grp schemas params from row
533+ -- ^ selection
534+ -> TableExpression outer commons grp schemas params from
370535 -- ^ intermediate virtual table
371− -> Query schema params (column ': columns)
372−select list rels = UnsafeQuery $
536+ -> Query outer commons schemas params row
537+select selection tabexpr = UnsafeQuery $
373538 "SELECT"
374− <+> renderCommaSeparated (renderAliasedAs renderExpression) list
375− <+> renderTableExpression rels
539+ <+> renderSQL selection
540+ <+> renderSQL tabexpr
541+
542+-- | Like `select` but takes an `NP` list of `Expression`s instead
543+-- of a general `Selection`.
544+select_
545+ :: (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
376552
377553-- | After the select list has been processed, the result table can
378554-- be subject to the elimination of duplicate rows using `selectDistinct`.
379555selectDistinct
380− :: SListI columns
381− => NP (Aliased (Expression schema relations 'Ungrouped params)) (column ': columns)
382− -- ^ select list
383− -> TableExpression schema params relations 'Ungrouped
556+ :: (SListI columns, columns ~ (col ': cols))
557+ => Selection outer commons grp schemas params from columns
558+ -- ^ selection
559+ -> TableExpression outer commons grp schemas params from
384560 -- ^ intermediate virtual table
385− -> Query schema params (column ': columns)
386−selectDistinct list rels = UnsafeQuery $
561+ -> Query outer commons schemas params columns
562+selectDistinct selection tabexpr = UnsafeQuery $
387563 "SELECT DISTINCT"
388− <+> renderCommaSeparated (renderAliasedAs renderExpression) list
389− <+> renderTableExpression rels
390−
391−-- | The simplest kind of query is `selectStar` which emits all columns
392−-- that the table expression produces.
393−selectStar
394− :: HasUnique relation relations columns
395− => TableExpression schema params relations 'Ungrouped
396− -- ^ intermediate virtual table
397− -> Query schema params columns
398−selectStar rels = UnsafeQuery $ "SELECT" <+> "*" <+> renderTableExpression rels
399−
400−-- | A `selectDistinctStar` emits all columns that the table expression
401−-- produces and eliminates duplicate rows.
402−selectDistinctStar
403− :: HasUnique relation relations columns
404− => TableExpression schema params relations 'Ungrouped
564+ <+> renderSQL selection
565+ <+> renderSQL tabexpr
566+
567+-- | Like `selectDistinct` but takes an `NP` list of `Expression`s instead
568+-- of a general `Selection`.
569+selectDistinct_
570+ :: (SListI columns, columns ~ (col ': cols))
571+ => NP (Aliased (Expression outer commons grp schemas params from)) columns
572+ -- ^ select list
573+ -> TableExpression outer commons grp schemas params from
405574 -- ^ intermediate virtual table
406− -> Query schema params columns
407−selectDistinctStar rels = UnsafeQuery $
408− "SELECT DISTINCT" <+> "*" <+> renderTableExpression rels
409−
410−-- | When working with multiple tables, it can also be useful to ask
411−-- for all the columns of a particular table, using `selectDotStar`.
412−selectDotStar
413− :: Has relation relations columns
414− => Alias relation
415− -- ^ particular virtual subtable
416− -> TableExpression schema params relations 'Ungrouped
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
417598 -- ^ intermediate virtual table
418− -> Query schema params columns
419−selectDotStar rel relations = UnsafeQuery $
420− "SELECT" <+> renderAlias rel <> ".*" <+> renderTableExpression relations
421−
422−-- | A `selectDistinctDotStar` asks for all the columns of a particular table,
423−-- and eliminates duplicate rows.
424−selectDistinctDotStar
425− :: Has relation relations columns
426− => Alias relation
427− -- ^ particular virtual table
428− -> TableExpression schema params relations 'Ungrouped
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
429623 -- ^ intermediate virtual table
430− -> Query schema params columns
431−selectDistinctDotStar rel relations = UnsafeQuery $
432− "SELECT DISTINCT" <+> renderAlias rel <> ".*"
433− <+> renderTableExpression relations
624+ -> Query outer commons schemas params columns
625+selectDistinctOn_ distincts = selectDistinctOn distincts . List
434626
435627-- | `values` computes a row value or set of row values
436628-- specified by value expressions. It is most commonly used
@@ -438,16 +630,16 @@ selectDistinctDotStar rel relations = UnsafeQuery $
438630-- but it can be used on its own.
439631--
440632-- >>> type Row = '["a" ::: 'NotNull 'PGint4, "b" ::: 'NotNull 'PGtext]
441−-- >>> let query = values (1 `as` #a :* "one" `as` #b) [] :: Query '[] '[] Row
633+-- >>> let query = values (1 `as` #a :* "one" `as` #b) [] :: Query outer commons schemas '[] Row
442634-- >>> printSQL query
443635-- SELECT * FROM (VALUES (1, E'one')) AS t ("a", "b")
444636values
445637 :: SListI cols
446− => NP (Aliased (Expression schema '[] 'Ungrouped params)) cols
447− -> [NP (Aliased (Expression schema '[] 'Ungrouped params)) cols]
638+ => NP (Aliased (Expression outer commons 'Ungrouped schemas params '[] )) cols
639+ -> [NP (Aliased (Expression outer commons 'Ungrouped schemas params '[] )) cols]
448640 -- ^ When more than one row is specified, all the rows must
449641 -- must have the same number of elements
450− -> Query schema params cols
642+ -> Query outer commons schemas params cols
451643values rw rws = UnsafeQuery $ "SELECT * FROM"
452644 <+> parenthesized (
453645 "VALUES"
@@ -458,17 +650,17 @@ values rw rws = UnsafeQuery $ "SELECT * FROM"
458650 <+> parenthesized (renderCommaSeparated renderAliasPart rw)
459651 where
460652 renderAliasPart, renderValuePart
461− :: Aliased (Expression schema '[] 'Ungrouped params) ty -> ByteString
462− renderAliasPart (_ `As` name) = renderAlias name
463− renderValuePart (value `As` _) = renderExpression value
653+ :: Aliased (Expression outer commons 'Ungrouped schemas params '[] ) ty -> ByteString
654+ renderAliasPart (_ `As` name) = renderSQL name
655+ renderValuePart (value `As` _) = renderSQL value
464656
465657-- | `values_` computes a row value or set of row values
466658-- specified by value expressions.
467659values_
468660 :: SListI cols
469− => NP (Aliased (Expression schema '[] 'Ungrouped params)) cols
661+ => NP (Aliased (Expression outer commons 'Ungrouped schemas params '[] )) cols
470662 -- ^ one row of values
471− -> Query schema params cols
663+ -> Query outer commons schemas params cols
472664values_ rw = values rw []
473665
474666{-----------------------------------------
@@ -482,15 +674,17 @@ Table Expressions
482674-- to a table on disk, a so-called base table, but more complex expressions
483675-- can be used to modify or combine base tables in various ways.
484676data TableExpression
485− (schema :: SchemaType)
677+ (outer :: FromType)
678+ (commons :: FromType)
679+ (grp :: Grouping)
680+ (schemas :: SchemasType)
486681 (params :: [NullityType])
487− (relations :: RelationsType)
488− (grouping :: Grouping)
682+ (from :: FromType)
489683 = TableExpression
490− { fromClause :: FromClause schema params relations
684+ { fromClause :: FromClause outer commons schemas params from
491685 -- ^ A table reference that can be a table name, or a derived table such
492686 -- as a subquery, a @JOIN@ construct, or complex combinations of these.
493− , whereClause :: [Condition schema relations 'Ungrouped params]
687+ , whereClause :: [Condition outer commons 'Ungrouped schemas params from]
494688 -- ^ optional search coditions, combined with `.&&`. After the processing
495689 -- of the `fromClause` is done, each row of the derived virtual table
496690 -- is checked against the search condition. If the result of the
@@ -499,20 +693,20 @@ data TableExpression
499693 -- at least one column of the table generated in the `fromClause`;
500694 -- this is not required, but otherwise the WHERE clause will
501695 -- be fairly useless.
502− , groupByClause :: GroupByClause relations grouping
696+ , groupByClause :: GroupByClause grp from
503697 -- ^ The `groupByClause` is used to group together those rows in a table
504698 -- that have the same values in all the columns listed. The order in which
505699 -- the columns are listed does not matter. The effect is to combine each
506700 -- set of rows having common values into one group row that represents all
507701 -- rows in the group. This is done to eliminate redundancy in the output
508702 -- and/or compute aggregates that apply to these groups.
509− , havingClause :: HavingClause schema relations grouping params
703+ , havingClause :: HavingClause outer commons grp schemas params from
510704 -- ^ If a table has been grouped using `groupBy`, but only certain groups
511705 -- are of interest, the `havingClause` can be used, much like a
512706 -- `whereClause`, to eliminate groups from the result. Expressions in the
513707 -- `havingClause` can refer both to grouped expressions and to ungrouped
514708 -- expressions (which necessarily involve an aggregate function).
515− , orderByClause :: [SortExpression schema relations grouping params]
709+ , orderByClause :: [SortExpression outer commons grp schemas params from]
516710 -- ^ The `orderByClause` is for optional sorting. When more than one
517711 -- `SortExpression` is specified, the later (right) values are used to sort
518712 -- rows that are equal according to the earlier (left) values.
@@ -522,72 +716,69 @@ data TableExpression
522716 -- will be returned (but possibly fewer, if the query itself yields
523717 -- fewer rows).
524718 , offsetClause :: [Word64]
525− -- ^ The `offsetClause` is combined with `+` to give an offset count
719+ -- ^ The `offsetClause` is combined with `Prelude.+` to give an offset count
526720 -- if nonempty. The offset count says to skip that many rows before
527721 -- beginning to return rows. The rows are skipped before the limit count
528722 -- is applied.
529− }
723+ } deriving (GHC.Generic)
530724
531725-- | Render a `TableExpression`
532−renderTableExpression
533− :: TableExpression schema params relations grouping
534− -> ByteString
535−renderTableExpression
536− (TableExpression frm' whs' grps' hvs' srts' lims' offs') = mconcat
537− [ "FROM ", renderFromClause frm'
538− , renderWheres whs'
539− , renderGroupByClause grps'
540− , renderHavingClause hvs'
541− , renderOrderByClause srts'
542− , renderLimits lims'
543− , renderOffsets offs'
544− ]
545− where
546− renderWheres = \case
547− [] -> ""
548− wh:[] -> " WHERE" <+> renderExpression wh
549− wh:whs -> " WHERE" <+> renderExpression (foldr (.&&) wh whs)
550− renderOrderByClause = \case
551− [] -> ""
552− srts -> " ORDER BY"
553− <+> commaSeparated (renderSortExpression <$> srts)
554− renderLimits = \case
555− [] -> ""
556− lims -> " LIMIT" <+> fromString (show (minimum lims))
557− renderOffsets = \case
558− [] -> ""
559− offs -> " OFFSET" <+> fromString (show (sum offs))
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))
560751
561752-- | A `from` generates a `TableExpression` from a table reference that can be
562753-- a table name, or a derived table such as a subquery, a JOIN construct,
563754-- or complex combinations of these. A `from` may be transformed by `where_`,
564−-- `group`, `having`, `orderBy`, `limit` and `offset`, using the `&` operator
755+-- `groupBy`, `having`, `orderBy`, `limit` and `offset`, using the `&` operator
565756-- to match the left-to-right sequencing of their placement in SQL.
566757from
567− :: FromClause schema params relations -- ^ table reference
568− -> TableExpression schema params relations 'Ungrouped
569−from rels = TableExpression rels [] NoGroups NoHaving [] [] []
758+ :: FromClause outer commons schemas params from -- ^ table reference
759+ -> TableExpression outer commons 'Ungrouped schemas params from
760+from tab = TableExpression tab [] noGroups NoHaving [] [] []
570761
571762-- | A `where_` is an endomorphism of `TableExpression`s which adds a
572763-- search condition to the `whereClause`.
573764where_
574− :: Condition schema relations 'Ungrouped params -- ^ filtering condition
575− -> TableExpression schema params relations grouping
576− -> TableExpression schema params relations grouping
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
577768where_ wh rels = rels {whereClause = wh : whereClause rels}
578769
579770-- | A `groupBy` is a transformation of `TableExpression`s which switches
580−-- its `Grouping` from `Ungrouped` to `Grouped`. Use @group Nil@ to perform
771+-- its `Grouping` from `Ungrouped` to `Grouped`. Use @groupBy Nil@ to perform
581772-- a "grand total" aggregation query.
582773groupBy
583774 :: SListI bys
584− => NP (By relations) bys -- ^ grouped columns
585− -> TableExpression schema params relations 'Ungrouped
586− -> TableExpression schema params relations ('Grouped bys)
775+ => NP (By from) bys -- ^ grouped columns
776+ -> TableExpression outer commons 'Ungrouped schemas params from
777+ -> TableExpression outer commons ('Grouped bys) schemas params from
587778groupBy bys rels = TableExpression
588779 { fromClause = fromClause rels
589780 , whereClause = whereClause rels
590− , groupByClause = Group bys
781+ , groupByClause = group bys
591782 , havingClause = Having []
592783 , orderByClause = []
593784 , limitClause = limitClause rels
@@ -597,34 +788,29 @@ groupBy bys rels = TableExpression
597788-- | A `having` is an endomorphism of `TableExpression`s which adds a
598789-- search condition to the `havingClause`.
599790having
600− :: Condition schema relations ('Grouped bys) params -- ^ having condition
601− -> TableExpression schema params relations ('Grouped bys)
602− -> TableExpression schema params relations ('Grouped bys)
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
603794having hv rels = rels
604795 { havingClause = case havingClause rels of Having hvs -> Having (hv:hvs) }
605796
606−-- | An `orderBy` is an endomorphism of `TableExpression`s which appends an
607−-- ordering to the right of the `orderByClause`.
608−orderBy
609− :: [SortExpression schema relations grouping params] -- ^ sort expressions
610− -> TableExpression schema params relations grouping
611− -> TableExpression schema params relations grouping
612−orderBy srts rels = rels {orderByClause = orderByClause rels ++ srts}
797+instance OrderBy TableExpression where
798+ orderBy srts rels = rels {orderByClause = orderByClause rels ++ srts}
613799
614800-- | A `limit` is an endomorphism of `TableExpression`s which adds to the
615801-- `limitClause`.
616802limit
617803 :: Word64 -- ^ limit parameter
618− -> TableExpression schema params relations grouping
619− -> TableExpression schema params relations grouping
804+ -> TableExpression outer commons grp schemas params from
805+ -> TableExpression outer commons grp schemas params from
620806limit lim rels = rels {limitClause = lim : limitClause rels}
621807
622808-- | An `offset` is an endomorphism of `TableExpression`s which adds to the
623809-- `offsetClause`.
624810offset
625811 :: Word64 -- ^ offset parameter
626− -> TableExpression schema params relations grouping
627− -> TableExpression schema params relations grouping
812+ -> TableExpression outer commons grp schemas params from
813+ -> TableExpression outer commons grp schemas params from
628814offset off rels = rels {offsetClause = off : offsetClause rels}
629815
630816{-----------------------------------------
@@ -635,61 +821,76 @@ FROM clauses
635821A `FromClause` can be a table name, or a derived table such
636822as a subquery, a @JOIN@ construct, or complex combinations of these.
637823-}
638−newtype FromClause schema params relations
824+newtype FromClause outer commons schemas params from
639825 = UnsafeFromClause { renderFromClause :: ByteString }
640826 deriving (GHC.Generic,Show,Eq,Ord,NFData)
827+instance RenderSQL (FromClause outer commons schemas params from) where
828+ renderSQL = renderFromClause
641829
642−-- | A real `table` is a table from the schema.
830+-- | A real `table` is a table from the database.
643831table
644− :: Has tab schema ('Table table)
645− => Aliased Alias (alias ::: tab)
646− -> FromClause schema params '[alias ::: TableToRelation table]
832+ :: (Has sch schemas schema, Has tab schema ('Table table))
833+ => Aliased (QualifiedAlias sch) (alias ::: tab)
834+ -> FromClause outer commons schemas params '[alias ::: TableToRow table]
647835table (tab `As` alias) = UnsafeFromClause $
648− renderAlias tab <+> "AS" <+> renderAlias alias
836+ renderSQL tab <+> "AS" <+> renderSQL alias
649837
650838-- | `subquery` derives a table from a `Query`.
651839subquery
652− :: Aliased (Query schema params) rel
653− -> FromClause schema params '[rel]
654−subquery = UnsafeFromClause . renderAliasedAs (parenthesized . renderQuery)
840+ :: Aliased (Query outer commons schemas params) query
841+ -> FromClause outer commons schemas params '[query]
842+subquery = UnsafeFromClause . renderAliased (parenthesized . renderSQL)
655843
656844-- | `view` derives a table from a `View`.
657845view
658− :: Has view schema ('View rel)
659− => Aliased Alias (alias ::: view)
660− -> FromClause schema params '[alias ::: rel]
846+ :: (Has sch schemas schema, Has vw schema ('View view))
847+ => Aliased (QualifiedAlias sch) (alias ::: vw)
848+ -> FromClause outer commons schemas params '[alias ::: view]
661849view (vw `As` alias) = UnsafeFromClause $
662− renderAlias vw <+> "AS" <+> renderAlias alias
850+ renderSQL vw <+> "AS" <+> renderSQL alias
851+
852+-- | `common` derives a table from a common table expression.
853+common
854+ :: Has cte commons common
855+ => Aliased Alias (alias ::: cte)
856+ -> FromClause outer commons schemas params '[alias ::: common]
857+common (cte `As` alias) = UnsafeFromClause $
858+ renderSQL cte <+> "AS" <+> renderSQL alias
859+
860+instance Additional (FromClause outer commons schemas params) where
861+ also right left = UnsafeFromClause $
862+ renderSQL left <> ", " <> renderSQL right
663863
664−{- | @left & crossJoin right@. For every possible combination of rows from
665− @left@ and @right@ (i.e., a Cartesian product), the joined table will contain
666− a row consisting of all columns in @left@ followed by all columns in @right@.
667− If the tables have @n@ and @m@ rows respectively, the joined table will
668− have @n * m@ rows.
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.
669870-}
670871crossJoin
671− :: FromClause schema params right
872+ :: FromClause outer commons schemas params right
672873 -- ^ right
673− -> FromClause schema params left
874+ -> FromClause outer commons schemas params left
674875 -- ^ left
675− -> FromClause schema params (Join left right)
876+ -> FromClause outer commons schemas params (Join left right)
676877crossJoin right left = UnsafeFromClause $
677− renderFromClause left <+> "CROSS JOIN" <+> renderFromClause right
878+ renderSQL left <+> "CROSS JOIN" <+> renderSQL right
678879
679880{- | @left & innerJoin right on@. The joined table is filtered by
680881the @on@ condition.
681882-}
682883innerJoin
683− :: FromClause schema params right
884+ :: FromClause outer commons schemas params right
684885 -- ^ right
685− -> Condition schema (Join left right) 'Ungrouped params
886+ -> Condition outer commons 'Ungrouped schemas params (Join left right)
686887 -- ^ @on@ condition
687− -> FromClause schema params left
888+ -> FromClause outer commons schemas params left
688889 -- ^ left
689− -> FromClause schema params (Join left right)
890+ -> FromClause outer commons schemas params (Join left right)
690891innerJoin right on left = UnsafeFromClause $
691− renderFromClause left <+> "INNER JOIN" <+> renderFromClause right
692− <+> "ON" <+> renderExpression on
892+ renderSQL left <+> "INNER JOIN" <+> renderSQL right
893+ <+> "ON" <+> renderSQL on
693894
694895{- | @left & leftOuterJoin right on@. First, an inner join is performed.
695896 Then, for each row in @left@ that does not satisfy the @on@ condition with
@@ -697,16 +898,16 @@ innerJoin right on left = UnsafeFromClause $
697898 Thus, the joined table always has at least one row for each row in @left@.
698899-}
699900leftOuterJoin
700− :: FromClause schema params right
901+ :: FromClause outer commons schemas params right
701902 -- ^ right
702− -> Condition schema (Join left right) 'Ungrouped params
903+ -> Condition outer commons 'Ungrouped schemas params (Join left right)
703904 -- ^ @on@ condition
704− -> FromClause schema params left
905+ -> FromClause outer commons schemas params left
705906 -- ^ left
706− -> FromClause schema params (Join left (NullifyRelations right))
907+ -> FromClause outer commons schemas params (Join left (NullifyFrom right))
707908leftOuterJoin right on left = UnsafeFromClause $
708− renderFromClause left <+> "LEFT OUTER JOIN" <+> renderFromClause right
709− <+> "ON" <+> renderExpression on
909+ renderSQL left <+> "LEFT OUTER JOIN" <+> renderSQL right
910+ <+> "ON" <+> renderSQL on
710911
711912{- | @left & rightOuterJoin right on@. First, an inner join is performed.
712913 Then, for each row in @right@ that does not satisfy the @on@ condition with
@@ -715,16 +916,16 @@ leftOuterJoin right on left = UnsafeFromClause $
715916 have a row for each row in @right@.
716917-}
717918rightOuterJoin
718− :: FromClause schema params right
919+ :: FromClause outer commons schemas params right
719920 -- ^ right
720− -> Condition schema (Join left right) 'Ungrouped params
921+ -> Condition outer commons 'Ungrouped schemas params (Join left right)
721922 -- ^ @on@ condition
722− -> FromClause schema params left
923+ -> FromClause outer commons schemas params left
723924 -- ^ left
724− -> FromClause schema params (Join (NullifyRelations left) right)
925+ -> FromClause outer commons schemas params (Join (NullifyFrom left) right)
725926rightOuterJoin right on left = UnsafeFromClause $
726− renderFromClause left <+> "RIGHT OUTER JOIN" <+> renderFromClause right
727− <+> "ON" <+> renderExpression on
927+ renderSQL left <+> "RIGHT OUTER JOIN" <+> renderSQL right
928+ <+> "ON" <+> renderSQL on
728929
729930{- | @left & fullOuterJoin right on@. First, an inner join is performed.
730931 Then, for each row in @left@ that does not satisfy the @on@ condition with
@@ -734,42 +935,46 @@ rightOuterJoin right on left = UnsafeFromClause $
734935 is added.
735936-}
736937fullOuterJoin
737− :: FromClause schema params right
938+ :: FromClause outer commons schemas params right
738939 -- ^ right
739− -> Condition schema (Join left right) 'Ungrouped params
940+ -> Condition outer commons 'Ungrouped schemas params (Join left right)
740941 -- ^ @on@ condition
741− -> FromClause schema params left
942+ -> FromClause outer commons schemas params left
742943 -- ^ left
743− -> FromClause schema params
744− (Join (NullifyRelations left) (NullifyRelations right))
944+ -> FromClause outer commons schemas params
945+ (Join (NullifyFrom left) (NullifyFrom right))
745946fullOuterJoin right on left = UnsafeFromClause $
746− renderFromClause left <+> "FULL OUTER JOIN" <+> renderFromClause right
747− <+> "ON" <+> renderExpression on
947+ renderSQL left <+> "FULL OUTER JOIN" <+> renderSQL right
948+ <+> "ON" <+> renderSQL on
748949
749950{-----------------------------------------
750951Grouping
751952-----------------------------------------}
752953
753−-- | `By`s are used in `group` to reference a list of columns which are then
954+-- | `By`s are used in `groupBy` to reference a list of columns which are then
754955-- used to group together those rows in a table that have the same values
755956-- in all the columns listed. @By \#col@ will reference an unambiguous
756957-- column @col@; otherwise @By2 (\#tab \! \#col)@ will reference a table
757958-- qualified column @tab.col@.
758959data By
759− (relations :: RelationsType)
960+ (from :: FromType)
760961 (by :: (Symbol,Symbol)) where
761962 By1
762− :: (HasUnique relation relations columns, Has column columns ty)
963+ :: (HasUnique table from columns, Has column columns ty)
763964 => Alias column
764− -> By relations '(relation, column)
965+ -> By from '(table, column)
765966 By2
766− :: (Has relation relations columns, Has column columns ty)
767− => Alias relation
967+ :: (Has table from columns, Has column columns ty)
968+ => Alias table
768969 -> Alias column
769− -> By relations '(relation, column)
770−deriving instance Show (By relations by)
771−deriving instance Eq (By relations by)
772−deriving instance Ord (By relations by)
970+ -> By from '(table, column)
971+deriving instance Show (By from by)
972+deriving instance Eq (By from by)
973+deriving 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
773978
774979instance (HasUnique rel rels cols, Has col cols ty, by ~ '(rel, col))
775980 => IsLabel col (By rels by) where fromLabel = By1 fromLabel
@@ -781,94 +986,113 @@ instance (Has rel rels cols, Has col cols ty, bys ~ '[ '(rel, col)])
781986 => IsQualified rel col (NP (By rels) bys) where
782987 rel ! col = By2 rel col :* Nil
783988
784−-- | Renders a `By`.
785−renderBy :: By relations by -> ByteString
786−renderBy = \case
787− By1 column -> renderAlias column
788− By2 rel column -> renderAlias rel <> "." <> renderAlias column
789−
790989-- | A `GroupByClause` indicates the `Grouping` of a `TableExpression`.
791990-- A `NoGroups` indicates `Ungrouped` while a `Group` indicates `Grouped`.
792991-- @NoGroups@ is distinguised from @Group Nil@ since no aggregation can be
793992-- done on @NoGroups@ while all output `Expression`s must be aggregated
794993-- in @Group Nil@. In general, all output `Expression`s in the
795994-- complement of @bys@ must be aggregated in @Group bys@.
796−data GroupByClause relations grouping where
797− NoGroups :: GroupByClause relations 'Ungrouped
798− Group
799− :: SListI bys
800− => NP (By relations) bys
801− -> GroupByClause relations ('Grouped bys)
802−
803−-- | Renders a `GroupByClause`.
804−renderGroupByClause :: GroupByClause relations grouping -> ByteString
805−renderGroupByClause = \case
806− NoGroups -> ""
807− Group Nil -> ""
808− Group bys -> " GROUP BY" <+> renderCommaSeparated renderBy 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'
8091009
8101010-- | A `HavingClause` is used to eliminate groups that are not of interest.
8111011-- An `Ungrouped` `TableExpression` may only use `NoHaving` while a `Grouped`
8121012-- `TableExpression` must use `Having` whose conditions are combined with
8131013-- `.&&`.
814−data HavingClause schema relations grouping params where
815− NoHaving :: HavingClause schema relations 'Ungrouped params
1014+data HavingClause outer commons grp schemas params from where
1015+ NoHaving :: HavingClause outer commons 'Ungrouped schemas params from
8161016 Having
817− :: [Condition schema relations ('Grouped bys) params]
818− -> HavingClause schema relations ('Grouped bys) params
819−deriving instance Show (HavingClause schema relations grouping params)
820−deriving instance Eq (HavingClause schema relations grouping params)
821−deriving instance Ord (HavingClause schema relations grouping params)
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)
8221022
8231023-- | Render a `HavingClause`.
824−renderHavingClause :: HavingClause schema relations grouping params -> ByteString
825−renderHavingClause = \case
826− NoHaving -> ""
827− Having [] -> ""
828− Having conditions ->
829− " HAVING" <+> commaSeparated (renderExpression <$> conditions)
830−
831−{-----------------------------------------
832−Sorting
833−-----------------------------------------}
1024+instance RenderSQL (HavingClause outer commons grp schemas params from) where
1025+ renderSQL = \case
1026+ NoHaving -> ""
1027+ Having [] -> ""
1028+ Having conditions ->
1029+ " HAVING" <+> commaSeparated (renderSQL <$> conditions)
1030+
1031+-- | A `CommonTableExpression` is an auxiliary statement in a `with` clause.
1032+data CommonTableExpression statement
1033+ (schemas :: SchemasType)
1034+ (params :: [NullityType])
1035+ (commons0 :: FromType)
1036+ (commons1 :: FromType) where
1037+ CommonTableExpression
1038+ :: Aliased (statement commons schemas params) (cte ::: common)
1039+ -> CommonTableExpression statement schemas params commons (cte ::: common ': commons)
1040+instance
1041+ ( KnownSymbol cte
1042+ , commons1 ~ (cte ::: common ': commons)
1043+ ) => Aliasable cte
1044+ (statement commons schemas params common)
1045+ (CommonTableExpression statement schemas params commons commons1) where
1046+ statement `as` cte = CommonTableExpression (statement `as` cte)
1047+instance
1048+ ( KnownSymbol cte
1049+ , commons1 ~ (cte ::: common ': commons)
1050+ ) => 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)
1059+
1060+-- | `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
1062+-- defining temporary tables that exist just for one query.
1063+class With statement where
1064+ with
1065+ :: Path (CommonTableExpression statement schemas params) commons0 commons1
1066+ -- ^ common table expressions
1067+ -> statement commons1 schemas params row
1068+ -- ^ larger query
1069+ -> statement commons0 schemas params row
1070+instance With (Query outer) where
1071+ with Done query = query
1072+ with ctes query = UnsafeQuery $
1073+ "WITH" <+> commaSeparated (ctoList renderSQL ctes) <+> renderSQL query
8341074
835−-- | `SortExpression`s are used by `sortBy` to optionally sort the results
836−-- of a `Query`. `Asc` or `Desc` set the sort direction of a `NotNull` result
837−-- column to ascending or descending. Ascending order puts smaller values
838−-- first, where "smaller" is defined in terms of the `.<` operator. Similarly,
839−-- descending order is determined with the `.>` operator. `AscNullsFirst`,
840−-- `AscNullsLast`, `DescNullsFirst` and `DescNullsLast` options are used to
841−-- determine whether nulls appear before or after non-null values in the sort
842−-- ordering of a `Null` result column.
843−data SortExpression schema relations grouping params where
844− Asc
845− :: Expression schema relations grouping params ('NotNull ty)
846− -> SortExpression schema relations grouping params
847− Desc
848− :: Expression schema relations grouping params ('NotNull ty)
849− -> SortExpression schema relations grouping params
850− AscNullsFirst
851− :: Expression schema relations grouping params ('Null ty)
852− -> SortExpression schema relations grouping params
853− AscNullsLast
854− :: Expression schema relations grouping params ('Null ty)
855− -> SortExpression schema relations grouping params
856− DescNullsFirst
857− :: Expression schema relations grouping params ('Null ty)
858− -> SortExpression schema relations grouping params
859− DescNullsLast
860− :: Expression schema relations grouping params ('Null ty)
861− -> SortExpression schema relations grouping params
862−deriving instance Show (SortExpression schema relations grouping params)
863−
864−-- | Render a `SortExpression`.
865−renderSortExpression :: SortExpression schema relations grouping params -> ByteString
866−renderSortExpression = \case
867− Asc expression -> renderExpression expression <+> "ASC"
868− Desc expression -> renderExpression expression <+> "DESC"
869− AscNullsFirst expression -> renderExpression expression
870− <+> "ASC NULLS FIRST"
871− DescNullsFirst expression -> renderExpression expression
872− <+> "DESC NULLS FIRST"
873− AscNullsLast expression -> renderExpression expression <+> "ASC NULLS LAST"
874− DescNullsLast expression -> renderExpression expression <+> "DESC NULLS LAST"
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