@@ -1,13 +1,14 @@
2Module: Squeal.PostgreSQL.Expression
2Module: Squeal.PostgreSQL.Expression
3Description: Squeal expressions
3Description: Squeal expressions
4−Copyright: (c) Eitan Chatav, 2019
4+Copyright: (c) Eitan Chatav, 2017
5Maintainer: eitan@morphism.tech
5Maintainer: eitan@morphism.tech
6Stability: experimental
6Stability: experimental
8Squeal expressions are the atoms used to build statements.
8Squeal expressions are the atoms used to build statements.
11+{-# OPTIONS_GHC -fno-warn-redundant-constraints #-}
11{-# LANGUAGE
12{-# LANGUAGE
12 AllowAmbiguousTypes
13 AllowAmbiguousTypes
13 , ConstraintKinds
14 , ConstraintKinds
@@ -33,214 +34,292 @@ Squeal expressions are the atoms used to build statements.
33module Squeal.PostgreSQL.Expression
34module Squeal.PostgreSQL.Expression
34 ( -- * Expression
35 ( -- * Expression
35 Expression (..)
36 Expression (..)
36− , Expr
37+ , HasParameter (parameter)
37− , type (-->)
38+ , param
38− , FunctionDB
39+ -- ** Null
39− , unsafeFunction
40+ , null_
40− , function
41+ , notNull
41− , unsafeLeftOp
42+ , coalesce
42− , leftOp
43+ , fromNull
43− , unsafeRightOp
44+ , isNull
44− , rightOp
45+ , isNotNull
45− , Operator
46+ , matchNull
46− , OperatorDB
47+ , nullIf
47 , unsafeBinaryOp
55 , unsafeBinaryOp
48− , binaryOp
56+ , unsafeUnaryOp
49− , FunctionVar
57+ , unsafeFunction
50− , unsafeFunctionVar
58+ , unsafeVariadicFunction
51− , type (--->)
59+ , atan2_
52− , FunctionNDB
60+ , cast
53− , unsafeFunctionN
61+ , quot_
54− , functionN
62+ , rem_
55− , PGSubset (..)
63+ , trunc
56− , PGIntersect (..)
64+ , round_
96+ -- *** Json and Jsonb operators
101+ -- *** Jsonb operators
128+ , jsonExtractPathAsText
129+ , jsonbExtractPathAsText
141+ -- * Window Functions
142+ , WindowDefinition (..)
144+ , WindowFunction (..)
157+ , SortExpression (..)
160+ , TypeExpression (..)
185+ , timestampWithTimeZone
57 -- * Re-export
196 -- * Re-export
63import Control.Category
203import Control.Category
64import Control.DeepSeq
204import Control.DeepSeq
65import Data.ByteString (ByteString)
205import Data.ByteString (ByteString)
206+import Data.ByteString.Lazy (toStrict)
66import Data.Function ((&))
207import Data.Function ((&))
67import Data.Semigroup hiding (All)
208import Data.Semigroup hiding (All)
209+import qualified Data.Aeson as JSON
68import Data.String
211import Data.String
69import Generics.SOP hiding (All, from)
213import Generics.SOP hiding (All, from)
214+import GHC.Generics ((:*:) (..))
70import GHC.OverloadedLabels
215import GHC.OverloadedLabels
71import GHC.TypeLits
216import GHC.TypeLits
73import Prelude hiding (id, (.))
217import Prelude hiding (id, (.))
219+import qualified Data.ByteString as ByteString
75import qualified GHC.Generics as GHC
220import qualified GHC.Generics as GHC
221+import qualified Generics.SOP as SOP
77−import Squeal.PostgreSQL.Alias
78−import Squeal.PostgreSQL.List
79import Squeal.PostgreSQL.Render
223import Squeal.PostgreSQL.Render
80import Squeal.PostgreSQL.Schema
224import Squeal.PostgreSQL.Schema
83−-- >>> import Squeal.PostgreSQL
85{-----------------------------------------
226{-----------------------------------------
86column expressions
227column expressions
87-----------------------------------------}
228-----------------------------------------}
89{- | `Expression`s are used in a variety of contexts,
230{- | `Expression`s are used in a variety of contexts,
90−such as in the target `Squeal.PostgreSQL.Query.List` of the
91−`Squeal.PostgreSQL.Query.select` command,
231+such as in the target list of the `Squeal.PostgreSQL.Query.select` command,
92as new column values in `Squeal.PostgreSQL.Manipulation.insertRow` or
232as new column values in `Squeal.PostgreSQL.Manipulation.insertRow` or
93`Squeal.PostgreSQL.Manipulation.update`,
233`Squeal.PostgreSQL.Manipulation.update`,
94−or in search `Squeal.PostgreSQL.Logic.Condition`s in a number of commands.
234+or in search `Condition`s in a number of commands.
96The expression syntax allows the calculation of
236The expression syntax allows the calculation of
97values from primitive expression using arithmetic, logical,
237values from primitive expression using arithmetic, logical,
98and other operations.
238and other operations.
100−The type parameters of `Expression` are
102−* @outer :: @ `FromType`, the @from@ clauses of any outer queries in which
103− the `Expression` is a correlated subquery expression;
104−* @commons :: @ `FromType`, the `Squeal.PostgreSQL.Query.CommonTableExpression`s
105− that are in scope for the `Expression`;
106−* @grp :: @ `Grouping`, the `Grouping` of the @from@ clause which may limit
107− which columns may be referenced by alias;
108−* @schemas :: @ `SchemasType`, the schemas of your database that are in
109− scope for the `Expression`;
110−* @from :: @ `FromType`, the @from@ clause which the `Expression` may use
111− to reference columns by alias;
112−* @ty :: @ `NullityType`, the type of the `Expression`.
114newtype Expression
240newtype Expression
115 (outer :: FromType)
241 (outer :: FromType)
116− (commons :: FromType)
117 (grp :: Grouping)
242 (grp :: Grouping)
243+ (commons :: FromType)
118 (schemas :: SchemasType)
244 (schemas :: SchemasType)
119 (params :: [NullityType])
245 (params :: [NullityType])
120 (from :: FromType)
246 (from :: FromType)
121 (ty :: NullityType)
247 (ty :: NullityType)
122 = UnsafeExpression { renderExpression :: ByteString }
248 = UnsafeExpression { renderExpression :: ByteString }
123 deriving (GHC.Generic,Show,Eq,Ord,NFData)
249 deriving (GHC.Generic,Show,Eq,Ord,NFData)
124−instance RenderSQL (Expression outer commons grp schemas params from ty) where
251+instance RenderSQL (Expression outer grp commons schemas params from ty) where
125 renderSQL = renderExpression
252 renderSQL = renderExpression
127−-- | An `Expr` is a closed `Expression`.
254+{- | A `HasParameter` constraint is used to indicate a value that is
128−-- It is a F@RankNType@ but don't be scared.
255+supplied externally to a SQL statement.
129−-- Think of it as an expression which sees no
256+`Squeal.PostgreSQL.PQ.manipulateParams`,
130−-- namespaces, so you can't use parameters
257+`Squeal.PostgreSQL.PQ.queryParams` and
131−-- or alias references. It can be used as
258+`Squeal.PostgreSQL.PQ.traversePrepared` support specifying data values
132−-- a simple piece of more complex `Expression`s.
259+separately from the SQL command string, in which case `param`s are used to
133−type Expr x
260+refer to the out-of-line data values.
134− = forall outer commons grp schemas params from
135− . Expression outer commons grp schemas params from x
136− -- ^ cannot reference aliases
138−-- | A @RankNType@ for binary operators.
139−type Operator x1 x2 y
140− = forall outer commons grp schemas params from
141− . Expression outer commons grp schemas params from x1
143− -> Expression outer commons grp schemas params from x2
145− -> Expression outer commons grp schemas params from y
148−type OperatorDB schemas x1 x2 y
149− = forall outer commons grp params from
150− . Expression outer commons grp schemas params from x1
152− -> Expression outer commons grp schemas params from x2
154− -> Expression outer commons grp schemas params from y
157−-- | A @RankNType@ for functions with a single argument.
158−-- These could be either function calls or unary operators.
159−-- This is a subtype of the usual Haskell function type `Prelude.->`,
160−-- indeed a subcategory as it is closed under the usual
161−-- `Prelude..` and `Prelude.id`.
163− = forall outer commons grp schemas params from
164− . Expression outer commons grp schemas params from x
166− -> Expression outer commons grp schemas params from y
169−type FunctionDB schemas x y
170− = forall outer commons grp params from
171− . Expression outer commons grp schemas params from x
173− -> Expression outer commons grp schemas params from y
176−{- | A @RankNType@ for functions with a fixed-length list of heterogeneous arguments.
177−Use the `*:` operator to end your argument lists, like so.
179−>>> printSQL (unsafeFunctionN "fun" (true :* false :* localTime *: true))
180−fun(TRUE, FALSE, LOCALTIME, TRUE)
183− = forall outer commons grp schemas params from
184− . NP (Expression outer commons grp schemas params from) xs
186− -> Expression outer commons grp schemas params from y
189−type FunctionNDB schemas xs y
190− = forall outer commons grp params from
191− . NP (Expression outer commons grp schemas params from) xs
193− -> Expression outer commons grp schemas params from y
196−{- | A @RankNType@ for functions with a variable-length list of
197−homogeneous arguments and at least 1 more argument.
199−type FunctionVar x0 x1 y
262+class KnownNat n => HasParameter
200− = forall outer commons grp schemas params from
263+ (n :: Nat)
201− . [Expression outer commons grp schemas params from x0]
264+ (params :: [NullityType])
202− -- ^ inputs
265+ (ty :: NullityType)
203− -> Expression outer commons grp schemas params from x1
266+ | n params -> ty where
204− -- ^ must have at least 1 input
267+ -- | `parameter` takes a `Nat` using type application and a `TypeExpression`.
205− -> Expression outer commons grp schemas params from y
269+ -- >>> let expr = parameter @1 int4 :: Expression outer grp '[] schemas '[ 'Null 'PGint4] from ('Null 'PGint4)
206− -- ^ output
270+ -- >>> printSQL expr
208−{- | >>> printSQL (unsafeFunctionVar "greatest" [true, null_] false)
272+ parameter
209−greatest(TRUE, NULL, FALSE)
273+ :: TypeExpression schemas ty
210−-}
274+ -> Expression outer grp commons schemas params from ty
211−unsafeFunctionVar :: ByteString -> FunctionVar x0 x1 y
212−unsafeFunctionVar fun xs x = UnsafeExpression $ fun <> parenthesized
275+ parameter ty = UnsafeExpression $ parenthesized $
213− (commaSeparated (renderSQL <$> xs) <> ", " <> renderSQL x)
276+ "$" <> renderNat @n <+> "::"
278+instance {-# OVERLAPPING #-} HasParameter 1 (ty1:tys) ty1
279+instance {-# OVERLAPPABLE #-} (KnownNat n, HasParameter (n-1) params ty)
280+ => HasParameter n (ty' : params) ty
282+-- | `param` takes a `Nat` using type application and for basic types,
283+-- infers a `TypeExpression`.
285+-- >>> let expr = param @1 :: Expression outer grp commons schemas '[ 'Null 'PGint4] from ('Null 'PGint4)
289+ :: forall n outer commons schemas params from grp ty
290+ . (PGTyped schemas ty, HasParameter n params ty)
291+ => Expression outer grp commons schemas params from ty -- ^ param
292+param = parameter @n (pgtype @schemas)
215instance (HasUnique tab (Join outer from) row, Has col row ty)
294instance (HasUnique tab (Join outer from) row, Has col row ty)
216− => IsLabel col (Expression outer commons 'Ungrouped schemas params from ty) where
295+ => IsLabel col (Expression outer 'Ungrouped commons schemas params from ty) where
217 fromLabel = UnsafeExpression $ renderSQL (Alias @col)
296 fromLabel = UnsafeExpression $ renderSQL (Alias @col)
218instance (HasUnique tab (Join outer from) row, Has col row ty, tys ~ '[ty])
297instance (HasUnique tab (Join outer from) row, Has col row ty, tys ~ '[ty])
219− => IsLabel col (NP (Expression outer commons 'Ungrouped schemas params from) tys) where
298+ => IsLabel col (NP (Expression outer 'Ungrouped commons schemas params from) tys) where
220 fromLabel = fromLabel @col :* Nil
299 fromLabel = fromLabel @col :* Nil
221instance (HasUnique tab (Join outer from) row, Has col row ty, column ~ (col ::: ty))
300instance (HasUnique tab (Join outer from) row, Has col row ty, column ~ (col ::: ty))
222 => IsLabel col
301 => IsLabel col
223− (Aliased (Expression outer commons 'Ungrouped schemas params from) column) where
302+ (Aliased (Expression outer 'Ungrouped commons schemas params from) column) where
224 fromLabel = fromLabel @col `As` Alias
303 fromLabel = fromLabel @col `As` Alias
225instance (HasUnique tab (Join outer from) row, Has col row ty, columns ~ '[col ::: ty])
304instance (HasUnique tab (Join outer from) row, Has col row ty, columns ~ '[col ::: ty])
226 => IsLabel col
305 => IsLabel col
227− (NP (Aliased (Expression outer commons 'Ungrouped schemas params from)) columns) where
306+ (NP (Aliased (Expression outer 'Ungrouped commons schemas params from)) columns) where
228 fromLabel = fromLabel @col :* Nil
307 fromLabel = fromLabel @col :* Nil
230instance (Has tab (Join outer from) row, Has col row ty)
309instance (Has tab (Join outer from) row, Has col row ty)
231− => IsQualified tab col (Expression outer commons 'Ungrouped schemas params from ty) where
310+ => IsQualified tab col (Expression outer 'Ungrouped commons schemas params from ty) where
232 tab ! col = UnsafeExpression $
311 tab ! col = UnsafeExpression $
233 renderSQL tab <> "." <> renderSQL col
312 renderSQL tab <> "." <> renderSQL col
234instance (Has tab (Join outer from) row, Has col row ty, tys ~ '[ty])
313instance (Has tab (Join outer from) row, Has col row ty, tys ~ '[ty])
235− => IsQualified tab col (NP (Expression outer commons 'Ungrouped schemas params from) tys) where
314+ => IsQualified tab col (NP (Expression outer 'Ungrouped commons schemas params from) tys) where
236 tab ! col = tab ! col :* Nil
315 tab ! col = tab ! col :* Nil
237instance (Has tab (Join outer from) row, Has col row ty, column ~ (col ::: ty))
316instance (Has tab (Join outer from) row, Has col row ty, column ~ (col ::: ty))
238 => IsQualified tab col
317 => IsQualified tab col
239− (Aliased (Expression outer commons 'Ungrouped schemas params from) column) where
318+ (Aliased (Expression outer 'Ungrouped commons schemas params from) column) where
240 tab ! col = tab ! col `As` col
319 tab ! col = tab ! col `As` col
241instance (Has tab (Join outer from) row, Has col row ty, columns ~ '[col ::: ty])
320instance (Has tab (Join outer from) row, Has col row ty, columns ~ '[col ::: ty])
242 => IsQualified tab col
321 => IsQualified tab col
243− (NP (Aliased (Expression outer commons 'Ungrouped schemas params from)) columns) where
322+ (NP (Aliased (Expression outer 'Ungrouped commons schemas params from)) columns) where
244 tab ! col = tab ! col :* Nil
323 tab ! col = tab ! col :* Nil
@@ -248,7 +327,7 @@ instance
248 , Has col row ty
327 , Has col row ty
249 , GroupedBy tab col bys
328 , GroupedBy tab col bys
250 ) => IsLabel col
329 ) => IsLabel col
251− (Expression outer commons ('Grouped bys) schemas params from ty) where
330+ (Expression outer ('Grouped bys) commons schemas params from ty) where
252 fromLabel = UnsafeExpression $ renderSQL (Alias @col)
331 fromLabel = UnsafeExpression $ renderSQL (Alias @col)
254 ( HasUnique tab (Join outer from) row
333 ( HasUnique tab (Join outer from) row
@@ -256,7 +335,7 @@ instance
256 , GroupedBy tab col bys
335 , GroupedBy tab col bys
257 , tys ~ '[ty]
336 , tys ~ '[ty]
258 ) => IsLabel col
337 ) => IsLabel col
259− (NP (Expression outer commons ('Grouped bys) schemas params from) tys) where
338+ (NP (Expression outer ('Grouped bys) commons schemas params from) tys) where
260 fromLabel = fromLabel @col :* Nil
339 fromLabel = fromLabel @col :* Nil
262 ( HasUnique tab (Join outer from) row
341 ( HasUnique tab (Join outer from) row
@@ -264,7 +343,7 @@ instance
264 , GroupedBy tab col bys
343 , GroupedBy tab col bys
265 , column ~ (col ::: ty)
344 , column ~ (col ::: ty)
266 ) => IsLabel col
345 ) => IsLabel col
267− (Aliased (Expression outer commons ('Grouped bys) schemas params from) column) where
346+ (Aliased (Expression outer ('Grouped bys) commons schemas params from) column) where
268 fromLabel = fromLabel @col `As` Alias
347 fromLabel = fromLabel @col `As` Alias
270 ( HasUnique tab (Join outer from) row
349 ( HasUnique tab (Join outer from) row
@@ -272,7 +351,7 @@ instance
272 , GroupedBy tab col bys
351 , GroupedBy tab col bys
273 , columns ~ '[col ::: ty]
352 , columns ~ '[col ::: ty]
274 ) => IsLabel col
353 ) => IsLabel col
275− (NP (Aliased (Expression outer commons ('Grouped bys) schemas params from)) columns) where
354+ (NP (Aliased (Expression outer ('Grouped bys) commons schemas params from)) columns) where
276 fromLabel = fromLabel @col :* Nil
355 fromLabel = fromLabel @col :* Nil
@@ -280,7 +359,7 @@ instance
280 , Has col row ty
359 , Has col row ty
281 , GroupedBy tab col bys
360 , GroupedBy tab col bys
282 ) => IsQualified tab col
361 ) => IsQualified tab col
283− (Expression outer commons ('Grouped bys) schemas params from ty) where
362+ (Expression outer ('Grouped bys) commons schemas params from ty) where
284 tab ! col = UnsafeExpression $
363 tab ! col = UnsafeExpression $
285 renderSQL tab <> "." <> renderSQL col
364 renderSQL tab <> "." <> renderSQL col
@@ -289,7 +368,7 @@ instance
289 , GroupedBy tab col bys
368 , GroupedBy tab col bys
290 , tys ~ '[ty]
369 , tys ~ '[ty]
291 ) => IsQualified tab col
370 ) => IsQualified tab col
292− (NP (Expression outer commons ('Grouped bys) schemas params from) tys) where
371+ (NP (Expression outer ('Grouped bys) commons schemas params from) tys) where
293 tab ! col = tab ! col :* Nil
372 tab ! col = tab ! col :* Nil
295 ( Has tab (Join outer from) row
374 ( Has tab (Join outer from) row
@@ -297,7 +376,7 @@ instance
297 , GroupedBy tab col bys
376 , GroupedBy tab col bys
298 , column ~ (col ::: ty)
377 , column ~ (col ::: ty)
299 ) => IsQualified tab col
378 ) => IsQualified tab col
300− (Aliased (Expression outer commons ('Grouped bys) schemas params from) column) where
379+ (Aliased (Expression outer ('Grouped bys) commons schemas params from) column) where
301 tab ! col = tab ! col `As` col
380 tab ! col = tab ! col `As` col
303 ( Has tab (Join outer from) row
382 ( Has tab (Join outer from) row
@@ -305,78 +384,244 @@ instance
305 , GroupedBy tab col bys
384 , GroupedBy tab col bys
306 , columns ~ '[col ::: ty]
385 , columns ~ '[col ::: ty]
307 ) => IsQualified tab col
386 ) => IsQualified tab col
308− (NP (Aliased (Expression outer commons ('Grouped bys) schemas params from)) columns) where
387+ (NP (Aliased (Expression outer ('Grouped bys) commons schemas params from)) columns) where
309 tab ! col = tab ! col :* Nil
388 tab ! col = tab ! col :* Nil
390+-- | analagous to `Nothing`
392+-- >>> printSQL null_
394+null_ :: Expression outer grp commons schemas params from ('Null ty)
395+null_ = UnsafeExpression "NULL"
397+-- | analagous to `Just`
399+-- >>> printSQL $ notNull true
402+ :: Expression outer grp commons schemas params from ('NotNull ty)
403+ -> Expression outer grp commons schemas params from ('Null ty)
404+notNull = UnsafeExpression . renderSQL
406+-- | return the leftmost value which is not NULL
408+-- >>> printSQL $ coalesce [null_, true] false
409+-- COALESCE(NULL, TRUE, FALSE)
411+ :: [Expression outer grp commons schemas params from ('Null ty)]
412+ -- ^ @NULL@s may be present
413+ -> Expression outer grp commons schemas params from ('NotNull ty)
414+ -- ^ @NULL@ is absent
415+ -> Expression outer grp commons schemas params from ('NotNull ty)
416+coalesce nullxs notNullx = UnsafeExpression $
417+ "COALESCE" <> parenthesized (commaSeparated
418+ ((renderSQL <$> nullxs) <> [renderSQL notNullx]))
420+-- | analagous to `Data.Maybe.fromMaybe` using @COALESCE@
422+-- >>> printSQL $ fromNull true null_
423+-- COALESCE(NULL, TRUE)
425+ :: Expression outer grp commons schemas params from ('NotNull ty)
426+ -- ^ what to convert @NULL@ to
427+ -> Expression outer grp commons schemas params from ('Null ty)
428+ -> Expression outer grp commons schemas params from ('NotNull ty)
429+fromNull notNullx nullx = coalesce [nullx] notNullx
431+-- | >>> printSQL $ null_ & isNull
434+ :: Expression outer grp commons schemas params from ('Null ty)
435+ -- ^ possibly @NULL@
436+ -> Condition outer grp commons schemas params from
437+isNull x = UnsafeExpression $ renderSQL x <+> "IS NULL"
439+-- | >>> printSQL $ null_ & isNotNull
442+ :: Expression outer grp commons schemas params from ('Null ty)
443+ -- ^ possibly @NULL@
444+ -> Condition outer grp commons schemas params from
445+isNotNull x = UnsafeExpression $ renderSQL x <+> "IS NOT NULL"
447+-- | analagous to `maybe` using @IS NULL@
449+-- >>> printSQL $ matchNull true not_ null_
450+-- CASE WHEN NULL IS NULL THEN TRUE ELSE (NOT NULL) END
452+ :: Expression outer grp commons schemas params from (nullty)
453+ -- ^ what to convert @NULL@ to
454+ -> ( Expression outer grp commons schemas params from ('NotNull ty)
455+ -> Expression outer grp commons schemas params from (nullty) )
456+ -- ^ function to perform when @NULL@ is absent
457+ -> Expression outer grp commons schemas params from ('Null ty)
458+ -> Expression outer grp commons schemas params from (nullty)
459+matchNull y f x = ifThenElse (isNull x) y
460+ (f (UnsafeExpression (renderSQL x)))
462+{-| right inverse to `fromNull`, if its arguments are equal then
463+`nullIf` gives @NULL@.
465+>>> :set -XTypeApplications -XDataKinds
466+>>> let expr = nullIf false (param @1) :: Expression outer grp commons schemas '[ 'NotNull 'PGbool] from ('Null 'PGbool)
468+NULL IF (FALSE, ($1 :: bool))
471+ :: Expression outer grp commons schemas params from ('NotNull ty)
472+ -- ^ @NULL@ is absent
473+ -> Expression outer grp commons schemas params from ('NotNull ty)
474+ -- ^ @NULL@ is absent
475+ -> Expression outer grp commons schemas params from ('Null ty)
476+nullIf x y = UnsafeExpression $ "NULL IF" <+> parenthesized
477+ (renderSQL x <> ", " <> renderSQL y)
479+-- | >>> printSQL $ array [null_, false, true]
480+-- ARRAY[NULL, FALSE, TRUE]
482+ :: [Expression outer grp commons schemas params from ty]
484+ -> Expression outer grp commons schemas params from (nullity ('PGvararray ty))
485+array xs = UnsafeExpression $
486+ "ARRAY[" <> commaSeparated (renderSQL <$> xs) <> "]"
488+-- | >>> printSQL $ cardinality (array [null_, false, true])
489+-- cardinality(ARRAY[NULL, FALSE, TRUE])
491+ :: Expression outer grp commons schemas params from (nullity ('PGvararray ty))
492+ -> Expression outer grp commons schemas params from (nullity 'PGint8)
493+cardinality = unsafeFunction "cardinality"
495+-- | >>> printSQL $ array [null_, false, true] & index 2
496+-- (ARRAY[NULL, FALSE, TRUE])[2]
498+ :: Word64 -- ^ index
499+ -> Expression outer grp commons schemas params from (nullity ('PGvararray ty)) -- ^ array
500+ -> Expression outer grp commons schemas params from (NullifyType ty)
501+index n expr = UnsafeExpression $
502+ parenthesized (renderSQL expr) <> "[" <> fromString (show n) <> "]"
311instance (KnownSymbol label, label `In` labels) => IsPGlabel label
504instance (KnownSymbol label, label `In` labels) => IsPGlabel label
312− (Expression outer commons grp schemas params from (null ('PGenum labels))) where
505+ (Expression outer grp commons schemas params from (nullity ('PGenum labels))) where
313 label = UnsafeExpression $ renderSQL (PGlabel @label)
506 label = UnsafeExpression $ renderSQL (PGlabel @label)
508+-- | A row constructor is an expression that builds a row value
509+-- (also called a composite value) using values for its member fields.
512+-- type Complex = 'PGcomposite
513+-- '[ "real" ::: 'NotNull 'PGfloat8
514+-- , "imaginary" ::: 'NotNull 'PGfloat8 ]
517+-- >>> let i = row (0 `as` #real :* 1 `as` #imaginary) :: Expression outer grp commons schemas params from ('NotNull Complex)
522+ => NP (Aliased (Expression outer grp commons schemas params from)) row
523+ -- ^ zero or more expressions for the row field values
524+ -> Expression outer grp commons schemas params from (nullity ('PGcomposite row))
525+row exprs = UnsafeExpression $ "ROW" <> parenthesized
526+ (renderCommaSeparated (\ (expr `As` _) -> renderSQL expr) exprs)
529+-- type Complex = 'PGcomposite
530+-- '[ "real" ::: 'NotNull 'PGfloat8
531+-- , "imaginary" ::: 'NotNull 'PGfloat8 ]
532+-- type Schema = '["complex" ::: 'Typedef Complex]
535+-- >>> let i = row (0 `as` #real :* 1 `as` #imaginary) :: Expression outer grp '[] (Public Schema) from params ('NotNull Complex)
536+-- >>> printSQL $ i & field #complex #imaginary
537+-- (ROW(0, 1)::"complex")."imaginary"
539+ :: ( Has sch schemas schema
540+ , Has tydef schema ('Typedef ('PGcomposite row))
542+ => QualifiedAlias sch tydef -- ^ row type
543+ -> Alias field -- ^ field name
544+ -> Expression outer grp commons schemas params from ('NotNull ('PGcomposite row))
545+ -> Expression outer grp commons schemas params from ty
546+field td fld expr = UnsafeExpression $
547+ parenthesized (renderSQL expr <> "::" <> renderSQL td)
548+ <> "." <> renderSQL fld
551+ (Expression outer grp commons schemas params from (nullity ('PGvararray ty))) where
552+ (<>) = unsafeBinaryOp "||"
555+ (Expression outer grp commons schemas params from (nullity ('PGvararray ty))) where
559+-- | >>> let expr = greatest currentTimestamp [param @1] :: Expression outer grp commons schemas '[ 'NotNull 'PGtimestamptz] from ('NotNull 'PGtimestamptz)
561+-- GREATEST(CURRENT_TIMESTAMP, ($1 :: timestamp with time zone))
563+ :: Expression outer grp commons schemas params from (nullty)
564+ -- ^ needs at least 1 argument
565+ -> [Expression outer grp commons schemas params from (nullty)]
567+ -> Expression outer grp commons schemas params from (nullty)
568+greatest x xs = UnsafeExpression $ "GREATEST("
569+ <> commaSeparated (renderSQL <$> (x:xs)) <> ")"
571+-- | >>> printSQL $ least currentTimestamp [null_]
572+-- LEAST(CURRENT_TIMESTAMP, NULL)
574+ :: Expression outer grp commons schemas params from (nullty)
575+ -- ^ needs at least 1 argument
576+ -> [Expression outer grp commons schemas params from (nullty)]
578+ -> Expression outer grp commons schemas params from (nullty)
579+least x xs = UnsafeExpression $ "LEAST("
580+ <> commaSeparated (renderSQL <$> (x:xs)) <> ")"
315-- | >>> printSQL $ unsafeBinaryOp "OR" true false
582-- | >>> printSQL $ unsafeBinaryOp "OR" true false
316-- (TRUE OR FALSE)
583-- (TRUE OR FALSE)
317−unsafeBinaryOp :: ByteString -> Operator ty0 ty1 ty2
584+unsafeBinaryOp
587+ -> Expression outer grp commons schemas params from (ty0)
588+ -> Expression outer grp commons schemas params from (ty1)
589+ -> Expression outer grp commons schemas params from (ty2)
318unsafeBinaryOp op x y = UnsafeExpression $ parenthesized $
590unsafeBinaryOp op x y = UnsafeExpression $ parenthesized $
319 renderSQL x <+> op <+> renderSQL y
591 renderSQL x <+> op <+> renderSQL y
322− :: forall op sch schemas schema x y z.
323− ( Has sch schemas schema
324− , Has op schema ('Operator ('BinaryOp x y z)) )
325− => OperatorDB schemas x y z
326−binaryOp = unsafeBinaryOp $ renderSymbol @op
328−-- | >>> printSQL $ unsafeLeftOp "NOT" true
593+-- | >>> printSQL $ unsafeUnaryOp "NOT" true
329-- (NOT TRUE)
594-- (NOT TRUE)
330−unsafeLeftOp :: ByteString -> x --> y
596+ :: ByteString
331−unsafeLeftOp op x = UnsafeExpression $ parenthesized $ op <+> renderSQL x
597+ -- ^ operator
332−
598+ -> Expression outer grp commons schemas params from (ty0)
333−leftOp
599+ -> Expression outer grp commons schemas params from (ty1)
334− :: forall op sch schemas schema x y.
335− ( Has sch schemas schema
336− , Has op schema ('Operator ('LeftOp x y)) )
337− => FunctionDB schemas x y
338−leftOp = unsafeLeftOp $ renderSymbol @op
340−-- | >>> printSQL $ true & unsafeRightOp "IS NOT TRUE"
341−-- (TRUE IS NOT TRUE)
342−unsafeRightOp :: ByteString -> x --> y
343−unsafeRightOp op x = UnsafeExpression $ parenthesized $ renderSQL x <+> op
600+unsafeUnaryOp op x = UnsafeExpression $ parenthesized $
344−
601+ op <+> renderSQL x
346− :: forall op sch schemas schema x y.
347− ( Has sch schemas schema
348− , Has op schema ('Operator ('RightOp x y)) )
349− => FunctionDB schemas x y
350−rightOp = unsafeRightOp $ renderSymbol @op
352-- | >>> printSQL $ unsafeFunction "f" true
603-- | >>> printSQL $ unsafeFunction "f" true
353-- f(TRUE)
604-- f(TRUE)
354−unsafeFunction :: ByteString -> x --> y
605+unsafeFunction
608+ -> Expression outer grp commons schemas params from (xty)
609+ -> Expression outer grp commons schemas params from (yty)
355unsafeFunction fun x = UnsafeExpression $
610unsafeFunction fun x = UnsafeExpression $
356 fun <> parenthesized (renderSQL x)
611 fun <> parenthesized (renderSQL x)
358−function
613+-- | Helper for defining variadic functions.
359− :: (Has sch schemas schema, Has fun schema ('Function ('[x] :=> 'Returns y)))
614+unsafeVariadicFunction
360− => QualifiedAlias sch fun
615+ :: SListI elems
361− -> FunctionDB schemas x y
362−function = unsafeFunction . renderSQL
364−-- | >>> printSQL $ unsafeFunctionN "f" (currentTime :* localTimestamp :* false *: literal 'a')
365−-- f(CURRENT_TIME, LOCALTIMESTAMP, FALSE, E'a')
366−unsafeFunctionN :: SListI xs => ByteString -> xs ---> y
616+ => ByteString
618+ -> NP (Expression outer grp commons schemas params from) elems
619+ -> Expression outer grp commons schemas params from ret
367−unsafeFunctionN fun xs = UnsafeExpression $
620+unsafeVariadicFunction fun x = UnsafeExpression $
368− fun <> parenthesized (renderCommaSeparated renderSQL xs)
621+ fun <> parenthesized (commaSeparated (hcollapse (hmap (K . renderSQL) x)))
371− :: ( Has sch schemas schema
372− , Has fun schema ('Function (xs :=> 'Returns y))
374− => QualifiedAlias sch fun
375− -> FunctionNDB schemas xs y
376−functionN = unsafeFunctionN . renderSQL
378instance ty `In` PGNum
623instance ty `In` PGNum
379− => Num (Expression outer commons grp schemas params from (null ty)) where
624+ => Num (Expression outer grp commons schemas params from (nullity ty)) where
380 (+) = unsafeBinaryOp "+"
625 (+) = unsafeBinaryOp "+"
381 (-) = unsafeBinaryOp "-"
626 (-) = unsafeBinaryOp "-"
382 (*) = unsafeBinaryOp "*"
627 (*) = unsafeBinaryOp "*"
@@ -388,17 +633,12 @@ instance ty `In` PGNum
390instance (ty `In` PGNum, ty `In` PGFloating) => Fractional
635instance (ty `In` PGNum, ty `In` PGFloating) => Fractional
391− (Expression outer commons grp schemas params from (null ty)) where
636+ (Expression outer grp commons schemas params from (nullity ty)) where
392 (/) = unsafeBinaryOp "/"
637 (/) = unsafeBinaryOp "/"
393− fromRational
638+ fromRational x = fromInteger (numerator x) / fromInteger (denominator x)
397− . showFFloat Nothing
400instance (ty `In` PGNum, ty `In` PGFloating) => Floating
640instance (ty `In` PGNum, ty `In` PGFloating) => Floating
401− (Expression outer commons grp schemas params from (null ty)) where
641+ (Expression outer grp commons schemas params from (nullity ty)) where
402 pi = UnsafeExpression "pi()"
642 pi = UnsafeExpression "pi()"
403 exp = unsafeFunction "exp"
643 exp = unsafeFunction "exp"
404 log = unsafeFunction "ln"
644 log = unsafeFunction "ln"
@@ -419,54 +659,1623 @@ instance (ty `In` PGNum, ty `In` PGFloating) => Floating
419 acosh x = log (x + sqrt (x*x - 1))
659 acosh x = log (x + sqrt (x*x - 1))
420 atanh x = log ((1 + x) / (1 - x)) / 2
660 atanh x = log ((1 + x) / (1 - x)) / 2
422−-- | Contained by operators
662+-- | >>> :{
423−class PGSubset ty where
663+-- let
424− (@>) :: Operator (null0 ty) (null1 ty) ('Null 'PGbool)
664+-- expression :: Expression outer grp commons schemas params from (nullity 'PGfloat4)
425− (@>) = unsafeBinaryOp "@>"
665+-- expression = atan2_ pi 2
426− (<@) :: Operator (null0 ty) (null1 ty) ('Null 'PGbool)
666+-- in printSQL expression
427− (<@) = unsafeBinaryOp "<@"
667+-- :}
428−instance PGSubset 'PGjsonb
668+-- atan2(pi(), 2)
429−instance PGSubset 'PGtsquery
669+atan2_
430−instance PGSubset ('PGvararray ty)
670+ :: float `In` PGFloating
431−instance PGSubset ('PGrange ty)
671+ => Expression outer grp commons schemas params from (nullity float)
433−class PGIntersect ty where
673+ -> Expression outer grp commons schemas params from (nullity float)
434− (@&&) :: Operator (null0 ty) (null1 ty) ('Null 'PGbool)
674+ -- ^ denominator
435− (@&&) = unsafeBinaryOp "&&"
675+ -> Expression outer grp commons schemas params from (nullity float)
436−instance PGIntersect ('PGvararray ty)
676+atan2_ y x = UnsafeExpression $
437−instance PGIntersect ('PGrange ty)
677+ "atan2(" <> renderSQL y <> ", " <> renderSQL x <> ")"
679+-- When a `cast` is applied to an `Expression` of a known type, it
680+-- represents a run-time type conversion. The cast will succeed only if a
681+-- suitable type conversion operation has been defined.
683+-- | >>> printSQL $ true & cast int4
686+ :: TypeExpression schemas ty1
687+ -- ^ type to cast as
688+ -> Expression outer grp commons schemas params from ty0
689+ -- ^ value to convert
690+ -> Expression outer grp commons schemas params from ty1
691+cast ty x = UnsafeExpression $ parenthesized $
692+ renderSQL x <+> "::" <+> renderSQL ty
694+-- | integer division, truncates the result
698+-- expression :: Expression outer grp commons schemas params from (nullity 'PGint2)
699+-- expression = 5 `quot_` 2
700+-- in printSQL expression
704+ :: int `In` PGIntegral
705+ => Expression outer grp commons schemas params from (nullity int)
707+ -> Expression outer grp commons schemas params from (nullity int)
709+ -> Expression outer grp commons schemas params from (nullity int)
710+quot_ = unsafeBinaryOp "/"
712+-- | remainder upon integer division
716+-- expression :: Expression outer grp commons schemas params from (nullity 'PGint2)
717+-- expression = 5 `rem_` 2
718+-- in printSQL expression
722+ :: int `In` PGIntegral
723+ => Expression outer grp commons schemas params from (nullity int)
725+ -> Expression outer grp commons schemas params from (nullity int)
727+ -> Expression outer grp commons schemas params from (nullity int)
728+rem_ = unsafeBinaryOp "%"
732+-- expression :: Expression outer grp commons schemas params from (nullity 'PGfloat4)
733+-- expression = trunc pi
734+-- in printSQL expression
738+ :: frac `In` PGFloating
739+ => Expression outer grp commons schemas params from (nullity frac)
740+ -- ^ fractional number
741+ -> Expression outer grp commons schemas params from (nullity frac)
742+trunc = unsafeFunction "trunc"
746+-- expression :: Expression outer grp commons schemas params from (nullity 'PGfloat4)
747+-- expression = round_ pi
748+-- in printSQL expression
752+ :: frac `In` PGFloating
753+ => Expression outer grp commons schemas params from (nullity frac)
754+ -- ^ fractional number
755+ -> Expression outer grp commons schemas params from (nullity frac)
756+round_ = unsafeFunction "round"
760+-- expression :: Expression outer grp commons schemas params from (nullity 'PGfloat4)
761+-- expression = ceiling_ pi
762+-- in printSQL expression
766+ :: frac `In` PGFloating
767+ => Expression outer grp commons schemas params from (nullity frac)
768+ -- ^ fractional number
769+ -> Expression outer grp commons schemas params from (nullity frac)
770+ceiling_ = unsafeFunction "ceiling"
772+-- | A `Condition` is an `Expression`, which can evaluate
773+-- to `true`, `false` or `null_`. This is because SQL uses
774+-- a three valued logic.
775+type Condition outer grp commons schemas params from =
776+ Expression outer grp commons schemas params from ('Null 'PGbool)
778+-- | >>> printSQL true
780+true :: Expression outer grp commons schemas params from (nullity 'PGbool)
781+true = UnsafeExpression "TRUE"
783+-- | >>> printSQL false
785+false :: Expression outer grp commons schemas params from (nullity 'PGbool)
786+false = UnsafeExpression "FALSE"
788+-- | >>> printSQL $ not_ true
791+ :: Expression outer grp commons schemas params from (nullity 'PGbool)
792+ -> Expression outer grp commons schemas params from (nullity 'PGbool)
793+not_ = unsafeUnaryOp "NOT"
795+-- | >>> printSQL $ true .&& false
798+ :: Expression outer grp commons schemas params from (nullity 'PGbool)
799+ -> Expression outer grp commons schemas params from (nullity 'PGbool)
800+ -> Expression outer grp commons schemas params from (nullity 'PGbool)
802+(.&&) = unsafeBinaryOp "AND"
804+-- | >>> printSQL $ true .|| false
807+ :: Expression outer grp commons schemas params from (nullity 'PGbool)
808+ -> Expression outer grp commons schemas params from (nullity 'PGbool)
809+ -> Expression outer grp commons schemas params from (nullity 'PGbool)
811+(.||) = unsafeBinaryOp "OR"
815+-- expression :: Expression outer grp commons schemas params from (nullity 'PGint2)
816+-- expression = caseWhenThenElse [(true, 1), (false, 2)] 3
817+-- in printSQL expression
819+-- CASE WHEN TRUE THEN 1 WHEN FALSE THEN 2 ELSE 3 END
821+ :: [ ( Condition outer grp commons schemas params from
822+ , Expression outer grp commons schemas params from ty
824+ -- ^ whens and thens
825+ -> Expression outer grp commons schemas params from ty
827+ -> Expression outer grp commons schemas params from ty
828+caseWhenThenElse whenThens else_ = UnsafeExpression $ mconcat
832+ [ " WHEN ", renderSQL when_
833+ , " THEN ", renderSQL then_
835+ | (when_,then_) <- whenThens
837+ , " ELSE ", renderSQL else_
843+-- expression :: Expression outer grp commons schemas params from (nullity 'PGint2)
844+-- expression = ifThenElse true 1 0
845+-- in printSQL expression
847+-- CASE WHEN TRUE THEN 1 ELSE 0 END
849+ :: Condition outer grp commons schemas params from
850+ -> Expression outer grp commons schemas params from ty -- ^ then
851+ -> Expression outer grp commons schemas params from ty -- ^ else
852+ -> Expression outer grp commons schemas params from ty
853+ifThenElse if_ then_ else_ = caseWhenThenElse [(if_,then_)] else_
855+-- | Comparison operations like `.==`, `./=`, `.>`, `.>=`, `.<` and `.<=`
856+-- will produce @NULL@s if one of their arguments is @NULL@.
858+-- >>> printSQL $ true .== null_
861+ :: Expression outer grp commons schemas params from (nullity0 ty) -- ^ lhs
862+ -> Expression outer grp commons schemas params from (nullity1 ty) -- ^ rhs
863+ -> Condition outer grp commons schemas params from
864+(.==) = unsafeBinaryOp "="
867+-- | >>> printSQL $ true ./= null_
870+ :: Expression outer grp commons schemas params from (nullity0 ty) -- ^ lhs
871+ -> Expression outer grp commons schemas params from (nullity1 ty) -- ^ rhs
872+ -> Condition outer grp commons schemas params from
873+(./=) = unsafeBinaryOp "<>"
876+-- | >>> printSQL $ true .>= null_
879+ :: Expression outer grp commons schemas params from (nullity0 ty) -- ^ lhs
880+ -> Expression outer grp commons schemas params from (nullity1 ty) -- ^ rhs
881+ -> Condition outer grp commons schemas params from
882+(.>=) = unsafeBinaryOp ">="
885+-- | >>> printSQL $ true .< null_
888+ :: Expression outer grp commons schemas params from (nullity0 ty) -- ^ lhs
889+ -> Expression outer grp commons schemas params from (nullity1 ty) -- ^ rhs
890+ -> Condition outer grp commons schemas params from
891+(.<) = unsafeBinaryOp "<"
894+-- | >>> printSQL $ true .<= null_
897+ :: Expression outer grp commons schemas params from (nullity0 ty) -- ^ lhs
898+ -> Expression outer grp commons schemas params from (nullity1 ty) -- ^ rhs
899+ -> Condition outer grp commons schemas params from
900+(.<=) = unsafeBinaryOp "<="
903+-- | >>> printSQL $ true .> null_
906+ :: Expression outer grp commons schemas params from (nullity0 ty) -- ^ lhs
907+ -> Expression outer grp commons schemas params from (nullity1 ty) -- ^ rhs
908+ -> Condition outer grp commons schemas params from
909+(.>) = unsafeBinaryOp ">"
912+-- | >>> printSQL currentDate
915+ :: Expression outer grp commons schemas params from (nullity 'PGdate)
916+currentDate = UnsafeExpression "CURRENT_DATE"
918+-- | >>> printSQL currentTime
921+ :: Expression outer grp commons schemas params from (nullity 'PGtimetz)
922+currentTime = UnsafeExpression "CURRENT_TIME"
924+-- | >>> printSQL currentTimestamp
927+ :: Expression outer grp commons schemas params from (nullity 'PGtimestamptz)
928+currentTimestamp = UnsafeExpression "CURRENT_TIMESTAMP"
930+-- | >>> printSQL localTime
933+ :: Expression outer grp commons schemas params from (nullity 'PGtime)
934+localTime = UnsafeExpression "LOCALTIME"
936+-- | >>> printSQL localTimestamp
939+ :: Expression outer grp commons schemas params from (nullity 'PGtimestamp)
940+localTimestamp = UnsafeExpression "LOCALTIMESTAMP"
942+{-----------------------------------------
944+-----------------------------------------}
439instance IsString
946instance IsString
440− (Expression outer commons grp schemas params from (null 'PGtext)) where
947+ (Expression outer grp commons schemas params from (nullity 'PGtext)) where
441 fromString str = UnsafeExpression $
948 fromString str = UnsafeExpression $
442 "E\'" <> fromString (escape =<< str) <> "\'"
949 "E\'" <> fromString (escape =<< str) <> "\'"
443−instance IsString
950+ where
444− (Expression outer commons grp schemas params from (null 'PGtsvector)) where
951+ escape = \case
445− fromString str = UnsafeExpression . parenthesized . (<> " :: tsvector") $
952+ '\NUL' -> "\\0"
446− "E\'" <> fromString (escape =<< str) <> "\'"
953+ '\'' -> "''"
447−instance IsString
954+ '"' -> "\\\""
448− (Expression outer commons grp schemas params from (null 'PGtsquery)) where
955+ '\b' -> "\\b"
449− fromString str = UnsafeExpression . parenthesized . (<> " :: tsquery") $
956+ '\n' -> "\\n"
450− "E\'" <> fromString (escape =<< str) <> "\'"
957+ '\r' -> "\\r"
452instance Semigroup
962instance Semigroup
453− (Expression outer commons grp schemas params from (null ('PGvararray ty))) where
454− (<>) = unsafeBinaryOp "||"
456− (Expression outer commons grp schemas params from (null 'PGjsonb)) where
457− (<>) = unsafeBinaryOp "||"
459− (Expression outer commons grp schemas params from (null 'PGtext)) where
963+ (Expression outer grp commons schemas params from (nullity 'PGtext)) where
460− (<>) = unsafeBinaryOp "||"
462− (Expression outer commons grp schemas params from (null 'PGtsvector)) where
463 (<>) = unsafeBinaryOp "||"
964 (<>) = unsafeBinaryOp "||"
465instance Monoid
966instance Monoid
466− (Expression outer commons grp schemas params from (null 'PGtext)) where
967+ (Expression outer grp commons schemas params from (nullity 'PGtext)) where
467− mempty = fromString ""
470− (Expression outer commons grp schemas params from (null 'PGtsvector)) where
471 mempty = fromString ""
968 mempty = fromString ""
472 mappend = (<>)
969 mappend = (<>)
971+-- | >>> printSQL $ lower "ARRRGGG"
974+ :: Expression outer grp commons schemas params from (nullity 'PGtext)
975+ -- ^ string to lower case
976+ -> Expression outer grp commons schemas params from (nullity 'PGtext)
977+lower = unsafeFunction "lower"
979+-- | >>> printSQL $ upper "eeee"
982+ :: Expression outer grp commons schemas params from (nullity 'PGtext)
983+ -- ^ string to upper case
984+ -> Expression outer grp commons schemas params from (nullity 'PGtext)
985+upper = unsafeFunction "upper"
987+-- | >>> printSQL $ charLength "four"
988+-- char_length(E'four')
990+ :: Expression outer grp commons schemas params from (nullity 'PGtext)
991+ -- ^ string to measure
992+ -> Expression outer grp commons schemas params from (nullity 'PGint4)
993+charLength = unsafeFunction "char_length"
995+-- | The `like` expression returns true if the @string@ matches
996+-- the supplied @pattern@. If @pattern@ does not contain percent signs
997+-- or underscores, then the pattern only represents the string itself;
998+-- in that case `like` acts like the equals operator. An underscore (_)
999+-- in pattern stands for (matches) any single character; a percent sign (%)
1000+-- matches any sequence of zero or more characters.
1002+-- >>> printSQL $ "abc" `like` "a%"
1003+-- (E'abc' LIKE E'a%')
1005+ :: Expression outer grp commons schemas params from (nullity 'PGtext)
1007+ -> Expression outer grp commons schemas params from (nullity 'PGtext)
1009+ -> Expression outer grp commons schemas params from (nullity 'PGbool)
1010+like = unsafeBinaryOp "LIKE"
1012+-- | The key word ILIKE can be used instead of LIKE to make the
1013+-- match case-insensitive according to the active locale.
1015+-- >>> printSQL $ "abc" `ilike` "a%"
1016+-- (E'abc' ILIKE E'a%')
1018+ :: Expression outer grp commons schemas params from (nullity 'PGtext)
1020+ -> Expression outer grp commons schemas params from (nullity 'PGtext)
1022+ -> Expression outer grp commons schemas params from (nullity 'PGbool)
1023+ilike = unsafeBinaryOp "ILIKE"
1025+{-----------------------------------------
1026+ -- json and jsonb support
1028+See https://www.postgresql.org/docs/10/static/functions-json.html -- most
1029+comments lifted directly from this page.
1031+Table 9.44: json and jsonb operators
1032+-----------------------------------------}
1034+-- | Get JSON value (object field or array element) at a key.
1036+ :: (json `In` PGJsonType, key `In` PGJsonKey)
1037+ => Expression outer grp commons schemas params from (nullity json)
1038+ -> Expression outer grp commons schemas params from (nullity key)
1039+ -> Expression outer grp commons schemas params from ('Null json)
1041+(.->) = unsafeBinaryOp "->"
1043+-- | Get JSON value (object field or array element) at a key, as text.
1045+ :: (json `In` PGJsonType, key `In` PGJsonKey)
1046+ => Expression outer grp commons schemas params from (nullity json)
1047+ -> Expression outer grp commons schemas params from (nullity key)
1048+ -> Expression outer grp commons schemas params from ('Null 'PGtext)
1050+(.->>) = unsafeBinaryOp "->>"
1052+-- | Get JSON value at a specified path.
1054+ :: (json `In` PGJsonType, PGTextArray "(.#>)" path)
1055+ => Expression outer grp commons schemas params from (nullity json)
1056+ -> Expression outer grp commons schemas params from (nullity path)
1057+ -> Expression outer grp commons schemas params from ('Null json)
1059+(.#>) = unsafeBinaryOp "#>"
1061+-- | Get JSON value at a specified path as text.
1063+ :: (json `In` PGJsonType, PGTextArray "(.#>>)" path)
1064+ => Expression outer grp commons schemas params from (nullity json)
1065+ -> Expression outer grp commons schemas params from (nullity path)
1066+ -> Expression outer grp commons schemas params from ('Null 'PGtext)
1068+(.#>>) = unsafeBinaryOp "#>>"
1070+-- Additional jsonb operators
1072+-- | Does the left JSON value contain the right JSON path/value entries at the
1075+ :: Expression outer grp commons schemas params from (nullity 'PGjsonb)
1076+ -> Expression outer grp commons schemas params from (nullity 'PGjsonb)
1077+ -> Condition outer grp commons schemas params from
1079+(.@>) = unsafeBinaryOp "@>"
1081+-- | Are the left JSON path/value entries contained at the top level within the
1082+-- right JSON value?
1084+ :: Expression outer grp commons schemas params from (nullity 'PGjsonb)
1085+ -> Expression outer grp commons schemas params from (nullity 'PGjsonb)
1086+ -> Condition outer grp commons schemas params from
1088+(.<@) = unsafeBinaryOp "<@"
1090+-- | Does the string exist as a top-level key within the JSON value?
1092+ :: Expression outer grp commons schemas params from (nullity 'PGjsonb)
1093+ -> Expression outer grp commons schemas params from (nullity 'PGtext)
1094+ -> Condition outer grp commons schemas params from
1096+(.?) = unsafeBinaryOp "?"
1098+-- | Do any of these array strings exist as top-level keys?
1100+ :: Expression outer grp commons schemas params from (nullity 'PGjsonb)
1101+ -> Expression outer grp commons schemas params from (nullity ('PGvararray ('NotNull 'PGtext)))
1102+ -> Condition outer grp commons schemas params from
1104+(.?|) = unsafeBinaryOp "?|"
1106+-- | Do all of these array strings exist as top-level keys?
1108+ :: Expression outer grp commons schemas params from (nullity 'PGjsonb)
1109+ -> Expression outer grp commons schemas params from (nullity ('PGvararray ('NotNull 'PGtext)))
1110+ -> Condition outer grp commons schemas params from
1112+(.?&) = unsafeBinaryOp "?&"
1114+-- | Concatenate two jsonb values into a new jsonb value.
1116+ (Expression outer grp commons schemas params from (nullity 'PGjsonb)) where
1117+ (<>) = unsafeBinaryOp "||"
1119+-- | Delete a key or keys from a JSON object, or remove an array element.
1121+-- If the right operand is..
1123+-- @ text @: Delete key/value pair or string element from left operand. Key/value pairs
1124+-- are matched based on their key value.
1126+-- @ text[] @: Delete multiple key/value pairs or string elements
1127+-- from left operand. Key/value pairs are matched based on their key value.
1129+-- @ integer @: Delete the array element with specified index (Negative integers
1130+-- count from the end). Throws an error if top level container is not an array.
1132+ :: (key `In` '[ 'PGtext, 'PGvararray ('NotNull 'PGtext), 'PGint4, 'PGint2 ]) -- hlint error without parens here
1133+ => Expression outer grp commons schemas params from (nullity 'PGjsonb)
1134+ -> Expression outer grp commons schemas params from (nullity key)
1135+ -> Expression outer grp commons schemas params from (nullity 'PGjsonb)
1137+(.-.) = unsafeBinaryOp "-"
1139+-- | Delete the field or element with specified path (for JSON arrays, negative
1140+-- integers count from the end)
1142+ :: PGTextArray "(#-.)" arrayty
1143+ => Expression outer grp commons schemas params from (nullity 'PGjsonb)
1144+ -> Expression outer grp commons schemas params from (nullity arrayty)
1145+ -> Expression outer grp commons schemas params from (nullity 'PGjsonb)
1147+(#-.) = unsafeBinaryOp "#-"
1149+{-----------------------------------------
1150+Table 9.45: JSON creation functions
1151+-----------------------------------------}
1153+-- | Literal binary JSON
1156+ => x -> Expression outer grp commons schemas params from (nullity 'PGjsonb)
1157+jsonbLit = cast jsonb . UnsafeExpression
1158+ . singleQuotedUtf8 . toStrict . JSON.encode
1163+ => x -> Expression outer grp commons schemas params from (nullity 'PGjson)
1164+jsonLit = cast json . UnsafeExpression
1165+ . singleQuotedUtf8 . toStrict . JSON.encode
1167+-- | Returns the value as json. Arrays and composites are converted
1168+-- (recursively) to arrays and objects; otherwise, if there is a cast from the
1169+-- type to json, the cast function will be used to perform the conversion;
1170+-- otherwise, a scalar value is produced. For any scalar type other than a
1171+-- number, a Boolean, or a null value, the text representation will be used, in
1172+-- such a fashion that it is a valid json value.
1174+ :: Expression outer grp commons schemas params from (nullity ty)
1175+ -> Expression outer grp commons schemas params from (nullity 'PGjson)
1176+toJson = unsafeFunction "to_json"
1178+-- | Returns the value as jsonb. Arrays and composites are converted
1179+-- (recursively) to arrays and objects; otherwise, if there is a cast from the
1180+-- type to json, the cast function will be used to perform the conversion;
1181+-- otherwise, a scalar value is produced. For any scalar type other than a
1182+-- number, a Boolean, or a null value, the text representation will be used, in
1183+-- such a fashion that it is a valid jsonb value.
1185+ :: Expression outer grp commons schemas params from (nullity ty)
1186+ -> Expression outer grp commons schemas params from (nullity 'PGjsonb)
1187+toJsonb = unsafeFunction "to_jsonb"
1189+-- | Returns the array as a JSON array. A PostgreSQL multidimensional array
1190+-- becomes a JSON array of arrays.
1192+ :: PGArray "arrayToJson" arr
1193+ => Expression outer grp commons schemas params from (nullity arr)
1194+ -> Expression outer grp commons schemas params from (nullity 'PGjson)
1195+arrayToJson = unsafeFunction "array_to_json"
1197+-- | Returns the row as a JSON object.
1199+ :: Expression outer grp commons schemas params from (nullity ('PGcomposite ty))
1200+ -> Expression outer grp commons schemas params from (nullity 'PGjson)
1201+rowToJson = unsafeFunction "row_to_json"
1203+-- | Builds a possibly-heterogeneously-typed JSON array out of a variadic
1207+ => NP (Expression outer grp commons schemas params from) elems
1208+ -> Expression outer grp commons schemas params from (nullity 'PGjson)
1209+jsonBuildArray = unsafeVariadicFunction "json_build_array"
1211+-- | Builds a possibly-heterogeneously-typed (binary) JSON array out of a
1212+-- variadic argument list.
1215+ => NP (Expression outer grp commons schemas params from) elems
1216+ -> Expression outer grp commons schemas params from (nullity 'PGjsonb)
1217+jsonbBuildArray = unsafeVariadicFunction "jsonb_build_array"
1220+ :: SOP.SListI elems
1221+ => NP (Aliased (Expression outer grp commons schemas params from)) elems
1224+ (`appEndo` []) . hcfoldMap (Proxy :: SOP.Proxy SOP.Top)
1225+ (\(col `As` name) -> Endo $ \xs ->
1226+ renderAliasString name : renderSQL col : xs)
1228+ renderAliasString :: KnownSymbol alias => Alias alias -> ByteString
1229+ renderAliasString = singleQuotedText . fromString . symbolVal
1231+-- | Builds a possibly-heterogeneously-typed JSON object out of a variadic
1232+-- argument list. The elements of the argument list must alternate between text
1235+ :: SOP.SListI elems
1236+ => NP (Aliased (Expression outer grp commons schemas params from)) elems
1237+ -> Expression outer grp commons schemas params from (nullity 'PGjson)
1239+ = unsafeFunction "json_build_object"
1242+ . unsafeRowFunction
1244+-- | Builds a possibly-heterogeneously-typed (binary) JSON object out of a
1245+-- variadic argument list. The elements of the argument list must alternate
1246+-- between text and values.
1248+ :: SOP.SListI elems
1249+ => NP (Aliased (Expression outer grp commons schemas params from)) elems
1250+ -> Expression outer grp commons schemas params from (nullity 'PGjsonb)
1252+ = unsafeFunction "jsonb_build_object"
1255+ . unsafeRowFunction
1257+-- | Builds a JSON object out of a text array. The array must have either
1258+-- exactly one dimension with an even number of members, in which case they are
1259+-- taken as alternating key/value pairs, or two dimensions such that each inner
1260+-- array has exactly two elements, which are taken as a key/value pair.
1262+ :: PGArrayOf "jsonObject" arr ('NotNull 'PGtext)
1263+ => Expression outer grp commons schemas params from (nullity arr)
1264+ -> Expression outer grp commons schemas params from (nullity 'PGjson)
1265+jsonObject = unsafeFunction "json_object"
1267+-- | Builds a binary JSON object out of a text array. The array must have either
1268+-- exactly one dimension with an even number of members, in which case they are
1269+-- taken as alternating key/value pairs, or two dimensions such that each inner
1270+-- array has exactly two elements, which are taken as a key/value pair.
1272+ :: PGArrayOf "jsonbObject" arr ('NotNull 'PGtext)
1273+ => Expression outer grp commons schemas params from (nullity arr)
1274+ -> Expression outer grp commons schemas params from (nullity 'PGjsonb)
1275+jsonbObject = unsafeFunction "jsonb_object"
1277+-- | This is an alternate form of 'jsonObject' that takes two arrays; one for
1278+-- keys and one for values, that are zipped pairwise to create a JSON object.
1280+ :: ( PGArrayOf "jsonZipObject" keysArray ('NotNull 'PGtext)
1281+ , PGArrayOf "jsonZipObject" valuesArray ('NotNull 'PGtext))
1282+ => Expression outer grp commons schemas params from (nullity keysArray)
1283+ -> Expression outer grp commons schemas params from (nullity valuesArray)
1284+ -> Expression outer grp commons schemas params from (nullity 'PGjson)
1285+jsonZipObject ks vs =
1286+ unsafeVariadicFunction "json_object" (ks :* vs :* Nil)
1288+-- | This is an alternate form of 'jsonObject' that takes two arrays; one for
1289+-- keys and one for values, that are zipped pairwise to create a binary JSON
1292+ :: ( PGArrayOf "jsonbZipObject" keysArray ('NotNull 'PGtext)
1293+ , PGArrayOf "jsonbZipObject" valuesArray ('NotNull 'PGtext))
1294+ => Expression outer grp commons schemas params from (nullity keysArray)
1295+ -> Expression outer grp commons schemas params from (nullity valuesArray)
1296+ -> Expression outer grp commons schemas params from (nullity 'PGjsonb)
1297+jsonbZipObject ks vs =
1298+ unsafeVariadicFunction "jsonb_object" (ks :* vs :* Nil)
1300+{-----------------------------------------
1301+Table 9.46: JSON processing functions
1302+-----------------------------------------}
1304+-- | Returns the number of elements in the outermost JSON array.
1306+ :: Expression outer grp commons schemas params from (nullity 'PGjson)
1307+ -> Expression outer grp commons schemas params from (nullity 'PGint4)
1308+jsonArrayLength = unsafeFunction "json_array_length"
1310+-- | Returns the number of elements in the outermost binary JSON array.
1312+ :: Expression outer grp commons schemas params from (nullity 'PGjsonb)
1313+ -> Expression outer grp commons schemas params from (nullity 'PGint4)
1314+jsonbArrayLength = unsafeFunction "jsonb_array_length"
1316+-- | Returns JSON value pointed to by the given path (equivalent to #>
1320+ => Expression outer grp commons schemas params from (nullity 'PGjson)
1321+ -> NP (Expression outer grp commons schemas params from) elems
1322+ -> Expression outer grp commons schemas params from (nullity 'PGjsonb)
1323+jsonExtractPath x xs =
1324+ unsafeVariadicFunction "json_extract_path" (x :* xs)
1326+-- | Returns JSON value pointed to by the given path (equivalent to #>
1330+ => Expression outer grp commons schemas params from (nullity 'PGjsonb)
1331+ -> NP (Expression outer grp commons schemas params from) elems
1332+ -> Expression outer grp commons schemas params from (nullity 'PGjsonb)
1333+jsonbExtractPath x xs =
1334+ unsafeVariadicFunction "jsonb_extract_path" (x :* xs)
1336+-- | Returns JSON value pointed to by the given path (equivalent to #>
1337+-- operator), as text.
1338+jsonExtractPathAsText
1340+ => Expression outer grp commons schemas params from (nullity 'PGjson)
1341+ -> NP (Expression outer grp commons schemas params from) elems
1342+ -> Expression outer grp commons schemas params from (nullity 'PGjson)
1343+jsonExtractPathAsText x xs =
1344+ unsafeVariadicFunction "json_extract_path_text" (x :* xs)
1346+-- | Returns JSON value pointed to by the given path (equivalent to #>
1347+-- operator), as text.
1348+jsonbExtractPathAsText
1350+ => Expression outer grp commons schemas params from (nullity 'PGjsonb)
1351+ -> NP (Expression outer grp commons schemas params from) elems
1352+ -> Expression outer grp commons schemas params from (nullity 'PGjsonb)
1353+jsonbExtractPathAsText x xs =
1354+ unsafeVariadicFunction "jsonb_extract_path_text" (x :* xs)
1356+-- | Returns the type of the outermost JSON value as a text string. Possible
1357+-- types are object, array, string, number, boolean, and null.
1359+ :: Expression outer grp commons schemas params from (nullity 'PGjson)
1360+ -> Expression outer grp commons schemas params from (nullity 'PGtext)
1361+jsonTypeof = unsafeFunction "json_typeof"
1363+-- | Returns the type of the outermost binary JSON value as a text string.
1364+-- Possible types are object, array, string, number, boolean, and null.
1366+ :: Expression outer grp commons schemas params from (nullity 'PGjsonb)
1367+ -> Expression outer grp commons schemas params from (nullity 'PGtext)
1368+jsonbTypeof = unsafeFunction "jsonb_typeof"
1370+-- | Returns its argument with all object fields that have null values omitted.
1371+-- Other null values are untouched.
1373+ :: Expression outer grp commons schemas params from (nullity 'PGjson)
1374+ -> Expression outer grp commons schemas params from (nullity 'PGjson)
1375+jsonStripNulls = unsafeFunction "json_strip_nulls"
1377+-- | Returns its argument with all object fields that have null values omitted.
1378+-- Other null values are untouched.
1380+ :: Expression outer grp commons schemas params from (nullity 'PGjsonb)
1381+ -> Expression outer grp commons schemas params from (nullity 'PGjsonb)
1382+jsonbStripNulls = unsafeFunction "jsonb_strip_nulls"
1384+-- | @ jsonbSet target path new_value create_missing @
1386+-- Returns target with the section designated by path replaced by new_value,
1387+-- or with new_value added if create_missing is true ( default is true) and the
1388+-- item designated by path does not exist. As with the path orientated
1389+-- operators, negative integers that appear in path count from the end of JSON
1392+ :: PGTextArray "jsonbSet" arr
1393+ => Expression outer grp commons schemas params from (nullity 'PGjsonb)
1394+ -> Expression outer grp commons schemas params from (nullity arr)
1395+ -> Expression outer grp commons schemas params from (nullity 'PGjsonb)
1396+ -> Maybe (Expression outer grp commons schemas params from (nullity 'PGbool))
1397+ -> Expression outer grp commons schemas params from (nullity 'PGjsonb)
1398+jsonbSet tgt path val createMissing = case createMissing of
1399+ Just m -> unsafeVariadicFunction "jsonb_set" (tgt :* path :* val :* m :* Nil)
1400+ Nothing -> unsafeVariadicFunction "jsonb_set" (tgt :* path :* val :* Nil)
1402+-- | @ jsonbInsert target path new_value insert_after @
1404+-- Returns target with new_value inserted. If target section designated by
1405+-- path is in a JSONB array, new_value will be inserted before target or after
1406+-- if insert_after is true (default is false). If target section designated by
1407+-- path is in JSONB object, new_value will be inserted only if target does not
1408+-- exist. As with the path orientated operators, negative integers that appear
1409+-- in path count from the end of JSON arrays.
1411+ :: PGTextArray "jsonbInsert" arr
1412+ => Expression outer grp commons schemas params from (nullity 'PGjsonb)
1413+ -> Expression outer grp commons schemas params from (nullity arr)
1414+ -> Expression outer grp commons schemas params from (nullity 'PGjsonb)
1415+ -> Maybe (Expression outer grp commons schemas params from (nullity 'PGbool))
1416+ -> Expression outer grp commons schemas params from (nullity 'PGjsonb)
1417+jsonbInsert tgt path val insertAfter = case insertAfter of
1418+ Just i -> unsafeVariadicFunction "jsonb_insert" (tgt :* path :* val :* i :* Nil)
1419+ Nothing -> unsafeVariadicFunction "jsonb_insert" (tgt :* path :* val :* Nil)
1421+-- | Returns its argument as indented JSON text.
1423+ :: Expression outer grp commons schemas params from (nullity 'PGjsonb)
1424+ -> Expression outer grp commons schemas params from (nullity 'PGtext)
1425+jsonbPretty = unsafeFunction "jsonb_pretty"
1427+{-----------------------------------------
1429+-----------------------------------------}
1432+`Aggregate` functions compute a single result from a set of input values.
1433+`Aggregate` functions can be used as `GroupedBy` `Expression`s as well
1434+as `WindowFunction`s.
1436+class Aggregate expr1 expr2 aggr
1437+ | aggr -> expr1, aggr -> expr2 where
1439+ -- | A special aggregation that does not require an input
1443+ -- expression :: Expression '[] ('Grouped bys) commons schemas params from ('NotNull 'PGint8)
1444+ -- expression = countStar
1445+ -- in printSQL expression
1448+ countStar :: aggr ('NotNull 'PGint8)
1452+ -- expression :: Expression '[] ('Grouped bys) commons schemas params '[tab ::: '["col" ::: nullity ty]] ('NotNull 'PGint8)
1453+ -- expression = count (All #col)
1454+ -- in printSQL expression
1456+ -- count(ALL "col")
1460+ -> aggr ('NotNull 'PGint8)
1464+ -- expression :: Expression '[] ('Grouped bys) commons schemas params '[tab ::: '["col" ::: 'Null 'PGnumeric]] ('NotNull 'PGnumeric)
1465+ -- expression = sum_ (Distinct #col)
1466+ -- in printSQL expression
1468+ -- sum(DISTINCT "col")
1471+ => expr1 (nullity ty)
1472+ -> aggr ('NotNull ty)
1474+ -- | input values, including nulls, concatenated into an array
1477+ -> aggr ('Null ('PGvararray ty))
1479+ -- | aggregates values as a JSON array
1482+ -> aggr ('Null 'PGjson)
1484+ -- | aggregates values as a JSON array
1487+ -> aggr ('Null 'PGjsonb)
1490+ the bitwise AND of all non-null input values, or null if none
1493+ expression :: Expression '[] ('Grouped bys) commons schemas params '[tab ::: '["col" ::: nullity 'PGint4]] ('Null 'PGint4)
1494+ expression = bitAnd (Distinct #col)
1495+ in printSQL expression
1497+ bit_and(DISTINCT "col")
1500+ :: int `In` PGIntegral
1501+ => expr1 (nullity int)
1502+ -- ^ what to aggregate
1503+ -> aggr ('Null int)
1506+ the bitwise OR of all non-null input values, or null if none
1510+ expression :: Expression '[] ('Grouped bys) commons schemas params '[tab ::: '["col" ::: nullity 'PGint4]] ('Null 'PGint4)
1511+ expression = bitOr (All #col)
1512+ in printSQL expression
1517+ :: int `In` PGIntegral
1518+ => expr1 (nullity int)
1519+ -- ^ what to aggregate
1520+ -> aggr ('Null int)
1523+ true if all input values are true, otherwise false
1527+ winFun :: WindowFunction '[] 'Ungrouped commons schemas params '[tab ::: '["col" ::: nullity 'PGbool]] ('Null 'PGbool)
1528+ winFun = boolAnd #col
1534+ :: expr1 (nullity 'PGbool)
1535+ -- ^ what to aggregate
1536+ -> aggr ('Null 'PGbool)
1539+ true if at least one input value is true, otherwise false
1543+ expression :: Expression '[] ('Grouped bys) commons schemas params '[tab ::: '["col" ::: nullity 'PGbool]] (nullity 'PGbool)
1544+ expression = boolOr (All #col)
1545+ in printSQL expression
1550+ :: expr1(nullity 'PGbool)
1551+ -- ^ what to aggregate
1552+ -> aggr ('Null 'PGbool)
1555+ equivalent to `boolAnd`
1559+ expression :: Expression '[] ('Grouped bys) commons schemas params '[tab ::: '["col" ::: nullity 'PGbool]] (nullity 'PGbool)
1560+ expression = every (Distinct #col)
1561+ in printSQL expression
1563+ every(DISTINCT "col")
1566+ :: expr1 (nullity 'PGbool)
1567+ -- ^ what to aggregate
1568+ -> aggr ('Null 'PGbool)
1570+ {- |maximum value of expression across all input values-}
1572+ :: expr1 (nullity ty)
1573+ -- ^ what to maximize
1576+ -- | minimum value of expression across all input values
1578+ :: expr1 (nullity ty)
1579+ -- ^ what to minimize
1582+ -- | the average (arithmetic mean) of all input values
1584+ :: expr1 (nullity ty)
1585+ -- ^ what to average
1586+ -> aggr ('Null (PGAvg ty))
1588+ {- | correlation coefficient
1591+ expression :: Expression '[] ('Grouped g) c s p '[t ::: '["x" ::: 'NotNull 'PGfloat8, "y" ::: 'NotNull 'PGfloat8]] ('NotNull 'PGfloat8)
1592+ expression = corr (All (#y :*: #x))
1593+ in printSQL expression
1598+ :: expr2 (nullity 'PGfloat8)
1599+ -> aggr ('Null 'PGfloat8)
1601+ {- | population covariance
1604+ expression :: Expression '[] ('Grouped g) c s p '[t ::: '["x" ::: 'NotNull 'PGfloat8, "y" ::: 'NotNull 'PGfloat8]] ('NotNull 'PGfloat8)
1605+ expression = covarPop (All (#y :*: #x))
1606+ in printSQL expression
1608+ covar_pop(ALL "y", "x")
1611+ :: expr2 (nullity 'PGfloat8)
1612+ -> aggr ('Null 'PGfloat8)
1614+ {- | sample covariance
1617+ winFun :: WindowFunction '[] 'Ungrouped c s p '[t ::: '["x" ::: 'NotNull 'PGfloat8, "y" ::: 'NotNull 'PGfloat8]] ('NotNull 'PGfloat8)
1618+ winFun = covarSamp (#y :*: #x)
1621+ covar_samp("y", "x")
1624+ :: expr2 (nullity 'PGfloat8)
1625+ -> aggr ('Null 'PGfloat8)
1627+ {- | average of the independent variable (sum(X)/N)
1630+ expression :: Expression '[] ('Grouped g) c s p '[t ::: '["x" ::: 'NotNull 'PGfloat8, "y" ::: 'NotNull 'PGfloat8]] ('NotNull 'PGfloat8)
1631+ expression = regrAvgX (All (#y :*: #x))
1632+ in printSQL expression
1634+ regr_avgx(ALL "y", "x")
1637+ :: expr2 (nullity 'PGfloat8)
1638+ -> aggr ('Null 'PGfloat8)
1640+ {- | average of the dependent variable (sum(Y)/N)
1643+ winFun :: WindowFunction '[] 'Ungrouped c s p '[t ::: '["x" ::: 'NotNull 'PGfloat8, "y" ::: 'NotNull 'PGfloat8]] ('NotNull 'PGfloat8)
1644+ winFun = regrAvgY (#y :*: #x)
1647+ regr_avgy("y", "x")
1650+ :: expr2 (nullity 'PGfloat8)
1651+ -> aggr ('Null 'PGfloat8)
1653+ {- | number of input rows in which both expressions are nonnull
1656+ winFun :: WindowFunction '[] 'Ungrouped c s p '[t ::: '["x" ::: 'NotNull 'PGfloat8, "y" ::: 'NotNull 'PGfloat8]] ('NotNull 'PGint8)
1657+ winFun = regrCount (#y :*: #x)
1660+ regr_count("y", "x")
1663+ :: expr2 (nullity 'PGfloat8)
1664+ -> aggr ('Null 'PGint8)
1666+ {- | y-intercept of the least-squares-fit linear equation determined by the (X, Y) pairs
1669+ expression :: Expression '[] ('Grouped g) c s p '[t ::: '["x" ::: 'NotNull 'PGfloat8, "y" ::: 'NotNull 'PGfloat8]] ('NotNull 'PGfloat8)
1670+ expression = regrIntercept (All (#y :*: #x))
1671+ in printSQL expression
1673+ regr_intercept(ALL "y", "x")
1676+ :: expr2 (nullity 'PGfloat8)
1677+ -> aggr ('Null 'PGfloat8)
1679+ -- | @regr_r2(Y, X)@, square of the correlation coefficient
1681+ :: expr2 (nullity 'PGfloat8)
1682+ -> aggr ('Null 'PGfloat8)
1684+ -- | @regr_slope(Y, X)@, slope of the least-squares-fit linear equation
1685+ -- determined by the (X, Y) pairs
1687+ :: expr2 (nullity 'PGfloat8)
1688+ -> aggr ('Null 'PGfloat8)
1690+ -- | @regr_sxx(Y, X)@, sum(X^2) - sum(X)^2/N
1691+ -- (“sum of squares” of the independent variable)
1693+ :: expr2 (nullity 'PGfloat8)
1694+ -> aggr ('Null 'PGfloat8)
1696+ -- | @regr_sxy(Y, X)@, sum(X*Y) - sum(X) * sum(Y)/N
1697+ -- (“sum of products” of independent times dependent variable)
1699+ :: expr2 (nullity 'PGfloat8)
1700+ -> aggr ('Null 'PGfloat8)
1702+ -- | @regr_syy(Y, X)@, sum(Y^2) - sum(Y)^2/N
1703+ -- (“sum of squares” of the dependent variable)
1705+ :: expr2 (nullity 'PGfloat8)
1706+ -> aggr ('Null 'PGfloat8)
1708+ -- | historical alias for `stddevSamp`
1710+ :: expr1 (nullity ty)
1711+ -> aggr ('Null (PGAvg ty))
1713+ -- | population standard deviation of the input values
1715+ :: expr1 (nullity ty)
1716+ -> aggr ('Null (PGAvg ty))
1718+ -- | sample standard deviation of the input values
1720+ :: expr1 (nullity ty)
1721+ -> aggr ('Null (PGAvg ty))
1723+ -- | historical alias for `varSamp`
1725+ :: expr1 (nullity ty)
1726+ -> aggr ('Null (PGAvg ty))
1728+ -- | population variance of the input values
1729+ -- (square of the population standard deviation)
1731+ :: expr1 (nullity ty)
1732+ -> aggr ('Null (PGAvg ty))
1734+ -- | sample variance of the input values
1735+ -- (square of the sample standard deviation)
1737+ :: expr1 (nullity ty)
1738+ -> aggr ('Null (PGAvg ty))
1741+`Distinction`s are used for the input of `Aggregate` `Expression`s.
1742+`All` invokes the aggregate once for each input row.
1743+`Distinct` invokes the aggregate once for each distinct value of the expression
1744+(or distinct set of values, for multiple expressions) found in the input
1746+data Distinction expr ty
1748+ | Distinct (expr ty)
1749+ deriving (GHC.Generic,Show,Eq,Ord)
1750+instance NFData (Distinction (Expression outer grp commons schemas params from) ty)
1751+instance RenderSQL (Distinction (Expression outer grp commons schemas params from) ty) where
1753+ All x -> "ALL" <+> renderSQL x
1754+ Distinct x -> "DISTINCT" <+> renderSQL x
1757+ ( Expression outer grp commons schemas params from
1759+ Expression outer grp commons schemas params from) xty ) where
1762+ "ALL" <+> renderSQL x <> ", " <> renderSQL x'
1763+ Distinct (x :*: x') ->
1764+ "DISTINCT" <+> renderSQL x <> ", " <> renderSQL x'
1767+ (Distinction (Expression outer 'Ungrouped commons schemas params from))
1768+ (Distinction (Expression outer 'Ungrouped commons schemas params from :*: Expression outer 'Ungrouped commons schemas params from))
1769+ (Expression outer ('Grouped bys) commons schemas params from) where
1770+ countStar = UnsafeExpression "count(*)"
1771+ count = unsafeAggregate1 "count"
1772+ sum_ = unsafeAggregate1 "sum"
1773+ arrayAgg = unsafeAggregate1 "array_agg"
1774+ jsonAgg = unsafeAggregate1 "json_agg"
1775+ jsonbAgg = unsafeAggregate1 "jsonb_agg"
1776+ bitAnd = unsafeAggregate1 "bit_and"
1777+ bitOr = unsafeAggregate1 "bit_or"
1778+ boolAnd = unsafeAggregate1 "bool_and"
1779+ boolOr = unsafeAggregate1 "bool_or"
1780+ every = unsafeAggregate1 "every"
1781+ max_ = unsafeAggregate1 "max"
1782+ min_ = unsafeAggregate1 "min"
1783+ avg = unsafeAggregate1 "avg"
1784+ corr = unsafeAggregate2 "corr"
1785+ covarPop = unsafeAggregate2 "covar_pop"
1786+ covarSamp = unsafeAggregate2 "covar_samp"
1787+ regrAvgX = unsafeAggregate2 "regr_avgx"
1788+ regrAvgY = unsafeAggregate2 "regr_avgy"
1789+ regrCount = unsafeAggregate2 "regr_count"
1790+ regrIntercept = unsafeAggregate2 "regr_intercept"
1791+ regrR2 = unsafeAggregate2 "regr_r2"
1792+ regrSlope = unsafeAggregate2 "regr_slope"
1793+ regrSxx = unsafeAggregate2 "regr_sxx"
1794+ regrSxy = unsafeAggregate2 "regr_sxy"
1795+ regrSyy = unsafeAggregate2 "regr_syy"
1796+ stddev = unsafeAggregate1 "stddev"
1797+ stddevPop = unsafeAggregate1 "stddev_pop"
1798+ stddevSamp = unsafeAggregate1 "stddev_samp"
1799+ variance = unsafeAggregate1 "variance"
1800+ varPop = unsafeAggregate1 "var_pop"
1801+ varSamp = unsafeAggregate1 "var_samp"
1803+ (Expression outer grp commons schemas params from)
1804+ (Expression outer grp commons schemas params from :*: Expression outer grp commons schemas params from)
1805+ (WindowFunction outer grp commons schemas params from) where
1806+ countStar = UnsafeWindowFunction "count(*)"
1807+ count = unsafeWindowFunction1 "count"
1808+ sum_ = unsafeWindowFunction1 "sum"
1809+ arrayAgg = unsafeWindowFunction1 "array_agg"
1810+ jsonAgg = unsafeWindowFunction1 "json_agg"
1811+ jsonbAgg = unsafeWindowFunction1 "jsonb_agg"
1812+ bitAnd = unsafeWindowFunction1 "bit_and"
1813+ bitOr = unsafeWindowFunction1 "bit_or"
1814+ boolAnd = unsafeWindowFunction1 "bool_and"
1815+ boolOr = unsafeWindowFunction1 "bool_or"
1816+ every = unsafeWindowFunction1 "every"
1817+ max_ = unsafeWindowFunction1 "max"
1818+ min_ = unsafeWindowFunction1 "min"
1819+ avg = unsafeWindowFunction1 "avg"
1820+ corr = unsafeWindowFunction2 "corr"
1821+ covarPop = unsafeWindowFunction2 "covar_pop"
1822+ covarSamp = unsafeWindowFunction2 "covar_samp"
1823+ regrAvgX = unsafeWindowFunction2 "regr_avgx"
1824+ regrAvgY = unsafeWindowFunction2 "regr_avgy"
1825+ regrCount = unsafeWindowFunction2 "regr_count"
1826+ regrIntercept = unsafeWindowFunction2 "regr_intercept"
1827+ regrR2 = unsafeWindowFunction2 "regr_r2"
1828+ regrSlope = unsafeWindowFunction2 "regr_slope"
1829+ regrSxx = unsafeWindowFunction2 "regr_sxx"
1830+ regrSxy = unsafeWindowFunction2 "regr_sxy"
1831+ regrSyy = unsafeWindowFunction2 "regr_syy"
1832+ stddev = unsafeWindowFunction1 "stddev"
1833+ stddevPop = unsafeWindowFunction1 "stddev_pop"
1834+ stddevSamp = unsafeWindowFunction1 "stddev_samp"
1835+ variance = unsafeWindowFunction1 "variance"
1836+ varPop = unsafeWindowFunction1 "var_pop"
1837+ varSamp = unsafeWindowFunction1 "var_samp"
1839+-- | escape hatch to define aggregate functions
1841+ :: ByteString -- ^ aggregate function
1842+ -> Distinction (Expression outer 'Ungrouped commons schemas params from) xty
1843+ -> Expression outer ('Grouped bys) commons schemas params from yty
1844+unsafeAggregate1 fun x = UnsafeExpression $ mconcat
1845+ [fun, "(", renderSQL x, ")"]
1847+-- | escape hatch to define aggregate binary functions
1849+ :: ByteString -- ^ aggregate function
1850+ -> Distinction (Expression outer 'Ungrouped commons schemas params from :*: Expression outer 'Ungrouped commons schemas params from) xty
1851+ -> Expression outer ('Grouped bys) commons schemas params from yty
1852+unsafeAggregate2 fun xx = UnsafeExpression $ mconcat
1853+ [fun, "(", renderSQL xx, ")"]
1855+-- | A type family that calculates `PGAvg` type of a `PGType`.
1856+type family PGAvg ty where
1857+ PGAvg 'PGint2 = 'PGnumeric
1858+ PGAvg 'PGint4 = 'PGnumeric
1859+ PGAvg 'PGint8 = 'PGnumeric
1860+ PGAvg 'PGnumeric = 'PGnumeric
1861+ PGAvg 'PGfloat4 = 'PGfloat8
1862+ PGAvg 'PGfloat8 = 'PGfloat8
1863+ PGAvg 'PGinterval = 'PGinterval
1864+ PGAvg pg = TypeError
1865+ ('Text "Squeal type error: No average for " ':<>: 'ShowType pg)
1867+{-----------------------------------------
1869+-----------------------------------------}
1871+-- | `TypeExpression`s are used in `cast`s and
1872+-- `Squeal.PostgreSQL.Definition.createTable` commands.
1873+newtype TypeExpression (schemas :: SchemasType) (ty :: NullityType)
1874+ = UnsafeTypeExpression { renderTypeExpression :: ByteString }
1875+ deriving (GHC.Generic,Show,Eq,Ord,NFData)
1876+instance RenderSQL (TypeExpression schemas ty) where
1877+ renderSQL = renderTypeExpression
1879+-- | The enum or composite type in a `Typedef` can be expressed by its alias.
1881+ :: (Has sch schemas schema, Has td schema ('Typedef ty))
1882+ => QualifiedAlias sch td
1883+ -> TypeExpression schemas (nullity ty)
1884+typedef = UnsafeTypeExpression . renderSQL
1886+-- | The composite type corresponding to a `Table` definition can be expressed
1889+ :: (Has sch schemas schema, Has tab schema ('Table table))
1890+ => QualifiedAlias sch tab
1891+ -> TypeExpression schemas (nullity ('PGcomposite (TableToRow table)))
1892+typetable = UnsafeTypeExpression . renderSQL
1894+-- | The composite type corresponding to a `View` definition can be expressed
1897+ :: (Has sch schemas schema, Has vw schema ('View view))
1898+ => QualifiedAlias sch vw
1899+ -> TypeExpression schemas (nullity ('PGcomposite view))
1900+typeview = UnsafeTypeExpression . renderSQL
1902+-- | logical Boolean (true/false)
1903+bool :: TypeExpression schemas (nullity 'PGbool)
1904+bool = UnsafeTypeExpression "bool"
1905+-- | signed two-byte integer
1906+int2, smallint :: TypeExpression schemas (nullity 'PGint2)
1907+int2 = UnsafeTypeExpression "int2"
1908+smallint = UnsafeTypeExpression "smallint"
1909+-- | signed four-byte integer
1910+int4, int, integer :: TypeExpression schemas (nullity 'PGint4)
1911+int4 = UnsafeTypeExpression "int4"
1912+int = UnsafeTypeExpression "int"
1913+integer = UnsafeTypeExpression "integer"
1914+-- | signed eight-byte integer
1915+int8, bigint :: TypeExpression schemas (nullity 'PGint8)
1916+int8 = UnsafeTypeExpression "int8"
1917+bigint = UnsafeTypeExpression "bigint"
1918+-- | arbitrary precision numeric type
1919+numeric :: TypeExpression schemas (nullity 'PGnumeric)
1920+numeric = UnsafeTypeExpression "numeric"
1921+-- | single precision floating-point number (4 bytes)
1922+float4, real :: TypeExpression schemas (nullity 'PGfloat4)
1923+float4 = UnsafeTypeExpression "float4"
1924+real = UnsafeTypeExpression "real"
1925+-- | double precision floating-point number (8 bytes)
1926+float8, doublePrecision :: TypeExpression schemas (nullity 'PGfloat8)
1927+float8 = UnsafeTypeExpression "float8"
1928+doublePrecision = UnsafeTypeExpression "double precision"
1929+-- | variable-length character string
1930+text :: TypeExpression schemas (nullity 'PGtext)
1931+text = UnsafeTypeExpression "text"
1932+-- | fixed-length character string
1934+ :: forall n schemas nullity. (KnownNat n, 1 <= n)
1935+ => TypeExpression schemas (nullity ('PGchar n))
1936+char = UnsafeTypeExpression $ "char(" <> renderNat @n <> ")"
1937+character = UnsafeTypeExpression $ "character(" <> renderNat @n <> ")"
1938+-- | variable-length character string
1939+varchar, characterVarying
1940+ :: forall n schemas nullity. (KnownNat n, 1 <= n)
1941+ => TypeExpression schemas (nullity ('PGvarchar n))
1942+varchar = UnsafeTypeExpression $ "varchar(" <> renderNat @n <> ")"
1943+characterVarying = UnsafeTypeExpression $
1944+ "character varying(" <> renderNat @n <> ")"
1945+-- | binary data ("byte array")
1946+bytea :: TypeExpression schemas (nullity 'PGbytea)
1947+bytea = UnsafeTypeExpression "bytea"
1948+-- | date and time (no time zone)
1949+timestamp :: TypeExpression schemas (nullity 'PGtimestamp)
1950+timestamp = UnsafeTypeExpression "timestamp"
1951+-- | date and time, including time zone
1952+timestampWithTimeZone :: TypeExpression schemas (nullity 'PGtimestamptz)
1953+timestampWithTimeZone = UnsafeTypeExpression "timestamp with time zone"
1954+-- | calendar date (year, month, day)
1955+date :: TypeExpression schemas (nullity 'PGdate)
1956+date = UnsafeTypeExpression "date"
1957+-- | time of day (no time zone)
1958+time :: TypeExpression schemas (nullity 'PGtime)
1959+time = UnsafeTypeExpression "time"
1960+-- | time of day, including time zone
1961+timeWithTimeZone :: TypeExpression schemas (nullity 'PGtimetz)
1962+timeWithTimeZone = UnsafeTypeExpression "time with time zone"
1964+interval :: TypeExpression schemas (nullity 'PGinterval)
1965+interval = UnsafeTypeExpression "interval"
1966+-- | universally unique identifier
1967+uuid :: TypeExpression schemas (nullity 'PGuuid)
1968+uuid = UnsafeTypeExpression "uuid"
1969+-- | IPv4 or IPv6 host address
1970+inet :: TypeExpression schemas (nullity 'PGinet)
1971+inet = UnsafeTypeExpression "inet"
1972+-- | textual JSON data
1973+json :: TypeExpression schemas (nullity 'PGjson)
1974+json = UnsafeTypeExpression "json"
1975+-- | binary JSON data, decomposed
1976+jsonb :: TypeExpression schemas (nullity 'PGjsonb)
1977+jsonb = UnsafeTypeExpression "jsonb"
1978+-- | variable length array
1980+ :: TypeExpression schemas pg
1981+ -> TypeExpression schemas (nullity ('PGvararray pg))
1982+vararray ty = UnsafeTypeExpression $ renderSQL ty <> "[]"
1983+-- | fixed length array
1985+-- >>> renderSQL (fixarray @'[2] json)
1988+ :: forall dims schemas nullity pg. SOP.All KnownNat dims
1989+ => TypeExpression schemas pg
1990+ -> TypeExpression schemas (nullity ('PGfixarray dims pg))
1991+fixarray ty = UnsafeTypeExpression $
1992+ renderSQL ty <> renderDims @dims
1994+ renderDims :: forall ns. SOP.All KnownNat ns => ByteString
1998+ . ByteString.intercalate "]["
2000+ $ hcmap (SOP.Proxy @KnownNat)
2001+ (K . fromString . show . natVal)
2002+ (hpure SOP.Proxy :: NP SOP.Proxy ns)
2004+-- | `pgtype` is a demoted version of a `PGType`
2005+class PGTyped schemas (ty :: NullityType) where
2006+ pgtype :: TypeExpression schemas ty
2007+instance PGTyped schemas (nullity 'PGbool) where pgtype = bool
2008+instance PGTyped schemas (nullity 'PGint2) where pgtype = int2
2009+instance PGTyped schemas (nullity 'PGint4) where pgtype = int4
2010+instance PGTyped schemas (nullity 'PGint8) where pgtype = int8
2011+instance PGTyped schemas (nullity 'PGnumeric) where pgtype = numeric
2012+instance PGTyped schemas (nullity 'PGfloat4) where pgtype = float4
2013+instance PGTyped schemas (nullity 'PGfloat8) where pgtype = float8
2014+instance PGTyped schemas (nullity 'PGtext) where pgtype = text
2015+instance (KnownNat n, 1 <= n)
2016+ => PGTyped schemas (nullity ('PGchar n)) where pgtype = char @n
2017+instance (KnownNat n, 1 <= n)
2018+ => PGTyped schemas (nullity ('PGvarchar n)) where pgtype = varchar @n
2019+instance PGTyped schemas (nullity 'PGbytea) where pgtype = bytea
2020+instance PGTyped schemas (nullity 'PGtimestamp) where pgtype = timestamp
2021+instance PGTyped schemas (nullity 'PGtimestamptz) where pgtype = timestampWithTimeZone
2022+instance PGTyped schemas (nullity 'PGdate) where pgtype = date
2023+instance PGTyped schemas (nullity 'PGtime) where pgtype = time
2024+instance PGTyped schemas (nullity 'PGtimetz) where pgtype = timeWithTimeZone
2025+instance PGTyped schemas (nullity 'PGinterval) where pgtype = interval
2026+instance PGTyped schemas (nullity 'PGuuid) where pgtype = uuid
2027+instance PGTyped schemas (nullity 'PGjson) where pgtype = json
2028+instance PGTyped schemas (nullity 'PGjsonb) where pgtype = jsonb
2029+instance PGTyped schemas ty
2030+ => PGTyped schemas (nullity ('PGvararray ty)) where
2031+ pgtype = vararray (pgtype @schemas @ty)
2032+instance (SOP.All KnownNat dims, PGTyped schemas ty)
2033+ => PGTyped schemas (nullity ('PGfixarray dims ty)) where
2034+ pgtype = fixarray @dims (pgtype @schemas @ty)
2036+{-----------------------------------------
2038+-----------------------------------------}
2040+-- | `SortExpression`s are used by `orderBy` to optionally sort the results
2041+-- of a `Squeal.PostgreSQL.Query.Query`. `Asc` or `Desc`
2042+-- set the sort direction of a `NotNull` result
2043+-- column to ascending or descending. Ascending order puts smaller values
2044+-- first, where "smaller" is defined in terms of the `.<` operator. Similarly,
2045+-- descending order is determined with the `.>` operator. `AscNullsFirst`,
2046+-- `AscNullsLast`, `DescNullsFirst` and `DescNullsLast` options are used to
2047+-- determine whether nulls appear before or after non-null values in the sort
2048+-- ordering of a `Null` result column.
2049+data SortExpression outer grp commons schemas params from where
2051+ :: Expression outer grp commons schemas params from ('NotNull ty)
2052+ -> SortExpression outer grp commons schemas params from
2054+ :: Expression outer grp commons schemas params from ('NotNull ty)
2055+ -> SortExpression outer grp commons schemas params from
2057+ :: Expression outer grp commons schemas params from ('Null ty)
2058+ -> SortExpression outer grp commons schemas params from
2060+ :: Expression outer grp commons schemas params from ('Null ty)
2061+ -> SortExpression outer grp commons schemas params from
2063+ :: Expression outer grp commons schemas params from ('Null ty)
2064+ -> SortExpression outer grp commons schemas params from
2066+ :: Expression outer grp commons schemas params from ('Null ty)
2067+ -> SortExpression outer grp commons schemas params from
2068+deriving instance Show (SortExpression outer grp commons schemas params from)
2071+The `orderBy` clause causes the result rows of a `Squeal.PostgreSQL.Query.TableExpression`
2072+to be sorted according to the specified `SortExpression`(s).
2073+If two rows are equal according to the leftmost expression,
2074+they are compared according to the next expression and so on.
2075+If they are equal according to all specified expressions,
2076+they are returned in an implementation-dependent order.
2078+You can also control the order in which rows are processed by window functions
2079+using `orderBy` within `Squeal.PostgreSQL.Query.Over`.
2081+class OrderBy expr where
2083+ :: [SortExpression outer grp commons schemas params from]
2084+ -> expr outer grp commons schemas params from
2085+ -> expr outer grp commons schemas params from
2087+-- | Render a `SortExpression`.
2088+instance RenderSQL (SortExpression outer grp commons schemas params from) where
2090+ Asc expression -> renderSQL expression <+> "ASC"
2091+ Desc expression -> renderSQL expression <+> "DESC"
2092+ AscNullsFirst expression -> renderSQL expression
2093+ <+> "ASC NULLS FIRST"
2094+ DescNullsFirst expression -> renderSQL expression
2095+ <+> "DESC NULLS FIRST"
2096+ AscNullsLast expression -> renderSQL expression <+> "ASC NULLS LAST"
2097+ DescNullsLast expression -> renderSQL expression <+> "DESC NULLS LAST"
2099+-- | A `WindowDefinition` is a set of table rows that are somehow related
2100+-- to the current row
2101+data WindowDefinition outer grp commons schemas params from where
2104+ => NP (Expression outer grp commons schemas params from) bys
2105+ -> [SortExpression outer grp commons schemas params from]
2106+ -> WindowDefinition outer grp commons schemas params from
2108+instance OrderBy WindowDefinition where
2109+ orderBy sortsR (WindowDefinition parts sortsL)
2110+ = WindowDefinition parts (sortsL ++ sortsR)
2112+instance RenderSQL (WindowDefinition outer commons schemas from grp params) where
2113+ renderSQL (WindowDefinition part ord) =
2114+ renderPartitionByClause part <> renderOrderByClause ord
2116+ renderPartitionByClause = \case
2118+ parts -> "PARTITION" <+> "BY" <+> renderCommaSeparated renderExpression parts
2119+ renderOrderByClause = \case
2121+ srts -> " ORDER" <+> "BY"
2122+ <+> commaSeparated (renderSQL <$> srts)
2125+The `partitionBy` clause within `Squeal.PostgreSQL.Query.Over` divides the rows into groups,
2126+or partitions, that share the same values of the `partitionBy` `Expression`(s).
2127+For each row, the window function is computed across the rows that fall into
2128+the same partition as the current row.
2132+ => NP (Expression outer grp commons schemas params from) bys
2133+ -> WindowDefinition outer grp commons schemas params from
2134+partitionBy bys = WindowDefinition bys []
2137+A window function performs a calculation across a set of table rows
2138+that are somehow related to the current row. This is comparable to the type
2139+of calculation that can be done with an aggregate function.
2140+However, window functions do not cause rows to become grouped into a single
2141+output row like non-window aggregate calls would.
2142+Instead, the rows retain their separate identities.
2143+Behind the scenes, the window function is able to access more than
2144+just the current row of the query result.
2146+newtype WindowFunction
2147+ (outer :: FromType)
2149+ (commons :: FromType)
2150+ (schemas :: SchemasType)
2151+ (params :: [NullityType])
2153+ (ty :: NullityType)
2154+ = UnsafeWindowFunction { renderWindowFunction :: ByteString }
2155+ deriving (GHC.Generic,Show,Eq,Ord,NFData)
2157+instance RenderSQL (WindowFunction outer grp commons schemas params from ty) where
2158+ renderSQL = renderWindowFunction
2160+unsafeWindowFunction1
2162+ -> Expression outer grp commons schemas params from ty0
2163+ -> WindowFunction outer grp commons schemas params from ty1
2164+unsafeWindowFunction1 fun x
2165+ = UnsafeWindowFunction $ fun <> parenthesized (renderSQL x)
2167+unsafeWindowFunction2
2169+ -> (Expression outer grp commons schemas params from :*: Expression outer grp commons schemas params from) ty0
2170+ -> WindowFunction outer grp commons schemas params from ty1
2171+unsafeWindowFunction2 fun (x :*: x')
2172+ = UnsafeWindowFunction $ fun <> parenthesized (renderSQL x <> ", " <> renderSQL x')
2174+{- | rank of the current row with gaps; same as `rowNumber` of its first peer
2178+rank :: WindowFunction outer grp commons schemas params from ('NotNull 'PGint8)
2179+rank = UnsafeWindowFunction "rank()"
2181+{- | number of the current row within its partition, counting from 1
2182+>>> printSQL rowNumber
2185+rowNumber :: WindowFunction outer grp commons schemas params from ('NotNull 'PGint8)
2186+rowNumber = UnsafeWindowFunction "row_number()"
2188+{- | rank of the current row without gaps; this function counts peer groups
2189+>>> printSQL denseRank
2192+denseRank :: WindowFunction outer grp commons schemas params from ('NotNull 'PGint8)
2193+denseRank = UnsafeWindowFunction "dense_rank()"
2195+{- | relative rank of the current row: (rank - 1) / (total partition rows - 1)
2196+>>> printSQL percentRank
2199+percentRank :: WindowFunction outer grp commons schemas params from ('NotNull 'PGfloat8)
2200+percentRank = UnsafeWindowFunction "percent_rank()"
2202+{- | cumulative distribution: (number of partition rows
2203+preceding or peer with current row) / total partition rows
2204+>>> printSQL cumeDist
2207+cumeDist :: WindowFunction outer grp commons schemas params from ('NotNull 'PGfloat8)
2208+cumeDist = UnsafeWindowFunction "cume_dist()"
2210+{- | integer ranging from 1 to the argument value,
2211+dividing the partition as equally as possible
2214+ :: Expression outer grp commons schemas params from ('NotNull 'PGint4)
2216+ -> WindowFunction outer grp commons schemas params from ('NotNull 'PGint4)
2217+ntile = unsafeWindowFunction1 "ntile"
2219+{- | returns value evaluated at the row that is offset rows before the current
2220+row within the partition; if there is no such row, instead return default
2221+(which must be of the same type as value). Both offset and default are
2222+evaluated with respect to the current row.
2225+ :: Expression outer grp commons schemas params from ty
2227+ -> Expression outer grp commons schemas params from ('NotNull 'PGint4)
2229+ -> Expression outer grp commons schemas params from ty
2231+ -> WindowFunction outer grp commons schemas params from ty
2232+lag value offset def = UnsafeWindowFunction $ "lag"
2234+ (commaSeparated ([renderSQL value, renderSQL offset, renderSQL def]))
2236+{- | returns value evaluated at the row that is offset rows after the current
2237+row within the partition; if there is no such row, instead return default
2238+(which must be of the same type as value). Both offset and default are
2239+evaluated with respect to the current row.
2242+ :: Expression outer grp commons schemas params from ty
2244+ -> Expression outer grp commons schemas params from ('NotNull 'PGint4)
2246+ -> Expression outer grp commons schemas params from ty
2248+ -> WindowFunction outer grp commons schemas params from ty
2249+lead value offset def = UnsafeWindowFunction $ "lag"
2251+ (commaSeparated ([renderSQL value, renderSQL offset, renderSQL def]))
2253+{- | returns value evaluated at the row that is the
2254+first row of the window frame
2257+ :: Expression outer grp commons schemas params from ty
2259+ -> WindowFunction outer grp commons schemas params from ty
2260+firstValue = unsafeWindowFunction1 "first_value"
2262+{- | returns value evaluated at the row that is the
2263+last row of the window frame
2266+ :: Expression outer grp commons schemas params from ty
2268+ -> WindowFunction outer grp commons schemas params from ty
2269+lastValue = unsafeWindowFunction1 "last_value"
2271+{- | returns value evaluated at the row that is the nth
2272+row of the window frame (counting from 1); null if no such row
2275+ :: Expression outer grp commons schemas params from (nullity ty)
2277+ -> Expression outer grp commons schemas params from ('NotNull 'PGint4)
2279+ -> WindowFunction outer grp commons schemas params from ('Null ty)
2280+nthValue value nth = UnsafeWindowFunction $ "nth_value"
2281+ <> parenthesized (commaSeparated [renderSQL value, renderSQL nth])